Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ FontAwesome is owned by the consuming app: install your licensed FontAwesome pac

Follow [Consumer-owned asset maps](docs/asset-map.md). The consuming app explicitly calls `injectAssetMap` from `@upfluence/oss-components/build/classic-asset-map.cjs` (classic builds) or adds the `assetMap` plugin from `@upfluence/oss-components/build/vite-asset-map.mjs` (Vite builds); addon hooks do not activate either. Remove competing ember-cli-ifa registrations when adopting this adapter.

## Patterns

Patterns attach a UX behavior to an existing action, such as asking for confirmation before running it. Import them from `@upfluence/oss-components/patterns/...` and see the [Patterns docs in Storybook](https://storybook.upfluence.co/?path=/docs/patterns-confirmation--docs) (source in [`packages/test-app/stories/patterns`](packages/test-app/stories/patterns)).

## Development

This is a pnpm workspace with the published addon in `packages/oss-components` and its demo, tests, and Storybook in `packages/test-app`.
Expand Down
11 changes: 8 additions & 3 deletions packages/oss-components/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@upfluence/oss-components",
"version": "5.1.4",
"version": "5.2.0-beta.0",
"repository": "https://github.com/upfluence/oss-components",
"publishConfig": {
"registry": "https://npm.pkg.github.com",
Expand Down Expand Up @@ -69,7 +69,7 @@
"ember-cli-babel": "^8.2.0",
"ember-cli-code-coverage": "^3.1.0",
"ember-cli-htmlbars": "^7.0.1",
"ember-intl": "^6.4.0",
"ember-intl": "^6.5.6",
"ember-source": "~6.12.1",
"ember-template-lint": "^3.15.0",
"eslint": "^10.5.0",
Expand Down Expand Up @@ -176,6 +176,10 @@
"types": "./declarations/types.d.ts",
"default": "./dist/types.js"
},
"./patterns/*": {
"types": "./declarations/patterns/*.d.ts",
"default": "./dist/patterns/*.js"
},
"./utils/*": {
"types": "./declarations/utils/*.d.ts",
"default": "./dist/utils/*.js"
Expand All @@ -197,7 +201,8 @@
"default": "./dist/utils/index.js"
},
"./components/o-s-s/private/base-modal": null,
"./modifiers/install-scroll-reached-modifier": null
"./modifiers/install-scroll-reached-modifier": null,
"./patterns/private/*": null
},
"typesVersions": {
"*": {
Expand Down
3 changes: 2 additions & 1 deletion packages/oss-components/rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ export default {
exclude: [
'**/*.stories.*',
'components/o-s-s/private/base-modal.*',
'modifiers/install-scroll-reached-modifier.*'
'modifiers/install-scroll-reached-modifier.*',
'patterns/private/**'
]
}),
addon.appReexports(
Expand Down
194 changes: 194 additions & 0 deletions packages/oss-components/src/patterns/confirmation.ts
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>;

Copy link
Copy Markdown
Member

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?

Copy link
Copy Markdown
Member Author

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:

  • a static text (hardcoded)
  • or any function that returns some text

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 Text is not even exported

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> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this too could also be moved to a helpers file

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The 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 confirmable pattern usages, so having both public functions (the decorator and this one, the imperative way) in the same file makes sense to me (instead of decorator = one file and imperative = another file to import from)

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;
Comment thread
Copilot marked this conversation as resolved.
Resolved

return descriptor;
};
}
99 changes: 99 additions & 0 deletions packages/oss-components/src/patterns/private/confirmation-utils.ts
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';
}
2 changes: 1 addition & 1 deletion packages/test-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
"ember-cli-babel": "^8.2.0",
"ember-cli-code-coverage": "^3.1.0",
"ember-cli-htmlbars": "^7.0.1",
"ember-intl": "^6.4.0",
"ember-intl": "^6.5.6",
"ember-load-initializers": "^3.0.1",
"ember-modifier": "^3.2.7",
"ember-qunit": "^9.0.4",
Expand Down
Loading
Loading