// S72-T14 (R113, C3): a link in an answer opens one large centred pop-up that hosts the real // module. The pop-up never reads or writes `location.hash`, so the chat stays at `#/assistant`. // The host's mount point (AssistantPage.tsx) imports `styles/sdlc72/open-in-place.css`. import { Component, createContext, lazy, Suspense, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, } from "react"; import type { ComponentType, MouseEvent as ReactMouseEvent, ReactNode } from "react"; import { createPortal } from "react-dom"; import { NAV_MINIMIZE_EVENT } from "../apiContract"; import { OverlayProvider } from "../customer-grid/OverlaySurface"; import { ARTIFACTS_ROUTE, DATA_ROUTE, databaseEntries, QUERY_ROUTE, readDataAddress, routeKeyOf } from "../shell/nav"; import type { NavEntry } from "../shell/nav"; import { readSheetAddress } from "../sheet"; import { useEscapeClose } from "../ui/useEscapeClose"; import { ITEM_NOT_AVAILABLE } from "../ui/itemAvailability"; /** C3: the address a hosted module reads instead of the hash. */ export type EmbedAddress = { database?: string; view?: string; wb?: string; tab?: string }; type HostedNavigate = (address: { database: string; view?: string }) => void; /** C3: what `CustomerGrid` and `SheetPage` accept once lanes L and M land. */ export type EmbedModule = ComponentType<{ address?: EmbedAddress; embedded?: boolean; onNavigate?: HostedNavigate }>; export type QueryModule = ComponentType<{ granted: NavEntry[]; hostedRail?: boolean; selectedId?: string }>; /** S72-T16 (C7): one artifact record, shown by id. The host that mounts it injects it. */ export type ArtifactModule = ComponentType<{ id: string }>; /** One hostable address. A new kind adds a member here, a parser leg and a registry entry. */ export type InPlaceTarget = | { kind: "data"; database: string; view?: string } | { kind: "sheet"; wb: string; tab?: string } | { kind: "query"; id: string } | { kind: "artifact"; id: string }; /** The loader registry, injectable so a test mounts stubs. */ export interface InPlaceModules { data?: EmbedModule; sheet?: EmbedModule; query?: QueryModule; // No default: a host without it declines `#/artifacts?item=`, so the link navigates as before. artifact?: ArtifactModule; } export const NOT_AVAILABLE = ITEM_NOT_AVAILABLE; export const LOAD_FAILED = "This could not be opened. Close it and try again."; /** Map an in-app hash to a hostable target. Null keeps plain navigation. */ export function addressFromHash(hash: string): InPlaceTarget | null { const value = String(hash || "").trim(); if (!value.startsWith("#/")) return null; const route = routeKeyOf(value); if (route === DATA_ROUTE || route === "data") { const address = readDataAddress(value); return address.database ? { kind: "data", database: address.database, ...(address.view ? { view: address.view } : {}) } : null; } if (route === "sheet") { const address = readSheetAddress(value); return address?.wb ? { kind: "sheet", wb: address.wb, ...(address.tab ? { tab: address.tab } : {}) } : null; } if (route === QUERY_ROUTE || route === ARTIFACTS_ROUTE) { const params = new URLSearchParams(value.slice(2).split("#")[0].split("?")[1] ?? ""); const id = params.get("view"); if (id) return { kind: "query", id }; // C7: the in-app link of one artifact record. const item = route === ARTIFACTS_ROUTE ? params.get("item") : null; return item ? { kind: "artifact", id: item } : null; } return null; } export interface OpenInPlaceApi { /** Open the pop-up for an in-app hash. False when the hash is not hostable. */ open: (href: string) => boolean; } export const OpenInPlaceContext = createContext(null); /** The mounted host, or null. A null host keeps the link's plain hash navigation. */ export function useOpenInPlace(): OpenInPlaceApi | null { return useContext(OpenInPlaceContext); } type ClickLike = Pick; /** Handle a plain left click on an in-app link. True when the host opened it and the default stopped. */ export function interceptOpen(host: OpenInPlaceApi | null, href: string, event: ClickLike): boolean { if (!host || event.defaultPrevented || event.button !== 0) return false; if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return false; if (!addressFromHash(href)) return false; event.preventDefault(); return host.open(href); } // Only a `#/` target becomes a link. Any other scheme stays literal text. const ANSWER_LINK = /\[([^\]\n]+)\]\((#\/[^)\s]*)\)/g; /** Answer text with its `[label](#/...)` links as real links. */ export function LinkedText({ text }: { text: string }) { const host = useOpenInPlace(); const source = String(text ?? ""); const parts: ReactNode[] = []; let last = 0; for (const match of source.matchAll(ANSWER_LINK)) { const at = match.index ?? 0; if (at > last) parts.push(source.slice(last, at)); const href = match[2]; parts.push( { interceptOpen(host, href, event); }}>{match[1]}); last = at + match[0].length; } if (!parts.length) return <>{source}; if (last < source.length) parts.push(source.slice(last)); return <>{parts}; } type EmbedGrid = ComponentType<{ address?: EmbedAddress; embedded?: boolean }>; // tsc follows only literal specifiers. Vite expands each pattern (one file) at build. // ⛔ Not `import.meta.glob`: verify_alerts transpiles this file to CommonJS and allows only BASE_URL. const EXACT = ""; // The casts let this compile before and after lanes L and M add `address` to the modules. const DEFAULT_MODULES: Required> = { // The grid's menus need an overlay stack, as the shell's Data mount gives it. data: lazy(() => (import(`../customer-grid/CustomerGrid${EXACT}.tsx`) as Promise<{ default: unknown }>) .then((grid) => { const CustomerGrid = grid.default as EmbedGrid; return { default: (props: { address?: EmbedAddress; embedded?: boolean }) => }; })), sheet: lazy(() => (import(`../sheet/SheetPage${EXACT}.tsx`) as Promise<{ default: unknown }>) .then((page) => ({ default: page.default as EmbedModule }))), query: lazy(() => import(`../query/QueryPage${EXACT}.tsx`) as Promise<{ default: QueryModule }>), }; class InPlaceBoundary extends Component<{ children: ReactNode }, { failed: boolean }> { state = { failed: false }; static getDerivedStateFromError() { return { failed: true }; } render() { return this.state.failed ?

{LOAD_FAILED}

: this.props.children; } } function InPlaceLoading() { return
; } /** The pop-up's content: the hosted module, the loading state, or one plain sentence. */ export function InPlaceBody({ target, granted, modules, onNavigate }: { target: InPlaceTarget; granted: NavEntry[]; modules?: InPlaceModules; onNavigate?: HostedNavigate; }) { const registry = { ...DEFAULT_MODULES, ...modules }; let body: ReactNode; if (target.kind === "data") { const shared = databaseEntries(granted).some((entry) => entry.kind !== "group" && entry.key === target.database); if (!shared) return

{NOT_AVAILABLE}

; const CustomerGrid = registry.data; body = ; } else if (target.kind === "sheet") { const SheetPage = registry.sheet; body = ; } else if (target.kind === "artifact") { const ArtifactView = registry.artifact; if (!ArtifactView) return

{NOT_AVAILABLE}

; body = ; } else { // QueryPage says its own plain sentence for an id that is gone or not shared. const QueryPage = registry.query; body = ; } return }>{body}; } const TITLES: Record = { data: "Records", sheet: "Sheet", query: "Artifact", artifact: "Artifact" }; const navFoldHolds = new Set(); let restoreNavDispatch: (() => void) | null = null; /** Hold page-nav folding until the last hosted dialog unmounts. */ function holdPageNavFold(): () => void { const hold = {}; navFoldHolds.add(hold); if (navFoldHolds.size === 1) { const dispatch = window.dispatchEvent; // Direct window dispatch follows registration order, even for capture listeners. const intercept = function (this: Window, event: Event): boolean { if (event.type === NAV_MINIMIZE_EVENT && navFoldHolds.size) return !event.defaultPrevented; return dispatch.call(this, event); }; window.dispatchEvent = intercept; restoreNavDispatch = () => { if (window.dispatchEvent === intercept) window.dispatchEvent = dispatch; }; } return () => { if (!navFoldHolds.delete(hold) || navFoldHolds.size) return; restoreNavDispatch?.(); restoreNavDispatch = null; }; } /** The title names the database when the grant carries its label, in sentence case. */ export function inPlaceTitle(target: InPlaceTarget, granted: NavEntry[]): string { if (target.kind !== "data") return TITLES[target.kind]; const label = granted.find((entry) => entry.key === target.database)?.label; return label ? label.charAt(0).toUpperCase() + label.slice(1) : TITLES.data; } /** One large centred dialog over the chat. Esc, the close button or a click outside closes it. */ export function InPlaceDialog({ target, granted, modules, onClose, onNavigate }: { target: InPlaceTarget; granted: NavEntry[]; modules?: InPlaceModules; onClose: () => void; onNavigate?: HostedNavigate; }) { const panelRef = useRef(null); const pressedOutside = useRef(false); useEscapeClose(true, onClose, { container: () => panelRef.current }); useEffect(() => { panelRef.current?.focus({ preventScroll: true }); }, []); // Acquire before the hosted module's passive mount effects can dispatch a fold. useLayoutEffect(holdPageNavFold, []); const title = inPlaceTitle(target, granted); const dialog =
{ pressedOutside.current = event.target === event.currentTarget; }} onClick={(event) => { if (pressedOutside.current && event.target === event.currentTarget) onClose(); pressedOutside.current = false; }}>

{title}

; // Under SSR there is no body to portal into, so the dialog renders in place. return typeof document === "undefined" ? dialog : createPortal(dialog, document.body); } /** Provides `useOpenInPlace()` to the links below it and owns the one pop-up. */ export function OpenInPlaceHost({ granted, modules, children }: { granted: NavEntry[]; modules?: InPlaceModules; children?: ReactNode; }) { const [opened, setOpened] = useState<{ target: InPlaceTarget; serial: number } | null>(null); const opener = useRef(null); const serial = useRef(0); const open = useCallback((href: string) => { const target = addressFromHash(href); if (!target || (target.kind === "artifact" && !modules?.artifact)) return false; const active = typeof document === "undefined" ? null : document.activeElement; opener.current = active && "focus" in active ? active as HTMLElement : null; serial.current += 1; setOpened({ target, serial: serial.current }); return true; }, [modules?.artifact]); const close = useCallback(() => { setOpened(null); const back = opener.current; opener.current = null; back?.focus?.({ preventScroll: true }); }, []); const navigate = useCallback((address) => { setOpened((current) => current ? { ...current, target: { kind: "data", ...address } } : current); }, []); const api = useMemo(() => ({ open }), [open]); return {children} {opened ? : null} ; }