@inkandswitch/patchwork-pkg-base 0.0.109 → 0.0.111

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.
Files changed (33) hide show
  1. package/module-settings-url +1 -1
  2. package/package.json +1 -1
  3. package/packages/account-history/dist/assets/{HistoryRecorder-_3PrVW6n.js → HistoryRecorder-TRWDhOKO.js} +2 -3
  4. package/packages/account-history/dist/assets/HistoryRecorder-TRWDhOKO.js.map +1 -0
  5. package/packages/account-history/dist/assets/{index-DYqbrbYW.js → index-DBnlnSMc.js} +2 -2
  6. package/packages/account-history/dist/assets/{index-DYqbrbYW.js.map → index-DBnlnSMc.js.map} +1 -1
  7. package/packages/account-history/dist/index.js +1 -1
  8. package/packages/add-doc-to-sidebar-button/button.js +141 -25
  9. package/packages/add-doc-to-sidebar-button/button.test.js +114 -0
  10. package/packages/theming/dist/{active-theme-CC3CS64F.js → active-theme-6H5UANUR.js} +2 -2
  11. package/packages/theming/dist/{chunk-DH4YUYFJ.js → chunk-HHCCYVOT.js} +1 -2
  12. package/packages/theming/dist/chunk-HHCCYVOT.js.map +7 -0
  13. package/packages/theming/dist/main.js +3 -3
  14. package/packages/theming/dist/{theme-titlebar-BO2Y2GRN.js → theme-titlebar-UX4BND5Z.js} +2 -2
  15. package/packages/theming/dist/{theme-tray-V6BEXQWR.js → theme-tray-B477G2WR.js} +2 -2
  16. package/packages/theming/dist/tool.js +1 -1
  17. package/packages/threepane/dist/IsolatedDocumentArea-5WRK3TWL.js +2 -0
  18. package/packages/threepane/dist/PatchworkFrame-22UEOQ6E.js +2 -0
  19. package/packages/threepane/dist/PatchworkFrame-22UEOQ6E.js.map +7 -0
  20. package/packages/threepane/dist/{chunk-XOKWELWP.js → chunk-U4IJVHXK.js} +10 -5
  21. package/packages/threepane/dist/chunk-U4IJVHXK.js.map +7 -0
  22. package/packages/threepane/dist/index.js +1 -1
  23. package/plugin-registry-url +1 -1
  24. package/packages/account-history/dist/assets/HistoryRecorder-_3PrVW6n.js.map +0 -1
  25. package/packages/theming/dist/chunk-DH4YUYFJ.js.map +0 -7
  26. package/packages/threepane/dist/IsolatedDocumentArea-UTNJADQ7.js +0 -2
  27. package/packages/threepane/dist/PatchworkFrame-U2TVLGCZ.js +0 -2
  28. package/packages/threepane/dist/PatchworkFrame-U2TVLGCZ.js.map +0 -7
  29. package/packages/threepane/dist/chunk-XOKWELWP.js.map +0 -7
  30. /package/packages/theming/dist/{active-theme-CC3CS64F.js.map → active-theme-6H5UANUR.js.map} +0 -0
  31. /package/packages/theming/dist/{theme-titlebar-BO2Y2GRN.js.map → theme-titlebar-UX4BND5Z.js.map} +0 -0
  32. /package/packages/theming/dist/{theme-tray-V6BEXQWR.js.map → theme-tray-B477G2WR.js.map} +0 -0
  33. /package/packages/threepane/dist/{IsolatedDocumentArea-UTNJADQ7.js.map → IsolatedDocumentArea-5WRK3TWL.js.map} +0 -0
@@ -1 +1 @@
1
- automerge:3h6FuxrJaHQSbZFAg7yjoP7KVq6c
1
+ automerge:25656PAF9f4QGmJyW1J8fUhuP1F9
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkandswitch/patchwork-pkg-base",
3
- "version": "0.0.109",
3
+ "version": "0.0.111",
4
4
  "type": "module",
5
5
  "description": "Base packages for the Patchwork system",
6
6
  "repository": {
@@ -18,7 +18,7 @@ import { getType } from "@inkandswitch/patchwork-filesystem";
18
18
  import { getFallbackTool, getRegistry } from "@inkandswitch/patchwork-plugins";
19
19
  import { createStore, reconcile } from "solid-js/store";
20
20
  import * as Providers from "@inkandswitch/patchwork-providers";
21
- import { A as ACCOUNT_HISTORY_DATATYPE, D as DEDUPLICATION_TIME_THRESHOLD, V as VIEWER_TOOL_ID } from "./index-DYqbrbYW.js";
21
+ import { A as ACCOUNT_HISTORY_DATATYPE, D as DEDUPLICATION_TIME_THRESHOLD, V as VIEWER_TOOL_ID } from "./index-DBnlnSMc.js";
22
22
  function resolveElement(source) {
23
23
  return typeof source === "function" ? source() : source;
24
24
  }
@@ -97,7 +97,6 @@ function HistoryRecorder(props) {
97
97
  const url = docUrl;
98
98
  let toolId = rawToolId;
99
99
  const docHandle = await props.repo.find(url);
100
- await docHandle.whenReady();
101
100
  const doc = docHandle.doc();
102
101
  if (!doc) {
103
102
  console.warn("HistoryRecorder: failed to load document");
@@ -197,4 +196,4 @@ export {
197
196
  HistoryRecorder,
198
197
  renderHistoryRecorder
199
198
  };
200
- //# sourceMappingURL=HistoryRecorder-_3PrVW6n.js.map
199
+ //# sourceMappingURL=HistoryRecorder-TRWDhOKO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HistoryRecorder-TRWDhOKO.js","sources":["../../node_modules/.pnpm/@inkandswitch+patchwork-providers-solid@0.2.8_@automerge+automerge-repo@2.6.0-subductio_67b137d5e2e338e4087baee1e2e96ad1/node_modules/@inkandswitch/patchwork-providers-solid/dist/index.js","../../src/HistoryRecorder.tsx"],"sourcesContent":["import { createEffect, createSignal, onCleanup, onMount, } from \"solid-js\";\nimport { createStore, reconcile } from \"solid-js/store\";\nimport * as Providers from \"@inkandswitch/patchwork-providers\";\nfunction resolveElement(source) {\n return typeof source === \"function\" ? source() : source;\n}\n/**\n * Generic reactive request. Resolves the first value a provider emits for\n * `selector` (via the one-shot `request` helper) and returns an accessor that\n * reads `undefined` until then. `T` is the response type.\n */\nexport function request(element, selector) {\n const [value, setValue] = createSignal(undefined);\n onMount(() => {\n const target = resolveElement(element);\n if (!target)\n return;\n Providers.request(target, selector).then((v) => {\n if (v == null)\n return;\n setValue(() => v);\n });\n });\n return value;\n}\nexport function subscribe(element, selector, initialValue) {\n const [value, setValue] = createSignal(initialValue);\n onMount(() => {\n const target = resolveElement(element);\n if (!target)\n return;\n const unsubscribe = Providers.subscribe(target, selector, setValue);\n onCleanup(unsubscribe);\n });\n return value;\n}\n/**\n * Store-backed subscription. Use this when a consumer wants Solid's\n * fine-grained nested reactivity for incoming JSON object or array snapshots.\n * Requires an initial object/array so the store has a stable root.\n *\n * `reconcile` preserves stable object/array identity where possible, so this\n * helper is not a good fit when the top-level value is used as an identity key\n * for resources or memos.\n */\nexport function subscribeReconciled(element, selector, initialValue) {\n const [store, setStore] = createStore(initialValue);\n onMount(() => {\n const target = resolveElement(element);\n if (!target)\n return;\n const unsubscribe = Providers.subscribe(target, selector, (v) => {\n setStore(reconcile(v));\n });\n onCleanup(unsubscribe);\n });\n return store;\n}\n/**\n * Handle-specialized subscription. Use when the answering provider emits an\n * `AutomergeUrl`. The handle is recovered locally from the global repo\n * (`window.repo`), so it stays fully live — reads project reactively and writes go\n * straight back to the same repo. Returns `[doc, handle]` matching the shape\n * of `solid-automerge`'s `useDocument`; both read `undefined` until the first\n * url arrives. `T` is the doc shape inside the handle.\n */\nexport function subscribeDoc(element, selector) {\n const [handle, setHandle] = createSignal(undefined);\n onMount(() => {\n const target = resolveElement(element);\n if (!target)\n return;\n let canceled = false;\n const unsubscribe = Providers.subscribe(target, selector, (url) => {\n if (!url)\n return;\n const repo = \"repo\" in window ? window.repo : undefined;\n if (!repo)\n return;\n void Promise.resolve(repo.find(url)).then((h) => {\n if (canceled)\n return;\n setHandle(() => h);\n });\n });\n onCleanup(() => {\n canceled = true;\n unsubscribe();\n });\n });\n // Mirror the doc into a store by `reconcile`-ing against the *materialized*\n // snapshot (`handle.doc()`) on every change, rather than replaying the\n // change's incremental patches (as `solid-automerge`'s `createDocumentProjection`\n // / `autoproduce` does).\n //\n // A whole-value write such as `doc.list = [...]` is lowered by Automerge to\n // `putObjectFromHydrate`, whose patch stream is a `put` that materializes the\n // new container *plus* per-element `insert` patches. Replaying that delta with\n // `applyPatches` double-applies the contents — the `put` seeds `[a, b]`, then\n // the inserts splice `a, b` in again, yielding `[a, b, a, b]` — even though the\n // document itself is correct. The materialized snapshot is always\n // authoritative, so reconciling against it is robust to any valid change,\n // whole-array reassignment included.\n const [store, setStore] = createStore({});\n const [ready, setReady] = createSignal(false);\n createEffect(() => {\n const h = handle();\n if (!h) {\n setReady(false);\n return;\n }\n const sync = () => {\n setStore(reconcile((h.doc() ?? {})));\n setReady(true);\n };\n sync();\n h.on(\"change\", sync);\n onCleanup(() => h.off(\"change\", sync));\n });\n const doc = () => (ready() ? store : undefined);\n return [doc, handle];\n}\n","import { onMount, onCleanup, createEffect } from \"solid-js\";\nimport { render } from \"solid-js/web\";\nimport { type AutomergeUrl } from \"@automerge/automerge-repo/slim\";\nimport type { ToolImplementation } from \"@inkandswitch/patchwork-plugins\";\nimport \"./index.css\";\nimport { OpenDocumentEvent } from \"@inkandswitch/patchwork-elements\";\nimport {\n getType,\n type HasPatchworkMetadata,\n} from \"@inkandswitch/patchwork-filesystem\";\nimport {\n getFallbackTool,\n getRegistry,\n type DatatypeDescription,\n type DatatypeImplementation,\n} from \"@inkandswitch/patchwork-plugins\";\nimport { subscribeDoc } from \"@inkandswitch/patchwork-providers-solid\";\nimport {\n ACCOUNT_HISTORY_DATATYPE,\n DEDUPLICATION_TIME_THRESHOLD,\n VIEWER_TOOL_ID,\n} from \"./constants.ts\";\nimport {\n type PatchworkToolProps,\n type HistoryDoc,\n type HistoryEntry,\n} from \"./types.ts\";\n\n// Key under which this tool's private storage doc is registered — see the\n// `patchwork:tool-storage` provider (patchwork-base/providers). Mounted as a\n// titlebar-tool, this component is bound to whatever *document* is focused,\n// not the account, so it can't reach its own storage via `props.handle`; the\n// provider gives it a private, account-scoped doc instead.\nconst TOOL_STORAGE_ID = \"account-history\";\n\nexport function HistoryRecorder(props: PatchworkToolProps<any>) {\n // Resolves (and, on first use, creates) this tool's private storage doc.\n // The provider only guarantees an empty doc exists — the shape below\n // (`entries`, `title`, `@patchwork`) is seeded by us the first time it's\n // used.\n const [historyDoc, historyHandle] = subscribeDoc<HistoryDoc>(\n props.element,\n { type: \"patchwork:tool-storage\", toolId: TOOL_STORAGE_ID }\n );\n\n const historyUrl = () => historyHandle()?.url;\n\n createEffect(() => {\n const handle = historyHandle();\n const doc = historyDoc();\n if (!handle || !doc || Array.isArray(doc.entries)) return;\n handle.change((d) => {\n if (Array.isArray(d.entries)) return; // lost an initialization race\n d[\"@patchwork\"] = { type: ACCOUNT_HISTORY_DATATYPE };\n d.title = \"Account History\";\n d.entries = [];\n });\n });\n\n onMount(() => {\n const onDocumentOpened = async (event: Event) => {\n const openEvent = event as OpenDocumentEvent;\n const { url: rawUrl, toolId: rawToolId } = openEvent.detail;\n const [docUrl, ...heads] = rawUrl.split(\"#\");\n const url = docUrl as AutomergeUrl;\n let toolId = rawToolId;\n\n // Get document to extract title and type\n const docHandle = await props.repo.find(url);\n const doc = docHandle.doc();\n\n if (!doc) {\n console.warn(\"HistoryRecorder: failed to load document\");\n return;\n }\n\n const datatype = getType(doc as Partial<HasPatchworkMetadata>);\n\n if (!toolId) {\n // if the tool id isn't defined, use the current fallback tool\n if (!datatype) {\n console.warn(\n \"HistoryRecorder: no tool found for document type; skipping history recording\"\n );\n return;\n }\n const fallbackTool = getFallbackTool(doc as HasPatchworkMetadata);\n if (!fallbackTool) {\n console.warn(\n \"HistoryRecorder: no tool found for document type; skipping history recording\"\n );\n return;\n }\n toolId = fallbackTool.id;\n }\n\n if (datatype === ACCOUNT_HISTORY_DATATYPE) {\n return; // Don't record when opening account history documents\n }\n\n const currentHistoryHandle = historyHandle();\n if (!currentHistoryHandle) {\n console.warn(\"HistoryRecorder: history handle not ready yet\");\n return;\n }\n const historyDocSnapshot = currentHistoryHandle.doc();\n if (!historyDocSnapshot) {\n console.warn(\"HistoryRecorder: history document not ready yet\");\n return;\n }\n\n // Deduplication: check if this entry is a duplicate from rapid clicks\n const lastEntry =\n historyDocSnapshot.entries[historyDocSnapshot.entries.length - 1];\n if (\n lastEntry &&\n lastEntry.docUrl === url &&\n lastEntry.toolId === toolId &&\n Date.now() - lastEntry.timestamp < DEDUPLICATION_TIME_THRESHOLD\n ) {\n return; // Skip recording - duplicate from rapid clicking\n }\n\n // Extract title\n let docTitle = \"Untitled\";\n if (datatype) {\n const registry = getRegistry<DatatypeDescription>(\"patchwork:datatype\");\n const loaded = registry.get(datatype);\n if (loaded && \"module\" in loaded) {\n const impl = loaded.module as DatatypeImplementation;\n try {\n docTitle = impl.getTitle(doc) || \"Untitled\";\n } catch {\n // getTitle may fail if the document shape doesn't match the datatype\n }\n }\n }\n\n // Get current heads, unless the URL specified a head\n let entryHeads = heads;\n if (entryHeads.length === 0) entryHeads = docHandle.heads();\n\n // Create new entry\n const newEntry: HistoryEntry = {\n timestamp: Date.now(),\n docUrl: url,\n docTitle,\n docType: datatype || \"unknown\",\n toolId,\n heads: entryHeads,\n };\n\n // Add entry to history\n currentHistoryHandle.change((doc) => {\n doc.entries.push(newEntry);\n });\n };\n\n // Listen to patchwork:open-document events (should fire once per user action)\n document.addEventListener(\n \"patchwork:open-document\",\n onDocumentOpened as EventListener,\n { capture: true }\n );\n\n onCleanup(() => {\n document.removeEventListener(\n \"patchwork:open-document\",\n onDocumentOpened as EventListener,\n { capture: true }\n );\n });\n });\n\n const openHistory = () => {\n const currentHistoryUrl = historyUrl();\n if (!currentHistoryUrl) {\n console.warn(\"HistoryRecorder: no history URL yet\");\n return;\n }\n\n // Dispatch open document event\n props.element.dispatchEvent(\n new OpenDocumentEvent({\n url: currentHistoryUrl,\n toolId: VIEWER_TOOL_ID,\n })\n );\n };\n\n return (\n <button\n onClick={openHistory}\n class=\"account-history-toolbar-button\"\n title=\"Open account history\"\n >\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <polyline points=\"12 6 12 12 16 14\" />\n </svg>\n </button>\n );\n}\n\nexport const renderHistoryRecorder: ToolImplementation<any> = (\n handle,\n element\n) => render(() => <HistoryRecorder handle={handle} repo={element.repo} element={element} />, element);\n"],"names":["TOOL_STORAGE_ID","HistoryRecorder","props","historyDoc","historyHandle","subscribeDoc","element","type","toolId","historyUrl","url","createEffect","handle","doc","Array","isArray","entries","change","d","ACCOUNT_HISTORY_DATATYPE","title","onMount","onDocumentOpened","event","openEvent","rawUrl","rawToolId","detail","docUrl","heads","split","docHandle","repo","find","console","warn","datatype","getType","fallbackTool","getFallbackTool","id","currentHistoryHandle","historyDocSnapshot","lastEntry","length","Date","now","timestamp","DEDUPLICATION_TIME_THRESHOLD","docTitle","registry","getRegistry","loaded","get","impl","module","getTitle","entryHeads","newEntry","docType","push","document","addEventListener","capture","onCleanup","removeEventListener","openHistory","currentHistoryUrl","dispatchEvent","OpenDocumentEvent","VIEWER_TOOL_ID","_el$","_tmpl$","$$click","renderHistoryRecorder","render","_$createComponent","_$delegateEvents"],"mappings":";;;;;;;;;AAGA,SAAS,eAAe,QAAQ;AAC5B,SAAO,OAAO,WAAW,aAAa,OAAM,IAAK;AACrD;AA6DO,SAAS,aAAa,SAAS,UAAU;AAC5C,QAAM,CAAC,QAAQ,SAAS,IAAI,aAAa,MAAS;AAClD,UAAQ,MAAM;AACV,UAAM,SAAS,eAAe,OAAO;AACrC,QAAI,CAAC;AACD;AACJ,QAAI,WAAW;AACf,UAAM,cAAc,UAAU,UAAU,QAAQ,UAAU,CAAC,QAAQ;AAC/D,UAAI,CAAC;AACD;AACJ,YAAM,OAAO,UAAU,SAAS,OAAO,OAAO;AAC9C,UAAI,CAAC;AACD;AACJ,WAAK,QAAQ,QAAQ,KAAK,KAAK,GAAG,CAAC,EAAE,KAAK,CAAC,MAAM;AAC7C,YAAI;AACA;AACJ,kBAAU,MAAM,CAAC;AAAA,MACrB,CAAC;AAAA,IACL,CAAC;AACD,cAAU,MAAM;AACZ,iBAAW;AACX,kBAAW;AAAA,IACf,CAAC;AAAA,EACL,CAAC;AAcD,QAAM,CAAC,OAAO,QAAQ,IAAI,YAAY,CAAA,CAAE;AACxC,QAAM,CAAC,OAAO,QAAQ,IAAI,aAAa,KAAK;AAC5C,eA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renderHistoryRecorder2
96
- } = await import("./HistoryRecorder-_3PrVW6n.js");
96
+ } = await import("./HistoryRecorder-TRWDhOKO.js");
97
97
  return {
98
98
  renderHistoryRecorder: renderHistoryRecorder2
99
99
  };
@@ -145,4 +145,4 @@ export {
145
145
  VIEWER_TOOL_ID as V,
146
146
  plugins as p
147
147
  };
148
- //# sourceMappingURL=index-DYqbrbYW.js.map
148
+ //# sourceMappingURL=index-DBnlnSMc.js.map
@@ -1 +1 @@
1
- {"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAO,MAAM,2BAA2B;AAEjC,MAAM,+BAA+B;AACrC,MAAM,iBAAiB;AACvB,MAAM,0BAA0B;ACIhC,MAAMA,UAAU,CACrB;AAAA,EACEC,IAAIC;AAAAA,EACJC,MAAM;AAAA,EACNC,MAAM;AAAA,EACNC,MAAM;AAAA,EACNC,UAAU;AAAA,EACV,MAAMC,OAAO;AACX,WAAO;AAAA,MACLC,UAAUA,CAACC,QAAoBA,IAAIC,SAAS;AAAA,MAC5CC,QAAQA,OAAmB;AAAA,QACzB,CAAC,YAAY,GAAG;AAAA,UAAER,MAAMD;AAAAA;AAAAA,QACxBQ,OAAO;AAAA,QACPE,SAAS;AAAA;AAAA,IACX;AAAA,EAEJ;AACF,GACA;AAAA,EACEX,IAAI;AAAA,EACJE,MAAM;AAAA,EACNU,MAAM,CAAC,eAAe;AAAA,EACtBT,MAAM;AAAA,EACNU,oBAAoB,CAAC,SAAS;AAAA,EAC9BT,MAAM;AAAA,EACNC,UAAU;AAAA,EACV,MAAMC,OAAyC;AAC7C,UAAM;AAAA,MAAEQ;AAAAA,QAA0B;AAAA;AAAA;MAAM,iBAAO,+BAAuB;AAAA;AAAA;MAAA;AAAA;AACtE,WAAOA;AAAAA,EACT;AACF,GACA;AAAA,EACEd,IAAIe;AAAAA,EACJb,MAAM;AAAA,EACNC,MAAM;AAAA,EACNU,oBAAoB,CAACZ,wBAAwB;AAAA,EAC7CG,MAAM;AAAA,EACN,MAAME,OAAgD;AACpD,UAAM;AAAA,MAAEU;AAAAA,QAAwB;AAAA;AAAA;MAAM,iBAAO,6BAAqB;AAAA;AAAA;MAAA;AAAA;AAClE,WAAOA;AAAAA,EACT;AACF,GACA;AAAA,EACEhB,IAAIiB;AAAAA,EACJf,MAAM;AAAA,EACNC,MAAM;AAAA,EACNU,oBAAoB,CAACZ,wBAAwB;AAAA,EAC7CG,MAAM;AAAA,EACN,MAAME,OAAgD;AACpD,UAAM;AAAA,MAAEY;AAAAA,QAAyB;AAAA;AAAA;MAAM,iBAAO,8BAAsB;AAAA;AAAA;MAAA;AAAA;AACpE,WAAOA;AAAAA,EACT;AACF,CAAC","names":["plugins","id","ACCOUNT_HISTORY_DATATYPE","type","name","icon","unlisted","load","getTitle","doc","title","create","entries","tags","supportedDatatypes","renderHistoryRecorder","VIEWER_TOOL_ID","renderHistoryViewer","NOTEBOOK_VIEWER_TOOL_ID","renderNotebookViewer"],"ignoreList":[],"sources":["../../src/constants.ts","../../src/index.tsx"],"sourcesContent":["export const ACCOUNT_HISTORY_DATATYPE = \"patchwork:account-history\";\n// if the same document is opened again within this time, we consider it a duplicate and don't record it again\nexport const DEDUPLICATION_TIME_THRESHOLD = 500; // milliseconds\nexport const VIEWER_TOOL_ID = \"account-history-viewer\";\nexport const NOTEBOOK_VIEWER_TOOL_ID = \"account-history-notebook-viewer\";\n","import { type ToolImplementation } from \"@inkandswitch/patchwork-plugins\";\nimport {\n ACCOUNT_HISTORY_DATATYPE,\n VIEWER_TOOL_ID,\n NOTEBOOK_VIEWER_TOOL_ID,\n} from \"./constants.ts\";\nimport type { HistoryDoc } from \"./types.ts\";\n\nexport const plugins = [\n {\n id: ACCOUNT_HISTORY_DATATYPE,\n type: \"patchwork:datatype\",\n name: \"Account History\",\n icon: \"Clock\",\n unlisted: true,\n async load() {\n return {\n getTitle: (doc: HistoryDoc) => doc.title || \"Account History\",\n create: (): HistoryDoc => ({\n [\"@patchwork\"]: { type: ACCOUNT_HISTORY_DATATYPE },\n title: \"Account History\",\n entries: [],\n }),\n };\n },\n },\n {\n id: \"account-history-toolbar\",\n type: \"patchwork:tool\",\n tags: [\"titlebar-tool\"],\n name: \"Account History\",\n supportedDatatypes: [\"account\"],\n icon: \"Clock\",\n unlisted: true,\n async load(): Promise<ToolImplementation<any>> {\n const { renderHistoryRecorder } = await import(\"./HistoryRecorder.tsx\");\n return renderHistoryRecorder;\n },\n },\n {\n id: VIEWER_TOOL_ID,\n type: \"patchwork:tool\",\n name: \"Account History Viewer\",\n supportedDatatypes: [ACCOUNT_HISTORY_DATATYPE],\n icon: \"Clock\",\n async load(): Promise<ToolImplementation<HistoryDoc>> {\n const { renderHistoryViewer } = await import(\"./HistoryViewer.tsx\");\n return renderHistoryViewer;\n },\n },\n {\n id: NOTEBOOK_VIEWER_TOOL_ID,\n type: \"patchwork:tool\",\n name: \"Account History Notebook\",\n supportedDatatypes: [ACCOUNT_HISTORY_DATATYPE],\n icon: \"BookOpen\",\n async load(): Promise<ToolImplementation<HistoryDoc>> {\n const { renderNotebookViewer } = await import(\"./NotebookViewer.tsx\");\n return renderNotebookViewer;\n },\n },\n];\n"],"file":"index-DYqbrbYW.js"}
1
+ {"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAO,MAAM,2BAA2B;AAEjC,MAAM,+BAA+B;AACrC,MAAM,iBAAiB;AACvB,MAAM,0BAA0B;ACIhC,MAAMA,UAAU,CACrB;AAAA,EACEC,IAAIC;AAAAA,EACJC,MAAM;AAAA,EACNC,MAAM;AAAA,EACNC,MAAM;AAAA,EACNC,UAAU;AAAA,EACV,MAAMC,OAAO;AACX,WAAO;AAAA,MACLC,UAAUA,CAACC,QAAoBA,IAAIC,SAAS;AAAA,MAC5CC,QAAQA,OAAmB;AAAA,QACzB,CAAC,YAAY,GAAG;AAAA,UAAER,MAAMD;AAAAA;AAAAA,QACxBQ,OAAO;AAAA,QACPE,SAAS;AAAA;AAAA,IACX;AAAA,EAEJ;AACF,GACA;AAAA,EACEX,IAAI;AAAA,EACJE,MAAM;AAAA,EACNU,MAAM,CAAC,eAAe;AAAA,EACtBT,MAAM;AAAA,EACNU,oBAAoB,CAAC,SAAS;AAAA,EAC9BT,MAAM;AAAA,EACNC,UAAU;AAAA,EACV,MAAMC,OAAyC;AAC7C,UAAM;AAAA,MAAEQ;AAAAA,QAA0B;AAAA;AAAA;MAAM,iBAAO,+BAAuB;AAAA;AAAA;MAAA;AAAA;AACtE,WAAOA;AAAAA,EACT;AACF,GACA;AAAA,EACEd,IAAIe;AAAAA,EACJb,MAAM;AAAA,EACNC,MAAM;AAAA,EACNU,oBAAoB,CAACZ,wBAAwB;AAAA,EAC7CG,MAAM;AAAA,EACN,MAAME,OAAgD;AACpD,UAAM;AAAA,MAAEU;AAAAA,QAAwB;AAAA;AAAA;MAAM,iBAAO,6BAAqB;AAAA;AAAA;MAAA;AAAA;AAClE,WAAOA;AAAAA,EACT;AACF,GACA;AAAA,EACEhB,IAAIiB;AAAAA,EACJf,MAAM;AAAA,EACNC,MAAM;AAAA,EACNU,oBAAoB,CAACZ,wBAAwB;AAAA,EAC7CG,MAAM;AAAA,EACN,MAAME,OAAgD;AACpD,UAAM;AAAA,MAAEY;AAAAA,QAAyB;AAAA;AAAA;MAAM,iBAAO,8BAAsB;AAAA;AAAA;MAAA;AAAA;AACpE,WAAOA;AAAAA,EACT;AACF,CAAC","names":["plugins","id","ACCOUNT_HISTORY_DATATYPE","type","name","icon","unlisted","load","getTitle","doc","title","create","entries","tags","supportedDatatypes","renderHistoryRecorder","VIEWER_TOOL_ID","renderHistoryViewer","NOTEBOOK_VIEWER_TOOL_ID","renderNotebookViewer"],"ignoreList":[],"sources":["../../src/constants.ts","../../src/index.tsx"],"sourcesContent":["export const ACCOUNT_HISTORY_DATATYPE = \"patchwork:account-history\";\n// if the same document is opened again within this time, we consider it a duplicate and don't record it again\nexport const DEDUPLICATION_TIME_THRESHOLD = 500; // milliseconds\nexport const VIEWER_TOOL_ID = \"account-history-viewer\";\nexport const NOTEBOOK_VIEWER_TOOL_ID = \"account-history-notebook-viewer\";\n","import { type ToolImplementation } from \"@inkandswitch/patchwork-plugins\";\nimport {\n ACCOUNT_HISTORY_DATATYPE,\n VIEWER_TOOL_ID,\n NOTEBOOK_VIEWER_TOOL_ID,\n} from \"./constants.ts\";\nimport type { HistoryDoc } from \"./types.ts\";\n\nexport const plugins = [\n {\n id: ACCOUNT_HISTORY_DATATYPE,\n type: \"patchwork:datatype\",\n name: \"Account History\",\n icon: \"Clock\",\n unlisted: true,\n async load() {\n return {\n getTitle: (doc: HistoryDoc) => doc.title || \"Account History\",\n create: (): HistoryDoc => ({\n [\"@patchwork\"]: { type: ACCOUNT_HISTORY_DATATYPE },\n title: \"Account History\",\n entries: [],\n }),\n };\n },\n },\n {\n id: \"account-history-toolbar\",\n type: \"patchwork:tool\",\n tags: [\"titlebar-tool\"],\n name: \"Account History\",\n supportedDatatypes: [\"account\"],\n icon: \"Clock\",\n unlisted: true,\n async load(): Promise<ToolImplementation<any>> {\n const { renderHistoryRecorder } = await import(\"./HistoryRecorder.tsx\");\n return renderHistoryRecorder;\n },\n },\n {\n id: VIEWER_TOOL_ID,\n type: \"patchwork:tool\",\n name: \"Account History Viewer\",\n supportedDatatypes: [ACCOUNT_HISTORY_DATATYPE],\n icon: \"Clock\",\n async load(): Promise<ToolImplementation<HistoryDoc>> {\n const { renderHistoryViewer } = await import(\"./HistoryViewer.tsx\");\n return renderHistoryViewer;\n },\n },\n {\n id: NOTEBOOK_VIEWER_TOOL_ID,\n type: \"patchwork:tool\",\n name: \"Account History Notebook\",\n supportedDatatypes: [ACCOUNT_HISTORY_DATATYPE],\n icon: \"BookOpen\",\n async load(): Promise<ToolImplementation<HistoryDoc>> {\n const { renderNotebookViewer } = await import(\"./NotebookViewer.tsx\");\n return renderNotebookViewer;\n },\n },\n];\n"],"file":"index-DBnlnSMc.js"}
@@ -1,4 +1,4 @@
1
- import { p } from "./assets/index-DYqbrbYW.js";
1
+ import { p } from "./assets/index-DBnlnSMc.js";
2
2
  export {
3
3
  p as plugins
4
4
  };
@@ -7,19 +7,99 @@ link.rel = "stylesheet";
7
7
  link.href = cssURL.href;
8
8
  document.head.appendChild(link);
9
9
 
10
+ const LABEL = "Add to sidebar";
11
+
12
+ /**
13
+ * Fired (bubbling, composed, cancelable) at the button's own element. A frame
14
+ * that claims it calls preventDefault() and hands its work to
15
+ * `detail.respondWith`. threepane listens for this.
16
+ */
17
+ export const ADD_TO_SIDEBAR_EVENT = "patchwork:add-to-sidebar";
18
+
19
+ /**
20
+ * Put `link` first in the folder. A doc that's already there is lifted to the
21
+ * top, keeping its own name, rather than added twice. (threepane has the same
22
+ * rule in src/account/addToSidebar.ts.)
23
+ */
24
+ export function putAtTop(folder, link) {
25
+ if (!folder.docs) folder.docs = [];
26
+ const docs = folder.docs;
27
+ const at = docs.findIndex((existing) => existing.url === link.url);
28
+ if (at === 0) return;
29
+ if (at > 0) {
30
+ const { name, type } = docs[at];
31
+ docs.splice(at, 1);
32
+ docs.unshift({ url: link.url, name, type });
33
+ return;
34
+ }
35
+ docs.unshift({ url: link.url, name: link.name, type: link.type });
36
+ }
37
+
38
+ /**
39
+ * The account handle, wherever this host put it. Most hosts copy it onto
40
+ * `window.accountDocHandle`; some (gaios) only have it on `window.patchwork`.
41
+ */
42
+ function accountHandle() {
43
+ return window.accountDocHandle ?? window.patchwork?.account;
44
+ }
45
+
46
+ /**
47
+ * The page's own repo, not the one on the element: titlebar tools can sit
48
+ * inside a draft overlay, whose repo would hand back a draft of the sidebar.
49
+ */
50
+ function pageRepo(element) {
51
+ return window.repo ?? window.patchwork?.repo ?? element.repo;
52
+ }
53
+
54
+ /** Resolves with pick(doc) once it's something. */
55
+ function when(handle, pick) {
56
+ return new Promise((resolve) => {
57
+ const check = () => {
58
+ const doc = handle.doc();
59
+ const picked = doc && pick(doc);
60
+ if (!picked) return;
61
+ handle.off("change", check);
62
+ resolve(picked);
63
+ };
64
+ handle.on("change", check);
65
+ check();
66
+ });
67
+ }
68
+
69
+ function withTimeout(promise, ms, message) {
70
+ let timer;
71
+ return Promise.race([
72
+ promise,
73
+ new Promise((_, reject) => {
74
+ timer = setTimeout(() => reject(new Error(message)), ms);
75
+ }),
76
+ ]).finally(() => clearTimeout(timer));
77
+ }
78
+
10
79
  export default function renderAddDocToSidebarButton(handle, element) {
11
80
  const wrapper = document.createElement("div");
12
81
  wrapper.className = "add-doc-to-sidebar";
13
82
 
14
83
  const button = document.createElement("button");
15
- button.textContent = "Add to sidebar";
84
+ button.type = "button";
85
+ button.textContent = LABEL;
16
86
  wrapper.appendChild(button);
17
87
 
18
- // hidden by default until we confirm there's a datatype
88
+ // hidden until we know the doc's datatype (a doc link needs one)
19
89
  wrapper.style.display = "none";
20
90
 
21
91
  let docDatatypeId;
22
92
  let title;
93
+ let loadingDatatype;
94
+ let resetTimer;
95
+ let disposed = false;
96
+
97
+ // The doc the frame has open. The view's doc-url is the real one; the handle
98
+ // may be a draft overlay presenting it.
99
+ const docUrl = () =>
100
+ element.closest?.("patchwork-view")?.getAttribute("doc-url") ??
101
+ element.getAttribute?.("doc-url") ??
102
+ handle.url;
23
103
 
24
104
  function update() {
25
105
  const doc = handle.doc();
@@ -35,48 +115,84 @@ export default function renderAddDocToSidebarButton(handle, element) {
35
115
  const loaded = registry.get(docDatatypeId);
36
116
  if (loaded && "module" in loaded) {
37
117
  title = loaded.module.getTitle(doc) || undefined;
118
+ } else if (loadingDatatype !== docDatatypeId) {
119
+ loadingDatatype = docDatatypeId;
120
+ registry.load(docDatatypeId).then(() => {
121
+ if (!disposed) update();
122
+ });
38
123
  }
39
124
 
40
125
  wrapper.style.display = "";
41
126
  }
42
127
 
43
- async function onAddDocToSidebar() {
44
- const repo = element.repo;
128
+ function flash(text) {
129
+ clearTimeout(resetTimer);
130
+ button.textContent = text;
131
+ resetTimer = setTimeout(() => {
132
+ button.textContent = LABEL;
133
+ button.disabled = false;
134
+ }, 1500);
135
+ }
45
136
 
46
- // hack: get reference to the account doc handle through window
47
- const accountDocHandle = window.accountDocHandle;
137
+ // Ask whatever frame we're in to do it (threepane answers). If nobody
138
+ // claims the event, put it in the account's root folder ourselves.
139
+ function askFrame(link) {
140
+ let work;
141
+ const event = new CustomEvent(ADD_TO_SIDEBAR_EVENT, {
142
+ bubbles: true,
143
+ composed: true,
144
+ cancelable: true,
145
+ detail: {
146
+ ...link,
147
+ respondWith(promise) {
148
+ work = promise;
149
+ },
150
+ },
151
+ });
152
+ wrapper.dispatchEvent(event);
153
+ if (!event.defaultPrevented) return undefined;
154
+ return work ?? Promise.resolve();
155
+ }
48
156
 
49
- const rootFolderDocHandle = await repo.find(
50
- accountDocHandle.doc().rootFolderUrl
157
+ async function addItOurselves(link) {
158
+ const account = accountHandle();
159
+ if (!account) throw new Error("no account handle on this page");
160
+ const rootFolderUrl = await withTimeout(
161
+ when(account, (doc) => doc.rootFolderUrl),
162
+ 5000,
163
+ "account has no rootFolderUrl"
51
164
  );
165
+ const rootFolder = await pageRepo(element).find(rootFolderUrl);
166
+ rootFolder.change((folder) => putAtTop(folder, link));
167
+ }
52
168
 
53
- rootFolderDocHandle.change((doc) => {
54
- doc.docs.unshift({
55
- name: title ?? "Untitled",
56
- url: handle.url,
57
- type: docDatatypeId,
58
- });
59
- });
169
+ async function onAddDocToSidebar() {
170
+ const link = {
171
+ url: docUrl(),
172
+ name: title ?? "Untitled",
173
+ type: docDatatypeId,
174
+ };
175
+ button.disabled = true;
176
+ try {
177
+ await (askFrame(link) ?? addItOurselves(link));
178
+ flash("Added ✓");
179
+ } catch (error) {
180
+ console.error("[add-doc-to-sidebar] couldn't add to sidebar", error);
181
+ flash("Couldn't add");
182
+ }
60
183
  }
61
184
 
62
185
  button.addEventListener("click", onAddDocToSidebar);
63
186
  handle.on("change", update);
64
187
  update();
65
188
 
66
- // try to load the datatype async if it wasn't ready yet
67
- const doc = handle.doc();
68
- if (doc) {
69
- const datatypeId = getType(doc);
70
- if (datatypeId) {
71
- const registry = getRegistry("patchwork:datatype");
72
- registry.load(datatypeId).then(() => update());
73
- }
74
- }
75
-
76
189
  element.appendChild(wrapper);
77
190
 
78
191
  return () => {
192
+ disposed = true;
193
+ clearTimeout(resetTimer);
79
194
  handle.off("change", update);
80
195
  button.removeEventListener("click", onAddDocToSidebar);
196
+ wrapper.remove();
81
197
  };
82
198
  }
@@ -0,0 +1,114 @@
1
+ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { Repo, initSubduction } from "@automerge/automerge-repo";
3
+
4
+ beforeAll(() => initSubduction());
5
+
6
+ vi.mock("@inkandswitch/patchwork-plugins", () => ({
7
+ getRegistry: () => ({
8
+ get: () => ({ module: { getTitle: (doc) => doc.title } }),
9
+ load: () => Promise.resolve(),
10
+ }),
11
+ }));
12
+
13
+ const { default: render, putAtTop, ADD_TO_SIDEBAR_EVENT } = await import(
14
+ "./button.js"
15
+ );
16
+
17
+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
18
+
19
+ describe("putAtTop", () => {
20
+ const a = { url: "automerge:a", name: "A", type: "t" };
21
+ const b = { url: "automerge:b", name: "B", type: "t" };
22
+
23
+ it("adds a new doc first", () => {
24
+ const folder = { docs: [a] };
25
+ putAtTop(folder, b);
26
+ expect(folder.docs.map((d) => d.url)).toEqual([b.url, a.url]);
27
+ });
28
+
29
+ it("lifts a doc that's already there instead of adding it twice", () => {
30
+ const folder = { docs: [a, { ...b, name: "kept" }] };
31
+ putAtTop(folder, b);
32
+ expect(folder.docs).toEqual([{ ...b, name: "kept" }, a]);
33
+ });
34
+
35
+ it("makes the list if the folder has none", () => {
36
+ const folder = {};
37
+ putAtTop(folder, a);
38
+ expect(folder.docs).toEqual([a]);
39
+ });
40
+ });
41
+
42
+ describe("the button", () => {
43
+ let repo, doc, root, account, host, cleanup;
44
+
45
+ beforeEach(() => {
46
+ repo = new Repo();
47
+ root = repo.create({ docs: [{ url: "automerge:x", name: "X", type: "t" }] });
48
+ account = repo.create({ rootFolderUrl: root.url });
49
+ doc = repo.create({ "@patchwork": { type: "essay" }, title: "My essay" });
50
+ host = document.createElement("patchwork-view");
51
+ host.setAttribute("doc-url", doc.url);
52
+ document.body.appendChild(host);
53
+ window.repo = repo;
54
+ window.accountDocHandle = account;
55
+ cleanup = render(doc, host);
56
+ });
57
+
58
+ afterEach(() => {
59
+ cleanup();
60
+ host.remove();
61
+ delete window.repo;
62
+ delete window.accountDocHandle;
63
+ });
64
+
65
+ const click = () => host.querySelector("button").click();
66
+
67
+ it("lets a frame that claims the event do the adding", async () => {
68
+ const seen = [];
69
+ let done;
70
+ const claim = (event) => {
71
+ event.preventDefault();
72
+ seen.push({ ...event.detail });
73
+ event.detail.respondWith(new Promise((resolve) => (done = resolve)));
74
+ };
75
+ document.body.addEventListener(ADD_TO_SIDEBAR_EVENT, claim);
76
+ click();
77
+ document.body.removeEventListener(ADD_TO_SIDEBAR_EVENT, claim);
78
+
79
+ expect(seen[0]).toMatchObject({
80
+ url: doc.url,
81
+ name: "My essay",
82
+ type: "essay",
83
+ });
84
+ done();
85
+ await flush();
86
+ expect(host.querySelector("button").textContent).toBe("Added ✓");
87
+ expect(root.doc().docs).toHaveLength(1);
88
+ });
89
+
90
+ it("adds to the top of the root folder itself when nobody claims it", async () => {
91
+ click();
92
+ await flush();
93
+ await flush();
94
+ expect(root.doc().docs.map((d) => d.url)).toEqual([doc.url, "automerge:x"]);
95
+ expect(root.doc().docs[0]).toEqual({
96
+ url: doc.url,
97
+ name: "My essay",
98
+ type: "essay",
99
+ });
100
+ });
101
+
102
+ it("finds the account on window.patchwork when that's all there is", async () => {
103
+ delete window.accountDocHandle;
104
+ window.patchwork = { account, repo };
105
+ try {
106
+ click();
107
+ await flush();
108
+ await flush();
109
+ expect(root.doc().docs[0].url).toBe(doc.url);
110
+ } finally {
111
+ delete window.patchwork;
112
+ }
113
+ });
114
+ });
@@ -9,7 +9,7 @@ import {
9
9
  setThemeForMode,
10
10
  startActiveTheme,
11
11
  startActiveThemeFromProvider
12
- } from "./chunk-DH4YUYFJ.js";
12
+ } from "./chunk-HHCCYVOT.js";
13
13
  import "./chunk-L7WQSSFT.js";
14
14
  export {
15
15
  CURRENT_THEME_SELECTOR,
@@ -23,4 +23,4 @@ export {
23
23
  startActiveTheme,
24
24
  startActiveThemeFromProvider
25
25
  };
26
- //# sourceMappingURL=active-theme-CC3CS64F.js.map
26
+ //# sourceMappingURL=active-theme-6H5UANUR.js.map
@@ -120,7 +120,6 @@ function ensureThemePreferencesShape(prefsHandle) {
120
120
  });
121
121
  }
122
122
  async function useThemePreferencesHandle(prefsHandle) {
123
- await prefsHandle.whenReady?.();
124
123
  ensureThemePreferencesShape(prefsHandle);
125
124
  if (currentPrefsHandle === prefsHandle) return;
126
125
  if (currentPrefsHandle?.url && prefsHandle.url && currentPrefsHandle.url === prefsHandle.url) {
@@ -285,4 +284,4 @@ export {
285
284
  hasThemePreferences,
286
285
  onActiveThemeChange
287
286
  };
288
- //# sourceMappingURL=chunk-DH4YUYFJ.js.map
287
+ //# sourceMappingURL=chunk-HHCCYVOT.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/active-theme.ts"],
4
+ "sourcesContent": ["import {getRegistry} from \"@inkandswitch/patchwork-plugins\"\nimport themeCssUrl from \"./theme.css\"\nimport lycheeCssUrl from \"./lychee.css\"\nimport gloomCssUrl from \"./gloom.css\"\n\ntype ActiveThemeState = {\n\tmode: \"light\" | \"dark\"\n\tthemeId: string\n\tlight: string\n\tdark: string\n\tpreferencesUrl?: string\n}\n\ntype ThemePreferencesHandle = {\n\turl?: string\n\tdoc(): any\n\tchange(fn: (doc: any) => void): void\n\ton?(event: \"change\", listener: () => void): void\n\toff?(event: \"change\", listener: () => void): void\n}\n\nexport const CURRENT_THEME_SELECTOR = \"patchwork:current-theme\"\n\n/**\n * Which themes an account that has not chosen one starts on. A site states\n * this on its root element \u2014 `<html data-theme-light=\"warm\" data-theme-dark=\"dark\">`\n * \u2014 so the answer comes from the site itself rather than from whichever\n * module happened to load last. `lychee`/`gloom` apply when it says nothing.\n *\n * Nothing is written to the preferences document: an unset preference resolves\n * through here at read time, so the theme a user picked explicitly is never\n * overwritten, and a site changing its defaults moves everyone who never\n * picked one.\n */\nconst FALLBACK_DEFAULTS = {light: \"lychee\", dark: \"gloom\"}\n\nfunction defaultThemeIds() {\n\tconst root = document.documentElement\n\treturn {\n\t\tlight: root.getAttribute(\"data-theme-light\") || FALLBACK_DEFAULTS.light,\n\t\tdark: root.getAttribute(\"data-theme-dark\") || FALLBACK_DEFAULTS.dark,\n\t}\n}\n\nconst bundledStyleUrls = [themeCssUrl, lycheeCssUrl, gloomCssUrl].map(\n\t(href) => new URL(href, import.meta.url).href\n)\nconst bundledStyles = new Set(bundledStyleUrls)\nconst themeLinks = new Map<string, HTMLLinkElement>()\nconst listeners = new Set<(state: ActiveThemeState) => void>()\n\nlet started = false\nlet stylesBootstrapped = false\nlet currentPrefsHandle: ThemePreferencesHandle | undefined\nlet currentState: ActiveThemeState | undefined\nlet storageStarted = false\nlet storageElement: HTMLElement | undefined\nlet unsubscribeStorage: (() => void) | undefined\nlet unsubscribePrefsChange: (() => void) | undefined\n\nconst TOOL_STORAGE_ID = \"theme-preferences\"\n\nfunction ensureThemeLink(style: string) {\n\tif (themeLinks.has(style)) return\n\tconst link = document.createElement(\"link\")\n\tlink.rel = \"stylesheet\"\n\tlink.href = style\n\tdocument.head.appendChild(link)\n\tthemeLinks.set(style, link)\n}\n\nfunction removeThemeLink(style: string) {\n\tconst link = themeLinks.get(style)\n\tif (link) {\n\t\tlink.remove()\n\t\tthemeLinks.delete(style)\n\t}\n}\n\nfunction getMode(): \"light\" | \"dark\" {\n\treturn window.matchMedia(\"(prefers-color-scheme: dark)\").matches\n\t\t? \"dark\"\n\t\t: \"light\"\n}\n\nfunction getPreferredThemeId(prefs: any): string {\n\tconst mode = getMode()\n\tconst themeId = prefs ? (mode === \"dark\" ? prefs.dark : prefs.light) : undefined\n\treturn themeId || defaultThemeIds()[mode]\n}\n\nfunction snapshot(): ActiveThemeState {\n\tconst prefs = currentPrefsHandle?.doc()\n\tconst mode = getMode()\n\tconst defaults = defaultThemeIds()\n\treturn {\n\t\tmode,\n\t\tthemeId: getPreferredThemeId(prefs),\n\t\tlight: prefs?.light || defaults.light,\n\t\tdark: prefs?.dark || defaults.dark,\n\t\tpreferencesUrl: currentPrefsHandle?.url,\n\t}\n}\n\nfunction emit() {\n\tcurrentState = snapshot()\n\tfor (const listener of listeners) listener(currentState)\n}\n\nfunction applyTheme(themeId: string) {\n\tif (themeId) document.documentElement.setAttribute(\"theme\", themeId)\n}\n\nfunction applyFromPrefs() {\n\tapplyTheme(getPreferredThemeId(currentPrefsHandle?.doc()))\n\temit()\n}\n\nfunction subscribeToProvider<T>(\n\telement: HTMLElement,\n\tselector: Record<string, unknown>,\n\tonValue: (value: T) => void\n) {\n\tconst view = element.closest(\"patchwork-view\")\n\tconst dispatchElement = (view as HTMLElement) ?? element\n\tconst channel = new MessageChannel()\n\tconst port = channel.port2\n\tconst controller = new AbortController()\n\n\tport.addEventListener(\n\t\t\"message\",\n\t\t(event: MessageEvent) => {\n\t\t\tif ((event.data as any)?.type === \"change\") onValue((event.data as any).value as T)\n\t\t},\n\t\t{signal: controller.signal}\n\t)\n\tport.start()\n\n\tdispatchElement.dispatchEvent(\n\t\tnew CustomEvent(\"patchwork:subscribe\", {\n\t\t\tdetail: {selector, port: channel.port1},\n\t\t\tbubbles: true,\n\t\t\tcomposed: true,\n\t\t})\n\t)\n\n\treturn () => {\n\t\tif (controller.signal.aborted) return\n\t\tcontroller.abort()\n\t\ttry {\n\t\t\tport.postMessage({type: \"unsubscribe\"})\n\t\t} catch {}\n\t\ttry {\n\t\t\tport.close()\n\t\t} catch {}\n\t}\n}\n\nfunction ensureThemePreferencesShape(prefsHandle: ThemePreferencesHandle) {\n\tprefsHandle.change((doc: any) => {\n\t\tdoc[\"@patchwork\"] = {type: \"theme-preferences\"}\n\t})\n}\n\nasync function useThemePreferencesHandle(prefsHandle: ThemePreferencesHandle) {\n\tensureThemePreferencesShape(prefsHandle)\n\n\tif (currentPrefsHandle === prefsHandle) return\n\tif (\n\t\tcurrentPrefsHandle?.url &&\n\t\tprefsHandle.url &&\n\t\tcurrentPrefsHandle.url === prefsHandle.url\n\t) {\n\t\treturn\n\t}\n\n\tunsubscribePrefsChange?.()\n\tcurrentPrefsHandle = prefsHandle\n\tapplyFromPrefs()\n\n\tprefsHandle.on?.(\"change\", applyFromPrefs)\n\tunsubscribePrefsChange = () => prefsHandle.off?.(\"change\", applyFromPrefs)\n}\n\nasync function useToolStoragePreferences(element: HTMLElement, storageUrl: string) {\n\tconst repo = (element as any).repo ?? (window as any).repo\n\tif (!repo) return\n\n\tconst prefsHandle = await repo.find(storageUrl)\n\tawait useThemePreferencesHandle(prefsHandle)\n}\n\nfunction connectThemePreferences(element: HTMLElement) {\n\tif (currentPrefsHandle) return\n\tif (storageStarted && storageElement === element) return\n\n\tunsubscribeStorage?.()\n\tstorageStarted = true\n\tstorageElement = element\n\n\tlet lastStorageUrl: string | undefined\n\n\tunsubscribeStorage = subscribeToProvider<string | undefined>(\n\t\telement,\n\t\t{type: \"patchwork:tool-storage\", toolId: TOOL_STORAGE_ID},\n\t\t(storageUrl) => {\n\t\t\tif (!storageUrl || storageUrl === lastStorageUrl) return\n\t\t\tlastStorageUrl = storageUrl\n\t\t\tuseToolStoragePreferences(element, storageUrl).catch(() => {\n\t\t\t\t// Theme preferences are best-effort; keep the default theme.\n\t\t\t})\n\t\t}\n\t)\n}\n\nfunction watchThemeRegistry() {\n\tconst themeRegistry = getRegistry(\"patchwork:theme\") as any\n\n\tfor (const theme of themeRegistry.all?.() || []) {\n\t\tif (theme.style) ensureThemeLink(theme.style)\n\t}\n\n\tthemeRegistry.on(\"registered\", (plugin: any) => {\n\t\tif (plugin.style) ensureThemeLink(plugin.style)\n\t})\n\tthemeRegistry.on(\"removed\", () => {\n\t\tconst knownStyles = new Set(\n\t\t\t(themeRegistry.all?.() || [])\n\t\t\t\t.map((t: any) => t.style)\n\t\t\t\t.filter(Boolean)\n\t\t)\n\t\tfor (const [style] of themeLinks) {\n\t\t\tif (!bundledStyles.has(style) && !knownStyles.has(style)) {\n\t\t\t\tremoveThemeLink(style)\n\t\t\t}\n\t\t}\n\t})\n}\n\n// Load the bundled theme stylesheets and keep the registry-provided ones in\n// sync. Idempotent \u2014 safe to call from every entry point. This is the CSS side\n// of theming, independent of where the *active* theme id is sourced from.\nfunction bootstrapThemeStyles() {\n\tif (stylesBootstrapped) return\n\tstylesBootstrapped = true\n\tfor (const href of bundledStyleUrls) ensureThemeLink(href)\n\twatchThemeRegistry()\n}\n\nexport function startActiveTheme(\n\telement?: HTMLElement,\n\tpreferencesHandle?: ThemePreferencesHandle\n) {\n\tif (preferencesHandle) {\n\t\tuseThemePreferencesHandle(preferencesHandle).catch(() => {\n\t\t\t// Theme preferences are best-effort; keep the default theme.\n\t\t})\n\t} else if (element) {\n\t\tconnectThemePreferences(element)\n\t}\n\tif (started) return\n\tstarted = true\n\n\tbootstrapThemeStyles()\n\tapplyFromPrefs()\n\n\twindow\n\t\t.matchMedia(\"(prefers-color-scheme: dark)\")\n\t\t.addEventListener(\"change\", applyFromPrefs)\n}\n\n/**\n * Drive the active theme from a `patchwork:current-theme` provider instead of\n * from local preferences. Used by the titlebar theme tool, which runs isolated\n * and mirrors whatever theme the host is showing: it applies each theme id the\n * provider emits and re-applies whenever that value changes.\n *\n * Stylesheets are still loaded locally so the referenced themes render; only\n * the *choice* of active theme comes from the provider. Deliberately does not\n * wire up preferences or the prefers-color-scheme listener \u2014 those would fight\n * the provider for control of the `theme` attribute.\n *\n * @returns an unsubscribe function.\n */\nexport function startActiveThemeFromProvider(element: HTMLElement) {\n\tbootstrapThemeStyles()\n\n\treturn subscribeToProvider<string | ActiveThemeState | undefined>(\n\t\telement,\n\t\t{type: CURRENT_THEME_SELECTOR},\n\t\t(value) => {\n\t\t\tconst themeId = typeof value === \"string\" ? value : value?.themeId\n\t\t\tif (themeId) applyTheme(themeId)\n\t\t}\n\t)\n}\n\ntype CurrentThemeSubscribeEvent = CustomEvent<{\n\tselector: {type: string; [key: string]: unknown}\n\tport: MessagePort\n}>\n\n/**\n * Answer `patchwork:current-theme` subscriptions with the active theme id,\n * pushing a fresh value whenever the theme changes. This is the host-side\n * counterpart to {@link startActiveThemeFromProvider}: it lets isolated tools\n * (the titlebar theme tool) mirror the host's active theme across the isolation\n * boundary, where the theme is relayed by the providers bridge.\n *\n * The listener is installed on the given root (the theme tray installs it on\n * `document.documentElement`) so that bridged `patchwork:subscribe` events \u2014\n * which bubble up to `<html>` \u2014 reach it. Implements the provider port protocol\n * directly to avoid a dependency on `@inkandswitch/patchwork-providers`.\n *\n * @returns an unsubscribe function that removes the listener and tears down any\n * live subscriptions.\n */\nexport function serveCurrentThemeProvider(root: HTMLElement): () => void {\n\tconst responders = new Set<() => void>()\n\n\tconst onSubscribe = (event: Event) => {\n\t\tconst detail = (event as CurrentThemeSubscribeEvent).detail\n\t\tif (!detail || detail.selector?.type !== CURRENT_THEME_SELECTOR) return\n\t\tevent.stopPropagation()\n\n\t\tconst port = detail.port\n\t\tlet alive = true\n\t\tconst emit = () => {\n\t\t\tif (!alive) return\n\t\t\tport.postMessage({type: \"change\", value: getActiveThemeState().themeId})\n\t\t}\n\t\tconst removeThemeListener = onActiveThemeChange(emit)\n\n\t\tconst stop = () => {\n\t\t\tif (!alive) return\n\t\t\talive = false\n\t\t\tremoveThemeListener()\n\t\t\tresponders.delete(stop)\n\t\t\ttry {\n\t\t\t\tport.close()\n\t\t\t} catch {}\n\t\t}\n\t\tresponders.add(stop)\n\n\t\tport.onmessage = (e: MessageEvent) => {\n\t\t\tif ((e.data as any)?.type === \"unsubscribe\") stop()\n\t\t}\n\t\tport.start?.()\n\t}\n\n\troot.addEventListener(\"patchwork:subscribe\", onSubscribe)\n\n\treturn () => {\n\t\troot.removeEventListener(\"patchwork:subscribe\", onSubscribe)\n\t\tfor (const stop of [...responders]) stop()\n\t}\n}\n\nexport function getActiveThemeState() {\n\treturn currentState || snapshot()\n}\n\n/**\n * Best-effort color scheme for a theme. Prefers the plugin's declared\n * `colorScheme`, otherwise sniffs `color-scheme: light|dark` out of the theme's\n * stylesheet. Returns `undefined` when neither is available (treated as\n * scheme-agnostic by callers). Shared by the theme tray and the theme picker\n * tool so they group light/dark themes the same way.\n */\nexport async function detectColorScheme(theme: {\n\tcolorScheme?: \"light\" | \"dark\"\n\tstyle?: string\n}): Promise<\"light\" | \"dark\" | undefined> {\n\tif (theme.colorScheme) return theme.colorScheme\n\tif (!theme.style) return undefined\n\ttry {\n\t\tconst res = await fetch(theme.style)\n\t\tconst css = await res.text()\n\t\tconst match = css.match(/color-scheme:\\s*(light|dark)/)\n\t\treturn (match?.[1] as \"light\" | \"dark\") ?? undefined\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\nexport function setThemeForCurrentMode(themeId: string) {\n\tconst mode = getMode()\n\tsetThemeForMode(mode, themeId)\n}\n\nexport function setThemeForMode(mode: \"light\" | \"dark\", themeId: string) {\n\tcurrentPrefsHandle?.change((doc: any) => {\n\t\tdoc[mode] = themeId\n\t})\n}\n\nexport function hasThemePreferences() {\n\treturn Boolean(currentPrefsHandle)\n}\n\nexport function onActiveThemeChange(listener: (state: ActiveThemeState) => void) {\n\tlisteners.add(listener)\n\tlistener(getActiveThemeState())\n\treturn () => listeners.delete(listener)\n}\n"],
5
+ "mappings": ";;;;;;AAAA,SAAQ,mBAAkB;;;;;;AAqBnB,IAAM,yBAAyB;AAatC,IAAM,oBAAoB,EAAC,OAAO,UAAU,MAAM,QAAO;AAEzD,SAAS,kBAAkB;AAC1B,QAAM,OAAO,SAAS;AACtB,SAAO;AAAA,IACN,OAAO,KAAK,aAAa,kBAAkB,KAAK,kBAAkB;AAAA,IAClE,MAAM,KAAK,aA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3CS64F.js")).startActiveTheme();
8
+ (await import("./active-theme-6H5UANUR.js")).startActiveTheme();
9
9
  })();
10
10
  var plugins = [
11
11
  {
@@ -57,7 +57,7 @@ var plugins = [
57
57
  unlisted: true,
58
58
  forTitleBar: true,
59
59
  async load() {
60
- const { ThemeTitlebarTool } = await import("./theme-titlebar-BO2Y2GRN.js");
60
+ const { ThemeTitlebarTool } = await import("./theme-titlebar-UX4BND5Z.js");
61
61
  return ThemeTitlebarTool;
62
62
  }
63
63
  },
@@ -68,7 +68,7 @@ var plugins = [
68
68
  icon: "Palette",
69
69
  tags: ["system-tray"],
70
70
  async load() {
71
- const { ThemeTray } = await import("./theme-tray-V6BEXQWR.js");
71
+ const { ThemeTray } = await import("./theme-tray-B477G2WR.js");
72
72
  return ThemeTray;
73
73
  }
74
74
  },
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  startActiveThemeFromProvider
3
- } from "./chunk-DH4YUYFJ.js";
3
+ } from "./chunk-HHCCYVOT.js";
4
4
  import "./chunk-L7WQSSFT.js";
5
5
 
6
6
  // src/theme-titlebar.ts
@@ -18,4 +18,4 @@ function ThemeTitlebarTool(_handle, element) {
18
18
  export {
19
19
  ThemeTitlebarTool
20
20
  };
21
- //# sourceMappingURL=theme-titlebar-BO2Y2GRN.js.map
21
+ //# sourceMappingURL=theme-titlebar-UX4BND5Z.js.map
@@ -5,7 +5,7 @@ import {
5
5
  serveCurrentThemeProvider,
6
6
  setThemeForCurrentMode,
7
7
  startActiveTheme
8
- } from "./chunk-DH4YUYFJ.js";
8
+ } from "./chunk-HHCCYVOT.js";
9
9
  import "./chunk-L7WQSSFT.js";
10
10
 
11
11
  // src/theme-tray.tsx
@@ -368,4 +368,4 @@ _$delegateEvents(["click", "input"]);
368
368
  export {
369
369
  ThemeTray
370
370
  };
371
- //# sourceMappingURL=theme-tray-V6BEXQWR.js.map
371
+ //# sourceMappingURL=theme-tray-B477G2WR.js.map
@@ -4,7 +4,7 @@ import {
4
4
  onActiveThemeChange,
5
5
  setThemeForMode,
6
6
  startActiveTheme
7
- } from "./chunk-DH4YUYFJ.js";
7
+ } from "./chunk-HHCCYVOT.js";
8
8
  import "./chunk-L7WQSSFT.js";
9
9
 
10
10
  // src/tool.tsx
@@ -0,0 +1,2 @@
1
+ import{r as a,s as b}from"./chunk-U4IJVHXK.js";import"./chunk-FW4363Y4.js";export{a as IsolatedDocumentArea,b as mountIsolationRoot};
2
+ //# sourceMappingURL=IsolatedDocumentArea-5WRK3TWL.js.map
@@ -0,0 +1,2 @@
1
+ import{a as H,b as de,c as M,d as R}from"./chunk-YERFWP5I.js";import{a as Ie,b as B,c as j,d as te,e as re,f as oe,g as ne,h as ie,i as ae,j as le,k as se,l as O,m as P,n as W,o as ce,p as ue,q as me,r as fe}from"./chunk-U4IJVHXK.js";import{b as Le}from"./chunk-FW4363Y4.js";import{template as _}from"solid-js/web";import{delegateEvents as nt}from"solid-js/web";import{memo as it}from"solid-js/web";import{setStyleProperty as at}from"solid-js/web";import{setAttribute as Y}from"solid-js/web";import{effect as I}from"solid-js/web";import{getOwner as k}from"solid-js/web";import{use as T}from"solid-js/web";import{insert as v}from"solid-js/web";import{createComponent as m}from"solid-js/web";import"@inkandswitch/patchwork-elements";import{subscribe as wt}from"@inkandswitch/patchwork-providers";import{template as q}from"solid-js/web";import{delegateEvents as Ae}from"solid-js/web";import{memo as xe}from"solid-js/web";import{insert as pe}from"solid-js/web";import{createComponent as L}from"solid-js/web";import{For as We,Show as z}from"solid-js";var Fe=q("<div class=threepane-widgets>"),Oe=q("<div class=threepane-widgets__empty><button type=button class=threepane-widgets__add>\uFF0B Add document list"),Pe=q("<div class=threepane-widget>");function he(e){let i=()=>{let o=e.rootFolderUrl(),n=e.configHandle();!o||!n||n.change(r=>{r.sidebar.widgets.push([M,o])})};return(()=>{var o=Fe();return pe(o,L(z,{get when(){return e.ready()},get children(){return L(z,{get when(){return e.widgets().length},get fallback(){return L(z,{get when(){return xe(()=>!!e.rootFolderUrl())()&&e.configHandle()},get children(){var n=Oe(),r=n.firstChild;return r.$$click=i,n}})},get children(){return L(We,{get each(){return e.widgets()},children:n=>(()=>{var r=Pe();return pe(r,L(W,{slot:n})),r})()})}})}})),o})()}Ae(["click"]);import{template as we}from"solid-js/web";import{setAttribute as He}from"solid-js/web";import{effect as Me}from"solid-js/web";import{insert as ge}from"solid-js/web";import{createComponent as K}from"solid-js/web";import{For as Be,Show as je}from"solid-js";var Ne=we("<div class=frame-tray>"),Ve=we("<div class=frame-tray__item>");function ve(e){return K(je,{get when(){return e.slots().length},get children(){var i=Ne();return ge(i,K(Be,{get each(){return P(e.slots())},children:o=>(()=>{var n=Ve();return ge(n,K(W,{slot:o})),Me(()=>He(n,"data-tray-id",O(o))),n})()})),i}})}import{createEffect as V,createMemo as vt,createSignal as b,onCleanup as C,onMount as Ce,Show as S}from"solid-js";import{render as _t}from"solid-js/web";import{createDocOfDatatype2 as qe}from"@inkandswitch/patchwork-plugins";import{getRegistry as ze}from"@inkandswitch/patchwork-plugins";function N(e){return ze("patchwork:datatype").loadWhenReady(e)}var Ke=new Set(["document-title","spacer"]);function _e(e){return e?[[M,e]]:[]}function Ge(e,i){if(!((e.version??0)>=1)){if(e.sidebar||(e.sidebar={widgets:[]}),i&&!e.sidebar.widgets?.length&&(e.sidebar.widgets=_e(i)),!e.tray)e.tray=H.slice();else{let o=P(e.tray);o.length!==e.tray.length&&(e.tray=o);let n=new Set(e.tray.map(r=>O(r)));for(let r of H)n.has(r)||(e.tray.push(r),n.add(r))}e.doctitle?.tools?.length||(e.doctitle={...e.doctitle,tools:de.slice()}),!(!e.sidebar.widgets?.length&&!i)&&(e.version=1)}}async function ye(e,i){let o=e.doc()?.rootFolderUrl,n=e.doc()?.tools?.threepane;if(n){let l=await i.find(n);if((l.doc()?.version??0)>=1)return;l.change(d=>Ge(d,o));return}let r=await N("threepane:config");if(!r){console.warn("frame: threepane:config datatype never registered");return}if(e.doc()?.tools?.threepane)return;let t=e.doc(),a=(t?.documentToolbarToolIds??[]).filter(l=>!Ke.has(l)),s=await qe(r,i);s.change(l=>{a.length&&(l.doctitle.tools=a),l.sidebar.widgets=_e(t?.rootFolderUrl),l.tray||(l.tray=H.slice()),t?.rootFolderUrl?l.version=1:delete l.version}),e.change(l=>{l.tools||(l.tools={}),l.tools.threepane||(l.tools.threepane=s.url)})}var Se=Le(Ie(),1);import{createDocOfDatatype2 as Ye}from"@inkandswitch/patchwork-plugins";var g=(0,Se.default)("patchwork:threepane:examples");async function $e(e,i){let o=e.doc();if(!o?.rootFolderUrl){g("skipped \u2014 account has no rootFolderUrl");return}if(o.exampleDocsSeededAt){g("skipped \u2014 already ran for this account at",new Date(o.exampleDocsSeededAt).toISOString());return}g("claiming marker on account",e.url),e.change(u=>{u.exampleDocsSeededAt||(u.exampleDocsSeededAt=Date.now())});let n=await i.find(o.rootFolderUrl),r=n.doc()?.docs?.length??0;if(r){g(`skipped \u2014 root folder already has ${r} doc(s); only fresh accounts are seeded`);return}let t=window.location.hostname.includes("gaios"),a=t?[]:await Je();if(g(t?"gaios examples":"bundle init scripts:",a),!t&&!a.length){g("skipped \u2014 no static module bundles to ask");return}let s=await N("folder");if(!s){g("folder datatype never registered; giving up");return}let l=await Ye(s,i,u=>{u.title="Examples"});if(t){let{seedGaiosExamples:u}=await import("./gaiosExamples-YDNQB35L.js");await u(i,l)}for(let u of a)try{await(await import(u)).default?.(i,l),g("ran init script",u)}catch(c){g("init script unavailable or failed",u,c)}let d=l.doc()?.docs?.length??0;if(!d){g("no bundle contributed any documents");return}n.change(u=>{u.docs.unshift({name:"Examples",type:"folder",url:l.url})}),g(`seeded ${d} document(s) into Examples folder`,l.url)}var be="https://patchwork-tools.netlify.app/init.js",De="https://patchwork-base.netlify.app/init.js";function Xe(){return document.documentElement.getAttribute("data-examples")==="site"}async function Je(){let e=Xe(),i=window.patchwork?.packages;if(!i?.urls)return e?[]:[De,be];await i.doneLoading;let o=Object.values(i.urls).filter(r=>typeof r=="string"&&!r.startsWith("automerge:")).map(r=>new URL("init.js",new URL(r,document.baseURI)).href);if(e)return[...new Set(o)];let n=o.length?[]:[De];return[...new Set([...o,...n,be])]}var ke="patchwork:add-to-sidebar";function Qe(e,i){e.docs||(e.docs=[]);let o=e.docs,n=o.findIndex(r=>r.url===i.url);if(n!==0){if(n>0){let{name:r,type:t}=o[n];o.splice(n,1),o.unshift({url:i.url,name:r,type:t});return}o.unshift({url:i.url,name:i.name,type:i.type})}}function Ze(e,i){return new Promise(o=>{let n=()=>{let r=e.doc(),t=r&&i(r);t&&(e.off("change",n),o(t))};e.on("change",n),n()})}function Te(e,i,o){let n=r=>{let t=r.detail;if(!t?.url)return;r.preventDefault(),r.stopPropagation();let a=(async()=>{let s=await Ze(o,d=>d.rootFolderUrl);(await i.find(s)).change(d=>Qe(d,{url:t.url,name:t.name||"Untitled",type:t.type||"unknown"}))})();a.catch(s=>console.error("threepane: couldn't add to sidebar",s)),t.respondWith?.(a)};return e.addEventListener(ke,n),()=>e.removeEventListener(ke,n)}import{createEffect as et,createMemo as tt,createSignal as rt,onCleanup as ot}from"solid-js";function G(e){let[i,o]=rt(0);return et(()=>{let n=e();if(!n)return;let r=()=>o(t=>t+1);n.on("change",r),ot(()=>n.off("change",r))}),tt(()=>(i(),e()?.doc()))}var lt=_("<div class=frame-shell><aside class=frame-warning-banner>research grade software. do not share links. sharing a doc is sharing your account.</aside><div class=frame><patchwork-view component=patchwork-selected-doc-provider><patchwork-view component=patchwork-account-provider><patchwork-view component=patchwork-tool-storage-provider><patchwork-view component=patchwork-worker-provider>",!0,!1,!1),st=_("<div style=display:contents>"),dt=_("<div class=main-area>"),ct=_("<div class=frame__popover-backdrop><div class=frame__popover role=dialog aria-modal=true><div class=frame__popover-toolbar><patchwork-view tool-id=doc-openwith></patchwork-view></div><div class=frame__popover-body><patchwork-view>",!0,!1,!1),ut=_('<button type=button class="frame__sidebar-toggle frame__left-toggle">'),mt=_("<div class=threepane-sidebar><div class=threepane-sidebar__footer><footer class=threepane-account-bar><button type=button class=threepane-account-bar__button>Settings"),ft=_("<div class=frame__tray-dock>"),pt=_('<button type=button class="threepane-account-bar__button threepane-account-bar__avatar"title=Account aria-label=Account><patchwork-view tool-id=contact-avatar>',!0,!1,!1),ht=_("<button type=button class=threepane-account-bar__button>Packages"),gt=_('<svg xmlns=http://www.w3.org/2000/svg width=18 height=18 viewBox="0 0 24 24"fill=none stroke=var(--studio-chrome-line) stroke-width=1.75 stroke-linecap=round stroke-linejoin=round><rect width=18 height=18 x=3 y=3 rx=2></rect><path d="M9 3v18">'),X=(e,i)=>{let[o,n]=b(!1);return V(()=>{let r=i();if(!r)return;n(!1);let t=a=>{a.detail?.componentId===e&&n(!0)};r.addEventListener("patchwork:mounted",t),C(()=>r.removeEventListener("patchwork:mounted",t))}),o};function J(e,i){e.dispatchEvent(new CustomEvent("patchwork:open-document",{detail:i,bubbles:!0,composed:!0}))}function yt({handle:e,repo:i,...o}){me();let n=e.url,[r,t]=b(),a=X("patchwork-account-provider",r),[s,l]=b(),d=X("patchwork-tool-storage-provider",s),[u,c]=b(),p=X("patchwork-selected-doc-provider",u),f=vt(()=>p()&&a()&&d());return(()=>{var w=lt(),E=w.firstChild,Q=E.firstChild,A=E.nextSibling,h=A.firstChild,D=h.firstChild,$=D.firstChild,U=$.firstChild;return v(E,m(S,{get when(){return o.isolation},get children(){return[" ","isolation is highly experimental. if things are broken, switch back to wild west."]}}),null),T(c,h),h._$owner=k(),T(t,D),D.docUrl=n,D._$owner=k(),T(l,$),$.docUrl=n,$._$owner=k(),U._$owner=k(),v(U,m(S,{get when(){return f()},get children(){return m(bt,{handle:e,repo:i,get isolation(){return o.isolation}})}})),w})()}function bt(e){let i=B(()=>e.handle.url,{repo:e.repo});(async()=>{await ye(e.handle,e.repo),await $e(e.handle,e.repo)})().catch(y=>{console.error("frame: account bootstrap failed",y)});let o=G(i),n=e.handle.url,r=()=>o()?.tools?.threepane,t=B(()=>r(),{repo:e.repo}),a=G(t),s=()=>a()?.doctitle?.tools,l=()=>a()?.sidebar?.widgets??[],d=()=>a()?.tray??[],u=()=>o()?.rootFolderUrl,c=ie(),p=ae("left",{isCollapsed:c.isSidebarCollapsed,setCollapsed:c.setIsSidebarCollapsed,setWidth:c.setLeftSidebarWidth}),f,[w,E]=b(null),[Q,A]=b(null);Ce(()=>{let y=wt(f,{type:"patchwork:selected-view"},x=>E(x));C(y),C(Te(f,e.repo,e.handle))});let h=()=>w()?.url,D=()=>w()?.toolId??void 0,$=()=>oe(j.rightWidth,re),U=()=>ne(j.rightCollapsed),[Ee,Z]=b(),Ue=le(Ee,h),[ee,Re]=b(!1);return V(()=>{ee()||(e.isolation||!h()||Ue())&&Re(!0)}),(()=>{var y=st(),x=f;return typeof x=="function"?T(x,y):f=y,v(y,m(St,{accountDocUrl:n,sidebarState:c,sidebarResize:p,sidebarWidgets:l,traySlots:d,configHandle:t,rootFolderUrl:u,widgetsReady:ee,contactUrl:()=>o()?.contactUrl,moduleSettingsUrl:()=>o()?.moduleSettingsUrl,get isolation(){return e.isolation},onInterceptOpen:A,get children(){return m(S,{get when(){return h()},get fallback(){return(()=>{var F=dt();return v(F,m(ce,{viewKey:h,selectedDocUrl:h,toolId:D,ref:Z})),F})()},get children(){return m(S,{get when(){return e.isolation},get fallback(){return m(ue,{setMainDocElement:Z,selectedDocUrl:h,selectedToolId:D,doctitleSlots:s,get isLeftCollapsed(){return c.isSidebarCollapsed},initialRightWidth:$,initialRightCollapsed:U})},get children(){return m(fe,{get contactUrl(){return o()?.contactUrl},selectedDocUrl:h,selectedToolId:D,doctitleSlots:s,get isLeftCollapsed(){return c.isSidebarCollapsed},initialRightWidth:$,initialRightCollapsed:U})}})}})}}),null),v(y,m(S,{get when(){return Q()},children:F=>m(Dt,{get view(){return F()},onClose:()=>A(null)})}),null),y})()}function Dt(e){let[i,o]=b(e.view.toolId??void 0);V(()=>o(e.view.toolId??void 0));let n;return Ce(()=>{let r=s=>{s.key==="Escape"&&e.onClose()};window.addEventListener("keydown",r),C(()=>window.removeEventListener("keydown",r));let t=n;if(!t)return;let a=s=>{let{url:l,toolId:d}=s.detail;l&&(s.stopPropagation(),o(d??void 0))};t.addEventListener("patchwork:open-document",a),C(()=>t.removeEventListener("patchwork:open-document",a))}),(()=>{var r=ct(),t=r.firstChild,a=t.firstChild,s=a.firstChild,l=a.nextSibling,d=l.firstChild;r.$$click=()=>e.onClose(),t.$$click=c=>c.stopPropagation();var u=n;return typeof u=="function"?T(u,t):n=t,s._$owner=k(),d._$owner=k(),I(c=>{var p=e.view.url,f=e.view.url,w=i();return p!==c.e&&(s.docUrl=c.e=p),f!==c.t&&(d.docUrl=c.t=f),w!==c.a&&(d.toolId=c.a=w),c},{e:void 0,t:void 0,a:void 0}),r})()}function St(e){let i=e.sidebarState.isSidebarCollapsed,o=()=>e.traySlots().length>0,n,r;return V(()=>{if(i())return;let t=n;if(!t)return;let a=r,s=l=>{let{url:d,toolId:u}=l.detail;if(e.isolation&&d&&a&&l.composedPath().includes(a)){l.stopPropagation(),e.onInterceptOpen?.({url:d,toolId:u??null});return}t.getBoundingClientRect().width<=window.innerWidth*.75||(e.sidebarState.setIsSidebarCollapsed(!0),window.dispatchEvent(new CustomEvent(te)))};t.addEventListener("patchwork:open-document",s),C(()=>t.removeEventListener("patchwork:open-document",s))}),[(()=>{var t=ut();return t.$$click=()=>e.sidebarState.setIsSidebarCollapsed(a=>!a),v(t,m($t,{})),I(a=>{var s=i()?"Show sidebar":"Hide sidebar",l=i()?"Show sidebar":"Hide sidebar",d=!i();return s!==a.e&&Y(t,"title",a.e=s),l!==a.t&&Y(t,"aria-label",a.t=l),d!==a.a&&Y(t,"aria-pressed",a.a=d),a},{e:void 0,t:void 0,a:void 0}),t})(),m(se,{side:"left",isCollapsed:i,get width(){return e.sidebarState.leftSidebarWidth},get onMouseDown(){return e.sidebarResize.handleMouseDown},get onToggleClick(){return e.sidebarResize.handleToggleClick},get children(){var t=mt(),a=t.firstChild,s=a.firstChild,l=s.firstChild,d=n;typeof d=="function"?T(d,t):n=t,v(t,m(he,{get widgets(){return e.sidebarWidgets},get configHandle(){return e.configHandle},get rootFolderUrl(){return e.rootFolderUrl},get ready(){return e.widgetsReady}}),a);var u=r;return typeof u=="function"?T(u,a):r=a,v(s,m(S,{get when(){return e.contactUrl()},children:c=>(()=>{var p=pt(),f=p.firstChild;return p.$$click=w=>J(w.currentTarget,{url:e.accountDocUrl,toolId:"account-picker"}),f._$owner=k(),I(()=>f.docUrl=c()),p})()}),l),v(s,m(S,{get when(){return e.moduleSettingsUrl()},children:c=>(()=>{var p=ht();return p.$$click=f=>J(f.currentTarget,{url:c(),toolId:"packages"}),p})()}),l),l.$$click=c=>J(c.currentTarget,{url:e.accountDocUrl,toolId:"frame-configurator"}),I(()=>t.classList.toggle("threepane-sidebar--has-tray",!!o())),t}}),m(S,{get when(){return o()},get children(){var t=ft();return v(t,m(ve,{get slots(){return e.traySlots}})),I(a=>{var s=!!i(),l=`${e.sidebarState.leftSidebarWidth()}px`;return s!==a.e&&t.classList.toggle("frame__tray-dock--collapsed",a.e=s),l!==a.t&&at(t,"width",a.t=l),a},{e:void 0,t:void 0}),t}}),it(()=>e.children)]}function $t(){return gt()}function Er(e){return(i,o)=>_t(()=>m(yt,{handle:i,get repo(){return o.repo},isolation:e}),o)}nt(["click"]);export{St as FrameLayout,yt as PatchworkFrame,Er as renderPatchworkFrame};
2
+ //# sourceMappingURL=PatchworkFrame-22UEOQ6E.js.map