@tonycodes-ui/mortar 0.25.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,8 @@
1
1
  import { type Navigate } from "./navigation.js";
2
+ import { type OverlayPortal } from "./internal.js";
2
3
  import { type BrandDefinition } from "./brand.js";
3
4
  import { type ReactNode } from "react";
5
+ export type { OverlayPortal };
4
6
  export type Appearance = "light" | "dark" | "system";
5
7
  /**
6
8
  * A built-in brand, or the name of one declared in CSS
@@ -27,7 +29,8 @@ export interface ThemeProviderProps {
27
29
  /**
28
30
  * document writes the root element. container paints a wrapper and leaves
29
31
  * the document unchanged; menus, listboxes and dialogs opened inside it keep
30
- * its theme.
32
+ * its theme. Container scope also mounts an overlay host so Modal and
33
+ * SlideOver can use portal="contained" and stay inside the wrapper.
31
34
  */
32
35
  scope?: "document" | "container";
33
36
  /** On the container wrapper (container scope only). */
@@ -1,10 +1,10 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { NavigationContext } from "./navigation.js";
3
3
  import { SegmentedControl } from "./inspection.js";
4
- import { AsComponentRoot, ThemeScopeContext, componentRoot, } from "./internal.js";
4
+ import { AsComponentRoot, ContainedPortalContext, ThemeScopeContext, componentRoot, } from "./internal.js";
5
5
  import { Portal } from "@headlessui/react";
6
6
  import { brandToCss } from "./brand.js";
7
- import { createContext, useContext, useEffect, useLayoutEffect, useState, useSyncExternalStore, } from "react";
7
+ import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useState, useSyncExternalStore, } from "react";
8
8
  const ThemeContext = createContext(null);
9
9
  const DARK = "(prefers-color-scheme: dark)";
10
10
  function subscribeToScheme(update) {
@@ -58,6 +58,8 @@ export function ThemeProvider({ children, initialAppearance = "system", appearan
58
58
  "data-mortar-appearance": resolvedAppearance,
59
59
  };
60
60
  const host = usePortalHost(scope === "container", attributes);
61
+ const [overlayHost, setOverlayHost] = useState(null);
62
+ const containedPortal = useMemo(() => ({ host: overlayHost }), [overlayHost]);
61
63
  useEffect(() => {
62
64
  if (scope !== "document")
63
65
  return;
@@ -97,7 +99,7 @@ export function ThemeProvider({ children, initialAppearance = "system", appearan
97
99
  // portalled overlays match it wherever they render.
98
100
  _jsx("style", { "data-mortar-brand-style": brand, children: brandCss })), _jsx(ThemeContext.Provider, { value: { appearance, setAppearance, brand, density }, children: children })] }));
99
101
  if (scope === "container")
100
- return (_jsx("div", { ...componentRoot("ThemeProvider"), ...attributes, className: className, children: _jsx(ThemeScopeContext.Provider, { value: attributes, children: _jsx(Portal.Group, { target: host, children: theme }) }) }));
102
+ return (_jsx("div", { ...componentRoot("ThemeProvider"), ...attributes, className: className, children: _jsx(ThemeScopeContext.Provider, { value: attributes, children: _jsxs(ContainedPortalContext.Provider, { value: containedPortal, children: [_jsx(Portal.Group, { target: host, children: theme }), _jsx("div", { ref: setOverlayHost, className: "m-overlay-host" })] }) }) }));
101
103
  return theme;
102
104
  }
103
105
  export function AppearanceControl({ value, onChange, className, } = {}) {
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { ThemeProvider, AppearanceControl } from "./foundation.js";
2
2
  export type { BrandDefinition, BrandAppearanceTokens } from "./brand.js";
3
- export type { ThemeProviderProps, Appearance, Brand, Density, } from "./foundation.js";
3
+ export type { ThemeProviderProps, Appearance, Brand, Density, OverlayPortal, } from "./foundation.js";
4
4
  export { Button, ButtonGroup, ActionLink, Input, Select, TextArea, Checkbox, Fieldset, RadioGroup, Switch, Badge, Tabs, Modal, Dropdown, Notice, EmptyState, ErrorSummary, } from "./primitives.js";
5
5
  export type { ButtonProps, ButtonGroupItem, DropdownItem, ErrorSummaryItem, InputProps, LinkAction, Tone, } from "./primitives.js";
6
6
  export { AppShell, PageHeading, MetricGroup, DataTable, Table, Pagination, SettingsSection, ActivityFeed, SignInPanel, Sidebar, Navbar, StackedShell, Breadcrumbs, ProgressSteps, TabNav, ActionPanel, } from "./application.js";
@@ -417,12 +417,31 @@ export declare function FieldMessage({ id, hint, error, }: {
417
417
  hint?: string;
418
418
  error?: string;
419
419
  }): import("react").JSX.Element | null;
420
+ /**
421
+ * Where an overlay portals. `document` (default) uses Headless UI's body
422
+ * portal. `contained` keeps the overlay inside the nearest container-scoped
423
+ * ThemeProvider's overlay host so an embedded widget does not cover the page.
424
+ */
425
+ export type OverlayPortal = "document" | "contained";
426
+ /**
427
+ * The overlay host of the nearest container-scoped ThemeProvider.
428
+ * Undefined outside one; `{ host: null }` while the host node is mounting.
429
+ * Default is undefined (like ThemeScopeContext) so document-portal dialogs do
430
+ * not depend on ThemeProvider in the catalogue.
431
+ */
432
+ export declare const ContainedPortalContext: import("react").Context<{
433
+ host: HTMLElement | null;
434
+ } | undefined>;
420
435
  /** Headless dialog root with the shared backdrop. */
421
- export declare function DialogFrame({ open, onClose, component, children, }: {
436
+ export declare function DialogFrame({ open, onClose, component, portal, labelledBy, children, }: {
422
437
  open: boolean;
423
438
  onClose: () => void;
424
439
  /** The catalogue component this dialog is the root of, if any. */
425
440
  component?: string;
441
+ /** document (default) portals to the body; contained stays in the widget host. */
442
+ portal?: OverlayPortal;
443
+ /** Accessible name for contained portals (document mode uses DialogTitle). */
444
+ labelledBy?: string;
426
445
  children: ReactNode;
427
446
  }): import("react").JSX.Element;
428
447
  /** Narrow-screen navigation drawer used by AppShell and DocsShell. */
@@ -494,8 +513,9 @@ export declare function focusAway(element: HTMLElement | null, { scope, fallback
494
513
  export declare const ThemeScopeContext: import("react").Context<Record<string, string> | undefined>;
495
514
  /**
496
515
  * Re-applies a container-scoped theme to content rendered outside its wrapper
497
- * (dialogs portal to the document body). The wrapper is display: contents, so
498
- * it carries the tokens without adding a box.
516
+ * (document-portal dialogs land on the body). Contained portals render inside
517
+ * the wrapper and do not need this. The wrapper is display: contents, so it
518
+ * carries the tokens without adding a box.
499
519
  */
500
520
  export declare function ThemeScope({ children }: {
501
521
  children: ReactNode;
package/dist/internal.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  // Shared building blocks for the kit's components. Internal: nothing here is
3
3
  // exported from the package entry, so these can change without a release note.
4
- import { Fragment, createContext, createElement, useContext, useEffect, useId, useState, cloneElement, isValidElement, } from "react";
4
+ import { Fragment, createContext, createElement, useContext, useEffect, useId, useRef, useState, cloneElement, isValidElement, } from "react";
5
+ import { createPortal } from "react-dom";
5
6
  import { CloseButton, Dialog, DialogPanel, DialogTitle, Popover, PopoverButton, PopoverPanel, } from "@headlessui/react";
6
7
  import { KitLink } from "./navigation.js";
7
8
  import { ChevronDown } from "./icons.js";
@@ -179,8 +180,76 @@ export function useField({ id, hint, error, describedBy, }) {
179
180
  export function FieldMessage({ id, hint, error, }) {
180
181
  return error || hint ? (_jsx("p", { id: id, className: error ? "m-error" : "", children: error || hint })) : null;
181
182
  }
183
+ /**
184
+ * The overlay host of the nearest container-scoped ThemeProvider.
185
+ * Undefined outside one; `{ host: null }` while the host node is mounting.
186
+ * Default is undefined (like ThemeScopeContext) so document-portal dialogs do
187
+ * not depend on ThemeProvider in the catalogue.
188
+ */
189
+ export const ContainedPortalContext = createContext(undefined);
190
+ const FOCUSABLE = 'a[href],button:not([disabled]),textarea:not([disabled]),input:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex="-1"])';
191
+ /**
192
+ * Dialog root portalled into a container ThemeProvider's overlay host.
193
+ * Bounds, backdrop and focus stay inside the widget; the host page outside it
194
+ * stays usable. Escape closes; Tab cycles within the dialog.
195
+ */
196
+ function ContainedDialogFrame({ open, onClose, component, labelledBy, children, }) {
197
+ const portal = useContext(ContainedPortalContext);
198
+ if (!portal)
199
+ throw new Error('portal="contained" requires a ThemeProvider with scope="container".');
200
+ const dialogRef = useRef(null);
201
+ const onCloseRef = useRef(onClose);
202
+ onCloseRef.current = onClose;
203
+ useEffect(() => {
204
+ if (!open)
205
+ return;
206
+ const root = dialogRef.current;
207
+ if (!root)
208
+ return;
209
+ const previouslyFocused = document.activeElement;
210
+ const focusables = () => [...root.querySelectorAll(FOCUSABLE)].filter((el) => el.offsetParent !== null || el === document.activeElement);
211
+ const initial = focusables()[0] ?? root;
212
+ initial.focus();
213
+ const onKeyDown = (event) => {
214
+ if (event.key === "Escape") {
215
+ event.preventDefault();
216
+ event.stopPropagation();
217
+ onCloseRef.current();
218
+ return;
219
+ }
220
+ if (event.key !== "Tab")
221
+ return;
222
+ const items = focusables();
223
+ if (items.length === 0) {
224
+ event.preventDefault();
225
+ root.focus();
226
+ return;
227
+ }
228
+ const first = items[0];
229
+ const last = items[items.length - 1];
230
+ if (event.shiftKey && document.activeElement === first) {
231
+ event.preventDefault();
232
+ last.focus();
233
+ }
234
+ else if (!event.shiftKey && document.activeElement === last) {
235
+ event.preventDefault();
236
+ first.focus();
237
+ }
238
+ };
239
+ document.addEventListener("keydown", onKeyDown, true);
240
+ return () => {
241
+ document.removeEventListener("keydown", onKeyDown, true);
242
+ previouslyFocused?.focus?.();
243
+ };
244
+ }, [open]);
245
+ if (!open || !portal.host)
246
+ return null;
247
+ return createPortal(_jsxs("div", { ref: dialogRef, role: "dialog", "aria-modal": "true", "aria-labelledby": labelledBy, tabIndex: -1, className: "m-dialog", "data-portal": "contained", ...componentRoot(component ?? "", component !== undefined), children: [_jsx("div", { className: "m-backdrop", "aria-hidden": "true", onClick: () => onCloseRef.current() }), children] }), portal.host);
248
+ }
182
249
  /** Headless dialog root with the shared backdrop. */
183
- export function DialogFrame({ open, onClose, component, children, }) {
250
+ export function DialogFrame({ open, onClose, component, portal = "document", labelledBy, children, }) {
251
+ if (portal === "contained")
252
+ return (_jsx(ContainedDialogFrame, { open: open, onClose: onClose, component: component, labelledBy: labelledBy, children: children }));
184
253
  return (_jsx(Dialog, { open: open, onClose: onClose, className: "m-dialog", ...componentRoot(component ?? "", component !== undefined), children: _jsxs(ThemeScope, { children: [_jsx("div", { className: "m-backdrop", "aria-hidden": "true" }), children] }) }));
185
254
  }
186
255
  /** Narrow-screen navigation drawer used by AppShell and DocsShell. */
@@ -272,8 +341,9 @@ export function focusAway(element, { scope, fallback, } = {}) {
272
341
  export const ThemeScopeContext = createContext(undefined);
273
342
  /**
274
343
  * Re-applies a container-scoped theme to content rendered outside its wrapper
275
- * (dialogs portal to the document body). The wrapper is display: contents, so
276
- * it carries the tokens without adding a box.
344
+ * (document-portal dialogs land on the body). Contained portals render inside
345
+ * the wrapper and do not need this. The wrapper is display: contents, so it
346
+ * carries the tokens without adding a box.
277
347
  */
278
348
  export function ThemeScope({ children }) {
279
349
  const attributes = useContext(ThemeScopeContext);
@@ -1,5 +1,6 @@
1
1
  import { type ButtonHTMLAttributes, type InputHTMLAttributes, type SelectHTMLAttributes, type TextareaHTMLAttributes, type ReactNode } from "react";
2
2
  import { type HeadingLevel } from "./heading.js";
3
+ import { type OverlayPortal } from "./internal.js";
3
4
  export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
4
5
  /** accent: the brand's accent fill (its accent gradient when it defines one) with on-accent text. */
5
6
  variant?: "primary" | "secondary" | "ghost" | "danger" | "accent";
@@ -152,7 +153,7 @@ export declare function Tabs({ label, value, onChange, items, variant, fullWidth
152
153
  }[];
153
154
  className?: string;
154
155
  }): import("react").JSX.Element;
155
- export declare function Modal({ open, onClose, title, children, actions, size, className, }: {
156
+ export declare function Modal({ open, onClose, title, children, actions, size, className, portal, }: {
156
157
  open: boolean;
157
158
  onClose: () => void;
158
159
  title: string;
@@ -162,6 +163,11 @@ export declare function Modal({ open, onClose, title, children, actions, size, c
162
163
  size?: "md" | "lg";
163
164
  /** On the dialog panel. */
164
165
  className?: string;
166
+ /**
167
+ * document (default) portals over the page. contained keeps the overlay
168
+ * inside the nearest ThemeProvider scope="container" host.
169
+ */
170
+ portal?: OverlayPortal;
165
171
  }): import("react").JSX.Element;
166
172
  export interface DropdownItem {
167
173
  label: string;
@@ -153,9 +153,14 @@ export function Tabs({ label, value, onChange, items, variant = "underline", ful
153
153
  document.getElementById(tabId(items[next].id))?.focus();
154
154
  }, children: items.map((item) => (_jsx("button", { id: tabId(item.id), type: "button", role: "tab", "aria-selected": item.id === value, "aria-controls": `${base}-${item.id}-panel`, tabIndex: item.id === focusable ? 0 : -1, onClick: () => onChange(item.id), children: _jsx(LinkContent, { prefix: "tab", icon: item.icon, label: item.label, count: item.count }) }, item.id))) }), items.map((item) => (_jsx("div", { hidden: item.id !== value, role: "tabpanel", id: `${base}-${item.id}-panel`, "aria-labelledby": tabId(item.id), tabIndex: 0, children: item.content }, item.id)))] }));
155
155
  }
156
- export function Modal({ open, onClose, title, children, actions, size = "md", className, }) {
156
+ export function Modal({ open, onClose, title, children, actions, size = "md", className, portal = "document", }) {
157
157
  const component = useComponentName("Modal");
158
- return (_jsx(DialogFrame, { open: open, onClose: onClose, component: component, children: _jsx("div", { className: "m-dialog-position", children: _jsxs(DialogPanel, { className: cx("m-dialog-panel", className), "data-size": size === "md" ? undefined : size, children: [_jsxs("div", { className: "m-dialog-heading", children: [_jsx(DialogTitle, { children: title }), _jsx(Button, { variant: "ghost", onClick: onClose, "aria-label": "Close dialog", children: "Close" })] }), children, actions && _jsx("div", { className: "m-actions", children: actions })] }) }) }));
158
+ const titleId = useId();
159
+ const panelClass = cx("m-dialog-panel", className);
160
+ const panelSize = size === "md" ? undefined : size;
161
+ const heading = (_jsxs("div", { className: "m-dialog-heading", children: [portal === "contained" ? (_jsx("h2", { id: titleId, children: title })) : (_jsx(DialogTitle, { children: title })), _jsx(Button, { variant: "ghost", onClick: onClose, "aria-label": "Close dialog", children: "Close" })] }));
162
+ const body = (_jsxs(_Fragment, { children: [heading, children, actions && _jsx("div", { className: "m-actions", children: actions })] }));
163
+ return (_jsx(DialogFrame, { open: open, onClose: onClose, component: component, portal: portal, labelledBy: portal === "contained" ? titleId : undefined, children: _jsx("div", { className: "m-dialog-position", children: portal === "contained" ? (_jsx("div", { className: panelClass, "data-size": panelSize, onClick: (event) => event.stopPropagation(), children: body })) : (_jsx(DialogPanel, { className: panelClass, "data-size": panelSize, children: body })) }) }));
159
164
  }
160
165
  export function Dropdown({ label, items, icon, iconOnly = false, variant = "secondary", align = "end", header, className, }) {
161
166
  const groups = [];
@@ -1,6 +1,7 @@
1
1
  import { type ItemGroup } from "./navigation.js";
2
2
  import { type ReactNode } from "react";
3
3
  import { type HeadingLevel } from "./heading.js";
4
+ import { type OverlayPortal } from "./internal.js";
4
5
  export interface SlideOverProps {
5
6
  open: boolean;
6
7
  onClose: () => void;
@@ -12,8 +13,13 @@ export interface SlideOverProps {
12
13
  size?: "md" | "lg" | "xl";
13
14
  /** Class on the sliding panel. */
14
15
  className?: string;
16
+ /**
17
+ * document (default) portals over the page. contained keeps the overlay
18
+ * inside the nearest ThemeProvider scope="container" host.
19
+ */
20
+ portal?: OverlayPortal;
15
21
  }
16
- export declare function SlideOver({ open, onClose, title, description, children, actions, size, className, }: SlideOverProps): import("react").JSX.Element;
22
+ export declare function SlideOver({ open, onClose, title, description, children, actions, size, className, portal, }: SlideOverProps): import("react").JSX.Element;
17
23
  export interface CommandItem {
18
24
  id: string;
19
25
  label: string;
package/dist/workspace.js CHANGED
@@ -7,8 +7,14 @@ import { Kbd } from "./display.js";
7
7
  import { ChevronRight, Close } from "./icons.js";
8
8
  import { childLevel, headingTag } from "./heading.js";
9
9
  import { DialogFrame, componentRoot, cx, useComponentName, } from "./internal.js";
10
- export function SlideOver({ open, onClose, title, description, children, actions, size = "md", className, }) {
11
- return (_jsx(DialogFrame, { open: open, onClose: onClose, component: "SlideOver", children: _jsxs(DialogPanel, { className: cx("m-slide-over", className), "data-size": size === "md" ? undefined : size, children: [_jsxs("header", { children: [_jsxs("div", { children: [_jsx(DialogTitle, { children: title }), description && _jsx(Description, { children: description })] }), _jsx(Button, { variant: "ghost", onClick: onClose, "aria-label": "Close panel", children: _jsx(Close, {}) })] }), _jsx("div", { className: "m-slide-over-body", children: children }), actions && _jsx("footer", { className: "m-actions", children: actions })] }) }));
10
+ export function SlideOver({ open, onClose, title, description, children, actions, size = "md", className, portal = "document", }) {
11
+ const titleId = useId();
12
+ const panelClass = cx("m-slide-over", className);
13
+ const panelSize = size === "md" ? undefined : size;
14
+ const header = (_jsxs("header", { children: [_jsxs("div", { children: [portal === "contained" ? (_jsx("h2", { id: titleId, children: title })) : (_jsx(DialogTitle, { children: title })), description &&
15
+ (portal === "contained" ? (_jsx("p", { children: description })) : (_jsx(Description, { children: description })))] }), _jsx(Button, { variant: "ghost", onClick: onClose, "aria-label": "Close panel", children: _jsx(Close, {}) })] }));
16
+ const body = (_jsxs(_Fragment, { children: [header, _jsx("div", { className: "m-slide-over-body", children: children }), actions && _jsx("footer", { className: "m-actions", children: actions })] }));
17
+ return (_jsx(DialogFrame, { open: open, onClose: onClose, component: "SlideOver", portal: portal, labelledBy: portal === "contained" ? titleId : undefined, children: portal === "contained" ? (_jsx("div", { className: panelClass, "data-size": panelSize, onClick: (event) => event.stopPropagation(), children: body })) : (_jsx(DialogPanel, { className: panelClass, "data-size": panelSize, children: body })) }));
12
18
  }
13
19
  function Highlight({ label, match, }) {
14
20
  if (!match)
package/docs/agents.md CHANGED
@@ -105,6 +105,7 @@ Add `--json` for machine-readable output. `mortar audit` exits with status 1 whe
105
105
  | `unknown-prop` | error | A prop the component's contract does not declare, with the 0.6 rename where there is one |
106
106
  | `invalid-value` | error | A literal outside the prop's declared union, such as `layout="centered"` (now `center`) |
107
107
  | `css-override` | error | Consumer CSS selecting Mortar's `.m-*` classes or `[data-m-component]` |
108
+ | `ancestor-override` | error | An obvious ancestor/native-element selector (such as `.toolbar button`) that reaches a Mortar control in the JSX and sets visual properties (background, border, typography, radius). Layout-only rules and native controls under the same ancestor are not flagged. Complex selectors stay a manual review |
108
109
  | `class-override` | error | A Tailwind arbitrary variant that targets `.m-*` classes, such as `[&_.m-button]:rounded-none` |
109
110
  | `local-copy` | error | A copy of a Mortar source file, or code rendering Mortar's component marker |
110
111
  | `raw-element` | error | A raw `<table>`, `<select>`, `<textarea>`, `<dialog>`, `<progress>` or `<input>` (by type; not `hidden`, `file`, `range`, `color` or `image`) anywhere in an app that uses Mortar, naming the component to use instead. A raw `<button>` is a warning. The mapping comes from each contract's `replaces` field, so new components extend it |
@@ -123,7 +124,7 @@ Add `--json` for machine-readable output. `mortar audit` exits with status 1 whe
123
124
 
124
125
  The audit is a fast scanner, not a type checker. It checks JSX body children when a component's contract has no `children` slot (for example `<Switch>…</Switch>`). It does not see props passed through a spread (`{...props}`), components re-exported or wrapped under another name, class names built at runtime, or markup in `.vue`, `.svelte`, `.astro` or `.html` files. Run the app's typecheck and build as well.
125
126
 
126
- A clean audit means the audit found none of the problems above. It is not proof that a page is built only from Mortar components: hand-written layout, typography or animation in the app's own markup is invisible to it unless it touches Mortar's classes or colours. Do not report a passing audit as that proof. To show a page is composed from the kit, point to the components it renders (each root carries `data-m-component`) and to [what you can extend](theming.md#what-you-can-extend).
127
+ A clean audit means the audit found none of the problems above. It is not proof that a page is built only from Mortar components: hand-written layout, typography or animation in the app's own markup is invisible to it unless it touches Mortar's classes, colours, or an obvious ancestor/native-element visual override. Do not report a passing audit as that proof. To show a page is composed from the kit, point to the components it renders (each root carries `data-m-component`) and to [what you can extend](theming.md#what-you-can-extend).
127
128
 
128
129
  ## Agent skill
129
130
 
package/docs/native.md CHANGED
@@ -143,7 +143,7 @@ A component with a native version names it in its manifest:
143
143
  "platforms": { "swiftui": "MortarTextField", "compose": "MortarTextField" }
144
144
  ```
145
145
 
146
- `get_component` shows it as `native`, with each import, and a build packet for a brief about an iOS, iPadOS or Android app adds this guide and a `native` section listing every component the libraries have. `tests/native.test.mjs` checks that each named view or composable exists, and that every public one is named by a manifest.
146
+ `get_component` shows it as `native`, with each import, and a build packet for a brief about an iOS, iPadOS or Android app adds this guide and a `native` section listing every component the libraries have. `tests/native.test.mjs` checks that each named view or composable exists, and that every public one is named by a manifest. `npm run check` also rejects a malformed `platforms` entry, or one naming a type the native sources do not define (rule M011).
147
147
 
148
148
  ## Brands
149
149
 
package/docs/theming.md CHANGED
@@ -16,7 +16,7 @@ Components only read the live `--m-*` tokens. Never style components directly; c
16
16
  </ThemeProvider>
17
17
  ```
18
18
 
19
- ThemeProvider writes `data-mortar-brand`, `data-mortar-appearance` and `data-mortar-density` on the document root, or on a wrapper with `scope="container"`. Menus, listboxes and dialogs opened inside a container keep its theme.
19
+ ThemeProvider writes `data-mortar-brand`, `data-mortar-appearance` and `data-mortar-density` on the document root, or on a wrapper with `scope="container"`. Menus, listboxes and dialogs opened inside a container keep its theme. A container also mounts an overlay host: Modal and SlideOver `portal="contained"` render into that host so the backdrop and panel stay inside the wrapper (for embedded widgets) instead of covering the host page. The default `portal="document"` still uses the page-level dialog portal.
20
20
 
21
21
  ## Adding a brand
22
22
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tonycodes-ui/mortar",
3
- "version": "0.25.0",
3
+ "version": "0.27.0",
4
4
  "description": "Mortar: a shared design foundation, application and marketing UI for React and Tailwind.",
5
5
  "keywords": [
6
6
  "react",
@@ -2,8 +2,10 @@ import { NavigationContext, type Navigate } from "./navigation.js";
2
2
  import { SegmentedControl } from "./inspection.js";
3
3
  import {
4
4
  AsComponentRoot,
5
+ ContainedPortalContext,
5
6
  ThemeScopeContext,
6
7
  componentRoot,
8
+ type OverlayPortal,
7
9
  } from "./internal.js";
8
10
  import { Portal } from "@headlessui/react";
9
11
  import { brandToCss, type BrandDefinition } from "./brand.js";
@@ -12,11 +14,14 @@ import {
12
14
  useContext,
13
15
  useEffect,
14
16
  useLayoutEffect,
17
+ useMemo,
15
18
  useState,
16
19
  useSyncExternalStore,
17
20
  type ReactNode,
18
21
  } from "react";
19
22
 
23
+ export type { OverlayPortal };
24
+
20
25
  export type Appearance = "light" | "dark" | "system";
21
26
  /**
22
27
  * A built-in brand, or the name of one declared in CSS
@@ -50,7 +55,8 @@ export interface ThemeProviderProps {
50
55
  /**
51
56
  * document writes the root element. container paints a wrapper and leaves
52
57
  * the document unchanged; menus, listboxes and dialogs opened inside it keep
53
- * its theme.
58
+ * its theme. Container scope also mounts an overlay host so Modal and
59
+ * SlideOver can use portal="contained" and stay inside the wrapper.
54
60
  */
55
61
  scope?: "document" | "container";
56
62
  /** On the container wrapper (container scope only). */
@@ -126,6 +132,8 @@ export function ThemeProvider({
126
132
  "data-mortar-appearance": resolvedAppearance,
127
133
  };
128
134
  const host = usePortalHost(scope === "container", attributes);
135
+ const [overlayHost, setOverlayHost] = useState<HTMLElement | null>(null);
136
+ const containedPortal = useMemo(() => ({ host: overlayHost }), [overlayHost]);
129
137
  useEffect(() => {
130
138
  if (scope !== "document") return;
131
139
  const element = document.documentElement;
@@ -182,7 +190,10 @@ export function ThemeProvider({
182
190
  className={className}
183
191
  >
184
192
  <ThemeScopeContext.Provider value={attributes}>
185
- <Portal.Group target={host}>{theme}</Portal.Group>
193
+ <ContainedPortalContext.Provider value={containedPortal}>
194
+ <Portal.Group target={host}>{theme}</Portal.Group>
195
+ <div ref={setOverlayHost} className="m-overlay-host" />
196
+ </ContainedPortalContext.Provider>
186
197
  </ThemeScopeContext.Provider>
187
198
  </div>
188
199
  );
package/src/index.ts CHANGED
@@ -5,6 +5,7 @@ export type {
5
5
  Appearance,
6
6
  Brand,
7
7
  Density,
8
+ OverlayPortal,
8
9
  } from "./foundation.js";
9
10
  export {
10
11
  Button,
package/src/internal.tsx CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  useContext,
8
8
  useEffect,
9
9
  useId,
10
+ useRef,
10
11
  useState,
11
12
  type HTMLAttributes,
12
13
  type RefObject,
@@ -14,6 +15,7 @@ import {
14
15
  cloneElement,
15
16
  isValidElement,
16
17
  } from "react";
18
+ import { createPortal } from "react-dom";
17
19
  import {
18
20
  CloseButton,
19
21
  Dialog,
@@ -373,19 +375,149 @@ export function FieldMessage({
373
375
  ) : null;
374
376
  }
375
377
 
378
+ /**
379
+ * Where an overlay portals. `document` (default) uses Headless UI's body
380
+ * portal. `contained` keeps the overlay inside the nearest container-scoped
381
+ * ThemeProvider's overlay host so an embedded widget does not cover the page.
382
+ */
383
+ export type OverlayPortal = "document" | "contained";
384
+
385
+ /**
386
+ * The overlay host of the nearest container-scoped ThemeProvider.
387
+ * Undefined outside one; `{ host: null }` while the host node is mounting.
388
+ * Default is undefined (like ThemeScopeContext) so document-portal dialogs do
389
+ * not depend on ThemeProvider in the catalogue.
390
+ */
391
+ export const ContainedPortalContext = createContext<
392
+ { host: HTMLElement | null } | undefined
393
+ >(undefined);
394
+
395
+ const FOCUSABLE =
396
+ 'a[href],button:not([disabled]),textarea:not([disabled]),input:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex="-1"])';
397
+
398
+ /**
399
+ * Dialog root portalled into a container ThemeProvider's overlay host.
400
+ * Bounds, backdrop and focus stay inside the widget; the host page outside it
401
+ * stays usable. Escape closes; Tab cycles within the dialog.
402
+ */
403
+ function ContainedDialogFrame({
404
+ open,
405
+ onClose,
406
+ component,
407
+ labelledBy,
408
+ children,
409
+ }: {
410
+ open: boolean;
411
+ onClose: () => void;
412
+ component?: string;
413
+ labelledBy?: string;
414
+ children: ReactNode;
415
+ }) {
416
+ const portal = useContext(ContainedPortalContext);
417
+ if (!portal)
418
+ throw new Error(
419
+ 'portal="contained" requires a ThemeProvider with scope="container".',
420
+ );
421
+ const dialogRef = useRef<HTMLDivElement>(null);
422
+ const onCloseRef = useRef(onClose);
423
+ onCloseRef.current = onClose;
424
+
425
+ useEffect(() => {
426
+ if (!open) return;
427
+ const root = dialogRef.current;
428
+ if (!root) return;
429
+ const previouslyFocused = document.activeElement as HTMLElement | null;
430
+ const focusables = () =>
431
+ [...root.querySelectorAll<HTMLElement>(FOCUSABLE)].filter(
432
+ (el) => el.offsetParent !== null || el === document.activeElement,
433
+ );
434
+ const initial = focusables()[0] ?? root;
435
+ initial.focus();
436
+
437
+ const onKeyDown = (event: KeyboardEvent) => {
438
+ if (event.key === "Escape") {
439
+ event.preventDefault();
440
+ event.stopPropagation();
441
+ onCloseRef.current();
442
+ return;
443
+ }
444
+ if (event.key !== "Tab") return;
445
+ const items = focusables();
446
+ if (items.length === 0) {
447
+ event.preventDefault();
448
+ root.focus();
449
+ return;
450
+ }
451
+ const first = items[0];
452
+ const last = items[items.length - 1];
453
+ if (event.shiftKey && document.activeElement === first) {
454
+ event.preventDefault();
455
+ last.focus();
456
+ } else if (!event.shiftKey && document.activeElement === last) {
457
+ event.preventDefault();
458
+ first.focus();
459
+ }
460
+ };
461
+ document.addEventListener("keydown", onKeyDown, true);
462
+ return () => {
463
+ document.removeEventListener("keydown", onKeyDown, true);
464
+ previouslyFocused?.focus?.();
465
+ };
466
+ }, [open]);
467
+
468
+ if (!open || !portal.host) return null;
469
+ return createPortal(
470
+ <div
471
+ ref={dialogRef}
472
+ role="dialog"
473
+ aria-modal="true"
474
+ aria-labelledby={labelledBy}
475
+ tabIndex={-1}
476
+ className="m-dialog"
477
+ data-portal="contained"
478
+ {...componentRoot(component ?? "", component !== undefined)}
479
+ >
480
+ <div
481
+ className="m-backdrop"
482
+ aria-hidden="true"
483
+ onClick={() => onCloseRef.current()}
484
+ />
485
+ {children}
486
+ </div>,
487
+ portal.host,
488
+ );
489
+ }
490
+
376
491
  /** Headless dialog root with the shared backdrop. */
377
492
  export function DialogFrame({
378
493
  open,
379
494
  onClose,
380
495
  component,
496
+ portal = "document",
497
+ labelledBy,
381
498
  children,
382
499
  }: {
383
500
  open: boolean;
384
501
  onClose: () => void;
385
502
  /** The catalogue component this dialog is the root of, if any. */
386
503
  component?: string;
504
+ /** document (default) portals to the body; contained stays in the widget host. */
505
+ portal?: OverlayPortal;
506
+ /** Accessible name for contained portals (document mode uses DialogTitle). */
507
+ labelledBy?: string;
387
508
  children: ReactNode;
388
509
  }) {
510
+ if (portal === "contained")
511
+ return (
512
+ <ContainedDialogFrame
513
+ open={open}
514
+ onClose={onClose}
515
+ component={component}
516
+ labelledBy={labelledBy}
517
+ >
518
+ {children}
519
+ </ContainedDialogFrame>
520
+ );
389
521
  return (
390
522
  <Dialog
391
523
  open={open}
@@ -640,8 +772,9 @@ export const ThemeScopeContext = createContext<
640
772
  >(undefined);
641
773
  /**
642
774
  * Re-applies a container-scoped theme to content rendered outside its wrapper
643
- * (dialogs portal to the document body). The wrapper is display: contents, so
644
- * it carries the tokens without adding a box.
775
+ * (document-portal dialogs land on the body). Contained portals render inside
776
+ * the wrapper and do not need this. The wrapper is display: contents, so it
777
+ * carries the tokens without adding a box.
645
778
  */
646
779
  export function ThemeScope({ children }: { children: ReactNode }) {
647
780
  const attributes = useContext(ThemeScopeContext);
package/src/overlays.css CHANGED
@@ -5,6 +5,29 @@
5
5
  one section, ordered base, then variants and states, then media and container
6
6
  queries, except where that would change which equal-specificity rule wins. */
7
7
  @layer components {
8
+ /* == Contained overlay host == */
9
+ /* ThemeProvider scope="container" mounts this for portal="contained". */
10
+ [data-m-component="ThemeProvider"] {
11
+ position: relative;
12
+ }
13
+ .m-overlay-host {
14
+ position: absolute;
15
+ inset: 0;
16
+ z-index: var(--m-z-overlay);
17
+ pointer-events: none;
18
+ }
19
+ .m-overlay-host > * {
20
+ pointer-events: auto;
21
+ }
22
+ .m-dialog[data-portal="contained"],
23
+ .m-dialog[data-portal="contained"] .m-backdrop,
24
+ .m-dialog[data-portal="contained"] .m-dialog-position {
25
+ position: absolute;
26
+ }
27
+ .m-dialog[data-portal="contained"] .m-slide-over {
28
+ position: absolute;
29
+ }
30
+
8
31
  /* == Modal == */
9
32
  .m-dialog {
10
33
  position: fixed;