@abraca/nuxt 2.42.0 → 2.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=4.0.0"
6
6
  },
7
- "version": "2.42.0",
7
+ "version": "2.46.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.2",
10
10
  "unbuild": "3.6.1"
@@ -13,6 +13,18 @@ type __VLS_Props = {
13
13
  editorClass?: string;
14
14
  /** CSS class applied to structured renderers (kanban, table, etc.) */
15
15
  rendererClass?: string;
16
+ /**
17
+ * Override the doc-tree lookup with an explicit entry (`type`/`label`/`meta`).
18
+ * Use this when rendering a doc that is NOT in the active provider's root
19
+ * doc-tree — e.g. an admin browsing another space's documents, where the
20
+ * type lives in that space's own tree. When unset, falls back to the root
21
+ * tree as before, so this is purely additive.
22
+ */
23
+ entry?: {
24
+ type?: string;
25
+ label?: string;
26
+ meta?: Record<string, unknown>;
27
+ } | null;
16
28
  };
17
29
  declare var __VLS_1: {}, __VLS_23: {
18
30
  error: string;
@@ -2,7 +2,7 @@
2
2
  import { computed, watch, shallowRef } from "vue";
3
3
  import { useFetch } from "#imports";
4
4
  import { useAbracadabra } from "../composables/useAbracadabra";
5
- import { useSyncedMap } from "../composables/useYDoc";
5
+ import { useSpaceConnections } from "../composables/useSpaceConnections";
6
6
  import { usePluginRegistry } from "../composables/usePluginRegistry";
7
7
  import { resolveDocType } from "../utils/docTypes";
8
8
  const props = defineProps({
@@ -10,32 +10,33 @@ const props = defineProps({
10
10
  editable: { type: Boolean, required: false, default: true },
11
11
  breadcrumbMenu: { type: Boolean, required: false, default: true },
12
12
  editorClass: { type: String, required: false },
13
- rendererClass: { type: String, required: false }
13
+ rendererClass: { type: String, required: false },
14
+ entry: { type: [Object, null], required: false }
14
15
  });
15
16
  const abra = useAbracadabra();
16
- const treeMap = useSyncedMap(abra.doc, "doc-tree");
17
- const docEntry = computed(() => treeMap.data[props.docId]);
18
- const docTitle = computed(() => docEntry.value?.label ?? "Untitled");
19
- const docType = computed(() => docEntry.value?.type ?? "doc");
20
- const docMeta = computed(() => docEntry.value?.meta ?? {});
17
+ const { resolveEntry, findDocSpaceId, getProviderForDoc, connectSpace, connections } = useSpaceConnections();
18
+ const resolvedEntry = computed(() => resolveEntry(props.docId));
19
+ const docTitle = computed(() => props.entry?.label ?? resolvedEntry.value?.label ?? "Untitled");
20
+ const docType = computed(() => props.entry?.type ?? resolvedEntry.value?.type ?? "doc");
21
+ const docMeta = computed(() => props.entry?.meta ?? resolvedEntry.value?.meta ?? {});
21
22
  const registry = usePluginRegistry();
22
23
  const docTypeDef = computed(() => resolveDocType(docType.value, registry));
23
24
  const childProvider = shallowRef(null);
24
25
  async function loadChildProvider(id) {
25
26
  childProvider.value = null;
26
- if (!abra.provider.value) return;
27
- try {
28
- const prov = await abra.provider.value.loadChild(id);
29
- if (!prov.isSynced) {
30
- await new Promise((resolve) => {
31
- const done = () => {
32
- prov.off("synced", done);
33
- resolve();
34
- };
35
- prov.on("synced", done);
36
- setTimeout(resolve, 6e3);
37
- });
27
+ if (!id) return;
28
+ const spaceId = findDocSpaceId(id);
29
+ if (spaceId && !connections.get(spaceId)) {
30
+ try {
31
+ await connectSpace(spaceId);
32
+ } catch {
38
33
  }
34
+ }
35
+ const provider = getProviderForDoc(id);
36
+ if (!provider) return;
37
+ try {
38
+ const prov = await provider.loadChild(id);
39
+ if (prov?.ready) await prov.ready;
39
40
  childProvider.value = prov;
40
41
  } catch (e) {
41
42
  console.error("[ADocRenderer] Failed to load child provider:", e);
@@ -13,6 +13,18 @@ type __VLS_Props = {
13
13
  editorClass?: string;
14
14
  /** CSS class applied to structured renderers (kanban, table, etc.) */
15
15
  rendererClass?: string;
16
+ /**
17
+ * Override the doc-tree lookup with an explicit entry (`type`/`label`/`meta`).
18
+ * Use this when rendering a doc that is NOT in the active provider's root
19
+ * doc-tree — e.g. an admin browsing another space's documents, where the
20
+ * type lives in that space's own tree. When unset, falls back to the root
21
+ * tree as before, so this is purely additive.
22
+ */
23
+ entry?: {
24
+ type?: string;
25
+ label?: string;
26
+ meta?: Record<string, unknown>;
27
+ } | null;
16
28
  };
17
29
  declare var __VLS_1: {}, __VLS_23: {
18
30
  error: string;
@@ -1,3 +1,4 @@
1
+ import type * as Y from 'yjs';
1
2
  type __VLS_Props = {
2
3
  collapsed?: boolean;
3
4
  editable?: boolean;
@@ -8,6 +9,26 @@ type __VLS_Props = {
8
9
  * root as before — so this is a purely additive opt-in filter.
9
10
  */
10
11
  rootId?: string | null;
12
+ /**
13
+ * Render the tree from an explicitly supplied Y.Doc — typically a sibling
14
+ * space's child doc loaded via `provider.loadChild(spaceId)` — instead of
15
+ * the active entry doc. The supplied doc's OWN `doc-tree` map is used; its
16
+ * `parentId == null` entries (plus anything parented to `rootId`) become
17
+ * the roots, and the doc's self-entry (`rootId`) is hidden. This lets an
18
+ * admin browse another space's subtree without re-pointing the whole
19
+ * provider. When null (default) the tree reads the active entry doc as
20
+ * before, so this is purely additive.
21
+ */
22
+ sourceDoc?: Y.Doc | null;
23
+ /**
24
+ * Bind the tree to a space by id (= its root doc id). The owning space is
25
+ * connected on demand via `useSpaceConnections`, and the tree reads/writes
26
+ * its `doc-tree` natively — no need to hand in a `sourceDoc`. Precedence:
27
+ * explicit `sourceDoc` > `spaceId` connection doc > active entry doc.
28
+ * When the space is the active one this is a no-op (resolves to the
29
+ * singleton). Purely additive.
30
+ */
31
+ spaceId?: string | null;
11
32
  };
12
33
  declare var __VLS_39: {};
13
34
  type __VLS_Slots = {} & {
@@ -22,8 +43,10 @@ declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {
22
43
  onCreate?: ((parentId: string | null) => any) | undefined;
23
44
  onNavigate?: ((id: string) => any) | undefined;
24
45
  }>, {
46
+ spaceId: string | null;
25
47
  editable: boolean;
26
48
  rootId: string | null;
49
+ sourceDoc: Y.Doc | null;
27
50
  }, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
28
51
  declare const __VLS_export: __VLS_WithSlots<typeof __VLS_base, __VLS_Slots>;
29
52
  declare const _default: typeof __VLS_export;
@@ -6,12 +6,15 @@ import { resolveDocType, getAvailableDocTypes } from "../utils/docTypes";
6
6
  import { avatarBorderStyle } from "../utils/avatarStyle";
7
7
  import { DOC_DRAG_MIME, isDocDrag, parseDocDragPayload, isDescendantInMap } from "../utils/docDragDrop";
8
8
  import { useDocDragBus } from "../composables/useDocDragBus";
9
+ import { useSpaceConnections } from "../composables/useSpaceConnections";
9
10
  const dragBus = useDocDragBus();
10
11
  const props = defineProps({
11
12
  collapsed: { type: Boolean, required: false },
12
13
  editable: { type: Boolean, required: false, default: true },
13
14
  selectedId: { type: [String, null], required: false },
14
- rootId: { type: [String, null], required: false, default: null }
15
+ rootId: { type: [String, null], required: false, default: null },
16
+ sourceDoc: { type: null, required: false, default: null },
17
+ spaceId: { type: [String, null], required: false, default: null }
15
18
  });
16
19
  const emit = defineEmits(["navigate", "create"]);
17
20
  const { doc, spaceDocId, isReady, provider, client, userName } = useAbracadabra();
@@ -30,7 +33,28 @@ function leaveRoom() {
30
33
  const toast = useToast();
31
34
  const appConfig = useAppConfig();
32
35
  const presenceNeutral = computed(() => appConfig.ui?.colors?.neutral ?? "zinc");
33
- const treeMap = useSyncedMap(doc, "doc-tree");
36
+ const { connections, connectSpace } = useSpaceConnections();
37
+ const spaceConnDoc = shallowRef(null);
38
+ watch(() => props.spaceId, (sid) => {
39
+ spaceConnDoc.value = null;
40
+ if (!sid) return;
41
+ const existing = connections.get(sid);
42
+ if (existing) {
43
+ spaceConnDoc.value = existing.doc;
44
+ return;
45
+ }
46
+ void connectSpace(sid).then((conn) => {
47
+ if (props.spaceId === sid) spaceConnDoc.value = conn.doc;
48
+ }).catch(() => {
49
+ });
50
+ }, { immediate: true });
51
+ const treeSourceDoc = shallowRef(
52
+ props.sourceDoc ?? spaceConnDoc.value ?? doc.value
53
+ );
54
+ watch([() => props.sourceDoc, spaceConnDoc, doc], ([src, sconn, d]) => {
55
+ treeSourceDoc.value = src ?? sconn ?? d;
56
+ }, { immediate: true });
57
+ const treeMap = useSyncedMap(treeSourceDoc, "doc-tree");
34
58
  const structureHash = computed(() => {
35
59
  let h = 0;
36
60
  const data = treeMap.data;
@@ -54,10 +78,17 @@ const treeItems = computed(() => {
54
78
  const raw = toRaw(treeMap.data);
55
79
  const ROOT = "@root";
56
80
  const scopeRoot = props.rootId ?? null;
57
- const isTopLevel = (p) => scopeRoot != null ? p === scopeRoot : p == null || p === sid;
81
+ const boundSpaceId = props.spaceId && treeSourceDoc.value && treeSourceDoc.value !== doc.value ? props.spaceId : null;
82
+ const usingExplicitSource = props.sourceDoc != null;
83
+ const isTopLevel = (p) => {
84
+ if (scopeRoot != null) return p === scopeRoot;
85
+ if (boundSpaceId) return p == null || p === boundSpaceId;
86
+ if (usingExplicitSource) return p == null;
87
+ return p == null || p === sid;
88
+ };
58
89
  const childrenByParent = /* @__PURE__ */ new Map();
59
90
  for (const id in raw) {
60
- if (id === sid || id === scopeRoot) continue;
91
+ if (id === sid || id === scopeRoot || id === boundSpaceId) continue;
61
92
  const v = raw[id];
62
93
  const rawPid = v.parentId ?? null;
63
94
  const pid = isTopLevel(rawPid) ? ROOT : rawPid;
@@ -1192,7 +1223,7 @@ defineExpose({
1192
1223
  <template v-if="isReady">
1193
1224
  <div
1194
1225
  ref="scrollParent"
1195
- class="flex-1 min-h-0 overflow-y-auto px-1"
1226
+ class="flex-1 min-h-0 overflow-y-auto px-1 pb-4"
1196
1227
  :class="{ 'is-dragging': dragId }"
1197
1228
  @dragover.prevent
1198
1229
  @dragleave="onListDragLeave"
@@ -1,3 +1,4 @@
1
+ import type * as Y from 'yjs';
1
2
  type __VLS_Props = {
2
3
  collapsed?: boolean;
3
4
  editable?: boolean;
@@ -8,6 +9,26 @@ type __VLS_Props = {
8
9
  * root as before — so this is a purely additive opt-in filter.
9
10
  */
10
11
  rootId?: string | null;
12
+ /**
13
+ * Render the tree from an explicitly supplied Y.Doc — typically a sibling
14
+ * space's child doc loaded via `provider.loadChild(spaceId)` — instead of
15
+ * the active entry doc. The supplied doc's OWN `doc-tree` map is used; its
16
+ * `parentId == null` entries (plus anything parented to `rootId`) become
17
+ * the roots, and the doc's self-entry (`rootId`) is hidden. This lets an
18
+ * admin browse another space's subtree without re-pointing the whole
19
+ * provider. When null (default) the tree reads the active entry doc as
20
+ * before, so this is purely additive.
21
+ */
22
+ sourceDoc?: Y.Doc | null;
23
+ /**
24
+ * Bind the tree to a space by id (= its root doc id). The owning space is
25
+ * connected on demand via `useSpaceConnections`, and the tree reads/writes
26
+ * its `doc-tree` natively — no need to hand in a `sourceDoc`. Precedence:
27
+ * explicit `sourceDoc` > `spaceId` connection doc > active entry doc.
28
+ * When the space is the active one this is a no-op (resolves to the
29
+ * singleton). Purely additive.
30
+ */
31
+ spaceId?: string | null;
11
32
  };
12
33
  declare var __VLS_39: {};
13
34
  type __VLS_Slots = {} & {
@@ -22,8 +43,10 @@ declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {
22
43
  onCreate?: ((parentId: string | null) => any) | undefined;
23
44
  onNavigate?: ((id: string) => any) | undefined;
24
45
  }>, {
46
+ spaceId: string | null;
25
47
  editable: boolean;
26
48
  rootId: string | null;
49
+ sourceDoc: Y.Doc | null;
27
50
  }, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
28
51
  declare const __VLS_export: __VLS_WithSlots<typeof __VLS_base, __VLS_Slots>;
29
52
  declare const _default: typeof __VLS_export;
@@ -11,6 +11,7 @@ import { useDocTree } from "../composables/useDocTree";
11
11
  import { useDocBreadcrumb } from "../composables/useDocBreadcrumb";
12
12
  import { useDocSlugs } from "../composables/useDocSlugs";
13
13
  import { useChildTree } from "../composables/useChildTree";
14
+ import { useSpaceConnections } from "../composables/useSpaceConnections";
14
15
  import { useFavorites } from "../composables/useFavorites";
15
16
  import { useWindowManager } from "../composables/useWindowManager";
16
17
  import { useDocDragBus } from "../composables/useDocDragBus";
@@ -51,9 +52,15 @@ const viewMode = ref("rich");
51
52
  const emit = defineEmits(["ready", "update", "rename", "updateMeta"]);
52
53
  const model = defineModel({ type: null });
53
54
  const { doc, provider, registry } = useNuxtApp().$abracadabra;
54
- const _treeMap = useSyncedMap(doc, "doc-tree");
55
+ const { connections, getProviderForDoc, getDocForDoc } = useSpaceConnections();
56
+ const ownerProvider = computed(() => getProviderForDoc(props.docId) ?? provider.value);
57
+ const ownerDoc = shallowRef(getDocForDoc(props.docId) ?? doc.value);
58
+ watch(() => [doc.value, connections.size], () => {
59
+ ownerDoc.value = getDocForDoc(props.docId) ?? doc.value;
60
+ }, { immediate: true });
61
+ const _treeMap = useSyncedMap(ownerDoc, "doc-tree");
55
62
  const childProvider = shallowRef(null);
56
- watch(provider, async (prov) => {
63
+ watch(ownerProvider, async (prov) => {
57
64
  if (!prov || !props.docId) return;
58
65
  try {
59
66
  childProvider.value = await prov.loadChild(props.docId);
@@ -63,10 +70,10 @@ watch(provider, async (prov) => {
63
70
  }
64
71
  }, { immediate: true });
65
72
  onBeforeUnmount(() => {
66
- provider.value?.unpinChild?.(props.docId);
73
+ ownerProvider.value?.unpinChild?.(props.docId);
67
74
  });
68
75
  const docSuggestEnabled = (useRuntimeConfig().public?.abracadabra?.docPicker ?? "inline") === "inline";
69
- const _suggestTree = useChildTree(doc, props.docId);
76
+ const _suggestTree = useChildTree(ownerDoc, props.docId);
70
77
  const docSuggestExt = DocSuggest.configure({
71
78
  search: makeDocSearch(_suggestTree, props.docId),
72
79
  onCommit: (item, mode, range, query) => {
@@ -93,7 +100,7 @@ const editorRef = ref(null);
93
100
  const tiptapEditor = computed(() => editorRef.value?.editor ?? null);
94
101
  defineExpose({ editor: tiptapEditor });
95
102
  const { bubbleItems: toolbarItems } = useEditorToolbar({ docId: props.docId });
96
- const docTree = useDocTree();
103
+ const docTree = useDocTree(props.docId);
97
104
  const resolvedMetaSchema = computed(() => {
98
105
  if (props.metaSchema) return props.metaSchema;
99
106
  const geoType = props.docMeta?.geoType;
@@ -1,9 +1,10 @@
1
1
  <script setup>
2
- import { ref, computed, watch, defineAsyncComponent } from "vue";
2
+ import { ref, shallowRef, computed, watch, defineAsyncComponent } from "vue";
3
3
  import { useAbracadabra } from "../composables/useAbracadabra";
4
4
  import { useSyncedMap } from "../composables/useYDoc";
5
5
  import { navigateTo, useRuntimeConfig } from "#imports";
6
6
  import { useChildTree } from "../composables/useChildTree";
7
+ import { useSpaceConnections } from "../composables/useSpaceConnections";
7
8
  import { useAbraLocale } from "../composables/useAbraLocale";
8
9
  import { useDocSlugs } from "../composables/useDocSlugs";
9
10
  import { useResizableWidth } from "../composables/useResizableWidth";
@@ -35,11 +36,18 @@ const open = computed({
35
36
  });
36
37
  const locale = computed(() => useAbraLocale("nodePanel", props.labels));
37
38
  const { doc: rootDoc, registry } = useAbracadabra();
39
+ const { connections, getDocForDoc } = useSpaceConnections();
40
+ const ownerDoc = shallowRef(
41
+ props.nodeId ? getDocForDoc(props.nodeId) ?? rootDoc.value : rootDoc.value
42
+ );
43
+ watch(() => [props.nodeId, rootDoc.value, connections.size], () => {
44
+ ownerDoc.value = props.nodeId ? getDocForDoc(props.nodeId) ?? rootDoc.value : rootDoc.value;
45
+ }, { immediate: true });
38
46
  const tree = computed(() => {
39
47
  if (!props.nodeId) return null;
40
- return useChildTree(rootDoc, props.nodeId);
48
+ return useChildTree(ownerDoc, props.nodeId);
41
49
  });
42
- const treeMap = useSyncedMap(rootDoc, "doc-tree");
50
+ const treeMap = useSyncedMap(ownerDoc, "doc-tree");
43
51
  const entry = computed(() => {
44
52
  if (!props.nodeId) return null;
45
53
  return treeMap.data[props.nodeId] ?? null;
@@ -32,4 +32,11 @@ export interface DocTreeReturn {
32
32
  /** Raw useSyncedMap return for advanced usage */
33
33
  raw: ReturnType<typeof useSyncedMap>;
34
34
  }
35
- export declare function useDocTree(): DocTreeReturn;
35
+ /**
36
+ * @param docId When provided, the tree is read from the space that OWNS this
37
+ * doc (its label/type/meta + children live in that space's root `doc-tree`),
38
+ * not the active root — so the editor/slideover mutate the correct tree for a
39
+ * cross-space doc. Omitted (default) keeps the active-root behaviour, so every
40
+ * existing caller is unaffected.
41
+ */
42
+ export declare function useDocTree(docId?: string | null): DocTreeReturn;
@@ -1,15 +1,35 @@
1
- import { computed } from "vue";
1
+ import { computed, shallowRef, watch } from "vue";
2
2
  import { resolveDocType } from "../utils/docTypes.js";
3
3
  import { buildSlugMap } from "../utils/slugify.js";
4
4
  import { useRuntimeConfig } from "#imports";
5
5
  import { useAbracadabra } from "./useAbracadabra.js";
6
+ import { useSpaceConnections } from "./useSpaceConnections.js";
6
7
  import { useSyncedMap } from "./useYDoc.js";
7
- export function useDocTree() {
8
+ export function useDocTree(docId) {
8
9
  const abra = useAbracadabra();
10
+ const { connections, getDocForDoc, findDocSpaceId } = useSpaceConnections();
9
11
  const config = useRuntimeConfig();
10
12
  const docBasePath = config.public?.abracadabra?.docBasePath ?? "/doc";
11
- const treeMap = useSyncedMap(abra.doc, "doc-tree");
12
- const spaceDocId = abra.spaceDocId;
13
+ const boundDoc = shallowRef(
14
+ docId ? getDocForDoc(docId) ?? abra.doc.value : abra.doc.value
15
+ );
16
+ if (docId) {
17
+ watch(
18
+ () => [abra.doc.value, abra.spaceDocId.value, connections.size],
19
+ () => {
20
+ boundDoc.value = getDocForDoc(docId) ?? abra.doc.value;
21
+ },
22
+ { immediate: true }
23
+ );
24
+ } else {
25
+ watch(abra.doc, (d) => {
26
+ boundDoc.value = d;
27
+ }, { immediate: true });
28
+ }
29
+ const treeMap = useSyncedMap(boundDoc, "doc-tree");
30
+ const spaceDocId = computed(
31
+ () => docId ? findDocSpaceId(docId) ?? abra.spaceDocId.value : abra.spaceDocId.value
32
+ );
13
33
  const entries = computed(
14
34
  () => Object.entries(treeMap.data).filter(([id]) => id !== spaceDocId.value).map(([id, entry]) => ({ id, ...entry }))
15
35
  );
@@ -1,6 +1,6 @@
1
1
  import { ref, shallowRef, watch, onUnmounted } from "vue";
2
2
  import { Extension } from "@tiptap/core";
3
- import { XmlElement } from "yjs";
3
+ import { enforceDocumentShape } from "../utils/enforceDocumentShape.js";
4
4
  import { useNuxtApp } from "#imports";
5
5
  export function useEditor(options) {
6
6
  const { childProvider, extraExtensions = [] } = options;
@@ -90,56 +90,14 @@ export function useEditor(options) {
90
90
  ];
91
91
  const ydoc = prov.document;
92
92
  const fragment = ydoc?.getXmlFragment?.("default");
93
- function dedupeByName(nodeName) {
94
- if (!fragment) return;
95
- const children = fragment.toArray();
96
- const indices = [];
97
- children.forEach((child, idx) => {
98
- if (child.nodeName === nodeName) indices.push(idx);
99
- });
100
- if (indices.length <= 1) return;
101
- const toRemove = /* @__PURE__ */ new Set();
102
- for (let i = 1; i < indices.length; i++) {
103
- const hi = indices[i];
104
- toRemove.add(hi);
105
- const afterIdx = hi + 1;
106
- const beforeIdx = hi - 1;
107
- if (afterIdx < children.length && !toRemove.has(afterIdx) && children[afterIdx]?.nodeName === "paragraph" && children[afterIdx].length === 0) {
108
- toRemove.add(afterIdx);
109
- } else if (beforeIdx >= 0 && !toRemove.has(beforeIdx) && children[beforeIdx]?.nodeName === "paragraph" && children[beforeIdx].length === 0) {
110
- toRemove.add(beforeIdx);
111
- }
112
- }
113
- const sortedDesc = [...toRemove].sort((a, b) => b - a);
114
- ydoc.transact(() => {
115
- for (const idx of sortedDesc) fragment.delete(idx, 1);
116
- });
117
- }
118
- const dedupeHeaders = () => dedupeByName("documentHeader");
119
- const dedupeDocumentMeta = () => dedupeByName("documentMeta");
120
- function ensureDocumentMeta() {
121
- if (!fragment) return;
122
- const children = fragment.toArray();
123
- if (children.some((c) => c.nodeName === "documentMeta")) return;
124
- const headerIdx = children.findIndex((c) => c.nodeName === "documentHeader");
125
- const insertIdx = headerIdx >= 0 ? headerIdx + 1 : 0;
126
- const metaEl = new XmlElement("documentMeta");
127
- ydoc.transact(() => {
128
- fragment.insert(insertIdx, [metaEl]);
129
- });
130
- }
93
+ const healShape = () => {
94
+ if (fragment && ydoc) enforceDocumentShape(fragment, ydoc);
95
+ };
131
96
  if (fragment) {
132
- fragment.observe(dedupeHeaders);
133
- fragment.observe(dedupeDocumentMeta);
134
- dedupeHeaders();
135
- dedupeDocumentMeta();
136
- ensureDocumentMeta();
97
+ fragment.observe(healShape);
98
+ healShape();
137
99
  }
138
- const onProviderSynced = () => {
139
- dedupeHeaders();
140
- dedupeDocumentMeta();
141
- ensureDocumentMeta();
142
- };
100
+ const onProviderSynced = () => healShape();
143
101
  prov.on?.("synced", onProviderSynced);
144
102
  if (prov.isSynced) Promise.resolve().then(onProviderSynced);
145
103
  ready.value = true;
@@ -224,8 +182,7 @@ export function useEditor(options) {
224
182
  fadeOutTimeouts.forEach((t) => clearTimeout(t));
225
183
  fadeOutTimeouts.clear();
226
184
  if (fragment) {
227
- fragment.unobserve(dedupeHeaders);
228
- fragment.unobserve(dedupeDocumentMeta);
185
+ fragment.unobserve(healShape);
229
186
  }
230
187
  if (cursorBroadcastTimer) {
231
188
  clearTimeout(cursorBroadcastTimer);
@@ -1,22 +1,36 @@
1
1
  /**
2
- * useSpaceConnections — Single-space adapter.
2
+ * useSpaceConnections — per-space provider manager (module-native, lean port).
3
3
  *
4
- * cou-sh has a multi-space `useSpaceConnections` (1073 LOC) that manages
5
- * one provider per connected space. The Nuxt module is single-space — we
6
- * always have exactly one active provider tied to `spaceDocId`.
4
+ * Replaces the module's single-root-provider + `loadChild` model: alongside the
5
+ * always-bound ACTIVE space (which reuses the singleton provider/doc), any other
6
+ * space can be connected on demand as its OWN connection (own Y.Doc +
7
+ * AbracadabraProvider + live `treeData`), all multiplexed over the one shared
8
+ * server WebSocket. A document then resolves to its *owning space's* provider +
9
+ * tree — so doc type/label/meta and every mutation target the correct tree.
7
10
  *
8
- * This adapter wraps that single connection in the same `Map<spaceId, conn>`
9
- * shape, so consumers like `useDocLookup` and `useAggregatedPresence` can
10
- * iterate it the same way as in cou-sh. When (if ever) the module gains
11
- * multi-space, swap the implementation; the API stays.
11
+ * This is a deliberately lean adaptation of `cou-sh/app/composables/
12
+ * useSpaceConnections.ts`: it keeps the `SpaceConnection { doc, provider,
13
+ * treeData }` shape, connect/disconnect lifecycle, and the `findDocSpaceId` /
14
+ * `getProviderForDoc` / `resolveEntry` resolvers, but drops cou-sh's LRU
15
+ * eviction, WebRTC P2P, local/offline spaces, background sync, file-blob
16
+ * caching, and search indexing — none of which the module needs.
12
17
  *
13
- * Why a Map for a single entry? It keeps the cou-sh ports near-1:1 — they
14
- * iterate `for (const [, conn] of connections)` and read
15
- * `conn.provider?.awareness`. Forcing them to special-case "single space"
16
- * adds noise without changing behavior.
18
+ * Back-compat: the previous single-space adapter exposed `{ connections }` with
19
+ * exactly one entry (the active space), consumed by `useDocLookup` and
20
+ * `useAggregatedPresence`. That entry is preserved — the active-space binding
21
+ * below keeps it auto-populated, so those consumers are unaffected.
22
+ *
23
+ * Socket reuse: the module already owns one `AbracadabraWS` + `AbracadabraClient`.
24
+ * The client plugin injects a `createProvider(spaceId, ydoc)` factory via
25
+ * `_initSpaceConnections(...)` that builds a new `AbracadabraProvider` on that
26
+ * SAME `wsp`/`client`, so connecting a non-active space adds no new socket.
27
+ * Until that ctx is injected, only the active space is available (dormant mode).
28
+ *
29
+ * A space's id IS its root document id (see plugin `switchSpace`).
17
30
  */
18
31
  import { type Ref } from 'vue';
19
32
  import * as Y from 'yjs';
33
+ type AnyProvider = any;
20
34
  export interface SpaceTreeEntry {
21
35
  label: string;
22
36
  parentId: string | null;
@@ -27,17 +41,60 @@ export interface SpaceTreeEntry {
27
41
  updatedAt?: number;
28
42
  }
29
43
  export interface SpaceConnection {
44
+ /** Space id === space root document id. */
30
45
  spaceId: string;
31
46
  doc: Y.Doc;
32
- provider: unknown | null;
33
- client: unknown | null;
47
+ provider: AnyProvider | null;
48
+ client: AnyProvider | null;
49
+ /** Live snapshot of the space root's `doc-tree` Y.Map (deep-observed). */
34
50
  treeData: Ref<Record<string, SpaceTreeEntry>>;
35
- trashData: Ref<Record<string, unknown>>;
36
51
  status: Ref<'disconnected' | 'connecting' | 'connected'>;
37
52
  isReady: Ref<boolean>;
53
+ /** Cleanup functions to call on disconnect. */
54
+ _cleanups: Array<() => void>;
55
+ /** True for the singleton-backed active-space binding (never provider-destroyed). */
56
+ _isActive?: boolean;
38
57
  }
39
- interface SpaceConnectionsApi {
40
- connections: Map<string, SpaceConnection>;
58
+ /**
59
+ * Plugin-injected context. The client plugin owns the shared `wsp`/`client`,
60
+ * so it supplies the provider factory used to connect NON-active spaces.
61
+ * Set once at boot via `_initSpaceConnections`.
62
+ */
63
+ export interface SpaceConnectionsCtx {
64
+ /** Build a provider for `spaceId` (its root doc) on the shared socket. */
65
+ createProvider: (spaceId: string, ydoc: Y.Doc) => AnyProvider;
41
66
  }
42
- export declare function useSpaceConnections(): SpaceConnectionsApi;
67
+ /** Wire the shared socket factory. Called once from the client plugin. */
68
+ export declare function _initSpaceConnections(ctx: SpaceConnectionsCtx): void;
69
+ /** Tear down non-active connections + clear injected ctx (server/space switch). */
70
+ export declare function _resetSpaceConnections(): void;
71
+ /**
72
+ * Connect to a space (its root doc). Reuses the active binding when `spaceId`
73
+ * is the active space; otherwise creates a provider on the shared socket via
74
+ * the injected ctx, mirrors the tree, and registers the connection. Idempotent.
75
+ */
76
+ export declare function connectSpace(spaceId: string): Promise<SpaceConnection>;
77
+ /**
78
+ * Disconnect a single space: stop observers and destroy its provider. The
79
+ * active-space binding is singleton-backed (`_isActive`) and is NOT destroyed
80
+ * here — call this only for explicitly connected non-active spaces.
81
+ */
82
+ export declare function disconnectSpace(spaceId: string): void;
83
+ /** Disconnect every non-active space. */
84
+ export declare function disconnectAllSpaces(): void;
85
+ export declare function getSpaceConnection(spaceId: string): SpaceConnection | undefined;
86
+ /** Look up the connection that owns a given Y.Doc (used by child-tree views). */
87
+ export declare function findSpaceConnectionByDoc(doc: Y.Doc): SpaceConnection | undefined;
88
+ export declare function useSpaceConnections(): {
89
+ connections: import("vue").ShallowReactive<Map<string, SpaceConnection>>;
90
+ connectSpace: typeof connectSpace;
91
+ disconnectSpace: typeof disconnectSpace;
92
+ disconnectAllSpaces: typeof disconnectAllSpaces;
93
+ getSpaceConnection: typeof getSpaceConnection;
94
+ findSpaceConnectionByDoc: typeof findSpaceConnectionByDoc;
95
+ findDocSpaceId: (docId: string) => string | undefined;
96
+ getProviderForDoc: (docId: string) => AnyProvider | null;
97
+ getDocForDoc: (docId: string) => Y.Doc | null;
98
+ resolveEntry: (docId: string) => SpaceTreeEntry | undefined;
99
+ };
43
100
  export {};
@@ -1,72 +1,255 @@
1
- import { shallowReactive, ref, watch } from "vue";
1
+ import { ref, shallowReactive, watch } from "vue";
2
2
  import * as Y from "yjs";
3
3
  import { useAbracadabra } from "./useAbracadabra.js";
4
- let _singleton = null;
5
- function _build() {
6
- const state = useAbracadabra();
7
- const connections = shallowReactive(/* @__PURE__ */ new Map());
8
- const treeData = ref({});
9
- const trashData = ref({});
10
- let detachTree = null;
11
- let detachTrash = null;
12
- function syncMap(map, target) {
4
+ let _ctx = null;
5
+ export function _initSpaceConnections(ctx) {
6
+ _ctx = ctx;
7
+ }
8
+ export function _resetSpaceConnections() {
9
+ for (const id of [...connections.keys()]) {
10
+ const conn = connections.get(id);
11
+ if (conn && !conn._isActive) disconnectSpace(id);
12
+ }
13
+ _connectPromises.clear();
14
+ _ctx = null;
15
+ }
16
+ const connections = shallowReactive(/* @__PURE__ */ new Map());
17
+ const _connectPromises = /* @__PURE__ */ new Map();
18
+ function observeYMap(doc, mapName) {
19
+ const ymap = doc.getMap(mapName);
20
+ const data = ref({});
21
+ const snapshot = () => {
13
22
  const obj = {};
14
- map.forEach((val, key) => {
23
+ ymap.forEach((val, key) => {
15
24
  obj[key] = val instanceof Y.Map ? val.toJSON() : val;
16
25
  });
17
- target.value = obj;
18
- }
19
- function attachObservers(doc) {
20
- detachTree?.();
21
- detachTrash?.();
22
- const tree = doc.getMap("doc-tree");
23
- const trash = doc.getMap("doc-trash");
24
- syncMap(tree, treeData);
25
- syncMap(trash, trashData);
26
- const onTree = () => syncMap(tree, treeData);
27
- const onTrash = () => syncMap(trash, trashData);
28
- tree.observe(onTree);
29
- trash.observe(onTrash);
30
- detachTree = () => tree.unobserve(onTree);
31
- detachTrash = () => trash.unobserve(onTrash);
26
+ return obj;
27
+ };
28
+ data.value = snapshot();
29
+ let rafId = null;
30
+ const flush = () => {
31
+ rafId = null;
32
+ data.value = snapshot();
33
+ };
34
+ const observer = (_events, transaction) => {
35
+ if (transaction.local) {
36
+ if (rafId !== null) {
37
+ cancelAnimationFrame(rafId);
38
+ rafId = null;
39
+ }
40
+ data.value = snapshot();
41
+ } else if (typeof requestAnimationFrame !== "undefined") {
42
+ if (rafId === null) rafId = requestAnimationFrame(flush);
43
+ } else {
44
+ data.value = snapshot();
45
+ }
46
+ };
47
+ ymap.observeDeep(observer);
48
+ const onVisibilityChange = () => {
49
+ if (typeof document !== "undefined" && !document.hidden) {
50
+ if (rafId !== null) {
51
+ cancelAnimationFrame(rafId);
52
+ rafId = null;
53
+ }
54
+ data.value = snapshot();
55
+ }
56
+ };
57
+ if (typeof document !== "undefined") {
58
+ document.addEventListener("visibilitychange", onVisibilityChange);
32
59
  }
33
- if (import.meta.client) {
34
- watch(
35
- () => [
36
- state.spaceDocId.value,
37
- state.doc.value,
38
- state.provider.value,
39
- state.client.value
40
- ],
41
- ([spaceId, doc, provider, client]) => {
42
- connections.clear();
43
- if (!spaceId || !doc) {
44
- detachTree?.();
45
- detachTrash?.();
46
- detachTree = null;
47
- detachTrash = null;
48
- treeData.value = {};
49
- trashData.value = {};
50
- return;
60
+ queueMicrotask(() => {
61
+ data.value = snapshot();
62
+ });
63
+ const cleanup = () => {
64
+ try {
65
+ ymap.unobserveDeep(observer);
66
+ } catch {
67
+ }
68
+ if (rafId !== null) {
69
+ cancelAnimationFrame(rafId);
70
+ rafId = null;
71
+ }
72
+ if (typeof document !== "undefined") {
73
+ document.removeEventListener("visibilitychange", onVisibilityChange);
74
+ }
75
+ };
76
+ return { data, cleanup };
77
+ }
78
+ let _activeBound = false;
79
+ let _activeSpaceId = null;
80
+ function _ensureActiveBinding() {
81
+ if (_activeBound || !import.meta.client) return;
82
+ _activeBound = true;
83
+ const state = useAbracadabra();
84
+ watch(
85
+ () => [state.spaceDocId.value, state.doc.value, state.provider.value, state.client.value],
86
+ ([spaceId, doc, provider, client]) => {
87
+ if (_activeSpaceId && _activeSpaceId !== spaceId) {
88
+ const prev = connections.get(_activeSpaceId);
89
+ if (prev?._isActive) {
90
+ for (const fn of prev._cleanups) {
91
+ try {
92
+ fn();
93
+ } catch {
94
+ }
95
+ }
96
+ connections.delete(_activeSpaceId);
51
97
  }
52
- attachObservers(doc);
53
- connections.set(spaceId, {
54
- spaceId,
55
- doc,
56
- provider,
57
- client,
58
- treeData,
59
- trashData,
60
- status: state.status,
61
- isReady: state.isReady
62
- });
63
- },
64
- { immediate: true }
65
- );
98
+ }
99
+ _activeSpaceId = spaceId ?? null;
100
+ if (!spaceId || !doc) return;
101
+ if (connections.has(spaceId)) {
102
+ const c = connections.get(spaceId);
103
+ c._isActive = true;
104
+ return;
105
+ }
106
+ const { data: treeData, cleanup } = observeYMap(doc, "doc-tree");
107
+ connections.set(spaceId, {
108
+ spaceId,
109
+ doc,
110
+ provider,
111
+ client,
112
+ treeData,
113
+ status: state.status,
114
+ isReady: state.isReady,
115
+ _cleanups: [cleanup],
116
+ _isActive: true
117
+ });
118
+ },
119
+ { immediate: true }
120
+ );
121
+ }
122
+ export function connectSpace(spaceId) {
123
+ _ensureActiveBinding();
124
+ const existing = connections.get(spaceId);
125
+ if (existing) return Promise.resolve(existing);
126
+ const inflight = _connectPromises.get(spaceId);
127
+ if (inflight) return inflight;
128
+ const p = _connectSpace(spaceId).finally(() => {
129
+ _connectPromises.delete(spaceId);
130
+ });
131
+ _connectPromises.set(spaceId, p);
132
+ return p;
133
+ }
134
+ async function _connectSpace(spaceId) {
135
+ if (!_ctx) {
136
+ throw new Error("[useSpaceConnections] no provider factory \u2014 only the active space is available until the client plugin calls _initSpaceConnections()");
137
+ }
138
+ const ydoc = new Y.Doc();
139
+ const status = ref("connecting");
140
+ const isReady = ref(false);
141
+ const { data: treeData, cleanup: treeCleanup } = observeYMap(ydoc, "doc-tree");
142
+ const provider = _ctx.createProvider(spaceId, ydoc);
143
+ const conn = {
144
+ spaceId,
145
+ doc: ydoc,
146
+ provider,
147
+ client: null,
148
+ treeData,
149
+ status,
150
+ isReady,
151
+ _cleanups: [treeCleanup]
152
+ };
153
+ connections.set(spaceId, conn);
154
+ try {
155
+ if (provider?.ready) await provider.ready;
156
+ isReady.value = true;
157
+ status.value = "connected";
158
+ } catch (e) {
159
+ status.value = "disconnected";
160
+ console.error(`[useSpaceConnections] connect failed for ${spaceId}:`, e);
161
+ }
162
+ return conn;
163
+ }
164
+ export function disconnectSpace(spaceId) {
165
+ const conn = connections.get(spaceId);
166
+ if (!conn) return;
167
+ for (const fn of conn._cleanups) {
168
+ try {
169
+ fn();
170
+ } catch {
171
+ }
172
+ }
173
+ if (!conn._isActive) {
174
+ try {
175
+ conn.provider?.destroy?.();
176
+ } catch {
177
+ }
178
+ try {
179
+ conn.doc.destroy();
180
+ } catch {
181
+ }
182
+ }
183
+ connections.delete(spaceId);
184
+ }
185
+ export function disconnectAllSpaces() {
186
+ for (const spaceId of [...connections.keys()]) {
187
+ const conn = connections.get(spaceId);
188
+ if (conn && !conn._isActive) disconnectSpace(spaceId);
66
189
  }
67
- return { connections };
190
+ }
191
+ export function getSpaceConnection(spaceId) {
192
+ return connections.get(spaceId);
193
+ }
194
+ export function findSpaceConnectionByDoc(doc) {
195
+ for (const conn of connections.values()) {
196
+ if (conn.doc === doc) return conn;
197
+ }
198
+ return void 0;
68
199
  }
69
200
  export function useSpaceConnections() {
70
- if (!_singleton) _singleton = _build();
71
- return _singleton;
201
+ const abra = useAbracadabra();
202
+ _ensureActiveBinding();
203
+ function findDocSpaceId(docId) {
204
+ const current = abra.spaceDocId.value;
205
+ if (current === docId) return current;
206
+ for (const s of abra.currentServerSpaces.value) {
207
+ if (s.id === docId) return s.id;
208
+ }
209
+ for (const [spaceId, conn] of connections) {
210
+ if (conn.treeData.value[docId]) return spaceId;
211
+ }
212
+ return void 0;
213
+ }
214
+ function getProviderForDoc(docId) {
215
+ const spaceId = findDocSpaceId(docId);
216
+ if (spaceId) {
217
+ const conn = connections.get(spaceId);
218
+ if (conn?.provider) return conn.provider;
219
+ }
220
+ return abra.provider.value;
221
+ }
222
+ function getDocForDoc(docId) {
223
+ const spaceId = findDocSpaceId(docId);
224
+ if (spaceId) {
225
+ const conn = connections.get(spaceId);
226
+ if (conn?.doc) return conn.doc;
227
+ }
228
+ return abra.doc.value;
229
+ }
230
+ function resolveEntry(docId) {
231
+ const spaceId = findDocSpaceId(docId);
232
+ const conn = spaceId ? connections.get(spaceId) : void 0;
233
+ const fromConn = conn?.treeData.value[docId];
234
+ if (fromConn) return fromConn;
235
+ try {
236
+ const raw = abra.doc.value?.getMap("doc-tree")?.get(docId);
237
+ if (!raw) return void 0;
238
+ return raw instanceof Y.Map ? raw.toJSON() : raw;
239
+ } catch {
240
+ return void 0;
241
+ }
242
+ }
243
+ return {
244
+ connections,
245
+ connectSpace,
246
+ disconnectSpace,
247
+ disconnectAllSpaces,
248
+ getSpaceConnection,
249
+ findSpaceConnectionByDoc,
250
+ findDocSpaceId,
251
+ getProviderForDoc,
252
+ getDocForDoc,
253
+ resolveEntry
254
+ };
72
255
  }
@@ -48,6 +48,10 @@ import {
48
48
  _initServerInfo,
49
49
  _destroyServerInfo
50
50
  } from "./composables/useServerInfo.js";
51
+ import {
52
+ _initSpaceConnections,
53
+ _resetSpaceConnections
54
+ } from "./composables/useSpaceConnections.js";
51
55
  import { setSdkModule, getSdkModule } from "./utils/sdkRef.js";
52
56
  const NUXT_UI_PRIMARY_COLORS = /* @__PURE__ */ new Set([
53
57
  "red",
@@ -596,6 +600,7 @@ export default defineNuxtPlugin({
596
600
  lastClientIds = /* @__PURE__ */ new Set();
597
601
  clientNameCache.clear();
598
602
  doc.value = new Y.Doc();
603
+ _resetSpaceConnections();
599
604
  _destroyBackgroundSync();
600
605
  _destroyFileBlobStore();
601
606
  _destroySearchIndex();
@@ -1512,6 +1517,20 @@ export default defineNuxtPlugin({
1512
1517
  });
1513
1518
  _provider.attach();
1514
1519
  provider.value = _provider;
1520
+ _initSpaceConnections({
1521
+ createProvider: (spaceId, ydoc) => {
1522
+ const p = new AbracadabraProvider({
1523
+ name: spaceId,
1524
+ document: ydoc,
1525
+ websocketProvider: wsp,
1526
+ client: _client,
1527
+ forceSyncInterval: 3e4,
1528
+ token: () => tm.getValidToken()
1529
+ });
1530
+ p.attach();
1531
+ return p;
1532
+ }
1533
+ });
1515
1534
  try {
1516
1535
  const { FileBlobStore } = await import("@abraca/dabra");
1517
1536
  const blobStore = new FileBlobStore(serverUrl, _client);
@@ -0,0 +1,30 @@
1
+ import type { XmlFragment, Doc as YDoc } from 'yjs';
2
+ /**
3
+ * enforceDocumentShape — bulletproofs the structural invariant
4
+ * `documentHeader@0 + documentMeta@1 + block+` directly on the Y.XmlFragment.
5
+ *
6
+ * Operates *below* y-prosemirror so PM never sees a damaged shape (which would
7
+ * trigger PM's schema corrector to insert synthetic empty nodes — the root
8
+ * cause of "title moves down a few lines" and "metadata vanishes").
9
+ *
10
+ * Repairs performed, all inside a single `ydoc.transact(_, 'shape-enforcer')`:
11
+ * 1. Pick the *canonical* documentHeader by text weight (longer-text-wins).
12
+ * Tie → earliest. All other documentHeaders are deleted.
13
+ * 2. Pick the canonical documentMeta by child count. Tie → earliest.
14
+ * Before deleting extras, clone their metaField children into the
15
+ * canonical (deduped by metaKey/startKey/latKey identity) so no
16
+ * property chips are ever lost to a merge.
17
+ * 3. Delete any empty paragraph immediately adjacent to a deleted
18
+ * header/meta (legacy seed cleanup — pairs created during concurrent
19
+ * empty-seeding).
20
+ * 4. If canonical documentHeader is not at index 0, clone+reinsert at 0.
21
+ * 5. If canonical documentMeta is not at index 1 (or directly after the
22
+ * header), clone+reinsert at the correct slot.
23
+ * 6. If documentHeader is missing entirely, insert empty at index 0.
24
+ * 7. If documentMeta is missing entirely, insert empty after header.
25
+ *
26
+ * Idempotent. Safe to call on every observe event (no-op when healthy).
27
+ *
28
+ * Ported from cou-sh/app/utils/enforceDocumentShape.ts.
29
+ */
30
+ export declare function enforceDocumentShape(fragment: XmlFragment, ydoc: YDoc): void;
@@ -0,0 +1,228 @@
1
+ import { XmlElement } from "yjs";
2
+ export function enforceDocumentShape(fragment, ydoc) {
3
+ if (!fragment || !ydoc) return;
4
+ const children = fragment.toArray();
5
+ if (children.length === 0) {
6
+ return;
7
+ }
8
+ const headers = [];
9
+ const metas = [];
10
+ children.forEach((c, idx) => {
11
+ if (!(c instanceof XmlElement)) return;
12
+ if (c.nodeName === "documentHeader") {
13
+ headers.push({
14
+ idx,
15
+ el: c,
16
+ hasContent: hasHeaderText(c),
17
+ weight: weighElement(c)
18
+ });
19
+ } else if (c.nodeName === "documentMeta") {
20
+ metas.push({
21
+ idx,
22
+ el: c,
23
+ hasContent: hasMetaFields(c),
24
+ weight: weighElement(c)
25
+ });
26
+ }
27
+ });
28
+ const canonicalHeader = pickCanonical(headers);
29
+ const canonicalMeta = pickCanonical(metas);
30
+ const headerExtras = canonicalHeader ? headers.filter((h) => h !== canonicalHeader) : [];
31
+ const metaExtras = canonicalMeta ? metas.filter((m) => m !== canonicalMeta) : [];
32
+ const headerMissing = !canonicalHeader;
33
+ const metaMissing = !canonicalMeta;
34
+ const headerMisplaced = !!canonicalHeader && canonicalHeader.idx !== 0;
35
+ const metaMisplaced = !!canonicalMeta && (canonicalHeader ? canonicalMeta.idx !== (headerMisplaced ? 1 : canonicalHeader.idx + 1) : canonicalMeta.idx !== 0);
36
+ const hasDupes = headerExtras.length > 0 || metaExtras.length > 0;
37
+ if (!headerMissing && !metaMissing && !headerMisplaced && !metaMisplaced && !hasDupes) {
38
+ return;
39
+ }
40
+ const canonicalMetaKeys = /* @__PURE__ */ new Set();
41
+ if (canonicalMeta) {
42
+ forEachChild(canonicalMeta.el, (child) => {
43
+ if (child instanceof XmlElement && child.nodeName === "metaField") {
44
+ const id = metaFieldIdentity(child);
45
+ if (id) canonicalMetaKeys.add(id);
46
+ }
47
+ });
48
+ }
49
+ const metaFieldsToMerge = [];
50
+ for (const extra of metaExtras) {
51
+ forEachChild(extra.el, (child) => {
52
+ if (!(child instanceof XmlElement) || child.nodeName !== "metaField") return;
53
+ const id = metaFieldIdentity(child);
54
+ if (id && canonicalMetaKeys.has(id)) return;
55
+ if (id) canonicalMetaKeys.add(id);
56
+ const cloned = cloneMetaFieldElement(child);
57
+ if (cloned) metaFieldsToMerge.push(cloned);
58
+ });
59
+ }
60
+ ydoc.transact(() => {
61
+ if (metaFieldsToMerge.length > 0 && canonicalMeta?.el) {
62
+ try {
63
+ canonicalMeta.el.insert(canonicalMeta.el.length, metaFieldsToMerge);
64
+ } catch {
65
+ }
66
+ }
67
+ const childrenSnap = fragment.toArray();
68
+ const protectedIdx = /* @__PURE__ */ new Set();
69
+ if (canonicalHeader) protectedIdx.add(canonicalHeader.idx);
70
+ if (canonicalMeta) protectedIdx.add(canonicalMeta.idx);
71
+ const toDelete = /* @__PURE__ */ new Set();
72
+ const queueAdjacentEmpty = (anchor) => {
73
+ const after = anchor + 1;
74
+ if (after < childrenSnap.length && childrenSnap[after]?.nodeName === "paragraph" && (childrenSnap[after]?.length ?? 0) === 0 && !protectedIdx.has(after) && !toDelete.has(after))
75
+ toDelete.add(after);
76
+ };
77
+ for (const h of headerExtras) {
78
+ toDelete.add(h.idx);
79
+ queueAdjacentEmpty(h.idx);
80
+ }
81
+ for (const m of metaExtras) {
82
+ toDelete.add(m.idx);
83
+ queueAdjacentEmpty(m.idx);
84
+ }
85
+ const sorted = [...toDelete].sort((a, b) => b - a);
86
+ for (const idx of sorted) {
87
+ try {
88
+ fragment.delete(idx, 1);
89
+ } catch {
90
+ }
91
+ }
92
+ let curHeaderIdx = findFirst(fragment, "documentHeader");
93
+ if (curHeaderIdx > 0) {
94
+ const headerEl = fragment.toArray()[curHeaderIdx];
95
+ const cloned = headerEl ? safeClone(headerEl) : null;
96
+ if (cloned) {
97
+ fragment.delete(curHeaderIdx, 1);
98
+ fragment.insert(0, [cloned]);
99
+ curHeaderIdx = 0;
100
+ }
101
+ }
102
+ const expectedMetaIdx = curHeaderIdx >= 0 ? curHeaderIdx + 1 : 0;
103
+ const curMetaIdx = findFirst(fragment, "documentMeta");
104
+ if (curMetaIdx >= 0 && curMetaIdx !== expectedMetaIdx) {
105
+ const metaEl = fragment.toArray()[curMetaIdx];
106
+ const cloned = metaEl ? safeClone(metaEl) : null;
107
+ if (cloned) {
108
+ fragment.delete(curMetaIdx, 1);
109
+ const finalLen = fragment.length;
110
+ const target = Math.min(expectedMetaIdx, finalLen);
111
+ fragment.insert(target, [cloned]);
112
+ }
113
+ }
114
+ if (findFirst(fragment, "documentHeader") === -1) {
115
+ fragment.insert(0, [new XmlElement("documentHeader")]);
116
+ }
117
+ if (findFirst(fragment, "documentMeta") === -1) {
118
+ const hIdx = findFirst(fragment, "documentHeader");
119
+ fragment.insert(hIdx >= 0 ? hIdx + 1 : 0, [new XmlElement("documentMeta")]);
120
+ }
121
+ }, "shape-enforcer");
122
+ }
123
+ function weighElement(el) {
124
+ let w = 0;
125
+ try {
126
+ w = (typeof el?.toString === "function" ? el.toString() : "").length;
127
+ } catch {
128
+ }
129
+ if (typeof el?.length === "number") w = Math.max(w, el.length);
130
+ return w;
131
+ }
132
+ function hasHeaderText(el) {
133
+ try {
134
+ const arr = el?.toArray?.();
135
+ if (!Array.isArray(arr)) return false;
136
+ for (const child of arr) {
137
+ const len = typeof child?.length === "number" ? child.length : typeof child?.toString === "function" ? child.toString().length : 0;
138
+ if (len > 0) return true;
139
+ }
140
+ } catch {
141
+ }
142
+ return false;
143
+ }
144
+ function hasMetaFields(el) {
145
+ try {
146
+ const arr = el?.toArray?.();
147
+ if (!Array.isArray(arr)) return false;
148
+ for (const child of arr) {
149
+ if (child instanceof XmlElement && child.nodeName === "metaField") return true;
150
+ }
151
+ } catch {
152
+ }
153
+ return false;
154
+ }
155
+ function pickCanonical(arr) {
156
+ if (arr.length === 0) return null;
157
+ let best = arr[0];
158
+ for (let i = 1; i < arr.length; i++) {
159
+ const c = arr[i];
160
+ if (c.hasContent && !best.hasContent) {
161
+ best = c;
162
+ continue;
163
+ }
164
+ if (!c.hasContent && best.hasContent) continue;
165
+ if (c.weight > best.weight || c.weight === best.weight && c.idx < best.idx)
166
+ best = c;
167
+ }
168
+ return best;
169
+ }
170
+ function forEachChild(el, fn) {
171
+ try {
172
+ const arr = el?.toArray?.();
173
+ if (!Array.isArray(arr)) return;
174
+ for (const c of arr) fn(c);
175
+ } catch {
176
+ }
177
+ }
178
+ function metaFieldIdentity(mf) {
179
+ try {
180
+ const attrs = typeof mf?.getAttributes === "function" ? mf.getAttributes() : {};
181
+ const metaKey = String(attrs.metaKey ?? "");
182
+ if (metaKey) return `mk:${metaKey}`;
183
+ const startKey = String(attrs.startKey ?? "");
184
+ const endKey = String(attrs.endKey ?? "");
185
+ const latKey = String(attrs.latKey ?? "");
186
+ const lngKey = String(attrs.lngKey ?? "");
187
+ const allDayKey = String(attrs.allDayKey ?? "");
188
+ const composite = `${startKey}:${endKey}:${latKey}:${lngKey}:${allDayKey}`;
189
+ if (composite === "::::") return "";
190
+ return `c:${composite}`;
191
+ } catch {
192
+ return "";
193
+ }
194
+ }
195
+ function cloneMetaFieldElement(src) {
196
+ try {
197
+ if (typeof src?.clone === "function") {
198
+ const c = src.clone();
199
+ if (c) return c;
200
+ }
201
+ const clone = new XmlElement("metaField");
202
+ const attrs = src.getAttributes();
203
+ for (const [k, v] of Object.entries(attrs)) clone.setAttribute(k, v);
204
+ return clone;
205
+ } catch {
206
+ return null;
207
+ }
208
+ }
209
+ function safeClone(src) {
210
+ try {
211
+ if (typeof src?.clone === "function") {
212
+ const c = src.clone();
213
+ if (c) return c;
214
+ }
215
+ } catch {
216
+ }
217
+ return null;
218
+ }
219
+ function findFirst(fragment, nodeName) {
220
+ try {
221
+ const arr = fragment.toArray();
222
+ for (let i = 0; i < arr.length; i++) {
223
+ if (arr[i]?.nodeName === nodeName) return i;
224
+ }
225
+ } catch {
226
+ }
227
+ return -1;
228
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abraca/nuxt",
3
- "version": "2.42.0",
3
+ "version": "2.46.0",
4
4
  "description": "First-class Nuxt module for the Abracadabra CRDT collaboration platform",
5
5
  "repository": "abracadabra/abracadabra-nuxt",
6
6
  "license": "MIT",