Repository navigation
Add new primitives to easily wire confirmation dialogs onto actions #755
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
aff851c
c8b4cde
20e4ead
3dc2fbf
ffb25be
c02d150
873b20f
6cf40aa
536d18d
45cb82f
95d04b0
52d62c4
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,194 @@ | ||
| import { setComponentTemplate } from '@ember/component'; | ||
| import templateOnly from '@ember/component/template-only'; | ||
| import { assert } from '@ember/debug'; | ||
| import { fn, hash } from '@ember/helper'; | ||
| import { getOwner } from '@ember/owner'; | ||
| import type Owner from '@ember/owner'; | ||
| import { renderComponent } from '@ember/renderer'; | ||
| import type RouterService from '@ember/routing/router-service'; | ||
| import { precompileTemplate } from '@ember/template-compilation'; | ||
| import { isTesting } from '@embroider/macros'; | ||
| import { tracked } from '@glimmer/tracking'; | ||
|
|
||
| import type { IntlService } from 'ember-intl'; | ||
|
|
||
| import OSSDialog, { type Skin as DialogSkin } from '../components/o-s-s/dialog'; | ||
| import { | ||
| cancelDialog, | ||
| confirmDialog, | ||
| createDialog, | ||
| dismissActiveDialog, | ||
| hasLoadingDialog, | ||
| openDialog | ||
| } from './private/confirmation-utils'; | ||
|
|
||
| type Content = ReturnType<IntlService['t']>; | ||
| type Texts = { | ||
| title?: Content; | ||
| subtitle?: Content; | ||
| confirmLabel?: Content; | ||
| cancelLabel?: Content; | ||
| }; | ||
| type Text<T, A extends unknown[]> = Content | ((self: T, ...args: A) => Content); | ||
| type ConfirmOptions = Texts & { | ||
| baseTranslationKey?: string; | ||
| skin?: DialogSkin; | ||
| icon?: string; | ||
| dataControlName?: string; | ||
| onConfirm?: () => unknown; | ||
| }; | ||
|
|
||
| export type ConfirmableOptions<T, A extends unknown[]> = { | ||
| baseTranslationKey?: string; | ||
| title?: Text<T, A>; | ||
| subtitle?: Text<T, A>; | ||
| confirmLabel?: Text<T, A>; | ||
| cancelLabel?: Text<T, A>; | ||
| skin?: DialogSkin; | ||
| icon?: string; | ||
| dataControlName?: string; | ||
| when?: (self: T, ...args: A) => boolean; | ||
| }; | ||
|
|
||
| const DEFAULT_DATA_CONTROL_NAME = 'confirmable-dialog'; | ||
|
|
||
| class ConfirmationState { | ||
| @tracked loading: boolean = false; | ||
|
|
||
| constructor( | ||
| readonly texts: Texts, | ||
| readonly skin: DialogSkin | undefined, | ||
| readonly icon: string | undefined, | ||
| readonly dataControlName: string | ||
| ) {} | ||
| } | ||
|
|
||
| const ConfirmationDialog = setComponentTemplate( | ||
| precompileTemplate( | ||
| `<div class="confirmable-dialog"> | ||
| <OSSDialog | ||
| @title={{@state.texts.title}} | ||
| @subtitle={{@state.texts.subtitle}} | ||
| @skin={{@state.skin}} | ||
| @icon={{@state.icon}} | ||
| @mainAction={{hash | ||
| label=@state.texts.confirmLabel | ||
| action=(fn confirmDialog @dialog) | ||
| loading=@state.loading | ||
| }} | ||
| @secondaryAction={{hash label=@state.texts.cancelLabel action=(fn cancelDialog @dialog)}} | ||
| data-control-name={{@state.dataControlName}} | ||
| /> | ||
| </div>`, | ||
| { strictMode: true, scope: () => ({ OSSDialog, hash, fn, confirmDialog, cancelDialog }) } | ||
| ), | ||
| templateOnly() | ||
| ); | ||
|
|
||
| const HOST_ID = 'confirmable-dialog-host'; | ||
|
|
||
| function hostElement(): HTMLElement { | ||
| let host = document.getElementById(HOST_ID); | ||
|
|
||
| if (!host) { | ||
| host = document.createElement('div'); | ||
| host.id = HOST_ID; | ||
| ((isTesting() && document.getElementById('ember-testing')) || document.body).append(host); | ||
| } | ||
|
|
||
| return host; | ||
| } | ||
|
|
||
| function translate(owner: Owner, baseTranslationKey: string | undefined, suffix: string): Content | undefined { | ||
| if (!baseTranslationKey) return undefined; | ||
|
|
||
| const intl = owner.lookup('service:intl') as IntlService; | ||
| const key = `${baseTranslationKey}.${suffix}`; | ||
|
|
||
| assert(`[pattern][confirmation] Missing translation "${key}"`, intl.exists(key)); | ||
|
|
||
| return intl.t(key); | ||
| } | ||
|
|
||
| export function confirm(context: object, options: ConfirmOptions): Promise<boolean> { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this too could also be moved to a helpers file
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @Miexil the thing is to have only one source of truth for the |
||
| const owner = getOwner(context); | ||
|
|
||
| assert('[pattern][confirmation] The context must have an owner (component, controller, route or service)', owner); | ||
|
|
||
| const texts: Texts = { | ||
| title: options.title ?? translate(owner, options.baseTranslationKey, 'title'), | ||
| subtitle: options.subtitle ?? translate(owner, options.baseTranslationKey, 'subtitle'), | ||
| confirmLabel: options.confirmLabel ?? translate(owner, options.baseTranslationKey, 'confirm'), | ||
| cancelLabel: options.cancelLabel ?? translate(owner, options.baseTranslationKey, 'cancel') | ||
| }; | ||
| assert( | ||
| '[pattern][confirmation] A title, a confirmLabel and a cancelLabel are mandatory, either directly or through a baseTranslationKey', | ||
| texts.title && texts.confirmLabel && texts.cancelLabel | ||
| ); | ||
|
|
||
| if (hasLoadingDialog()) return Promise.resolve(false); | ||
| dismissActiveDialog(); | ||
|
|
||
| const router = owner.lookup('service:router') as RouterService; | ||
| const state = new ConfirmationState( | ||
| texts, | ||
| options.skin, | ||
| options.icon, | ||
| options.dataControlName ?? DEFAULT_DATA_CONTROL_NAME | ||
| ); | ||
|
|
||
| return new Promise<boolean>((resolve, reject) => { | ||
| const dialog = createDialog({ context, owner, router, state, action: options.onConfirm, resolve, reject }); | ||
|
|
||
| openDialog(dialog, renderComponent(ConfirmationDialog, { into: hostElement(), owner, args: { state, dialog } })); | ||
| }); | ||
| } | ||
|
|
||
| function resolveText<T, A extends unknown[]>(text: Text<T, A> | undefined, self: T, args: A): Content | undefined { | ||
| return typeof text === 'function' ? text(self, ...args) : text; | ||
| } | ||
|
|
||
| export function confirmable<T extends object, A extends unknown[] = unknown[]>(options: ConfirmableOptions<T, A>) { | ||
| return function <M extends (this: T, ...args: A) => unknown>( | ||
| _target: T, | ||
| key: string, | ||
| descriptor: TypedPropertyDescriptor<M> | ||
| ): TypedPropertyDescriptor<M> { | ||
| const original = descriptor.value; | ||
|
|
||
| assert( | ||
| `[pattern][confirmation] \`${key}\` must be a method. If it is also an \`@action\`, put \`@action\` above \`@confirmable\`.`, | ||
| typeof original === 'function' | ||
| ); | ||
|
|
||
| const openDialogs = new WeakMap<T, Promise<boolean>>(); | ||
|
|
||
| descriptor.value = function (this: T, ...args: A): unknown { | ||
| if (options.when && !options.when(this, ...args)) { | ||
| return original.apply(this, args); | ||
| } | ||
|
|
||
| let dialog = openDialogs.get(this); | ||
|
|
||
| if (!dialog) { | ||
| dialog = confirm(this, { | ||
| baseTranslationKey: options.baseTranslationKey, | ||
| title: resolveText(options.title, this, args), | ||
| subtitle: resolveText(options.subtitle, this, args), | ||
| confirmLabel: resolveText(options.confirmLabel, this, args), | ||
| cancelLabel: resolveText(options.cancelLabel, this, args), | ||
| skin: options.skin, | ||
| icon: options.icon, | ||
| dataControlName: options.dataControlName, | ||
| onConfirm: () => original.apply(this, args) | ||
| }).finally(() => openDialogs.delete(this)); | ||
|
|
||
| openDialogs.set(this, dialog); | ||
| } | ||
|
|
||
| return dialog.then(() => undefined); | ||
| } as M; | ||
|
Copilot marked this conversation as resolved.
Resolved
|
||
|
|
||
| return descriptor; | ||
| }; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| import { isDestroying, registerDestructor, unregisterDestructor } from '@ember/destroyable'; | ||
| import type Owner from '@ember/owner'; | ||
| import type RouterService from '@ember/routing/router-service'; | ||
|
|
||
| export type Dialog = { | ||
| readonly context: object; | ||
| readonly owner: Owner; | ||
| readonly router: RouterService; | ||
| readonly state: { loading: boolean }; | ||
| readonly action: (() => unknown) | undefined; | ||
| readonly resolve: (confirmed: boolean) => void; | ||
| readonly reject: (error: unknown) => void; | ||
| readonly dismiss: () => void; | ||
| rendered?: { destroy(): void }; | ||
| closed: boolean; | ||
| }; | ||
|
|
||
| let activeDialog: Dialog | undefined; | ||
|
|
||
| export function createDialog(fields: Omit<Dialog, 'dismiss' | 'closed' | 'rendered'>): Dialog { | ||
| const dialog: Dialog = { | ||
| ...fields, | ||
| closed: false, | ||
| dismiss: () => dismissDialog(dialog) | ||
| }; | ||
|
|
||
| return dialog; | ||
| } | ||
|
|
||
| export function openDialog(dialog: Dialog, rendered: { destroy(): void }): void { | ||
| dialog.rendered = rendered; | ||
| dialog.router.on('routeWillChange', dialog.dismiss); | ||
| registerDestructor(dialog.context, dialog.dismiss); | ||
| registerDestructor(dialog.owner, dialog.dismiss); | ||
| activeDialog = dialog; | ||
| } | ||
|
|
||
| export function hasLoadingDialog(): boolean { | ||
| return activeDialog?.state.loading ?? false; | ||
| } | ||
|
|
||
| export function dismissActiveDialog(): void { | ||
| if (activeDialog) dismissDialog(activeDialog); | ||
| } | ||
|
|
||
| export function dismissDialog(dialog: Dialog): void { | ||
| if (dialog.closed) return; | ||
| closeDialog(dialog); | ||
| if (!dialog.state.loading) dialog.resolve(false); | ||
| } | ||
|
|
||
| export function cancelDialog(dialog: Dialog, event?: Event): void { | ||
| event?.stopPropagation(); | ||
| if (!dialog.state.loading) dismissDialog(dialog); | ||
| } | ||
|
|
||
| export function confirmDialog(dialog: Dialog, event?: Event): void { | ||
| event?.stopPropagation(); | ||
| if (dialog.closed || dialog.state.loading) return; | ||
|
|
||
| let outcome: unknown; | ||
| try { | ||
| outcome = dialog.action?.(); | ||
| } catch (error) { | ||
| closeDialog(dialog); | ||
| dialog.reject(error); | ||
| return; | ||
| } | ||
|
|
||
| if (!isThenable(outcome)) { | ||
| closeDialog(dialog); | ||
| dialog.resolve(true); | ||
| return; | ||
| } | ||
|
|
||
| dialog.state.loading = true; | ||
| outcome.then( | ||
| () => settleDialog(dialog, () => dialog.resolve(true)), | ||
| (error: unknown) => settleDialog(dialog, () => dialog.reject(error)) | ||
| ); | ||
| } | ||
|
|
||
| function closeDialog(dialog: Dialog): void { | ||
| dialog.closed = true; | ||
| dialog.router.off('routeWillChange', dialog.dismiss); | ||
| if (!isDestroying(dialog.context)) unregisterDestructor(dialog.context, dialog.dismiss); | ||
| if (!isDestroying(dialog.owner)) unregisterDestructor(dialog.owner, dialog.dismiss); | ||
| if (activeDialog === dialog) activeDialog = undefined; | ||
| dialog.rendered?.destroy(); | ||
| } | ||
|
|
||
| function settleDialog(dialog: Dialog, finish: () => void): void { | ||
| if (!dialog.closed) closeDialog(dialog); | ||
| finish(); | ||
| } | ||
|
|
||
| function isThenable(value: unknown): value is PromiseLike<unknown> { | ||
| return typeof (value as PromiseLike<unknown> | undefined)?.then === 'function'; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
bruh. ^^
Do we actually need this level of abstraction for confirmation texts?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@Miexil it's just to say that Text is either:
the generic signature just seems complex but it's just to say that the function might take any number of arguments. From the consumer's level, this will be totally obfuscated as
type Textis not even exported