Skip to content
Merged
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
6 changes: 4 additions & 2 deletions .agents/skills/dragone-component-authoring/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,10 @@ live in `AGENTS.md` (root) and `projects/dragone/ui/AGENTS.md`; this skill is th
6. **Tests.** Use `render()` from `@wismaz/vitest-browser-angular`; add a Test Host for native
element selectors or parent-driven tests. Timers: `setUpFastForward()` /
`setUpManualForward()` from `tests/setup-timer-mode.ts`.
7. **Stories.** Add `<name>.stories.ts` with `tags: ['autodocs']`, title `Dragone/UI/<Name>`,
and `play` functions for interactive behavior.
7. **Stories.** Add `<name>.stories.ts` with `tags: ['autodocs']`, `play` functions for interactive
behavior, and title `Dragone/UI/<Name>` — or a nested `Dragone/UI/<Name>/<Unit>` when the entry
point exposes several units that read better apart (e.g. `Dragone/UI/Dialog/Component` and
`Dragone/UI/Dialog/Service`).
8. **Validate.** `pnpm format:check`, `pnpm lint`,
`CI=true pnpm exec vitest run <area>`, `CI=true pnpm test`, `pnpm build @dragone/ui`;
add `pnpm build-storybook` if stories changed.
Expand Down
30 changes: 30 additions & 0 deletions docs/adr/0009-dialog-declarative-and-service-api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Dialog: Declarative Component plus a Dynamic Service

One entry point, `@dragone/ui/dialog`, exposes two distinct units over one shared skeleton, built on `ng-primitives/dialog` (`NgpDialogManager`, `NgpDialogOverlay`, `NgpDialog`, `NgpDialogTitle`, `NgpDialogDescription`):

- **`Dialog`** (component, `<drgn-dialog>`): declarative — content in markup, opening driven by a two-way `[(open)]` binding.
- **`DynamicDialog`** (service): programmatic — `DynamicDialog.open(BodyComponent, config)` creates the body component at runtime and returns a `DynamicDialogRef`.

Both render the same private `DialogPanel` skeleton (scrim, panel, status icon, title, description, close action) and are portaled by `NgpDialogManager`, which owns focus trap, escape routing, scrim clicks, scroll blocking, `aria-hidden` bookkeeping and exit animations — nothing is re-implemented (ADR-0001). They are documented as two Storybook sections: `Dragone/UI/Dialog/Component` and `Dragone/UI/Dialog/Service`.

## Considered Options

- **One entry point, two units (chosen)**: The skeleton is private and shared, so both units stay in the same secondary entry point and differ only in their public surface and docs. Keeps one source of truth for markup and styles.
- **Two entry points (`@dragone/ui/dialog` + `@dragone/ui/dialog-service`)**: Rejected: cross-entry-point imports resolve only through public exports (AGENTS rule), so the shared panel would have to be either published (it injects `NgpDialogRef`; not a consumer API) or duplicated (two skeletons — what this ADR exists to prevent). A third "internals" entry point would invent a pattern the repo does not have.
- **Service-only (earlier step)**: One call site for dialogs, typed results and reactive input bindings, but no way to author a dialog in markup — every dialog needed a body component class and an imperative call.
- **Declarative-only**: Markup-native, but dynamic bodies would force every consumer to wire portals, templates and injectors themselves.
- **Re-export the upstream `NgpDialogManager` / `NgpDialogTrigger`**: Zero Dragone code, but no Sirio styling, no typed result contract, and the public API would leak upstream internals (root `public-api.ts` stays a placeholder per ADR-0002 anyway).

## Consequences

- `DialogPanel` is a **Private Component** shared by both units: its selector, inputs and the service's context token are internal. Public surface: `Dialog`, `DynamicDialog`, `DynamicDialogConfig`, `DynamicDialogRef`, `injectDynamicDialogRef`, `DialogSize`, `DialogRole`. The dynamic unit carries the `Dynamic` prefix throughout, so no name reads as configuration for the component.
- The declarative component cannot be opened by the manager as a _component_ (the manager's `ComponentPortal` accepts no projectable nodes), so it portals its own `<ng-template>` containing the panel and its `<ng-content>`. Angular resolves that projection because the embedded view keeps a reference to its declaration view — verified with a probe (both descendant and ancestor view containers) before committing to the design.
- The declarative component closes its dialog on destroy: the portaled dialog lives outside the component's view and would otherwise outlive its owner (e.g. a route change while the dialog is open).
- `DynamicDialog.open()` and `injectDynamicDialogRef()` hand out the same memoized handle per dialog. `DynamicDialogRef` is an interface backed by a private implementation — the upstream `NgpDialogRef` never appears in the public types.
- `DynamicDialogConfig.inputs` and `.outputs` are the reactive seam for dynamic bodies: they compile to declarative `inputBinding`/`outputBinding` bindings at `createComponent` time, so the body uses plain signal inputs and outputs like in a template — the framework owns propagation, no manual `setInput`/subscription bookkeeping.
- No CDK-style `data` bag: with declarative input bindings available, a payload token would duplicate the seam with weaker typing. The body declares its payload as typed inputs (`inputs: { articleId: signal(42) }`), and `DynamicDialogRef`/`DynamicDialogConfig` carry no data generic — the only generic left is the close result.
- The declarative component exposes `title`, `description`, `size`, `status`, `closeButtonLabel`, `modal` and `open`; escape/outside-click/container come from the global `provideDialogConfig` (the manager's trigger path offers no per-dialog switch for them either).
- `modal: false` renders no scrim (transparent, `pointer-events: none`) and `aria-modal="false"`; the page stays pointer-interactive. Two upstream limitations in `NgpDialog`/`NgpDialogManager` remain and cannot be worked around through the public API; they are recorded here rather than escalated because they are library gaps, not Sirio design defects (ADR-0005):
- **Focus stays trapped even when non-modal.** `NgpDialog` always applies `NgpFocusTrap` and does not derive it from `modal`: the trap arms unconditionally, and its `disabled` input only skips the initial focus and is not exposed. Keyboard users therefore cannot leave a "non-modal" dialog. Fixing it requires an upstream change to derive/expose the focus trap from `modal`.
- **Page scroll is blocked while any dialog is open,** including non-modal ones. Fixing it requires scroll blocking to become modal-aware upstream.
- Faithfulness notes recorded with the tokens (`src/components.css`): several Penpot variants carry an untokenized `#aab2bb/50%` shadow (token-linked elevations are used), the warning/danger icons are swapped versus Alert (circle-exclamation / triangle-exclamation per the dialog design), and `success` has no dialog variant in the design (Alert's icon is used).
1 change: 1 addition & 0 deletions oxlint.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ export default defineConfig({
overrides: { constructors: 'off', methods: 'no-public' }
}
],
'typescript/method-signature-style': 'off',
'typescript/no-duplicate-enum-values': 'error',
'typescript/no-empty-interface': 'error',
'typescript/no-empty-object-type': 'error',
Expand Down
8 changes: 5 additions & 3 deletions projects/dragone/ui/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,11 @@ Components. Never create a barrel export from the root `public-api.ts`; its plac
- `test-setup.ts` forces `prefers-reduced-motion: reduce`; do not re-enable animations in
tests.
- There is no e2e runner: interaction coverage lives in `play` functions.
- Every visual Component has `<name>.stories.ts` with `tags: ['autodocs']` and title
`Dragone/UI/<Name>`. Add `play` functions for the interactive behavior you touch. Preview
with `pnpm storybook`; verify with `pnpm build-storybook`.
- Every visual Component has `<name>.stories.ts` with `tags: ['autodocs']`. Title: `Dragone/UI/<Name>`
when the entry point documents a single unit; when it exposes several units that read better apart
(e.g. a component and the service over the same skeleton), nest them as `Dragone/UI/<Name>/<Unit>`
— `Dragone/UI/Dialog/Component` and `Dragone/UI/Dialog/Service`. Add `play` functions for the
interactive behavior you touch. Preview with `pnpm storybook`; verify with `pnpm build-storybook`.

## Component validation

Expand Down
1 change: 1 addition & 0 deletions projects/dragone/ui/dialog/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './public-api';
6 changes: 6 additions & 0 deletions projects/dragone/ui/dialog/ng-package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"$schema": "../../../../node_modules/ng-packagr/ng-package.schema.json",
"lib": {
"entryFile": "public-api.ts"
}
}
3 changes: 3 additions & 0 deletions projects/dragone/ui/dialog/public-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './src/component/dialog';
export * from './src/models/dialog.model';
export * from './src/dynamic/dynamic-dialog';
6 changes: 6 additions & 0 deletions projects/dragone/ui/dialog/src/component/dialog.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/* Flat :host selectors per ADR-0008 (no nesting under :host). */

/* The component renders nothing inline: the content is portaled into the dialog container. */
:host {
display: contents;
}
126 changes: 126 additions & 0 deletions projects/dragone/ui/dialog/src/component/dialog.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { Component, signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { faSolidCircleExclamation } from '@ng-icons/font-awesome/solid';
import { render } from '@wismaz/vitest-browser-angular';
import { NgpDialogManager } from 'ng-primitives/dialog';
import { firstValueFrom } from 'rxjs';
import { page, userEvent } from 'vitest/browser';

import type { StatusType } from '@dragone/ui/utils';

import type { DialogSize } from '../models/dialog.model';
import { Dialog } from './dialog';

@Component({
selector: 'drgn-dialog-declarative-host',
imports: [Dialog],
template: `
<drgn-dialog
title="Titolo finestra di dialogo"
description="Descrizione della finestra"
[size]="size()"
[status]="status()"
[modal]="modal()"
[(open)]="open"
>
<p data-testid="dialog-content">Contenuto proiettato</p>
</drgn-dialog>
`
})
class DeclarativeHost {
readonly open = signal(false);
readonly size = signal<DialogSize>('small');
readonly status = signal<StatusType>('neutral');
readonly modal = signal(true);
}

describe(Dialog, () => {
const renderDialog = async () => render(DeclarativeHost);

afterEach(async () => {
const manager = TestBed.inject(NgpDialogManager);
if (manager.openDialogs.length > 0) {
manager.closeAll();
await firstValueFrom(manager.afterAllClosed);
}
});

it('renders the projected content and the title when open becomes true', async () => {
const { componentClassInstance: host } = await renderDialog();
expect(page.getByRole('dialog').elements()).toHaveLength(0);

host.open.set(true);

await expect
.element(page.getByRole('dialog', { name: 'Titolo finestra di dialogo' }))
.toBeInTheDocument();
await expect
.element(page.getByTestId('dialog-content'))
.toHaveTextContent('Contenuto proiettato');
await expect.element(page.getByText('Descrizione della finestra')).toBeInTheDocument();
});

it('forwards the panel inputs', async () => {
const { componentClassInstance: host } = await renderDialog();
host.size.set('large');
host.status.set('warning');
host.open.set(true);

await expect.element(page.getByRole('dialog')).toHaveAttribute('data-size', 'large');
await expect.element(page.getByRole('dialog')).toHaveAttribute('data-status', 'warning');
await expect
.element(page.getByTestId('dialog-status-icon'))
.toContainHTML(faSolidCircleExclamation);
});

it('closes and writes back to the two-way binding from the close button', async () => {
const { componentClassInstance: host } = await renderDialog();
host.open.set(true);
await expect.element(page.getByRole('dialog')).toBeInTheDocument();

await userEvent.click(page.getByRole('button', { name: 'Chiudi' }));

await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();
expect(host.open()).toBeFalsy();
});

it('closes and writes back to the two-way binding on escape', async () => {
const { componentClassInstance: host } = await renderDialog();
host.open.set(true);
await expect.element(page.getByRole('dialog')).toBeInTheDocument();

await userEvent.keyboard('{Escape}');

await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();
expect(host.open()).toBeFalsy();
});

it('opens and closes from the consumer binding', async () => {
const { componentClassInstance: host } = await renderDialog();

host.open.set(true);
await expect.element(page.getByRole('dialog')).toBeInTheDocument();

host.open.set(false);
await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();
});

it('renders a non-modal dialog without scrim and with aria-modal false', async () => {
const { componentClassInstance: host } = await renderDialog();
host.modal.set(false);
host.open.set(true);

await expect.element(page.getByTestId('dialog-overlay')).toHaveAttribute('data-modal', 'false');
await expect.element(page.getByRole('dialog')).toHaveAttribute('aria-modal', 'false');
});

it('closes its dialog when the host is destroyed', async () => {
const { componentClassInstance: host, fixture } = await renderDialog();
host.open.set(true);
await expect.element(page.getByRole('dialog')).toBeInTheDocument();

fixture.destroy();

await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();
});
});
181 changes: 181 additions & 0 deletions projects/dragone/ui/dialog/src/component/dialog.stories.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import {
argsToTemplate,
moduleMetadata,
type Meta,
type StoryObj
} from '@analogjs/storybook-angular';
import { Component, input, signal } from '@angular/core';
import { expect, screen, userEvent, waitFor } from 'storybook/test';

import { Button } from '@dragone/ui/button';
import type { StatusType } from '@dragone/ui/utils';

import { Dialog } from './dialog';
import type { DialogSize } from './dialog.model';

/**
* Declarative demo: the content is authored in markup and the dialog is driven by a two-way `open`
* binding. The rendered `Aperta:` line mirrors the binding, so the write-back is observable.
*/
@Component({
selector: 'drgn-dialog-declarative-demo',
imports: [Button, Dialog],
template: `
<button drgnButton type="button" (click)="open.set(true)">Apri finestra di dialogo</button>
<p class="drgn-p-md-01" data-testid="dialog-open-state">Aperta: {{ open() }}</p>
<drgn-dialog
[title]="title()"
[description]="description()"
[size]="size()"
[status]="status()"
[modal]="modal()"
[(open)]="open"
>
<p class="drgn-p-md-01">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua.
</p>
<footer class="demo-actions">
<button drgnButton type="button" semantic="secondary" (click)="open.set(false)">
Annulla
</button>
<button drgnButton type="button" (click)="open.set(false)">Conferma</button>
</footer>
</drgn-dialog>
`,
styles: `
.demo-actions {
display: flex;
gap: 24px;
}
`
})
class DeclarativeDemo {
readonly title = input('Titolo finestra di dialogo');
readonly description = input<string | undefined>(undefined);
readonly size = input<DialogSize>('small');
readonly status = input<StatusType>('neutral');
readonly modal = input(true);
readonly open = signal(false);
}

const meta: Meta<Dialog> = {
title: 'Dragone/UI/Dialog/Component',
component: Dialog,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Declarative dialog: the content is authored in markup and projected into the shared ' +
'dialog panel, while `[(open)]` drives opening and closing. The component renders nothing ' +
'inline — it portals its own template through `NgpDialogManager`, so the projected ' +
'content inherits the primitive focus trap, escape/outside-click handling, scroll ' +
'blocking and `aria-hidden` bookkeeping. Closing from the dialog itself (escape, scrim, ' +
'close button) writes back into the `open` binding. Prefer it when the body is known at ' +
'build time; for a body component chosen at runtime use `Dragone/UI/Dialog/Service`.'
}
}
},
args: {
title: 'Titolo finestra di dialogo',
description: 'Descrizione facoltativa della finestra di dialogo.',
size: 'small',
status: 'neutral',
modal: true
},
argTypes: {
title: { control: 'text' },
description: { control: 'text' },
size: {
options: ['small', 'large'],
control: { type: 'select' },
table: { defaultValue: { summary: 'small' } }
},
status: {
options: ['neutral', 'info', 'success', 'warning', 'danger'],
control: { type: 'select' },
table: { defaultValue: { summary: 'neutral' } }
},
modal: {
control: 'boolean',
table: { defaultValue: { summary: 'true' } }
}
},
decorators: [moduleMetadata({ imports: [Button, DeclarativeDemo] })]
};

export default meta;
type Story = StoryObj<DeclarativeDemo>;

export const Default: Story = {
render: args => ({
props: args,
template: `<drgn-dialog-declarative-demo ${argsToTemplate(args)} />`
}),
play: async ({ canvas, step }) => {
await step('opens from the [(open)] binding', async () => {
await userEvent.click(canvas.getByRole('button', { name: 'Apri finestra di dialogo' }));
// The dialog is portaled into document.body, outside the story canvas: `screen`
// (document.body-scoped) is the locator that can see it.
await waitFor(() => {
expect(screen.getByRole('dialog', { name: 'Titolo finestra di dialogo' })).toBeVisible();
});
});
await step('closes from the projected action and syncs the binding', async () => {
await userEvent.click(screen.getByRole('button', { name: 'Conferma' }));
await waitFor(() => {
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
});
}
};

export const Large: Story = {
args: { size: 'large' },
render: args => ({
props: args,
template: `<drgn-dialog-declarative-demo ${argsToTemplate(args)} />`
})
};

export const Warning: Story = {
args: { status: 'warning' },
render: args => ({
props: args,
template: `<drgn-dialog-declarative-demo ${argsToTemplate(args)} />`
})
};

export const NonModal: Story = {
args: { modal: false },
render: args => ({
props: args,
template: `<drgn-dialog-declarative-demo ${argsToTemplate(args)} />`
})
};

/**
* The dialog closing itself (here: escape) writes back into the consumer's `open` signal — the
* rendered state line follows.
*/
export const TwoWayBinding: Story = {
render: args => ({
props: args,
template: `<drgn-dialog-declarative-demo ${argsToTemplate(args)} />`
}),
play: async ({ canvas, step }) => {
await userEvent.click(canvas.getByRole('button', { name: 'Apri finestra di dialogo' }));
await step('the consumer state reflects the open dialog', async () => {
await waitFor(() => {
expect(canvas.getByTestId('dialog-open-state')).toHaveTextContent('Aperta: true');
});
});
await step('escape closes the dialog and the binding follows', async () => {
await userEvent.keyboard('{Escape}');
await waitFor(() => {
expect(canvas.getByTestId('dialog-open-state')).toHaveTextContent('Aperta: false');
});
});
}
};
Loading
Loading