@protobase/ui 0.113.0 → 0.114.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account/messages.d.ts +2 -2
- package/dist/app/app.d.ts +4 -1
- package/dist/app/app.js +9 -7
- package/dist/app/change-confirm/messages.d.ts +2 -2
- package/dist/app/charts/messages.d.ts +2 -2
- package/dist/app/confirm-sign-in-messages.d.ts +2 -2
- package/dist/app/create/messages.d.ts +2 -2
- package/dist/app/delete/messages.d.ts +2 -2
- package/dist/app/displays/messages.d.ts +2 -2
- package/dist/app/displays/virtual-cards.js +1 -0
- package/dist/app/embedded-list/messages.d.ts +2 -2
- package/dist/app/export/messages.d.ts +2 -2
- package/dist/app/field-messages.d.ts +2 -2
- package/dist/app/field-types/workflow/messages.d.ts +2 -2
- package/dist/app/field-types/workflow-page/messages.d.ts +2 -2
- package/dist/app/field-types/workflow-run/messages.d.ts +2 -2
- package/dist/app/field-types/workflow-status/messages.d.ts +2 -2
- package/dist/app/file-viewers/messages.d.ts +2 -2
- package/dist/app/first-frame.d.ts +13 -0
- package/dist/app/first-frame.js +23 -0
- package/dist/app/focus/messages.d.ts +2 -2
- package/dist/app/gallery/gallery-layout.d.ts +2 -2
- package/dist/app/gallery/messages.d.ts +2 -2
- package/dist/app/hand-order/messages.d.ts +2 -2
- package/dist/app/import/messages.d.ts +2 -2
- package/dist/app/index.html +0 -17
- package/dist/app/list-messages.d.ts +2 -2
- package/dist/app/main.js +19 -7
- package/dist/app/messages.d.ts +2 -2
- package/dist/app/pages/messages.d.ts +2 -2
- package/dist/app/record-chart/messages.d.ts +2 -2
- package/dist/app/record-messages.d.ts +2 -2
- package/dist/app/record-mode/shown-layout.d.ts +1 -1
- package/dist/app/record-row/messages.d.ts +2 -2
- package/dist/app/record-row/record-row.d.ts +3 -2
- package/dist/app/record-row/record-row.js +43 -27
- package/dist/app/record-row/row-window.d.ts +11 -0
- package/dist/app/record-row/row-window.js +15 -2
- package/dist/app/refresh-mark.d.ts +2 -1
- package/dist/app/refresh-mark.js +3 -1
- package/dist/app/related-cards/messages.d.ts +2 -2
- package/dist/app/reveal-when-loaded.d.ts +8 -2
- package/dist/app/reveal-when-loaded.js +12 -5
- package/dist/app/runtime/messages.d.ts +2 -2
- package/dist/app/saved/messages.d.ts +2 -2
- package/dist/app/searches/messages.d.ts +2 -2
- package/dist/app/splash-hold.d.ts +0 -1
- package/dist/app/splash-hold.js +1 -1
- package/dist/app/start-screen.d.ts +0 -9
- package/dist/app/start-screen.js +1 -10
- package/dist/app/ui-ready.d.ts +11 -0
- package/dist/app/ui-ready.js +12 -0
- package/dist/app-shell/app-shell.js +3 -1
- package/dist/app-shell/close-sidebar.d.ts +10 -0
- package/dist/app-shell/close-sidebar.js +17 -0
- package/dist/app-shell/drawer.d.ts +7 -1
- package/dist/app-shell/drawer.js +26 -7
- package/dist/app-shell/index.d.ts +2 -1
- package/dist/app-shell/index.js +2 -1
- package/dist/app-shell/messages.d.ts +2 -2
- package/dist/app-shell/top-bar.js +4 -4
- package/dist/assistant-dock/messages.d.ts +2 -2
- package/dist/auth/messages.d.ts +2 -2
- package/dist/calls/messages.d.ts +2 -2
- package/dist/compact-table/messages.d.ts +2 -2
- package/dist/data/query-keys.d.ts +6 -0
- package/dist/data/query-keys.js +10 -0
- package/dist/data/start-cache/cached-plugins.d.ts +6 -0
- package/dist/data/start-cache/cached-plugins.js +10 -0
- package/dist/data-grid/column-spec.d.ts +1 -1
- package/dist/data-grid/data-grid.js +1 -0
- package/dist/data-grid/messages.d.ts +2 -2
- package/dist/data-grid/row-source.d.ts +5 -0
- package/dist/data-grid/use-paged-rows.d.ts +5 -3
- package/dist/data-grid/use-paged-rows.js +21 -6
- package/dist/filter-panel/messages.d.ts +2 -2
- package/dist/focus-page/messages.d.ts +2 -2
- package/dist/index.d.ts +4 -1
- package/dist/index.js +4 -1
- package/dist/invitations/messages.d.ts +2 -2
- package/dist/live/grid-loader.d.ts +1 -0
- package/dist/live/grid-loader.js +3 -1
- package/dist/live/use-live-rows.js +1 -0
- package/dist/mailbox/messages.d.ts +2 -2
- package/dist/mocks/customers.d.ts +1 -1
- package/dist/mocks/invoices.d.ts +1 -1
- package/dist/mocks/orders.d.ts +3 -3
- package/dist/notifications/bell/messages.d.ts +2 -2
- package/dist/organizations/members-page.js +13 -7
- package/dist/organizations/messages.d.ts +2 -2
- package/dist/organizations/use-organizations.d.ts +4 -1
- package/dist/organizations/use-organizations.js +25 -19
- package/dist/package.js +1 -1
- package/dist/plugins/plugin-source.d.ts +24 -4
- package/dist/plugins/plugin-source.js +48 -14
- package/dist/plugins/use-plugin-loads.d.ts +3 -1
- package/dist/plugins/use-plugin-loads.js +24 -7
- package/dist/primitives/messages.d.ts +2 -2
- package/dist/primitives/skeleton.js +1 -0
- package/dist/record-view/messages.d.ts +2 -2
- package/dist/roles/use-active-role.d.ts +4 -1
- package/dist/roles/use-active-role.js +18 -13
- package/dist/shell/assets/api-provider-BJJrOoO4.js +2 -0
- package/dist/shell/assets/app-VoTi41IN.js +16 -0
- package/dist/shell/assets/badge-OU9hb6yQ.js +2 -0
- package/dist/shell/assets/checkbox-DFfK432Y.js +2 -0
- package/dist/shell/assets/createLucideIcon-DGm8SdFI.js +2 -0
- package/dist/shell/assets/display-value-CIH2qfgQ.js +2 -0
- package/dist/shell/assets/{field-badge-3QmjR1r3.js → field-badge-DX2Mc_fH.js} +2 -2
- package/dist/shell/assets/{graph-view-BcbWbnHO.js → graph-view-CY9LPr0B.js} +2 -2
- package/dist/shell/assets/{html-viewer-tGtSpy9M.js → html-viewer-BPGMH_GA.js} +2 -2
- package/dist/shell/assets/{in-place-form-B0EkP4B1.js → in-place-form-RWSQGEg4.js} +2 -2
- package/dist/shell/assets/index-Bzb-O7ER.js +2 -0
- package/dist/shell/assets/index-HnFovy2Q.css +2 -0
- package/dist/shell/assets/{intl-cache-bXVNV0Yq.js → intl-cache-D4doUjK1.js} +2 -2
- package/dist/shell/assets/{lib-d3-interpolate-Cl0dHO4f.js → lib-d3-interpolate-D3u38iyJ.js} +2 -2
- package/dist/shell/assets/{lib-d3-transition-DUHAGQ8z.js → lib-d3-transition-BUpPvFvt.js} +2 -2
- package/dist/shell/assets/{lib-d3-zoom-gQh2osrj.js → lib-d3-zoom-BF7SPKNh.js} +2 -2
- package/dist/shell/assets/{lib-vis.gl-react-maplibre-CU7gWYjg.js → lib-vis.gl-react-maplibre-C7-0xNFC.js} +2 -2
- package/dist/shell/assets/{lib-xyflow-react-DGg_5r7u.js → lib-xyflow-react-CKyW7szC.js} +2 -2
- package/dist/shell/assets/maplibre-9ViQO48S.js +2 -0
- package/dist/shell/assets/{markdown-content-DHKbAJjx.js → markdown-content-DTB9RQDs.js} +2 -2
- package/dist/shell/assets/{record-map-nGRmsk6x.js → record-map-CVqCWtfe.js} +2 -2
- package/dist/shell/assets/{records-map-D2flyaz3.js → records-map-ClYSxrVR.js} +2 -2
- package/dist/shell/assets/{run-trace-view-DfrAPeum.js → run-trace-view-CN16MiXg.js} +2 -2
- package/dist/shell/assets/search-picker-BGpvJQRD.js +2 -0
- package/dist/shell/assets/shared-protobase-ui-BC8LqGQB.js +2 -0
- package/dist/shell/assets/step-catalog-CZY0ZpCC.js +2 -0
- package/dist/shell/assets/step-panel-DhD80lsJ.js +2 -0
- package/dist/shell/assets/use-app-address-B4Uk3nWy.js +2 -0
- package/dist/shell/assets/{use-meta-BqEqOLNe.js → use-meta-D5kYywHm.js} +2 -2
- package/dist/shell/assets/{use-sibling-page-CiuiG-Tz.js → use-sibling-page-BJ81HcOP.js} +3 -3
- package/dist/shell/assets/value-badge-Dpd8dRqq.js +2 -0
- package/dist/shell/assets/{vendor-WWp_xlp2.js → vendor-3etemhgS.js} +4 -4
- package/dist/shell/assets/{workflow-canvas-DMP7SDWX.js → workflow-canvas-C1nGpi5w.js} +2 -2
- package/dist/shell/assets/{workflow-graph-editor-xpV8_qEl.js → workflow-graph-editor-DAJa4lq6.js} +2 -2
- package/dist/shell/assets/workflow-workbench-HramVZEJ.js +4 -0
- package/dist/shell/assets/{workflows-Bku4o2su.js → workflows-DlvOln9v.js} +2 -2
- package/dist/shell/assets/{workflows-start-kl7rSSay.js → workflows-start-QUKfwFqf.js} +2 -2
- package/dist/shell/index.html +16 -19
- package/dist/shell/protobase.shell.json +2 -2
- package/dist/shell/protobase.sw.js +2 -2
- package/dist/shell-source-maps/assets/api-provider-BJJrOoO4.js.map +1 -0
- package/dist/shell-source-maps/assets/app-VoTi41IN.js.map +1 -0
- package/dist/shell-source-maps/assets/{badge-ChHXC28D.js.map → badge-OU9hb6yQ.js.map} +1 -1
- package/dist/shell-source-maps/assets/{checkbox-COOOlJPG.js.map → checkbox-DFfK432Y.js.map} +1 -1
- package/dist/shell-source-maps/assets/createLucideIcon-DGm8SdFI.js.map +1 -0
- package/dist/shell-source-maps/assets/display-value-CIH2qfgQ.js.map +1 -0
- package/dist/shell-source-maps/assets/{field-badge-3QmjR1r3.js.map → field-badge-DX2Mc_fH.js.map} +1 -1
- package/dist/shell-source-maps/assets/{graph-view-BcbWbnHO.js.map → graph-view-CY9LPr0B.js.map} +1 -1
- package/dist/shell-source-maps/assets/{html-viewer-tGtSpy9M.js.map → html-viewer-BPGMH_GA.js.map} +1 -1
- package/dist/shell-source-maps/assets/{in-place-form-B0EkP4B1.js.map → in-place-form-RWSQGEg4.js.map} +1 -1
- package/dist/shell-source-maps/assets/index-Bzb-O7ER.js.map +1 -0
- package/dist/shell-source-maps/assets/{intl-cache-bXVNV0Yq.js.map → intl-cache-D4doUjK1.js.map} +1 -1
- package/dist/shell-source-maps/assets/{lib-d3-interpolate-Cl0dHO4f.js.map → lib-d3-interpolate-D3u38iyJ.js.map} +1 -1
- package/dist/shell-source-maps/assets/{lib-d3-transition-DUHAGQ8z.js.map → lib-d3-transition-BUpPvFvt.js.map} +1 -1
- package/dist/shell-source-maps/assets/{lib-d3-zoom-gQh2osrj.js.map → lib-d3-zoom-BF7SPKNh.js.map} +1 -1
- package/dist/shell-source-maps/assets/{lib-vis.gl-react-maplibre-CU7gWYjg.js.map → lib-vis.gl-react-maplibre-C7-0xNFC.js.map} +1 -1
- package/dist/shell-source-maps/assets/{lib-xyflow-react-DGg_5r7u.js.map → lib-xyflow-react-CKyW7szC.js.map} +1 -1
- package/dist/shell-source-maps/assets/{maplibre-Y7X50Jfk.js.map → maplibre-9ViQO48S.js.map} +1 -1
- package/dist/shell-source-maps/assets/{markdown-content-DHKbAJjx.js.map → markdown-content-DTB9RQDs.js.map} +1 -1
- package/dist/shell-source-maps/assets/{record-map-nGRmsk6x.js.map → record-map-CVqCWtfe.js.map} +1 -1
- package/dist/shell-source-maps/assets/{records-map-D2flyaz3.js.map → records-map-ClYSxrVR.js.map} +1 -1
- package/dist/shell-source-maps/assets/{run-trace-view-DfrAPeum.js.map → run-trace-view-CN16MiXg.js.map} +1 -1
- package/dist/shell-source-maps/assets/{search-picker-CJcJetBh.js.map → search-picker-BGpvJQRD.js.map} +1 -1
- package/dist/shell-source-maps/assets/shared-protobase-ui-BC8LqGQB.js.map +1 -0
- package/dist/shell-source-maps/assets/{step-catalog-ZvQOXfSh.js.map → step-catalog-CZY0ZpCC.js.map} +1 -1
- package/dist/shell-source-maps/assets/{step-panel-B1yHz7OC.js.map → step-panel-DhD80lsJ.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-app-address-B6k3dkV0.js.map → use-app-address-B4Uk3nWy.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-meta-BqEqOLNe.js.map → use-meta-D5kYywHm.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-sibling-page-CiuiG-Tz.js.map → use-sibling-page-BJ81HcOP.js.map} +1 -1
- package/dist/shell-source-maps/assets/{value-badge-BKLV4otJ.js.map → value-badge-Dpd8dRqq.js.map} +1 -1
- package/dist/shell-source-maps/assets/{vendor-WWp_xlp2.js.map → vendor-3etemhgS.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-canvas-DMP7SDWX.js.map → workflow-canvas-C1nGpi5w.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-graph-editor-xpV8_qEl.js.map → workflow-graph-editor-DAJa4lq6.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-workbench-Djdd_ODh.js.map → workflow-workbench-HramVZEJ.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflows-Bku4o2su.js.map → workflows-DlvOln9v.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflows-start-kl7rSSay.js.map → workflows-start-QUKfwFqf.js.map} +1 -1
- package/dist/status/messages.d.ts +2 -2
- package/dist/styles.css +14 -0
- package/dist/users/messages.d.ts +2 -2
- package/package.json +5 -5
- package/dist/app/hold-start-for-first-loads.d.ts +0 -12
- package/dist/app/hold-start-for-first-loads.js +0 -43
- package/dist/shell/assets/api-provider-CcDtTh0D.js +0 -2
- package/dist/shell/assets/app-DG30qs8Q.js +0 -16
- package/dist/shell/assets/badge-ChHXC28D.js +0 -2
- package/dist/shell/assets/checkbox-COOOlJPG.js +0 -2
- package/dist/shell/assets/display-value-fDiKbfJO.js +0 -2
- package/dist/shell/assets/index-BkCaPeOq.css +0 -2
- package/dist/shell/assets/index-CZ013UoE.js +0 -2
- package/dist/shell/assets/maplibre-Y7X50Jfk.js +0 -2
- package/dist/shell/assets/messages-ClKBpZlk.js +0 -2
- package/dist/shell/assets/search-picker-CJcJetBh.js +0 -2
- package/dist/shell/assets/shared-protobase-ui-CVwqj5Cp.js +0 -2
- package/dist/shell/assets/step-catalog-ZvQOXfSh.js +0 -2
- package/dist/shell/assets/step-panel-B1yHz7OC.js +0 -2
- package/dist/shell/assets/use-app-address-B6k3dkV0.js +0 -2
- package/dist/shell/assets/value-badge-BKLV4otJ.js +0 -2
- package/dist/shell/assets/workflow-workbench-Djdd_ODh.js +0 -4
- package/dist/shell-source-maps/assets/api-provider-CcDtTh0D.js.map +0 -1
- package/dist/shell-source-maps/assets/app-DG30qs8Q.js.map +0 -1
- package/dist/shell-source-maps/assets/display-value-fDiKbfJO.js.map +0 -1
- package/dist/shell-source-maps/assets/index-CZ013UoE.js.map +0 -1
- package/dist/shell-source-maps/assets/messages-ClKBpZlk.js.map +0 -1
- package/dist/shell-source-maps/assets/shared-protobase-ui-CVwqj5Cp.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-meta-BqEqOLNe.js","names":["useRef","useRef","createPortal","createContext","useContext","useMemo","n","a","t","__toESM","require_react","require_react_dom","require_jsx_runtime","useQuery","useQueryClient","isRestored","useClient","ClientStartContext","keys","cn","capitalise","text","humanize","name","import_react","import_react_dom","attribute","lockPageScroll","root","overflow","body","locked","focusable","stack","useFocusTrap","escape","onEscape","active","container","previous","unlock","token","items","onKey","event","list","first","last","import_jsx_runtime","Dialog","panel","onClose","title","wide","description","children","actions","MetaContext","keepOnVersionChange","next","useMeta","client","queryClient","merged","startedAt","query","current","result","state","model","entry"],"sources":["../../../../schema/src/humanize.ts","../../../src/lib/page-scroll-lock.ts","../../../src/lib/use-focus-trap.ts","../../../src/primitives/dialog.tsx","../../../src/data/meta-context.ts","../../../src/data/version-freeze.ts","../../../src/data/use-meta.ts"],"sourcesContent":["const capitalise = (text: string) => text.charAt(0).toUpperCase() + text.slice(1)\n\n/**\n * A field's or resource's name in words, where its view gives no label: `companyId` and `company_id` become \"Company\",\n * `discountPercent` and `discount_percent` become \"Discount percent\".\n */\nexport const humanize = (name: string) => {\n const words = name\n .replace(/(Id|Code|_id|_code)$/, '')\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/_+/g, ' ')\n .trim()\n .toLowerCase()\n return capitalise(words || name)\n}\n","const attribute = 'data-pb-scroll-locked'\n\n/**\n * Stops the page scrolling behind a modal until the returned function is called. Where the page shows a scrollbar that\n * takes room, the page keeps that room meanwhile (`styles.css` reserves it for this attribute), so hiding the scrollbar\n * does not widen the page and move everything behind the modal sideways.\n */\nexport const lockPageScroll = () => {\n const { body, documentElement: root } = document\n const overflow = body.style.overflow\n const locked = root.hasAttribute(attribute)\n if (window.innerWidth > root.clientWidth) root.setAttribute(attribute, '')\n body.style.overflow = 'hidden'\n return () => {\n body.style.overflow = overflow\n if (!locked) root.removeAttribute(attribute)\n }\n}\n","import { useEffect, useRef, type RefObject } from 'react'\nimport { lockPageScroll } from './page-scroll-lock'\n\nconst focusable = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex=\"-1\"])'\n\n// The active traps, the last opened last: only it takes the keys, so Escape in a sheet over a dialog closes the sheet alone\nconst stack: object[] = []\n\n/**\n * While `active`: moves focus into `container`, keeps Tab inside it, locks page scrolling (see `lockPageScroll`),\n * calls `onEscape` on Escape, and returns focus to the previously focused element afterwards. A trap opened while\n * another is active takes Tab and Escape until it ends.\n */\nexport const useFocusTrap = (container: RefObject<HTMLElement | null>, active: boolean, onEscape: () => void) => {\n const escape = useRef(onEscape)\n escape.current = onEscape\n useEffect(() => {\n if (!active || !container.current) return\n const root = container.current\n const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null\n const unlock = lockPageScroll()\n const token = {}\n stack.push(token)\n const items = () => [...root.querySelectorAll<HTMLElement>(focusable)]\n ;(items()[0] ?? root).focus()\n\n const onKey = (event: KeyboardEvent) => {\n if (stack.at(-1) !== token) return\n if (event.key === 'Escape') return escape.current()\n if (event.key !== 'Tab') return\n const list = items()\n if (list.length === 0) return event.preventDefault()\n const first = list[0]!\n const last = list[list.length - 1]!\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault()\n last.focus()\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault()\n first.focus()\n } else if (!root.contains(document.activeElement)) {\n event.preventDefault()\n first.focus()\n }\n }\n document.addEventListener('keydown', onKey)\n return () => {\n document.removeEventListener('keydown', onKey)\n stack.splice(stack.indexOf(token), 1)\n unlock()\n previous?.focus()\n }\n }, [active, container])\n}\n","import { useRef, type ReactNode } from 'react'\nimport { createPortal } from 'react-dom'\nimport { cn } from '../lib/cn'\nimport { useFocusTrap } from '../lib/use-focus-trap'\n\nexport type DialogProps = {\n title: string\n description?: ReactNode\n onClose: () => void\n /** Buttons, rendered right-aligned. */\n actions: ReactNode\n children?: ReactNode\n /** Room for a row of cards or a table in the body, instead of a short question. */\n wide?: boolean\n /** Names the dialog in its layer's `data-dialog` (empty without), for code that asks whether an element sits in it. */\n name?: string\n}\n\n/**\n * A modal with a title, optional body and action buttons. Closes on Escape and on a click outside. It is portalled to\n * the body, so no stacking context of the page it opens from, such as a sticky column, puts page content above it.\n */\nexport const Dialog = ({ title, description, onClose, actions, children, wide = false, name }: DialogProps) => {\n const panel = useRef<HTMLDivElement>(null)\n useFocusTrap(panel, true, onClose)\n return createPortal(\n <div data-dialog={name ?? ''} className=\"fixed inset-0 z-[90] flex items-center justify-center bg-backdrop/30 p-4 pb-[calc(1rem+var(--pb-safe-bottom))] pl-[calc(1rem+var(--pb-safe-left))] pr-[calc(1rem+var(--pb-safe-right))] pt-[calc(1rem+var(--pb-safe-top))]\" onMouseDown={(event) => event.target === event.currentTarget && onClose()}>\n <div ref={panel} tabIndex={-1} role=\"dialog\" aria-modal=\"true\" aria-label={title} className={cn('outline-none max-h-[min(90vh,100%)] w-full overflow-y-auto rounded-lg border bg-background p-4 shadow-pop sm:p-5', wide ? 'max-w-3xl' : 'max-w-md')}>\n <h2 className=\"text-base font-semibold\">{title}</h2>\n {description && <p className=\"mt-1.5 text-muted-foreground\">{description}</p>}\n {children && <div className=\"mt-4\">{children}</div>}\n <div className=\"mt-5 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end [&>*]:min-h-11 sm:[&>*]:min-h-0\">{actions}</div>\n </div>\n </div>,\n document.body,\n )\n}\n","import { createContext } from 'react'\nimport type { MetaData } from './meta-data'\n\n/** The app's `/meta` with the resources of its sources, as `MetaGate` gives it to everything below it. */\nexport const MetaContext = createContext<MetaData | null>(null)\n","import type { MetaData } from './meta-data'\n\n/**\n * The `/meta` the page keeps after reading it again: `next`, unless the server now runs another Protobase version than\n * the page started with. The page then keeps the `/meta` it has, marked with the version the server moved to, and\n * `useMeta` stops reading it, so nothing on the page changes until it is reloaded.\n */\nexport const keepOnVersionChange = (previous: MetaData | undefined, next: MetaData): MetaData => {\n if (!previous) return next\n if (previous.versionChange) return previous\n if (next.protobaseVersion === previous.protobaseVersion) return next\n return { ...previous, versionChange: { ...(next.protobaseVersion && { to: next.protobaseVersion }) } }\n}\n","import { useQuery, useQueryClient, type UseQueryResult } from '@tanstack/react-query'\nimport { useContext, useMemo } from 'react'\nimport { useClient } from './api-provider'\nimport { MetaContext } from './meta-context'\nimport type { MetaData } from './meta-data'\nimport { keys } from './query-keys'\nimport { isRestored, ClientStartContext } from './start-cache/restored-state'\nimport { keepOnVersionChange } from './version-freeze'\n\n/**\n * The resource and view models. Refetches on window focus with `If-None-Match`, so an unchanged\n * `/meta` costs a 304, and the cached object keeps its identity. Once the server runs another Protobase version than\n * the page started with, it keeps the `/meta` it has and stops reading it (see `keepOnVersionChange`). Below the app's\n * `MetaGate`, `data` holds the resources of its sources too, as every page of the app reads them. A `/meta` from the start\n * cache is replaced by the first one read, whatever its version.\n */\nexport const useMeta = (): UseQueryResult<MetaData> => {\n const client = useClient()\n const queryClient = useQueryClient()\n const merged = useContext(MetaContext)\n const startedAt = useContext(ClientStartContext)\n const query = useQuery({\n queryKey: keys.meta,\n staleTime: 0,\n refetchOnWindowFocus: 'always',\n enabled: (current) => !current.state.data?.versionChange,\n queryFn: async (): Promise<MetaData> => {\n const previous = queryClient.getQueryData<MetaData>(keys.meta)\n const result = await client.meta(previous?.etag)\n if (result.status === 'unchanged') {\n if (!previous) throw new Error('The server answered 304 to a request without If-None-Match')\n return previous\n }\n // A cached `/meta` is from an earlier start, so the version this page started with is the first one it reads\n const state = queryClient.getQueryState(keys.meta)\n return keepOnVersionChange(state && isRestored(state, startedAt) ? undefined : previous, {\n etag: result.etag,\n appName: result.meta.appName,\n ...(result.meta.protobaseVersion && { protobaseVersion: result.meta.protobaseVersion }),\n ...(result.meta.appIcon && { appIcon: result.meta.appIcon }),\n resources: Object.fromEntries(result.meta.resources.map((model) => [model.name, model])),\n views: Object.fromEntries(result.meta.views.map((model) => [model.resource, model])),\n pages: Object.fromEntries((result.meta.pages ?? []).map((model) => [model.name, model])),\n ...(result.meta.account && { account: result.meta.account }),\n permissions: result.meta.permissions ?? {},\n ...(result.meta.userMenu && { userMenu: result.meta.userMenu }),\n ...(result.meta.signIn && { signIn: Object.fromEntries(result.meta.signIn.map((entry) => [entry.resource, entry])) }),\n ...(result.meta.bottomBar && { bottomBar: result.meta.bottomBar }),\n ...(result.meta.assistant && { assistant: result.meta.assistant }),\n ...(result.meta.runtime && { runtime: result.meta.runtime }),\n ...(result.meta.errorReporting && { errorReporting: result.meta.errorReporting }),\n ...(result.meta.maps && { maps: result.meta.maps }),\n ...(result.meta.notifications?.bell && { bell: true }),\n ...(result.meta.status && { status: true }),\n ...(result.meta.calls && { calls: true }),\n ...(result.meta.locale && { locale: result.meta.locale }),\n ...(result.meta.texts && { texts: result.meta.texts }),\n ...(result.meta.files && { files: result.meta.files }),\n ...(result.meta.plugins && { plugins: result.meta.plugins }),\n // The sources' own `/meta` is read below `MetaGate` (see `withSources`).\n ...(result.meta.sources && { sources: result.meta.sources.map((source) => ({ source, state: 'loading' as const })) }),\n })\n },\n })\n return useMemo(() => (merged && query.data ? ({ ...query, data: merged } as UseQueryResult<MetaData>) : query), [merged, query])\n}\n"],"mappings":"0tBAAA,IAAMoB,EAAc,GAAiBC,EAAK,OAAO,CAAC,CAAC,CAAC,YAAY,EAAIA,EAAK,MAAM,CAAC,EAMnEC,EAAY,GAOhBF,EANOG,EACX,QAAQ,uBAAwB,EAAE,CAAC,CACnC,QAAQ,qBAAsB,OAAO,CAAC,CACtC,QAAQ,MAAO,GAAG,CAAC,CACnB,KAAK,CAAC,CACN,YACe,GAASA,CAAI,wBCb3BG,EAAY,wBAOLC,MAAuB,CAClC,GAAM,CAAE,OAAM,gBAAiBC,GAAS,SAClCC,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,CACjI","debugId":"6a12a38b-35ea-4db0-b9b0-5f5ff2cef250"}
|
|
1
|
+
{"version":3,"file":"use-meta-D5kYywHm.js","names":["useRef","useRef","createPortal","createContext","useContext","useMemo","n","a","t","__toESM","require_react","require_react_dom","require_jsx_runtime","useQuery","useQueryClient","keys","isRestored","useClient","ClientStartContext","cn","capitalise","text","humanize","name","import_react","import_react_dom","attribute","lockPageScroll","root","overflow","body","locked","focusable","stack","useFocusTrap","escape","onEscape","active","container","previous","unlock","token","items","onKey","event","list","first","last","import_jsx_runtime","Dialog","panel","onClose","title","wide","description","children","actions","MetaContext","keepOnVersionChange","next","useMeta","client","queryClient","merged","startedAt","query","current","result","state","model","entry"],"sources":["../../../../schema/src/humanize.ts","../../../src/lib/page-scroll-lock.ts","../../../src/lib/use-focus-trap.ts","../../../src/primitives/dialog.tsx","../../../src/data/meta-context.ts","../../../src/data/version-freeze.ts","../../../src/data/use-meta.ts"],"sourcesContent":["const capitalise = (text: string) => text.charAt(0).toUpperCase() + text.slice(1)\n\n/**\n * A field's or resource's name in words, where its view gives no label: `companyId` and `company_id` become \"Company\",\n * `discountPercent` and `discount_percent` become \"Discount percent\".\n */\nexport const humanize = (name: string) => {\n const words = name\n .replace(/(Id|Code|_id|_code)$/, '')\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/_+/g, ' ')\n .trim()\n .toLowerCase()\n return capitalise(words || name)\n}\n","const attribute = 'data-pb-scroll-locked'\n\n/**\n * Stops the page scrolling behind a modal until the returned function is called. Where the page shows a scrollbar that\n * takes room, the page keeps that room meanwhile (`styles.css` reserves it for this attribute), so hiding the scrollbar\n * does not widen the page and move everything behind the modal sideways.\n */\nexport const lockPageScroll = () => {\n const { body, documentElement: root } = document\n const overflow = body.style.overflow\n const locked = root.hasAttribute(attribute)\n if (window.innerWidth > root.clientWidth) root.setAttribute(attribute, '')\n body.style.overflow = 'hidden'\n return () => {\n body.style.overflow = overflow\n if (!locked) root.removeAttribute(attribute)\n }\n}\n","import { useEffect, useRef, type RefObject } from 'react'\nimport { lockPageScroll } from './page-scroll-lock'\n\nconst focusable = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex=\"-1\"])'\n\n// The active traps, the last opened last: only it takes the keys, so Escape in a sheet over a dialog closes the sheet alone\nconst stack: object[] = []\n\n/**\n * While `active`: moves focus into `container`, keeps Tab inside it, locks page scrolling (see `lockPageScroll`),\n * calls `onEscape` on Escape, and returns focus to the previously focused element afterwards. A trap opened while\n * another is active takes Tab and Escape until it ends.\n */\nexport const useFocusTrap = (container: RefObject<HTMLElement | null>, active: boolean, onEscape: () => void) => {\n const escape = useRef(onEscape)\n escape.current = onEscape\n useEffect(() => {\n if (!active || !container.current) return\n const root = container.current\n const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null\n const unlock = lockPageScroll()\n const token = {}\n stack.push(token)\n const items = () => [...root.querySelectorAll<HTMLElement>(focusable)]\n ;(items()[0] ?? root).focus()\n\n const onKey = (event: KeyboardEvent) => {\n if (stack.at(-1) !== token) return\n if (event.key === 'Escape') return escape.current()\n if (event.key !== 'Tab') return\n const list = items()\n if (list.length === 0) return event.preventDefault()\n const first = list[0]!\n const last = list[list.length - 1]!\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault()\n last.focus()\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault()\n first.focus()\n } else if (!root.contains(document.activeElement)) {\n event.preventDefault()\n first.focus()\n }\n }\n document.addEventListener('keydown', onKey)\n return () => {\n document.removeEventListener('keydown', onKey)\n stack.splice(stack.indexOf(token), 1)\n unlock()\n previous?.focus()\n }\n }, [active, container])\n}\n","import { useRef, type ReactNode } from 'react'\nimport { createPortal } from 'react-dom'\nimport { cn } from '../lib/cn'\nimport { useFocusTrap } from '../lib/use-focus-trap'\n\nexport type DialogProps = {\n title: string\n description?: ReactNode\n onClose: () => void\n /** Buttons, rendered right-aligned. */\n actions: ReactNode\n children?: ReactNode\n /** Room for a row of cards or a table in the body, instead of a short question. */\n wide?: boolean\n /** Names the dialog in its layer's `data-dialog` (empty without), for code that asks whether an element sits in it. */\n name?: string\n}\n\n/**\n * A modal with a title, optional body and action buttons. Closes on Escape and on a click outside. It is portalled to\n * the body, so no stacking context of the page it opens from, such as a sticky column, puts page content above it.\n */\nexport const Dialog = ({ title, description, onClose, actions, children, wide = false, name }: DialogProps) => {\n const panel = useRef<HTMLDivElement>(null)\n useFocusTrap(panel, true, onClose)\n return createPortal(\n <div data-dialog={name ?? ''} className=\"fixed inset-0 z-[90] flex items-center justify-center bg-backdrop/30 p-4 pb-[calc(1rem+var(--pb-safe-bottom))] pl-[calc(1rem+var(--pb-safe-left))] pr-[calc(1rem+var(--pb-safe-right))] pt-[calc(1rem+var(--pb-safe-top))]\" onMouseDown={(event) => event.target === event.currentTarget && onClose()}>\n <div ref={panel} tabIndex={-1} role=\"dialog\" aria-modal=\"true\" aria-label={title} className={cn('outline-none max-h-[min(90vh,100%)] w-full overflow-y-auto rounded-lg border bg-background p-4 shadow-pop sm:p-5', wide ? 'max-w-3xl' : 'max-w-md')}>\n <h2 className=\"text-base font-semibold\">{title}</h2>\n {description && <p className=\"mt-1.5 text-muted-foreground\">{description}</p>}\n {children && <div className=\"mt-4\">{children}</div>}\n <div className=\"mt-5 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end [&>*]:min-h-11 sm:[&>*]:min-h-0\">{actions}</div>\n </div>\n </div>,\n document.body,\n )\n}\n","import { createContext } from 'react'\nimport type { MetaData } from './meta-data'\n\n/** The app's `/meta` with the resources of its sources, as `MetaGate` gives it to everything below it. */\nexport const MetaContext = createContext<MetaData | null>(null)\n","import type { MetaData } from './meta-data'\n\n/**\n * The `/meta` the page keeps after reading it again: `next`, unless the server now runs another Protobase version than\n * the page started with. The page then keeps the `/meta` it has, marked with the version the server moved to, and\n * `useMeta` stops reading it, so nothing on the page changes until it is reloaded.\n */\nexport const keepOnVersionChange = (previous: MetaData | undefined, next: MetaData): MetaData => {\n if (!previous) return next\n if (previous.versionChange) return previous\n if (next.protobaseVersion === previous.protobaseVersion) return next\n return { ...previous, versionChange: { ...(next.protobaseVersion && { to: next.protobaseVersion }) } }\n}\n","import { useQuery, useQueryClient, type UseQueryResult } from '@tanstack/react-query'\nimport { useContext, useMemo } from 'react'\nimport { useClient } from './api-provider'\nimport { MetaContext } from './meta-context'\nimport type { MetaData } from './meta-data'\nimport { keys } from './query-keys'\nimport { isRestored, ClientStartContext } from './start-cache/restored-state'\nimport { keepOnVersionChange } from './version-freeze'\n\n/**\n * The resource and view models. Refetches on window focus with `If-None-Match`, so an unchanged\n * `/meta` costs a 304, and the cached object keeps its identity. Once the server runs another Protobase version than\n * the page started with, it keeps the `/meta` it has and stops reading it (see `keepOnVersionChange`). Below the app's\n * `MetaGate`, `data` holds the resources of its sources too, as every page of the app reads them. A `/meta` from the start\n * cache is replaced by the first one read, whatever its version.\n */\nexport const useMeta = (): UseQueryResult<MetaData> => {\n const client = useClient()\n const queryClient = useQueryClient()\n const merged = useContext(MetaContext)\n const startedAt = useContext(ClientStartContext)\n const query = useQuery({\n queryKey: keys.meta,\n staleTime: 0,\n refetchOnWindowFocus: 'always',\n enabled: (current) => !current.state.data?.versionChange,\n queryFn: async (): Promise<MetaData> => {\n const previous = queryClient.getQueryData<MetaData>(keys.meta)\n const result = await client.meta(previous?.etag)\n if (result.status === 'unchanged') {\n if (!previous) throw new Error('The server answered 304 to a request without If-None-Match')\n return previous\n }\n // A cached `/meta` is from an earlier start, so the version this page started with is the first one it reads\n const state = queryClient.getQueryState(keys.meta)\n return keepOnVersionChange(state && isRestored(state, startedAt) ? undefined : previous, {\n etag: result.etag,\n appName: result.meta.appName,\n ...(result.meta.protobaseVersion && { protobaseVersion: result.meta.protobaseVersion }),\n ...(result.meta.appIcon && { appIcon: result.meta.appIcon }),\n resources: Object.fromEntries(result.meta.resources.map((model) => [model.name, model])),\n views: Object.fromEntries(result.meta.views.map((model) => [model.resource, model])),\n pages: Object.fromEntries((result.meta.pages ?? []).map((model) => [model.name, model])),\n ...(result.meta.account && { account: result.meta.account }),\n permissions: result.meta.permissions ?? {},\n ...(result.meta.userMenu && { userMenu: result.meta.userMenu }),\n ...(result.meta.signIn && { signIn: Object.fromEntries(result.meta.signIn.map((entry) => [entry.resource, entry])) }),\n ...(result.meta.bottomBar && { bottomBar: result.meta.bottomBar }),\n ...(result.meta.assistant && { assistant: result.meta.assistant }),\n ...(result.meta.runtime && { runtime: result.meta.runtime }),\n ...(result.meta.errorReporting && { errorReporting: result.meta.errorReporting }),\n ...(result.meta.maps && { maps: result.meta.maps }),\n ...(result.meta.notifications?.bell && { bell: true }),\n ...(result.meta.status && { status: true }),\n ...(result.meta.calls && { calls: true }),\n ...(result.meta.locale && { locale: result.meta.locale }),\n ...(result.meta.texts && { texts: result.meta.texts }),\n ...(result.meta.files && { files: result.meta.files }),\n ...(result.meta.plugins && { plugins: result.meta.plugins }),\n // The sources' own `/meta` is read below `MetaGate` (see `withSources`).\n ...(result.meta.sources && { sources: result.meta.sources.map((source) => ({ source, state: 'loading' as const })) }),\n })\n },\n })\n return useMemo(() => (merged && query.data ? ({ ...query, data: merged } as UseQueryResult<MetaData>) : query), [merged, query])\n}\n"],"mappings":"0tBAAA,IAAMoB,EAAc,GAAiBC,EAAK,OAAO,CAAC,CAAC,CAAC,YAAY,EAAIA,EAAK,MAAM,CAAC,EAMnEC,EAAY,GAOhBF,EANOG,EACX,QAAQ,uBAAwB,EAAE,CAAC,CACnC,QAAQ,qBAAsB,OAAO,CAAC,CACtC,QAAQ,MAAO,GAAG,CAAC,CACnB,KAAK,CAAC,CACN,YACe,GAASA,CAAI,wBCb3BG,EAAY,wBAOLC,MAAuB,CAClC,GAAM,CAAE,OAAM,gBAAiBC,GAAS,SAClCC,EAAWC,EAAK,MAAM,SACtBC,EAASH,EAAK,aAAaF,CAAS,EAG1C,OAFI,OAAO,WAAaE,EAAK,aAAaA,EAAK,aAAaF,EAAW,EAAE,EACzE,EA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","useCallback","useRef","useMemo","useMemo","n","a","t","__toESM","require_react","require_jsx_runtime","useQueries","useQuery","useResourceClient","useViewedResource","fileNamed","cn","import_react","ofDocument","state","nonce","initial","useDocumentState","setState","update","next","linkAttribute","frameBridge","frameSandbox","frameCsp","scripts","frameNonce","byte","removed","frameDocument","page","html","element","policy","referrer","bridge","rounding","nextFrameHeight","previous","viewport","height","frameBox","size","maxHeight","frameMessage","frame","event","data","links","import_jsx_runtime","noLinks","scrollToPlace","bars","top","HtmlFrame","shown","setHeight","shownAgain","setShownAgain","key","loads","receive","message","onLink","loaded","times","box","className","climbs","value","siblingReference","reference","unescaped","decoded","siblings","error","rewriteSrcset","parts","candidate","resolved","resolve","rewriteCssUrls","text","whole","externalUrl","url","sources","rewriteResources","set","attribute","resource","parse","referencedSiblings","found","sibling","siblingPage","contents","link","href","target","address","siblingsKey","FileReadError","status","useFileText","client","file","response","dataUrl","reader","reject","bytes","useSiblingContents","reads","files","read","index","useSiblingPage","siblingKey","contentsKey","ready"],"sources":["../../../src/app/file-viewers/document-state.ts","../../../src/app/file-viewers/frame-bridge.ts","../../../src/app/file-viewers/frame-policy.ts","../../../src/app/file-viewers/frame-document.ts","../../../src/app/file-viewers/frame-height.ts","../../../src/app/file-viewers/frame-messages.ts","../../../src/app/file-viewers/html-frame.tsx","../../../src/app/file-viewers/sibling-references.ts","../../../src/app/file-viewers/sibling-page.ts","../../../src/app/file-viewers/siblings-key.ts","../../../src/app/file-viewers/use-file-text.ts","../../../src/app/file-viewers/use-sibling-contents.ts","../../../src/app/file-viewers/use-sibling-page.ts"],"sourcesContent":["import { useCallback, useState } from 'react'\n\n/** A value of an `HtmlFrame` that belongs to the document it shows, by that document's `nonce`. */\nexport type DocumentState<T> = { nonce: string; value: T }\n\n/** `state`'s value for the document `nonce`; `initial` for another document, which starts again. */\nexport const ofDocument = <T>(state: DocumentState<T> | undefined, nonce: string, initial: T) => (state?.nonce === nonce ? state.value : initial)\n\n/** State that starts again at `initial` (a constant) each time the frame shows another document, `nonce`. */\nexport const useDocumentState = <T>(nonce: string, initial: T) => {\n const [state, setState] = useState<DocumentState<T>>()\n const update = useCallback((next: (value: T) => T) => setState((state) => ({ nonce, value: next(ofDocument(state, nonce, initial)) })), [nonce, initial])\n return [ofDocument(state, nonce, initial), update] as const\n}\n","/** The attribute an `HtmlFrame` page's link carries, the index of its target in the frame's `links`. */\nexport const linkAttribute = 'data-protobase-link'\n\n/**\n * The script an `HtmlFrame` runs in its page, the only one a page it does not trust runs. A click on a link carrying\n * `linkAttribute` posts its index to the app, with whether it asks for a new tab. A click on a link to a place on the\n * page (`#results`) moves the focus there and posts how far down the page it is, since the app's page scrolls rather\n * than the frame. A\n * click on any other link does nothing, so the page never leaves the frame. It also posts the page's height, so the\n * frame grows with it.\n */\nexport const frameBridge = `(() => {\n const post = (message) => parent.postMessage({ protobase: 'html-frame', ...message }, '*')\n const place = (hash) => {\n const name = decodeURIComponent(hash.slice(1))\n const target = name === '' || name === 'top' ? null : document.getElementById(name) ?? document.getElementsByName(name)[0]\n if (!target) return 0\n if (target.tabIndex < 0 && !target.hasAttribute('tabindex')) target.setAttribute('tabindex', '-1')\n target.focus({ preventScroll: true })\n return target.getBoundingClientRect().top + window.scrollY\n }\n const follow = (event) => {\n const link = event.target instanceof Element ? event.target.closest('a, area') : null\n if (!link) return\n event.preventDefault()\n const index = link.getAttribute('${linkAttribute}')\n const href = link.getAttribute('href') ?? ''\n if (index !== null) post({ link: Number(index), newTab: event.button === 1 || event.ctrlKey || event.metaKey || event.shiftKey })\n else if (href.startsWith('#') && event.button === 0) post({ scroll: place(href) })\n }\n document.addEventListener('click', follow, true)\n document.addEventListener('auxclick', (event) => event.button === 1 && follow(event), true)\n const height = () => post({ height: document.documentElement.getBoundingClientRect().height })\n new ResizeObserver(height).observe(document.documentElement)\n})()`\n","/**\n * What an `HtmlFrame`'s page may run: `'bridge'`, only the frame's own link script, for a page it does not trust, such\n * as an uploaded file; `'trusted-page'`, also the page's own inline scripts, for a page an app generates itself.\n */\nexport type FrameScripts = 'bridge' | 'trusted-page'\n\n/**\n * The frame's sandbox: scripts, so the link script runs, and nothing else. Never `allow-same-origin`, so the page has an\n * opaque origin and cannot reach the app's cookies, storage or DOM; no top navigation, forms or popups.\n */\nexport const frameSandbox = 'allow-scripts'\n\n/**\n * The page's Content-Security-Policy. With `'bridge'` only the script carrying `nonce` runs: the page's own scripts,\n * inline handlers and `javascript:` links do not. `'trusted-page'` runs inline scripts and so carries no nonce, which\n * would turn `'unsafe-inline'` off. Either way nothing loads from the network: images, media, styles and fonts come\n * from `data:` URLs, and nothing is fetched, framed or submitted.\n */\nexport const frameCsp = (scripts: FrameScripts, nonce: string) =>\n [\n \"default-src 'none'\",\n scripts === 'bridge' ? `script-src 'nonce-${nonce}'` : \"script-src 'unsafe-inline'\",\n 'img-src data:',\n 'media-src data:',\n \"style-src 'unsafe-inline' data:\",\n 'font-src data:',\n \"base-uri 'none'\",\n \"form-action 'none'\",\n ].join('; ')\n\n/** A fresh 128-bit nonce, as hex. */\nexport const frameNonce = () => Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join('')\n","import { frameBridge } from './frame-bridge'\nimport { frameCsp, type FrameScripts } from './frame-policy'\n\n// What a page could use to leave its policy or the frame: its own `http-equiv` (a refresh, another policy), a `<base>`,\n// and `<noscript>`, read as markup here but as text in the frame, where scripts run, so markup hidden in it would come\n// out after these were removed.\nconst removed = 'meta[http-equiv], base, noscript'\n\n/**\n * `html` as the page an `HtmlFrame` shows: parsed, cleared of `removed`, and opened with the frame's own policy, a\n * referrer policy that sends no address on, and the frame's link script carrying `nonce`. They are the first nodes of\n * `<head>`, put there in the parsed document, so the policy covers everything of the page, even a script written before\n * its `<html>`.\n */\nexport const frameDocument = (html: string, scripts: FrameScripts, nonce: string) => {\n const page = new DOMParser().parseFromString(html, 'text/html')\n for (const element of page.querySelectorAll(removed)) element.remove()\n\n const policy = page.createElement('meta')\n policy.httpEquiv = 'Content-Security-Policy'\n policy.content = frameCsp(scripts, nonce)\n const referrer = page.createElement('meta')\n referrer.name = 'referrer'\n referrer.content = 'no-referrer'\n const bridge = page.createElement('script')\n if (scripts === 'bridge') bridge.setAttribute('nonce', nonce)\n bridge.textContent = frameBridge\n page.head.prepend(policy, referrer, bridge)\n\n return `<!doctype html>${page.documentElement.outerHTML}`\n}\n","/**\n * How tall an `HtmlFrame` is for its page: `measured`, the height its page last reported, with the frame's own height\n * when it did, or `fixed`, for a page sized by the frame's viewport, such as one `100vh` tall or `height: 100%` with a\n * margin, which reports a taller page each time the frame takes its last height.\n */\nexport type FrameHeight = { kind: 'measured'; height: number; viewport: number } | { kind: 'fixed' }\n\n// Reported heights are rounded up to whole pixels.\nconst rounding = 1\n\n/**\n * The frame's height after its page reports `height` while the frame is `viewport` tall. A page whose height changed by\n * as much as the frame did since its last report is sized by the frame, and the frame stays fixed for it.\n */\nexport const nextFrameHeight = (previous: FrameHeight | undefined, height: number, viewport: number): FrameHeight => {\n if (previous?.kind === 'fixed') return previous\n if (previous && viewport !== previous.viewport && Math.abs(height - previous.height - (viewport - previous.viewport)) <= rounding) return { kind: 'fixed' }\n return { kind: 'measured', height, viewport }\n}\n\n/**\n * The frame's box: as tall as its page's measured height, or a fixed minimum while nothing is measured, for a page\n * measured 0 tall, and for a page sized by the frame. That page scrolls inside the frame, the one inner scroll box here:\n * the app's page cannot scroll content whose height depends on the frame's own.\n */\nexport const frameBox = (size: FrameHeight | undefined) =>\n size?.kind === 'measured' && size.height > 0 ? { style: { height: size.height } } : { className: 'min-h-[60vh]' }\n","/**\n * What an `HtmlFrame`'s page asks of the app: follow its link `index`, be as tall as `height` CSS pixels, or scroll to\n * the place `top` CSS pixels down the page.\n */\nexport type FrameMessage = { kind: 'link'; index: number; newTab: boolean } | { kind: 'height'; height: number } | { kind: 'scroll'; top: number }\n\n// Tall enough for a long report, short enough that a page cannot make the app's page endless.\nconst maxHeight = 100_000\n\n/**\n * The request a message event carries from the frame's own window `frame`, with a link index below `links`; `undefined`\n * for any other source or shape. Every sandboxed page's origin is `\"null\"`, so only the window itself tells them apart.\n */\nexport const frameMessage = (event: Pick<MessageEvent, 'source' | 'data'>, frame: Window | null | undefined, links: number): FrameMessage | undefined => {\n if (!frame || event.source !== frame) return\n const data: unknown = event.data\n if (typeof data !== 'object' || data === null || !('protobase' in data) || data.protobase !== 'html-frame') return\n if ('link' in data && Number.isInteger(data.link) && (data.link as number) >= 0 && (data.link as number) < links) {\n return { kind: 'link', index: data.link as number, newTab: 'newTab' in data && data.newTab === true }\n }\n if ('height' in data && typeof data.height === 'number' && Number.isFinite(data.height) && data.height >= 0) {\n return { kind: 'height', height: Math.min(Math.ceil(data.height), maxHeight) }\n }\n if ('scroll' in data && typeof data.scroll === 'number' && Number.isFinite(data.scroll)) {\n return { kind: 'scroll', top: Math.min(Math.max(Math.round(data.scroll), 0), maxHeight) }\n }\n return\n}\n","import { useEffect, useMemo, useRef } from 'react'\nimport { cn } from '../../lib/cn'\nimport { useDocumentState } from './document-state'\nimport type { ViewedFile } from './file-viewer'\nimport { frameDocument } from './frame-document'\nimport { frameBox, nextFrameHeight, type FrameHeight } from './frame-height'\nimport { frameMessage } from './frame-messages'\nimport { frameNonce, frameSandbox, type FrameScripts } from './frame-policy'\nimport type { FrameLink } from './sibling-page'\n\nconst noLinks: readonly never[] = []\n\n// Scrolls the app's page to the place `top` pixels down the page in `frame`, below the bars that stay at the top.\nconst scrollToPlace = (frame: HTMLIFrameElement, top: number) => {\n const bars = Number.parseFloat(getComputedStyle(document.documentElement).scrollPaddingTop) || 0\n window.scrollTo({ top: frame.getBoundingClientRect().top + window.scrollY + top - bars })\n}\n\ntype HtmlFrameProps<File extends ViewedFile> = {\n /** The page, a whole HTML document or a fragment. */\n html: string\n /** The frame's accessible name, such as the file's name. */\n title: string\n /** The targets of the page's links, by the index each carries (`useSiblingPage`). */\n links?: readonly FrameLink<File>[]\n /** Follows a link of the page; `newTab` when it was a middle or modified click. */\n onLink?: (link: FrameLink<File>, options: { newTab: boolean }) => void\n /**\n * `'bridge'` (the default) runs none of the page's own scripts, for a page you do not trust, such as an uploaded file;\n * `'trusted-page'` runs them, for a page your viewer generates itself. Either way the page cannot reach the app.\n */\n scripts?: FrameScripts\n className?: string\n}\n\n/**\n * A whole HTML page drawn in a sandboxed frame with an opaque origin: it cannot read the app's cookies, storage or DOM,\n * call its API as the user, load anything from the network or navigate the app's window. Its links reach the app only\n * as the index of one of `links`, which `onLink` follows. The frame is as tall as its page, so the app's page scrolls,\n * unless the page is sized by the frame (`FrameHeight`).\n */\nexport const HtmlFrame = <File extends ViewedFile>({ html, title, links = noLinks, onLink, scripts = 'bridge', className }: HtmlFrameProps<File>) => {\n const frame = useRef<HTMLIFrameElement>(null)\n const shown = useMemo(() => {\n const nonce = frameNonce()\n return { nonce, srcDoc: frameDocument(html, scripts, nonce) }\n }, [html, scripts])\n const [height, setHeight] = useDocumentState<FrameHeight | undefined>(shown.nonce, undefined)\n // A page that navigated its frame anyway is shown again once; doing so again leaves the frame empty, until another\n // document is shown.\n const [shownAgain, setShownAgain] = useDocumentState(shown.nonce, 0)\n const key = `${shown.nonce}:${shownAgain}`\n // The loads of the frame shown as `key`: its first is its page, any later one the page leaving it.\n const loads = useRef({ key, count: 0 })\n\n useEffect(() => {\n const receive = (event: MessageEvent) => {\n const message = frameMessage(event, frame.current?.contentWindow, links.length)\n const viewport = frame.current?.clientHeight\n if (message?.kind === 'height' && viewport !== undefined) setHeight((size) => nextFrameHeight(size, message.height, viewport))\n if (message?.kind === 'link') onLink?.(links[message.index]!, { newTab: message.newTab })\n if (message?.kind === 'scroll' && frame.current) scrollToPlace(frame.current, message.top)\n }\n window.addEventListener('message', receive)\n return () => window.removeEventListener('message', receive)\n }, [links, onLink, setHeight])\n\n const loaded = () => {\n if (loads.current.key !== key) loads.current = { key, count: 0 }\n loads.current.count += 1\n if (loads.current.count > 1) setShownAgain((times) => times + 1)\n }\n\n const box = frameBox(height)\n return (\n <iframe\n key={key}\n ref={frame}\n title={title}\n sandbox={frameSandbox}\n referrerPolicy=\"no-referrer\"\n // A video's own fullscreen control; a page that does not run its scripts can ask for nothing else.\n allow={scripts === 'bridge' ? 'fullscreen' : undefined}\n srcDoc={shownAgain > 1 ? '' : shown.srcDoc}\n onLoad={loaded}\n className={cn('block w-full border-0 bg-white', box.className, className)}\n style={box.style}\n />\n )\n}\n","import { fileNamed, type ViewedFile } from './file-viewer'\n\n// Whether a reference's path climbs out of its folder with a `..` segment.\nconst climbs = (value: string) => value.split(/[?#]/, 1)[0]!.split('/').includes('..')\n\n/**\n * The sibling a page's relative reference names, such as `shots/before.png` or `my%20chart.png`, by its file name\n * (`fileNamed`), as written or with its escapes read; none for an absolute or protocol-relative address, a path from\n * the root, a fragment, or a path that climbs out with `..`, written or escaped.\n */\nexport const siblingReference = <File extends ViewedFile>(siblings: readonly File[], reference: string) => {\n const value = reference.trim()\n const unescaped = decoded(value)\n if (climbs(value) || climbs(unescaped)) return\n return fileNamed(siblings, value) ?? fileNamed(siblings, unescaped)\n}\n\n// A reference with its escapes, such as `%20`, read; as it is when one is malformed.\nconst decoded = (value: string) => {\n try {\n return decodeURI(value)\n } catch (error) {\n if (error instanceof URIError) return value\n throw error\n }\n}\n\n/** `value` of a `srcset`, each candidate's address resolved on its own; a candidate `resolve` gives nothing for stays as written. */\nexport const rewriteSrcset = (value: string, resolve: (reference: string) => string | undefined) =>\n value\n .split(',')\n .map((candidate) => {\n const parts = /^(\\s*)(\\S+)([\\s\\S]*)$/.exec(candidate)\n const resolved = parts && resolve(parts[2]!)\n return parts && resolved ? `${parts[1]}${resolved}${parts[3]}` : candidate\n })\n .join(',')\n\n/** CSS `text` with each `url(...)` resolved; one `resolve` gives nothing for stays as written. */\nexport const rewriteCssUrls = (text: string, resolve: (reference: string) => string | undefined) =>\n text.replace(/url\\(\\s*(['\"]?)([^'\")]*)\\1\\s*\\)/gi, (whole, _quote: string, reference: string) => {\n const resolved = resolve(reference.trim())\n return resolved ? `url(\"${resolved}\")` : whole\n })\n\n/** An absolute `http:` or `https:` address as the URL parser reads it, else `undefined`, such as for `javascript:` or a relative path. */\nexport const externalUrl = (reference: string) => {\n if (!URL.canParse(reference)) return\n const url = new URL(reference)\n return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : undefined\n}\n","import type { ViewedFile } from './file-viewer'\nimport { linkAttribute } from './frame-bridge'\nimport { externalUrl, rewriteCssUrls, rewriteSrcset, siblingReference } from './sibling-references'\n\n/** Where a link of a page in an `HtmlFrame` leads: a sibling file, or an outside `http`/`https` address. */\nexport type FrameLink<File extends ViewedFile = ViewedFile> = { kind: 'file'; file: File } | { kind: 'external'; url: string }\n\n/** A page with its references to siblings resolved, and the targets of its links, which carry their index. */\nexport type SiblingPage<File extends ViewedFile = ViewedFile> = { html: string; links: FrameLink<File>[] }\n\n// The attributes that load a file into the page, by the elements they are on.\nconst sources = ['img[src]', 'source[src]', 'video[src]', 'audio[src]', 'track[src]', 'input[src]'].join(', ')\n\n// Each reference of `page` that loads a file, set to what `resource` gives for it; one it gives nothing for stays.\nconst rewriteResources = (page: Document, resource: (reference: string) => string | undefined) => {\n const set = (element: Element, attribute: string, value: string | undefined) => value !== undefined && element.setAttribute(attribute, value)\n for (const element of page.querySelectorAll(sources)) set(element, 'src', resource(element.getAttribute('src')!))\n for (const element of page.querySelectorAll('video[poster]')) set(element, 'poster', resource(element.getAttribute('poster')!))\n for (const element of page.querySelectorAll('img[srcset], source[srcset]')) set(element, 'srcset', rewriteSrcset(element.getAttribute('srcset')!, resource))\n for (const element of page.querySelectorAll('link[href]')) set(element, 'href', resource(element.getAttribute('href')!))\n for (const element of page.querySelectorAll('image[href]')) set(element, 'href', resource(element.getAttribute('href')!))\n for (const element of page.querySelectorAll('[style]')) set(element, 'style', rewriteCssUrls(element.getAttribute('style')!, resource))\n for (const element of page.querySelectorAll('style')) element.textContent = rewriteCssUrls(element.textContent, resource)\n}\n\nconst parse = (html: string) => new DOMParser().parseFromString(html, 'text/html')\n\n/** The siblings `html` loads as images, videos, sounds, styles or fonts, each once: those a page needs read to show. */\nexport const referencedSiblings = <File extends ViewedFile>(html: string, siblings: readonly File[]) => {\n const found = new Set<File>()\n rewriteResources(parse(html), (reference) => {\n const sibling = siblingReference(siblings, reference)\n if (sibling) found.add(sibling)\n return\n })\n return [...found]\n}\n\n/** The address a page's link shows for where it leads, for the browser's link preview and copy link; `undefined` keeps its own. */\nexport type LinkAddress<File extends ViewedFile = ViewedFile> = (link: FrameLink<File>) => string | undefined\n\n/**\n * `html` with each relative reference to a sibling resolved: one that loads a file to the `data:` URL `contents` holds\n * by its stored `uri`, a link to a sibling or to an outside `http`/`https` address to an entry of `links`, showing the\n * address `address` gives it. A reference to no sibling, or to one `contents` lacks, stays as written; a link to\n * anywhere else, such as `javascript:`, loses its address. A link to a place on the page (`#top`) stays.\n */\nexport const siblingPage = <File extends ViewedFile>(html: string, siblings: readonly File[], contents: ReadonlyMap<string, string>, address?: LinkAddress<File>): SiblingPage<File> => {\n const page = parse(html)\n for (const element of page.querySelectorAll(`[${linkAttribute}]`)) element.removeAttribute(linkAttribute)\n rewriteResources(page, (reference) => {\n const sibling = siblingReference(siblings, reference)\n return sibling && contents.get(sibling.uri)\n })\n\n const links: FrameLink<File>[] = []\n for (const link of page.querySelectorAll('a[href], area[href]')) {\n const href = link.getAttribute('href')!\n if (href.startsWith('#')) continue\n link.removeAttribute('target')\n const sibling = siblingReference(siblings, href)\n const url = sibling ? undefined : externalUrl(href)\n if (!sibling && !url) {\n link.removeAttribute('href')\n continue\n }\n const target: FrameLink<File> = sibling ? { kind: 'file', file: sibling } : { kind: 'external', url: url! }\n const shown = address?.(target)\n if (shown !== undefined) link.setAttribute('href', shown)\n link.setAttribute(linkAttribute, String(links.length))\n links.push(target)\n }\n return { html: `<!doctype html>${page.documentElement.outerHTML}`, links }\n}\n","import type { ViewedFile } from './file-viewer'\n\n/**\n * A key that changes when any of `siblings` does: its stored uri, and the record key and file field a sibling carries\n * (`SiblingFile`), which its link's address names. A missing key or field is `null`.\n */\nexport const siblingsKey = <File extends ViewedFile>(siblings: readonly File[]) =>\n JSON.stringify(siblings.map((sibling) => [sibling.uri, 'key' in sibling ? sibling.key : null, 'field' in sibling ? sibling.field : null]))\n","import { useQuery } from '@tanstack/react-query'\nimport { useResourceClient } from '../../data/api-provider'\nimport type { ViewedFile } from './file-viewer'\nimport { useViewedResource } from './viewed-resource'\n\n/** A file that could not be read, with the status its link answered. */\nexport class FileReadError extends Error {\n override name = 'FileReadError'\n constructor(readonly status: number) {\n super(`The file could not be read: its link answered ${status}`)\n }\n}\n\n/**\n * The text of a file a viewer shows, read once and kept while the file is the same: a TanStack Query result keyed by\n * its resource and stored `uri`, as the link changes each time it is signed. Parse JSON from `data` yourself. It reads\n * from the API that serves the record, which sends the bytes itself whatever store holds them or wherever the file's\n * link points, up to 10 MB; a larger file fails with a 403.\n */\nexport const useFileText = (file: ViewedFile) => {\n const resource = useViewedResource()\n const client = useResourceClient(resource)\n return useQuery({\n queryKey: ['file-text', resource, file.uri],\n staleTime: Infinity,\n queryFn: async () => {\n const response = await fetch(client.fileReadUrl(resource, file))\n if (!response.ok) throw new FileReadError(response.status)\n return response.text()\n },\n })\n}\n","import { useQueries } from '@tanstack/react-query'\nimport { useResourceClient } from '../../data/api-provider'\nimport type { ViewedFile } from './file-viewer'\nimport { FileReadError } from './use-file-text'\nimport { useViewedResource } from './viewed-resource'\n\n// The bytes as a `data:` URL of the file's own type: a sandboxed page cannot load the app's `blob:` URLs, and the URL\n// holds the bytes alone, no signed link that would open the file elsewhere.\nconst dataUrl = (bytes: Blob) =>\n new Promise<string>((resolve, reject) => {\n const reader = new FileReader()\n reader.onload = () => resolve(reader.result as string)\n reader.onerror = () => reject(reader.error)\n reader.readAsDataURL(bytes)\n })\n\n/**\n * The contents of `files` as `data:` URLs by their stored `uri`, each read once from the API that serves the viewed\n * record, with the user's own rights, as `useFileText` reads, up to 10 MB each; `ready` once every read has answered. A\n * file that could not be read is left out, so what refers to it stays as written.\n */\nexport const useSiblingContents = (files: readonly ViewedFile[]) => {\n const resource = useViewedResource()\n const client = useResourceClient(resource)\n const reads = useQueries({\n queries: files.map((file) => ({\n queryKey: ['file-data-url', resource, file.uri],\n staleTime: Infinity,\n retry: false,\n queryFn: async () => {\n const response = await fetch(client.fileReadUrl(resource, file))\n if (!response.ok) throw new FileReadError(response.status)\n return dataUrl(new Blob([await response.arrayBuffer()], { type: file.type }))\n },\n })),\n })\n const contents = new Map<string, string>()\n reads.forEach((read, index) => read.data !== undefined && contents.set(files[index]!.uri, read.data))\n return { contents, ready: reads.every((read) => !read.isPending) }\n}\n","import { useMemo } from 'react'\nimport type { ViewedFile } from './file-viewer'\nimport { referencedSiblings, siblingPage, type LinkAddress, type SiblingPage } from './sibling-page'\nimport { siblingsKey } from './siblings-key'\nimport { useSiblingContents } from './use-sibling-contents'\n\n/**\n * `html`, a page a file viewer shows, with its relative references resolved to `siblings` (`siblingPage`), for an\n * `HtmlFrame`: the images, videos and styles it names read as `data:` URLs, its links to siblings and outside addresses\n * in `links`, each showing the address `address` gives it. `undefined` while `html` or those reads are pending. Use it\n * inside a file viewer, which reads them from the API that serves the viewed record.\n */\nexport const useSiblingPage = <File extends ViewedFile>(html: string | undefined, siblings: readonly File[], address?: LinkAddress<File>): SiblingPage<File> | undefined => {\n // A viewer's siblings are a new list each render: their key, and the contents read, say when they changed.\n const siblingKey = siblingsKey(siblings)\n const named = useMemo(() => (html === undefined ? [] : referencedSiblings(html, siblings)), [html, siblingKey])\n const { contents, ready } = useSiblingContents(named)\n const contentsKey = [...contents.keys()].join('\\n')\n return useMemo(() => (html === undefined || !ready ? undefined : siblingPage(html, siblings, contents, address)), [html, siblingKey, ready, contentsKey, address])\n}\n"],"mappings":"2vBAMakB,GAAiB,EAAqC,EAAe,IAAgBC,GAAO,QAAUC,EAAQD,EAAM,MAAQE,EAG5HC,GAAuB,EAAe,IAAe,CAChE,GAAM,CAACH,EAAOI,IAAA,EAAYvB,E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AAMF,EAAO,YAAYf,EAAUgB,CAAI,CAAC,EAC/D,GAAI,CAACC,EAAS,GAAI,MAAM,IAAIL,EAAcK,EAAS,MAAM,EACzD,OAAOC,EAAQ,IAAI,KAAK,CAAC,MAAMD,EAAS,YAAY,CAAC,EAAG,CAAE,KAAMD,EAAK,IAAK,CAAC,CAAC,CAC9E,CACF,EAAE,CACJ,CAAC,EACKV,EAAW,IAAI,IAErB,OADAiB,EAAM,SAAS,EAAM,IAAUE,EAAK,OAAS,IAAA,IAAanB,EAAS,IAAIkB,EAAME,EAAM,CAAE,IAAKD,EAAK,IAAI,CAAC,EAC7F,CAAE,WAAU,MAAOF,EAAM,MAAO,GAAS,CAACE,EAAK,SAAS,CAAE,CACnE,EC3BaE,GAA2C,EAA0B,EAA2B,IAA+D,CAE1K,IAAMC,EAAajB,EAAY3B,CAAQ,EAEjC,CAAE,WAAU,SAAUsC,GADtB,EAAQjH,EAAAA,QAAAA,KAAegC,IAAS,IAAA,GAAY,CAAC,EAAI6D,EAAmB7D,EAAM2C,CAAQ,EAAI,CAAC3C,EAAMuF,CAAU,CAC9D,CAAK,EAC9CC,EAAc,CAAC,GAAGvB,EAAS,KAAK,CAAC,CAAC,CAAC,KAAK;CAAI,EAClD,OAAA,EAAOjG,EAAAA,QAAAA,KAAegC,IAAS,IAAA,IAAa,CAACyF,EAAQ,IAAA,GAAYzB,EAAYhE,EAAM2C,EAAUsB,EAAUI,CAAO,EAAI,CAACrE,EAAMuF,EAAYE,EAAOD,EAAanB,CAAO,CAAC,CACnK","debugId":"a2ba21be-4f3e-4055-900f-cdf4945c9db7"}
|
|
1
|
+
{"version":3,"file":"use-sibling-page-BJ81HcOP.js","names":["useState","useCallback","useRef","useMemo","useMemo","n","a","t","__toESM","require_react","require_jsx_runtime","useQueries","useQuery","useResourceClient","fileNamed","useViewedResource","cn","import_react","ofDocument","state","nonce","initial","useDocumentState","setState","update","next","linkAttribute","frameBridge","frameSandbox","frameCsp","scripts","frameNonce","byte","removed","frameDocument","page","html","element","policy","referrer","bridge","rounding","nextFrameHeight","previous","viewport","height","frameBox","size","maxHeight","frameMessage","frame","event","data","links","import_jsx_runtime","noLinks","scrollToPlace","bars","top","HtmlFrame","shown","setHeight","shownAgain","setShownAgain","key","loads","receive","message","onLink","loaded","times","box","className","climbs","value","siblingReference","reference","unescaped","decoded","siblings","error","rewriteSrcset","parts","candidate","resolved","resolve","rewriteCssUrls","text","whole","externalUrl","url","sources","rewriteResources","set","attribute","resource","parse","referencedSiblings","found","sibling","siblingPage","contents","link","href","target","address","siblingsKey","FileReadError","status","useFileText","client","file","response","dataUrl","reader","reject","bytes","useSiblingContents","reads","files","read","index","useSiblingPage","siblingKey","contentsKey","ready"],"sources":["../../../src/app/file-viewers/document-state.ts","../../../src/app/file-viewers/frame-bridge.ts","../../../src/app/file-viewers/frame-policy.ts","../../../src/app/file-viewers/frame-document.ts","../../../src/app/file-viewers/frame-height.ts","../../../src/app/file-viewers/frame-messages.ts","../../../src/app/file-viewers/html-frame.tsx","../../../src/app/file-viewers/sibling-references.ts","../../../src/app/file-viewers/sibling-page.ts","../../../src/app/file-viewers/siblings-key.ts","../../../src/app/file-viewers/use-file-text.ts","../../../src/app/file-viewers/use-sibling-contents.ts","../../../src/app/file-viewers/use-sibling-page.ts"],"sourcesContent":["import { useCallback, useState } from 'react'\n\n/** A value of an `HtmlFrame` that belongs to the document it shows, by that document's `nonce`. */\nexport type DocumentState<T> = { nonce: string; value: T }\n\n/** `state`'s value for the document `nonce`; `initial` for another document, which starts again. */\nexport const ofDocument = <T>(state: DocumentState<T> | undefined, nonce: string, initial: T) => (state?.nonce === nonce ? state.value : initial)\n\n/** State that starts again at `initial` (a constant) each time the frame shows another document, `nonce`. */\nexport const useDocumentState = <T>(nonce: string, initial: T) => {\n const [state, setState] = useState<DocumentState<T>>()\n const update = useCallback((next: (value: T) => T) => setState((state) => ({ nonce, value: next(ofDocument(state, nonce, initial)) })), [nonce, initial])\n return [ofDocument(state, nonce, initial), update] as const\n}\n","/** The attribute an `HtmlFrame` page's link carries, the index of its target in the frame's `links`. */\nexport const linkAttribute = 'data-protobase-link'\n\n/**\n * The script an `HtmlFrame` runs in its page, the only one a page it does not trust runs. A click on a link carrying\n * `linkAttribute` posts its index to the app, with whether it asks for a new tab. A click on a link to a place on the\n * page (`#results`) moves the focus there and posts how far down the page it is, since the app's page scrolls rather\n * than the frame. A\n * click on any other link does nothing, so the page never leaves the frame. It also posts the page's height, so the\n * frame grows with it.\n */\nexport const frameBridge = `(() => {\n const post = (message) => parent.postMessage({ protobase: 'html-frame', ...message }, '*')\n const place = (hash) => {\n const name = decodeURIComponent(hash.slice(1))\n const target = name === '' || name === 'top' ? null : document.getElementById(name) ?? document.getElementsByName(name)[0]\n if (!target) return 0\n if (target.tabIndex < 0 && !target.hasAttribute('tabindex')) target.setAttribute('tabindex', '-1')\n target.focus({ preventScroll: true })\n return target.getBoundingClientRect().top + window.scrollY\n }\n const follow = (event) => {\n const link = event.target instanceof Element ? event.target.closest('a, area') : null\n if (!link) return\n event.preventDefault()\n const index = link.getAttribute('${linkAttribute}')\n const href = link.getAttribute('href') ?? ''\n if (index !== null) post({ link: Number(index), newTab: event.button === 1 || event.ctrlKey || event.metaKey || event.shiftKey })\n else if (href.startsWith('#') && event.button === 0) post({ scroll: place(href) })\n }\n document.addEventListener('click', follow, true)\n document.addEventListener('auxclick', (event) => event.button === 1 && follow(event), true)\n const height = () => post({ height: document.documentElement.getBoundingClientRect().height })\n new ResizeObserver(height).observe(document.documentElement)\n})()`\n","/**\n * What an `HtmlFrame`'s page may run: `'bridge'`, only the frame's own link script, for a page it does not trust, such\n * as an uploaded file; `'trusted-page'`, also the page's own inline scripts, for a page an app generates itself.\n */\nexport type FrameScripts = 'bridge' | 'trusted-page'\n\n/**\n * The frame's sandbox: scripts, so the link script runs, and nothing else. Never `allow-same-origin`, so the page has an\n * opaque origin and cannot reach the app's cookies, storage or DOM; no top navigation, forms or popups.\n */\nexport const frameSandbox = 'allow-scripts'\n\n/**\n * The page's Content-Security-Policy. With `'bridge'` only the script carrying `nonce` runs: the page's own scripts,\n * inline handlers and `javascript:` links do not. `'trusted-page'` runs inline scripts and so carries no nonce, which\n * would turn `'unsafe-inline'` off. Either way nothing loads from the network: images, media, styles and fonts come\n * from `data:` URLs, and nothing is fetched, framed or submitted.\n */\nexport const frameCsp = (scripts: FrameScripts, nonce: string) =>\n [\n \"default-src 'none'\",\n scripts === 'bridge' ? `script-src 'nonce-${nonce}'` : \"script-src 'unsafe-inline'\",\n 'img-src data:',\n 'media-src data:',\n \"style-src 'unsafe-inline' data:\",\n 'font-src data:',\n \"base-uri 'none'\",\n \"form-action 'none'\",\n ].join('; ')\n\n/** A fresh 128-bit nonce, as hex. */\nexport const frameNonce = () => Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join('')\n","import { frameBridge } from './frame-bridge'\nimport { frameCsp, type FrameScripts } from './frame-policy'\n\n// What a page could use to leave its policy or the frame: its own `http-equiv` (a refresh, another policy), a `<base>`,\n// and `<noscript>`, read as markup here but as text in the frame, where scripts run, so markup hidden in it would come\n// out after these were removed.\nconst removed = 'meta[http-equiv], base, noscript'\n\n/**\n * `html` as the page an `HtmlFrame` shows: parsed, cleared of `removed`, and opened with the frame's own policy, a\n * referrer policy that sends no address on, and the frame's link script carrying `nonce`. They are the first nodes of\n * `<head>`, put there in the parsed document, so the policy covers everything of the page, even a script written before\n * its `<html>`.\n */\nexport const frameDocument = (html: string, scripts: FrameScripts, nonce: string) => {\n const page = new DOMParser().parseFromString(html, 'text/html')\n for (const element of page.querySelectorAll(removed)) element.remove()\n\n const policy = page.createElement('meta')\n policy.httpEquiv = 'Content-Security-Policy'\n policy.content = frameCsp(scripts, nonce)\n const referrer = page.createElement('meta')\n referrer.name = 'referrer'\n referrer.content = 'no-referrer'\n const bridge = page.createElement('script')\n if (scripts === 'bridge') bridge.setAttribute('nonce', nonce)\n bridge.textContent = frameBridge\n page.head.prepend(policy, referrer, bridge)\n\n return `<!doctype html>${page.documentElement.outerHTML}`\n}\n","/**\n * How tall an `HtmlFrame` is for its page: `measured`, the height its page last reported, with the frame's own height\n * when it did, or `fixed`, for a page sized by the frame's viewport, such as one `100vh` tall or `height: 100%` with a\n * margin, which reports a taller page each time the frame takes its last height.\n */\nexport type FrameHeight = { kind: 'measured'; height: number; viewport: number } | { kind: 'fixed' }\n\n// Reported heights are rounded up to whole pixels.\nconst rounding = 1\n\n/**\n * The frame's height after its page reports `height` while the frame is `viewport` tall. A page whose height changed by\n * as much as the frame did since its last report is sized by the frame, and the frame stays fixed for it.\n */\nexport const nextFrameHeight = (previous: FrameHeight | undefined, height: number, viewport: number): FrameHeight => {\n if (previous?.kind === 'fixed') return previous\n if (previous && viewport !== previous.viewport && Math.abs(height - previous.height - (viewport - previous.viewport)) <= rounding) return { kind: 'fixed' }\n return { kind: 'measured', height, viewport }\n}\n\n/**\n * The frame's box: as tall as its page's measured height, or a fixed minimum while nothing is measured, for a page\n * measured 0 tall, and for a page sized by the frame. That page scrolls inside the frame, the one inner scroll box here:\n * the app's page cannot scroll content whose height depends on the frame's own.\n */\nexport const frameBox = (size: FrameHeight | undefined) =>\n size?.kind === 'measured' && size.height > 0 ? { style: { height: size.height } } : { className: 'min-h-[60vh]' }\n","/**\n * What an `HtmlFrame`'s page asks of the app: follow its link `index`, be as tall as `height` CSS pixels, or scroll to\n * the place `top` CSS pixels down the page.\n */\nexport type FrameMessage = { kind: 'link'; index: number; newTab: boolean } | { kind: 'height'; height: number } | { kind: 'scroll'; top: number }\n\n// Tall enough for a long report, short enough that a page cannot make the app's page endless.\nconst maxHeight = 100_000\n\n/**\n * The request a message event carries from the frame's own window `frame`, with a link index below `links`; `undefined`\n * for any other source or shape. Every sandboxed page's origin is `\"null\"`, so only the window itself tells them apart.\n */\nexport const frameMessage = (event: Pick<MessageEvent, 'source' | 'data'>, frame: Window | null | undefined, links: number): FrameMessage | undefined => {\n if (!frame || event.source !== frame) return\n const data: unknown = event.data\n if (typeof data !== 'object' || data === null || !('protobase' in data) || data.protobase !== 'html-frame') return\n if ('link' in data && Number.isInteger(data.link) && (data.link as number) >= 0 && (data.link as number) < links) {\n return { kind: 'link', index: data.link as number, newTab: 'newTab' in data && data.newTab === true }\n }\n if ('height' in data && typeof data.height === 'number' && Number.isFinite(data.height) && data.height >= 0) {\n return { kind: 'height', height: Math.min(Math.ceil(data.height), maxHeight) }\n }\n if ('scroll' in data && typeof data.scroll === 'number' && Number.isFinite(data.scroll)) {\n return { kind: 'scroll', top: Math.min(Math.max(Math.round(data.scroll), 0), maxHeight) }\n }\n return\n}\n","import { useEffect, useMemo, useRef } from 'react'\nimport { cn } from '../../lib/cn'\nimport { useDocumentState } from './document-state'\nimport type { ViewedFile } from './file-viewer'\nimport { frameDocument } from './frame-document'\nimport { frameBox, nextFrameHeight, type FrameHeight } from './frame-height'\nimport { frameMessage } from './frame-messages'\nimport { frameNonce, frameSandbox, type FrameScripts } from './frame-policy'\nimport type { FrameLink } from './sibling-page'\n\nconst noLinks: readonly never[] = []\n\n// Scrolls the app's page to the place `top` pixels down the page in `frame`, below the bars that stay at the top.\nconst scrollToPlace = (frame: HTMLIFrameElement, top: number) => {\n const bars = Number.parseFloat(getComputedStyle(document.documentElement).scrollPaddingTop) || 0\n window.scrollTo({ top: frame.getBoundingClientRect().top + window.scrollY + top - bars })\n}\n\ntype HtmlFrameProps<File extends ViewedFile> = {\n /** The page, a whole HTML document or a fragment. */\n html: string\n /** The frame's accessible name, such as the file's name. */\n title: string\n /** The targets of the page's links, by the index each carries (`useSiblingPage`). */\n links?: readonly FrameLink<File>[]\n /** Follows a link of the page; `newTab` when it was a middle or modified click. */\n onLink?: (link: FrameLink<File>, options: { newTab: boolean }) => void\n /**\n * `'bridge'` (the default) runs none of the page's own scripts, for a page you do not trust, such as an uploaded file;\n * `'trusted-page'` runs them, for a page your viewer generates itself. Either way the page cannot reach the app.\n */\n scripts?: FrameScripts\n className?: string\n}\n\n/**\n * A whole HTML page drawn in a sandboxed frame with an opaque origin: it cannot read the app's cookies, storage or DOM,\n * call its API as the user, load anything from the network or navigate the app's window. Its links reach the app only\n * as the index of one of `links`, which `onLink` follows. The frame is as tall as its page, so the app's page scrolls,\n * unless the page is sized by the frame (`FrameHeight`).\n */\nexport const HtmlFrame = <File extends ViewedFile>({ html, title, links = noLinks, onLink, scripts = 'bridge', className }: HtmlFrameProps<File>) => {\n const frame = useRef<HTMLIFrameElement>(null)\n const shown = useMemo(() => {\n const nonce = frameNonce()\n return { nonce, srcDoc: frameDocument(html, scripts, nonce) }\n }, [html, scripts])\n const [height, setHeight] = useDocumentState<FrameHeight | undefined>(shown.nonce, undefined)\n // A page that navigated its frame anyway is shown again once; doing so again leaves the frame empty, until another\n // document is shown.\n const [shownAgain, setShownAgain] = useDocumentState(shown.nonce, 0)\n const key = `${shown.nonce}:${shownAgain}`\n // The loads of the frame shown as `key`: its first is its page, any later one the page leaving it.\n const loads = useRef({ key, count: 0 })\n\n useEffect(() => {\n const receive = (event: MessageEvent) => {\n const message = frameMessage(event, frame.current?.contentWindow, links.length)\n const viewport = frame.current?.clientHeight\n if (message?.kind === 'height' && viewport !== undefined) setHeight((size) => nextFrameHeight(size, message.height, viewport))\n if (message?.kind === 'link') onLink?.(links[message.index]!, { newTab: message.newTab })\n if (message?.kind === 'scroll' && frame.current) scrollToPlace(frame.current, message.top)\n }\n window.addEventListener('message', receive)\n return () => window.removeEventListener('message', receive)\n }, [links, onLink, setHeight])\n\n const loaded = () => {\n if (loads.current.key !== key) loads.current = { key, count: 0 }\n loads.current.count += 1\n if (loads.current.count > 1) setShownAgain((times) => times + 1)\n }\n\n const box = frameBox(height)\n return (\n <iframe\n key={key}\n ref={frame}\n title={title}\n sandbox={frameSandbox}\n referrerPolicy=\"no-referrer\"\n // A video's own fullscreen control; a page that does not run its scripts can ask for nothing else.\n allow={scripts === 'bridge' ? 'fullscreen' : undefined}\n srcDoc={shownAgain > 1 ? '' : shown.srcDoc}\n onLoad={loaded}\n className={cn('block w-full border-0 bg-white', box.className, className)}\n style={box.style}\n />\n )\n}\n","import { fileNamed, type ViewedFile } from './file-viewer'\n\n// Whether a reference's path climbs out of its folder with a `..` segment.\nconst climbs = (value: string) => value.split(/[?#]/, 1)[0]!.split('/').includes('..')\n\n/**\n * The sibling a page's relative reference names, such as `shots/before.png` or `my%20chart.png`, by its file name\n * (`fileNamed`), as written or with its escapes read; none for an absolute or protocol-relative address, a path from\n * the root, a fragment, or a path that climbs out with `..`, written or escaped.\n */\nexport const siblingReference = <File extends ViewedFile>(siblings: readonly File[], reference: string) => {\n const value = reference.trim()\n const unescaped = decoded(value)\n if (climbs(value) || climbs(unescaped)) return\n return fileNamed(siblings, value) ?? fileNamed(siblings, unescaped)\n}\n\n// A reference with its escapes, such as `%20`, read; as it is when one is malformed.\nconst decoded = (value: string) => {\n try {\n return decodeURI(value)\n } catch (error) {\n if (error instanceof URIError) return value\n throw error\n }\n}\n\n/** `value` of a `srcset`, each candidate's address resolved on its own; a candidate `resolve` gives nothing for stays as written. */\nexport const rewriteSrcset = (value: string, resolve: (reference: string) => string | undefined) =>\n value\n .split(',')\n .map((candidate) => {\n const parts = /^(\\s*)(\\S+)([\\s\\S]*)$/.exec(candidate)\n const resolved = parts && resolve(parts[2]!)\n return parts && resolved ? `${parts[1]}${resolved}${parts[3]}` : candidate\n })\n .join(',')\n\n/** CSS `text` with each `url(...)` resolved; one `resolve` gives nothing for stays as written. */\nexport const rewriteCssUrls = (text: string, resolve: (reference: string) => string | undefined) =>\n text.replace(/url\\(\\s*(['\"]?)([^'\")]*)\\1\\s*\\)/gi, (whole, _quote: string, reference: string) => {\n const resolved = resolve(reference.trim())\n return resolved ? `url(\"${resolved}\")` : whole\n })\n\n/** An absolute `http:` or `https:` address as the URL parser reads it, else `undefined`, such as for `javascript:` or a relative path. */\nexport const externalUrl = (reference: string) => {\n if (!URL.canParse(reference)) return\n const url = new URL(reference)\n return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : undefined\n}\n","import type { ViewedFile } from './file-viewer'\nimport { linkAttribute } from './frame-bridge'\nimport { externalUrl, rewriteCssUrls, rewriteSrcset, siblingReference } from './sibling-references'\n\n/** Where a link of a page in an `HtmlFrame` leads: a sibling file, or an outside `http`/`https` address. */\nexport type FrameLink<File extends ViewedFile = ViewedFile> = { kind: 'file'; file: File } | { kind: 'external'; url: string }\n\n/** A page with its references to siblings resolved, and the targets of its links, which carry their index. */\nexport type SiblingPage<File extends ViewedFile = ViewedFile> = { html: string; links: FrameLink<File>[] }\n\n// The attributes that load a file into the page, by the elements they are on.\nconst sources = ['img[src]', 'source[src]', 'video[src]', 'audio[src]', 'track[src]', 'input[src]'].join(', ')\n\n// Each reference of `page` that loads a file, set to what `resource` gives for it; one it gives nothing for stays.\nconst rewriteResources = (page: Document, resource: (reference: string) => string | undefined) => {\n const set = (element: Element, attribute: string, value: string | undefined) => value !== undefined && element.setAttribute(attribute, value)\n for (const element of page.querySelectorAll(sources)) set(element, 'src', resource(element.getAttribute('src')!))\n for (const element of page.querySelectorAll('video[poster]')) set(element, 'poster', resource(element.getAttribute('poster')!))\n for (const element of page.querySelectorAll('img[srcset], source[srcset]')) set(element, 'srcset', rewriteSrcset(element.getAttribute('srcset')!, resource))\n for (const element of page.querySelectorAll('link[href]')) set(element, 'href', resource(element.getAttribute('href')!))\n for (const element of page.querySelectorAll('image[href]')) set(element, 'href', resource(element.getAttribute('href')!))\n for (const element of page.querySelectorAll('[style]')) set(element, 'style', rewriteCssUrls(element.getAttribute('style')!, resource))\n for (const element of page.querySelectorAll('style')) element.textContent = rewriteCssUrls(element.textContent, resource)\n}\n\nconst parse = (html: string) => new DOMParser().parseFromString(html, 'text/html')\n\n/** The siblings `html` loads as images, videos, sounds, styles or fonts, each once: those a page needs read to show. */\nexport const referencedSiblings = <File extends ViewedFile>(html: string, siblings: readonly File[]) => {\n const found = new Set<File>()\n rewriteResources(parse(html), (reference) => {\n const sibling = siblingReference(siblings, reference)\n if (sibling) found.add(sibling)\n return\n })\n return [...found]\n}\n\n/** The address a page's link shows for where it leads, for the browser's link preview and copy link; `undefined` keeps its own. */\nexport type LinkAddress<File extends ViewedFile = ViewedFile> = (link: FrameLink<File>) => string | undefined\n\n/**\n * `html` with each relative reference to a sibling resolved: one that loads a file to the `data:` URL `contents` holds\n * by its stored `uri`, a link to a sibling or to an outside `http`/`https` address to an entry of `links`, showing the\n * address `address` gives it. A reference to no sibling, or to one `contents` lacks, stays as written; a link to\n * anywhere else, such as `javascript:`, loses its address. A link to a place on the page (`#top`) stays.\n */\nexport const siblingPage = <File extends ViewedFile>(html: string, siblings: readonly File[], contents: ReadonlyMap<string, string>, address?: LinkAddress<File>): SiblingPage<File> => {\n const page = parse(html)\n for (const element of page.querySelectorAll(`[${linkAttribute}]`)) element.removeAttribute(linkAttribute)\n rewriteResources(page, (reference) => {\n const sibling = siblingReference(siblings, reference)\n return sibling && contents.get(sibling.uri)\n })\n\n const links: FrameLink<File>[] = []\n for (const link of page.querySelectorAll('a[href], area[href]')) {\n const href = link.getAttribute('href')!\n if (href.startsWith('#')) continue\n link.removeAttribute('target')\n const sibling = siblingReference(siblings, href)\n const url = sibling ? undefined : externalUrl(href)\n if (!sibling && !url) {\n link.removeAttribute('href')\n continue\n }\n const target: FrameLink<File> = sibling ? { kind: 'file', file: sibling } : { kind: 'external', url: url! }\n const shown = address?.(target)\n if (shown !== undefined) link.setAttribute('href', shown)\n link.setAttribute(linkAttribute, String(links.length))\n links.push(target)\n }\n return { html: `<!doctype html>${page.documentElement.outerHTML}`, links }\n}\n","import type { ViewedFile } from './file-viewer'\n\n/**\n * A key that changes when any of `siblings` does: its stored uri, and the record key and file field a sibling carries\n * (`SiblingFile`), which its link's address names. A missing key or field is `null`.\n */\nexport const siblingsKey = <File extends ViewedFile>(siblings: readonly File[]) =>\n JSON.stringify(siblings.map((sibling) => [sibling.uri, 'key' in sibling ? sibling.key : null, 'field' in sibling ? sibling.field : null]))\n","import { useQuery } from '@tanstack/react-query'\nimport { useResourceClient } from '../../data/api-provider'\nimport type { ViewedFile } from './file-viewer'\nimport { useViewedResource } from './viewed-resource'\n\n/** A file that could not be read, with the status its link answered. */\nexport class FileReadError extends Error {\n override name = 'FileReadError'\n constructor(readonly status: number) {\n super(`The file could not be read: its link answered ${status}`)\n }\n}\n\n/**\n * The text of a file a viewer shows, read once and kept while the file is the same: a TanStack Query result keyed by\n * its resource and stored `uri`, as the link changes each time it is signed. Parse JSON from `data` yourself. It reads\n * from the API that serves the record, which sends the bytes itself whatever store holds them or wherever the file's\n * link points, up to 10 MB; a larger file fails with a 403.\n */\nexport const useFileText = (file: ViewedFile) => {\n const resource = useViewedResource()\n const client = useResourceClient(resource)\n return useQuery({\n queryKey: ['file-text', resource, file.uri],\n staleTime: Infinity,\n queryFn: async () => {\n const response = await fetch(client.fileReadUrl(resource, file))\n if (!response.ok) throw new FileReadError(response.status)\n return response.text()\n },\n })\n}\n","import { useQueries } from '@tanstack/react-query'\nimport { useResourceClient } from '../../data/api-provider'\nimport type { ViewedFile } from './file-viewer'\nimport { FileReadError } from './use-file-text'\nimport { useViewedResource } from './viewed-resource'\n\n// The bytes as a `data:` URL of the file's own type: a sandboxed page cannot load the app's `blob:` URLs, and the URL\n// holds the bytes alone, no signed link that would open the file elsewhere.\nconst dataUrl = (bytes: Blob) =>\n new Promise<string>((resolve, reject) => {\n const reader = new FileReader()\n reader.onload = () => resolve(reader.result as string)\n reader.onerror = () => reject(reader.error)\n reader.readAsDataURL(bytes)\n })\n\n/**\n * The contents of `files` as `data:` URLs by their stored `uri`, each read once from the API that serves the viewed\n * record, with the user's own rights, as `useFileText` reads, up to 10 MB each; `ready` once every read has answered. A\n * file that could not be read is left out, so what refers to it stays as written.\n */\nexport const useSiblingContents = (files: readonly ViewedFile[]) => {\n const resource = useViewedResource()\n const client = useResourceClient(resource)\n const reads = useQueries({\n queries: files.map((file) => ({\n queryKey: ['file-data-url', resource, file.uri],\n staleTime: Infinity,\n retry: false,\n queryFn: async () => {\n const response = await fetch(client.fileReadUrl(resource, file))\n if (!response.ok) throw new FileReadError(response.status)\n return dataUrl(new Blob([await response.arrayBuffer()], { type: file.type }))\n },\n })),\n })\n const contents = new Map<string, string>()\n reads.forEach((read, index) => read.data !== undefined && contents.set(files[index]!.uri, read.data))\n return { contents, ready: reads.every((read) => !read.isPending) }\n}\n","import { useMemo } from 'react'\nimport type { ViewedFile } from './file-viewer'\nimport { referencedSiblings, siblingPage, type LinkAddress, type SiblingPage } from './sibling-page'\nimport { siblingsKey } from './siblings-key'\nimport { useSiblingContents } from './use-sibling-contents'\n\n/**\n * `html`, a page a file viewer shows, with its relative references resolved to `siblings` (`siblingPage`), for an\n * `HtmlFrame`: the images, videos and styles it names read as `data:` URLs, its links to siblings and outside addresses\n * in `links`, each showing the address `address` gives it. `undefined` while `html` or those reads are pending. Use it\n * inside a file viewer, which reads them from the API that serves the viewed record.\n */\nexport const useSiblingPage = <File extends ViewedFile>(html: string | undefined, siblings: readonly File[], address?: LinkAddress<File>): SiblingPage<File> | undefined => {\n // A viewer's siblings are a new list each render: their key, and the contents read, say when they changed.\n const siblingKey = siblingsKey(siblings)\n const named = useMemo(() => (html === undefined ? [] : referencedSiblings(html, siblings)), [html, siblingKey])\n const { contents, ready } = useSiblingContents(named)\n const contentsKey = [...contents.keys()].join('\\n')\n return useMemo(() => (html === undefined || !ready ? undefined : siblingPage(html, siblings, contents, address)), [html, siblingKey, ready, contentsKey, address])\n}\n"],"mappings":"2vBAMakB,GAAiB,EAAqC,EAAe,IAAgBC,GAAO,QAAUC,EAAQD,EAAM,MAAQE,EAG5HC,GAAuB,EAAe,IAAe,CAChE,GAAM,CAACH,EAAOI,IAAA,EAAYvB,EAAAA,SAAAA,CAA2B,EAC/CwB,GAAA,EAASvB,EAAAA,YAAAA,CAAa,GAA0BsB,EAAU,IAAW,CAAE,QAAO,MAAOE,EAAKP,EAAWC,EAAOC,EAAOC,CAAO,CAAC,CAAE,EAAE,EAAG,CAACD,EAAOC,CAAO,C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D,EAAK,IAAK,CAAC,CAAC,CAC9E,CACF,EAAE,CACJ,CAAC,EACKV,EAAW,IAAI,IAErB,OADAiB,EAAM,SAAS,EAAM,IAAUE,EAAK,OAAS,IAAA,IAAanB,EAAS,IAAIkB,EAAME,EAAM,CAAE,IAAKD,EAAK,IAAI,CAAC,EAC7F,CAAE,WAAU,MAAOF,EAAM,MAAO,GAAS,CAACE,EAAK,SAAS,CAAE,CACnE,EC3BaE,GAA2C,EAA0B,EAA2B,IAA+D,CAE1K,IAAMC,EAAajB,EAAY3B,CAAQ,EAEjC,CAAE,WAAU,SAAUsC,GADtB,EAAQjH,EAAAA,QAAAA,KAAegC,IAAS,IAAA,GAAY,CAAC,EAAI6D,EAAmB7D,EAAM2C,CAAQ,EAAI,CAAC3C,EAAMuF,CAAU,CAC9D,CAAK,EAC9CC,EAAc,CAAC,GAAGvB,EAAS,KAAK,CAAC,CAAC,CAAC,KAAK;CAAI,EAClD,OAAA,EAAOjG,EAAAA,QAAAA,KAAegC,IAAS,IAAA,IAAa,CAACyF,EAAQ,IAAA,GAAYzB,EAAYhE,EAAM2C,EAAUsB,EAAUI,CAAO,EAAI,CAACrE,EAAMuF,EAAYE,EAAOD,EAAanB,CAAO,CAAC,CACnK","debugId":"49f351dc-38f8-432a-a25d-4d085c588fd0"}
|
package/dist/shell-source-maps/assets/{value-badge-BKLV4otJ.js.map → value-badge-Dpd8dRqq.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"value-badge-
|
|
1
|
+
{"version":3,"file":"value-badge-Dpd8dRqq.js","names":["useCallback","n","a","t","__toESM","require_react","require_jsx_runtime","useQuery","useQueryClient","keepPreviousData","readsResource","keys","encodeKey","useClient","recordKey","messages","Badge","badgeTones","isBadgeTone","name","import_react","declared","key","value","colors","valueColor","color","valueTone","tone","scopeOf","row","model","countQuery","filter","page","client","useCount","firstRecordQuery","sort","stored","useFirstRecord","query","listPageQuery","pageSize","pageToken","useListPage","request","plannedRecord","planned","useRefreshResource","queryClient","resource","text","import_jsx_runtime","ValueBadge","hints"],"sources":["../../../../schema/src/badge-tones.ts","../../../src/live/value-color.ts","../../../src/app/pages/use-layout-data.ts","../../../src/app/pages/messages.ts","../../../src/app/value-badge.tsx"],"sourcesContent":["/** The tones an enum value's badge takes by name in `valueColors`; a value without one is `neutral`. */\nexport const badgeTones = ['neutral', 'blue', 'green', 'amber', 'red', 'violet'] as const\n\n/** A badge's tone by name, one of `badgeTones`. */\nexport type BadgeTone = (typeof badgeTones)[number]\n\n/** Whether `name` is one of the badge tones, rather than a hex colour. */\nexport const isBadgeTone = (name: string): name is BadgeTone => (badgeTones as readonly string[]).includes(name)\n","import { isBadgeTone, type BadgeTone } from '@protobase/schema'\n\nconst declared = (colors: Readonly<Record<string, string>> | undefined, value: unknown) => {\n const key = String(value)\n return colors && Object.hasOwn(colors, key) ? colors[key] : undefined\n}\n\n/** The hex colour a view gives a value's badge, if any; a tone name is no colour. */\nexport const valueColor = (colors: Readonly<Record<string, string>> | undefined, value: unknown) => {\n const color = declared(colors, value)\n return color === undefined || isBadgeTone(color) ? undefined : color\n}\n\n/** The tone a view gives a value's badge, `neutral` when it names none. */\nexport const valueTone = (colors: Readonly<Record<string, string>> | undefined, value: unknown): BadgeTone => {\n const tone = declared(colors, value)\n return tone !== undefined && isBadgeTone(tone) ? tone : 'neutral'\n}\n","import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'\nimport { useCallback } from 'react'\nimport type { Client, RecordPermissions } from '@protobase/client'\nimport type { ResourceModel } from '@protobase/schema'\nimport { encodeKey } from '@protobase/schema/internal'\nimport { useClient } from '../../data/api-provider'\nimport { keys, readsResource } from '../../data/query-keys'\nimport { recordKey } from '../../live/model-helpers'\nimport type { Planned } from './planned'\nimport type { LayoutRecord } from './record-scope'\n\ntype Row = Record<string, unknown>\n\n/** A list item as a record scope: the key as the URL carries it, and the etag and permissions the item carries. */\nexport const scopeOf = (model: ResourceModel, row: Row): LayoutRecord => ({\n model,\n record: row,\n key: encodeKey(recordKey(model, row)),\n etag: typeof row.etag === 'string' ? row.etag : undefined,\n permissions: row.permissions as RecordPermissions | undefined,\n})\n\n/** How many records of `model` match `filter`, counted by the server inside the caller's access rules. */\nexport const countQuery = (client: Client, model: ResourceModel, filter = '') => ({\n queryKey: keys.count(model.name, filter),\n queryFn: async () => {\n const page = await client.list(model.name, { filter: filter || undefined, pageSize: 1, count: 'exact', fields: model.primaryKey })\n return page.totalSize ?? page.totalSizeEstimate\n },\n})\n\nexport const useCount = (model: ResourceModel, filter = '', enabled = true) => useQuery({ ...countQuery(useClient(), model, filter), enabled })\n\ntype FirstRecord = { filter?: string; sort?: string; key?: string }\n\n/** The record a RecordCard shows: the one `recordKey` names, or the first that matches `filter` in `sort` order. */\nexport const firstRecordQuery = (client: Client, model: ResourceModel, { filter = '', sort = '', key }: FirstRecord) => ({\n queryKey: key === undefined ? keys.firstRecord(model.name, filter, sort) : keys.record(model.name, key),\n queryFn: async (): Promise<LayoutRecord | null> => {\n if (key !== undefined) {\n const stored = await client.get(model.name, key)\n return { ...scopeOf(model, stored.record), etag: stored.etag, permissions: stored.permissions }\n }\n const page = await client.list(model.name, { filter: filter || undefined, orderBy: sort || undefined, pageSize: 1 })\n return page.items[0] ? scopeOf(model, page.items[0]) : null\n },\n})\n\nexport const useFirstRecord = (model: ResourceModel, { enabled = true, ...query }: FirstRecord & { enabled?: boolean }) => useQuery({ ...firstRecordQuery(useClient(), model, query), enabled })\n\ntype ListPageRequest = { filter?: string; sort?: string; pageSize: number; pageToken?: string }\n\n/** One page of a list, from `pageToken`. */\nexport const listPageQuery = (client: Client, model: ResourceModel, { filter = '', sort = '', pageSize, pageToken = '' }: ListPageRequest) => ({\n queryKey: keys.list(model.name, filter, sort, pageSize, pageToken),\n queryFn: () => client.list(model.name, { filter: filter || undefined, orderBy: sort || undefined, pageSize, pageToken: pageToken || undefined }),\n})\n\n/** One page of a list, as `listPageQuery`; the previous page stays on screen while the next loads. */\nexport const useListPage = (model: ResourceModel, { enabled = true, ...request }: ListPageRequest & { enabled?: boolean }) => useQuery({ ...listPageQuery(useClient(), model, request), enabled, placeholderData: keepPreviousData })\n\n/** A planned read's first record, as `useFirstRecord` gives it: `null` when it holds none. */\nexport const plannedRecord = (model: ResourceModel, planned: Planned): { isPending: boolean; error: Error | null; data: LayoutRecord | null | undefined } => ({\n isPending: planned.isPending,\n error: planned.error,\n data: planned.rows[0] ? { ...scopeOf(model, planned.rows[0]), planned: true } : planned.isPending ? undefined : null,\n})\n\n/** Refetches everything shown of a resource after a write: lists, counts, records, labels and the page's planned reads. */\nexport const useRefreshResource = () => {\n const queryClient = useQueryClient()\n return useCallback((resource: string) => queryClient.invalidateQueries({ predicate: (query) => readsResource(query.queryKey, new Set([resource])) }), [queryClient])\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/pages')\n","import type { ReactNode } from 'react'\nimport type { FieldViewModel } from '@protobase/schema'\nimport { valueColor, valueTone } from '../live/value-color'\nimport { Badge } from '../primitives/badge'\n\n/** A stored value as a badge: in its badge shape, filled with the colour the view gives it or in the tone it gives it. */\nexport const ValueBadge = ({ value, hints, children }: { value: unknown; hints: FieldViewModel | undefined; children: ReactNode }) => (\n <Badge tone={valueTone(hints?.valueColors, value)} color={valueColor(hints?.valueColors, value)} shape={hints?.badgeShape}>\n {children}\n </Badge>\n)\n"],"mappings":"i0BACA,IAAaiB,EAAa,CAAC,UAAW,OAAQ,QAAS,QAAS,MAAO,QAAQ,EAMlEC,EAAe,GAAqCD,EAAiC,SAASE,CAAI,aCLzGE,GAAY,EAAsD,IAAmB,CACzF,IAAMC,EAAM,OAAOC,CAAK,EACxB,OAAOC,GAAU,OAAO,OAAOA,EAAQF,CAAG,EAAIE,EAAOF,GAAO,IAAA,EAC9D,EAGaG,GAAc,EAAsD,IAAmB,CAClG,IAAMC,EAAQL,EAASG,EAAQD,CAAK,EACpC,OAAOG,IAAU,IAAA,IAAaR,EAAYQ,CAAK,EAAI,IAAA,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