@proteos/component-sdk 0.41.1 → 0.42.1
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.
- package/dist/{chunk-DD7AKVFC.js → chunk-2EAOQNQB.js} +4 -3
- package/dist/chunk-2EAOQNQB.js.map +1 -0
- package/dist/{chunk-GL7ZEEP4.cjs → chunk-P4MKRWPA.cjs} +4 -2
- package/dist/chunk-P4MKRWPA.cjs.map +1 -0
- package/dist/index.cjs +86 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +70 -2
- package/dist/index.d.ts +70 -2
- package/dist/index.js +77 -5
- package/dist/index.js.map +1 -1
- package/dist/protocol.cjs +8 -4
- package/dist/protocol.d.cts +100 -3
- package/dist/protocol.d.ts +100 -3
- package/dist/protocol.js +1 -1
- package/package.json +2 -2
- package/src/context.tsx +98 -1
- package/src/hooks.test.tsx +85 -2
- package/src/hooks.ts +78 -1
- package/src/index.ts +20 -2
- package/src/protocol.ts +115 -1
- package/dist/chunk-DD7AKVFC.js.map +0 -1
- package/dist/chunk-GL7ZEEP4.cjs.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context.tsx","../src/hooks.ts"],"names":[],"mappings":";;;;;AAmFO,IAAM,cAAA,GAAiB,cAA0C,IAAI,CAAA;AAI5E,SAAS,aAAa,EAAA,EAAkB;AACtC,EAAA,MAAM,WAAsC,EAAE,MAAA,EAAQ,cAAA,EAAgB,IAAA,EAAM,YAAY,EAAA,EAAG;AAC3F,EAAA,MAAA,CAAO,MAAA,EAAQ,WAAA,CAAY,QAAA,EAAU,GAAG,CAAA;AAC1C;AAIA,SAAS,aAAa,EAAA,EAAkB;AACtC,EAAA,MAAM,WAAsC,EAAE,MAAA,EAAQ,cAAA,EAAgB,IAAA,EAAM,aAAa,EAAA,EAAG;AAC5F,EAAA,MAAA,CAAO,MAAA,EAAQ,WAAA,CAAY,QAAA,EAAU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I,SAAA,EAAW,SAAS,CAAC,CAAA;AAAA,MAC1C,CAAA,CAAA,MAAQ;AACN,QAAA,SAAA,CAAU,IAAI,CAAA;AAAA,MAChB;AAAA,IACF;AACA,IAAA,OAAA,EAAQ;AACR,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,MAAA,CAAO,gBAAA,CAAiB,QAAA,EAAU,OAAO,CAAA;AAChD,MAAA,OAAO,MAAM,MAAA,CAAO,MAAA,CAAO,mBAAA,CAAoB,UAAU,OAAO,CAAA;AAAA,IAClE,CAAA,CAAA,MAAQ;AACN,MAAA;AAAA,IACF;AAAA,EACF,CAAA,EAAG,CAAC,YAAA,EAAc,SAAS,CAAC,CAAA;AAE5B,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["import type {\n AccountClient,\n AgentClient,\n ConversationClient,\n DataClient,\n FunctionsClient,\n KnowledgeClient,\n MetaClient,\n StorageClient,\n} from '@proteos/sdk'\nimport { createContext, type ReactNode, useMemo } from 'react'\n\nimport {\n type Envelope,\n MESSAGE_SOURCE,\n type NavigateMessage,\n type OpenPeekMessage,\n type PageContext,\n} from './protocol'\n\n/** Options for {@link RuntimeContextValue.navigate}. */\nexport interface NavigateOptions {\n /** Open the target in a peek (slide-over) panel instead of full-page. */\n peek?: boolean\n}\n\n/**\n * The authenticated `@proteos/sdk` clients the runtime injects. Same instances\n * the host app uses — pre-wired with a refreshing bearer token, so a component\n * never touches auth headers.\n */\nexport interface ComponentSdk {\n account: AccountClient\n agents: AgentClient\n /**\n * Conversations, messages, contacts, connections (conversation-service) —\n * e.g. the DraftMessageComposer review surface. Plural per the platform's\n * resource-naming rule; the web app's own `useSdk().conversation` predates\n * it (documented asymmetry).\n */\n conversations: ConversationClient\n data: DataClient\n functions: FunctionsClient\n knowledge: KnowledgeClient\n meta: MetaClient\n storage: StorageClient\n}\n\n/**\n * The raw runtime payload the shell hands a component at INIT. The shell builds\n * this; component authors read it through the hooks.\n */\nexport interface RuntimeValue {\n /**\n * The injected sdk clients. On an authenticated page these are the full,\n * bearer-wired clients. On a PUBLIC page (`isPublic: true`) only\n * `functions.actions.invokePublic` reaches the platform — every other\n * client throws on use (there is no token, and the server rejects\n * unauthenticated calls anyway).\n */\n sdk: ComponentSdk\n /** Liquid-resolved props (a snapshot — not a live binding). */\n props: Record<string, unknown>\n /** Page context snapshot: the host record, entity, and URL params. */\n pageCtx: PageContext\n /** API origin SDK calls + asset URLs resolve against. */\n apiBaseUrl: string\n /** Current bearer token getter (escape hatch for raw fetches). Returns ''\n * on public pages. */\n getToken: () => string\n /** True when rendering on an unauthenticated public page. */\n isPublic?: boolean\n /** Org id, set in public mode (public API routes carry it in the path). */\n orgId?: string\n}\n\n/** Runtime value plus the derived helpers the hooks expose. */\nexport interface RuntimeContextValue extends RuntimeValue {\n /** Navigate the host SPA to an in-app path (posts a NAVIGATE message), or\n * open it in a peek panel with `{ peek: true }` (posts OPEN_PEEK). */\n navigate: (to: string, options?: NavigateOptions) => void\n}\n\nexport const RuntimeContext = createContext<RuntimeContextValue | null>(null)\n\n/** Post a NAVIGATE envelope to the host. The host only honours relative,\n * in-app targets (it ignores absolute/external URLs). */\nfunction postNavigate(to: string): void {\n const envelope: Envelope<NavigateMessage> = { source: MESSAGE_SOURCE, type: 'NAVIGATE', to }\n window.parent?.postMessage(envelope, '*')\n}\n\n/** Post an OPEN_PEEK envelope to the host — open the in-app path in a peek\n * panel. Same relative-path contract as {@link postNavigate}. */\nfunction postOpenPeek(to: string): void {\n const envelope: Envelope<OpenPeekMessage> = { source: MESSAGE_SOURCE, type: 'OPEN_PEEK', to }\n window.parent?.postMessage(envelope, '*')\n}\n\n/** Navigate full-page (default) or into a peek panel (`{ peek: true }`). */\nfunction navigate(to: string, options?: NavigateOptions): void {\n if (options?.peek) postOpenPeek(to)\n else postNavigate(to)\n}\n\n/**\n * Provides the runtime value + derived helpers to a component subtree. Mounted\n * by the component-runtime shell around the loaded component — authors never\n * render this themselves. Lives in `@proteos/component-sdk` (a shared,\n * import-mapped singleton) so the context the shell provides is the very same\n * context the component's hooks read, across the bundle boundary.\n */\nexport function RuntimeProvider({ value, children }: { value: RuntimeValue; children: ReactNode }) {\n // The shell builds `value` once at INIT (a stable state object — clients,\n // props and pageCtx are all set once), so memoizing on its identity recreates\n // the context only when the runtime genuinely re-inits.\n const ctx = useMemo<RuntimeContextValue>(() => ({ ...value, navigate }), [value])\n return <RuntimeContext.Provider value={ctx}>{children}</RuntimeContext.Provider>\n}\n","import { useContext, useEffect, useState } from 'react'\n\nimport {\n type ComponentSdk,\n type NavigateOptions,\n RuntimeContext,\n type RuntimeContextValue,\n} from './context'\nimport type { PageContext } from './protocol'\n\n/**\n * Low-level escape hatch: the whole runtime context (sdk, props, pageCtx,\n * apiBaseUrl, getToken, navigate). Prefer the focused hooks below. Throws a\n * clear error if used outside the component runtime.\n */\nexport function useRuntime(): RuntimeContextValue {\n const ctx = useContext(RuntimeContext)\n if (!ctx) {\n throw new Error(\n '@proteos/component-sdk: hooks must run inside the Proteos component runtime. ' +\n 'This usually means the component is rendered outside its iframe, or a ' +\n 'second copy of @proteos/component-sdk was bundled instead of using the ' +\n 'runtime-provided one (keep it external).',\n )\n }\n return ctx\n}\n\n/** The authenticated SDK clients (account / agents / conversations / data / functions / knowledge / meta / storage). */\nexport function useSdk(): ComponentSdk {\n return useRuntime().sdk\n}\n\n/** The component's Liquid-resolved props (a snapshot, not a live binding). */\nexport function useProps<T extends Record<string, unknown> = Record<string, unknown>>(): T {\n return useRuntime().props as T\n}\n\n/**\n * The full page context: host `record`, `entity`, and URL `params`. The\n * `record` is a snapshot taken at mount (`undefined` on record-less platform\n * pages) — fetch via `useSdk().data` for anything that must stay fresh.\n */\nexport function usePageContext(): PageContext {\n return useRuntime().pageCtx\n}\n\n/**\n * Navigate the host SPA to an in-app path, e.g.\n * `navigate('/org/acme/record/task/123')`. The host ignores absolute/external\n * URLs. Build org/app-prefixed paths with `useHostLocation().appBasePath`.\n *\n * Pass `{ peek: true }` to open the path in a peek (slide-over) panel instead\n * of full-page navigation — e.g. `navigate(path, { peek: true })`. The host\n * peeks what it can (today: platform pages) and falls back to full navigation.\n */\nexport function useNavigate(): (to: string, options?: NavigateOptions) => void {\n return useRuntime().navigate\n}\n\n/** The API origin SDK calls resolve against (for building raw asset URLs). */\nexport function useApiBaseUrl(): string {\n return useRuntime().apiBaseUrl\n}\n\n/**\n * A getter for the current bearer token. Returns a function (not the token)\n * because the token is refreshed in place — read it at call time for a raw\n * `fetch`. Most components never need this; prefer `useSdk()`.\n */\nexport function useAuthToken(): () => string {\n return useRuntime().getToken\n}\n\nexport interface HostLocation {\n /** The host tab's pathname (same-origin read), or null if unavailable. */\n pathname: string | null\n /** The org id parsed from `/org/<orgId>/…`, or null. */\n orgId: string | null\n /** The `/org/<orgId>/app/<appId>` prefix, or null when not on an app page. */\n appBasePath: string | null\n}\n\nfunction readHostLocation(): HostLocation {\n const empty: HostLocation = { pathname: null, orgId: null, appBasePath: null }\n try {\n const parentWindow = window.parent\n if (!parentWindow || parentWindow === window) return empty\n const pathname = parentWindow.location.pathname\n const appMatch = pathname.match(/^\\/org\\/[^/]+\\/app\\/[^/]+/)\n const orgMatch = pathname.match(/^\\/org\\/([^/]+)\\//)\n return {\n pathname,\n orgId: orgMatch ? (orgMatch[1] ?? null) : null,\n appBasePath: appMatch ? appMatch[0] : null,\n }\n } catch {\n // Cross-origin (untrusted-component future) or detached — fall back to null.\n return empty\n }\n}\n\n/**\n * Read the host tab's location (same-origin) — the org id and `/org/.../app/...`\n * prefix needed to build navigation targets on platform pages. Read once on\n * mount (the iframe re-inits when the host route changes).\n */\nexport function useHostLocation(): HostLocation {\n const [loc] = useState(readHostLocation)\n return loc\n}\n\nexport interface FillViewportOptions {\n /** Gap left below the component (px). Default 24. */\n bottomMargin?: number\n /** Floor for the computed height (px). Default 320. */\n minHeight?: number\n}\n\n/**\n * Compute a \"fill the rest of the viewport\" height for full-bleed layouts\n * (boards, canvases). The runtime auto-sizes the iframe to its content, so a\n * component can't use its own `vh` units (circular). The iframe is same-origin,\n * so this measures the parent viewport minus the iframe's offset instead.\n * Returns `null` when it can't measure (fall back to natural height).\n */\nexport function useFillViewportHeight(options: FillViewportOptions = {}): number | null {\n const { bottomMargin = 24, minHeight = 320 } = options\n const [height, setHeight] = useState<number | null>(null)\n\n useEffect(() => {\n function compute(): void {\n try {\n const frame = window.frameElement\n const parentWindow = window.parent\n if (!frame || !parentWindow || parentWindow === window) return\n const available =\n parentWindow.innerHeight - frame.getBoundingClientRect().top - bottomMargin\n setHeight(Math.max(available, minHeight))\n } catch {\n setHeight(null) // cross-origin or detached — fall back to natural height\n }\n }\n compute()\n try {\n window.parent.addEventListener('resize', compute)\n return () => window.parent.removeEventListener('resize', compute)\n } catch {\n return\n }\n }, [bottomMargin, minHeight])\n\n return height\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/context.tsx","../src/hooks.ts"],"names":["useMemo"],"mappings":";;;;;AAuHO,IAAM,cAAA,GAAiB,cAA0C,IAAI,CAAA;AAI5E,SAAS,aAAa,EAAA,EAAkB;AACtC,EAAA,MAAM,WAAsC,EAAE,MAAA,EAAQ,cAAA,EAAgB,IAAA,EAAM,YAAY,EAAA,EAAG;AAC3F,EAAA,MAAA,CAAO,MAAA,EAAQ,WAAA,CAAY,QAAA,EAAU,GAAG,CAAA;AAC1C;AAIA,SAAS,aAAa,EAAA,EAAkB;AACtC,EAAA,MAAM,WAAsC,EAAE,MAAA,EAAQ,cAAA,EAAgB,IAAA,EAAM,aAAa,EAAA,EAAG;AAC5F,EAAA,MAAA,CAAO,MAAA,EAAQ,WAAA,CAAY,QAAA,EAAU,GAAG,CAAA;AAC1C;AAGA,SAAS,QAAA,CAAS,IAAY,OAAA,EAAiC;AAC7D,EAAA,IAAI,OAAA,EAAS,IAAA,EAAM,YAAA,CAAa,EAAE,CAAA;AAAA,oBAChB,EAAE,CAAA;AACtB;AAMA,IAAM,aAAA,uBAAoB,GAAA,EAAuC;AACjE,IAAI,qBAAA,GA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K,GAAA,CAAI,SAAA,EAAW,SAAS,CAAC,CAAA;AAAA,MAC1C,CAAA,CAAA,MAAQ;AACN,QAAA,SAAA,CAAU,IAAI,CAAA;AAAA,MAChB;AAAA,IACF;AACA,IAAA,OAAA,EAAQ;AACR,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,MAAA,CAAO,gBAAA,CAAiB,QAAA,EAAU,OAAO,CAAA;AAChD,MAAA,OAAO,MAAM,MAAA,CAAO,MAAA,CAAO,mBAAA,CAAoB,UAAU,OAAO,CAAA;AAAA,IAClE,CAAA,CAAA,MAAQ;AACN,MAAA;AAAA,IACF;AAAA,EACF,CAAA,EAAG,CAAC,YAAA,EAAc,SAAS,CAAC,CAAA;AAE5B,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["import type {\n AccountClient,\n AgentClient,\n ConversationClient,\n DataClient,\n FunctionsClient,\n KnowledgeClient,\n MetaClient,\n StorageClient,\n} from '@proteos/sdk'\nimport { createContext, type ReactNode, useMemo } from 'react'\n\nimport {\n type Envelope,\n isHostMessage,\n MESSAGE_SOURCE,\n type ModalResultMessage,\n type NavigateMessage,\n type OpenModalMessage,\n type OpenPeekMessage,\n type PageContext,\n} from './protocol'\n\n/** Options for {@link RuntimeContextValue.navigate}. */\nexport interface NavigateOptions {\n /** Open the target in a peek (slide-over) panel instead of full-page. */\n peek?: boolean\n}\n\n/** Options for {@link RuntimeContextValue.openModal}. */\nexport interface OpenModalOptions {\n /** Heading rendered in the modal chrome. */\n title?: string\n}\n\n/**\n * Manual control over iframe overlay promotion. The runtime already detects\n * overlays automatically (anything portaled to the iframe's `document.body` —\n * every `@proteos/ui` overlay qualifies), so components need this only for\n * custom portal targets, or to promote a frame *before* opening an overlay.\n * Calls are reference-counted: every `expand()` needs its `collapse()`.\n */\nexport interface OverlayController {\n expand: () => void\n collapse: () => void\n isExpanded: () => boolean\n}\n\n/**\n * The authenticated `@proteos/sdk` clients the runtime injects. Same instances\n * the host app uses — pre-wired with a refreshing bearer token, so a component\n * never touches auth headers.\n */\nexport interface ComponentSdk {\n account: AccountClient\n agents: AgentClient\n /**\n * Conversations, messages, contacts, connections (conversation-service) —\n * e.g. the DraftMessageComposer review surface. Plural per the platform's\n * resource-naming rule; the web app's own `useSdk().conversation` predates\n * it (documented asymmetry).\n */\n conversations: ConversationClient\n data: DataClient\n functions: FunctionsClient\n knowledge: KnowledgeClient\n meta: MetaClient\n storage: StorageClient\n}\n\n/**\n * The raw runtime payload the shell hands a component at INIT. The shell builds\n * this; component authors read it through the hooks.\n */\nexport interface RuntimeValue {\n /**\n * The injected sdk clients. On an authenticated page these are the full,\n * bearer-wired clients. On a PUBLIC page (`isPublic: true`) only\n * `functions.actions.invokePublic` reaches the platform — every other\n * client throws on use (there is no token, and the server rejects\n * unauthenticated calls anyway).\n */\n sdk: ComponentSdk\n /** Liquid-resolved props (a snapshot — not a live binding). */\n props: Record<string, unknown>\n /** Page context snapshot: the host record, entity, and URL params. */\n pageCtx: PageContext\n /** API origin SDK calls + asset URLs resolve against. */\n apiBaseUrl: string\n /** Current bearer token getter (escape hatch for raw fetches). Returns ''\n * on public pages. */\n getToken: () => string\n /** True when rendering on an unauthenticated public page. */\n isPublic?: boolean\n /** Org id, set in public mode (public API routes carry it in the path). */\n orgId?: string\n /** Set when this component is the content of a host component modal — the\n * correlation id it closes with. See `useModalHost()`. */\n modalRequestId?: string\n /** Overlay promotion controller, provided by the shell. Absent on older\n * shells / non-promoting hosts, in which case `useOverlayExpansion()`\n * no-ops. */\n overlay?: OverlayController\n}\n\n/** Runtime value plus the derived helpers the hooks expose. */\nexport interface RuntimeContextValue extends RuntimeValue {\n /** Navigate the host SPA to an in-app path (posts a NAVIGATE message), or\n * open it in a peek panel with `{ peek: true }` (posts OPEN_PEEK). */\n navigate: (to: string, options?: NavigateOptions) => void\n /** Open another component in a host-rendered modal; resolves with the value\n * that component closed with (`undefined` if dismissed). */\n openModal: (\n componentSlug: string,\n props?: Record<string, unknown>,\n options?: OpenModalOptions,\n ) => Promise<unknown>\n}\n\nexport const RuntimeContext = createContext<RuntimeContextValue | null>(null)\n\n/** Post a NAVIGATE envelope to the host. The host only honours relative,\n * in-app targets (it ignores absolute/external URLs). */\nfunction postNavigate(to: string): void {\n const envelope: Envelope<NavigateMessage> = { source: MESSAGE_SOURCE, type: 'NAVIGATE', to }\n window.parent?.postMessage(envelope, '*')\n}\n\n/** Post an OPEN_PEEK envelope to the host — open the in-app path in a peek\n * panel. Same relative-path contract as {@link postNavigate}. */\nfunction postOpenPeek(to: string): void {\n const envelope: Envelope<OpenPeekMessage> = { source: MESSAGE_SOURCE, type: 'OPEN_PEEK', to }\n window.parent?.postMessage(envelope, '*')\n}\n\n/** Navigate full-page (default) or into a peek panel (`{ peek: true }`). */\nfunction navigate(to: string, options?: NavigateOptions): void {\n if (options?.peek) postOpenPeek(to)\n else postNavigate(to)\n}\n\n// ── Component modals ────────────────────────────────────────────────────────\n// One module-level listener + a pending map, rather than a listener per call:\n// the SDK is an import-mapped singleton, so this is per-iframe state.\n\nconst pendingModals = new Map<string, (result: unknown) => void>()\nlet modalListenerAttached = false\n\nfunction ensureModalListener(): void {\n if (modalListenerAttached) return\n modalListenerAttached = true\n window.addEventListener('message', (event: MessageEvent) => {\n const data: unknown = event.data\n if (!isHostMessage(data) || data.type !== 'MODAL_CLOSED') return\n const resolve = pendingModals.get(data.requestId)\n // An unknown requestId is someone else's modal (or a stale reply) — drop it.\n if (!resolve) return\n pendingModals.delete(data.requestId)\n resolve(data.result)\n })\n}\n\nfunction newRequestId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID()\n }\n return `modal_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`\n}\n\n/** Post OPEN_MODAL and resolve when the host answers MODAL_CLOSED. */\nfunction openModal(\n componentSlug: string,\n props?: Record<string, unknown>,\n options?: OpenModalOptions,\n): Promise<unknown> {\n ensureModalListener()\n const requestId = newRequestId()\n const envelope: Envelope<OpenModalMessage> = {\n source: MESSAGE_SOURCE,\n type: 'OPEN_MODAL',\n requestId,\n componentSlug,\n ...(props !== undefined ? { props } : {}),\n ...(options?.title !== undefined ? { title: options.title } : {}),\n }\n return new Promise<unknown>((resolve) => {\n pendingModals.set(requestId, resolve)\n window.parent?.postMessage(envelope, '*')\n })\n}\n\n/** Post MODAL_RESULT — the component inside a host modal closing with a value. */\nexport function postModalResult(requestId: string, result?: unknown): void {\n const envelope: Envelope<ModalResultMessage> = {\n source: MESSAGE_SOURCE,\n type: 'MODAL_RESULT',\n requestId,\n ...(result !== undefined ? { result } : {}),\n }\n window.parent?.postMessage(envelope, '*')\n}\n\n/**\n * Provides the runtime value + derived helpers to a component subtree. Mounted\n * by the component-runtime shell around the loaded component — authors never\n * render this themselves. Lives in `@proteos/component-sdk` (a shared,\n * import-mapped singleton) so the context the shell provides is the very same\n * context the component's hooks read, across the bundle boundary.\n */\nexport function RuntimeProvider({ value, children }: { value: RuntimeValue; children: ReactNode }) {\n // The shell builds `value` once at INIT (a stable state object — clients,\n // props and pageCtx are all set once), so memoizing on its identity recreates\n // the context only when the runtime genuinely re-inits.\n const ctx = useMemo<RuntimeContextValue>(() => ({ ...value, navigate, openModal }), [value])\n return <RuntimeContext.Provider value={ctx}>{children}</RuntimeContext.Provider>\n}\n","import { useCallback, useContext, useEffect, useMemo, useState } from 'react'\n\nimport {\n type ComponentSdk,\n type NavigateOptions,\n type OpenModalOptions,\n type OverlayController,\n postModalResult,\n RuntimeContext,\n type RuntimeContextValue,\n} from './context'\nimport type { PageContext } from './protocol'\n\n/**\n * Low-level escape hatch: the whole runtime context (sdk, props, pageCtx,\n * apiBaseUrl, getToken, navigate). Prefer the focused hooks below. Throws a\n * clear error if used outside the component runtime.\n */\nexport function useRuntime(): RuntimeContextValue {\n const ctx = useContext(RuntimeContext)\n if (!ctx) {\n throw new Error(\n '@proteos/component-sdk: hooks must run inside the Proteos component runtime. ' +\n 'This usually means the component is rendered outside its iframe, or a ' +\n 'second copy of @proteos/component-sdk was bundled instead of using the ' +\n 'runtime-provided one (keep it external).',\n )\n }\n return ctx\n}\n\n/** The authenticated SDK clients (account / agents / conversations / data / functions / knowledge / meta / storage). */\nexport function useSdk(): ComponentSdk {\n return useRuntime().sdk\n}\n\n/** The component's Liquid-resolved props (a snapshot, not a live binding). */\nexport function useProps<T extends Record<string, unknown> = Record<string, unknown>>(): T {\n return useRuntime().props as T\n}\n\n/**\n * The full page context: host `record`, `entity`, and URL `params`. The\n * `record` is a snapshot taken at mount (`undefined` on record-less platform\n * pages) — fetch via `useSdk().data` for anything that must stay fresh.\n */\nexport function usePageContext(): PageContext {\n return useRuntime().pageCtx\n}\n\n/**\n * Navigate the host SPA to an in-app path, e.g.\n * `navigate('/org/acme/record/task/123')`. The host ignores absolute/external\n * URLs. Build org/app-prefixed paths with `useHostLocation().appBasePath`.\n *\n * Pass `{ peek: true }` to open the path in a peek (slide-over) panel instead\n * of full-page navigation — e.g. `navigate(path, { peek: true })`. The host\n * peeks what it can (today: platform pages) and falls back to full navigation.\n */\nexport function useNavigate(): (to: string, options?: NavigateOptions) => void {\n return useRuntime().navigate\n}\n\n/** The API origin SDK calls resolve against (for building raw asset URLs). */\nexport function useApiBaseUrl(): string {\n return useRuntime().apiBaseUrl\n}\n\nconst NOOP_OVERLAY: OverlayController = {\n expand: () => {\n console.warn(\n '@proteos/component-sdk: useOverlayExpansion() has no effect — this runtime ' +\n 'does not support overlay promotion (older shell or non-promoting host).',\n )\n },\n collapse: () => {},\n isExpanded: () => false,\n}\n\n/**\n * Manual overlay promotion — lifts the whole component iframe over the rest of\n * the page so an overlay can escape the frame's box.\n *\n * You rarely need this. Every `@proteos/ui` overlay (Modal, Popover, Menu,\n * Select, Tooltip, …) portals to the iframe document's `<body>`, which the\n * runtime watches — those promote automatically, with no code. Reach for this\n * hook only when you portal somewhere else yourself, or want the frame lifted\n * *before* the overlay mounts. Reference-counted: pair every `expand()` with a\n * `collapse()`.\n */\nexport function useOverlayExpansion(): OverlayController {\n return useRuntime().overlay ?? NOOP_OVERLAY\n}\n\n/**\n * Open ANOTHER component in a modal the host renders above everything — the\n * cross-component flow (a picker, a wizard step, a confirm dialog shared by\n * several components). Resolves with whatever that component closed with, or\n * `undefined` if the user dismissed it.\n *\n * ```ts\n * const openModal = useComponentModal()\n * const picked = await openModal('contact-picker', { entity: 'contact' }, { title: 'Pick a contact' })\n * ```\n *\n * For an overlay that is part of THIS component, just render a `<Modal>` from\n * `@proteos/ui` — it promotes automatically.\n */\nexport function useComponentModal(): (\n componentSlug: string,\n props?: Record<string, unknown>,\n options?: OpenModalOptions,\n) => Promise<unknown> {\n return useRuntime().openModal\n}\n\nexport interface ModalHost {\n /** True when this component is rendered as the content of a host modal. */\n isInModal: boolean\n /** Close the host modal, resolving the opener's promise with `result`.\n * No-op outside a modal. */\n close: (result?: unknown) => void\n}\n\n/**\n * For a component that is being shown INSIDE a host modal (opened by another\n * component's `useComponentModal()`): close it and hand a value back.\n * `isInModal` is false on ordinary page-hosted mounts, so one component can\n * serve both roles.\n */\nexport function useModalHost(): ModalHost {\n const requestId = useRuntime().modalRequestId\n const close = useCallback(\n (result?: unknown) => {\n if (requestId === undefined) return\n postModalResult(requestId, result)\n },\n [requestId],\n )\n return useMemo(() => ({ isInModal: requestId !== undefined, close }), [requestId, close])\n}\n\n/**\n * A getter for the current bearer token. Returns a function (not the token)\n * because the token is refreshed in place — read it at call time for a raw\n * `fetch`. Most components never need this; prefer `useSdk()`.\n */\nexport function useAuthToken(): () => string {\n return useRuntime().getToken\n}\n\nexport interface HostLocation {\n /** The host tab's pathname (same-origin read), or null if unavailable. */\n pathname: string | null\n /** The org id parsed from `/org/<orgId>/…`, or null. */\n orgId: string | null\n /** The `/org/<orgId>/app/<appId>` prefix, or null when not on an app page. */\n appBasePath: string | null\n}\n\nfunction readHostLocation(): HostLocation {\n const empty: HostLocation = { pathname: null, orgId: null, appBasePath: null }\n try {\n const parentWindow = window.parent\n if (!parentWindow || parentWindow === window) return empty\n const pathname = parentWindow.location.pathname\n const appMatch = pathname.match(/^\\/org\\/[^/]+\\/app\\/[^/]+/)\n const orgMatch = pathname.match(/^\\/org\\/([^/]+)\\//)\n return {\n pathname,\n orgId: orgMatch ? (orgMatch[1] ?? null) : null,\n appBasePath: appMatch ? appMatch[0] : null,\n }\n } catch {\n // Cross-origin (untrusted-component future) or detached — fall back to null.\n return empty\n }\n}\n\n/**\n * Read the host tab's location (same-origin) — the org id and `/org/.../app/...`\n * prefix needed to build navigation targets on platform pages. Read once on\n * mount (the iframe re-inits when the host route changes).\n */\nexport function useHostLocation(): HostLocation {\n const [loc] = useState(readHostLocation)\n return loc\n}\n\nexport interface FillViewportOptions {\n /** Gap left below the component (px). Default 24. */\n bottomMargin?: number\n /** Floor for the computed height (px). Default 320. */\n minHeight?: number\n}\n\n/**\n * Compute a \"fill the rest of the viewport\" height for full-bleed layouts\n * (boards, canvases). The runtime auto-sizes the iframe to its content, so a\n * component can't use its own `vh` units (circular). The iframe is same-origin,\n * so this measures the parent viewport minus the iframe's offset instead.\n * Returns `null` when it can't measure (fall back to natural height).\n */\nexport function useFillViewportHeight(options: FillViewportOptions = {}): number | null {\n const { bottomMargin = 24, minHeight = 320 } = options\n const [height, setHeight] = useState<number | null>(null)\n\n useEffect(() => {\n function compute(): void {\n try {\n const frame = window.frameElement\n const parentWindow = window.parent\n if (!frame || !parentWindow || parentWindow === window) return\n const available =\n parentWindow.innerHeight - frame.getBoundingClientRect().top - bottomMargin\n setHeight(Math.max(available, minHeight))\n } catch {\n setHeight(null) // cross-origin or detached — fall back to natural height\n }\n }\n compute()\n try {\n window.parent.addEventListener('resize', compute)\n return () => window.parent.removeEventListener('resize', compute)\n } catch {\n return\n }\n }, [bottomMargin, minHeight])\n\n return height\n}\n"]}
|
package/dist/protocol.cjs
CHANGED
|
@@ -1,20 +1,24 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkP4MKRWPA_cjs = require('./chunk-P4MKRWPA.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
|
|
7
|
+
Object.defineProperty(exports, "COMPONENT_OVERLAY_Z_INDEX", {
|
|
8
|
+
enumerable: true,
|
|
9
|
+
get: function () { return chunkP4MKRWPA_cjs.COMPONENT_OVERLAY_Z_INDEX; }
|
|
10
|
+
});
|
|
7
11
|
Object.defineProperty(exports, "MESSAGE_SOURCE", {
|
|
8
12
|
enumerable: true,
|
|
9
|
-
get: function () { return
|
|
13
|
+
get: function () { return chunkP4MKRWPA_cjs.MESSAGE_SOURCE; }
|
|
10
14
|
});
|
|
11
15
|
Object.defineProperty(exports, "isHostMessage", {
|
|
12
16
|
enumerable: true,
|
|
13
|
-
get: function () { return
|
|
17
|
+
get: function () { return chunkP4MKRWPA_cjs.isHostMessage; }
|
|
14
18
|
});
|
|
15
19
|
Object.defineProperty(exports, "isRuntimeMessage", {
|
|
16
20
|
enumerable: true,
|
|
17
|
-
get: function () { return
|
|
21
|
+
get: function () { return chunkP4MKRWPA_cjs.isRuntimeMessage; }
|
|
18
22
|
});
|
|
19
23
|
//# sourceMappingURL=protocol.cjs.map
|
|
20
24
|
//# sourceMappingURL=protocol.cjs.map
|
package/dist/protocol.d.cts
CHANGED
|
@@ -1,4 +1,33 @@
|
|
|
1
1
|
declare const MESSAGE_SOURCE: "proteos-component-runtime";
|
|
2
|
+
/**
|
|
3
|
+
* z-index the component iframe is promoted to while one of its own overlays
|
|
4
|
+
* (modal, popover, menu, select, tooltip) is open. The iframe goes
|
|
5
|
+
* `position: fixed; inset: 0` at this z so the overlay — which portals to the
|
|
6
|
+
* IFRAME's body and would otherwise clip at the frame's box — can paint over
|
|
7
|
+
* the rest of the page.
|
|
8
|
+
*
|
|
9
|
+
* Host z ladder this slots into:
|
|
10
|
+
* 50 @proteos/ui Modal / Tooltip / ImageLightbox (default tier)
|
|
11
|
+
* 1000+ full-page panel stack (scrim 1000, panels 1001+n)
|
|
12
|
+
* 1090 peek scrim 1100 peek panel, ask-proteos window
|
|
13
|
+
* 1150 ← THIS
|
|
14
|
+
* 1200 menu popover, command palette, action dialog, component modal
|
|
15
|
+
* 1300 select popover
|
|
16
|
+
*
|
|
17
|
+
* Above the peek/full-page surfaces a component can live on, below the global
|
|
18
|
+
* host chrome. Note the cap: inside a peek (a `fixed` + z-index ancestor) the
|
|
19
|
+
* promoted iframe paints within that 1100 stacking context — it covers the
|
|
20
|
+
* peek's own content and everything under it, but host chrome at 1200+ still
|
|
21
|
+
* wins. That is the intended layering, not a bug.
|
|
22
|
+
*/
|
|
23
|
+
declare const COMPONENT_OVERLAY_Z_INDEX = 1150;
|
|
24
|
+
/** Viewport-relative box of the iframe's in-flow placeholder, in CSS px. */
|
|
25
|
+
interface OverlayRect {
|
|
26
|
+
top: number;
|
|
27
|
+
left: number;
|
|
28
|
+
width: number;
|
|
29
|
+
height: number;
|
|
30
|
+
}
|
|
2
31
|
interface PageContext {
|
|
3
32
|
record?: Record<string, unknown>;
|
|
4
33
|
entity?: {
|
|
@@ -28,6 +57,11 @@ interface InitMessage {
|
|
|
28
57
|
/** Org id for public mode — public endpoints carry the org in the path
|
|
29
58
|
* because there is no token to scope from. */
|
|
30
59
|
orgId?: string;
|
|
60
|
+
/** Set when this frame is the CONTENT of a host component modal (opened by
|
|
61
|
+
* another component via OPEN_MODAL). The component reads it through
|
|
62
|
+
* `useModalHost()` and closes with a result by posting MODAL_RESULT with
|
|
63
|
+
* this id. Absent on ordinary page-hosted frames. */
|
|
64
|
+
modalRequestId?: string;
|
|
31
65
|
}
|
|
32
66
|
interface AuthRefreshMessage {
|
|
33
67
|
type: 'AUTH_REFRESH';
|
|
@@ -37,7 +71,23 @@ interface DataInvalidateMessage {
|
|
|
37
71
|
type: 'DATA_INVALIDATE';
|
|
38
72
|
queryKey?: unknown[];
|
|
39
73
|
}
|
|
40
|
-
|
|
74
|
+
/** Where the iframe's in-flow box sits in the host viewport. Sent while the
|
|
75
|
+
* frame is promoted (OVERLAY_STATE open) so the runtime can keep its content
|
|
76
|
+
* parked at the original rect while the iframe itself covers the viewport —
|
|
77
|
+
* and re-sent when the host window resizes under an open overlay. */
|
|
78
|
+
interface OverlayRectMessage {
|
|
79
|
+
type: 'OVERLAY_RECT';
|
|
80
|
+
rect: OverlayRect;
|
|
81
|
+
}
|
|
82
|
+
/** Resolution of an OPEN_MODAL request: the host modal closed. `result` is the
|
|
83
|
+
* value the modal's component passed to MODAL_RESULT, and is absent when the
|
|
84
|
+
* modal was dismissed (backdrop / Esc / ×). */
|
|
85
|
+
interface ModalClosedMessage {
|
|
86
|
+
type: 'MODAL_CLOSED';
|
|
87
|
+
requestId: string;
|
|
88
|
+
result?: unknown;
|
|
89
|
+
}
|
|
90
|
+
type HostMessage = InitMessage | AuthRefreshMessage | DataInvalidateMessage | OverlayRectMessage | ModalClosedMessage;
|
|
41
91
|
interface ReadyMessage {
|
|
42
92
|
type: 'READY';
|
|
43
93
|
}
|
|
@@ -56,16 +106,63 @@ interface OpenPeekMessage {
|
|
|
56
106
|
type: 'OPEN_PEEK';
|
|
57
107
|
to: string;
|
|
58
108
|
}
|
|
109
|
+
/** The runtime has (or no longer has) an overlay open and needs the host to
|
|
110
|
+
* promote (or restore) the iframe. See {@link COMPONENT_OVERLAY_Z_INDEX}.
|
|
111
|
+
*
|
|
112
|
+
* Same-origin today, so the runtime applies the promotion styles to its own
|
|
113
|
+
* `window.frameElement` synchronously (pre-paint, no flicker) and this message
|
|
114
|
+
* is the host's cue to MIRROR that state into React — gate RESIZE, hold the
|
|
115
|
+
* placeholder height, start posting OVERLAY_RECT. When components move to a
|
|
116
|
+
* dedicated origin the runtime can no longer touch the frame and this message
|
|
117
|
+
* becomes the actuation instead; the runtime hides its overlay until the
|
|
118
|
+
* answering OVERLAY_RECT arrives. */
|
|
119
|
+
interface OverlayStateMessage {
|
|
120
|
+
type: 'OVERLAY_STATE';
|
|
121
|
+
open: boolean;
|
|
122
|
+
}
|
|
123
|
+
/** Ask the host to open ANOTHER component in a central modal, above everything
|
|
124
|
+
* this frame could reach on its own. The host answers with MODAL_CLOSED
|
|
125
|
+
* carrying the same `requestId`. */
|
|
126
|
+
interface OpenModalMessage {
|
|
127
|
+
type: 'OPEN_MODAL';
|
|
128
|
+
/** Correlates the eventual MODAL_CLOSED. Generated by the opener. */
|
|
129
|
+
requestId: string;
|
|
130
|
+
/** Slug of the component to mount inside the modal. */
|
|
131
|
+
componentSlug: string;
|
|
132
|
+
/** Props for that component (already literal values — no Liquid). */
|
|
133
|
+
props?: Record<string, unknown>;
|
|
134
|
+
/** Optional modal heading. */
|
|
135
|
+
title?: string;
|
|
136
|
+
}
|
|
137
|
+
/** Escape was pressed with focus inside the iframe, and nothing in the runtime
|
|
138
|
+
* consumed it.
|
|
139
|
+
*
|
|
140
|
+
* Keyboard events don't cross the iframe boundary, and react-aria binds its
|
|
141
|
+
* Escape handling to the overlay element in its own React tree — so a
|
|
142
|
+
* host-rendered dialog CANNOT see Escape once the user has clicked into a
|
|
143
|
+
* component. The runtime forwards it so the host can dismiss on the user's
|
|
144
|
+
* behalf. Not sent while the runtime has its own overlay open: that overlay
|
|
145
|
+
* owns Escape. */
|
|
146
|
+
interface EscapePressedMessage {
|
|
147
|
+
type: 'ESCAPE_PRESSED';
|
|
148
|
+
}
|
|
149
|
+
/** Posted by the component INSIDE a host modal to close it with a value. The
|
|
150
|
+
* `requestId` is the one INIT carried as `modalRequestId`. */
|
|
151
|
+
interface ModalResultMessage {
|
|
152
|
+
type: 'MODAL_RESULT';
|
|
153
|
+
requestId: string;
|
|
154
|
+
result?: unknown;
|
|
155
|
+
}
|
|
59
156
|
interface ErrorMessage {
|
|
60
157
|
type: 'ERROR';
|
|
61
158
|
message: string;
|
|
62
159
|
stack?: string;
|
|
63
160
|
}
|
|
64
|
-
type RuntimeMessage = ReadyMessage | ResizeMessage | NavigateMessage | OpenPeekMessage | ErrorMessage;
|
|
161
|
+
type RuntimeMessage = ReadyMessage | ResizeMessage | NavigateMessage | OpenPeekMessage | OverlayStateMessage | OpenModalMessage | ModalResultMessage | EscapePressedMessage | ErrorMessage;
|
|
65
162
|
type Envelope<T> = T & {
|
|
66
163
|
source: typeof MESSAGE_SOURCE;
|
|
67
164
|
};
|
|
68
165
|
declare function isHostMessage(data: unknown): data is Envelope<HostMessage>;
|
|
69
166
|
declare function isRuntimeMessage(data: unknown): data is Envelope<RuntimeMessage>;
|
|
70
167
|
|
|
71
|
-
export { type AuthRefreshMessage, type DataInvalidateMessage, type Envelope, type ErrorMessage, type HostMessage, type InitMessage, MESSAGE_SOURCE, type NavigateMessage, type OpenPeekMessage, type PageContext, type ReadyMessage, type ResizeMessage, type RuntimeMessage, isHostMessage, isRuntimeMessage };
|
|
168
|
+
export { type AuthRefreshMessage, COMPONENT_OVERLAY_Z_INDEX, type DataInvalidateMessage, type Envelope, type ErrorMessage, type EscapePressedMessage, type HostMessage, type InitMessage, MESSAGE_SOURCE, type ModalClosedMessage, type ModalResultMessage, type NavigateMessage, type OpenModalMessage, type OpenPeekMessage, type OverlayRect, type OverlayRectMessage, type OverlayStateMessage, type PageContext, type ReadyMessage, type ResizeMessage, type RuntimeMessage, isHostMessage, isRuntimeMessage };
|
package/dist/protocol.d.ts
CHANGED
|
@@ -1,4 +1,33 @@
|
|
|
1
1
|
declare const MESSAGE_SOURCE: "proteos-component-runtime";
|
|
2
|
+
/**
|
|
3
|
+
* z-index the component iframe is promoted to while one of its own overlays
|
|
4
|
+
* (modal, popover, menu, select, tooltip) is open. The iframe goes
|
|
5
|
+
* `position: fixed; inset: 0` at this z so the overlay — which portals to the
|
|
6
|
+
* IFRAME's body and would otherwise clip at the frame's box — can paint over
|
|
7
|
+
* the rest of the page.
|
|
8
|
+
*
|
|
9
|
+
* Host z ladder this slots into:
|
|
10
|
+
* 50 @proteos/ui Modal / Tooltip / ImageLightbox (default tier)
|
|
11
|
+
* 1000+ full-page panel stack (scrim 1000, panels 1001+n)
|
|
12
|
+
* 1090 peek scrim 1100 peek panel, ask-proteos window
|
|
13
|
+
* 1150 ← THIS
|
|
14
|
+
* 1200 menu popover, command palette, action dialog, component modal
|
|
15
|
+
* 1300 select popover
|
|
16
|
+
*
|
|
17
|
+
* Above the peek/full-page surfaces a component can live on, below the global
|
|
18
|
+
* host chrome. Note the cap: inside a peek (a `fixed` + z-index ancestor) the
|
|
19
|
+
* promoted iframe paints within that 1100 stacking context — it covers the
|
|
20
|
+
* peek's own content and everything under it, but host chrome at 1200+ still
|
|
21
|
+
* wins. That is the intended layering, not a bug.
|
|
22
|
+
*/
|
|
23
|
+
declare const COMPONENT_OVERLAY_Z_INDEX = 1150;
|
|
24
|
+
/** Viewport-relative box of the iframe's in-flow placeholder, in CSS px. */
|
|
25
|
+
interface OverlayRect {
|
|
26
|
+
top: number;
|
|
27
|
+
left: number;
|
|
28
|
+
width: number;
|
|
29
|
+
height: number;
|
|
30
|
+
}
|
|
2
31
|
interface PageContext {
|
|
3
32
|
record?: Record<string, unknown>;
|
|
4
33
|
entity?: {
|
|
@@ -28,6 +57,11 @@ interface InitMessage {
|
|
|
28
57
|
/** Org id for public mode — public endpoints carry the org in the path
|
|
29
58
|
* because there is no token to scope from. */
|
|
30
59
|
orgId?: string;
|
|
60
|
+
/** Set when this frame is the CONTENT of a host component modal (opened by
|
|
61
|
+
* another component via OPEN_MODAL). The component reads it through
|
|
62
|
+
* `useModalHost()` and closes with a result by posting MODAL_RESULT with
|
|
63
|
+
* this id. Absent on ordinary page-hosted frames. */
|
|
64
|
+
modalRequestId?: string;
|
|
31
65
|
}
|
|
32
66
|
interface AuthRefreshMessage {
|
|
33
67
|
type: 'AUTH_REFRESH';
|
|
@@ -37,7 +71,23 @@ interface DataInvalidateMessage {
|
|
|
37
71
|
type: 'DATA_INVALIDATE';
|
|
38
72
|
queryKey?: unknown[];
|
|
39
73
|
}
|
|
40
|
-
|
|
74
|
+
/** Where the iframe's in-flow box sits in the host viewport. Sent while the
|
|
75
|
+
* frame is promoted (OVERLAY_STATE open) so the runtime can keep its content
|
|
76
|
+
* parked at the original rect while the iframe itself covers the viewport —
|
|
77
|
+
* and re-sent when the host window resizes under an open overlay. */
|
|
78
|
+
interface OverlayRectMessage {
|
|
79
|
+
type: 'OVERLAY_RECT';
|
|
80
|
+
rect: OverlayRect;
|
|
81
|
+
}
|
|
82
|
+
/** Resolution of an OPEN_MODAL request: the host modal closed. `result` is the
|
|
83
|
+
* value the modal's component passed to MODAL_RESULT, and is absent when the
|
|
84
|
+
* modal was dismissed (backdrop / Esc / ×). */
|
|
85
|
+
interface ModalClosedMessage {
|
|
86
|
+
type: 'MODAL_CLOSED';
|
|
87
|
+
requestId: string;
|
|
88
|
+
result?: unknown;
|
|
89
|
+
}
|
|
90
|
+
type HostMessage = InitMessage | AuthRefreshMessage | DataInvalidateMessage | OverlayRectMessage | ModalClosedMessage;
|
|
41
91
|
interface ReadyMessage {
|
|
42
92
|
type: 'READY';
|
|
43
93
|
}
|
|
@@ -56,16 +106,63 @@ interface OpenPeekMessage {
|
|
|
56
106
|
type: 'OPEN_PEEK';
|
|
57
107
|
to: string;
|
|
58
108
|
}
|
|
109
|
+
/** The runtime has (or no longer has) an overlay open and needs the host to
|
|
110
|
+
* promote (or restore) the iframe. See {@link COMPONENT_OVERLAY_Z_INDEX}.
|
|
111
|
+
*
|
|
112
|
+
* Same-origin today, so the runtime applies the promotion styles to its own
|
|
113
|
+
* `window.frameElement` synchronously (pre-paint, no flicker) and this message
|
|
114
|
+
* is the host's cue to MIRROR that state into React — gate RESIZE, hold the
|
|
115
|
+
* placeholder height, start posting OVERLAY_RECT. When components move to a
|
|
116
|
+
* dedicated origin the runtime can no longer touch the frame and this message
|
|
117
|
+
* becomes the actuation instead; the runtime hides its overlay until the
|
|
118
|
+
* answering OVERLAY_RECT arrives. */
|
|
119
|
+
interface OverlayStateMessage {
|
|
120
|
+
type: 'OVERLAY_STATE';
|
|
121
|
+
open: boolean;
|
|
122
|
+
}
|
|
123
|
+
/** Ask the host to open ANOTHER component in a central modal, above everything
|
|
124
|
+
* this frame could reach on its own. The host answers with MODAL_CLOSED
|
|
125
|
+
* carrying the same `requestId`. */
|
|
126
|
+
interface OpenModalMessage {
|
|
127
|
+
type: 'OPEN_MODAL';
|
|
128
|
+
/** Correlates the eventual MODAL_CLOSED. Generated by the opener. */
|
|
129
|
+
requestId: string;
|
|
130
|
+
/** Slug of the component to mount inside the modal. */
|
|
131
|
+
componentSlug: string;
|
|
132
|
+
/** Props for that component (already literal values — no Liquid). */
|
|
133
|
+
props?: Record<string, unknown>;
|
|
134
|
+
/** Optional modal heading. */
|
|
135
|
+
title?: string;
|
|
136
|
+
}
|
|
137
|
+
/** Escape was pressed with focus inside the iframe, and nothing in the runtime
|
|
138
|
+
* consumed it.
|
|
139
|
+
*
|
|
140
|
+
* Keyboard events don't cross the iframe boundary, and react-aria binds its
|
|
141
|
+
* Escape handling to the overlay element in its own React tree — so a
|
|
142
|
+
* host-rendered dialog CANNOT see Escape once the user has clicked into a
|
|
143
|
+
* component. The runtime forwards it so the host can dismiss on the user's
|
|
144
|
+
* behalf. Not sent while the runtime has its own overlay open: that overlay
|
|
145
|
+
* owns Escape. */
|
|
146
|
+
interface EscapePressedMessage {
|
|
147
|
+
type: 'ESCAPE_PRESSED';
|
|
148
|
+
}
|
|
149
|
+
/** Posted by the component INSIDE a host modal to close it with a value. The
|
|
150
|
+
* `requestId` is the one INIT carried as `modalRequestId`. */
|
|
151
|
+
interface ModalResultMessage {
|
|
152
|
+
type: 'MODAL_RESULT';
|
|
153
|
+
requestId: string;
|
|
154
|
+
result?: unknown;
|
|
155
|
+
}
|
|
59
156
|
interface ErrorMessage {
|
|
60
157
|
type: 'ERROR';
|
|
61
158
|
message: string;
|
|
62
159
|
stack?: string;
|
|
63
160
|
}
|
|
64
|
-
type RuntimeMessage = ReadyMessage | ResizeMessage | NavigateMessage | OpenPeekMessage | ErrorMessage;
|
|
161
|
+
type RuntimeMessage = ReadyMessage | ResizeMessage | NavigateMessage | OpenPeekMessage | OverlayStateMessage | OpenModalMessage | ModalResultMessage | EscapePressedMessage | ErrorMessage;
|
|
65
162
|
type Envelope<T> = T & {
|
|
66
163
|
source: typeof MESSAGE_SOURCE;
|
|
67
164
|
};
|
|
68
165
|
declare function isHostMessage(data: unknown): data is Envelope<HostMessage>;
|
|
69
166
|
declare function isRuntimeMessage(data: unknown): data is Envelope<RuntimeMessage>;
|
|
70
167
|
|
|
71
|
-
export { type AuthRefreshMessage, type DataInvalidateMessage, type Envelope, type ErrorMessage, type HostMessage, type InitMessage, MESSAGE_SOURCE, type NavigateMessage, type OpenPeekMessage, type PageContext, type ReadyMessage, type ResizeMessage, type RuntimeMessage, isHostMessage, isRuntimeMessage };
|
|
168
|
+
export { type AuthRefreshMessage, COMPONENT_OVERLAY_Z_INDEX, type DataInvalidateMessage, type Envelope, type ErrorMessage, type EscapePressedMessage, type HostMessage, type InitMessage, MESSAGE_SOURCE, type ModalClosedMessage, type ModalResultMessage, type NavigateMessage, type OpenModalMessage, type OpenPeekMessage, type OverlayRect, type OverlayRectMessage, type OverlayStateMessage, type PageContext, type ReadyMessage, type ResizeMessage, type RuntimeMessage, isHostMessage, isRuntimeMessage };
|
package/dist/protocol.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { MESSAGE_SOURCE, isHostMessage, isRuntimeMessage } from './chunk-
|
|
1
|
+
export { COMPONENT_OVERLAY_Z_INDEX, MESSAGE_SOURCE, isHostMessage, isRuntimeMessage } from './chunk-2EAOQNQB.js';
|
|
2
2
|
//# sourceMappingURL=protocol.js.map
|
|
3
3
|
//# sourceMappingURL=protocol.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@proteos/component-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.42.1",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"description": "Typed runtime hooks for authoring Proteos custom components — the SDK you import inside a component bundle.",
|
|
6
6
|
"repository": {
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"src"
|
|
43
43
|
],
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@proteos/sdk": "^0.
|
|
45
|
+
"@proteos/sdk": "^0.42.1"
|
|
46
46
|
},
|
|
47
47
|
"peerDependencies": {
|
|
48
48
|
"@tanstack/react-query": ">=5.0.0",
|
package/src/context.tsx
CHANGED
|
@@ -12,8 +12,11 @@ import { createContext, type ReactNode, useMemo } from 'react'
|
|
|
12
12
|
|
|
13
13
|
import {
|
|
14
14
|
type Envelope,
|
|
15
|
+
isHostMessage,
|
|
15
16
|
MESSAGE_SOURCE,
|
|
17
|
+
type ModalResultMessage,
|
|
16
18
|
type NavigateMessage,
|
|
19
|
+
type OpenModalMessage,
|
|
17
20
|
type OpenPeekMessage,
|
|
18
21
|
type PageContext,
|
|
19
22
|
} from './protocol'
|
|
@@ -24,6 +27,25 @@ export interface NavigateOptions {
|
|
|
24
27
|
peek?: boolean
|
|
25
28
|
}
|
|
26
29
|
|
|
30
|
+
/** Options for {@link RuntimeContextValue.openModal}. */
|
|
31
|
+
export interface OpenModalOptions {
|
|
32
|
+
/** Heading rendered in the modal chrome. */
|
|
33
|
+
title?: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Manual control over iframe overlay promotion. The runtime already detects
|
|
38
|
+
* overlays automatically (anything portaled to the iframe's `document.body` —
|
|
39
|
+
* every `@proteos/ui` overlay qualifies), so components need this only for
|
|
40
|
+
* custom portal targets, or to promote a frame *before* opening an overlay.
|
|
41
|
+
* Calls are reference-counted: every `expand()` needs its `collapse()`.
|
|
42
|
+
*/
|
|
43
|
+
export interface OverlayController {
|
|
44
|
+
expand: () => void
|
|
45
|
+
collapse: () => void
|
|
46
|
+
isExpanded: () => boolean
|
|
47
|
+
}
|
|
48
|
+
|
|
27
49
|
/**
|
|
28
50
|
* The authenticated `@proteos/sdk` clients the runtime injects. Same instances
|
|
29
51
|
* the host app uses — pre-wired with a refreshing bearer token, so a component
|
|
@@ -72,6 +94,13 @@ export interface RuntimeValue {
|
|
|
72
94
|
isPublic?: boolean
|
|
73
95
|
/** Org id, set in public mode (public API routes carry it in the path). */
|
|
74
96
|
orgId?: string
|
|
97
|
+
/** Set when this component is the content of a host component modal — the
|
|
98
|
+
* correlation id it closes with. See `useModalHost()`. */
|
|
99
|
+
modalRequestId?: string
|
|
100
|
+
/** Overlay promotion controller, provided by the shell. Absent on older
|
|
101
|
+
* shells / non-promoting hosts, in which case `useOverlayExpansion()`
|
|
102
|
+
* no-ops. */
|
|
103
|
+
overlay?: OverlayController
|
|
75
104
|
}
|
|
76
105
|
|
|
77
106
|
/** Runtime value plus the derived helpers the hooks expose. */
|
|
@@ -79,6 +108,13 @@ export interface RuntimeContextValue extends RuntimeValue {
|
|
|
79
108
|
/** Navigate the host SPA to an in-app path (posts a NAVIGATE message), or
|
|
80
109
|
* open it in a peek panel with `{ peek: true }` (posts OPEN_PEEK). */
|
|
81
110
|
navigate: (to: string, options?: NavigateOptions) => void
|
|
111
|
+
/** Open another component in a host-rendered modal; resolves with the value
|
|
112
|
+
* that component closed with (`undefined` if dismissed). */
|
|
113
|
+
openModal: (
|
|
114
|
+
componentSlug: string,
|
|
115
|
+
props?: Record<string, unknown>,
|
|
116
|
+
options?: OpenModalOptions,
|
|
117
|
+
) => Promise<unknown>
|
|
82
118
|
}
|
|
83
119
|
|
|
84
120
|
export const RuntimeContext = createContext<RuntimeContextValue | null>(null)
|
|
@@ -103,6 +139,67 @@ function navigate(to: string, options?: NavigateOptions): void {
|
|
|
103
139
|
else postNavigate(to)
|
|
104
140
|
}
|
|
105
141
|
|
|
142
|
+
// ── Component modals ────────────────────────────────────────────────────────
|
|
143
|
+
// One module-level listener + a pending map, rather than a listener per call:
|
|
144
|
+
// the SDK is an import-mapped singleton, so this is per-iframe state.
|
|
145
|
+
|
|
146
|
+
const pendingModals = new Map<string, (result: unknown) => void>()
|
|
147
|
+
let modalListenerAttached = false
|
|
148
|
+
|
|
149
|
+
function ensureModalListener(): void {
|
|
150
|
+
if (modalListenerAttached) return
|
|
151
|
+
modalListenerAttached = true
|
|
152
|
+
window.addEventListener('message', (event: MessageEvent) => {
|
|
153
|
+
const data: unknown = event.data
|
|
154
|
+
if (!isHostMessage(data) || data.type !== 'MODAL_CLOSED') return
|
|
155
|
+
const resolve = pendingModals.get(data.requestId)
|
|
156
|
+
// An unknown requestId is someone else's modal (or a stale reply) — drop it.
|
|
157
|
+
if (!resolve) return
|
|
158
|
+
pendingModals.delete(data.requestId)
|
|
159
|
+
resolve(data.result)
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function newRequestId(): string {
|
|
164
|
+
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
|
165
|
+
return crypto.randomUUID()
|
|
166
|
+
}
|
|
167
|
+
return `modal_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Post OPEN_MODAL and resolve when the host answers MODAL_CLOSED. */
|
|
171
|
+
function openModal(
|
|
172
|
+
componentSlug: string,
|
|
173
|
+
props?: Record<string, unknown>,
|
|
174
|
+
options?: OpenModalOptions,
|
|
175
|
+
): Promise<unknown> {
|
|
176
|
+
ensureModalListener()
|
|
177
|
+
const requestId = newRequestId()
|
|
178
|
+
const envelope: Envelope<OpenModalMessage> = {
|
|
179
|
+
source: MESSAGE_SOURCE,
|
|
180
|
+
type: 'OPEN_MODAL',
|
|
181
|
+
requestId,
|
|
182
|
+
componentSlug,
|
|
183
|
+
...(props !== undefined ? { props } : {}),
|
|
184
|
+
...(options?.title !== undefined ? { title: options.title } : {}),
|
|
185
|
+
}
|
|
186
|
+
return new Promise<unknown>((resolve) => {
|
|
187
|
+
pendingModals.set(requestId, resolve)
|
|
188
|
+
window.parent?.postMessage(envelope, '*')
|
|
189
|
+
})
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Post MODAL_RESULT — the component inside a host modal closing with a value. */
|
|
193
|
+
export function postModalResult(requestId: string, result?: unknown): void {
|
|
194
|
+
const envelope: Envelope<ModalResultMessage> = {
|
|
195
|
+
source: MESSAGE_SOURCE,
|
|
196
|
+
type: 'MODAL_RESULT',
|
|
197
|
+
requestId,
|
|
198
|
+
...(result !== undefined ? { result } : {}),
|
|
199
|
+
}
|
|
200
|
+
window.parent?.postMessage(envelope, '*')
|
|
201
|
+
}
|
|
202
|
+
|
|
106
203
|
/**
|
|
107
204
|
* Provides the runtime value + derived helpers to a component subtree. Mounted
|
|
108
205
|
* by the component-runtime shell around the loaded component — authors never
|
|
@@ -114,6 +211,6 @@ export function RuntimeProvider({ value, children }: { value: RuntimeValue; chil
|
|
|
114
211
|
// The shell builds `value` once at INIT (a stable state object — clients,
|
|
115
212
|
// props and pageCtx are all set once), so memoizing on its identity recreates
|
|
116
213
|
// the context only when the runtime genuinely re-inits.
|
|
117
|
-
const ctx = useMemo<RuntimeContextValue>(() => ({ ...value, navigate }), [value])
|
|
214
|
+
const ctx = useMemo<RuntimeContextValue>(() => ({ ...value, navigate, openModal }), [value])
|
|
118
215
|
return <RuntimeContext.Provider value={ctx}>{children}</RuntimeContext.Provider>
|
|
119
216
|
}
|
package/src/hooks.test.tsx
CHANGED
|
@@ -3,8 +3,18 @@ import type { ReactNode } from 'react'
|
|
|
3
3
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
4
4
|
|
|
5
5
|
import { RuntimeProvider, type RuntimeValue } from './context'
|
|
6
|
-
import {
|
|
7
|
-
|
|
6
|
+
import {
|
|
7
|
+
useApiBaseUrl,
|
|
8
|
+
useComponentModal,
|
|
9
|
+
useModalHost,
|
|
10
|
+
useNavigate,
|
|
11
|
+
useOverlayExpansion,
|
|
12
|
+
usePageContext,
|
|
13
|
+
useProps,
|
|
14
|
+
useRuntime,
|
|
15
|
+
useSdk,
|
|
16
|
+
} from './hooks'
|
|
17
|
+
import { type Envelope, MESSAGE_SOURCE, type ModalClosedMessage } from './protocol'
|
|
8
18
|
|
|
9
19
|
// A stable stand-in for the injected SDK — the hooks only pass it through.
|
|
10
20
|
const sdk = {} as RuntimeValue['sdk']
|
|
@@ -65,6 +75,79 @@ describe('runtime hooks', () => {
|
|
|
65
75
|
)
|
|
66
76
|
})
|
|
67
77
|
|
|
78
|
+
it('useOverlayExpansion drives the shell controller', () => {
|
|
79
|
+
const overlay = { expand: vi.fn(), collapse: vi.fn(), isExpanded: () => true }
|
|
80
|
+
const { result } = renderHook(() => useOverlayExpansion(), {
|
|
81
|
+
wrapper: wrapper(makeValue({ overlay })),
|
|
82
|
+
})
|
|
83
|
+
result.current.expand()
|
|
84
|
+
result.current.collapse()
|
|
85
|
+
expect(overlay.expand).toHaveBeenCalledTimes(1)
|
|
86
|
+
expect(overlay.collapse).toHaveBeenCalledTimes(1)
|
|
87
|
+
expect(result.current.isExpanded()).toBe(true)
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
it('useOverlayExpansion warns and no-ops on a runtime without promotion support', () => {
|
|
91
|
+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
92
|
+
const { result } = renderHook(() => useOverlayExpansion(), { wrapper: wrapper(makeValue()) })
|
|
93
|
+
result.current.expand()
|
|
94
|
+
expect(warn).toHaveBeenCalledWith(expect.stringContaining('overlay promotion'))
|
|
95
|
+
expect(result.current.isExpanded()).toBe(false)
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
it('useComponentModal posts OPEN_MODAL and resolves on the matching MODAL_CLOSED', async () => {
|
|
99
|
+
const post = vi.spyOn(window.parent, 'postMessage').mockImplementation(() => {})
|
|
100
|
+
const { result } = renderHook(() => useComponentModal(), { wrapper: wrapper(makeValue()) })
|
|
101
|
+
|
|
102
|
+
const pending = result.current('contact-picker', { entity: 'contact' }, { title: 'Pick one' })
|
|
103
|
+
const [payload] = post.mock.calls.at(-1) as [Record<string, unknown>]
|
|
104
|
+
expect(payload).toMatchObject({
|
|
105
|
+
source: MESSAGE_SOURCE,
|
|
106
|
+
type: 'OPEN_MODAL',
|
|
107
|
+
componentSlug: 'contact-picker',
|
|
108
|
+
props: { entity: 'contact' },
|
|
109
|
+
title: 'Pick one',
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
// Another modal's reply must not resolve ours.
|
|
113
|
+
const reply = (requestId: string, result?: unknown): Envelope<ModalClosedMessage> => ({
|
|
114
|
+
source: MESSAGE_SOURCE,
|
|
115
|
+
type: 'MODAL_CLOSED',
|
|
116
|
+
requestId,
|
|
117
|
+
...(result !== undefined ? { result } : {}),
|
|
118
|
+
})
|
|
119
|
+
window.dispatchEvent(new MessageEvent('message', { data: reply('someone-else', 'nope') }))
|
|
120
|
+
window.dispatchEvent(
|
|
121
|
+
new MessageEvent('message', {
|
|
122
|
+
data: reply(payload.requestId as string, { id: 'con_9' }),
|
|
123
|
+
}),
|
|
124
|
+
)
|
|
125
|
+
await expect(pending).resolves.toEqual({ id: 'con_9' })
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
it('useModalHost closes with a result only when mounted inside a modal', () => {
|
|
129
|
+
const post = vi.spyOn(window.parent, 'postMessage').mockImplementation(() => {})
|
|
130
|
+
const outside = renderHook(() => useModalHost(), { wrapper: wrapper(makeValue()) })
|
|
131
|
+
expect(outside.result.current.isInModal).toBe(false)
|
|
132
|
+
outside.result.current.close('ignored')
|
|
133
|
+
expect(post).not.toHaveBeenCalled()
|
|
134
|
+
|
|
135
|
+
const inside = renderHook(() => useModalHost(), {
|
|
136
|
+
wrapper: wrapper(makeValue({ modalRequestId: 'cmodal_3' })),
|
|
137
|
+
})
|
|
138
|
+
expect(inside.result.current.isInModal).toBe(true)
|
|
139
|
+
inside.result.current.close({ picked: true })
|
|
140
|
+
expect(post).toHaveBeenCalledWith(
|
|
141
|
+
{
|
|
142
|
+
source: MESSAGE_SOURCE,
|
|
143
|
+
type: 'MODAL_RESULT',
|
|
144
|
+
requestId: 'cmodal_3',
|
|
145
|
+
result: { picked: true },
|
|
146
|
+
},
|
|
147
|
+
'*',
|
|
148
|
+
)
|
|
149
|
+
})
|
|
150
|
+
|
|
68
151
|
it('throws a clear error when used outside the runtime', () => {
|
|
69
152
|
// Silence the expected React error-boundary console noise.
|
|
70
153
|
vi.spyOn(console, 'error').mockImplementation(() => {})
|