@inkandswitch/patchwork-pkg-base 0.0.110 → 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 (20) 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/theming/dist/{active-theme-CC3CS64F.js → active-theme-6H5UANUR.js} +2 -2
  9. package/packages/theming/dist/{chunk-DH4YUYFJ.js → chunk-HHCCYVOT.js} +1 -2
  10. package/packages/theming/dist/chunk-HHCCYVOT.js.map +7 -0
  11. package/packages/theming/dist/main.js +3 -3
  12. package/packages/theming/dist/{theme-titlebar-BO2Y2GRN.js → theme-titlebar-UX4BND5Z.js} +2 -2
  13. package/packages/theming/dist/{theme-tray-V6BEXQWR.js → theme-tray-B477G2WR.js} +2 -2
  14. package/packages/theming/dist/tool.js +1 -1
  15. package/plugin-registry-url +1 -1
  16. package/packages/account-history/dist/assets/HistoryRecorder-_3PrVW6n.js.map +0 -1
  17. package/packages/theming/dist/chunk-DH4YUYFJ.js.map +0 -7
  18. /package/packages/theming/dist/{active-theme-CC3CS64F.js.map → active-theme-6H5UANUR.js.map} +0 -0
  19. /package/packages/theming/dist/{theme-titlebar-BO2Y2GRN.js.map → theme-titlebar-UX4BND5Z.js.map} +0 -0
  20. /package/packages/theming/dist/{theme-tray-V6BEXQWR.js.map → theme-tray-B477G2WR.js.map} +0 -0
@@ -1 +1 @@
1
- automerge:25J8uXbNL9ojTwWnJpMJJzMahP28
1
+ automerge:25656PAF9f4QGmJyW1J8fUhuP1F9
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkandswitch/patchwork-pkg-base",
3
- "version": "0.0.110",
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,M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;AAClD;AAAA,IACF;AAGAjC,UAAMI,QAAQ8D,cACZ,IAAIC,kBAAkB;AAAA,MACpB3D,KAAKyD;AAAAA,MACL3D,QAAQ8D;AAAAA,IAAAA,CACT,CACH;AAAA,EACF;AAEA,UAAA,MAAA;AAAA,QAAAC,OAAAC,OAAAA;AAAAD,SAAAE,UAEaP;AAAW,WAAAK;AAAAA,EAAA,GAAA;AAoB1B;AAEO,MAAMG,wBAAiDA,CAC5D9D,QACAN,YACGqE,OAAO,MAAAC,gBAAO3E,iBAAe;AAAA,EAACW;AAAAA,EAAc,IAAEoB,OAAI;AAAA,WAAE1B,QAAQ0B;AAAAA,EAAI;AAAA,EAAE1B;AAAgB,CAAA,GAAMA,OAAO;AAAEuE,eAAA,CAAA,OAAA,CAAA;","x_google_ignoreList":[0]}
@@ -93,7 +93,7 @@ const plugins = [{
93
93
  } = await __vitePreload(async () => {
94
94
  const {
95
95
  renderHistoryRecorder: 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
  };
@@ -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,aAAa,iBAAiB,KAAK,kBAAkB;AAAA,EACjE;AACD;AAEA,IAAM,mBAAmB,CAAC,eAAa,gBAAc,aAAW,EAAE;AAAA,EACjE,CAAC,SAAS,IAAI,IAAI,MAAM,YAAY,GAAG,EAAE;AAC1C;AACA,IAAM,gBAAgB,IAAI,IAAI,gBAAgB;AAC9C,IAAM,aAAa,oBAAI,IAA6B;AACpD,IAAM,YAAY,oBAAI,IAAuC;AAE7D,IAAI,UAAU;AACd,IAAI,qBAAqB;AACzB,IAAI;AACJ,IAAI;AACJ,IAAI,iBAAiB;AACrB,IAAI;AACJ,IAAI;AACJ,IAAI;AAEJ,IAAM,kBAAkB;AAExB,SAAS,gBAAgB,OAAe;AACvC,MAAI,WAAW,IAAI,KAAK,EAAG;AAC3B,QAAM,OAAO,SAAS,cAAc,MAAM;AA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AAI,CAAC,MAAM,MAAO,QAAO;AACzB,MAAI;AACH,UAAM,MAAM,MAAM,MAAM,MAAM,KAAK;AACnC,UAAM,MAAM,MAAM,IAAI,KAAK;AAC3B,UAAM,QAAQ,IAAI,MAAM,8BAA8B;AACtD,WAAQ,QAAQ,CAAC,KAA0B;AAAA,EAC5C,QAAQ;AACP,WAAO;AAAA,EACR;AACD;AAEO,SAAS,uBAAuB,SAAiB;AACvD,QAAM,OAAO,QAAQ;AACrB,kBAAgB,MAAM,OAAO;AAC9B;AAEO,SAAS,gBAAgB,MAAwB,SAAiB;AACxE,sBAAoB,OAAO,CAAC,QAAa;AACxC,QAAI,IAAI,IAAI;AAAA,EACb,CAAC;AACF;AAEO,SAAS,sBAAsB;AACrC,SAAO,QAAQ,kBAAkB;AAClC;AAEO,SAAS,oBAAoB,UAA6C;AAChF,YAAU,IAAI,QAAQ;AACtB,WAAS,oBAAoB,CAAC;AAC9B,SAAO,MAAM,UAAU,OAAO,QAAQ;AACvC;",
6
+ "names": ["emit"]
7
+ }
@@ -5,7 +5,7 @@ import {
5
5
 
6
6
  // src/main.ts
7
7
  (async function() {
8
- (await import("./active-theme-CC3CS64F.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
@@ -1 +1 @@
1
- automerge:2LpXu6dKDGmpNEPhqy8Y4P1tddAK
1
+ automerge:4EA4mxwxWigFfxawcVP3xc7o8mRK
@@ -1 +0,0 @@
1
- {"version":3,"file":"HistoryRecorder-_3PrVW6n.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 await docHandle.whenReady();\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","whenReady","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,CA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AA;AAC1B,QAAI,CAAC2D,mBAAmB;AACtBjC,cAAQC,KAAK,qCAAqC;AAClD;AAAA,IACF;AAGAlC,UAAMI,QAAQ+D,cACZ,IAAIC,kBAAkB;AAAA,MACpB5D,KAAK0D;AAAAA,MACL5D,QAAQ+D;AAAAA,IAAAA,CACT,CACH;AAAA,EACF;AAEA,UAAA,MAAA;AAAA,QAAAC,OAAAC,OAAAA;AAAAD,SAAAE,UAEaP;AAAW,WAAAK;AAAAA,EAAA,GAAA;AAoB1B;AAEO,MAAMG,wBAAiDA,CAC5D/D,QACAN,YACGsE,OAAO,MAAAC,gBAAO5E,iBAAe;AAAA,EAACW;AAAAA,EAAc,IAAEoB,OAAI;AAAA,WAAE1B,QAAQ0B;AAAAA,EAAI;AAAA,EAAE1B;AAAgB,CAAA,GAAMA,OAAO;AAAEwE,eAAA,CAAA,OAAA,CAAA;","x_google_ignoreList":[0]}
@@ -1,7 +0,0 @@
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\twhenReady?(): Promise<unknown>\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\tawait prefsHandle.whenReady?.()\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;;;;;;AAsBnB,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,aAAa,iBAAiB,KAAK,kBAAkB;AAAA,EACjE;AACD;AAEA,IAAM,mBAAmB,CAAC,eAAa,gBAAc,aAAW,EAAE;AAAA,EACjE,CAAC,SAAS,IAAI,IAAI,MAAM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