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
4 changes: 3 additions & 1 deletion packages/react/src/command.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { SearchGlyph } from "./glyphs/search";
import { Button } from "./button";
import { CommandHints, CommandRowContent, commandRowShape, commandValue } from "./command-row";
import { Icon } from "./icon";
import { BAND_LEVEL, inLevel, MODAL_LEVEL, ModalDepth, useModalLayer, usePanelLevel } from "./layers";
import { BAND_LEVEL, inLevel, MODAL_LEVEL, ModalDepth, ModalHost, useModalLayer, usePanelLevel } from "./layers";
import { useModalOutside } from "./modal-outside";
import { isModKey } from "./platform";
import { Spinner } from "./spinner";
Expand Down Expand Up @@ -155,6 +155,7 @@ export function CommandMenuShell({ open, onOpenChange, groups, placeholder = "Se
const Panel = state.status === "ready" ? state.Panel : null;
return (
<ModalDepth.Provider value={layer.depth}>
<ModalHost.Provider value={popup}>
<BaseDialog.Root open={open} onOpenChange={onOpenChange} onOpenChangeComplete={closed}>
<BaseDialog.Portal>
<BaseDialog.Backdrop className="basalt-dialog-backdrop basalt-command-backdrop" style={{ zIndex: layer.backdrop }} />
Expand Down Expand Up @@ -203,6 +204,7 @@ export function CommandMenuShell({ open, onOpenChange, groups, placeholder = "Se
</BaseDialog.Popup>
</BaseDialog.Portal>
</BaseDialog.Root>
</ModalHost.Provider>
</ModalDepth.Provider>
);
}
Expand Down
6 changes: 4 additions & 2 deletions packages/react/src/diagram-figure.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as React from "react";

import { Kbd } from "./kbd";
import { useShortcutsVisible } from "./keyboard";
import { inLevel, usePanelLevel } from "./layers";
import { inLevel, ModalHost, usePanelLevel } from "./layers";
import {
applyTrace, buildModel, placeLabels, tapTrace, transcript, entranceDrawn, figureKey, figureList, figureTree, hasStops, hintEntries, keyTarget, measureFigure, settleEntrance, syncAttributes, toHtml,
} from "./diagram-core";
Expand Down Expand Up @@ -507,6 +507,8 @@ export function DiagramFigure({ spec, component, viewer, zoom = true, onLayout,
void fetchViewer().then((mod) => { setOpening(false); if (mod) setViewerOpen(true); });
};
const closeViewer = React.useCallback(() => setViewerOpen(false), []);
// The nearest Basalt modal's popup, when the figure is in one: the viewer is written into it (layers.ts, ModalHost).
const modalHost = React.useContext(ModalHost);
// An app's own actions: their module loads once script runs, only for a figure that has some; until it arrives, and if it cannot, none is drawn.
const hasActions = !viewer && Boolean(actions?.length);
const [actionsModule, setActionsModule] = React.useState<ActionsModule | null>(null);
Expand Down Expand Up @@ -639,7 +641,7 @@ export function DiagramFigure({ spec, component, viewer, zoom = true, onLayout,
{opening ? <span className="basalt-button-spinner" aria-hidden="true"><span className="basalt-spinner" data-variant="ring" style={{ width: 16, height: 16 }}><svg viewBox="0 0 16 16" width={16} height={16} fill="none" aria-hidden="true"><circle cx="8" cy="8" r="6.25" stroke="currentColor" strokeOpacity="0.25" strokeWidth="1.5" /><path d="M8 1.75A6.25 6.25 0 0 1 14.25 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" /></svg></span></span> : null}
</button>
{viewerOpen && viewerModule ? (
<viewerModule.DiagramViewer kit={kitOf()} actions={actions} Actions={Actions} spec={viewerSpec} component={component} source={source} summary={summary} opener={expandRef} onClose={closeViewer} />
<viewerModule.DiagramViewer kit={kitOf()} actions={actions} Actions={Actions} spec={viewerSpec} component={component} source={source} summary={summary} opener={expandRef} host={modalHost} onClose={closeViewer} />
) : null}
</>
) : null;
Expand Down
25 changes: 20 additions & 5 deletions packages/react/src/diagram-viewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ export interface DiagramViewerProps {
summary: React.ReactNode;
/** "Expand": focus returns to it when the viewer closes. */
opener: React.RefObject<HTMLButtonElement | null>;
/**
* The popup of the Basalt modal the figure sits in (layers.ts, ModalHost), or none on the page. Opened from a modal, the viewer is written into its popup:
* at the end of the body it would be outside the modal, where everything is inert, and every control in it dead.
*/
host?: React.RefObject<HTMLElement | null> | null;
onClose: () => void;
}

Expand All @@ -58,7 +63,7 @@ const EMPTY: ZoomState = { zoom: 1, level: 100, fit: 1, min: 1, max: 4, atMin: f
/** A length token's value in CSS pixels, read from a probe the stage holds. */
const probeWidth = (stage: HTMLElement | null, which: string) => stage?.querySelector<HTMLElement>(`.${P}-probe[data-probe="${which}"]`)?.offsetWidth ?? 0;

export function DiagramViewer({ kit, actions, Actions, spec, component, source, summary, opener, onClose }: DiagramViewerProps) {
export function DiagramViewer({ kit, actions, Actions, spec, component, source, summary, opener, host, onClose }: DiagramViewerProps) {
const { Figure: DiagramFigure, Kbd, buildModel, figureKey, figureList, hintEntries, toHtml, inLevel, measureFigure } = kit;
// The viewer's figure is still (9.7): no entrance, flow, mover or run, so no motion code is loaded for it.
const still = React.useMemo<DiagramSpec>(() => ({ ...spec, motion: "still" }), [spec]);
Expand Down Expand Up @@ -157,6 +162,8 @@ export function DiagramViewer({ kit, actions, Actions, spec, component, source,
const closing = React.useRef(false);
const onCloseRef = React.useRef(onClose);
onCloseRef.current = onClose;
// Where the dialog is written: the modal's popup, read once as the viewer opens (the modal is open, so it is there), else the body.
const [into] = React.useState<HTMLElement | null>(() => host?.current ?? null);
const close = React.useCallback(() => {
const d = dialogRef.current;
if (!d || closing.current) return;
Expand Down Expand Up @@ -200,11 +207,17 @@ export function DiagramViewer({ kit, actions, Actions, spec, component, source,
d.addEventListener("click", onClick);
d.addEventListener("click", onLink);
d.addEventListener("keydown", onKey);
return () => { clearTimeout(timer); d.removeEventListener("transitionend", onEntered); d.removeEventListener("close", onClose); d.removeEventListener("pointerdown", onDown); d.removeEventListener("click", onClick); d.removeEventListener("click", onLink); d.removeEventListener("keydown", onKey); if (d.open) d.close(); };
}, [opener, close]);
// In a modal, the viewer closes as the modal starts to close (Base UI marks its popup `data-closed`), so the two leave together, and the native modal
// is gone before the modal returns focus to its trigger (which the viewer would hold inert). Unmounted with it, the cleanup below closes it too.
const parent = into ? new MutationObserver(() => { if (into.hasAttribute("data-closed")) close(); }) : null;
if (into) parent?.observe(into, { attributes: true, attributeFilter: ["data-closed"] });
return () => { parent?.disconnect(); clearTimeout(timer); d.removeEventListener("transitionend", onEntered); d.removeEventListener("close", onClose); d.removeEventListener("pointerdown", onDown); d.removeEventListener("click", onClick); d.removeEventListener("click", onLink); d.removeEventListener("keydown", onKey); if (d.open) d.close(); };
}, [opener, close, into]);

return createPortal(
<dialog ref={dialogRef} className={`basalt-dialog ${P}-viewer`} data-form="" data-level={1} aria-labelledby={titleId} aria-describedby={descId}>
// In a modal, Esc closes the viewer alone (the browser's cancel): the key goes no further, so the modal's own dismissal, a React handler on its popup and
// a listener on the document, never sees it. On the page it travels as it always has.
<dialog ref={dialogRef} className={`basalt-dialog ${P}-viewer`} data-form="" data-level={1} aria-labelledby={titleId} aria-describedby={descId} onKeyDown={into ? stopEscape : undefined}>
{inLevel(1, <>
<header className="basalt-sheet-head">
<div className="basalt-sheet-head-text">
Expand Down Expand Up @@ -266,7 +279,9 @@ export function DiagramViewer({ kit, actions, Actions, spec, component, source,
</footer>
</>)}
</dialog>,
document.body,
into ?? document.body,
);
}

const stopEscape = (event: React.KeyboardEvent) => { if (event.key === "Escape") event.stopPropagation(); };

4 changes: 3 additions & 1 deletion packages/react/src/dialog.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Dialog as BaseDialog } from "@base-ui/react/dialog";
import * as React from "react";

import { inLevel, MODAL_LEVEL, ModalDepth, useModalLayer } from "./layers";
import { inLevel, MODAL_LEVEL, ModalDepth, ModalHost, useModalLayer } from "./layers";
import { useModalOutside } from "./modal-outside";
import type { FocusTarget, OpenChangeDetails, PartProps, PopupActions } from "./types";
import { withClass, withStyle } from "./utils";
Expand Down Expand Up @@ -182,10 +182,12 @@ export function DialogContent({ className, style, children, ref, size = "default
const first: FocusTarget | undefined = initialFocus ?? (form ? (type: string) => ((state?.opened ?? type) === "touch" ? title() : popup.current?.querySelector<HTMLElement>(FIRST_FIELD) ?? true) : size === "wide" ? title : undefined);
return (
<ModalDepth.Provider value={layer.depth}>
<ModalHost.Provider value={popup}>
<BaseDialog.Portal>
<BaseDialog.Backdrop className="basalt-dialog-backdrop" style={{ zIndex: layer.backdrop }} />
<BaseDialog.Popup {...props} ref={popupRef} data-level={MODAL_LEVEL} data-size={size === "default" ? undefined : size} data-form={form ? "" : undefined} data-held={top === null ? undefined : ""} initialFocus={first} style={withStyle(top === null ? { zIndex: layer.popup } : { zIndex: layer.popup, "--_dialog-top": `${top}px` } as React.CSSProperties, style)} className={withClass("basalt-dialog", className)}>{inLevel(MODAL_LEVEL, children)}</BaseDialog.Popup>
</BaseDialog.Portal>
</ModalHost.Provider>
</ModalDepth.Provider>
);
}
Expand Down
6 changes: 6 additions & 0 deletions packages/react/src/layers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ import { useScreenKeyboardLayout } from "./screen-keyboard";
// floating children; a nested modal then covers the entire preceding level.
export const ModalDepth = /* @__PURE__ */ React.createContext(0);

// The popup of the nearest Basalt modal (Dialog, AlertDialog, Sheet, CommandMenu), or null on the page. While a modal is open, what is outside its popup is
// inert (Base UI's marks, and useModalOutside's guard over anything added to the page later), so a native modal opened from inside one (the diagram viewer)
// is written into this popup rather than at the end of the body: inside, it stays operable, a press in it is not a press outside, and the focus trap holds it.
// A `showModal` dialog draws in the top layer wherever it sits. Context crosses portals, as the depth does.
export const ModalHost = /* @__PURE__ */ React.createContext<React.RefObject<HTMLElement | null> | null>(null);

export function useModalLayer() {
const parent = React.useContext(ModalDepth);
// A modal is fixed to the window: while an on-screen keyboard is up it is laid out on what is still seen.
Expand Down
6 changes: 5 additions & 1 deletion packages/react/src/overlays.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { IconButton } from "./button";
import { CloseGlyph } from "./glyphs/close";
import { Dialog, DialogActions, DialogClose, DialogContent, DialogDescription, DialogModal, DialogTitle, DialogTrigger } from "./dialog";
import type { DialogCloseProps, DialogContentProps, DialogProps, DialogTriggerProps } from "./dialog";
import { inLevel, MODAL_LEVEL, ModalDepth, useModalLayer } from "./layers";
import { inLevel, MODAL_LEVEL, ModalDepth, ModalHost, useModalLayer } from "./layers";
import { useModalOutside } from "./modal-outside";
import { useScrollStop } from "./scroll-stop";
import type { PartProps } from "./types";
Expand Down Expand Up @@ -44,10 +44,12 @@ export function AlertDialogContent({ className, initialFocus, ref, style, childr
const mergedRef = useModalOutside<HTMLDivElement>(keepRef);
return (
<ModalDepth.Provider value={layer.depth}>
<ModalHost.Provider value={popup}>
<BaseAlertDialog.Portal>
<BaseAlertDialog.Backdrop className="basalt-dialog-backdrop" style={{ zIndex: layer.backdrop }} />
<BaseAlertDialog.Popup {...props} data-level={MODAL_LEVEL} ref={mergedRef} style={withStyle({ zIndex: layer.popup }, style)} initialFocus={initialFocus ?? (() => popup.current?.querySelector<HTMLElement>("[data-basalt-cancel]") ?? true)} className={withClass("basalt-dialog", className)}>{inLevel(MODAL_LEVEL, children)}</BaseAlertDialog.Popup>
</BaseAlertDialog.Portal>
</ModalHost.Provider>
</ModalDepth.Provider>
);
}
Expand Down Expand Up @@ -91,10 +93,12 @@ export function SheetContent({ side = "right", className, style, children, ref,
}, [step]);
return (
<ModalDepth.Provider value={layer.depth}>
<ModalHost.Provider value={popup}>
<BaseDialog.Portal>
<BaseDialog.Backdrop data-side={side} className="basalt-dialog-backdrop basalt-sheet-backdrop" style={{ zIndex: layer.backdrop }} />
<BaseDialog.Popup {...props} ref={popupRef} data-side={side} data-level={MODAL_LEVEL} style={withStyle({ zIndex: layer.popup }, style)} className={withClass("basalt-sheet", className)}>{inLevel(MODAL_LEVEL, children)}</BaseDialog.Popup>
</BaseDialog.Portal>
</ModalHost.Provider>
</ModalDepth.Provider>
);
}
Expand Down
Loading
Loading