File size: 13,328 Bytes
1ad1eea
 
4bda856
1ad1eea
 
 
 
 
 
 
 
4ca2251
1ad1eea
 
 
2a0b8fb
1ad1eea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a0b8fb
1ad1eea
 
 
 
 
 
 
4ca2251
1ad1eea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// 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<OpenInPlaceApi | null>(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<ReactMouseEvent, "button" | "metaKey" | "ctrlKey" | "shiftKey" | "altKey"
  | "defaultPrevented" | "preventDefault">;

/** 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(<a key={`${at}-${href}`} className="as-inline-link" href={href}
      onClick={(event) => { interceptOpen(host, href, event); }}>{match[1]}</a>);
    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<Omit<InPlaceModules, "artifact">> = {
  // 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 }) =>
        <OverlayProvider><CustomerGrid {...props} /></OverlayProvider> };
    })),
  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 ? <p className="oip-sentence" role="status">{LOAD_FAILED}</p> : this.props.children;
  }
}

function InPlaceLoading() {
  return <div className="oip-loading"><span className="lp-spin lp-spin--lg" role="status" aria-label="Loading" /></div>;
}

/** 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 <p className="oip-sentence" role="status">{NOT_AVAILABLE}</p>;
    const CustomerGrid = registry.data;
    body = <CustomerGrid address={{ database: target.database, view: target.view }} embedded />;
  } else if (target.kind === "sheet") {
    const SheetPage = registry.sheet;
    body = <SheetPage address={{ wb: target.wb, tab: target.tab }} embedded onNavigate={onNavigate} />;
  } else if (target.kind === "artifact") {
    const ArtifactView = registry.artifact;
    if (!ArtifactView) return <p className="oip-sentence" role="status">{NOT_AVAILABLE}</p>;
    body = <ArtifactView id={target.id} />;
  } else {
    // QueryPage says its own plain sentence for an id that is gone or not shared.
    const QueryPage = registry.query;
    body = <QueryPage granted={granted} hostedRail selectedId={target.id} />;
  }
  return <InPlaceBoundary key={JSON.stringify(target)}><Suspense fallback={<InPlaceLoading />}>{body}</Suspense></InPlaceBoundary>;
}

const TITLES: Record<InPlaceTarget["kind"], string> = { data: "Records", sheet: "Sheet", query: "Artifact", artifact: "Artifact" };

const navFoldHolds = new Set<object>();
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<HTMLElement | null>(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 = <div className="oip-backdrop"
    onMouseDown={(event) => { pressedOutside.current = event.target === event.currentTarget; }}
    onClick={(event) => {
      if (pressedOutside.current && event.target === event.currentTarget) onClose();
      pressedOutside.current = false;
    }}>
    <section className="oip-dialog" ref={panelRef} role="dialog" aria-modal="true" aria-label={title} tabIndex={-1}>
      <header className="oip-head">
        <h2 className="oip-title">{title}</h2>
        <button type="button" className="oip-close" aria-label="Close" title="Close" onClick={onClose}>
          <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><path d="M4 4l8 8M12 4l-8 8" /></svg>
        </button>
      </header>
      <div className="oip-body"><InPlaceBody target={target} granted={granted} modules={modules} onNavigate={onNavigate} /></div>
    </section>
  </div>;
  // 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<HTMLElement | null>(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<HostedNavigate>((address) => {
    setOpened((current) => current ? { ...current, target: { kind: "data", ...address } } : current);
  }, []);
  const api = useMemo<OpenInPlaceApi>(() => ({ open }), [open]);
  return <OpenInPlaceContext.Provider value={api}>
    {children}
    {opened ? <InPlaceDialog key={opened.serial} target={opened.target} granted={granted}
      modules={modules} onClose={close} onNavigate={navigate} /> : null}
  </OpenInPlaceContext.Provider>;
}