From 20e8c0a3e507b86919ce06c9cfd567cee5605f77 Mon Sep 17 00:00:00 2001 From: straker <2433219+straker@users.noreply.github.com> Date: Wed, 24 Jul 2024 23:10:05 -0600 Subject: [PATCH] feat(button): allow adding the HTMLButton element to a container --- src/button.js | 4 +++- src/utils.js | 4 +++- test/unit/button.spec.js | 15 +++++++++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/button.js b/src/button.js index 68a1dcae..ac340c0f 100644 --- a/src/button.js +++ b/src/button.js @@ -13,6 +13,7 @@ import { srOnlyStyle, focusParams, noop, addToDom } from './utils.js'; * @param {Boolean} [properties.disabled] - Whether the button is disabled when created. * @param {Number} [properties.padX=0] - The horizontal padding. * @param {Number} [properties.padY=0] - The vertical padding. + * @param {HTMLElement} [properties.container] - The HTMLElement that the HTMLButtonElement will be appended to. * @param {Function} [properties.onEnable] - Function called when the button is enabled. * @param {Function} [properties.onDisable] - Function called when the button is disabled. * @param {Function} [properties.onFocus] - Function called when the button is focused by the keyboard. @@ -40,6 +41,7 @@ class Button extends SpriteClass { text, disabled = false, + container, onDown, onUp, ...props @@ -94,7 +96,7 @@ class Button extends SpriteClass { button.addEventListener('keydown', evt => this._kd(evt)); button.addEventListener('keyup', evt => this._ku(evt)); - addToDom(button, this.context.canvas); + addToDom(button, container ?? this.context.canvas); this._uw(); this._p(); diff --git a/src/utils.js b/src/utils.js index b658397b..1b96928f 100644 --- a/src/utils.js +++ b/src/utils.js @@ -24,8 +24,10 @@ export function addToDom(node, canvas) { ...container.querySelectorAll(':scope > [data-kontra]') ].pop() || canvas; target.after(node); - } else { + } else if (canvas.nodeName == 'CANVAS') { document.body.append(node); + } else { + canvas.append(node); } } diff --git a/test/unit/button.spec.js b/test/unit/button.spec.js index 64cd69a4..18f5f4db 100644 --- a/test/unit/button.spec.js +++ b/test/unit/button.spec.js @@ -136,6 +136,21 @@ describe('button', () => { expect(button.context.canvas.nextSibling).to.equal(button._dn); }); + it('should add the node to a container', () => { + const container = document.createElement('div'); + button.destroy(); + button = Button({ + width: 150, + text: { + text: 'Hello', + width: 100 + }, + container + }); + + expect(container.contains(button.node)).to.be.true; + }); + it('should hide the DOM node', () => { let styles = srOnlyStyle .split(';')