Skip to content

Commit

Permalink
feat(button): allow adding the HTMLButton element to a container
Browse files Browse the repository at this point in the history
  • Loading branch information
straker committed Jul 25, 2024
1 parent 7312c0e commit 20e8c0a
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/button.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -40,6 +41,7 @@ class Button extends SpriteClass {

text,
disabled = false,
container,
onDown,
onUp,
...props
Expand Down Expand Up @@ -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();
Expand Down
4 changes: 3 additions & 1 deletion src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down
15 changes: 15 additions & 0 deletions test/unit/button.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(';')
Expand Down

0 comments on commit 20e8c0a

Please sign in to comment.