Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ui): imperative dialog system and confirmation dialog (#5623)

dev-rbd46dca75a63a
diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsx
index e028ad8ab2..ac2128855f 100644
--- a/apps/web/src/components/app/Layout.tsx
+++ b/apps/web/src/components/app/Layout.tsx
@@ -65,7 +65,7 @@ import {
useLocation,
useNavigate,
} from '@solidjs/router';
-import { cn } from '@ui';
+import { cn, ImperativeDialogHost } from '@ui';
import { ScreencastHotkeys } from '@ui/components/ScreencastHotkeys';
import {
createEffect,
@@ -428,6 +428,7 @@ function LayoutInner(props: RouteSectionProps) {
'relative flex flex-col justify-between w-dvw h-[calc(var(--dvh,1dvh)*100)] pl-(--safe-left) pr-(--safe-right)'
)}
>
+ <ImperativeDialogHost />
<BundleUpdateProgressBar />
<Suspense>
<Show when={isAuthenticated()}>
diff --git a/apps/web/src/components/ui/components/ConfirmDialog.tsx b/apps/web/src/components/ui/components/ConfirmDialog.tsx
new file mode 100644
index 0000000000..ce8a2d3bfd
--- /dev/null
+++ b/apps/web/src/components/ui/components/ConfirmDialog.tsx
@@ -0,0 +1,97 @@
+import type { JSX } from 'solid-js';
+import { Button } from './Button';
+import { Dialog } from './Dialog';
+import {
+ type DialogHandle,
+ type ManagedDialogProps,
+ type OpenDialogOptions,
+ openDialog,
+ type PropsSource,
+} from './ImperativeDialog';
+import { Surface } from './Surface';
+
+/** Presentation options for the shared confirmation dialog. */
+export type ConfirmDialogDisplayProps = {
+ title: JSX.Element;
+ /** Dialog copy. `children` is used when `body` is omitted. */
+ body?: JSX.Element;
+ children?: JSX.Element;
+ confirmLabel?: JSX.Element;
+ cancelLabel?: JSX.Element;
+ tone?: 'default' | 'danger';
+};
+
+export type ConfirmDialogProps = ManagedDialogProps &
+ ConfirmDialogDisplayProps & {
+ onConfirm: () => void;
+ };
+
+/** Complete dialog used by `confirmDialog`. */
+export function ConfirmDialog(props: ConfirmDialogProps) {
+ return (
+ <Dialog
+ open={props.open}
+ onOpenChange={props.onOpenChange}
+ position="center"
+ class="w-[90%] max-w-120"
+ >
+ <Surface depth={2} class="rounded-xl text-ink">
+ <div class="shrink-0 flex items-center border-b border-edge-muted px-5 py-3">
+ <Dialog.Title class="text-sm font-semibold">
+ {props.title}
+ </Dialog.Title>
+ </div>
+ <div class="flex flex-col gap-4 p-5">
+ <Dialog.Description as="div" class="text-sm leading-5 text-ink-muted">
+ {props.body ?? props.children}
+ </Dialog.Description>
+ <div class="flex justify-end gap-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => props.onOpenChange(false)}
+ >
+ {props.cancelLabel ?? 'Cancel'}
+ </Button>
+ <Button
+ type="button"
+ variant={props.tone === 'danger' ? 'danger' : 'active'}
+ size="sm"
+ onClick={props.onConfirm}
+ >
+ {props.confirmLabel ?? 'Confirm'}
+ </Button>
+ </div>
+ </div>
+ </Surface>
+ </Dialog>
+ );
+}
+
+function resolveProps<P extends object>(source: PropsSource<P>): P {
+ return typeof source === 'function' ? source() : source;
+}
+
+/** Opens the shared confirmation dialog and resolves with the user's choice. */
+export function confirmDialog(
+ props: PropsSource<ConfirmDialogDisplayProps>,
+ options?: OpenDialogOptions
+): Promise<boolean> {
+ let confirmed = false;
+ let handle!: DialogHandle;
+
+ handle = openDialog(
+ ConfirmDialog,
+ () => ({
+ ...resolveProps(props),
+ onConfirm: () => {
+ confirmed = true;
+ handle.close();
+ },
+ }),
+ options
+ );
+
+ return handle.closed.then(() => confirmed);
+}
diff --git a/apps/web/src/components/ui/components/ImperativeDialog.test.tsx b/apps/web/src/components/ui/components/ImperativeDialog.test.tsx
new file mode 100644
index 0000000000..cf43334828
--- /dev/null
+++ b/apps/web/src/components/ui/components/ImperativeDialog.test.tsx
@@ -0,0 +1,250 @@
+import { cleanup, render, screen, waitFor } from '@solidjs/testing-library';
+import userEvent from '@testing-library/user-event';
+import {
+ type Component,
+ createContext,
+ createSignal,
+ Show,
+ useContext,
+} from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { Dialog } from './Dialog';
+import {
+ type ImperativeDialogController,
+ ImperativeDialogHost,
+ type ManagedDialogProps,
+ openDialog,
+ useImperativeDialog,
+} from './ImperativeDialog';
+
+function ManagedTestDialog(
+ props: ManagedDialogProps & {
+ label: string;
+ }
+) {
+ return (
+ <Dialog open={props.open} onOpenChange={props.onOpenChange}>
+ <div>
+ <Dialog.Title>{props.label}</Dialog.Title>
+ <button type="button" onClick={() => props.onOpenChange(false)}>
+ Dismiss {props.label}
+ </button>
+ </div>
+ </Dialog>
+ );
+}
+
+function PlainManagedDialog(
+ props: ManagedDialogProps & {
+ label: string;
+ }
+) {
+ return (
+ <div data-testid="managed-dialog" data-open={String(props.open)}>
+ <span>{props.label}</span>
+ <button type="button" onClick={() => props.onOpenChange(false)}>
+ Dismiss {props.label}
+ </button>
+ </div>
+ );
+}
+
+function typeAssertions() {
+ openDialog(ManagedTestDialog, { label: 'valid' });
+ openDialog(ManagedTestDialog, () => ({ label: 'reactive' }));
+
+ // @ts-expect-error label is required by the supplied dialog component.
+ openDialog(ManagedTestDialog, {});
+ openDialog(ManagedTestDialog, {
+ label: 'invalid',
+ // @ts-expect-error managed props cannot be supplied by callers.
+ open: false,
+ // @ts-expect-error managed props cannot be supplied by callers.
+ onOpenChange: () => undefined,
+ });
+}
+void typeAssertions;
+
+function hookTypeAssertions() {
+ const dialog = useImperativeDialog(ManagedTestDialog);
+ dialog.open({ label: 'valid' });
+ dialog.open(() => ({ label: 'reactive' }));
+
+ // @ts-expect-error label is required by the supplied dialog component.
+ dialog.open({});
+}
+void hookTypeAssertions;
+
+beforeEach(() => {
+ window.scrollTo = vi.fn();
+ if (!globalThis.CSS) {
+ Object.defineProperty(globalThis, 'CSS', {
+ configurable: true,
+ value: { escape: (value: string) => value },
+ });
+ }
+});
+
+afterEach(() => cleanup());
+
+describe('openDialog', () => {
+ it('renders a complete dialog and reports dismissals', async () => {
+ render(() => <ImperativeDialogHost />);
+ const handle = openDialog(ManagedTestDialog, { label: 'Complete dialog' });
+
+ await screen.findByText('Complete dialog');
+ expect(handle.isOpen()).toBe(true);
+
+ await userEvent.click(
+ screen.getByRole('button', { name: 'Dismiss Complete dialog' })
+ );
+
+ await expect(handle.closed).resolves.toEqual({
+ id: handle.id,
+ reason: 'dismissed',
+ });
+ expect(handle.isOpen()).toBe(false);
+ });
+
+ it('keeps accessor and store props reactive', async () => {
+ render(() => <ImperativeDialogHost />);
+ const [accessorLabel, setAccessorLabel] = createSignal('Accessor one');
+ const [store, setStore] = createStore({ label: 'Store one' });
+
+ const accessorHandle = openDialog(PlainManagedDialog, () => ({
+ label: accessorLabel(),
+ }));
+ const storeHandle = openDialog(PlainManagedDialog, store);
+
+ await screen.findByText('Accessor one');
+ expect(screen.getByText('Store one')).toBeTruthy();
+
+ setAccessorLabel('Accessor two');
+ setStore('label', 'Store two');
+
+ expect(await screen.findByText('Accessor two')).toBeTruthy();
+ expect(screen.getByText('Store two')).toBeTruthy();
+
+ accessorHandle.close();
+ storeHandle.close();
+ });
+
+ it('dismisses stacked dialogs in LIFO order with idempotent handles', async () => {
+ render(() => <ImperativeDialogHost />);
+ const first = openDialog(ManagedTestDialog, { label: 'First stacked' });
+ const second = openDialog(ManagedTestDialog, { label: 'Second stacked' });
+ await screen.findByText('Second stacked');
+
+ await userEvent.keyboard('{Escape}');
+
+ await expect(second.closed).resolves.toMatchObject({ reason: 'dismissed' });
+ expect(second.close()).toBe(false);
+ expect(first.isOpen()).toBe(true);
+ expect(screen.getByText('First stacked')).toBeTruthy();
+
+ expect(first.close()).toBe(true);
+ expect(first.close()).toBe(false);
+ await expect(first.closed).resolves.toEqual({
+ id: first.id,
+ reason: 'programmatic',
+ });
+ });
+
+ it('uses one owner-scoped slot and replaces its current dialog', async () => {
+ const LocalContext = createContext('host');
+ const [showOwner, setShowOwner] = createSignal(true);
+ let controller!: ImperativeDialogController<
+ ManagedDialogProps & { label: string }
+ >;
+
+ const ContextDialog: Component<ManagedDialogProps & { label: string }> = (
+ props
+ ) => (
+ <div>
+ {useContext(LocalContext)} {props.label}
+ </div>
+ );
+
+ function OwnerScopedController() {
+ controller = useImperativeDialog(ContextDialog);
+ return null;
+ }
+
+ render(() => (
+ <>
+ <Show when={showOwner()}>
+ <LocalContext.Provider value="caller-local">
+ <OwnerScopedController />
+ </LocalContext.Provider>
+ </Show>
+ <ImperativeDialogHost />
+ </>
+ ));
+
+ const first = controller.open({ label: 'first' });
+ expect(await screen.findByText('caller-local first')).toBeTruthy();
+
+ const second = controller.open({ label: 'second' });
+ await expect(first.closed).resolves.toMatchObject({ reason: 'replaced' });
+ expect(controller.handle()).toBe(second);
+ expect(controller.isOpen()).toBe(true);
+ expect(await screen.findByText('caller-local second')).toBeTruthy();
+
+ expect(controller.close()).toBe(true);
+ await expect(second.closed).resolves.toMatchObject({
+ reason: 'programmatic',
+ });
+ expect(controller.handle()).toBeUndefined();
+ expect(controller.isOpen()).toBe(false);
+
+ const third = controller.open({ label: 'third' });
+ expect(await screen.findByText('caller-local third')).toBeTruthy();
+ setShowOwner(false);
+ await expect(third.closed).resolves.toMatchObject({
+ reason: 'owner-disposed',
+ });
+ expect(screen.queryByText('caller-local third')).toBeNull();
+ });
+
+ it('returns focus only after the final managed dialog closes', async () => {
+ const trigger = document.createElement('button');
+ document.body.append(trigger);
+ trigger.focus();
+
+ render(() => <ImperativeDialogHost />);
+ const first = openDialog(PlainManagedDialog, {
+ label: 'First focus owner',
+ });
+ const second = openDialog(PlainManagedDialog, {
+ label: 'Second focus owner',
+ });
+ await screen.findByText('Second focus owner');
+
+ first.close();
+ expect(document.activeElement).toBe(trigger);
+
+ const dialogButton = screen.getByRole('button', {
+ name: 'Dismiss Second focus owner',
+ });
+ dialogButton.focus();
+ second.close();
+
+ await waitFor(() => expect(document.activeElement).toBe(trigger));
+ trigger.remove();
+ });
+
+ it('finalizes active entries when the host is disposed', async () => {
+ const rendered = render(() => <ImperativeDialogHost />);
+ const handle = openDialog(PlainManagedDialog, { label: 'Host owned' });
+ await screen.findByText('Host owned');
+
+ rendered.unmount();
+
+ await expect(handle.closed).resolves.toEqual({
+ id: handle.id,
+ reason: 'host-disposed',
+ });
+ expect(handle.isOpen()).toBe(false);
+ });
+});
diff --git a/apps/web/src/components/ui/components/ImperativeDialog.tsx b/apps/web/src/components/ui/components/ImperativeDialog.tsx
new file mode 100644
index 0000000000..061b3ac157
--- /dev/null
+++ b/apps/web/src/components/ui/components/ImperativeDialog.tsx
@@ -0,0 +1,259 @@
+import { useFocusLock } from '@core/util/createControlledOpenSignal';
+import {
+ type Accessor,
+ type Component,
+ createRoot,
+ createSignal,
+ For,
+ getOwner,
+ type Owner,
+ onCleanup,
+ runWithOwner,
+} from 'solid-js';
+import { Dynamic } from 'solid-js/web';
+
+/** Props controlled by the imperative dialog manager. */
+export type ManagedDialogProps = {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+};
+
+/** A static or reactive source of component props. */
+export type PropsSource<P extends object> = P | Accessor<P>;
+
+/** Options controlling an imperative dialog's lifecycle. */
+export type OpenDialogOptions = {
+ /**
+ * The Solid owner whose context and lifetime the dialog should inherit.
+ * Capture this owner while the calling component is being created; event
+ * handlers generally run without an owner.
+ */
+ owner?: Owner;
+};
+
+/** Why an imperative dialog was closed. */
+export type DialogCloseReason =
+ | 'dismissed'
+ | 'programmatic'
+ | 'replaced'
+ | 'owner-disposed'
+ | 'host-disposed';
+
+/** Information emitted after an imperative dialog has been cleaned up. */
+export type DialogClosedEvent = {
+ id: string;
+ reason: DialogCloseReason;
+};
+
+/** A stable handle to one imperative dialog entry. */
+export type DialogHandle = {
+ readonly id: string;
+ readonly isOpen: Accessor<boolean>;
+ /** Closes this dialog. Returns false when it was already closed. */
+ close: () => boolean;
+ /** Resolves once the dialog's reactive root has been disposed. */
+ readonly closed: Promise<DialogClosedEvent>;
+};
+
+type StoredManagedDialogProps = ManagedDialogProps & Record<string, unknown>;
+type ManagedDialogComponent = Component<StoredManagedDialogProps>;
+/** Props callers provide when opening a managed dialog. */
+export type ManagedDialogInput<P extends ManagedDialogProps> = Omit<
+ P,
+ keyof ManagedDialogProps
+> &
+ Partial<Record<keyof ManagedDialogProps, never>>;
+
+/** Controls the single active dialog owned by `useImperativeDialog`. */
+export type ImperativeDialogController<P extends ManagedDialogProps> = {
+ /** Opens this dialog, replacing the controller's current entry. */
+ open: (props: PropsSource<ManagedDialogInput<P>>) => DialogHandle;
+ /** Closes the current entry. Returns false when none is open. */
+ close: () => boolean;
+ /** Whether this controller currently owns an open entry. */
+ readonly isOpen: Accessor<boolean>;
+ /** The current entry-specific handle. */
+ readonly handle: Accessor<DialogHandle | undefined>;
+};
+
+type DialogEntry = {
+ id: string;
+ component: ManagedDialogComponent;
+ props: PropsSource<Record<string, unknown>>;
+ owner?: Owner;
+ isOpen: Accessor<boolean>;
+ setOpen: (open: boolean) => void;
+ finalized: boolean;
+ focusLock: ReturnType<typeof useFocusLock>;
+ rootDisposer?: () => void;
+ resolveClosed: (event: DialogClosedEvent) => void;
+};
+
+const [dialogEntries, setDialogEntries] = createSignal<DialogEntry[]>([]);
+let nextDialogId = 0;
+
+function resolveProps<P extends object>(source: PropsSource<P>): P {
+ return typeof source === 'function' ? source() : source;
+}
+
+function finalizeDialog(id: string, reason: DialogCloseReason): boolean {
+ const entry = dialogEntries().find((candidate) => candidate.id === id);
+ if (!entry || entry.finalized) return false;
+
+ entry.finalized = true;
+ entry.setOpen(false);
+
+ const disposeRoot = entry.rootDisposer;
+ entry.rootDisposer = undefined;
+ disposeRoot?.();
+
+ setDialogEntries((entries) =>
+ entries.filter((candidate) => candidate.id !== id)
+ );
+ entry.focusLock.release();
+ entry.resolveClosed({ id, reason });
+ return true;
+}
+
+/**
+ * Opens a complete, controlled dialog component in the global dialog host.
+ * The manager supplies `open` and `onOpenChange`; the component owns its
+ * `<Dialog>` and all presentation details.
+ */
+export function openDialog<P extends ManagedDialogProps>(
+ component: Component<P>,
+ props: PropsSource<ManagedDialogInput<P>>,
+ options: OpenDialogOptions = {}
+): DialogHandle {
+ const id = `imperative-dialog-${++nextDialogId}`;
+ const [isOpen, setOpen] = createSignal(true);
+ const focusLock = useFocusLock(id);
+ focusLock.acquire();
+
+ let resolveClosed!: (event: DialogClosedEvent) => void;
+ const closed = new Promise<DialogClosedEvent>((resolve) => {
+ resolveClosed = resolve;
+ });
+
+ const entry: DialogEntry = {
+ id,
+ component: component as ManagedDialogComponent,
+ props: props as PropsSource<Record<string, unknown>>,
+ owner: options.owner,
+ isOpen,
+ setOpen,
+ finalized: false,
+ focusLock,
+ resolveClosed,
+ };
+
+ setDialogEntries((entries) => [...entries, entry]);
+
+ if (options.owner) {
+ runWithOwner(options.owner, () => {
+ onCleanup(() => finalizeDialog(id, 'owner-disposed'));
+ });
+ }
+
+ return {
+ id,
+ isOpen,
+ close: () => finalizeDialog(id, 'programmatic'),
+ closed,
+ };
+}
+
+/**
+ * Creates a single-slot dialog controller bound to the current Solid owner.
+ * Opening again replaces only the entry created by this controller.
+ */
+export function useImperativeDialog<P extends ManagedDialogProps>(
+ component: Component<P>
+): ImperativeDialogController<P> {
+ const owner = getOwner();
+ if (!owner) {
+ throw new Error('useImperativeDialog must be called within a Solid owner');
+ }
+
+ const [handle, setHandle] = createSignal<DialogHandle>();
+
+ const open = (props: PropsSource<ManagedDialogInput<P>>) => {
+ const previous = handle();
+ if (previous?.isOpen()) {
+ finalizeDialog(previous.id, 'replaced');
+ }
+
+ const next = openDialog(component, props, { owner });
+ setHandle(next);
+ void next.closed.then(() => {
+ if (handle() === next) setHandle(undefined);
+ });
+ return next;
+ };
+
+ const close = () => {
+ const current = handle();
+ if (!current) return false;
+
+ const didClose = current.close();
+ if (didClose) setHandle(undefined);
+ return didClose;
+ };
+
+ return {
+ open,
+ close,
+ isOpen: () => handle()?.isOpen() ?? false,
+ handle,
+ };
+}
+
+function DialogEntryRenderer(props: { entry: DialogEntry }) {
+ const hostOwner = getOwner();
+ let disposed = false;
+ let disposeRoot!: () => void;
+
+ const content = createRoot((dispose) => {
+ disposeRoot = () => {
+ if (disposed) return;
+ disposed = true;
+ dispose();
+ };
+ props.entry.rootDisposer = disposeRoot;
+
+ return (
+ <Dynamic
+ component={props.entry.component}
+ {...resolveProps(props.entry.props)}
+ open={props.entry.isOpen()}
+ onOpenChange={(open: boolean) => {
+ if (!open) finalizeDialog(props.entry.id, 'dismissed');
+ }}
+ />
+ );
+ }, props.entry.owner ?? hostOwner);
+
+ onCleanup(() => {
+ if (props.entry.rootDisposer === disposeRoot) {
+ props.entry.rootDisposer = undefined;
+ }
+ disposeRoot();
+ });
+
+ return content;
+}
+
+/** Mounts and owns all dialogs opened through `openDialog`. Mount once. */
+export function ImperativeDialogHost() {
+ onCleanup(() => {
+ for (const entry of [...dialogEntries()]) {
+ finalizeDialog(entry.id, 'host-disposed');
+ }
+ });
+
+ return (
+ <For each={dialogEntries()}>
+ {(entry) => <DialogEntryRenderer entry={entry} />}
+ </For>
+ );
+}
diff --git a/apps/web/src/components/ui/index.ts b/apps/web/src/components/ui/index.ts
index a5d5285c59..f9a2fdafc3 100644
--- a/apps/web/src/components/ui/index.ts
+++ b/apps/web/src/components/ui/index.ts
@@ -40,6 +40,11 @@ export {
CommandMenuShell,
createCommandListController,
} from './components/CommandMenuPrimitives';
+export type {
+ ConfirmDialogDisplayProps,
+ ConfirmDialogProps,
+} from './components/ConfirmDialog';
+export { ConfirmDialog, confirmDialog } from './components/ConfirmDialog';
export type { DialogProps } from './components/Dialog';
export { Dialog } from './components/Dialog';
export { Dropdown } from './components/Dropdown';
@@ -52,6 +57,21 @@ export type { FilteredHiddenBannerProps } from './components/FilteredHiddenBanne
export { FilteredHiddenBanner } from './components/FilteredHiddenBanner';
export { Hotkey } from './components/Hotkey';
export { HoverCard } from './components/HoverCard';
+export type {
+ DialogClosedEvent,
+ DialogCloseReason,
+ DialogHandle,
+ ImperativeDialogController,
+ ManagedDialogInput,
+ ManagedDialogProps,
+ OpenDialogOptions,
+ PropsSource,
+} from './components/ImperativeDialog';
+export {
+ ImperativeDialogHost,
+ openDialog,
+ useImperativeDialog,
+} from './components/ImperativeDialog';
export { Layer } from './components/Layer';
export { LogoProgress } from './components/LogoProgress';
export type { NavRowProps } from './components/NavRow';