@dou-ui/dashboard 0.1.0-alpha.2 → 0.1.0-alpha.20

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 (100) hide show
  1. package/dist/chart/chart-settings.js.map +1 -1
  2. package/dist/chart/chart-settings.vue_vue_type_script_setup_true_lang.js +10 -8
  3. package/dist/chart/chart-settings.vue_vue_type_script_setup_true_lang.js.map +1 -1
  4. package/dist/chart/chart.js.map +1 -1
  5. package/dist/chart/chart.vue_vue_type_script_setup_true_lang.js +19 -15
  6. package/dist/chart/chart.vue_vue_type_script_setup_true_lang.js.map +1 -1
  7. package/dist/chart/read-props.js +26 -0
  8. package/dist/chart/read-props.js.map +1 -0
  9. package/dist/collaboration/index.js +151 -7
  10. package/dist/collaboration/index.js.map +1 -1
  11. package/dist/core/document.js +10 -1
  12. package/dist/core/document.js.map +1 -1
  13. package/dist/core/history.js +23 -0
  14. package/dist/core/history.js.map +1 -1
  15. package/dist/core/transaction.js +14 -5
  16. package/dist/core/transaction.js.map +1 -1
  17. package/dist/dashboard/comment-button.js +6 -0
  18. package/dist/dashboard/comment-button.js.map +1 -0
  19. package/dist/dashboard/comment-button.vue_vue_type_script_setup_true_lang.js +59 -0
  20. package/dist/dashboard/comment-button.vue_vue_type_script_setup_true_lang.js.map +1 -0
  21. package/dist/dashboard/comment-card.js +6 -0
  22. package/dist/dashboard/comment-card.js.map +1 -0
  23. package/dist/dashboard/comment-card.vue_vue_type_script_setup_true_lang.js +128 -0
  24. package/dist/dashboard/comment-card.vue_vue_type_script_setup_true_lang.js.map +1 -0
  25. package/dist/dashboard/comments.js +144 -0
  26. package/dist/dashboard/comments.js.map +1 -0
  27. package/dist/dashboard/dashboard.js.map +1 -1
  28. package/dist/dashboard/dashboard.vue_vue_type_script_setup_true_lang.js +132 -20
  29. package/dist/dashboard/dashboard.vue_vue_type_script_setup_true_lang.js.map +1 -1
  30. package/dist/dashboard/error-boundary.js +64 -0
  31. package/dist/dashboard/error-boundary.js.map +1 -0
  32. package/dist/dashboard/frame-context.js.map +1 -1
  33. package/dist/dashboard/widget-body.js.map +1 -1
  34. package/dist/dashboard/widget-body.vue_vue_type_script_setup_true_lang.js +53 -12
  35. package/dist/dashboard/widget-body.vue_vue_type_script_setup_true_lang.js.map +1 -1
  36. package/dist/dashboard/widget-frame.js.map +1 -1
  37. package/dist/dashboard/widget-frame.vue_vue_type_script_setup_true_lang.js +20 -10
  38. package/dist/dashboard/widget-frame.vue_vue_type_script_setup_true_lang.js.map +1 -1
  39. package/dist/dashboard/widget-settings.js.map +1 -1
  40. package/dist/dashboard/widget-settings.vue_vue_type_script_setup_true_lang.js +31 -5
  41. package/dist/dashboard/widget-settings.vue_vue_type_script_setup_true_lang.js.map +1 -1
  42. package/dist/index.js.map +1 -1
  43. package/dist/locale.js +12 -0
  44. package/dist/locale.js.map +1 -1
  45. package/dist/pivot/pivot-settings.js.map +1 -1
  46. package/dist/pivot/pivot-settings.vue_vue_type_script_setup_true_lang.js +6 -4
  47. package/dist/pivot/pivot-settings.vue_vue_type_script_setup_true_lang.js.map +1 -1
  48. package/dist/pivot/pivot.js.map +1 -1
  49. package/dist/pivot/pivot.vue_vue_type_script_setup_true_lang.js +5 -2
  50. package/dist/pivot/pivot.vue_vue_type_script_setup_true_lang.js.map +1 -1
  51. package/dist/pivot/read-props.js +44 -0
  52. package/dist/pivot/read-props.js.map +1 -0
  53. package/dist/style.css +1 -1
  54. package/dist/style.js +2 -4
  55. package/dist/types/chart/read-props.d.ts +3 -0
  56. package/dist/types/collaboration/index.d.ts +22 -1
  57. package/dist/types/core/document.d.ts +3 -2
  58. package/dist/types/core/history.d.ts +7 -1
  59. package/dist/types/core/transaction.d.ts +11 -2
  60. package/dist/types/core/types.d.ts +5 -0
  61. package/dist/types/dashboard/comment-button.vue.d.ts +15 -0
  62. package/dist/types/dashboard/comment-card.vue.d.ts +13 -0
  63. package/dist/types/dashboard/comments.d.ts +44 -0
  64. package/dist/types/dashboard/dashboard.vue.d.ts +12 -0
  65. package/dist/types/dashboard/error-boundary.d.ts +12 -0
  66. package/dist/types/dashboard/frame-context.d.ts +4 -0
  67. package/dist/types/dashboard/types.d.ts +47 -0
  68. package/dist/types/dashboard/widget-body.vue.d.ts +2 -0
  69. package/dist/types/dashboard/widget-settings.vue.d.ts +4 -0
  70. package/dist/types/index.d.ts +22 -1
  71. package/dist/types/locale.d.ts +8 -0
  72. package/dist/types/pivot/read-props.d.ts +3 -0
  73. package/dist/types/widgets/index.d.ts +1 -1
  74. package/dist/types/widgets/read-props.d.ts +4 -0
  75. package/dist/types/widgets/shared.d.ts +20 -4
  76. package/dist/widgets/index.js +2 -2
  77. package/dist/widgets/index.js.map +1 -1
  78. package/dist/widgets/read-props.js +52 -0
  79. package/dist/widgets/read-props.js.map +1 -0
  80. package/dist/widgets/shared.js +27 -5
  81. package/dist/widgets/shared.js.map +1 -1
  82. package/dist/widgets/stat-settings.js.map +1 -1
  83. package/dist/widgets/stat-settings.vue_vue_type_script_setup_true_lang.js +12 -10
  84. package/dist/widgets/stat-settings.vue_vue_type_script_setup_true_lang.js.map +1 -1
  85. package/dist/widgets/stat.js.map +1 -1
  86. package/dist/widgets/stat.vue_vue_type_script_setup_true_lang.js +10 -13
  87. package/dist/widgets/stat.vue_vue_type_script_setup_true_lang.js.map +1 -1
  88. package/dist/widgets/table-settings.js.map +1 -1
  89. package/dist/widgets/table-settings.vue_vue_type_script_setup_true_lang.js +6 -4
  90. package/dist/widgets/table-settings.vue_vue_type_script_setup_true_lang.js.map +1 -1
  91. package/dist/widgets/table.js.map +1 -1
  92. package/dist/widgets/table.vue_vue_type_script_setup_true_lang.js +4 -1
  93. package/dist/widgets/table.vue_vue_type_script_setup_true_lang.js.map +1 -1
  94. package/dist/widgets/text-settings.js.map +1 -1
  95. package/dist/widgets/text-settings.vue_vue_type_script_setup_true_lang.js +5 -3
  96. package/dist/widgets/text-settings.vue_vue_type_script_setup_true_lang.js.map +1 -1
  97. package/dist/widgets/text.js.map +1 -1
  98. package/dist/widgets/text.vue_vue_type_script_setup_true_lang.js +5 -3
  99. package/dist/widgets/text.vue_vue_type_script_setup_true_lang.js.map +1 -1
  100. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/collaboration/index.ts"],"sourcesContent":["import { collaborationColors } from 'dou-ui'\nimport { shallowRef } from 'vue'\nimport * as Y from 'yjs'\nimport type {\n DashboardCollaboration,\n DashboardCollaborationHost,\n DashboardPeer,\n DashboardPresence,\n} from '../core/collaboration'\nimport type { DashboardTransaction } from '../core/transaction'\nimport type { DashboardDocument, DashboardWidget } from '../core/types'\nimport { orderKeys } from './order'\n\n/** The part of an `Awareness` (`y-protocols/awareness`) the dashboard uses. */\nexport interface AwarenessLike {\n clientID: number\n getLocalState(): Record<string, unknown> | null\n setLocalStateField(field: string, value: unknown): void\n getStates(): Map<number, Record<string, unknown>>\n on(event: 'change', listener: (...args: unknown[]) => void): void\n off(event: 'change', listener: (...args: unknown[]) => void): void\n}\n\n/** How the people editing together see each other. */\nexport interface CollaborationUser {\n name: string\n /** The color of this user's outlines, any CSS color. Picked from the client id when left out. */\n color?: string\n}\n\nexport interface CollaborationOptions {\n /** Where the widgets live, e.g. `ydoc.getMap('widgets')`. */\n widgets: Y.Map<unknown>\n /** Shares which widget each person is at, and what they do there (`y-protocols/awareness`). */\n awareness?: AwarenessLike\n /** This user, shown to the others. Needs `awareness`. */\n user?: CollaborationUser\n}\n\nexport { collaborationColors }\nexport type { DashboardPeer, DashboardPresence }\n\ntype Shared = Y.Map<unknown>\ntype Item = Record<string, unknown>\n\n/** A widget's place among the others, kept beside its keys. */\nconst ORDER = '$order'\n/** The places by breakpoint, a map of their own, so places on two breakpoints don't overwrite each other. */\nconst PLACE = 'place'\n\nconst same = (a: unknown, b: unknown) =>\n a === b ||\n (typeof a === 'object' && typeof b === 'object' && JSON.stringify(a) === JSON.stringify(b))\n\n/** Where in `value` something JSON can't carry sits, e.g. a component or a function. */\nfunction unshareable(value: unknown, path: string): string | null {\n if (value === null || ['string', 'number', 'boolean', 'undefined'].includes(typeof value))\n return null\n if (typeof value !== 'object') return path\n const proto = Object.getPrototypeOf(value)\n if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) return path\n for (const [key, item] of Object.entries(value)) {\n const found = unshareable(item, Array.isArray(value) ? `${path}[${key}]` : `${path}.${key}`)\n if (found) return found\n }\n return null\n}\n\nconst warned = new Set<string>()\n/** Others would get a broken copy of such a value while this dashboard shows it fine. */\nfunction warnUnshareable(id: string, key: string, value: unknown) {\n // the app's bundler replaces this, as for Vue's own warnings\n if (process.env.NODE_ENV === 'production') return\n const path = unshareable(value, key)\n if (!path || warned.has(`${id}:${path}`)) return\n warned.add(`${id}:${path}`)\n console.warn(\n `[@dou-ui/dashboard] \"${id}\" has ${path}, which can't be shared: only JSON values reach the others.`,\n )\n}\n\n/** Writes the places that changed into a widget's place map. */\nfunction writePlace(fields: Shared, place: DashboardWidget['place']) {\n const shared = fields.get(PLACE)\n if (!(shared instanceof Y.Map)) {\n const map = new Y.Map<unknown>()\n for (const [name, value] of Object.entries(place)) if (value) map.set(name, { ...value })\n fields.set(PLACE, map)\n return\n }\n for (const [name, value] of Object.entries(place))\n if (value && !same(shared.get(name), value)) shared.set(name, { ...value })\n for (const name of Array.from(shared.keys())) if (!place[name]) shared.delete(name)\n}\n\n/** Writes a widget's keys besides its order, only those that changed; `keys` limits which. */\nfunction writeWidget(map: Shared, widget: DashboardWidget, keys?: Set<string>) {\n const existing = map.get(widget.id)\n const item = widget as unknown as Item\n if (!(existing instanceof Y.Map)) {\n // a new map can't be read before it is in the document: fill it, then put it in\n const fields = new Y.Map<unknown>()\n for (const [key, value] of Object.entries(item)) {\n if (key === 'id' || value === undefined) continue\n if (key === PLACE) {\n const places = new Y.Map<unknown>()\n for (const [name, place] of Object.entries(value as DashboardWidget['place']))\n if (place) places.set(name, { ...place })\n fields.set(PLACE, places)\n continue\n }\n warnUnshareable(widget.id, key, value)\n fields.set(key, value)\n }\n map.set(widget.id, fields)\n return\n }\n for (const [key, value] of Object.entries(item)) {\n if (key === 'id' || value === undefined || (keys && !keys.has(key))) continue\n if (key === PLACE) writePlace(existing, value as DashboardWidget['place'])\n else if (!same(existing.get(key), value)) {\n warnUnshareable(widget.id, key, value)\n existing.set(key, value)\n }\n }\n for (const key of Array.from(existing.keys()))\n if (key[0] !== '$' && item[key] === undefined && (!keys || keys.has(key))) existing.delete(key)\n}\n\n/** Writes each widget's order key, giving new keys only where it must. */\nfunction writeOrder(map: Shared, widgets: readonly DashboardWidget[]) {\n const shared = widgets.map((widget) => {\n const fields = map.get(widget.id)\n return fields instanceof Y.Map ? fields : null\n })\n const keys = orderKeys(shared.map((fields) => (fields?.get(ORDER) as string | undefined) ?? null))\n shared.forEach((fields, index) => {\n if (fields && fields.get(ORDER) !== keys[index]) fields.set(ORDER, keys[index])\n })\n}\n\n/**\n * Writes a dashboard into an empty map, e.g. when a dashboard so far saved\n * as JSON starts being edited together. Do it once, where the shared\n * document is created; otherwise the first person to open the dashboard\n * brings theirs.\n */\nexport function fillMap(map: Y.Map<unknown>, document: DashboardDocument) {\n const fill = () => {\n for (const widget of document.widgets) writeWidget(map, widget)\n writeOrder(map, document.widgets)\n }\n if (map.doc) map.doc.transact(fill)\n else fill()\n}\n\n/** The dashboard the map holds: its widgets by their order keys (then ids, the same for everyone). */\nexport function readMap(map: Y.Map<unknown>): DashboardDocument {\n const list: { widget: DashboardWidget; order: string }[] = []\n map.forEach((value, id) => {\n if (!(value instanceof Y.Map)) return\n const { [ORDER]: order, ...rest } = value.toJSON() as Item\n if (typeof rest.type !== 'string') return\n const place = rest[PLACE]\n list.push({\n widget: {\n ...rest,\n id,\n place: place && typeof place === 'object' ? place : {},\n } as DashboardWidget,\n order: typeof order === 'string' ? order : '',\n })\n })\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts the list built here\n list.sort((a, b) =>\n a.order < b.order ? -1 : a.order > b.order ? 1 : a.widget.id < b.widget.id ? -1 : 1,\n )\n return { version: 1, widgets: list.map((entry) => entry.widget) }\n}\n\n/** The widgets and keys a transaction changed, written to the map. */\nfunction writeChanges(map: Shared, tr: DashboardTransaction) {\n const after = new Map(tr.doc.widgets.map((widget) => [widget.id, widget]))\n const touched = new Map<string, Set<string> | true>()\n let added = false\n let removed = false\n for (const step of tr.steps) {\n if (step.type === 'add') {\n touched.set(step.widget.id, true)\n added = true\n } else if (step.type === 'remove') {\n removed = true\n touched.delete(step.id)\n } else {\n const current = touched.get(step.id)\n if (current === true) continue\n const keys = current ?? new Set<string>()\n for (const key of Object.keys(step.patch)) keys.add(key)\n touched.set(step.id, keys)\n }\n }\n if (removed)\n for (const widget of tr.before.widgets) if (!after.has(widget.id)) map.delete(widget.id)\n for (const [id, keys] of touched) {\n const widget = after.get(id)\n if (!widget) continue\n // a widget removed and added again in one change is written anew\n if (keys === true && map.get(id) instanceof Y.Map && removed) map.delete(id)\n writeWidget(map, widget, keys === true ? undefined : keys)\n }\n if (added) writeOrder(map, tr.doc.widgets)\n}\n\nconst NO_PEERS: readonly DashboardPeer[] = []\n\n/**\n * Edit a dashboard together through a Yjs document: pass the result to\n * `DouDashboard` as `collaboration`. Each widget lives in `widgets` as its\n * own `Y.Map`, each key on its own and each breakpoint's place on its own,\n * so two people changing different widgets, or different settings of one,\n * both keep their change. When two people move widgets at once, everyone\n * lays the places out the same way, so the dashboards agree. While a widget\n * is dragged, changes from others wait until it is let go. The dashboard's\n * `v-model` only mirrors the shared document: a document set through\n * `v-model` from outside is not written back. Undo only takes back this\n * user's own changes. With `awareness`, each person sees which widget the\n * others are at, outlined in their colors, and whether they are moving,\n * resizing or changing its settings.\n */\nexport function collaboration(options: CollaborationOptions): DashboardCollaboration {\n const { widgets: map, awareness, user } = options\n const ydoc = map.doc\n if (!ydoc) throw new Error('[@dou-ui/dashboard] widgets must be a map of a Y.Doc')\n if (awareness && user) {\n const color = user.color ?? collaborationColors[ydoc.clientID % collaborationColors.length]\n awareness.setLocalStateField('user', { name: user.name, color })\n }\n\n /** This dashboard's own changes, which undo can take back. */\n const tracked = { dashboard: 'tracked' }\n /** Changes undo leaves alone, e.g. filling the map. */\n const untracked = { dashboard: 'untracked' }\n const undoManager = new Y.UndoManager([map], {\n trackedOrigins: new Set([tracked]),\n captureTimeout: 500,\n })\n /** Bumped when the undo stacks change, so `canUndo` and `canRedo` update. */\n const stacks = shallowRef(0)\n const bump = () => stacks.value++\n undoManager.on('stack-item-added', bump)\n undoManager.on('stack-item-popped', bump)\n undoManager.on('stack-cleared', bump)\n\n let host: DashboardCollaborationHost | undefined\n /** What undo or redo is running, to name the change. */\n let travelling: 'undo' | 'redo' | null = null\n let lastGroup: string | undefined\n\n /** Brings the dashboard in line with the map. */\n function pull() {\n host?.apply(readMap(map), travelling ?? 'remote')\n }\n\n function run(action: 'undo' | 'redo') {\n const stack = action === 'undo' ? undoManager.undoStack : undoManager.redoStack\n if (!stack.length) return false\n travelling = action\n try {\n undoManager[action]()\n } finally {\n travelling = null\n }\n return true\n }\n\n /** The others at each widget. */\n const peersByWidget = shallowRef(new Map<string, DashboardPeer[]>())\n function readPeers() {\n if (!awareness) return\n const next = new Map<string, DashboardPeer[]>()\n awareness.getStates().forEach((state, client) => {\n if (client === awareness.clientID) return\n const who = state.user as { name?: string; color?: string } | undefined\n const presence = state.dashboard as DashboardPresence | null | undefined\n if (!who || !presence?.widget) return\n const peer: DashboardPeer = {\n client,\n name: who.name ?? '',\n color: who.color ?? 'currentColor',\n action: presence.action,\n }\n const list = next.get(presence.widget)\n if (list) list.push(peer)\n else next.set(presence.widget, [peer])\n })\n peersByWidget.value = next\n }\n\n return {\n setup(dashboard) {\n host = dashboard\n // the first one to open the dashboard brings its widgets; everyone else reads the map\n if (!map.size) ydoc.transact(() => fillMap(map, dashboard.document()), untracked)\n pull()\n\n // changes from others, and from undo: applied once per Yjs transaction\n let dirty = false\n const observe = (_events: unknown, transaction: Y.Transaction) => {\n if (transaction.origin !== tracked && transaction.origin !== untracked) dirty = true\n }\n const flush = () => {\n if (!dirty) return\n dirty = false\n pull()\n }\n map.observeDeep(observe)\n ydoc.on('afterTransaction', flush)\n if (awareness) {\n readPeers()\n awareness.on('change', readPeers)\n }\n return () => {\n map.unobserveDeep(observe)\n ydoc.off('afterTransaction', flush)\n if (awareness) awareness.off('change', readPeers)\n host = undefined\n }\n },\n transaction(tr) {\n const tracking = tr.meta.history !== false\n // like the dashboard's own history: only changes of one group undo together\n if (tracking && (!tr.meta.group || tr.meta.group !== lastGroup)) undoManager.stopCapturing()\n if (tracking) lastGroup = tr.meta.group\n ydoc.transact(() => writeChanges(map, tr), tracking ? tracked : untracked)\n },\n sync: pull,\n undo: () => run('undo'),\n redo: () => run('redo'),\n canUndo: () => (stacks.value, undoManager.undoStack.length > 0),\n canRedo: () => (stacks.value, undoManager.redoStack.length > 0),\n presence: awareness\n ? (presence) => awareness.setLocalStateField('dashboard', presence)\n : undefined,\n peers: awareness ? (id) => peersByWidget.value.get(id) ?? NO_PEERS : undefined,\n }\n}\n"],"mappings":";;;;;;AA8CA,IAAM,QAAQ;;AAEd,IAAM,QAAQ;AAEd,IAAM,QAAQ,GAAY,MACxB,MAAM,KACL,OAAO,MAAM,YAAY,OAAO,MAAM,YAAY,KAAK,UAAU,CAAC,MAAM,KAAK,UAAU,CAAC;;AAG3F,SAAS,YAAY,OAAgB,MAA6B;CAChE,IAAI,UAAU,QAAQ;EAAC;EAAU;EAAU;EAAW;CAAW,CAAC,CAAC,SAAS,OAAO,KAAK,GACtF,OAAO;CACT,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,MAAM,QAAQ,OAAO,eAAe,KAAK;CACzC,IAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,UAAU,OAAO,aAAa,UAAU,MAAM,OAAO;CAClF,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,KAAK,GAAG;EAC/C,MAAM,QAAQ,YAAY,MAAM,MAAM,QAAQ,KAAK,IAAI,GAAG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IAAI,YAAY,WAAW,WAAW,YAAY,WAAW,WAAW,QAAQ;GAClF;GACA,MAAM,cAAc;IAClB,IAAI,CAAC,OAAO;IACZ,QAAQ;IACR,KAAK;GACP;GACA,IAAI,YAAY,OAAO;GACvB,KAAK,GAAG,oBAAoB,KAAK;GACjC,IAAI,WAAW;IACb,UAAU;IACV,UAAU,GAAG,UAAU,SAAS;GAClC;GACA,aAAa;IACX,IAAI,cAAc,OAAO;IACzB,KAAK,IAAI,oBAAoB,KAAK;IAClC,IAAI,WAAW,UAAU,IAAI,UAAU,SAAS;IAChD,OAAO,KAAA;GACT;EACF;EACA,YAAY,IAAI;GACd,MAAM,WAAW,GAAG,KAAK,YAAY;GAErC,IAAI,aAAa,CAAC,GAAG,KAAK,SAAS,GAAG,KAAK,UAAU,YAAY,YAAY,cAAc;GAC3F,IAAI,UAAU,YAAY,GAAG,KAAK;GAClC,KAAK,eAAe,aAAa,KAAK,EAAE,GAAG,WAAW,UAAU,SAAS;EAC3E;EACA,MAAM;EACN,YAAY,IAAI,MAAM;EACtB,YAAY,IAAI,MAAM;EACtB,gBAAgB,OAAO,OAAO,YAAY,UAAU,SAAS;EAC7D,gBAAgB,OAAO,OAAO,YAAY,UAAU,SAAS;EAC7D,UAAU,aACL,aAAa,UAAU,mBAAmB,aAAa,QAAQ,IAChE,KAAA;EACJ,OAAO,aAAa,OAAO,cAAc,MAAM,IAAI,EAAE,KAAK,WAAW,KAAA;CACvE;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/collaboration/index.ts"],"sourcesContent":["import { collaborationColors } from 'dou-ui'\nimport { shallowRef } from 'vue'\nimport * as Y from 'yjs'\nimport type {\n DashboardCollaboration,\n DashboardCollaborationHost,\n DashboardPeer,\n DashboardPresence,\n} from '../core/collaboration'\nimport { sameValue, type DashboardTransaction } from '../core/transaction'\nimport type { DashboardDocument, DashboardWidget } from '../core/types'\nimport { keptIndexes, orderKeys } from './order'\n\n/** The part of an `Awareness` (`y-protocols/awareness`) the dashboard uses. */\nexport interface AwarenessLike {\n clientID: number\n getLocalState(): Record<string, unknown> | null\n setLocalStateField(field: string, value: unknown): void\n getStates(): Map<number, Record<string, unknown>>\n on(event: 'change', listener: (...args: unknown[]) => void): void\n off(event: 'change', listener: (...args: unknown[]) => void): void\n}\n\n/** How the people editing together see each other. */\nexport interface CollaborationUser {\n name: string\n /** The color of this user's outlines, any CSS color. Picked from the client id when left out. */\n color?: string\n}\n\nexport interface CollaborationOptions {\n /** Where the widgets live, e.g. `ydoc.getMap('widgets')`. */\n widgets: Y.Map<unknown>\n /** Shares which widget each person is at, and what they do there (`y-protocols/awareness`). */\n awareness?: AwarenessLike\n /** This user, shown to the others. Needs `awareness`. */\n user?: CollaborationUser\n}\n\nexport { collaborationColors }\nexport type { DashboardPeer, DashboardPresence }\n\ntype Shared = Y.Map<unknown>\ntype Item = Record<string, unknown>\n\n/** A widget's place among the others, kept beside its keys. */\nconst ORDER = '$order'\n/** The places by breakpoint, a map of their own, so places on two breakpoints don't overwrite each other. */\nconst PLACE = 'place'\n\n/** Whether two JSON values are the same, whatever the order of their keys. */\nconst same = sameValue\n\n/** Where in `value` something JSON can't carry sits, e.g. a component or a function. */\nfunction unshareable(value: unknown, path: string): string | null {\n if (value === null || ['string', 'number', 'boolean', 'undefined'].includes(typeof value))\n return null\n if (typeof value !== 'object') return path\n const proto = Object.getPrototypeOf(value)\n if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) return path\n for (const [key, item] of Object.entries(value)) {\n const found = unshareable(item, Array.isArray(value) ? `${path}[${key}]` : `${path}.${key}`)\n if (found) return found\n }\n return null\n}\n\nconst warned = new Set<string>()\n/** Others would get a broken copy of such a value while this dashboard shows it fine. */\nfunction warnUnshareable(id: string, key: string, value: unknown) {\n // the app's bundler replaces this, as for Vue's own warnings\n if (process.env.NODE_ENV === 'production') return\n const path = unshareable(value, key)\n if (!path || warned.has(`${id}:${path}`)) return\n warned.add(`${id}:${path}`)\n console.warn(\n `[@dou-ui/dashboard] \"${id}\" has ${path}, which can't be shared: only JSON values reach the others.`,\n )\n}\n\n/** Writes the places that changed into a widget's place map. */\nfunction writePlace(fields: Shared, place: DashboardWidget['place']) {\n const shared = fields.get(PLACE)\n if (!(shared instanceof Y.Map)) {\n const map = new Y.Map<unknown>()\n for (const [name, value] of Object.entries(place)) if (value) map.set(name, { ...value })\n fields.set(PLACE, map)\n return\n }\n for (const [name, value] of Object.entries(place))\n if (value && !same(shared.get(name), value)) shared.set(name, { ...value })\n for (const name of Array.from(shared.keys())) if (!place[name]) shared.delete(name)\n}\n\n/** Writes a widget's keys besides its order, only those that changed; `keys` limits which. */\nfunction writeWidget(map: Shared, widget: DashboardWidget, keys?: Set<string>) {\n const existing = map.get(widget.id)\n const item = widget as unknown as Item\n if (!(existing instanceof Y.Map)) {\n // a new map can't be read before it is in the document: fill it, then put it in\n const fields = new Y.Map<unknown>()\n for (const [key, value] of Object.entries(item)) {\n if (key === 'id' || value === undefined) continue\n if (key === PLACE) {\n const places = new Y.Map<unknown>()\n for (const [name, place] of Object.entries(value as DashboardWidget['place']))\n if (place) places.set(name, { ...place })\n fields.set(PLACE, places)\n continue\n }\n warnUnshareable(widget.id, key, value)\n fields.set(key, value)\n }\n map.set(widget.id, fields)\n return\n }\n for (const [key, value] of Object.entries(item)) {\n if (key === 'id' || value === undefined || (keys && !keys.has(key))) continue\n if (key === PLACE) writePlace(existing, value as DashboardWidget['place'])\n else if (!same(existing.get(key), value)) {\n warnUnshareable(widget.id, key, value)\n existing.set(key, value)\n }\n }\n for (const key of Array.from(existing.keys()))\n if (key[0] !== '$' && item[key] === undefined && (!keys || keys.has(key))) existing.delete(key)\n}\n\n/** Writes each widget's order key, giving new keys only where it must. */\nfunction writeOrder(map: Shared, widgets: readonly DashboardWidget[]) {\n const shared = widgets.map((widget) => {\n const fields = map.get(widget.id)\n return fields instanceof Y.Map ? fields : null\n })\n const keys = orderKeys(shared.map((fields) => (fields?.get(ORDER) as string | undefined) ?? null))\n shared.forEach((fields, index) => {\n if (fields && fields.get(ORDER) !== keys[index]) fields.set(ORDER, keys[index])\n })\n}\n\n/** Runs `write` as one transaction of the map's document, from `origin`. */\nfunction transact(map: Shared, write: () => void, origin: unknown) {\n if (map.doc) map.doc.transact(write, origin ?? null)\n else write()\n}\n\nexport interface FillMapOptions {\n /** The origin of the Yjs transaction, so the others can tell who wrote it. */\n origin?: unknown\n}\n\n/**\n * Writes a dashboard into an empty map, e.g. when a dashboard so far saved\n * as JSON starts being edited together. Do it once, where the shared\n * document is created; otherwise the first person to open the dashboard\n * brings theirs.\n */\nexport function fillMap(\n map: Y.Map<unknown>,\n document: DashboardDocument,\n options: FillMapOptions = {},\n) {\n const fill = () => {\n for (const widget of document.widgets) writeWidget(map, widget)\n writeOrder(map, document.widgets)\n }\n transact(map, fill, options.origin)\n}\n\n/** Writes the keys and places that differ between `before` and `after` into a widget's map. */\nfunction writeDifference(fields: Shared, before: DashboardWidget, after: DashboardWidget) {\n const a = before as unknown as Item\n const b = after as unknown as Item\n for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {\n if (key === 'id' || key[0] === '$') continue\n if (key === PLACE) {\n const from = before.place ?? {}\n const to = after.place ?? {}\n const found = fields.get(PLACE)\n let places = found instanceof Y.Map ? (found as Shared) : null\n for (const name of new Set([...Object.keys(from), ...Object.keys(to)])) {\n if (same(from[name], to[name])) continue\n if (!places) fields.set(PLACE, (places = new Y.Map<unknown>()))\n const place = to[name]\n if (place) places.set(name, { ...place })\n else places.delete(name)\n }\n } else if (!same(a[key], b[key])) {\n if (b[key] === undefined) fields.delete(key)\n else {\n warnUnshareable(after.id, key, b[key])\n fields.set(key, b[key])\n }\n }\n }\n}\n\n/**\n * Gives `placing` (widgets added or moved in `next`) order keys among the\n * widgets as they are ordered in the map now: right after the widget before\n * them in `next`; those before the first widget that stays go right before\n * it, and those after the last one go after all the others. Everyone else\n * keeps their key.\n */\nfunction placeOrder(map: Shared, next: readonly DashboardWidget[], placing: Set<string>) {\n if (!placing.size) return\n const list = readMap(map)\n .widgets.map((widget) => widget.id)\n .filter((id) => !placing.has(id))\n const listed = new Set(list)\n const stays = (id: string) => listed.has(id)\n let last = -1\n next.forEach((widget, index) => {\n if (stays(widget.id)) last = index\n })\n const leading: string[] = []\n const trailing: string[] = []\n const after = new Map<string, string[]>()\n let first: string | null = null\n let previous: string | null = null\n next.forEach((widget, index) => {\n if (stays(widget.id)) {\n first ??= widget.id\n previous = widget.id\n } else if (placing.has(widget.id)) {\n if (index > last) trailing.push(widget.id)\n else if (previous === null) leading.push(widget.id)\n else {\n const attached = after.get(previous)\n if (attached) attached.push(widget.id)\n else after.set(previous, [widget.id])\n }\n }\n })\n const ordered: string[] = []\n for (const id of list) {\n if (id === first) ordered.push(...leading)\n ordered.push(id, ...(after.get(id) ?? []))\n }\n ordered.push(...trailing)\n const shared = ordered.map((id) => map.get(id) as Shared)\n const keys = orderKeys(\n shared.map((fields, index) =>\n placing.has(ordered[index]!) ? null : ((fields.get(ORDER) as string | undefined) ?? null),\n ),\n )\n shared.forEach((fields, index) => {\n if (fields.get(ORDER) !== keys[index]) fields.set(ORDER, keys[index])\n })\n}\n\n/**\n * While developing: each widget `readMap` gave, as it was then, to tell a\n * widget of `base` changed in place from one others changed meanwhile.\n */\nconst asRead = new WeakMap<object, unknown>()\n\n/** The widgets of `next` that can be written: each id once, each with a type. */\nfunction writable(next: DashboardDocument, base: DashboardDocument | undefined) {\n const dev = process.env.NODE_ENV !== 'production'\n if (dev && base && (next === base || next.widgets === base.widgets))\n console.warn(\n '[@dou-ui/dashboard] updateMap got the same object as `next` and `base`, so nothing is written: change a copy of `base`, e.g. structuredClone(base).',\n )\n else if (dev && base) {\n // a widget of base that is no longer as `readMap` gave it was changed in place\n const kept = new Set<DashboardWidget>(base.widgets)\n for (const widget of next.widgets) {\n const snapshot = kept.has(widget) ? asRead.get(widget) : undefined\n if (!snapshot || same(snapshot, widget)) continue\n console.warn(\n `[@dou-ui/dashboard] updateMap got the widget \"${widget.id}\" of \\`base\\` itself in \\`next\\`, changed in place: the change isn't written. Change a copy of \\`base\\`, e.g. structuredClone(base).`,\n )\n break\n }\n }\n const seen = new Set<string>()\n return next.widgets.filter((widget) => {\n if (typeof widget.type !== 'string') {\n if (dev)\n console.warn(\n `[@dou-ui/dashboard] updateMap skips \"${widget.id}\": a widget needs a \\`type\\`.`,\n )\n return false\n }\n if (seen.has(widget.id)) {\n if (dev)\n console.warn(\n `[@dou-ui/dashboard] updateMap skips the second widget \"${widget.id}\": ids must be unique.`,\n )\n return false\n }\n seen.add(widget.id)\n return true\n })\n}\n\nexport interface UpdateMapOptions extends FillMapOptions {\n /**\n * The version `next` was made from, e.g. the one read with `readMap` and\n * given to a program that took a while to write `next`. Only what differs\n * between `base` and `next` is written: added and removed widgets, changed\n * keys, places on the breakpoints that changed, and the order of the\n * widgets that moved. What others changed meanwhile stays. Left out, the\n * map as it is now: then every widget not in `next` is removed.\n */\n base?: DashboardDocument\n}\n\n/**\n * Change a shared map from `options.base` to `next`, without a dashboard,\n * e.g. on the server when a program wrote a new version while people edit\n * the dashboard. Only what differs is written.\n */\nexport function updateMap(\n map: Y.Map<unknown>,\n next: DashboardDocument,\n options: UpdateMapOptions = {},\n) {\n // a map not in a document can't be read, so nothing could be merged\n if (!map.doc) throw new Error('[@dou-ui/dashboard] updateMap needs a map of a Y.Doc')\n const update = () => {\n const base = options.base ?? readMap(map)\n const widgets = writable(next, options.base)\n const before = new Map(base.widgets.map((widget) => [widget.id, widget]))\n const ids = new Set(next.widgets.map((widget) => widget.id))\n for (const id of before.keys()) if (!ids.has(id)) map.delete(id)\n\n // the widgets both have, in `base`'s order: those out of it in `next` moved\n const index = new Map(base.widgets.map((widget, i) => [widget.id, i]))\n const common = widgets.filter((widget) => index.has(widget.id))\n const kept = keptIndexes(common.map((widget) => String(index.get(widget.id)).padStart(10, '0')))\n const placing = new Set(common.filter((_, i) => !kept.has(i)).map((widget) => widget.id))\n\n for (const widget of widgets) {\n const old = before.get(widget.id)\n const fields = map.get(widget.id)\n if (!old) {\n writeWidget(map, widget)\n placing.add(widget.id)\n } else if (fields instanceof Y.Map) writeDifference(fields, old, widget)\n // removed meanwhile by someone else: it stays removed\n else placing.delete(widget.id)\n }\n placeOrder(map, widgets, placing)\n }\n transact(map, update, options.origin)\n}\n\n/** The dashboard the map holds: its widgets by their order keys (then ids, the same for everyone). */\nexport function readMap(map: Y.Map<unknown>): DashboardDocument {\n const list: { widget: DashboardWidget; order: string }[] = []\n map.forEach((value, id) => {\n if (!(value instanceof Y.Map)) return\n const { [ORDER]: order, ...rest } = value.toJSON() as Item\n if (typeof rest.type !== 'string') return\n const place = rest[PLACE]\n list.push({\n widget: {\n ...rest,\n id,\n place: place && typeof place === 'object' ? place : {},\n } as DashboardWidget,\n order: typeof order === 'string' ? order : '',\n })\n })\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts the list built here\n list.sort((a, b) =>\n a.order < b.order ? -1 : a.order > b.order ? 1 : a.widget.id < b.widget.id ? -1 : 1,\n )\n const widgets = list.map((entry) => entry.widget)\n if (process.env.NODE_ENV !== 'production')\n for (const widget of widgets) asRead.set(widget, structuredClone(widget))\n return { version: 1, widgets }\n}\n\n/** The widgets and keys a transaction changed, written to the map. */\nfunction writeChanges(map: Shared, tr: DashboardTransaction) {\n const after = new Map(tr.doc.widgets.map((widget) => [widget.id, widget]))\n const touched = new Map<string, Set<string> | true>()\n let added = false\n let removed = false\n for (const step of tr.steps) {\n if (step.type === 'add') {\n touched.set(step.widget.id, true)\n added = true\n } else if (step.type === 'remove') {\n removed = true\n touched.delete(step.id)\n } else {\n const current = touched.get(step.id)\n if (current === true) continue\n const keys = current ?? new Set<string>()\n for (const key of Object.keys(step.patch)) keys.add(key)\n touched.set(step.id, keys)\n }\n }\n if (removed)\n for (const widget of tr.before.widgets) if (!after.has(widget.id)) map.delete(widget.id)\n for (const [id, keys] of touched) {\n const widget = after.get(id)\n if (!widget) continue\n // a widget removed and added again in one change is written anew\n if (keys === true && map.get(id) instanceof Y.Map && removed) map.delete(id)\n writeWidget(map, widget, keys === true ? undefined : keys)\n }\n if (added) writeOrder(map, tr.doc.widgets)\n}\n\nconst NO_PEERS: readonly DashboardPeer[] = []\n\n/**\n * Edit a dashboard together through a Yjs document: pass the result to\n * `DouDashboard` as `collaboration`. Each widget lives in `widgets` as its\n * own `Y.Map`, each key on its own and each breakpoint's place on its own,\n * so two people changing different widgets, or different settings of one,\n * both keep their change. When two people move widgets at once, everyone\n * lays the places out the same way, so the dashboards agree. While a widget\n * is dragged, changes from others wait until it is let go. The dashboard's\n * `v-model` only mirrors the shared document: a document set through\n * `v-model` from outside is not written back. Undo only takes back this\n * user's own changes. With `awareness`, each person sees which widget the\n * others are at, outlined in their colors, and whether they are moving,\n * resizing or changing its settings.\n */\nexport function collaboration(options: CollaborationOptions): DashboardCollaboration {\n const { widgets: map, awareness, user } = options\n const ydoc = map.doc\n if (!ydoc) throw new Error('[@dou-ui/dashboard] widgets must be a map of a Y.Doc')\n if (awareness && user) {\n const color = user.color ?? collaborationColors[ydoc.clientID % collaborationColors.length]\n awareness.setLocalStateField('user', { name: user.name, color })\n }\n\n /** This dashboard's own changes, which undo can take back. */\n const tracked = { dashboard: 'tracked' }\n /** Changes undo leaves alone, e.g. filling the map. */\n const untracked = { dashboard: 'untracked' }\n const undoManager = new Y.UndoManager([map], {\n trackedOrigins: new Set([tracked]),\n captureTimeout: 500,\n })\n /** Bumped when the undo stacks change, so `canUndo` and `canRedo` update. */\n const stacks = shallowRef(0)\n const bump = () => stacks.value++\n undoManager.on('stack-item-added', bump)\n undoManager.on('stack-item-popped', bump)\n undoManager.on('stack-cleared', bump)\n\n let host: DashboardCollaborationHost | undefined\n /** What undo or redo is running, to name the change. */\n let travelling: 'undo' | 'redo' | null = null\n let lastGroup: string | undefined\n\n /** Brings the dashboard in line with the map. */\n function pull() {\n host?.apply(readMap(map), travelling ?? 'remote')\n }\n\n function run(action: 'undo' | 'redo') {\n const stack = action === 'undo' ? undoManager.undoStack : undoManager.redoStack\n if (!stack.length) return false\n travelling = action\n try {\n undoManager[action]()\n } finally {\n travelling = null\n }\n return true\n }\n\n /** The others at each widget. */\n const peersByWidget = shallowRef(new Map<string, DashboardPeer[]>())\n function readPeers() {\n if (!awareness) return\n const next = new Map<string, DashboardPeer[]>()\n awareness.getStates().forEach((state, client) => {\n if (client === awareness.clientID) return\n const who = state.user as { name?: string; color?: string } | undefined\n const presence = state.dashboard as DashboardPresence | null | undefined\n if (!who || !presence?.widget) return\n const peer: DashboardPeer = {\n client,\n name: who.name ?? '',\n color: who.color ?? 'currentColor',\n action: presence.action,\n }\n const list = next.get(presence.widget)\n if (list) list.push(peer)\n else next.set(presence.widget, [peer])\n })\n peersByWidget.value = next\n }\n\n return {\n setup(dashboard) {\n host = dashboard\n // the first one to open the dashboard brings its widgets; everyone else reads the map\n if (!map.size) ydoc.transact(() => fillMap(map, dashboard.document()), untracked)\n pull()\n\n // changes from others, and from undo: applied once per Yjs transaction\n let dirty = false\n const observe = (_events: unknown, transaction: Y.Transaction) => {\n if (transaction.origin !== tracked && transaction.origin !== untracked) dirty = true\n }\n const flush = () => {\n if (!dirty) return\n dirty = false\n pull()\n }\n map.observeDeep(observe)\n ydoc.on('afterTransaction', flush)\n if (awareness) {\n readPeers()\n awareness.on('change', readPeers)\n }\n return () => {\n map.unobserveDeep(observe)\n ydoc.off('afterTransaction', flush)\n if (awareness) awareness.off('change', readPeers)\n host = undefined\n }\n },\n transaction(tr) {\n const tracking = tr.meta.history !== false\n // like the dashboard's own history: only changes of one group undo together\n if (tracking && (!tr.meta.group || tr.meta.group !== lastGroup)) undoManager.stopCapturing()\n if (tracking) lastGroup = tr.meta.group\n ydoc.transact(() => writeChanges(map, tr), tracking ? tracked : untracked)\n },\n sync: pull,\n undo: () => run('undo'),\n redo: () => run('redo'),\n canUndo: () => (stacks.value, undoManager.undoStack.length > 0),\n canRedo: () => (stacks.value, undoManager.redoStack.length > 0),\n presence: awareness\n ? (presence) => awareness.setL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,KAAA;EACJ,OAAO,aAAa,OAAO,cAAc,MAAM,IAAI,EAAE,KAAK,WAAW,KAAA;CACvE;AACF"}
@@ -32,7 +32,8 @@ function shapeProblems(value, lists) {
32
32
  /**
33
33
  * The problems of a dashboard document, before it is saved or shown: an
34
34
  * unknown version, widgets without an id or sharing one, types nobody
35
- * registered, and places that are not whole cells.
35
+ * registered, places that are not whole cells, and `comments` that are
36
+ * not a list of thread ids.
36
37
  */
37
38
  function checkDocument(document, options = {}) {
38
39
  const shape = shapeProblems(document, ["widgets"]);
@@ -76,6 +77,14 @@ function checkDocument(document, options = {}) {
76
77
  text: name,
77
78
  message: `The place of "${widget.id}" on "${name}" is not whole cells`
78
79
  });
80
+ const notes = widget.comments;
81
+ if (notes !== void 0 && !(Array.isArray(notes) && notes.every((id) => typeof id === "string"))) problems.push({
82
+ code: "bad-comments",
83
+ widgetId: widget.id,
84
+ path: `${path}.comments`,
85
+ text: widget.id,
86
+ message: `The comments of "${widget.id}" are not a list of thread ids`
87
+ });
79
88
  });
80
89
  return problems;
81
90
  }
@@ -1 +1 @@
1
- {"version":3,"file":"document.js","names":[],"sources":["../../src/core/document.ts"],"sourcesContent":["import type { DashboardWidgetType } from '../widget/define'\nimport type { DashboardDocument, DashboardPlace, DashboardWidget } from './types'\n\n/** A dashboard with no widgets, the `v-model` when none is bound. */\nexport const emptyDocument = (): DashboardDocument => ({ version: 1, widgets: [] })\n\nexport interface DocumentProblem {\n code: 'version' | 'shape' | 'duplicate-id' | 'missing-id' | 'unknown-type' | 'bad-place'\n /** The widget at fault; none for the document's own problems. */\n widgetId?: string\n /** Where the problem is, e.g. `widgets[2]` or `widgets[2].place.lg`; `version` for the version. */\n path: string\n /** The id, type or breakpoint at fault, for the editor's message. */\n text: string\n /** An English description, for logs. */\n message: string\n}\n\nexport interface CheckDocumentOptions {\n /** The registered widget types; without them, types are not checked. */\n widgets?: readonly DashboardWidgetType<any>[]\n}\n\nconst isCount = (value: unknown, min: number) =>\n typeof value === 'number' && Number.isInteger(value) && value >= min\n\n/** Whether `value` is a place on a grid: whole numbers, the size at least 1. */\nexport function isDashboardPlace(value: unknown): value is DashboardPlace {\n if (!value || typeof value !== 'object') return false\n const place = value as Record<string, unknown>\n return isCount(place.x, 0) && isCount(place.y, 0) && isCount(place.w, 1) && isCount(place.h, 1)\n}\n\n/**\n * What is wrong with the shape itself: the document is not an object, or a\n * list in it is not an array. Nothing else can be checked until it is fixed.\n */\nfunction shapeProblems(value: unknown, lists: string[]): DocumentProblem[] {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n return [{ code: 'shape', path: '', text: '', message: 'The document is not an object' }]\n return lists\n .filter((key) => !Array.isArray((value as Record<string, unknown>)[key]))\n .map((key) => ({ code: 'shape', path: key, text: '', message: `\"${key}\" is not a list` }))\n}\n\n/**\n * The problems of a dashboard document, before it is saved or shown: an\n * unknown version, widgets without an id or sharing one, types nobody\n * registered, and places that are not whole cells.\n */\nexport function checkDocument(\n document: DashboardDocument,\n options: CheckDocumentOptions = {},\n): DocumentProblem[] {\n const shape = shapeProblems(document, ['widgets'])\n if (shape.length) return shape\n const problems: DocumentProblem[] = []\n if (document.version !== 1)\n problems.push({\n code: 'version',\n path: 'version',\n text: String(document.version),\n message: `Version ${String(document.version)} is not known`,\n })\n const types = options.widgets && new Set(options.widgets.map((type) => type.type))\n const ids = new Set<string>()\n document.widgets.forEach((widget, i) => {\n const path = `widgets[${i}]`\n if (!widget.id) {\n problems.push({ code: 'missing-id', path, text: '', message: `${path} has no id` })\n } else if (ids.has(widget.id)) {\n problems.push({\n code: 'duplicate-id',\n widgetId: widget.id,\n path,\n text: widget.id,\n message: `The id \"${widget.id}\" is used more than once`,\n })\n }\n ids.add(widget.id)\n if (types && !types.has(widget.type))\n problems.push({\n code: 'unknown-type',\n widgetId: widget.id,\n path,\n text: widget.type,\n message: `No widget type \"${widget.type}\" is registered`,\n })\n for (const [name, place] of Object.entries(widget.place ?? {}))\n if (place !== undefined && !isDashboardPlace(place))\n problems.push({\n code: 'bad-place',\n widgetId: widget.id,\n path: `${path}.place.${name}`,\n text: name,\n message: `The place of \"${widget.id}\" on \"${name}\" is not whole cells`,\n })\n })\n return problems\n}\n\n/** The saved data as an object of version 1, or an error saying why it can't be. */\nfunction sourceOf(input: unknown): Record<string, unknown> {\n if (!input || typeof input !== 'object' || Array.isArray(input))\n throw new Error(\n `[@dou-ui/dashboard] a dashboard document must be an object, not ${Array.isArray(input) ? 'an array' : (JSON.stringify(input) ?? String(input))}`,\n )\n const source = input as Record<string, unknown>\n const version = source.version ?? 1\n if (version !== 1)\n throw new Error(\n `[@dou-ui/dashboard] unknown document version ${JSON.stringify(version) ?? String(version)} (expected 1); data saved by a newer @dou-ui/dashboard needs that version to open`,\n )\n return source\n}\n\n/**\n * Brings a saved document up to the current version, and fills what an\n * older or hand-written one may lack (`version`, `place`). Widgets that are\n * not objects and places that are not whole cells are dropped; anything\n * else is kept as it is. Throws for data that is not an object\n * (an array, `null`, a string) and for a version it does not know.\n */\nexport function migrateDocument(input: unknown): DashboardDocument {\n const source = sourceOf(input)\n const list = Array.isArray(source.widgets) ? source.widgets : []\n const widgets: DashboardWidget[] = []\n for (const value of list) {\n if (!value || typeof value !== 'object') continue\n const widget = value as Record<string, unknown>\n const place: DashboardWidget['place'] = {}\n if (widget.place && typeof widget.place === 'object')\n for (const [name, entry] of Object.entries(widget.place))\n if (isDashboardPlace(entry))\n place[name] = { x: entry.x, y: entry.y, w: entry.w, h: entry.h }\n widgets.push({\n ...widget,\n id: String(widget.id ?? ''),\n type: String(widget.type ?? ''),\n place,\n } as DashboardWidget)\n }\n return { ...source, version: 1, widgets } as DashboardDocument\n}\n"],"mappings":";;AAIA,IAAa,uBAA0C;CAAE,SAAS;CAAG,SAAS,CAAC;AAAE;AAmBjF,IAAM,WAAW,OAAgB,QAC/B,OAAO,UAAU,YAAY,OAAO,UAAU,KAAK,KAAK,SAAS;;AAGnE,SAAgB,iBAAiB,OAAyC;CACxE,IAAI,CAAC,SAAS,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AC,MAAM,UAAU,OAAO,QAAQ,OAAO,KAAK,GACrD,IAAI,iBAAiB,KAAK,GACxB,MAAM,QAAQ;IAAE,GAAG,MAAM;IAAG,GAAG,MAAM;IAAG,GAAG,MAAM;IAAG,GAAG,MAAM;GAAE;EAAA;EACrE,QAAQ,KAAK;GACX,GAAG;GACH,IAAI,OAAO,OAAO,MAAM,EAAE;GAC1B,MAAM,OAAO,OAAO,QAAQ,EAAE;GAC9B;EACF,CAAoB;CACtB;CACA,OAAO;EAAE,GAAG;EAAQ,SAAS;EAAG;CAAQ;AAC1C"}
1
+ {"version":3,"file":"document.js","names":[],"sources":["../../src/core/document.ts"],"sourcesContent":["import type { DashboardWidgetType } from '../widget/define'\nimport type { DashboardDocument, DashboardPlace, DashboardWidget } from './types'\n\n/** A dashboard with no widgets, the `v-model` when none is bound. */\nexport const emptyDocument = (): DashboardDocument => ({ version: 1, widgets: [] })\n\nexport interface DocumentProblem {\n code:\n | 'version'\n | 'shape'\n | 'duplicate-id'\n | 'missing-id'\n | 'unknown-type'\n | 'bad-place'\n | 'bad-comments'\n /** The widget at fault; none for the document's own problems. */\n widgetId?: string\n /** Where the problem is, e.g. `widgets[2]` or `widgets[2].place.lg`; `version` for the version. */\n path: string\n /** The id, type or breakpoint at fault, for the editor's message. */\n text: string\n /** An English description, for logs. */\n message: string\n}\n\nexport interface CheckDocumentOptions {\n /** The registered widget types; without them, types are not checked. */\n widgets?: readonly DashboardWidgetType<any>[]\n}\n\nconst isCount = (value: unknown, min: number) =>\n typeof value === 'number' && Number.isInteger(value) && value >= min\n\n/** Whether `value` is a place on a grid: whole numbers, the size at least 1. */\nexport function isDashboardPlace(value: unknown): value is DashboardPlace {\n if (!value || typeof value !== 'object') return false\n const place = value as Record<string, unknown>\n return isCount(place.x, 0) && isCount(place.y, 0) && isCount(place.w, 1) && isCount(place.h, 1)\n}\n\n/**\n * What is wrong with the shape itself: the document is not an object, or a\n * list in it is not an array. Nothing else can be checked until it is fixed.\n */\nfunction shapeProblems(value: unknown, lists: string[]): DocumentProblem[] {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n return [{ code: 'shape', path: '', text: '', message: 'The document is not an object' }]\n return lists\n .filter((key) => !Array.isArray((value as Record<string, unknown>)[key]))\n .map((key) => ({ code: 'shape', path: key, text: '', message: `\"${key}\" is not a list` }))\n}\n\n/**\n * The problems of a dashboard document, before it is saved or shown: an\n * unknown version, widgets without an id or sharing one, types nobody\n * registered, places that are not whole cells, and `comments` that are\n * not a list of thread ids.\n */\nexport function checkDocument(\n document: DashboardDocument,\n options: CheckDocumentOptions = {},\n): DocumentProblem[] {\n const shape = shapeProblems(document, ['widgets'])\n if (shape.length) return shape\n const problems: DocumentProblem[] = []\n if (document.version !== 1)\n problems.push({\n code: 'version',\n path: 'version',\n text: String(document.version),\n message: `Version ${String(document.version)} is not known`,\n })\n const types = options.widgets && new Set(options.widgets.map((type) => type.type))\n const ids = new Set<string>()\n document.widgets.forEach((widget, i) => {\n const path = `widgets[${i}]`\n if (!widget.id) {\n problems.push({ code: 'missing-id', path, text: '', message: `${path} has no id` })\n } else if (ids.has(widget.id)) {\n problems.push({\n code: 'duplicate-id',\n widgetId: widget.id,\n path,\n text: widget.id,\n message: `The id \"${widget.id}\" is used more than once`,\n })\n }\n ids.add(widget.id)\n if (types && !types.has(widget.type))\n problems.push({\n code: 'unknown-type',\n widgetId: widget.id,\n path,\n text: widget.type,\n message: `No widget type \"${widget.type}\" is registered`,\n })\n for (const [name, place] of Object.entries(widget.place ?? {}))\n if (place !== undefined && !isDashboardPlace(place))\n problems.push({\n code: 'bad-place',\n widgetId: widget.id,\n path: `${path}.place.${name}`,\n text: name,\n message: `The place of \"${widget.id}\" on \"${name}\" is not whole cells`,\n })\n const notes: unknown = widget.comments\n if (\n notes !== undefined &&\n !(Array.isArray(notes) && notes.every((id) => typeof id === 'string'))\n )\n problems.push({\n code: 'bad-comments',\n widgetId: widget.id,\n path: `${path}.comments`,\n text: widget.id,\n message: `The comments of \"${widget.id}\" are not a list of thread ids`,\n })\n })\n return problems\n}\n\n/** The saved data as an object of version 1, or an error saying why it can't be. */\nfunction sourceOf(input: unknown): Record<string, unknown> {\n if (!input || typeof input !== 'object' || Array.isArray(input))\n throw new Error(\n `[@dou-ui/dashboard] a dashboard document must be an object, not ${Array.isArray(input) ? 'an array' : (JSON.stringify(input) ?? String(input))}`,\n )\n const source = input as Record<string, unknown>\n const version = source.version ?? 1\n if (version !== 1)\n throw new Error(\n `[@dou-ui/dashboard] unknown document version ${JSON.stringify(version) ?? String(version)} (expected 1); data saved by a newer @dou-ui/dashboard needs that version to open`,\n )\n return source\n}\n\n/**\n * Brings a saved document up to the current version, and fills what an\n * older or hand-written one may lack (`version`, `place`). Widgets that are\n * not objects and places that are not whole cells are dropped; anything\n * else is kept as it is. Throws for data that is not an object\n * (an array, `null`, a string) and for a version it does not know.\n */\nexport function migrateDocument(input: unknown): DashboardDocument {\n const source = sourceOf(input)\n const list = Array.isArray(source.widgets) ? source.widgets : []\n const widgets: DashboardWidget[] = []\n for (const value of list) {\n if (!value || typeof value !== 'object') continue\n const widget = value as Record<string, unknown>\n const place: DashboardWidget['place'] = {}\n if (widget.place && typeof widget.place === 'object')\n for (const [name, entry] of Object.entries(widget.place))\n if (isDashboardPlace(entry))\n place[name] = { x: entry.x, y: entry.y, w: entry.w, h: entry.h }\n widgets.push({\n ...widget,\n id: String(widget.id ?? ''),\n type: String(widget.type ?? ''),\n place,\n } as DashboardWidget)\n }\n return { ...source, version: 1, widgets } as DashboardDocument\n}\n"],"mappings":";;AAIA,IAAa,uBAA0C;CAAE,SAAS;CAAG,SAAS,CAAC;AAAE;AA0BjF,IAAM,WAAW,OAAgB,QAC/B,OAAO,UAAU,YAAY,OAAO,UAAU,KAAK,KAAK,SAAS;;AAGnE,SAAgB,iBAAiB,OAAyC;CACxE,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,MAAM,QAAQ;CACd,OAAO,QAAQ,MAAM,GAAG,CAAC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CACpC,KAAK,MAAM,SAAS,MAAM;EACxB,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU;EACzC,MAAM,SAAS;EACf,MAAM,QAAkC,CAAC;EACzC,IAAI,OAAO,SAAS,OAAO,OAAO,UAAU,UACrC;QAAA,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,OAAO,KAAK,GACrD,IAAI,iBAAiB,KAAK,GACxB,MAAM,QAAQ;IAAE,GAAG,MAAM;IAAG,GAAG,MAAM;IAAG,GAAG,MAAM;IAAG,GAAG,MAAM;GAAE;EAAA;EACrE,QAAQ,KAAK;GACX,GAAG;GACH,IAAI,OAAO,OAAO,MAAM,EAAE;GAC1B,MAAM,OAAO,OAAO,QAAQ,EAAE;GAC9B;EACF,CAAoB;CACtB;CACA,OAAO;EAAE,GAAG;EAAQ,SAAS;EAAG;CAAQ;AAC1C"}
@@ -56,11 +56,34 @@ var DashboardHistory = class {
56
56
  origin: "redo"
57
57
  });
58
58
  }
59
+ /**
60
+ * Gives a change kept out of undo to the widget as undo and redo bring it
61
+ * back, too: comments started on a widget stay on it when its adding is
62
+ * undone and redone.
63
+ */
64
+ carry(id, patch) {
65
+ const fix = (steps) => steps.map((step) => step.type === "add" && step.widget.id === id ? {
66
+ ...step,
67
+ widget: withPatch(step.widget, patch)
68
+ } : step);
69
+ for (const entry of [...this.done, ...this.undone]) {
70
+ entry.steps = fix(entry.steps);
71
+ entry.inverse = fix(entry.inverse);
72
+ }
73
+ }
59
74
  clear() {
60
75
  this.done = [];
61
76
  this.undone = [];
62
77
  }
63
78
  };
79
+ function withPatch(widget, patch) {
80
+ const next = {
81
+ ...widget,
82
+ ...patch
83
+ };
84
+ for (const [key, value] of Object.entries(patch)) if (value === void 0) delete next[key];
85
+ return next;
86
+ }
64
87
  export { DashboardHistory };
65
88
 
66
89
  //# sourceMappingURL=history.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"history.js","names":[],"sources":["../../src/core/history.ts"],"sourcesContent":["import { applySteps } from './transaction'\nimport type { DashboardStep, DashboardTransaction } from './transaction'\nimport type { DashboardDocument } from './types'\n\ninterface Entry {\n steps: DashboardStep[]\n inverse: DashboardStep[]\n group?: string\n time: number\n}\n\n/** Transactions of one group merge when they come within this many ms. */\nconst GROUP_WINDOW = 1000\n\n/** Undo and redo of a dashboard: the steps of each transaction and the steps that undo them. */\nexport class DashboardHistory {\n private done: Entry[] = []\n private undone: Entry[] = []\n\n constructor(private depth = 200) {}\n\n get canUndo() {\n return this.done.length > 0\n }\n\n get canRedo() {\n return this.undone.length > 0\n }\n\n record(tr: DashboardTransaction, now = Date.now()) {\n if (!tr.changed || tr.meta.history === false) return\n this.undone = []\n const last = this.done[this.done.length - 1]\n const group = tr.meta.group\n if (last && group && last.group === group && now - last.time < GROUP_WINDOW) {\n last.steps = [...last.steps, ...tr.steps]\n last.inverse = [...tr.inverse, ...last.inverse]\n last.time = now\n return\n }\n this.done.push({ steps: tr.steps.slice(), inverse: tr.inverse.slice(), group, time: now })\n if (this.done.length > this.depth) this.done.shift()\n }\n\n undo(document: DashboardDocument) {\n const entry = this.done.pop()\n if (!entry) return null\n this.undone.push(entry)\n return applySteps(document, entry.inverse, { history: false, origin: 'undo' })\n }\n\n redo(document: DashboardDocument) {\n const entry = this.undone.pop()\n if (!entry) return null\n this.done.push({ ...entry, group: undefined })\n return applySteps(document, entry.steps, { history: false, origin: 'redo' })\n }\n\n clear() {\n this.done = []\n this.undone = []\n }\n}\n"],"mappings":";;;AAYA,IAAM,eAAe;;AAGrB,IAAa,mBAAb,MAA8B;CAIR;CAHpB,OAAwB,CAAC;CACzB,SAA0B,CAAC;CAE3B,YAAY,QAAgB,KAAK;EAAb,KAAA,QAAA;CAAc;CAElC,IAAI,UAAU;EACZ,OAAO,KAAK,KAAK,SAAS;CAC5B;CAEA,IAAI,UAAU;EACZ,OAAO,KAAK,OAAO,SAAS;CAC9B;CAEA,OAAO,IAA0B,MAAM,KAAK,IAAI,GAAG;EACjD,IAAI,CAAC,GAAG,WAAW,GAAG,KAAK,YAAY,OAAO;EAC9C,KAAK,SAAS,CAAC;EACf,MAAM,OAAO,KAAK,KAAK,KAAK,KAAK,SAAS;EAC1C,MAAM,QAAQ,GAAG,KAAK;EACtB,IAAI,QAAQ,SAAS,KAAK,UAAU,SAAS,MAAM,KAAK,OAAO,cAAc;GAC3E,KAAK,QAAQ,CAAC,GAAG,KAAK,OAAO,GAAG,GAAG,KAAK;GACxC,KAAK,UAAU,CAAC,GAAG,GAAG,SAAS,GAAG,KAAK,OAAO;GAC9C,KAAK,OAAO;GACZ;EACF;EACA,KAAK,KAAK,KAAK;GAAE,OAAO,GAAG,MAAM,MAAM;GAAG,SAAS,GAAG,QAAQ,MAAM;GAAG;GAAO,MAAM;EAAI,CAAC;EACzF,IAAI,KAAK,KAAK,SAAS,KAAK,OAAO,KAAK,KAAK,MAAM;CACrD;CAEA,KAAK,UAA6B;EAChC,MAAM,QAAQ,KAAK,KAAK,IAAI;EAC5B,IAAI,CAAC,OAAO,OAAO;EACnB,KAAK,OAAO,KAAK,KAAK;EACtB,OAAO,WAAW,UAAU,MAAM,SAAS;GAAE,SAAS;GAAO,QAAQ;EAAO,CAAC;CAC/E;CAEA,KAAK,UAA6B;EAChC,MAAM,QAAQ,KAAK,OAAO,IAAI;EAC9B,IAAI,CAAC,OAAO,OAAO;EACnB,KAAK,KAAK,KAAK;GAAE,GAAG;GAAO,OAAO,KAAA;EAAU,CAAC;EAC7C,OAAO,WAAW,UAAU,MAAM,OAAO;GAAE,SAAS;GAAO,QAAQ;EAAO,CAAC;CAC7E;CAEA,QAAQ;EACN,KAAK,OAAO,CAAC;EACb,KAAK,SAAS,CAAC;CACjB;AACF"}
1
+ {"version":3,"file":"history.js","names":[],"sources":["../../src/core/history.ts"],"sourcesContent":["import { applySteps } from './transaction'\nimport type { DashboardStep, DashboardTransaction } from './transaction'\nimport type { DashboardDocument, DashboardWidget } from './types'\n\ninterface Entry {\n steps: DashboardStep[]\n inverse: DashboardStep[]\n group?: string\n time: number\n}\n\n/** Transactions of one group merge when they come within this many ms. */\nconst GROUP_WINDOW = 1000\n\n/** Undo and redo of a dashboard: the steps of each transaction and the steps that undo them. */\nexport class DashboardHistory {\n private done: Entry[] = []\n private undone: Entry[] = []\n\n constructor(private depth = 200) {}\n\n get canUndo() {\n return this.done.length > 0\n }\n\n get canRedo() {\n return this.undone.length > 0\n }\n\n record(tr: DashboardTransaction, now = Date.now()) {\n if (!tr.changed || tr.meta.history === false) return\n this.undone = []\n const last = this.done[this.done.length - 1]\n const group = tr.meta.group\n if (last && group && last.group === group && now - last.time < GROUP_WINDOW) {\n last.steps = [...last.steps, ...tr.steps]\n last.inverse = [...tr.inverse, ...last.inverse]\n last.time = now\n return\n }\n this.done.push({ steps: tr.steps.slice(), inverse: tr.inverse.slice(), group, time: now })\n if (this.done.length > this.depth) this.done.shift()\n }\n\n undo(document: DashboardDocument) {\n const entry = this.done.pop()\n if (!entry) return null\n this.undone.push(entry)\n return applySteps(document, entry.inverse, { history: false, origin: 'undo' })\n }\n\n redo(document: DashboardDocument) {\n const entry = this.undone.pop()\n if (!entry) return null\n this.done.push({ ...entry, group: undefined })\n return applySteps(document, entry.steps, { history: false, origin: 'redo' })\n }\n\n /**\n * Gives a change kept out of undo to the widget as undo and redo bring it\n * back, too: comments started on a widget stay on it when its adding is\n * undone and redone.\n */\n carry(id: string, patch: Partial<DashboardWidget>) {\n const fix = (steps: DashboardStep[]) =>\n steps.map((step) =>\n step.type === 'add' && step.widget.id === id\n ? { ...step, widget: withPatch(step.widget, patch) }\n : step,\n )\n for (const entry of [...this.done, ...this.undone]) {\n entry.steps = fix(entry.steps)\n entry.inverse = fix(entry.inverse)\n }\n }\n\n clear() {\n this.done = []\n this.undone = []\n }\n}\n\nfunction withPatch(widget: DashboardWidget, patch: Partial<DashboardWidget>): DashboardWidget {\n const next = { ...widget, ...patch }\n for (const [key, value] of Object.entries(patch))\n if (value === undefined) delete (next as Record<string, unknown>)[key]\n return next\n}\n"],"mappings":";;;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U,MAAM,OAAO;GAAE,SAAS;GAAO,QAAQ;EAAO,CAAC;CAC7E;;;;;;CAOA,MAAM,IAAY,OAAiC;EACjD,MAAM,OAAO,UACX,MAAM,KAAK,SACT,KAAK,SAAS,SAAS,KAAK,OAAO,OAAO,KACtC;GAAE,GAAG;GAAM,QAAQ,UAAU,KAAK,QAAQ,KAAK;EAAE,IACjD,IACN;EACF,KAAK,MAAM,SAAS,CAAC,GAAG,KAAK,MAAM,GAAG,KAAK,MAAM,GAAG;GAClD,MAAM,QAAQ,IAAI,MAAM,KAAK;GAC7B,MAAM,UAAU,IAAI,MAAM,OAAO;EACnC;CACF;CAEA,QAAQ;EACN,KAAK,OAAO,CAAC;EACb,KAAK,SAAS,CAAC;CACjB;AACF;AAEA,SAAS,UAAU,QAAyB,OAAkD;CAC5F,MAAM,OAAO;EAAE,GAAG;EAAQ,GAAG;CAAM;CACnC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAK,GAC7C,IAAI,UAAU,KAAA,GAAW,OAAQ,KAAiC;CACpE,OAAO;AACT"}
@@ -1,12 +1,15 @@
1
1
  // src/core/transaction.ts
2
2
  var PROTECTED = /* @__PURE__ */ new Set(["id", "type"]);
3
- /** Deep equality of JSON values; key order doesn't matter. */
3
+ /** The keys JSON keeps: those whose value isn't `undefined`. */
4
+ var jsonKeys = (value) => Object.keys(value).filter((key) => value[key] !== void 0);
5
+ /** Deep equality of JSON values; key order and keys set to `undefined` don't matter. */
4
6
  function sameValue(a, b) {
5
7
  if (a === b) return true;
6
8
  if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
7
9
  if (Array.isArray(a) !== Array.isArray(b)) return false;
8
- const keys = Object.keys(a);
9
- if (keys.length !== Object.keys(b).length) return false;
10
+ if (Array.isArray(a)) return a.length === b.length && a.every((item, i) => sameValue(item, b[i]));
11
+ const keys = jsonKeys(a);
12
+ if (keys.length !== jsonKeys(b).length) return false;
10
13
  return keys.every((key) => sameValue(a[key], b[key]));
11
14
  }
12
15
  /** Applies one step: the new document and the step that undoes it, or `null` when it changes nothing. */
@@ -192,8 +195,14 @@ function longestRun(values) {
192
195
  * that are gone are removed, new ones added, changed keys updated, and the
193
196
  * fewest widgets taken out and put back to match the order. Unchanged
194
197
  * widgets keep their objects.
198
+ *
199
+ * A widget that stays keeps its `comments`, the discussions on it, as they
200
+ * are: restoring a default layout doesn't take them off. Pass
201
+ * `{ keepComments: false }` for the exact steps, e.g. to apply a shared
202
+ * document.
195
203
  */
196
- function replaceWidgets(tr, next) {
204
+ function replaceWidgets(tr, next, options = {}) {
205
+ const keep = options.keepComments !== false;
197
206
  const wanted = new Map(next.widgets.map((widget, index) => [widget.id, index]));
198
207
  for (const widget of tr.doc.widgets) {
199
208
  const index = wanted.get(widget.id);
@@ -208,7 +217,7 @@ function replaceWidgets(tr, next) {
208
217
  const patch = {};
209
218
  const old = there;
210
219
  const item = widget;
211
- for (const key of /* @__PURE__ */ new Set([...Object.keys(old), ...Object.keys(item)])) if (!PROTECTED.has(key)) patch[key] = item[key];
220
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(old), ...Object.keys(item)])) if (!PROTECTED.has(key) && !(keep && key === "comments")) patch[key] = item[key];
212
221
  tr.update(widget.id, patch);
213
222
  });
214
223
  return tr;
@@ -1 +1 @@
1
- {"version":3,"file":"transaction.js","names":[],"sources":["../../src/core/transaction.ts"],"sourcesContent":["import type { DashboardDocument, DashboardWidget } from './types'\n\n/**\n * Keys of a widget to set; `undefined` removes the key. `id` and `type`\n * cannot be set: remove the widget and add another instead.\n */\nexport type DashboardWidgetPatch = { [key: string]: unknown } & {\n id?: never\n type?: never\n}\n\n/** One change to a dashboard. `index` is where in `widgets` an added widget goes. */\nexport type DashboardStep =\n | { type: 'add'; widget: DashboardWidget; index: number }\n | { type: 'remove'; id: string }\n | { type: 'update'; id: string; patch: DashboardWidgetPatch }\n\nexport interface DashboardTransactionMeta {\n /** `false` keeps the change out of undo, e.g. a change from another person. */\n history?: boolean\n /** Changes of the same group within a second become one undo step, e.g. typing in a setting. */\n group?: string\n /** Where the change came from: `layout`, `menu`, `keyboard`, `settings`, `api`… */\n origin?: string\n [key: string]: unknown\n}\n\nconst PROTECTED = new Set(['id', 'type'])\n\n/** Deep equality of JSON values; key order doesn't matter. */\nexport function sameValue(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false\n if (Array.isArray(a) !== Array.isArray(b)) return false\n const keys = Object.keys(a)\n if (keys.length !== Object.keys(b).length) return false\n return keys.every((key) =>\n sameValue((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n )\n}\n\n/** Applies one step: the new document and the step that undoes it, or `null` when it changes nothing. */\nfunction applyStep(\n document: DashboardDocument,\n step: DashboardStep,\n): [DashboardDocument, DashboardStep, DashboardStep] | null {\n const widgets = document.widgets\n const indexOf = (id: string) => widgets.findIndex((widget) => widget.id === id)\n if (step.type === 'add') {\n if (indexOf(step.widget.id) >= 0) return null\n const index = Math.max(0, Math.min(widgets.length, step.index))\n const next = [...widgets.slice(0, index), step.widget, ...widgets.slice(index)]\n return [\n { ...document, widgets: next },\n { ...step, index },\n { type: 'remove', id: step.widget.id },\n ]\n }\n const index = indexOf(step.id)\n if (index < 0) return null\n const widget = widgets[index]!\n if (step.type === 'remove') {\n const next = [...widgets.slice(0, index), ...widgets.slice(index + 1)]\n return [{ ...document, widgets: next }, step, { type: 'add', widget, index }]\n }\n const old = widget as unknown as Record<string, unknown>\n const changed: Record<string, unknown> = { ...old }\n const patch: Record<string, unknown> = {}\n const undo: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(step.patch)) {\n if (PROTECTED.has(key))\n throw new Error(`[@dou-ui/dashboard] a widget's \"${key}\" cannot be changed`)\n if (sameValue(old[key], value)) continue\n patch[key] = value\n undo[key] = old[key]\n if (value === undefined) delete changed[key]\n else changed[key] = value\n }\n if (!Object.keys(patch).length) return null\n const next = widgets.slice()\n next[index] = changed as unknown as DashboardWidget\n return [\n { ...document, widgets: next },\n { type: 'update', id: step.id, patch: patch as DashboardWidgetPatch },\n { type: 'update', id: step.id, patch: undo as DashboardWidgetPatch },\n ]\n}\n\n/**\n * Changes to a dashboard, made step by step and then handed to the\n * dashboard's `dispatch` as one change (one undo step). A step that changes\n * nothing (a widget that isn't there, a patch to the same values, an id\n * already in use) is left out.\n *\n * ```ts\n * const tr = dashboard.value.transaction()\n * tr.update('orders', { title: '本周订单' }).remove('memo')\n * dashboard.value.dispatch(tr)\n * ```\n */\nexport class DashboardTransaction {\n /** The document after the steps so far. */\n doc: DashboardDocument\n readonly steps: DashboardStep[] = []\n /** The steps that undo the ones so far, last one first. */\n readonly inverse: DashboardStep[] = []\n readonly meta: DashboardTransactionMeta = {}\n\n constructor(\n /** The document the transaction starts from. */\n readonly before: DashboardDocument,\n ) {\n this.doc = before\n }\n\n /** Whether any step was made. */\n get changed() {\n return this.steps.length > 0\n }\n\n /** Apply a step as it is. */\n step(step: DashboardStep) {\n const result = applyStep(this.doc, step)\n if (!result) return this\n this.doc = result[0]\n this.steps.push(result[1])\n this.inverse.unshift(result[2])\n return this\n }\n\n /** Put a widget into the document at `index` (the end by default). */\n add(widget: DashboardWidget, index = Infinity) {\n return this.step({ type: 'add', widget, index })\n }\n\n /** Take a widget out. */\n remove(id: string) {\n return this.step({ type: 'remove', id })\n }\n\n /** Set keys of a widget, e.g. `{ title }`, `{ props }` or `{ place }`; `undefined` removes a key. */\n update(id: string, patch: DashboardWidgetPatch) {\n return this.step({ type: 'update', id, patch })\n }\n\n setMeta(key: string, value: unknown) {\n this.meta[key] = value\n return this\n }\n}\n\n/**\n * Applies steps to a document in one go, giving the transaction: its `doc`\n * (unchanged widgets are kept as they are) and the `inverse` steps that\n * undo it. For the server, tests, or saved steps.\n */\nexport function applySteps(\n document: DashboardDocument,\n steps: readonly DashboardStep[],\n meta: DashboardTransactionMeta = {},\n): DashboardTransaction {\n const tr = new DashboardTransaction(document)\n Object.assign(tr.meta, meta)\n for (const step of steps) tr.step(step)\n return tr\n}\n\n/** A deep copy of a JSON value (also of a reactive one). */\nexport const cloneJson = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T\n\n/** The indexes of the longest strictly increasing run of `values`. */\nfunction longestRun(values: readonly number[]): Set<number> {\n const tails: number[] = []\n const previous: number[] = []\n values.forEach((value, index) => {\n let low = 0\n let high = tails.length\n while (low < high) {\n const mid = (low + high) >> 1\n if (values[tails[mid]!]! < value) low = mid + 1\n else high = mid\n }\n previous[index] = low > 0 ? tails[low - 1]! : -1\n tails[low] = index\n })\n const kept = new Set<number>()\n let index = tails.length ? tails[tails.length - 1]! : -1\n while (index >= 0) {\n kept.add(index)\n index = previous[index]!\n }\n return kept\n}\n\n/**\n * Adds the steps that turn the transaction's document into `next`: widgets\n * that are gone are removed, new ones added, changed keys updated, and the\n * fewest widgets taken out and put back to match the order. Unchanged\n * widgets keep their objects.\n */\nexport function replaceWidgets(tr: DashboardTransaction, next: DashboardDocument) {\n const wanted = new Map(next.widgets.map((widget, index) => [widget.id, index]))\n for (const widget of tr.doc.widgets) {\n const index = wanted.get(widget.id)\n // a widget whose type changed is a new widget\n if (index === undefined || next.widgets[index]!.type !== widget.type) tr.remove(widget.id)\n }\n const current = tr.doc.widgets\n const kept = longestRun(current.map((widget) => wanted.get(widget.id)!))\n for (const [index, widget] of current.entries()) if (!kept.has(index)) tr.remove(widget.id)\n next.widgets.forEach((widget, index) => {\n const there = tr.doc.widgets[index]\n if (there?.id !== widget.id) return void tr.add(widget, index)\n const patch: Record<string, unknown> = {}\n const old = there as unknown as Record<string, unknown>\n const item = widget as unknown as Record<string, unknown>\n for (const key of new Set([...Object.keys(old), ...Object.keys(item)]))\n if (!PROTECTED.has(key)) patch[key] = item[key]\n tr.update(widget.id, patch as DashboardWidgetPatch)\n })\n return tr\n}\n"],"mappings":";AA2BA,IAAM,4BAAY,IAAI,IAAI,CAAC,MAAM,MAAM,CAAC;;AAGxC,SAAgB,UAAU,GAAY,GAAqB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AAI,UAAU,KAAA,KAAa,KAAK,QAAQ,MAAM,CAAE,SAAS,OAAO,MAAM,GAAG,OAAO,OAAO,EAAE;CAC3F;CACA,MAAM,UAAU,GAAG,IAAI;CACvB,MAAM,OAAO,WAAW,QAAQ,KAAK,WAAW,OAAO,IAAI,OAAO,EAAE,CAAE,CAAC;CACvE,KAAK,MAAM,CAAC,OAAO,WAAW,QAAQ,QAAQ,GAAG,IAAI,CAAC,KAAK,IAAI,KAAK,GAAG,GAAG,OAAO,OAAO,EAAE;CAC1F,KAAK,QAAQ,SAAS,QAAQ,UAAU;EACtC,MAAM,QAAQ,GAAG,IAAI,QAAQ;EAC7B,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,KAAK,GAAG,IAAI,QAAQ,KAAK;EAC7D,MAAM,QAAiC,CAAC;EACxC,MAAM,MAAM;EACZ,MAAM,OAAO;EACb,KAAK,MAAM,uBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,GAAG,GAAG,GAAG,OAAO,KAAK,IAAI,CAAC,CAAC,GACnE,IAAI,CAAC,UAAU,IAAI,GAAG,GAAG,MAAM,OAAO,KAAK;EAC7C,GAAG,OAAO,OAAO,IAAI,KAA6B;CACpD,CAAC;CACD,OAAO;AACT"}
1
+ {"version":3,"file":"transaction.js","names":[],"sources":["../../src/core/transaction.ts"],"sourcesContent":["import type { DashboardDocument, DashboardWidget } from './types'\n\n/**\n * Keys of a widget to set; `undefined` removes the key. `id` and `type`\n * cannot be set: remove the widget and add another instead.\n */\nexport type DashboardWidgetPatch = { [key: string]: unknown } & {\n id?: never\n type?: never\n}\n\n/** One change to a dashboard. `index` is where in `widgets` an added widget goes. */\nexport type DashboardStep =\n | { type: 'add'; widget: DashboardWidget; index: number }\n | { type: 'remove'; id: string }\n | { type: 'update'; id: string; patch: DashboardWidgetPatch }\n\nexport interface DashboardTransactionMeta {\n /** `false` keeps the change out of undo, e.g. a change from another person. */\n history?: boolean\n /** Changes of the same group within a second become one undo step, e.g. typing in a setting. */\n group?: string\n /** Where the change came from: `layout`, `menu`, `keyboard`, `settings`, `api`… */\n origin?: string\n [key: string]: unknown\n}\n\nconst PROTECTED = new Set(['id', 'type'])\n\nexport interface ReplaceWidgetsOptions {\n /** A widget that stays keeps its `comments`; `true` by default. */\n keepComments?: boolean\n}\n\n/** The keys JSON keeps: those whose value isn't `undefined`. */\nconst jsonKeys = (value: object) =>\n Object.keys(value).filter((key) => (value as Record<string, unknown>)[key] !== undefined)\n\n/** Deep equality of JSON values; key order and keys set to `undefined` don't matter. */\nexport function sameValue(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false\n if (Array.isArray(a) !== Array.isArray(b)) return false\n if (Array.isArray(a))\n return (\n a.length === (b as unknown[]).length &&\n a.every((item, i) => sameValue(item, (b as unknown[])[i]))\n )\n const keys = jsonKeys(a)\n if (keys.length !== jsonKeys(b).length) return false\n return keys.every((key) =>\n sameValue((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n )\n}\n\n/** Applies one step: the new document and the step that undoes it, or `null` when it changes nothing. */\nfunction applyStep(\n document: DashboardDocument,\n step: DashboardStep,\n): [DashboardDocument, DashboardStep, DashboardStep] | null {\n const widgets = document.widgets\n const indexOf = (id: string) => widgets.findIndex((widget) => widget.id === id)\n if (step.type === 'add') {\n if (indexOf(step.widget.id) >= 0) return null\n const index = Math.max(0, Math.min(widgets.length, step.index))\n const next = [...widgets.slice(0, index), step.widget, ...widgets.slice(index)]\n return [\n { ...document, widgets: next },\n { ...step, index },\n { type: 'remove', id: step.widget.id },\n ]\n }\n const index = indexOf(step.id)\n if (index < 0) return null\n const widget = widgets[index]!\n if (step.type === 'remove') {\n const next = [...widgets.slice(0, index), ...widgets.slice(index + 1)]\n return [{ ...document, widgets: next }, step, { type: 'add', widget, index }]\n }\n const old = widget as unknown as Record<string, unknown>\n const changed: Record<string, unknown> = { ...old }\n const patch: Record<string, unknown> = {}\n const undo: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(step.patch)) {\n if (PROTECTED.has(key))\n throw new Error(`[@dou-ui/dashboard] a widget's \"${key}\" cannot be changed`)\n if (sameValue(old[key], value)) continue\n patch[key] = value\n undo[key] = old[key]\n if (value === undefined) delete changed[key]\n else changed[key] = value\n }\n if (!Object.keys(patch).length) return null\n const next = widgets.slice()\n next[index] = changed as unknown as DashboardWidget\n return [\n { ...document, widgets: next },\n { type: 'update', id: step.id, patch: patch as DashboardWidgetPatch },\n { type: 'update', id: step.id, patch: undo as DashboardWidgetPatch },\n ]\n}\n\n/**\n * Changes to a dashboard, made step by step and then handed to the\n * dashboard's `dispatch` as one change (one undo step). A step that changes\n * nothing (a widget that isn't there, a patch to the same values, an id\n * already in use) is left out.\n *\n * ```ts\n * const tr = dashboard.value.transaction()\n * tr.update('orders', { title: '本周订单' }).remove('memo')\n * dashboard.value.dispatch(tr)\n * ```\n */\nexport class DashboardTransaction {\n /** The document after the steps so far. */\n doc: DashboardDocument\n readonly steps: DashboardStep[] = []\n /** The steps that undo the ones so far, last one first. */\n readonly inverse: DashboardStep[] = []\n readonly meta: DashboardTransactionMeta = {}\n\n constructor(\n /** The document the transaction starts from. */\n readonly before: DashboardDocument,\n ) {\n this.doc = before\n }\n\n /** Whether any step was made. */\n get changed() {\n return this.steps.length > 0\n }\n\n /** Apply a step as it is. */\n step(step: DashboardStep) {\n const result = applyStep(this.doc, step)\n if (!result) return this\n this.doc = result[0]\n this.steps.push(result[1])\n this.inverse.unshift(result[2])\n return this\n }\n\n /** Put a widget into the document at `index` (the end by default). */\n add(widget: DashboardWidget, index = Infinity) {\n return this.step({ type: 'add', widget, index })\n }\n\n /** Take a widget out. */\n remove(id: string) {\n return this.step({ type: 'remove', id })\n }\n\n /** Set keys of a widget, e.g. `{ title }`, `{ props }` or `{ place }`; `undefined` removes a key. */\n update(id: string, patch: DashboardWidgetPatch) {\n return this.step({ type: 'update', id, patch })\n }\n\n setMeta(key: string, value: unknown) {\n this.meta[key] = value\n return this\n }\n}\n\n/**\n * Applies steps to a document in one go, giving the transaction: its `doc`\n * (unchanged widgets are kept as they are) and the `inverse` steps that\n * undo it. For the server, tests, or saved steps.\n */\nexport function applySteps(\n document: DashboardDocument,\n steps: readonly DashboardStep[],\n meta: DashboardTransactionMeta = {},\n): DashboardTransaction {\n const tr = new DashboardTransaction(document)\n Object.assign(tr.meta, meta)\n for (const step of steps) tr.step(step)\n return tr\n}\n\n/** A deep copy of a JSON value (also of a reactive one). */\nexport const cloneJson = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T\n\n/** The indexes of the longest strictly increasing run of `values`. */\nfunction longestRun(values: readonly number[]): Set<number> {\n const tails: number[] = []\n const previous: number[] = []\n values.forEach((value, index) => {\n let low = 0\n let high = tails.length\n while (low < high) {\n const mid = (low + high) >> 1\n if (values[tails[mid]!]! < value) low = mid + 1\n else high = mid\n }\n previous[index] = low > 0 ? tails[low - 1]! : -1\n tails[low] = index\n })\n const kept = new Set<number>()\n let index = tails.length ? tails[tails.length - 1]! : -1\n while (index >= 0) {\n kept.add(index)\n index = previous[index]!\n }\n return kept\n}\n\n/**\n * Adds the steps that turn the transaction's document into `next`: widgets\n * that are gone are removed, new ones added, changed keys updated, and the\n * fewest widgets taken out and put back to match the order. Unchanged\n * widgets keep their objects.\n *\n * A widget that stays keeps its `comments`, the discussions on it, as they\n * are: restoring a default layout doesn't take them off. Pass\n * `{ keepComments: false }` for the exact steps, e.g. to apply a shared\n * document.\n */\nexport function replaceWidgets(\n tr: DashboardTransaction,\n next: DashboardDocument,\n options: ReplaceWidgetsOptions = {},\n) {\n const keep = options.keepComments !== false\n const wanted = new Map(next.widgets.map((widget, index) => [widget.id, index]))\n for (const widget of tr.doc.widgets) {\n const index = wanted.get(widget.id)\n // a widget whose type changed is a new widget\n if (index === undefined || next.widgets[index]!.type !== widget.type) tr.remove(widget.id)\n }\n const current = tr.doc.widgets\n const kept = longestRun(current.map((widget) => wanted.get(widget.id)!))\n for (const [index, widget] of current.entries()) if (!kept.has(index)) tr.remove(widget.id)\n next.widgets.forEach((widget, index) => {\n const there = tr.doc.widgets[index]\n if (there?.id !== widget.id) return void tr.add(widget, index)\n const patch: Record<string, unknown> = {}\n const old = there as unknown as Record<string, unknown>\n const item = widget as unknown as Record<string, unknown>\n for (const key of new Set([...Object.keys(old), ...Object.keys(item)]))\n if (!PROTECTED.has(key) && !(keep && key === 'comments')) patch[key] = item[key]\n tr.update(widget.id, patch as DashboardWidgetPatch)\n })\n return tr\n}\n"],"mappings":";AA2BA,IAAM,4BAAY,IAAI,IAAI,CAAC,MAAM,MAAM,CAAC;;AAQxC,IAAM,YAAY,UAChB,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAS,MAAkC,SAAS,KAAA,CAAS;;AAG1F,SAAgB,UAAU,GAAY,GAAqB;CACzD,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI,CAAC,KAAK,CAAC,KAAK,OAAO,MAAM,YAAY,OAAO,MAAM,UAAU,OAAO;CACvE,IAAI,MAAM,QAAQ,CAAC,MAAM,MAAM,QAAQ,CAAC,GAAG,OAAO;CAClD,IAAI,MAAM,QAAQ,CAAC,GACjB,OACE,EAAE,WAAY,EAAgB,UAC9B,EAAE,OAAO,MAAM,MAAM,UAAU,MAAO,EAAgB,EAAE,CAAC;CAE7D,MAAM,OAAO,SAAS,CAAC;CACvB,IAAI,KAAK,WAAW,SAAS,CAAC,CAAC,CAAC,QAAQ,OAAO;CAC/C,OAAO,KAAK,OAAO,QACjB,UAAW,EAA8B,MAAO,EAA8B,IAAI,CACpF;AACF;;AAGA,SAAS,UACP,UACA,MAC0D;CAC1D,MAAM,UAAU,SAAS;CACzB,MAAM,WAAW,OAAe,QAAQ,WAAW,WAAW,OAAO,OAAO,EAAE;CAC9E,IAAI,KAAK,SAAS,OAAO;EACvB,IAAI,QAAQ,KAAK,OAAO,EAAE,KAAK,GAAG,OAAO;EACzC,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,IAA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uBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,GAAG,GAAG,GAAG,OAAO,KAAK,IAAI,CAAC,CAAC,GACnE,IAAI,CAAC,UAAU,IAAI,GAAG,KAAK,EAAE,QAAQ,QAAQ,aAAa,MAAM,OAAO,KAAK;EAC9E,GAAG,OAAO,OAAO,IAAI,KAA6B;CACpD,CAAC;CACD,OAAO;AACT"}
@@ -0,0 +1,6 @@
1
+ import comment_button_vue_vue_type_script_setup_true_lang_default from "./comment-button.vue_vue_type_script_setup_true_lang.js";
2
+ // src/dashboard/comment-button.vue
3
+ var comment_button_default = comment_button_vue_vue_type_script_setup_true_lang_default;
4
+ export { comment_button_default as default };
5
+
6
+ //# sourceMappingURL=comment-button.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"comment-button.js","names":["_sfc_main"],"sources":["../../src/dashboard/comment-button.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { MessageCircleIcon } from '@dou-ui/icons'\nimport { DouButton, DouTooltip, type Placement } from 'dou-ui'\nimport { computed } from 'vue'\nimport { format, type DashboardMessages } from '../locale'\nimport type { DashboardComments } from './comments'\n\n/*\n * A widget's comment button, in its title bar and its full screen view:\n * with how many open threads there are, opening them or the box to start one.\n */\n\nconst props = withDefaults(\n defineProps<{\n id: string\n comments: DashboardComments\n messages: DashboardMessages\n /** Where the tooltip goes: in the full screen view, clear of the dialog's close button above. */\n tooltipPlacement?: Placement\n }>(),\n { tooltipPlacement: 'top' },\n)\n\nconst count = computed(() => props.comments.openOn.value.get(props.id)?.length ?? 0)\n/** Shown with something to open, or a thread to start. */\nconst shown = computed(\n () => props.comments.enabled.value && (props.comments.writable.value || count.value > 0),\n)\nconst expanded = computed(() => props.comments.current.value === props.id)\nconst label = computed(() =>\n count.value ? format(props.messages.comments, { count: count.value }) : props.messages.comment,\n)\n\nfunction toggle(event: MouseEvent) {\n if (expanded.value) return props.comments.close()\n // pressed from the keyboard (no clicks counted): straight into the reply box;\n // a click or tap only shows the threads, without bringing up a phone's keyboard\n props.comments.start(props.id, event.detail === 0)\n}\n</script>\n\n<template>\n <DouTooltip v-if=\"shown\" :content=\"label\" :placement=\"tooltipPlacement\">\n <DouButton\n size=\"sm\"\n variant=\"ghost\"\n :class=\"['dou-dashboard__comment', count && 'has-threads']\"\n :aria-label=\"label\"\n :aria-expanded=\"expanded\"\n :data-dou-comment=\"id\"\n @click=\"toggle\"\n >\n <template v-if=\"count\" #leading><MessageCircleIcon /></template>\n <template v-if=\"count\">{{ count }}</template>\n <MessageCircleIcon v-else />\n </DouButton>\n </DouTooltip>\n</template>\n"],"mappings":""}
@@ -0,0 +1,59 @@
1
+ import { format } from "../locale.js";
2
+ import { DouButton, DouTooltip } from "dou-ui";
3
+ import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createSlots, createTextVNode, createVNode, defineComponent, normalizeClass, openBlock, toDisplayString, unref, withCtx } from "vue";
4
+ import { MessageCircleIcon } from "@dou-ui/icons";
5
+ // src/dashboard/comment-button.vue?vue&type=script&setup=true&lang.ts
6
+ var comment_button_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defineComponent({
7
+ __name: "comment-button",
8
+ props: {
9
+ id: {},
10
+ comments: {},
11
+ messages: {},
12
+ tooltipPlacement: { default: "top" }
13
+ },
14
+ setup(__props) {
15
+ const props = __props;
16
+ const count = computed(() => props.comments.openOn.value.get(props.id)?.length ?? 0);
17
+ /** Shown with something to open, or a thread to start. */
18
+ const shown = computed(() => props.comments.enabled.value && (props.comments.writable.value || count.value > 0));
19
+ const expanded = computed(() => props.comments.current.value === props.id);
20
+ const label = computed(() => count.value ? format(props.messages.comments, { count: count.value }) : props.messages.comment);
21
+ function toggle(event) {
22
+ if (expanded.value) return props.comments.close();
23
+ props.comments.start(props.id, event.detail === 0);
24
+ }
25
+ return (_ctx, _cache) => {
26
+ return shown.value ? (openBlock(), createBlock(unref(DouTooltip), {
27
+ key: 0,
28
+ content: label.value,
29
+ placement: __props.tooltipPlacement
30
+ }, {
31
+ default: withCtx(() => [createVNode(unref(DouButton), {
32
+ size: "sm",
33
+ variant: "ghost",
34
+ class: normalizeClass(["dou-dashboard__comment", count.value && "has-threads"]),
35
+ "aria-label": label.value,
36
+ "aria-expanded": expanded.value,
37
+ "data-dou-comment": __props.id,
38
+ onClick: toggle
39
+ }, createSlots({
40
+ default: withCtx(() => [count.value ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [createTextVNode(toDisplayString(count.value), 1)], 64)) : (openBlock(), createBlock(unref(MessageCircleIcon), { key: 1 }))]),
41
+ _: 2
42
+ }, [count.value ? {
43
+ name: "leading",
44
+ fn: withCtx(() => [createVNode(unref(MessageCircleIcon))]),
45
+ key: "0"
46
+ } : void 0]), 1032, [
47
+ "class",
48
+ "aria-label",
49
+ "aria-expanded",
50
+ "data-dou-comment"
51
+ ])]),
52
+ _: 1
53
+ }, 8, ["content", "placement"])) : createCommentVNode("", true);
54
+ };
55
+ }
56
+ });
57
+ export { comment_button_vue_vue_type_script_setup_true_lang_default as default };
58
+
59
+ //# sourceMappingURL=comment-button.vue_vue_type_script_setup_true_lang.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"comment-button.vue_vue_type_script_setup_true_lang.js","names":["_openBlock","_createBlock","_unref","_withCtx","_createVNode","_normalizeClass","_createSlots","_createElementBlock","_Fragment","_createTextVNode","_toDisplayString","_createCommentVNode"],"sources":["../../src/dashboard/comment-button.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { MessageCircleIcon } from '@dou-ui/icons'\nimport { DouButton, DouTooltip, type Placement } from 'dou-ui'\nimport { computed } from 'vue'\nimport { format, type DashboardMessages } from '../locale'\nimport type { DashboardComments } from './comments'\n\n/*\n * A widget's comment button, in its title bar and its full screen view:\n * with how many open threads there are, opening them or the box to start one.\n */\n\nconst props = withDefaults(\n defineProps<{\n id: string\n comments: DashboardComments\n messages: DashboardMessages\n /** Where the tooltip goes: in the full screen view, clear of the dialog's close button above. */\n tooltipPlacement?: Placement\n }>(),\n { tooltipPlacement: 'top' },\n)\n\nconst count = computed(() => props.comments.openOn.value.get(props.id)?.length ?? 0)\n/** Shown with something to open, or a thread to start. */\nconst shown = computed(\n () => props.comments.enabled.value && (props.comments.writable.value || count.value > 0),\n)\nconst expanded = computed(() => props.comments.current.value === props.id)\nconst label = computed(() =>\n count.value ? format(props.messages.comments, { count: count.value }) : props.messages.comment,\n)\n\nfunction toggle(event: MouseEvent) {\n if (expanded.value) return props.comments.close()\n // pressed from the keyboard (no clicks counted): straight into the reply box;\n // a click or tap only shows the threads, without bringing up a phone's keyboard\n props.comments.start(props.id, event.detail === 0)\n}\n</script>\n\n<template>\n <DouTooltip v-if=\"shown\" :content=\"label\" :placement=\"tooltipPlacement\">\n <DouButton\n size=\"sm\"\n variant=\"ghost\"\n :class=\"['dou-dashboard__comment', count && 'has-threads']\"\n :aria-label=\"label\"\n :aria-expanded=\"expanded\"\n :data-dou-comment=\"id\"\n @click=\"toggle\"\n >\n <template v-if=\"count\" #leading><MessageCircleIcon /></template>\n <template v-if=\"count\">{{ count }}</template>\n <MessageCircleIcon v-else />\n </DouButton>\n </DouTooltip>\n</template>\n"],"mappings":";;;;;;;;;;;;;;EAYA,MAAM,QAAQ;EAWd,MAAM,QAAQ,eAAe,MAAM,SAAS,OAAO,MAAM,IAAI,MAAM,EAAE,CAAC,EAAE,UAAU,CAAC;;EAEnF,MAAM,QAAQ,eACN,MAAM,SAAS,QAAQ,UAAU,MAAM,SAAS,SAAS,SAAS,MAAM,QAAQ,EACxF;EACA,MAAM,WAAW,eAAe,MAAM,SAAS,QAAQ,UAAU,MAAM,EAAE;EACzE,MAAM,QAAQ,eACZ,MAAM,QAAQ,OAAO,MAAM,SAAS,UAAU,EAAE,OAAO,MAAM,MAAM,CAAC,IAAI,MAAM,SAAS,OACzF;EAEA,SAAS,OAAO,OAAmB;GACjC,IAAI,SAAS,OAAO,OAAO,MAAM,SAAS,MAAM;GAGhD,MAAM,SAAS,MAAM,MAAM,IAAI,MAAM,WAAW,CAAC;EACnD;;GAIoB,OAAA,MAAA,SAAlBA,UAAA,GAAAC,YAcaC,MAAA,UAAA,GAAA;;IAda,SAAS,MAAA;IAAQ,WAAW,QAAA;;IACpD,SAAAC,cAYY,CAZZC,YAYYF,MAAA,SAAA,GAAA;KAXV,MAAK;KACL,SAAQ;KACP,OAAKG,eAAA,CAAA,0BAA6B,MAAA,SAAK,aAAA,CAAA;KACvC,cAAY,MAAA;KACZ,iBAAe,SAAA;KACf,oBAAkB,QAAA;KAClB,SAAO;;KAGR,SAAAF,cAA6C,CAA7B,MAAA,SAAhBH,UAAA,GAAAO,mBAA6CC,UAAA,EAAA,KAAA,EAAA,GAAA,CAAnBC,gBAAAC,gBAAA,MAAA,KAAK,GAAA,CAAA,C,WAC/BV,UAAA,GAAAC,YAA4BC,MAAA,iBAAA,GAAA,EAAA,KAAA,EAAA,CAAA,E;;I,IAFZ,MAAA,Q;KAAQ,MAAA;KAAQ,IAAAC,cAAqB,CAArBC,YAAqBF,MAAA,iBAAA,CAAA,C"}
@@ -0,0 +1,6 @@
1
+ import comment_card_vue_vue_type_script_setup_true_lang_default from "./comment-card.vue_vue_type_script_setup_true_lang.js";
2
+ // src/dashboard/comment-card.vue
3
+ var comment_card_default = comment_card_vue_vue_type_script_setup_true_lang_default;
4
+ export { comment_card_default as default };
5
+
6
+ //# sourceMappingURL=comment-card.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"comment-card.js","names":["_sfc_main"],"sources":["../../src/dashboard/comment-card.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { DouCommentThread, useFloating, useLayer, useZIndex, type VirtualElement } from 'dou-ui'\nimport { computed, nextTick, onBeforeUnmount, shallowRef, useTemplateRef, watch } from 'vue'\nimport type { DashboardMessages } from '../locale'\nimport type { DashboardComments } from './comments'\n\n/*\n * The card with a widget's discussions, by the comment button in its title\n * bar: every open thread there, or the box for a thread being started.\n */\n\nconst props = defineProps<{\n comments: DashboardComments\n messages: DashboardMessages\n /** The comment button of a widget, to put the card by and give the focus back to. */\n buttonOf: (widget: string) => HTMLElement | null\n /** Where the card goes: the button, or the widget while its button isn't drawn yet. */\n placeOf: (widget: string) => HTMLElement | null\n}>()\n\nconst { comments } = props\nconst panel = shallowRef<HTMLElement | null>(null)\nconst open = computed(() => !!comments.current.value)\n\nconst anchor: VirtualElement = {\n getBoundingClientRect() {\n const widget = comments.current.value\n const el = widget && props.placeOf(widget)\n return el ? el.getBoundingClientRect() : new DOMRect()\n },\n}\n\nconst { style, placement, update } = useFloating(() => (open.value ? anchor : null), panel, {\n open,\n placement: 'bottom-end',\n offset: 6,\n})\nconst { next } = useZIndex()\nconst zIndex = shallowRef(0)\nwatch(open, (value) => value && (zIndex.value = next()), { immediate: true })\n\n// a widget far from the view is drawn once it is scrolled to: then the card moves to its button\nlet frame = 0\nwatch(\n () => comments.current.value,\n (widget) => {\n cancelAnimationFrame(frame)\n if (!widget || props.buttonOf(widget)) return\n let tries = 60\n const wait = () => {\n if (comments.current.value !== widget) return\n if (props.buttonOf(widget)) return update()\n update()\n if (--tries > 0) frame = requestAnimationFrame(wait)\n }\n frame = requestAnimationFrame(wait)\n },\n { flush: 'post' },\n)\nonBeforeUnmount(() => cancelAnimationFrame(frame))\n\nlet lastWidget: string | null = null\nwatch(comments.current, (widget) => widget && (lastWidget = widget), { immediate: true })\n\nfunction restore() {\n const el = lastWidget ? props.buttonOf(lastWidget) : null\n el?.focus({ preventScroll: true })\n}\n\nconst focusLost = () => {\n const el = document.activeElement\n return !el || el === document.body || !!panel.value?.contains(el)\n}\n\nfunction close() {\n const refocus = focusLost()\n comments.close()\n if (refocus) restore()\n}\n\nuseLayer({\n open,\n elements: () => {\n const widget = comments.current.value\n return [panel.value, widget ? props.buttonOf(widget) : null]\n },\n onEscape: () => close(),\n onOutside: () => comments.close(),\n})\n\nconst views = useTemplateRef<InstanceType<typeof DouCommentThread>[]>('views')\n// asked to (the shortcut, the button, a thread just started): the reply box\nwatch(\n () => comments.focusRequest.value,\n async () => {\n await nextTick()\n await nextTick()\n const id = comments.active.value\n const index = comments.shown.value.findIndex((t) => t.id === id)\n views.value?.[Math.max(0, index)]?.focus()\n },\n)\n\n// a thread resolved or removed from the card: back to the button, once the card is gone\nfunction onClosed() {\n const el = document.activeElement\n if (!el || el === document.body) restore()\n}\n</script>\n\n<template>\n <Transition name=\"dou-floating\" @after-leave=\"onClosed\">\n <div\n v-if=\"open\"\n ref=\"panel\"\n class=\"dou-floating dou-dashboard__comment-card\"\n role=\"dialog\"\n :aria-label=\"messages.comment\"\n :style=\"[style, { zIndex }]\"\n :data-placement=\"placement\"\n >\n <DouCommentThread\n v-if=\"comments.pending.value\"\n ref=\"views\"\n key=\"new\"\n :thread=\"null\"\n :author=\"comments.author.value\"\n autofocus\n @action=\"comments.apply\"\n @cancel=\"close\"\n />\n <template v-else>\n <DouCommentThread\n v-for=\"thread in comments.shown.value\"\n :key=\"thread.id\"\n ref=\"views\"\n :thread=\"thread\"\n :author=\"comments.author.value\"\n :readonly=\"!comments.writable.value\"\n @action=\"comments.apply\"\n @cancel=\"close\"\n />\n </template>\n </div>\n </Transition>\n</template>\n"],"mappings":""}
@@ -0,0 +1,128 @@
1
+ import { DouCommentThread, useFloating, useLayer, useZIndex } from "dou-ui";
2
+ import { Fragment, Transition, computed, createBlock, createCommentVNode, createElementBlock, defineComponent, nextTick, normalizeStyle, onBeforeUnmount, openBlock, renderList, shallowRef, unref, useTemplateRef, watch, withCtx } from "vue";
3
+ // src/dashboard/comment-card.vue?vue&type=script&setup=true&lang.ts
4
+ var _hoisted_1 = ["aria-label", "data-placement"];
5
+ var comment_card_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defineComponent({
6
+ __name: "comment-card",
7
+ props: {
8
+ comments: {},
9
+ messages: {},
10
+ buttonOf: { type: Function },
11
+ placeOf: { type: Function }
12
+ },
13
+ setup(__props) {
14
+ const props = __props;
15
+ const { comments } = props;
16
+ const panel = shallowRef(null);
17
+ const open = computed(() => !!comments.current.value);
18
+ const anchor = { getBoundingClientRect() {
19
+ const widget = comments.current.value;
20
+ const el = widget && props.placeOf(widget);
21
+ return el ? el.getBoundingClientRect() : new DOMRect();
22
+ } };
23
+ const { style, placement, update } = useFloating(() => open.value ? anchor : null, panel, {
24
+ open,
25
+ placement: "bottom-end",
26
+ offset: 6
27
+ });
28
+ const { next } = useZIndex();
29
+ const zIndex = shallowRef(0);
30
+ watch(open, (value) => value && (zIndex.value = next()), { immediate: true });
31
+ let frame = 0;
32
+ watch(() => comments.current.value, (widget) => {
33
+ cancelAnimationFrame(frame);
34
+ if (!widget || props.buttonOf(widget)) return;
35
+ let tries = 60;
36
+ const wait = () => {
37
+ if (comments.current.value !== widget) return;
38
+ if (props.buttonOf(widget)) return update();
39
+ update();
40
+ if (--tries > 0) frame = requestAnimationFrame(wait);
41
+ };
42
+ frame = requestAnimationFrame(wait);
43
+ }, { flush: "post" });
44
+ onBeforeUnmount(() => cancelAnimationFrame(frame));
45
+ let lastWidget = null;
46
+ watch(comments.current, (widget) => widget && (lastWidget = widget), { immediate: true });
47
+ function restore() {
48
+ (lastWidget ? props.buttonOf(lastWidget) : null)?.focus({ preventScroll: true });
49
+ }
50
+ const focusLost = () => {
51
+ const el = document.activeElement;
52
+ return !el || el === document.body || !!panel.value?.contains(el);
53
+ };
54
+ function close() {
55
+ const refocus = focusLost();
56
+ comments.close();
57
+ if (refocus) restore();
58
+ }
59
+ useLayer({
60
+ open,
61
+ elements: () => {
62
+ const widget = comments.current.value;
63
+ return [panel.value, widget ? props.buttonOf(widget) : null];
64
+ },
65
+ onEscape: () => close(),
66
+ onOutside: () => comments.close()
67
+ });
68
+ const views = useTemplateRef("views");
69
+ watch(() => comments.focusRequest.value, async () => {
70
+ await nextTick();
71
+ await nextTick();
72
+ const id = comments.active.value;
73
+ const index = comments.shown.value.findIndex((t) => t.id === id);
74
+ views.value?.[Math.max(0, index)]?.focus();
75
+ });
76
+ function onClosed() {
77
+ const el = document.activeElement;
78
+ if (!el || el === document.body) restore();
79
+ }
80
+ return (_ctx, _cache) => {
81
+ return openBlock(), createBlock(Transition, {
82
+ name: "dou-floating",
83
+ onAfterLeave: onClosed
84
+ }, {
85
+ default: withCtx(() => [open.value ? (openBlock(), createElementBlock("div", {
86
+ key: 0,
87
+ ref_key: "panel",
88
+ ref: panel,
89
+ class: "dou-floating dou-dashboard__comment-card",
90
+ role: "dialog",
91
+ "aria-label": __props.messages.comment,
92
+ style: normalizeStyle([unref(style), { zIndex: zIndex.value }]),
93
+ "data-placement": unref(placement)
94
+ }, [unref(comments).pending.value ? (openBlock(), createBlock(unref(DouCommentThread), {
95
+ ref_key: "views",
96
+ ref: views,
97
+ key: "new",
98
+ thread: null,
99
+ author: unref(comments).author.value,
100
+ autofocus: "",
101
+ onAction: unref(comments).apply,
102
+ onCancel: close
103
+ }, null, 8, ["author", "onAction"])) : (openBlock(true), createElementBlock(Fragment, { key: 1 }, renderList(unref(comments).shown.value, (thread) => {
104
+ return openBlock(), createBlock(unref(DouCommentThread), {
105
+ key: thread.id,
106
+ ref_for: true,
107
+ ref_key: "views",
108
+ ref: views,
109
+ thread,
110
+ author: unref(comments).author.value,
111
+ readonly: !unref(comments).writable.value,
112
+ onAction: unref(comments).apply,
113
+ onCancel: close
114
+ }, null, 8, [
115
+ "thread",
116
+ "author",
117
+ "readonly",
118
+ "onAction"
119
+ ]);
120
+ }), 128))], 12, _hoisted_1)) : createCommentVNode("", true)]),
121
+ _: 1
122
+ });
123
+ };
124
+ }
125
+ });
126
+ export { comment_card_vue_vue_type_script_setup_true_lang_default as default };
127
+
128
+ //# sourceMappingURL=comment-card.vue_vue_type_script_setup_true_lang.js.map