From 5140b226f5b8330f2e930f3e125d73a0c6791b90 Mon Sep 17 00:00:00 2001 From: Ali Mihandoost Date: Wed, 15 Feb 2023 01:00:09 +0330 Subject: [PATCH] feat(element): toggle mixin --- ui/element/src/index.ts | 1 + ui/element/src/mixins/toggle.ts | 52 +++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 ui/element/src/mixins/toggle.ts diff --git a/ui/element/src/index.ts b/ui/element/src/index.ts index ffa3c90f4..5e2883fc2 100644 --- a/ui/element/src/index.ts +++ b/ui/element/src/index.ts @@ -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'; diff --git a/ui/element/src/mixins/toggle.ts b/ui/element/src/mixins/toggle.ts new file mode 100644 index 000000000..c2e7b3a7f --- /dev/null +++ b/ui/element/src/mixins/toggle.ts @@ -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>( + superClass: T, +): Constructor & 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 & T; +}