Skip to content

Commit

Permalink
feat(element): toggle mixin
Browse files Browse the repository at this point in the history
  • Loading branch information
alimd committed Feb 15, 2023
1 parent c585aa4 commit 5140b22
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
1 change: 1 addition & 0 deletions ui/element/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export * from './mixins/localize.js';
export * from './mixins/direction.js';
export * from './mixins/logging.js';
export * from './mixins/signal.js';
export * from './mixins/toggle.js';

export * from './directives/map.js';

Expand Down
52 changes: 52 additions & 0 deletions ui/element/src/mixins/toggle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import type {LoggerMixinInterface} from './logging.js';
import type {Constructor} from '@alwatr/type';

export declare class ToggleMixinInterface extends LoggerMixinInterface {
private _selected: boolean;
get selected(): boolean;
set selected(value: boolean);
protected _click(event: MouseEvent): void
}

export function ToggleMixin<T extends Constructor<LoggerMixinInterface>>(
superClass: T,
): Constructor<ToggleMixinInterface> & T {
class ToggleMixinClass extends superClass {
private _selected = false;

get selected(): boolean {
return this._selected;
}
set selected(value: boolean) {
if (this._selected === value) return;
this._logger.logProperty('selected', value);
this._selected = value;
if (value) {
this.setAttribute('selected', '');
}
else {
this.removeAttribute('selected');
}
}

override connectedCallback(): void {
super.connectedCallback();
this.addEventListener('click', this._click);
}
override disconnectedCallback(): void {
super.disconnectedCallback();
this.removeEventListener('click', this._click);
}

/**
* On host click event.
*/
protected _click(event: MouseEvent): void {
this._logger.logMethod('_click');
if (event.metaKey || event.altKey || event.shiftKey) return;
this.selected = !this.selected;
}
}

return ToggleMixinClass as unknown as Constructor<ToggleMixinInterface> & T;
}

0 comments on commit 5140b22

Please sign in to comment.