@powerhousedao/reactor-browser 6.2.3-dev.61 → 6.2.3-dev.62

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 (53) hide show
  1. package/dist/{attachment-service-DG6UkyMv.d.ts → attachment-service-CQ3JygJd.d.ts} +3 -3
  2. package/dist/{attachment-service-DG6UkyMv.d.ts.map → attachment-service-CQ3JygJd.d.ts.map} +1 -1
  3. package/dist/{client-Cq5avLW5.js → client-Bwiji4R6.js} +6 -2
  4. package/dist/client-Bwiji4R6.js.map +1 -0
  5. package/dist/{dispatch-C1VVTn5S.js → dispatch-BmdzdTwb.js} +15 -11
  6. package/dist/dispatch-BmdzdTwb.js.map +1 -0
  7. package/dist/{document-by-id-BRDkvmpn.js → document-by-id-BqNuTx4S.js} +2 -2
  8. package/dist/{document-by-id-BRDkvmpn.js.map → document-by-id-BqNuTx4S.js.map} +1 -1
  9. package/dist/{document-model-modules-Gsh1Xr7j.js → document-model-modules-Wjh92XAb.js} +192 -157
  10. package/dist/document-model-modules-Wjh92XAb.js.map +1 -0
  11. package/dist/{document-operations-BSzcF0mu.js → document-operations--Z0AOyyy.js} +74 -27
  12. package/dist/document-operations--Z0AOyyy.js.map +1 -0
  13. package/dist/{global-BuSwbbY0.d.ts → global-CPJA8ePb.d.ts} +56 -4
  14. package/dist/global-CPJA8ePb.d.ts.map +1 -0
  15. package/dist/{index-ewIc3pEO.d.ts → index-DRCTps7m.d.ts} +2 -2
  16. package/dist/{index-ewIc3pEO.d.ts.map → index-DRCTps7m.d.ts.map} +1 -1
  17. package/dist/index.d.ts +244 -18
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +305 -37
  20. package/dist/index.js.map +1 -1
  21. package/dist/make-ph-event-functions-C1JTfEw1.js +251 -0
  22. package/dist/make-ph-event-functions-C1JTfEw1.js.map +1 -0
  23. package/dist/navigation-B4fHR-Tm.js +315 -0
  24. package/dist/navigation-B4fHR-Tm.js.map +1 -0
  25. package/dist/{relational-DxHuX41f.js → relational-DZuyKp2y.js} +2 -2
  26. package/dist/{relational-DxHuX41f.js.map → relational-DZuyKp2y.js.map} +1 -1
  27. package/dist/{renown-D05wkobG.js → renown-CGQYQsvH.js} +2 -2
  28. package/dist/{renown-D05wkobG.js.map → renown-CGQYQsvH.js.map} +1 -1
  29. package/dist/{renown-CPAeJt5L.js → renown-DlkS61Dp.js} +28 -22
  30. package/dist/{renown-CPAeJt5L.js.map → renown-DlkS61Dp.js.map} +1 -1
  31. package/dist/src/ai/index.d.ts.map +1 -1
  32. package/dist/src/ai/index.js +3 -3
  33. package/dist/src/analytics/index.js +3 -3
  34. package/dist/src/graphql-client/entry.d.ts +2 -2
  35. package/dist/src/graphql-client/entry.js +3 -3
  36. package/dist/src/relational/index.js +1 -1
  37. package/dist/src/renown/index.d.ts +1 -1
  38. package/dist/src/renown/index.js +2 -2
  39. package/dist/src/rpc/index.d.ts +3 -1
  40. package/dist/src/rpc/index.d.ts.map +1 -1
  41. package/dist/src/rpc/index.js +1 -3
  42. package/dist/src/rpc/index.js.map +1 -1
  43. package/dist/{switchboard-3vHbIV5W.js → switchboard-DAvOdf_g.js} +8 -6
  44. package/dist/switchboard-DAvOdf_g.js.map +1 -0
  45. package/package.json +10 -10
  46. package/dist/client-Cq5avLW5.js.map +0 -1
  47. package/dist/dispatch-C1VVTn5S.js.map +0 -1
  48. package/dist/document-model-modules-Gsh1Xr7j.js.map +0 -1
  49. package/dist/document-operations-BSzcF0mu.js.map +0 -1
  50. package/dist/global-BuSwbbY0.d.ts.map +0 -1
  51. package/dist/make-ph-event-functions-CdsvEl5t.js +0 -55
  52. package/dist/make-ph-event-functions-CdsvEl5t.js.map +0 -1
  53. package/dist/switchboard-3vHbIV5W.js.map +0 -1
@@ -0,0 +1,251 @@
1
+ import { createContext, useContext, useEffect, useSyncExternalStore } from "react";
2
+ import { jsx } from "react/jsx-runtime";
3
+ import { capitalCase } from "change-case";
4
+ //#region src/hooks/ph-store.tsx
5
+ const ALL_KEYS = Symbol("all keys");
6
+ const listenersByStore = /* @__PURE__ */ new WeakMap();
7
+ const windowBound = /* @__PURE__ */ new WeakSet();
8
+ const subscribeCache = /* @__PURE__ */ new WeakMap();
9
+ function notifyKey(listeners, key) {
10
+ for (const set of [listeners.get(key), listeners.get(ALL_KEYS)]) for (const listener of set ?? []) listener();
11
+ if (windowBound.has(listeners) && typeof key === "string") window.dispatchEvent(new CustomEvent(`ph:${key}Updated`));
12
+ }
13
+ function createPHStore(initial = {}) {
14
+ const listeners = /* @__PURE__ */ new Map();
15
+ const store = new Proxy({ ...initial }, {
16
+ set: (target, key, value) => {
17
+ if (Reflect.get(target, key) === value) return true;
18
+ Reflect.set(target, key, value);
19
+ notifyKey(listeners, key);
20
+ return true;
21
+ },
22
+ deleteProperty: (target, key) => {
23
+ Reflect.deleteProperty(target, key);
24
+ notifyKey(listeners, key);
25
+ return true;
26
+ }
27
+ });
28
+ listenersByStore.set(store, listeners);
29
+ return store;
30
+ }
31
+ /** The keys a scoped store owns; every other key reads and writes its parent. */
32
+ const SCOPED_PH_KEYS = [
33
+ "selectedDriveId",
34
+ "selectedNodeId",
35
+ "navigation"
36
+ ];
37
+ const scopedKeys = new Set(SCOPED_PH_KEYS);
38
+ const parentOfScope = /* @__PURE__ */ new WeakMap();
39
+ /** A store with its own selection and navigation over `parent`, e.g. for an
40
+ * editor shown beside others; provide it with {@link PHStoreProvider}. */
41
+ function createScopedPHStore(parent, overrides = {}) {
42
+ const listeners = /* @__PURE__ */ new Map();
43
+ const own = {};
44
+ for (const key of SCOPED_PH_KEYS) if (overrides[key] !== void 0) Reflect.set(own, key, overrides[key]);
45
+ const store = new Proxy(own, {
46
+ get: (target, key) => scopedKeys.has(key) ? Reflect.get(target, key) : Reflect.get(parent, key),
47
+ has: (target, key) => scopedKeys.has(key) ? Reflect.has(target, key) : Reflect.has(parent, key),
48
+ set: (target, key, value) => {
49
+ if (!scopedKeys.has(key)) return Reflect.set(parent, key, value);
50
+ if (Reflect.get(target, key) === value) return true;
51
+ Reflect.set(target, key, value);
52
+ notifyKey(listeners, key);
53
+ return true;
54
+ },
55
+ deleteProperty: (target, key) => {
56
+ if (!scopedKeys.has(key)) return Reflect.deleteProperty(parent, key);
57
+ Reflect.deleteProperty(target, key);
58
+ notifyKey(listeners, key);
59
+ return true;
60
+ }
61
+ });
62
+ listenersByStore.set(store, listeners);
63
+ parentOfScope.set(store, parent);
64
+ return store;
65
+ }
66
+ /** Whether `store` was made by {@link createScopedPHStore}. */
67
+ function isScopedPHStore(store) {
68
+ return !!store && parentOfScope.has(store);
69
+ }
70
+ function listenersOf(store) {
71
+ const listeners = listenersByStore.get(store);
72
+ if (!listeners) throw new Error("Not a store made by createPHStore");
73
+ return listeners;
74
+ }
75
+ /** Subscribes to changes of `key`, or of every key when omitted. */
76
+ function subscribePHStore(store, listener, key = ALL_KEYS) {
77
+ const parent = parentOfScope.get(store);
78
+ if (parent && !scopedKeys.has(key)) {
79
+ const fromParent = subscribePHStore(parent, listener, key);
80
+ if (key !== ALL_KEYS) return fromParent;
81
+ const fromScope = subscribeOwn(store, listener, key);
82
+ return () => {
83
+ fromParent();
84
+ fromScope();
85
+ };
86
+ }
87
+ return subscribeOwn(store, listener, key);
88
+ }
89
+ function subscribeOwn(store, listener, key) {
90
+ const listeners = listenersOf(store);
91
+ const set = listeners.get(key) ?? /* @__PURE__ */ new Set();
92
+ listeners.set(key, set);
93
+ set.add(listener);
94
+ return () => {
95
+ set.delete(listener);
96
+ };
97
+ }
98
+ /** Notifies `key`'s listeners without a change, as re-setting a value does. */
99
+ function notifyPHStore(store, key) {
100
+ const parent = parentOfScope.get(store);
101
+ if (parent && !scopedKeys.has(key)) notifyPHStore(parent, key);
102
+ else notifyKey(listenersOf(store), key);
103
+ }
104
+ /** A subscribe for `key`, stable per store as useSyncExternalStore expects. */
105
+ function getPHStoreSubscribe(store, key) {
106
+ const cacheKey = key ?? ALL_KEYS;
107
+ const cache = subscribeCache.get(store) ?? /* @__PURE__ */ new Map();
108
+ subscribeCache.set(store, cache);
109
+ let subscribe = cache.get(cacheKey);
110
+ if (!subscribe) {
111
+ subscribe = (listener) => subscribePHStore(store, listener, cacheKey);
112
+ cache.set(cacheKey, subscribe);
113
+ }
114
+ return subscribe;
115
+ }
116
+ let activeStore;
117
+ /** The store bound with {@link bindPHStoreToWindow}, if any. */
118
+ function getActivePHStore() {
119
+ return activeStore;
120
+ }
121
+ /** The app's state outside React: the bound store, else `window.ph`. */
122
+ function getPHStore() {
123
+ if (activeStore) return activeStore;
124
+ return typeof window === "undefined" ? void 0 : window.ph;
125
+ }
126
+ /** The bound store; otherwise binds `window.ph` if it is a store, else a new
127
+ * store that takes over a plain `window.ph`'s values. */
128
+ function ensurePHStore() {
129
+ if (activeStore) return activeStore;
130
+ const current = typeof window === "undefined" ? void 0 : window.ph;
131
+ const store = current && listenersByStore.has(current) ? current : createPHStore();
132
+ bindPHStoreToWindow(store);
133
+ return store;
134
+ }
135
+ /** Makes `store` the app's state and `window.ph`; values set on a plain
136
+ * `window.ph` carry over where `store` has none. */
137
+ function bindPHStoreToWindow(store) {
138
+ activeStore = store;
139
+ if (typeof window === "undefined") return;
140
+ const previous = window.ph;
141
+ const previousListeners = previous && listenersByStore.get(previous);
142
+ if (previousListeners) windowBound.delete(previousListeners);
143
+ else if (previous) {
144
+ for (const [key, value] of Object.entries(previous)) if (!(key in store)) Reflect.set(store, key, value);
145
+ }
146
+ windowBound.add(listenersOf(store));
147
+ window.ph = store;
148
+ }
149
+ const PHStoreContext = createContext(void 0);
150
+ let mountedScopes = 0;
151
+ const warned = /* @__PURE__ */ new Set();
152
+ function isProduction() {
153
+ return typeof process !== "undefined" && false;
154
+ }
155
+ /** Warns once in development when a global setter runs while a scoped store
156
+ * is mounted, since it acts on the app's store and not the scope's. */
157
+ function warnGlobalSetterInScope(setter, hook) {
158
+ if (mountedScopes === 0 || warned.has(setter) || isProduction()) return;
159
+ warned.add(setter);
160
+ console.warn(`${setter} acts on the app's PH store while a scoped store is mounted; inside a scope, use ${hook}.`);
161
+ }
162
+ /** Hooks below read from `store`; without a provider they read `window.ph`. */
163
+ function PHStoreProvider(props) {
164
+ const scoped = isScopedPHStore(props.store);
165
+ useEffect(() => {
166
+ if (!scoped) return;
167
+ mountedScopes++;
168
+ return () => {
169
+ mountedScopes--;
170
+ };
171
+ }, [scoped]);
172
+ return /* @__PURE__ */ jsx(PHStoreContext.Provider, {
173
+ value: props.store,
174
+ children: props.children
175
+ });
176
+ }
177
+ function usePHStore() {
178
+ return useContext(PHStoreContext);
179
+ }
180
+ //#endregion
181
+ //#region src/hooks/make-ph-event-functions.ts
182
+ const isServer = typeof window === "undefined";
183
+ const updatedEventName = (key) => `ph:${key}Updated`;
184
+ /** Calls `onChange` whenever `key` is set: through the bound store, or the
185
+ * `ph:<key>Updated` event on pages that bound none. */
186
+ function subscribeToPHValue(key, onChange) {
187
+ if (isServer) return () => {};
188
+ const store = getActivePHStore();
189
+ if (store) return subscribePHStore(store, onChange, key);
190
+ const eventName = updatedEventName(key);
191
+ window.addEventListener(eventName, onChange);
192
+ return () => window.removeEventListener(eventName, onChange);
193
+ }
194
+ function makePHEventFunctions(key) {
195
+ const setEventName = `ph:set${capitalCase(key)}`;
196
+ const updateEventName = updatedEventName(key);
197
+ function setValue(value) {
198
+ if (isServer) return;
199
+ const store = getActivePHStore();
200
+ if (store) {
201
+ const unchanged = store[key] === value;
202
+ store[key] = value;
203
+ if (unchanged) notifyPHStore(store, key);
204
+ return;
205
+ }
206
+ const event = new CustomEvent(setEventName, { detail: { [key]: value } });
207
+ window.dispatchEvent(event);
208
+ }
209
+ function dispatchUpdatedEvent() {
210
+ if (isServer) return;
211
+ const event = new CustomEvent(updateEventName);
212
+ window.dispatchEvent(event);
213
+ }
214
+ function handleSetValueEvent(event) {
215
+ if (isServer) return;
216
+ if (getActivePHStore()) {
217
+ setValue(event.detail[key]);
218
+ return;
219
+ }
220
+ (window.ph ??= {})[key] = event.detail[key];
221
+ dispatchUpdatedEvent();
222
+ }
223
+ function addEventHandler() {
224
+ if (isServer) return;
225
+ window.addEventListener(setEventName, handleSetValueEvent);
226
+ }
227
+ function subscribeToValue(onStoreChange) {
228
+ return subscribeToPHValue(key, onStoreChange);
229
+ }
230
+ function getSnapshot() {
231
+ if (isServer) return;
232
+ return getPHStore()?.[key];
233
+ }
234
+ function getServerSnapshot() {}
235
+ function useValue() {
236
+ const store = usePHStore();
237
+ const readStore = () => store?.[key];
238
+ return useSyncExternalStore(store ? getPHStoreSubscribe(store, key) : subscribeToValue, store ? readStore : getSnapshot, store ? readStore : getServerSnapshot);
239
+ }
240
+ return {
241
+ useValue,
242
+ setValue,
243
+ addEventHandler,
244
+ subscribeToValue,
245
+ getSnapshot
246
+ };
247
+ }
248
+ //#endregion
249
+ export { bindPHStoreToWindow as a, ensurePHStore as c, getPHStoreSubscribe as d, isScopedPHStore as f, warnGlobalSetterInScope as g, usePHStore as h, SCOPED_PH_KEYS as i, getActivePHStore as l, subscribePHStore as m, subscribeToPHValue as n, createPHStore as o, notifyPHStore as p, PHStoreProvider as r, createScopedPHStore as s, makePHEventFunctions as t, getPHStore as u };
250
+
251
+ //# sourceMappingURL=make-ph-event-functions-C1JTfEw1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"make-ph-event-functions-C1JTfEw1.js","names":[],"sources":["../src/hooks/ph-store.tsx","../src/hooks/make-ph-event-functions.ts"],"sourcesContent":["import type { PHGlobal, PHGlobalKey } from \"@powerhousedao/reactor-browser\";\nimport type { ReactNode } from \"react\";\nimport { createContext, useContext, useEffect } from \"react\";\n\n/** PH state of one app (or one server request); assigning a key notifies. */\nexport type PHStore = PHGlobal;\n\ntype Listeners = Map<PropertyKey, Set<() => void>>;\n\n// Listeners per key; ALL_KEYS hears every change.\nconst ALL_KEYS = Symbol(\"all keys\");\nconst listenersByStore = new WeakMap<PHStore, Listeners>();\n// Stores bound to window.ph; their changes also fire `ph:<key>Updated`.\nconst windowBound = new WeakSet<Listeners>();\nconst subscribeCache = new WeakMap<\n PHStore,\n Map<PropertyKey, (listener: () => void) => () => void>\n>();\n\nfunction notifyKey(listeners: Listeners, key: PropertyKey) {\n for (const set of [listeners.get(key), listeners.get(ALL_KEYS)]) {\n for (const listener of set ?? []) listener();\n }\n // Another bundled copy of reactor-browser subscribes through window events.\n if (windowBound.has(listeners) && typeof key === \"string\") {\n window.dispatchEvent(new CustomEvent(`ph:${key}Updated`));\n }\n}\n\nexport function createPHStore(initial: PHGlobal = {}): PHStore {\n const listeners: Listeners = new Map();\n const store = new Proxy<PHGlobal>(\n { ...initial },\n {\n set: (target, key, value) => {\n if (Reflect.get(target, key) === value) return true;\n Reflect.set(target, key, value);\n notifyKey(listeners, key);\n return true;\n },\n deleteProperty: (target, key) => {\n Reflect.deleteProperty(target, key);\n notifyKey(listeners, key);\n return true;\n },\n },\n );\n listenersByStore.set(store, listeners);\n return store;\n}\n\n/** The keys a scoped store owns; every other key reads and writes its parent. */\nexport const SCOPED_PH_KEYS = [\n \"selectedDriveId\",\n \"selectedNodeId\",\n \"navigation\",\n] as const satisfies readonly PHGlobalKey[];\n\nexport type ScopedPHKey = (typeof SCOPED_PH_KEYS)[number];\nexport type ScopedPHStoreOverrides = Pick<PHGlobal, ScopedPHKey>;\n\nconst scopedKeys = new Set<PropertyKey>(SCOPED_PH_KEYS);\nconst parentOfScope = new WeakMap<PHStore, PHStore>();\n\n/** A store with its own selection and navigation over `parent`, e.g. for an\n * editor shown beside others; provide it with {@link PHStoreProvider}. */\nexport function createScopedPHStore(\n parent: PHStore,\n overrides: ScopedPHStoreOverrides = {},\n): PHStore {\n const listeners: Listeners = new Map();\n const own: PHGlobal = {};\n for (const key of SCOPED_PH_KEYS) {\n if (overrides[key] !== undefined) Reflect.set(own, key, overrides[key]);\n }\n const store = new Proxy<PHGlobal>(own, {\n get: (target, key): unknown =>\n scopedKeys.has(key) ? Reflect.get(target, key) : Reflect.get(parent, key),\n has: (target, key) =>\n scopedKeys.has(key) ? Reflect.has(target, key) : Reflect.has(parent, key),\n set: (target, key, value) => {\n if (!scopedKeys.has(key)) return Reflect.set(parent, key, value);\n if (Reflect.get(target, key) === value) return true;\n Reflect.set(target, key, value);\n notifyKey(listeners, key);\n return true;\n },\n deleteProperty: (target, key) => {\n if (!scopedKeys.has(key)) return Reflect.deleteProperty(parent, key);\n Reflect.deleteProperty(target, key);\n notifyKey(listeners, key);\n return true;\n },\n });\n listenersByStore.set(store, listeners);\n parentOfScope.set(store, parent);\n return store;\n}\n\n/** Whether `store` was made by {@link createScopedPHStore}. */\nexport function isScopedPHStore(store: PHStore | undefined) {\n return !!store && parentOfScope.has(store);\n}\n\nfunction listenersOf(store: PHStore) {\n const listeners = listenersByStore.get(store);\n if (!listeners) throw new Error(\"Not a store made by createPHStore\");\n return listeners;\n}\n\n/** Subscribes to changes of `key`, or of every key when omitted. */\nexport function subscribePHStore(\n store: PHStore,\n listener: () => void,\n key: PHGlobalKey | typeof ALL_KEYS = ALL_KEYS,\n): () => void {\n const parent = parentOfScope.get(store);\n // A scope hears its parent for the keys it reads through.\n if (parent && !scopedKeys.has(key)) {\n const fromParent = subscribePHStore(parent, listener, key);\n if (key !== ALL_KEYS) return fromParent;\n const fromScope = subscribeOwn(store, listener, key);\n return () => {\n fromParent();\n fromScope();\n };\n }\n return subscribeOwn(store, listener, key);\n}\n\nfunction subscribeOwn(store: PHStore, listener: () => void, key: PropertyKey) {\n const listeners = listenersOf(store);\n const set = listeners.get(key) ?? new Set();\n listeners.set(key, set);\n set.add(listener);\n return () => {\n set.delete(listener);\n };\n}\n\n/** Notifies `key`'s listeners without a change, as re-setting a value does. */\nexport function notifyPHStore(store: PHStore, key: PHGlobalKey) {\n const parent = parentOfScope.get(store);\n if (parent && !scopedKeys.has(key)) notifyPHStore(parent, key);\n else notifyKey(listenersOf(store), key);\n}\n\n/** A subscribe for `key`, stable per store as useSyncExternalStore expects. */\nexport function getPHStoreSubscribe(store: PHStore, key?: PHGlobalKey) {\n const cacheKey = key ?? ALL_KEYS;\n const cache =\n subscribeCache.get(store) ??\n new Map<PropertyKey, (listener: () => void) => () => void>();\n subscribeCache.set(store, cache);\n let subscribe = cache.get(cacheKey);\n if (!subscribe) {\n subscribe = (listener: () => void) =>\n subscribePHStore(store, listener, cacheKey);\n cache.set(cacheKey, subscribe);\n }\n return subscribe;\n}\n\nlet activeStore: PHStore | undefined;\n\n/** The store bound with {@link bindPHStoreToWindow}, if any. */\nexport function getActivePHStore() {\n return activeStore;\n}\n\n/** The app's state outside React: the bound store, else `window.ph`. */\nexport function getPHStore(): PHStore | undefined {\n if (activeStore) return activeStore;\n return typeof window === \"undefined\" ? undefined : window.ph;\n}\n\n/** The bound store; otherwise binds `window.ph` if it is a store, else a new\n * store that takes over a plain `window.ph`'s values. */\nexport function ensurePHStore(): PHStore {\n if (activeStore) return activeStore;\n const current = typeof window === \"undefined\" ? undefined : window.ph;\n const store =\n current && listenersByStore.has(current) ? current : createPHStore();\n bindPHStoreToWindow(store);\n return store;\n}\n\n/** Makes `store` the app's state and `window.ph`; values set on a plain\n * `window.ph` carry over where `store` has none. */\nexport function bindPHStoreToWindow(store: PHStore) {\n activeStore = store;\n if (typeof window === \"undefined\") return;\n const previous = window.ph;\n const previousListeners = previous && listenersByStore.get(previous);\n // A previously bound store is replaced, not merged.\n if (previousListeners) windowBound.delete(previousListeners);\n else if (previous) {\n for (const [key, value] of Object.entries(previous)) {\n if (!(key in store)) Reflect.set(store, key, value);\n }\n }\n windowBound.add(listenersOf(store));\n window.ph = store;\n}\n\nconst PHStoreContext = createContext<PHStore | undefined>(undefined);\n\n// Scoped stores provided right now; plain setters warn while any is.\nlet mountedScopes = 0;\nconst warned = new Set<string>();\n\nfunction isProduction() {\n // `process` need not exist in a browser bundle.\n return (\n typeof process !== \"undefined\" && process.env?.NODE_ENV === \"production\"\n );\n}\n\n/** Warns once in development when a global setter runs while a scoped store\n * is mounted, since it acts on the app's store and not the scope's. */\nexport function warnGlobalSetterInScope(setter: string, hook: string) {\n if (mountedScopes === 0 || warned.has(setter) || isProduction()) return;\n warned.add(setter);\n console.warn(\n `${setter} acts on the app's PH store while a scoped store is mounted; inside a scope, use ${hook}.`,\n );\n}\n\n/** Hooks below read from `store`; without a provider they read `window.ph`. */\nexport function PHStoreProvider(props: {\n store: PHStore;\n children: ReactNode;\n}) {\n const scoped = isScopedPHStore(props.store);\n useEffect(() => {\n if (!scoped) return;\n mountedScopes++;\n return () => {\n mountedScopes--;\n };\n }, [scoped]);\n return (\n <PHStoreContext.Provider value={props.store}>\n {props.children}\n </PHStoreContext.Provider>\n );\n}\n\nexport function usePHStore() {\n return useContext(PHStoreContext);\n}\n","import type {\n PHGlobal,\n PHGlobalKey,\n SetEvent,\n} from \"@powerhousedao/reactor-browser\";\nimport { capitalCase } from \"change-case\";\nimport { useSyncExternalStore } from \"react\";\nimport {\n getActivePHStore,\n getPHStore,\n getPHStoreSubscribe,\n notifyPHStore,\n subscribePHStore,\n usePHStore,\n} from \"./ph-store.js\";\n\n// guard condition for server side rendering\nconst isServer = typeof window === \"undefined\";\n\nconst updatedEventName = (key: PHGlobalKey) => `ph:${key}Updated`;\n\n/** Calls `onChange` whenever `key` is set: through the bound store, or the\n * `ph:<key>Updated` event on pages that bound none. */\nexport function subscribeToPHValue(key: PHGlobalKey, onChange: () => void) {\n if (isServer) return () => {};\n const store = getActivePHStore();\n if (store) return subscribePHStore(store, onChange, key);\n const eventName = updatedEventName(key);\n window.addEventListener(eventName, onChange);\n return () => window.removeEventListener(eventName, onChange);\n}\n\nexport function makePHEventFunctions<TKey extends PHGlobalKey>(key: TKey) {\n const setEventName = `ph:set${capitalCase(key)}` as const;\n const updateEventName = updatedEventName(key);\n\n function setValue(value: PHGlobal[TKey] | undefined) {\n if (isServer) {\n return;\n }\n const store = getActivePHStore();\n if (store) {\n const unchanged = store[key] === value;\n store[key] = value;\n // Re-setting a value still notifies, as the event path always has.\n if (unchanged) notifyPHStore(store, key);\n return;\n }\n const event = new CustomEvent(setEventName, {\n detail: { [key]: value },\n });\n window.dispatchEvent(event);\n }\n\n function dispatchUpdatedEvent() {\n if (isServer) {\n return;\n }\n const event = new CustomEvent(updateEventName);\n window.dispatchEvent(event);\n }\n\n function handleSetValueEvent(event: SetEvent<TKey>) {\n if (isServer) {\n return;\n }\n if (getActivePHStore()) {\n setValue(event.detail[key]);\n return;\n }\n // No bound store: the page keeps a plain `window.ph`.\n (window.ph ??= {})[key] = event.detail[key];\n dispatchUpdatedEvent();\n }\n\n // Only pages without a bound store need it; `ph:set*` events still apply.\n function addEventHandler() {\n if (isServer) {\n return;\n }\n window.addEventListener(setEventName, handleSetValueEvent as EventListener);\n }\n\n function subscribeToValue(onStoreChange: () => void) {\n return subscribeToPHValue(key, onStoreChange);\n }\n\n function getSnapshot() {\n if (isServer) {\n return undefined;\n }\n // Read before the first setValue is expected: subscribers mount before init.\n return getPHStore()?.[key];\n }\n\n function getServerSnapshot() {\n return undefined;\n }\n\n function useValue() {\n const store = usePHStore();\n const readStore = () => store?.[key];\n return useSyncExternalStore(\n store ? getPHStoreSubscribe(store, key) : subscribeToValue,\n store ? readStore : getSnapshot,\n store ? readStore : getServerSnapshot,\n );\n }\n\n return {\n useValue,\n setValue,\n addEventHandler,\n // Non-React access, e.g. Connect's boot wiring of the reactor worker.\n subscribeToValue,\n getSnapshot,\n };\n}\n"],"mappings":";;;;AAUA,MAAM,WAAW,OAAO,UAAU;AAClC,MAAM,mCAAmB,IAAI,QAA4B;AAEzD,MAAM,8BAAc,IAAI,QAAmB;AAC3C,MAAM,iCAAiB,IAAI,QAGzB;AAEF,SAAS,UAAU,WAAsB,KAAkB;CACzD,KAAK,MAAM,OAAO,CAAC,UAAU,IAAI,GAAG,GAAG,UAAU,IAAI,QAAQ,CAAC,GAC5D,KAAK,MAAM,YAAY,OAAO,CAAC,GAAG,SAAS;CAG7C,IAAI,YAAY,IAAI,SAAS,KAAK,OAAO,QAAQ,UAC/C,OAAO,cAAc,IAAI,YAAY,MAAM,IAAI,QAAQ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,KAAK;CAC5B;CAEA,SAAS,uBAAuB;EAC9B,IAAI,UACF;EAEF,MAAM,QAAQ,IAAI,YAAY,eAAe;EAC7C,OAAO,cAAc,KAAK;CAC5B;CAEA,SAAS,oBAAoB,OAAuB;EAClD,IAAI,UACF;EAEF,IAAI,iBAAiB,GAAG;GACtB,SAAS,MAAM,OAAO,IAAI;GAC1B;EACF;EAEA,CAAC,OAAO,OAAO,CAAC,EAAA,CAAG,OAAO,MAAM,OAAO;EACvC,qBAAqB;CACvB;CAGA,SAAS,kBAAkB;EACzB,IAAI,UACF;EAEF,OAAO,iBAAiB,cAAc,mBAAoC;CAC5E;CAEA,SAAS,iBAAiB,eAA2B;EACnD,OAAO,mBAAmB,KAAK,aAAa;CAC9C;CAEA,SAAS,cAAc;EACrB,IAAI,UACF;EAGF,OAAO,WAAW,CAAC,GAAG;CACxB;CAEA,SAAS,oBAAoB,CAE7B;CAEA,SAAS,WAAW;EAClB,MAAM,QAAQ,WAAW;EACzB,MAAM,kBAAkB,QAAQ;EAChC,OAAO,qBACL,QAAQ,oBAAoB,OAAO,GAAG,IAAI,kBAC1C,QAAQ,YAAY,aACpB,QAAQ,YAAY,iBACtB;CACF;CAEA,OAAO;EACL;EACA;EACA;EAEA;EACA;CACF;AACF"}
@@ -0,0 +1,315 @@
1
+ import { f as isScopedPHStore, u as getPHStore } from "./make-ph-event-functions-C1JTfEw1.js";
2
+ import { useMemo, useSyncExternalStore } from "react";
3
+ import { isDerivedDocumentId } from "@powerhousedao/shared/document-model";
4
+ import slug from "slug";
5
+ //#region src/utils/url.ts
6
+ const DERIVED_ID_LENGTH = 43;
7
+ function resolveUrlPathname(path) {
8
+ return new URL(path.replace(/^\/+/, ""), window.location.origin + (getPHStore()?.basePath ?? "/")).pathname;
9
+ }
10
+ /** Returns the path without a leading base path */
11
+ function getPathWithoutBase(path) {
12
+ const basePath = getPHStore()?.basePath ?? "/";
13
+ if (!path.startsWith(basePath)) return path;
14
+ const rest = path.slice(basePath.length);
15
+ if (basePath.endsWith("/")) return `/${rest}`;
16
+ return rest === "" || rest.startsWith("/") ? rest : path;
17
+ }
18
+ /** Makes a URL component for a drive.
19
+ * @deprecated Open drives through the store's `navigation`; it builds the path. */
20
+ function makeDriveUrlComponent(drive) {
21
+ if (!drive) return "";
22
+ return `/d/${slug(drive.header.slug)}`;
23
+ }
24
+ /** A drive's URL component: its slug, else its id, prefixed with the slugged
25
+ * name as `<name>-<id>` when the id is opaque (a UUID or derived id). */
26
+ function makeDriveSlug(drive) {
27
+ const { id, slug: driveSlug } = drive.header;
28
+ if (driveSlug && driveSlug !== id) return driveSlug;
29
+ return isOpaqueId(id) ? namedDriveSlug(drive) : id;
30
+ }
31
+ function isOpaqueId(id) {
32
+ return findUuid(id) !== void 0 || isDerivedDocumentId(id);
33
+ }
34
+ function namedDriveSlug(drive) {
35
+ return namedSlug(drive, drive.state.global.name || drive.header.name, drive.header.id);
36
+ }
37
+ const namedSlugs = /* @__PURE__ */ new WeakMap();
38
+ function namedSlug(owner, name, id) {
39
+ const cached = namedSlugs.get(owner);
40
+ if (cached?.name === name && cached.id === id) return cached.value;
41
+ const nameSlug = name ? slug(name) : "";
42
+ const value = nameSlug ? `${nameSlug}-${id}` : id;
43
+ namedSlugs.set(owner, {
44
+ name,
45
+ id,
46
+ value
47
+ });
48
+ return value;
49
+ }
50
+ /** The drive a URL slug names: its own slug, its id, or `<name>-<id>`. */
51
+ function findDriveBySlug(drives, ref) {
52
+ if (!drives || !ref) return void 0;
53
+ const exact = drives.find((d) => d.header.slug === ref || d.header.id === ref);
54
+ if (exact) return exact;
55
+ const id = extractDriveIdFromSlug(ref);
56
+ if (id !== void 0) {
57
+ const byId = drives.find((d) => d.header.id === id);
58
+ if (byId) return byId;
59
+ }
60
+ return drives.find((d) => (!d.header.slug || d.header.slug === d.header.id) && ref.endsWith(d.header.id) && namedDriveSlug(d) === ref);
61
+ }
62
+ /**
63
+ * Makes a URL component for a node: `<slugged name>-<id>`. The id is kept
64
+ * verbatim, since a v2-required id is case-sensitive base64url.
65
+ */
66
+ function makeNodeSlug(node) {
67
+ if (!node) return "";
68
+ return namedSlug(node, node.name, node.id);
69
+ }
70
+ /** Extracts the node slug from a path.
71
+ *
72
+ * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.
73
+ */
74
+ function extractNodeSlugFromPath(path) {
75
+ const currentPath = getPathWithoutBase(path);
76
+ return /^\/d\/[^/]+\/([^/]+)$/.exec(currentPath)?.[1];
77
+ }
78
+ /** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */
79
+ function findUuid(input) {
80
+ if (!input) return void 0;
81
+ return /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/.exec(input)?.[0];
82
+ }
83
+ /** The v2-required document id a slug ends with, if any. */
84
+ function findDerivedId(input) {
85
+ if (!input || input.length < DERIVED_ID_LENGTH) return void 0;
86
+ const start = input.length - DERIVED_ID_LENGTH;
87
+ if (start > 0 && input[start - 1] !== "-") return void 0;
88
+ const candidate = input.slice(start);
89
+ return isDerivedDocumentId(candidate) ? candidate : void 0;
90
+ }
91
+ function extractNodeIdFromSlug(nodeSlug) {
92
+ return findUuid(nodeSlug) ?? findDerivedId(nodeSlug);
93
+ }
94
+ /** @deprecated Route loaders resolve the node; use `extractNodeIdFromSlug`. */
95
+ function extractNodeIdFromPath(path) {
96
+ return extractNodeIdFromSlug(extractNodeSlugFromPath(path));
97
+ }
98
+ /** Extracts the drive slug from a path.
99
+ * Used for extracting drive ids from drive slugs in the URL.
100
+ * Expects the path to be in the format `/d/<drive-slug>`.
101
+ */
102
+ function extractDriveSlugFromPath(path) {
103
+ const currentPath = getPathWithoutBase(path);
104
+ return /^\/d\/([^/]+)/.exec(currentPath)?.[1] ?? "";
105
+ }
106
+ function extractDriveIdFromSlug(driveSlug) {
107
+ return findUuid(driveSlug) ?? findDerivedId(driveSlug);
108
+ }
109
+ /** @deprecated Route loaders resolve the drive; use `extractDriveIdFromSlug`. */
110
+ function extractDriveIdFromPath(path) {
111
+ return extractDriveIdFromSlug(extractDriveSlugFromPath(path));
112
+ }
113
+ /** Creates a URL string with the given pathname, keeping the query string.
114
+ * @deprecated The store's `navigation` keeps global params across navigations. */
115
+ function createUrlWithPreservedParams(pathname) {
116
+ const search = window.location.search;
117
+ return search ? `${pathname}${search}` : pathname;
118
+ }
119
+ //#endregion
120
+ //#region src/hooks/navigation.ts
121
+ const isServer = typeof window === "undefined";
122
+ /** Fired on `window` when the fallback navigator rewrites the URL. */
123
+ const PH_LOCATION_CHANGE_EVENT = "ph:locationchange";
124
+ /** Params read at boot or app-wide; they survive every navigation. Others,
125
+ * e.g. a document's own, are dropped when the target changes. */
126
+ const GLOBAL_SEARCH_PARAMS = [
127
+ "driveUrl",
128
+ "theme",
129
+ "embed",
130
+ "LOG_LEVEL",
131
+ "reactorWorker"
132
+ ];
133
+ /** Feature flags are any `FEATURE_*` param, so they are retained by prefix. */
134
+ const FEATURE_FLAG_PARAM_PREFIX = "FEATURE_";
135
+ /** Whether `key` is a param every navigation keeps. */
136
+ function isGlobalSearchParam(key) {
137
+ return GLOBAL_SEARCH_PARAMS.includes(key) || key.startsWith("FEATURE_");
138
+ }
139
+ function globalSearch(search) {
140
+ return Object.fromEntries(Object.entries(searchToRecord(search)).filter(([key]) => isGlobalSearchParam(key)));
141
+ }
142
+ /** A query string's params; repeated keys keep their last value. */
143
+ function searchToRecord(search) {
144
+ return Object.fromEntries(new URLSearchParams(search));
145
+ }
146
+ /** `prev` with `update` applied; an `undefined` value removes the key. */
147
+ function applySearchUpdate(prev, update) {
148
+ const next = { ...prev };
149
+ for (const [key, value] of Object.entries(update)) if (value === void 0) delete next[key];
150
+ else next[key] = value;
151
+ return next;
152
+ }
153
+ /** `?a=1&b=2`, or an empty string for no params. */
154
+ function recordToSearch(record) {
155
+ const search = new URLSearchParams(record).toString();
156
+ return search ? `?${search}` : "";
157
+ }
158
+ /** The settings page's path; its tabs are below it. */
159
+ const SETTINGS_PATH = "/settings";
160
+ function isSettingsTarget(target) {
161
+ return !!target && "settings" in target;
162
+ }
163
+ /** The pathname a target opens at, base path included. */
164
+ function targetPathname(target) {
165
+ if (!target) return resolveUrlPathname("/");
166
+ if (isSettingsTarget(target)) {
167
+ const { settings } = target;
168
+ return resolveUrlPathname(settings === true ? SETTINGS_PATH : `${SETTINGS_PATH}/${settings}`);
169
+ }
170
+ const { driveSlug, nodeSlug } = target;
171
+ return resolveUrlPathname(nodeSlug ? `/d/${driveSlug}/${nodeSlug}` : `/d/${driveSlug}`);
172
+ }
173
+ /** History state key: the index of the entry a document was opened from. */
174
+ const OPENED_FROM_STATE_KEY = "phOpenedFrom";
175
+ function browserEntryState() {
176
+ const state = window.history.state;
177
+ return state && typeof state === "object" ? state : {};
178
+ }
179
+ /** The index to go back to from `index`, when it lies before it. */
180
+ function openedFromIndex(state, index) {
181
+ const from = state?.[OPENED_FROM_STATE_KEY];
182
+ return typeof from === "number" && from >= 0 && from < index ? from : void 0;
183
+ }
184
+ function writeBrowserUrl(href, replace, openedFrom) {
185
+ const prev = browserEntryState();
186
+ const index = prev.phIndex ?? 0;
187
+ const from = openedFrom === "keep" ? prev.phOpenedFrom : openedFrom;
188
+ if (replace) window.history.replaceState({
189
+ ...prev,
190
+ phIndex: index,
191
+ phOpenedFrom: from
192
+ }, "", href);
193
+ else window.history.pushState({
194
+ phIndex: index + 1,
195
+ phOpenedFrom: from
196
+ }, "", href);
197
+ window.dispatchEvent(new Event(PH_LOCATION_CHANGE_EVENT));
198
+ }
199
+ function subscribeToLocation(onChange) {
200
+ window.addEventListener("popstate", onChange);
201
+ window.addEventListener(PH_LOCATION_CHANGE_EVENT, onChange);
202
+ return () => {
203
+ window.removeEventListener("popstate", onChange);
204
+ window.removeEventListener(PH_LOCATION_CHANGE_EVENT, onChange);
205
+ };
206
+ }
207
+ const readSearch = () => window.location.search;
208
+ const readPathname = () => window.location.pathname;
209
+ const readServerPathname = () => "";
210
+ const readServerSearch = () => "";
211
+ function setBrowserSearch(update, options) {
212
+ const prev = searchToRecord(window.location.search);
213
+ const next = recordToSearch(applySearchUpdate({}, update(prev)));
214
+ if (next === recordToSearch(prev)) return;
215
+ writeBrowserUrl(`${window.location.pathname}${next}`, options?.replace, "keep");
216
+ }
217
+ function setBrowserSearchParams(update, options) {
218
+ setBrowserSearch((prev) => resolveSearchUpdate(prev, update), options);
219
+ }
220
+ /** The fallback without a host: `window.location` and `window.history`. Only
221
+ * the global params carry over to another target, as with a router. */
222
+ let syncSelectionAfterOpen = () => {};
223
+ /** @internal Selects what the browser fallback opens; sync-selection.ts sets it. */
224
+ function setBrowserOpenSync(sync) {
225
+ syncSelectionAfterOpen = sync;
226
+ }
227
+ const browserNavigation = {
228
+ location: () => window.location,
229
+ hrefFor: (target) => `${targetPathname(target)}${recordToSearch(globalSearch(window.location.search))}`,
230
+ useIsCurrent(target) {
231
+ return useSyncExternalStore(subscribeToLocation, readPathname, readServerPathname) === targetPathname(target);
232
+ },
233
+ open: (target, options) => {
234
+ const prev = globalSearch(window.location.search);
235
+ const search = options?.search ? applySearchUpdate(prev, options.search) : prev;
236
+ const entry = browserEntryState();
237
+ writeBrowserUrl(`${targetPathname(target)}${recordToSearch(search)}`, options?.replace, options?.replace ? entry.phOpenedFrom : entry.phIndex ?? 0);
238
+ syncSelectionAfterOpen();
239
+ },
240
+ closeOpened: () => {
241
+ const entry = browserEntryState();
242
+ const index = entry.phIndex ?? 0;
243
+ const from = openedFromIndex(entry, index);
244
+ if (from === void 0) return false;
245
+ window.history.go(from - index);
246
+ return true;
247
+ },
248
+ setSearch: setBrowserSearch,
249
+ useSearchParams() {
250
+ const search = useSyncExternalStore(subscribeToLocation, readSearch, readServerSearch);
251
+ return useMemo(() => searchToRecord(search), [search]);
252
+ },
253
+ useSetSearchParams: () => setBrowserSearchParams
254
+ };
255
+ const NO_PARAMS = {};
256
+ const noop = () => {};
257
+ const detachedNavigation = {
258
+ location: () => ({
259
+ pathname: "",
260
+ search: ""
261
+ }),
262
+ open: noop,
263
+ setSearch: noop,
264
+ useSearchParams: () => NO_PARAMS,
265
+ useSetSearchParams: () => noop
266
+ };
267
+ /** The navigation `store` acts through: a scope's own, else the app's. */
268
+ function getNavigationOf(store) {
269
+ if (store && isScopedPHStore(store)) return store.navigation ?? detachedNavigation;
270
+ return store?.navigation ?? getPHNavigation();
271
+ }
272
+ /** True when the store has a host navigation, not the browser fallback. */
273
+ function hasHostNavigation() {
274
+ return !isServer && getPHStore()?.navigation !== void 0;
275
+ }
276
+ /** The app store's navigation, else the browser fallback. */
277
+ function getPHNavigation() {
278
+ return getPHStore()?.navigation ?? browserNavigation;
279
+ }
280
+ /** The current pathname as the navigation sees it, base path included. */
281
+ function getCurrentPathname() {
282
+ return getPHNavigation().location().pathname;
283
+ }
284
+ /** Opens `target`; without `search`, a target already open is left alone. */
285
+ function openTarget(target, options) {
286
+ openTargetWith(getPHNavigation(), target, options);
287
+ }
288
+ /** Opens `target` through `navigation`, unless it is open already. */
289
+ function openTargetWith(navigation, target, options) {
290
+ const pathname = navigation.location().pathname;
291
+ const targetPath = targetPathname(target);
292
+ const open = targetPath === pathname || isSettingsTarget(target) && target.settings === true && pathname.startsWith(`${targetPath}/`);
293
+ if (!options?.search && open) return;
294
+ navigation.open(target, options);
295
+ }
296
+ /** Asks the host navigation to warm `target`; a no-op without one. */
297
+ function preloadTarget(target) {
298
+ if (!hasHostNavigation()) return;
299
+ getPHNavigation().preload?.(target);
300
+ }
301
+ /** The href `target` opens at through `navigation`, base path included. */
302
+ function getTargetHref(target, navigation = getPHNavigation()) {
303
+ return navigation.hrefFor?.(target) ?? targetPathname(target);
304
+ }
305
+ function resolveSearchUpdate(prev, update) {
306
+ return typeof update === "function" ? applySearchUpdate({}, update(prev)) : applySearchUpdate(prev, update);
307
+ }
308
+ /** Rewrites the current query params through the app store's navigation. */
309
+ function setSearchParams(update, options) {
310
+ getPHNavigation().setSearch((prev) => resolveSearchUpdate(prev, update), options);
311
+ }
312
+ //#endregion
313
+ export { extractNodeIdFromSlug as A, setSearchParams as C, extractDriveIdFromSlug as D, extractDriveIdFromPath as E, getPathWithoutBase as F, makeDriveSlug as I, makeDriveUrlComponent as L, findDerivedId as M, findDriveBySlug as N, extractDriveSlugFromPath as O, findUuid as P, makeNodeSlug as R, setBrowserOpenSync as S, createUrlWithPreservedParams as T, openedFromIndex as _, SETTINGS_PATH as a, resolveSearchUpdate as b, getCurrentPathname as c, getTargetHref as d, hasHostNavigation as f, openTargetWith as g, openTarget as h, PH_LOCATION_CHANGE_EVENT as i, extractNodeSlugFromPath as j, extractNodeIdFromPath as k, getNavigationOf as l, isSettingsTarget as m, GLOBAL_SEARCH_PARAMS as n, applySearchUpdate as o, isGlobalSearchParam as p, OPENED_FROM_STATE_KEY as r, browserNavigation as s, FEATURE_FLAG_PARAM_PREFIX as t, getPHNavigation as u, preloadTarget as v, targetPathname as w, searchToRecord as x, recordToSearch as y, resolveUrlPathname as z };
314
+
315
+ //# sourceMappingURL=navigation-B4fHR-Tm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"navigation-B4fHR-Tm.js","names":[],"sources":["../src/utils/url.ts","../src/hooks/navigation.ts"],"sourcesContent":["import { getPHStore } from \"../hooks/ph-store.js\";\nimport type {\n DocumentDriveDocument,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport { isDerivedDocumentId } from \"@powerhousedao/shared/document-model\";\nimport slug from \"slug\";\n\n// Length of the base64url id a v2-required document gets.\nconst DERIVED_ID_LENGTH = 43;\n\n// Returns url with base path plus provided path\nexport function resolveUrlPathname(path: string) {\n return new URL(\n path.replace(/^\\/+/, \"\"),\n window.location.origin + (getPHStore()?.basePath ?? \"/\"),\n ).pathname;\n}\n\n/** Returns the path without a leading base path */\nexport function getPathWithoutBase(path: string) {\n const basePath = getPHStore()?.basePath ?? \"/\";\n if (!path.startsWith(basePath)) return path;\n const rest = path.slice(basePath.length);\n if (basePath.endsWith(\"/\")) return `/${rest}`;\n return rest === \"\" || rest.startsWith(\"/\") ? rest : path;\n}\n\n/** Makes a URL component for a drive.\n * @deprecated Open drives through the store's `navigation`; it builds the path. */\nexport function makeDriveUrlComponent(\n drive: DocumentDriveDocument | undefined,\n) {\n if (!drive) return \"\";\n return `/d/${slug(drive.header.slug)}`;\n}\n\n/** A drive's URL component: its slug, else its id, prefixed with the slugged\n * name as `<name>-<id>` when the id is opaque (a UUID or derived id). */\nexport function makeDriveSlug(drive: DocumentDriveDocument) {\n const { id, slug: driveSlug } = drive.header;\n if (driveSlug && driveSlug !== id) return driveSlug;\n return isOpaqueId(id) ? namedDriveSlug(drive) : id;\n}\n\nfunction isOpaqueId(id: string) {\n return findUuid(id) !== undefined || isDerivedDocumentId(id);\n}\n\nfunction namedDriveSlug(drive: DocumentDriveDocument) {\n const name = drive.state.global.name || drive.header.name;\n return namedSlug(drive, name, drive.header.id);\n}\n\nconst namedSlugs = new WeakMap<\n object,\n { name: string; id: string; value: string }\n>();\n\n// `<slugged name>-<id>`, cached per drive or node; inputs are rechecked.\nfunction namedSlug(owner: object, name: string, id: string) {\n const cached = namedSlugs.get(owner);\n if (cached?.name === name && cached.id === id) return cached.value;\n const nameSlug = name ? slug(name) : \"\";\n const value = nameSlug ? `${nameSlug}-${id}` : id;\n namedSlugs.set(owner, { name, id, value });\n return value;\n}\n\n/** The drive a URL slug names: its own slug, its id, or `<name>-<id>`. */\nexport function findDriveBySlug(\n drives: readonly DocumentDriveDocument[] | undefined,\n ref: string | undefined,\n) {\n if (!drives || !ref) return undefined;\n const exact = drives.find(\n (d) => d.header.slug === ref || d.header.id === ref,\n );\n if (exact) return exact;\n const id = extractDriveIdFromSlug(ref);\n if (id !== undefined) {\n const byId = drives.find((d) => d.header.id === id);\n if (byId) return byId;\n }\n // `<name>-<id>` also for a readable id, as older links wrote it.\n return drives.find(\n (d) =>\n (!d.header.slug || d.header.slug === d.header.id) &&\n ref.endsWith(d.header.id) &&\n namedDriveSlug(d) === ref,\n );\n}\n\n/**\n * Makes a URL component for a node: `<slugged name>-<id>`. The id is kept\n * verbatim, since a v2-required id is case-sensitive base64url.\n */\nexport function makeNodeSlug(node: Node | undefined) {\n if (!node) return \"\";\n return namedSlug(node, node.name, node.id);\n}\n\n/** Extracts the node slug from a path.\n *\n * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.\n */\nexport function extractNodeSlugFromPath(path: string) {\n const currentPath = getPathWithoutBase(path);\n const match = /^\\/d\\/[^/]+\\/([^/]+)$/.exec(currentPath);\n return match?.[1];\n}\n\n/** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */\nexport function findUuid(input: string | undefined) {\n if (!input) return undefined;\n const uuidRegex =\n /\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\b/;\n const match = uuidRegex.exec(input);\n return match?.[0];\n}\n\n/** The v2-required document id a slug ends with, if any. */\nexport function findDerivedId(input: string | undefined) {\n if (!input || input.length < DERIVED_ID_LENGTH) return undefined;\n const start = input.length - DERIVED_ID_LENGTH;\n if (start > 0 && input[start - 1] !== \"-\") return undefined;\n const candidate = input.slice(start);\n return isDerivedDocumentId(candidate) ? candidate : undefined;\n}\n\nexport function extractNodeIdFromSlug(nodeSlug: string | undefined) {\n return findUuid(nodeSlug) ?? findDerivedId(nodeSlug);\n}\n\n/** @deprecated Route loaders resolve the node; use `extractNodeIdFromSlug`. */\nexport function extractNodeIdFromPath(path: string) {\n const nodeSlug = extractNodeSlugFromPath(path);\n const nodeId = extractNodeIdFromSlug(nodeSlug);\n return nodeId;\n}\n\n/** Extracts the drive slug from a path.\n * Used for extracting drive ids from drive slugs in the URL.\n * Expects the path to be in the format `/d/<drive-slug>`.\n */\nexport function extractDriveSlugFromPath(path: string) {\n const currentPath = getPathWithoutBase(path);\n const match = /^\\/d\\/([^/]+)/.exec(currentPath);\n return match?.[1] ?? \"\";\n}\n\nexport function extractDriveIdFromSlug(driveSlug: string | undefined) {\n return findUuid(driveSlug) ?? findDerivedId(driveSlug);\n}\n\n/** @deprecated Route loaders resolve the drive; use `extractDriveIdFromSlug`. */\nexport function extractDriveIdFromPath(path: string) {\n const driveSlug = extractDriveSlugFromPath(path);\n const driveId = extractDriveIdFromSlug(driveSlug);\n return driveId;\n}\n\n/** Creates a URL string with the given pathname, keeping the query string.\n * @deprecated The store's `navigation` keeps global params across navigations. */\nexport function createUrlWithPreservedParams(pathname: string): string {\n const search = window.location.search;\n return search ? `${pathname}${search}` : pathname;\n}\n","import type {\n PHNavigateOptions,\n PHNavigation,\n PHNavigationTarget,\n PHSearchUpdate,\n PHSettingsTarget,\n SearchParamsUpdate,\n} from \"@powerhousedao/reactor-browser\";\nimport { useMemo, useSyncExternalStore } from \"react\";\nimport { resolveUrlPathname } from \"../utils/url.js\";\nimport type { PHStore } from \"./ph-store.js\";\nimport { getPHStore, isScopedPHStore } from \"./ph-store.js\";\n\nconst isServer = typeof window === \"undefined\";\n\n/** Fired on `window` when the fallback navigator rewrites the URL. */\nexport const PH_LOCATION_CHANGE_EVENT = \"ph:locationchange\";\n\n/** Params read at boot or app-wide; they survive every navigation. Others,\n * e.g. a document's own, are dropped when the target changes. */\nexport const GLOBAL_SEARCH_PARAMS = [\n // A remote drive to add on boot.\n \"driveUrl\",\n // The theme override read by the inline theme boot script.\n \"theme\",\n // Embedded mode, which hides Connect's chrome.\n \"embed\",\n // Log level override for the feature-flag provider.\n \"LOG_LEVEL\",\n // The reactor worker runtime flag override.\n \"reactorWorker\",\n] as const;\n\n/** Feature flags are any `FEATURE_*` param, so they are retained by prefix. */\nexport const FEATURE_FLAG_PARAM_PREFIX = \"FEATURE_\";\n\n/** Whether `key` is a param every navigation keeps. */\nexport function isGlobalSearchParam(key: string) {\n return (\n (GLOBAL_SEARCH_PARAMS as readonly string[]).includes(key) ||\n key.startsWith(FEATURE_FLAG_PARAM_PREFIX)\n );\n}\n\nfunction globalSearch(search: string) {\n return Object.fromEntries(\n Object.entries(searchToRecord(search)).filter(([key]) =>\n isGlobalSearchParam(key),\n ),\n );\n}\n\n/** A query string's params; repeated keys keep their last value. */\nexport function searchToRecord(search: string): Record<string, string> {\n return Object.fromEntries(new URLSearchParams(search));\n}\n\n/** `prev` with `update` applied; an `undefined` value removes the key. */\nexport function applySearchUpdate(\n prev: Record<string, string>,\n update: PHSearchUpdate,\n): Record<string, string> {\n const next = { ...prev };\n for (const [key, value] of Object.entries(update)) {\n if (value === undefined) delete next[key];\n else next[key] = value;\n }\n return next;\n}\n\n/** `?a=1&b=2`, or an empty string for no params. */\nexport function recordToSearch(record: Record<string, string>) {\n const search = new URLSearchParams(record).toString();\n return search ? `?${search}` : \"\";\n}\n\n/** The settings page's path; its tabs are below it. */\nexport const SETTINGS_PATH = \"/settings\";\n\nexport function isSettingsTarget(\n target: PHNavigationTarget | undefined,\n): target is PHSettingsTarget {\n return !!target && \"settings\" in target;\n}\n\n/** The pathname a target opens at, base path included. */\nexport function targetPathname(target: PHNavigationTarget | undefined) {\n if (!target) return resolveUrlPathname(\"/\");\n if (isSettingsTarget(target)) {\n const { settings } = target;\n return resolveUrlPathname(\n settings === true ? SETTINGS_PATH : `${SETTINGS_PATH}/${settings}`,\n );\n }\n const { driveSlug, nodeSlug } = target;\n return resolveUrlPathname(\n nodeSlug ? `/d/${driveSlug}/${nodeSlug}` : `/d/${driveSlug}`,\n );\n}\n\n/** History state key: the index of the entry a document was opened from. */\nexport const OPENED_FROM_STATE_KEY = \"phOpenedFrom\";\n\n// The fallback numbers its own entries; a router's history has its own index.\ntype BrowserEntryState = { phIndex?: number; phOpenedFrom?: number };\n\nfunction browserEntryState(): BrowserEntryState {\n const state: unknown = window.history.state;\n return state && typeof state === \"object\" ? (state as BrowserEntryState) : {};\n}\n\n/** The index to go back to from `index`, when it lies before it. */\nexport function openedFromIndex(\n state: object | undefined,\n index: number,\n): number | undefined {\n const from = (state as Record<string, unknown> | undefined)?.[\n OPENED_FROM_STATE_KEY\n ];\n return typeof from === \"number\" && from >= 0 && from < index\n ? from\n : undefined;\n}\n\n// `openedFrom` \"keep\" carries the current entry's, as an in-document write does.\nfunction writeBrowserUrl(\n href: string,\n replace: boolean | undefined,\n openedFrom: number | \"keep\" | undefined,\n) {\n const prev = browserEntryState();\n const index = prev.phIndex ?? 0;\n const from = openedFrom === \"keep\" ? prev.phOpenedFrom : openedFrom;\n // Keeps the entry's state, e.g. a router's history key, on a replace.\n if (replace) {\n window.history.replaceState(\n { ...prev, phIndex: index, phOpenedFrom: from },\n \"\",\n href,\n );\n } else {\n window.history.pushState(\n { phIndex: index + 1, phOpenedFrom: from },\n \"\",\n href,\n );\n }\n window.dispatchEvent(new Event(PH_LOCATION_CHANGE_EVENT));\n}\n\nfunction subscribeToLocation(onChange: () => void) {\n window.addEventListener(\"popstate\", onChange);\n window.addEventListener(PH_LOCATION_CHANGE_EVENT, onChange);\n return () => {\n window.removeEventListener(\"popstate\", onChange);\n window.removeEventListener(PH_LOCATION_CHANGE_EVENT, onChange);\n };\n}\n\nconst readSearch = () => window.location.search;\nconst readPathname = () => window.location.pathname;\nconst readServerPathname = () => \"\";\nconst readServerSearch = () => \"\";\n\nfunction setBrowserSearch(\n update: (prev: Record<string, string>) => PHSearchUpdate,\n options?: { replace?: boolean },\n) {\n const prev = searchToRecord(window.location.search);\n const next = recordToSearch(applySearchUpdate({}, update(prev)));\n if (next === recordToSearch(prev)) return;\n // Like a router's search update, this drops the hash.\n writeBrowserUrl(\n `${window.location.pathname}${next}`,\n options?.replace,\n \"keep\",\n );\n}\n\nfunction setBrowserSearchParams(\n update: SearchParamsUpdate,\n options?: { replace?: boolean },\n) {\n setBrowserSearch((prev) => resolveSearchUpdate(prev, update), options);\n}\n\n/** The fallback without a host: `window.location` and `window.history`. Only\n * the global params carry over to another target, as with a router. */\n// Set by sync-selection.ts, which imports this module: importing it here would be a cycle.\nlet syncSelectionAfterOpen = () => {};\n\n/** @internal Selects what the browser fallback opens; sync-selection.ts sets it. */\nexport function setBrowserOpenSync(sync: () => void) {\n syncSelectionAfterOpen = sync;\n}\n\nexport const browserNavigation: PHNavigation = {\n location: () => window.location,\n hrefFor: (target) =>\n `${targetPathname(target)}${recordToSearch(globalSearch(window.location.search))}`,\n useIsCurrent(target) {\n const pathname = useSyncExternalStore(\n subscribeToLocation,\n readPathname,\n readServerPathname,\n );\n return pathname === targetPathname(target);\n },\n open: (target, options) => {\n const prev = globalSearch(window.location.search);\n const search = options?.search\n ? applySearchUpdate(prev, options.search)\n : prev;\n const entry = browserEntryState();\n writeBrowserUrl(\n `${targetPathname(target)}${recordToSearch(search)}`,\n options?.replace,\n options?.replace ? entry.phOpenedFrom : (entry.phIndex ?? 0),\n );\n // No router selects for it, and pushState fires no popstate.\n syncSelectionAfterOpen();\n },\n closeOpened: () => {\n const entry = browserEntryState();\n const index = entry.phIndex ?? 0;\n const from = openedFromIndex(entry, index);\n if (from === undefined) return false;\n window.history.go(from - index);\n return true;\n },\n setSearch: setBrowserSearch,\n useSearchParams() {\n const search = useSyncExternalStore(\n subscribeToLocation,\n readSearch,\n readServerSearch,\n );\n return useMemo(() => searchToRecord(search), [search]);\n },\n useSetSearchParams: () => setBrowserSearchParams,\n};\n\nconst NO_PARAMS: Record<string, string> = {};\nconst noop = () => {};\n\n// A scope without a navigation of its own: no URL, so opening only selects.\nconst detachedNavigation: PHNavigation = {\n location: () => ({ pathname: \"\", search: \"\" }),\n open: noop,\n setSearch: noop,\n useSearchParams: () => NO_PARAMS,\n useSetSearchParams: () => noop,\n};\n\n/** The navigation `store` acts through: a scope's own, else the app's. */\nexport function getNavigationOf(store: PHStore | undefined): PHNavigation {\n if (store && isScopedPHStore(store)) {\n return store.navigation ?? detachedNavigation;\n }\n return store?.navigation ?? getPHNavigation();\n}\n\n/** True when the store has a host navigation, not the browser fallback. */\nexport function hasHostNavigation() {\n return !isServer && getPHStore()?.navigation !== undefined;\n}\n\n/** The app store's navigation, else the browser fallback. */\nexport function getPHNavigation(): PHNavigation {\n return getPHStore()?.navigation ?? browserNavigation;\n}\n\n/** The current pathname as the navigation sees it, base path included. */\nexport function getCurrentPathname() {\n return getPHNavigation().location().pathname;\n}\n\n/** Opens `target`; without `search`, a target already open is left alone. */\nexport function openTarget(\n target: PHNavigationTarget | undefined,\n options?: PHNavigateOptions,\n) {\n openTargetWith(getPHNavigation(), target, options);\n}\n\n/** Opens `target` through `navigation`, unless it is open already. */\nexport function openTargetWith(\n navigation: PHNavigation,\n target: PHNavigationTarget | undefined,\n options?: PHNavigateOptions,\n) {\n const pathname = navigation.location().pathname;\n const targetPath = targetPathname(target);\n // On any tab, the settings page is open.\n const open =\n targetPath === pathname ||\n (isSettingsTarget(target) &&\n target.settings === true &&\n pathname.startsWith(`${targetPath}/`));\n if (!options?.search && open) return;\n navigation.open(target, options);\n}\n\n/** Asks the host navigation to warm `target`; a no-op without one. */\nexport function preloadTarget(target: PHNavigationTarget | undefined) {\n if (!hasHostNavigation()) return;\n getPHNavigation().preload?.(target);\n}\n\n/** The href `target` opens at through `navigation`, base path included. */\nexport function getTargetHref(\n target: PHNavigationTarget | undefined,\n navigation: PHNavigation = getPHNavigation(),\n) {\n return navigation.hrefFor?.(target) ?? targetPathname(target);\n}\n\nexport function resolveSearchUpdate(\n prev: Record<string, string>,\n update: SearchParamsUpdate,\n): Record<string, string> {\n return typeof update === \"function\"\n ? applySearchUpdate({}, update(prev))\n : applySearchUpdate(prev, update);\n}\n\n/** Rewrites the current query params through the app store's navigation. */\nexport function setSearchParams(\n update: SearchParamsUpdate,\n options?: { replace?: boolean },\n) {\n getPHNavigation().setSearch(\n (prev) => resolveSearchUpdate(prev, update),\n options,\n );\n}\n"],"mappings":";;;;;AASA,MAAM,oBAAoB;AAG1B,SAAgB,mBAAmB,MAAc;CAC/C,OAAO,IAAI,IACT,KAAK,QAAQ,QAAQ,EAAE,GACvB,OAAO,SAAS,UAAU,WAAW,CAAC,EAAE,YAAY,IACtD,CAAC,CAAC;AACJ;;AAGA,SAAgB,mBAAmB,MAAc;C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