Skip to content

Commit

Permalink
feat(snack-bar): new component
Browse files Browse the repository at this point in the history
  • Loading branch information
MM25Zamanian committed Jun 22, 2024
1 parent 4657941 commit 4c02604
Show file tree
Hide file tree
Showing 6 changed files with 254 additions and 73 deletions.
3 changes: 3 additions & 0 deletions demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,8 @@
"unplugin-fonts": "^1.1.1",
"vite": "^5.2.4",
"vite-tsconfig-paths": "^4.3.2"
},
"dependencies": {
"@gecut/utilities": "^5.4.0"
}
}
69 changes: 59 additions & 10 deletions demo/snack-bar/scripts.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,64 @@
import {SnackBarManager} from '@gecut/components';
import {SnackBarManager, gecutButton} from '@gecut/components';
import {render, html} from 'lit/html.js';

const sbm = new SnackBarManager({gapBottom: '0'});
let index = 0;
const sbm = new SnackBarManager({
position: {
bottom: '0px',
left: '0px',
right: '0px',
},
});

const x = setInterval(() => {
sbm.open('s-' + index++, {
message: 'Hello ' + index,
});
const id1 = 'id1';
const id2 = 'id2';

if (x > 5) clearInterval(x);
}, 5000);
sbm.connect(id1, {
message: 'Hello ' + id1,
close: true,
});

render(html` <div class="mx-auto max-w-sm flex flex-col gap-4">${sbm.html}</div> `, document.body);
sbm.connect(id2, {
message:
// eslint-disable-next-line max-len
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ' +
id2,
action: {
label: 'Longer Action',
},
});

render(
html`
<div class="mx-auto max-w-sm flex flex-col gap-4 relative h-full w-full">
${sbm.html}
${gecutButton({
type: 'filled',
label: 'Push 1',
events: {
click: () => {
sbm.open(id1);
},
},
})}
${gecutButton({
type: 'filled',
label: 'Push 2',
events: {
click: () => {
sbm.open(id2);
},
},
})}
${gecutButton({
type: 'filled',
label: 'Remove 1',
events: {
click: () => {
sbm.disconnect(id1);
},
},
})}
</div>
`,
document.body,
);
97 changes: 67 additions & 30 deletions packages/components/src/snack-bar/manager.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,86 @@
import {gecutContext} from '@gecut/lit-helper/directives/context.js';
import {GecutLogger} from '@gecut/logger';
import {ContextSignal} from '@gecut/signal';
import {map} from 'lit/directives/map.js';
import {styleMap} from 'lit/directives/style-map.js';
import {html} from 'lit/html.js';

import {gecutSnackBar, type SnackBarContent} from './snack-bar.js';

import {repeat} from 'lit/directives/repeat.js';

export interface SnackBarManagerContent {
gapBottom: string;
position?: {
top?: string;
bottom?: string;
left?: string;
right?: string;
};
}

export class SnackBarManager {
constructor(content: SnackBarManagerContent) {
this.content = content;
this.snackBars.value = [];
this.snackBars = {};
this._$updaterContext.value = 'update';

this.html = html`
<div class="flex flex-col absolute inset-x-0" style=${styleMap(this.content?.position ?? {})}>
${gecutContext(this._$updaterContext, () =>
map(Object.keys(this.snackBars), (k) => gecutSnackBar(this.snackBars[k])),
)}
</div>
`;
}

content: SnackBarManagerContent = {};
snackBars: Record<string, ContextSignal<SnackBarContent>> = {};
html;

protected _$log = new GecutLogger('gecut-snackbar-manager');
protected _$updaterContext = new ContextSignal<'update'>('gecut-snackbar-updater', 'AnimationFrame');

connect(id: string, content: SnackBarContent) {
this._$log.methodArgs?.('connect', {id, content});

const context = new ContextSignal<SnackBarContent>(id, 'AnimationFrame');
context.value = {...content, open: false};

// this.html = html`${gecutContext<'open' | 'close'>(this.controller, (status) => {
// const dialogContent: DialogContent = {...this.content, controller: this.controller, provider: this.provider};
this.snackBars[id] = context;
this.update();
}
disconnect(id: string) {
this._$log.methodArgs?.('disconnect', {id});

// return gecutDialog(dialogContent, status === 'open');
// })}`;
this.close(id);

// this.controller.value = 'close';
setTimeout(() => {
delete this.snackBars[id];
this.update();
}, 500);
}

content: SnackBarManagerContent;
snackBars = new ContextSignal<[string, SnackBarContent, {open: true}][]>('snack-bars');
html = gecutContext(this.snackBars, (snackBars) =>
repeat(
snackBars,
(snackBar) => snackBar[0],
(snackBar) => gecutSnackBar(snackBar[1]),
),
);

open(id: string, content: SnackBarContent) {
this.snackBars.functionalValue((old) => [[id, content, {open: true}], ...(old ?? [])]);
open(id: string) {
this._$log.methodArgs?.('open', {id});

if (!this.snackBars[id]) return this._$log.warning('open', 'id_not_found', `'${id}' not found`);

this.snackBars[id].functionalValue((old) => {
return {...(old ?? {message: ''}), open: true};
});
this.update();
}
close(id: string) {
this._$log.methodArgs?.('close', {id});

if (!this.snackBars[id]) return this._$log.warning('close', 'id_not_found', `'${id}' not found`);

// onAfterClose() {
// return new Promise<string>((resolve) => {
// this.provider.subscribe(resolve, {
// receivePrevious: false,
// once: true,
// priority: 1000,
// });
// });
// }
this.snackBars[id].functionalValue((old) => {
return {...(old ?? {message: ''}), open: false};
});
this.update();
}

protected update() {
this._$log.methodArgs?.('update', {snackBars: this.snackBars});
this._$updaterContext.renotify();
}
}
117 changes: 90 additions & 27 deletions packages/components/src/snack-bar/snack-bar.ts
Original file line number Diff line number Diff line change
@@ -1,70 +1,133 @@
import {GecutDirective} from '@gecut/lit-helper/directives/directive.js';
import {noChange, nothing, html} from 'lit/html.js';
import {type PartInfo, directive} from 'lit/directive.js';
import {gecutButton, type ButtonContent} from '../button/button.js';
import {gecutIconButton, type IconButtonContent} from '../components.js';
import {classMap, type ClassInfo} from 'lit/directives/class-map.js';
import {GecutAsyncDirective} from '@gecut/lit-helper/directives/async-directive.js';
import {directive} from 'lit/directive.js';
import {classMap} from 'lit/directives/class-map.js';
import {nothing, html, noChange} from 'lit/html.js';

import {gecutButton} from '../button/button.js';
import {gecutIconButton} from '../components.js';

import type {ButtonContent} from '../button/button.js';
import type {IconButtonContent} from '../components.js';
import type {ContextSignal} from '@gecut/signal';
import type {PartInfo} from 'lit/directive.js';
import type {ClassInfo} from 'lit/directives/class-map.js';

export interface SnackBarContent {
message: string;

open?: boolean;
action?: Omit<ButtonContent, 'type'>;
close?: boolean | Omit<IconButtonContent, 'type'>;
}

export class GecutSnackBarDirective extends GecutDirective {
export class GecutSnackBarDirective extends GecutAsyncDirective {
constructor(partInfo: PartInfo) {
super(partInfo, 'gecut-snack-bar');
}

protected content?: SnackBarContent;
protected _$signalContext?: ContextSignal<SnackBarContent>;
protected _$unsubscribe?: () => void;

render(signalContext: ContextSignal<SnackBarContent>): unknown {
this.log.methodArgs?.('render', signalContext);

if (this._$signalContext !== signalContext) {
// When the observable changes, unsubscribe to the old one and subscribe to the new one
this._$unsubscribe?.();
this._$signalContext = signalContext;

if (this.isConnected) {
this.subscribe();
}
}

return noChange;
}

// When the directive is disconnected from the DOM, unsubscribe to ensure
// the directive instance can be garbage collected
override disconnected(): void {
super.disconnected();

render(content?: SnackBarContent): unknown {
this.log.methodArgs?.('render', content);
this._$unsubscribe!();
}
// If the subtree the directive is in was disconnected and subsequently
// re-connected, re-subscribe to make the directive operable again
override reconnected(): void {
super.reconnected();

if (content === undefined) return noChange;
this.subscribe();
}

this.content = content;
close() {
if (this._$signalContext?.value?.open) {
this._$signalContext.value.open = false;

return this.renderSnackBar();
this._$signalContext?.renotify();
}
}

protected renderSnackBar() {
if (!this.content) return nothing;
protected subscribe() {
this.log.method?.('subscribe');

this._$unsubscribe = this._$signalContext?.subscribe(
(content) => {
this.setValue(this.renderSnackBar(content));
},
{receivePrevious: true},
).unsubscribe;
}

protected renderSnackBar(content: SnackBarContent) {
this.log.method?.('renderSnackBar');

return html`
<div class=${classMap(this.getRenderClasses())}>
<span class="gecut-snack-bar-message">${this.content.message}</span>
${this.renderAction()} ${this.renderClose()}
<span class="gecut-snack-bar-message">${content.message}</span>
<div @click=${this.close.bind(this)}>
${this.renderAction(content.action)} ${this.renderClose(content.close)}
</div>
</div>
`;
}
protected renderAction(): unknown {
if (!this.content?.action) return nothing;
protected renderAction(content: SnackBarContent['action']): unknown {
if (!content) return nothing;

this.log.method?.('renderAction');

return gecutButton({...this.content.action, type: 'text'});
return gecutButton({
...content,
type: 'text',
});
}
protected renderClose(): unknown {
if (!this.content?.close) return nothing;
protected renderClose(content: SnackBarContent['close']): unknown {
if (!content) return nothing;

this.log.method?.('renderClose');

return gecutIconButton({
svg: '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-dasharray="12" stroke-dashoffset="12" stroke-linecap="round" stroke-width="2" d="M12 12L19 19M12 12L5 5M12 12L5 19M12 12L19 5"><animate fill="freeze" attributeName="stroke-dashoffset" dur="1.2s" values="12;0"/></path></svg>',
const _content: Omit<IconButtonContent, 'type'> =
typeof content !== 'boolean'
? content
: {
svg:
// eslint-disable-next-line max-len
'<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-dasharray="12" stroke-dashoffset="12" stroke-linecap="round" stroke-width="2" d="M12 12L19 19M12 12L5 5M12 12L5 19M12 12L19 5"><animate fill="freeze" attributeName="stroke-dashoffset" dur="1.2s" values="12;0"/></path></svg>',
};

...(typeof this.content.close !== 'boolean' ? this.content.close : {}),
});
return gecutIconButton(_content);
}

protected override getRenderClasses(): ClassInfo {
const content = this._$signalContext?.value;

if (!content) return super.getRenderClasses();

return {
...super.getRenderClasses(),

'longer-action': (this.content?.action?.label?.length ?? 0) > 10,
'longer-action': (content.action?.label?.length ?? 0) > 10,
open: content.open ?? false,
close: !(content.open ?? false),
};
}
}
Expand Down
Loading

0 comments on commit 4c02604

Please sign in to comment.