Repository navigation
feat(design): add a dialog component - #509
Conversation
Add two components with a shared configuration (ComplianceConfig), so that apps add cookie consent and a compliance footer from configuration alone: - ecc-utils-design-cookie-consent: banner on the first visit (accept all, necessary only, customize), preferences dialog per category, consent in localStorage, asked again when the categories or the version change; hasConsent(), onConsentChange(), openCookiePreferences() and a window event for other code. - ecc-utils-design-compliance-footer: default legal items (privacy, terms, cookie policy, cookie preferences, imprint, accessibility, contact, privacy choices) that operators change, hide or extend; actions link, mailto, preferences, Markdown page (escaped subset) and https embed (sandboxed, optionally gated by consent). Configured URLs are checked (no javascript: links). Docs pages with previews and operator notes; tests for both components. Closes #458 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes for the compliance components: - Consent signature includes whether a category is required, so a category that becomes optional asks users again. - Consent that can't be written takes precedence over an older stored choice, which is removed, so revoking works with full storage. - onConsentChange() takes the config and also reports changes from other tabs (storage events); both components follow them. - The cookie consent keeps unsaved choices when an equal config object is passed (e.g. on every React render). - mailto items accept only plain addresses (no percent-encoding). - Same-origin embeds get no allow-same-origin in their sandbox. - Markdown links open a new tab only for other origins. - Footer dialog texts (texts.close); listeners removed on disconnect; URL tests; docs on consent-less embeds and Cookie Preferences. Refs #458 Co-Authored-By: Claude Opus 5.5 <[email protected]>
- A storage event drops consent kept in memory after a failed write, since the other tab's write is newer; a cleared storage (key null) counts too. - The cookie consent refreshes when its preferences close and when it is connected again, so changes made meanwhile aren't missed. Refs #458 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideData structuresDefine the dialog’s public open-change event detail and reason type, which the component and consumers rely on.
APIExpose the dialog component and its event types, and define the component’s public properties and methods.
ImplementationImplement native modal behavior, focus and scroll management, user-action events, slots, and dialog rendering.
UIAdd a runnable demo page showing basic, controlled, and nested dialog usage, and link it from the component demo index.
ConfigurationRecord the dialog as a minor package release change.
DocumentationDocument dialog usage, public API, events, styling, and accessibility, and add the component to the documentation navigation.
TestsExercise dialog state, user interactions, nested behavior, focus management, scroll locking, slots, accessibility, and layout.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 9 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="packages/ecc-utils-design/src/components/compliance-footer/compliance-footer.ts" line_range="178" />
<code_context>
+ // a same-origin frame with both flags could lift its own sandbox
+ const sandbox = isSameOrigin(src)
+ ? "allow-scripts allow-popups allow-popups-to-escape-sandbox"
+ : "allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox";
+ return html`<iframe
+ class="mt-4 h-[60vh] w-full rounded-md border border-border"
</code_context>
<issue_to_address>
**Embedded content escapes sandbox restrictions**
When a visitor interacts with a malicious or compromised external embed, the external-frame sandbox allows popups to escape sandboxing. A malicious or compromised embed can open an unsandboxed popup after a user interaction and use it to navigate the app's top-level window, bypassing the frame's sandbox restrictions.
Omit `allow-popups-to-escape-sandbox` or disallow popups for embedded content.
</issue_to_address>
### Comment 2
<location path="packages/ecc-utils-design/src/components/cookie-consent/consent.ts" line_range="342-343" />
<code_context>
+ config?: CookieConsentConfig
+): () => void {
+ const handler = (event: Event) => {
+ const { detail } = event as CustomEvent<{ consent: CookieConsent }>;
+ if (detail?.consent) listener(detail.consent);
+ };
+ const storageHandler = (event: StorageEvent) => {
</code_context>
<issue_to_address>
**Other configurations receive consent**
When multiple consent configurations with different storage keys are used on the same page and one saves consent, `onConsentChange`'s same-window handler forwards every `CONSENT_CHANGED_EVENT` payload without matching the subscribed config's storage key or signature, so listeners receive unrelated choices and can enable optional behavior without consent for their configuration.
Match each event's consent to the subscribed configuration's storage key or signature before invoking its listener.
</issue_to_address>
### Comment 3
<location path="packages/ecc-utils-design/src/components/cookie-consent/cookie-consent.ts" line_range="108" />
<code_context>
+ private listen(): void {
+ this.stopListening?.();
+ this.stopListening = onConsentChange(() => {
+ if (!this.dialog?.open) this.refresh();
+ }, this.config?.cookies);
+ }
</code_context>
<issue_to_address>
**Stale preferences overwrite newer consent**
When one tab changes consent while another tab's preferences dialog is open, and the second tab then saves, `listen()` skips `refresh()` while the dialog is open, so this tab's `choices` remain stale; saving them calls `saveConsent()` for every category and overwrites the other tab's newer choices.
Reconcile incoming consent with the dialog's edits before saving, or detect that consent changed since the dialog opened and refresh or ask the user to resolve it.
</issue_to_address>
### Comment 4
<location path="packages/ecc-utils-design/src/components/cookie-consent/consent.ts" line_range="323-324" />
<code_context>
+ updatedAt: new Date().toISOString(),
+ };
+ writeItem(consentStorageKey(config), JSON.stringify(consent));
+ window.dispatchEvent(
+ new CustomEvent(CONSENT_CHANGED_EVENT, { detail: { consent } })
+ );
+ return consent;
</code_context>
<issue_to_address>
**Reentrant saves deliver stale consent**
When an earlier consent-change listener saves consent while handling an event, and a later listener also reacts to consent changes, `dispatchEvent()` invokes listeners synchronously, so an earlier listener that calls `saveConsent()` dispatches a newer event before the outer dispatch reaches later listeners; those listeners then receive the newer consent followed by the stale one and can re-enable behavior after a revocation.
Queue consent notifications and drain them in save order rather than allowing nested dispatches to overtake the outer event.
</issue_to_address>
### Comment 5
<location path="packages/ecc-utils-design/src/components/cookie-consent/consent.ts" line_range="314" />
<code_context>
+ }
+ const categories: Record<string, boolean> = {};
+ cookieCategories(config).forEach((category) => {
+ categories[category.id] =
+ !!category.required || consent.categories?.[category.id] === true;
+ });
</code_context>
<issue_to_address>
**The special category choice is lost**
When a configured category has the ID `__proto__`, `saveConsent()` assigns the category into ordinary objects, so the inherited `__proto__` setter prevents the choice from being stored or serialized; reads then miss the consent and the preference can appear enabled regardless of the user's choice.
Use prototype-safe records or equivalent own-property handling for category choices and saved consent.
Also at `packages/ecc-utils-design/src/components/cookie-consent/cookie-consent.ts:138-139`, `packages/ecc-utils-design/src/components/cookie-consent/consent.ts:273-276`.
</issue_to_address>
### Comment 6
<location path="packages/ecc-utils-design/src/components/cookie-consent/consent.ts" line_range="190" />
<code_context>
+ * @param config Cookie consent configuration
+ * @returns The categories
+ */
+export function cookieCategories(
+ config?: CookieConsentConfig
+): CookieCategory[] {
</code_context>
<issue_to_address>
**Duplicate categories conflict**
When configured categories contain duplicate IDs with conflicting `required` values, including a non-required `necessary` category when the default is added, `cookieCategories()` retains duplicate IDs, so the preferences can show conflicting switches while `saveConsent()` stores one value per ID and `hasConsent()` can treat the category as granted even after rejection.
Deduplicate category IDs while preserving the required category's consent semantics.
Also at `packages/ecc-utils-design/src/components/cookie-consent/consent.ts:193-198`, `packages/ecc-utils-design/src/components/cookie-consent/consent.ts:292-298`, `packages/ecc-utils-design/src/components/cookie-consent/consent.ts:314-315`.
</issue_to_address>
### Comment 7
<location path="packages/ecc-utils-design/src/components/cookie-consent/consent.ts" line_range="193" />
<code_context>
+export function cookieCategories(
+ config?: CookieConsentConfig
+): CookieCategory[] {
+ const categories = (config?.categories ?? []).filter(
+ (category) => category && typeof category.id === "string" && category.id
+ );
</code_context>
<issue_to_address>
**Malformed config breaks rendering**
When runtime deployment configuration supplies a non-array `cookies.categories` or `footer.items` value, `cookieCategories` or `footerItems` calls `.filter()` on the configured value, so a deployment setting with `categories` or `items` set to a non-array throws during component updates and the consent or footer UI fails to render. No runtime shape check catches this.
Validate these fields as arrays before filtering and fall back safely or report the invalid setting.
Also at `packages/ecc-utils-design/src/components/cookie-consent/consent.ts:374`.
</issue_to_address>
### Comment 8
<location path="packages/ecc-utils-design/src/components/cookie-consent/cookie-consent.ts" line_range="124" />
<code_context>
+ private async openDialog(item: DialogItem): Promise<void> {
+ this.openItem = item;
+ await this.updateComplete;
+ if (this.dialog && !this.dialog.open) this.dialog.showModal();
+ }
+
</code_context>
<issue_to_address>
**Detached dialogs reject opening**
When the component is removed after an open request schedules an update but before `updateComplete` resolves, `showModal()` runs after an `await` without checking whether the component is still connected; removing the component while its update is pending leaves the dialog detached, so `showModal()` throws and the preferences or footer page does not open.
After awaiting `updateComplete`, return without opening the dialog if the component is no longer connected.
Also at `packages/ecc-utils-design/src/components/compliance-footer/compliance-footer.ts:107`.
</issue_to_address>
### Comment 9
<location path="apps/documentation/pages/docs/design/components/cookie-consent.mdx" line_range="99" />
<code_context>
+ </Tabs.Tab>
+ <Tabs.Tab>
+ ```html showLineNumbers copy filename="index.html"
+ <script type="module" src="https://esm.sh/@elixir-cloud/[email protected]/components/cookie-consent"></script>
+ <ecc-utils-design-cookie-consent></ecc-utils-design-cookie-consent>
+ <script type="module">
</code_context>
<issue_to_address>
**HTML examples load unavailable release**
The package version is `2.0.0-alpha.49`, so these URLs request `2.0.0-alpha.50`, which is not the version built by this PR. Users following either HTML example fail to load the component or load no implementation of the new feature.
Point the examples at the package version that contains these components, or bump the package version to `2.0.0-alpha.50` through the release process.
Also at `apps/documentation/pages/docs/design/components/compliance-footer.mdx:70`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 9 findings to address first, and if consent checks or their configuration are wrong, an optional embed or script could load before the user has agreed, sending browsing data to a third party. Reverting can stop future loads, but it cannot undo data already disclosed.
Blocking findings: packages/ecc-utils-design/src/components/compliance-footer/compliance-footer.ts:178, packages/ecc-utils-design/src/components/cookie-consent/consent.ts:343, packages/ecc-utils-design/src/components/cookie-consent/cookie-consent.ts:108, packages/ecc-utils-design/src/components/cookie-consent/consent.ts:324, packages/ecc-utils-design/src/components/cookie-consent/consent.ts:314, and 4 more
Fixes from the automated review: - onConsentChange() reports only consent of its config's storage key; the window event's detail carries the storage key. - Consent events are dispatched in save order, also when a listener saves consent itself. - Categories with the same ID are merged (required wins); __proto__ and non-array settings are skipped, also for footer items. - Consent from another tab is merged into open preferences: categories the user switched stay, the others follow. - Dialogs don't open once the element was removed. - Embeds lose allow-popups-to-escape-sandbox. Refs #458 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the conflict in the design package's test scripts: take dev's port 8000, as assigned to the package in #446. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Linked issues
#458 feat: cookie consent and compliance footer · 9 of 10 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Show a consent banner on the first visit | 🟡 Partly met | The banner is suppressed when there are no optional categories unless notice is enabled. |
| 2 | Collect consent per category, including necessary and configurable categories | ✅ Met | Categories are configurable, and a required necessary category is added when none is marked required. |
| 3 | Store consent in the browser and ask again when configured categories change | ✅ Met | Consent is stored in localStorage, and the signature includes category IDs, required status, and policy version. |
| 4 | Provide a way to reopen cookie preferences | ✅ Met | The footer preferences action and openCookiePreferences() open the preferences dialog. |
| 5 | Provide an API or event for checking consent before loading optional scripts | ✅ Met | The change exports hasConsent(), onConsentChange(), and consent events. |
| 6 | Provide a configurable compliance footer with the listed default items | ✅ Met | The defaults are defined in the shared consent module; entries without actions are not displayed. |
| 7 | Let operators remove, change, and add footer items | ✅ Met | Footer configuration supports overrides, hidden items, additional items, and replacing the defaults. |
| 8 | Support Markdown pages, embeds, mailto, preferences, and external links as item actions | ✅ Met | Each action is supported; embed actions can name a consent category and wait for that consent before rendering the frame. |
| 9 | Document a sample configuration and what operators must provide | ✅ Met | The component docs include configuration examples and operator notes on policies, consent, and embed CSP. |
| 10 | Allow apps to add consent management and a footer from configuration alone | ✅ Met | Both components consume the shared ComplianceConfig. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## dev #509 +/- ##
==========================================
+ Coverage 76.21% 76.97% +0.76%
==========================================
Files 71 73 +2
Lines 18122 18783 +661
Branches 1088 1177 +89
==========================================
+ Hits 13811 14458 +647
- Misses 4292 4304 +12
- Partials 19 21 +2 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Linked issuesChecked at commit a3926b3 #458 feat: cookie consent and compliance footer · 0 of 9 met
#585 feat(design): add a dialog component · 7 of 7 met
|
anuragxxd
left a comment
There was a problem hiding this comment.
Thanks for this, the URL checks and escaping look solid. I'd keep the design package to generic building blocks, though. Cookie consent and the legal footer are app features (storage, consent rules, Markdown), and they'd tie every app to one policy.
What we're missing is a generic Dialog, matching shadcn's (open, title/description/footer slots, Esc and overlay to close, focus trap, an open-change event). Could this PR become that? The consent banner and footer can then live in cloud-registry-ui, built from Dialog, Button and Checkbox, without embed/page.
Per review, the design package keeps to generic building blocks: cookie consent and the compliance footer are app features and move to cloud-registry-ui. In their place, add ecc-utils-design-dialog, a modal dialog matching shadcn/ui's Dialog: open, show() and close(); trigger, title, description and footer slots; Escape, overlay click, close button and data-dialog-close to close; a focus trap with focus return; and the cancelable ecc-dialog-open-changed event for user actions. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Skip elements that report tabIndex 0 but can't take focus, and try the next candidate if focus() fails, so Tab never gets stuck. Keep the trap for triggers of closed nested dialogs, let content handle Escape and Tab first, scroll tall content, and put the trigger's ARIA state on the focusable control of custom-element triggers. Move the reason type to the event module, add a demo page. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Lit-based triggers such as ecc-utils-design-button may render their inner control after the trigger slot changed. Set aria-haspopup and aria-expanded again once they have rendered, and test that without a manual update. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@anuragxxd Thanks, agreed. I've reworked the PR into a generic Dialog and taken cookie consent and the footer out of the design package. What's in it now:
It comes with 49 tests (Chromium and Firefox locally, WebKit in CI), a docs page, a demo and a changeset. Where consent and footer go: a follow-up issue in cloud-registry-ui will cover building the banner and the footer there from Dialog, Button and Checkbox, without Ready for another look when you have time. |
anuragxxd
left a comment
There was a problem hiding this comment.
Thanks, this is a clean Dialog. Two things:
- Focus doesn't return to the trigger in Safari, or Firefox on macOS: a mouse click doesn't focus buttons there, so focus goes to
body. Saving the trigger from the click would fix it (the test focuses it manually first). - The open-change event bubbles, so closing a nested dialog also closes the outer one in the controlled example. A
e.target === e.currentTargetguard in the docs (or the component) would fix it.
Optional: body scroll lock while open, as shadcn does.
After review: - Return focus to the trigger that opened the dialog also when a click did not focus it (Safari, Firefox on macOS), and to the inner control of a custom-element trigger; keyboard focus is kept. - ecc-dialog-open-changed no longer bubbles, so a controlled outer dialog does not close when a nested one does. - Lock the page scrolling while a dialog is open, as shadcn/ui does; nested dialogs share the lock, the last close restores the page. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Find a focusable control also inside a light-DOM wrapper trigger, and fall back to the element focused before if there is none. Restore the body styles only where the lock still has its own values, so that changes by the app or other scroll lockers stay. Docs say that the event, unlike the other components, does not bubble. Adds tests for wrapper triggers, canceled openings, the scrollbar padding and styles changed during the lock. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks! All three are in, and the branch has the latest Focus return without a focusing click
Open-change event and nested dialogs
Body scroll lock
Locally, 123 dialog tests pass in Chromium and Firefox. Both reviewer agents ran two rounds, and their findings are fixed (see the PR body). Could you take another look? |
anuragxxd
left a comment
There was a problem hiding this comment.
Thanks, focus return, nested events and the scroll lock all look right. LGTM.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sourcery withdrew this approval because it has stopped reviewing this pull request.
|
Sourcery has withdrawn its approval of this pull request. It auto-reviews a pull request 5 times, and this push is past that limit, so the approval no longer reflects code Sourcery has read. Comment |
Description
Reworked after review: the design package keeps to generic building blocks, so this PR no longer adds cookie consent and a compliance footer. It adds
ecc-utils-design-dialog, a modal dialog matching shadcn/ui's Dialog. The consent banner and the footer move to cloud-registry-ui, built from Dialog, Button and Checkbox, withoutembed/page(follow-up issue to be opened there).open(reflected),show()andclose(). Built on the native<dialog>withshowModal(), so the rest of the page is inert and the dialog sits in the top layer.trigger(opens on click; getsaria-haspopup="dialog"andaria-expanded),title,description, default (body) andfooter. Header and footer hide when empty.no-overlay-close), the close button (close-label,hide-close-button), and any element withdata-dialog-close(likeDialogClose). Nested dialogs: only the innermost closes.autofocus, else the first focusable element, else the panel); a focus trap that handles every Tab and Shift+Tab across slots and shadow roots, so it behaves the same in every browser; focus returns on close to the trigger (saved on click, so it works where a click doesn't focus buttons, as in Safari; for custom-element or wrapper triggers, their focusable control) or to the element focused before an opening by code.bodydoesn't scroll while a dialog is open; its right padding grows by the scrollbar width so the page doesn't shift. Nested dialogs share the lock; on release, only values the lock set are restored.ecc-dialog-open-changedwith{ open, reason }(trigger,escape,overlay,close-button,close) for user actions only, likeonOpenChange; cancelable (preventDefault()keeps the state). Unlike our other components' events, it doesn't bubble and isn't composed, so an outer dialog's listener never hears a nested dialog. React:onEccDialogOpenChanged.aria-modal,aria-labelledby(title) oraria-label(label),aria-describedby(description); the a11y audit passes.demo/dialog/index.html(basic, controlled, nested).@elixir-cloud/design.Closes #585
Part of #458
How it was verified
npx web-test-runner --group dialoginpackages/ecc-utils-design: 49/49 pass in Chromium and Firefox (open/close, trigger, Escape, cancel, overlay, close button,data-dialog-close, nested dialogs, focus trap incl. elements that refuse focus, focus return, slots, ARIA incl. custom-element triggers, scrolling, axe audit). Coverage ofdialog.tsin Chromium: 510/510 lines. WebKit can't start on my machine; CI runs it.npx eslint --max-warnings 0on the new and changed files: clean (as chore(design): fix ESLint warnings #584 will require for the package).npm run lint(whole repo, also in the pre-commit hook): 0 errors.npm run buildin the package (TypeScript, React wrappers, CEM) andnpx turbo run build --filter=ecc-docs: pass.Second review round (focus return, nested events, scroll lock)
npx web-test-runner --group dialog: 123 pass in Chromium and Firefox (new: focus return after a click that doesn't focus the trigger, custom-element and wrapper triggers, canceled opening, non-bubbling event with a controlled outer dialog, scroll lock incl. scrollbar padding, nesting, removal, browser close, app-changed styles). The only local failure is the existing GlobalStyles "fold arrows" test in Chromium, unrelated and green in CI.npm run lint(pre-commit): pass.mcr.microsoft.com/playwright:v1.56.1-noble): 13 runs of the package and 2 full turbo runs, also with limited CPUs, all green, so I couldn't reproduce it. It needs a closer look in a follow-up if it keeps showing up.Checklist
Declined review findings
Docs version
2.0.0-alpha.52: intentional. The dialog ships first in the release after2.0.0-alpha.51; if it gets another number, the release PR updates the page.Tests in
dialog/tests/rather than next to the component: matches the newer test files (e.g.services/tests/services.test.tsin the service-registry package); the test glob covers both.deepActiveElementduplicated in the test: kept, so the tests check focus independently of the implementation.syncTriggers()in bothupdated()andonSlotChange(): both needed, since a changed trigger slot doesn't always change state and so doesn't always cause an update.ARIA on triggers whose control appears late: Lit-based triggers are marked again once they have rendered (
updateComplete). Triggers that are defined later, or render their control only after a later update, are marked at the dialog's next update (at the latest on open); aMutationObserveron every trigger's shadow root seemed too much for that edge case.Named React imports in the docs (
{ EccUtilsDesignDialog }fromreact/dialog, which has a default export): the same on every component page; better fixed for all pages in a separate change.html-leveloverflowandscrollbar-gutter: the lock works onbodylike shadcn's; pages that scrollhtmlor reserve a gutter are an edge case for later.A trigger click whose opening is canceled and later re-opened asynchronously loses the trigger: focus then returns to the element focused at opening, which is sensible.
Moving an open dialog in the DOM loses the focus-return target: behaviour from before this round, rare.
Lock state is per copy of the module: a page should load the design package once; noted in the code.
Only the first focusable element in a wrapper trigger gets
aria-expanded: one control per wrapper is the normal case.Open questions
None.
Comments
🤖 Generated with Claude Code