@nocode-factory/sanity-kit 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/bin/ncf-kit.mjs +201 -0
  2. package/dist/index.d.ts +1643 -0
  3. package/dist/index.js +6632 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/web-server.d.ts +46 -0
  6. package/dist/web-server.js +51 -0
  7. package/dist/web-server.js.map +1 -0
  8. package/dist/web.d.ts +27 -0
  9. package/dist/web.js +117 -0
  10. package/dist/web.js.map +1 -0
  11. package/package.json +90 -0
  12. package/scripts/use-client.mjs +20 -0
  13. package/src/config/defaults.ts +74 -0
  14. package/src/config/resolve.ts +153 -0
  15. package/src/config/types.ts +290 -0
  16. package/src/config/validate.ts +193 -0
  17. package/src/context/BoardLayoutContext.tsx +24 -0
  18. package/src/context/KitContext.tsx +30 -0
  19. package/src/context/PreviewTargetContext.tsx +27 -0
  20. package/src/hooks/useAnnotations.ts +60 -0
  21. package/src/hooks/useBoardLayout.ts +398 -0
  22. package/src/hooks/useColumnOptions.ts +47 -0
  23. package/src/hooks/useDocumentColumns.ts +61 -0
  24. package/src/hooks/useHistory.ts +89 -0
  25. package/src/hooks/useInternalColumns.ts +19 -0
  26. package/src/hooks/useKitClient.ts +15 -0
  27. package/src/hooks/useOccurrences.ts +62 -0
  28. package/src/hooks/usePageContents.ts +65 -0
  29. package/src/hooks/usePages.ts +41 -0
  30. package/src/hooks/usePreviewTarget.ts +162 -0
  31. package/src/hooks/useQueryData.ts +103 -0
  32. package/src/hooks/useRegistration.ts +50 -0
  33. package/src/index.ts +280 -0
  34. package/src/lib/blocks.ts +38 -0
  35. package/src/lib/colors.ts +103 -0
  36. package/src/lib/columns.ts +137 -0
  37. package/src/lib/diff.ts +200 -0
  38. package/src/lib/elkLayout.ts +124 -0
  39. package/src/lib/graph.ts +238 -0
  40. package/src/lib/grouping.ts +116 -0
  41. package/src/lib/links.ts +70 -0
  42. package/src/lib/occurrences.ts +93 -0
  43. package/src/lib/pageThumbnail.ts +43 -0
  44. package/src/lib/pages.ts +199 -0
  45. package/src/lib/paths.ts +68 -0
  46. package/src/lib/query.ts +113 -0
  47. package/src/lib/schemaColumns.ts +162 -0
  48. package/src/lib/schemaTypes.ts +75 -0
  49. package/src/lib/sectionsMap.ts +83 -0
  50. package/src/lib/service.ts +88 -0
  51. package/src/lib/siteRoutes.ts +43 -0
  52. package/src/lib/status.ts +122 -0
  53. package/src/lib/studioLinks.ts +137 -0
  54. package/src/schema/boardLayout.ts +190 -0
  55. package/src/tools/components/BlockCard.tsx +79 -0
  56. package/src/tools/components/ComponentsTool.tsx +171 -0
  57. package/src/tools/components/map/SectionNode.tsx +109 -0
  58. package/src/tools/components/map/SectionsMap.tsx +339 -0
  59. package/src/tools/createToolComponent.tsx +67 -0
  60. package/src/tools/history/ChangeRow.tsx +87 -0
  61. package/src/tools/history/DiffPanel.tsx +227 -0
  62. package/src/tools/history/HistoryTool.tsx +230 -0
  63. package/src/tools/more/MoreTool.tsx +82 -0
  64. package/src/tools/pages/ColumnHeader.tsx +216 -0
  65. package/src/tools/pages/ColumnVisibility.tsx +173 -0
  66. package/src/tools/pages/FieldValue.tsx +327 -0
  67. package/src/tools/pages/PagesTable.tsx +394 -0
  68. package/src/tools/pages/PagesTool.tsx +333 -0
  69. package/src/tools/pages/PagesToolbar.tsx +53 -0
  70. package/src/tools/pages/PathCell.tsx +71 -0
  71. package/src/tools/pages/PreviewTarget.tsx +226 -0
  72. package/src/tools/pages/TagCell.tsx +124 -0
  73. package/src/tools/pages/ViewTabs.tsx +57 -0
  74. package/src/tools/pages/board/BoardView.tsx +661 -0
  75. package/src/tools/pages/board/PageNode.tsx +306 -0
  76. package/src/tools/pages/board/PagePanel.tsx +228 -0
  77. package/src/tools/presentation/PreviewHeader.tsx +75 -0
  78. package/src/tools/shared/AnnotationNode.tsx +126 -0
  79. package/src/ui/ActorName.tsx +20 -0
  80. package/src/ui/ConfigIssues.tsx +41 -0
  81. package/src/ui/InlineCode.tsx +22 -0
  82. package/src/ui/Popover.tsx +85 -0
  83. package/src/ui/ProjectStatusNotice.tsx +58 -0
  84. package/src/ui/QueryError.tsx +16 -0
  85. package/src/ui/QuietInput.tsx +64 -0
  86. package/src/ui/StatusBadge.tsx +11 -0
  87. package/src/ui/ToolPlaceholder.tsx +23 -0
  88. package/src/ui/formatDate.ts +14 -0
  89. package/src/ui/tokens.ts +54 -0
  90. package/src/version.ts +5 -0
  91. package/src/web/PreviewBanner.tsx +115 -0
  92. package/src/web/draftModeToggle.ts +56 -0
  93. package/src/web/environment.ts +21 -0
  94. package/src/web/index.ts +15 -0
  95. package/src/web/server.ts +11 -0
@@ -0,0 +1,38 @@
1
+ /** camelCase / PascalCase / dotted -> kebab-case. */
2
+ export function toKebabCase(value: string): string {
3
+ return value
4
+ .replace(/[.\s_]+/g, '-')
5
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
6
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
7
+ .replace(/-+/g, '-')
8
+ .replace(/^-|-$/g, '')
9
+ .toLowerCase()
10
+ }
11
+
12
+ /**
13
+ * Nom court d'un bloc : le type amputé de son préfixe de convention.
14
+ * `blockName('section.imageText', 'section.')` -> 'imageText'
15
+ */
16
+ export function blockName(type: string, namespace: string): string {
17
+ if (namespace && type.startsWith(namespace)) return type.slice(namespace.length)
18
+ return type
19
+ }
20
+
21
+ /**
22
+ * Remplit un gabarit d'URL. `{name}` garde la casse d'origine (les captures
23
+ * générées par la CI sont nommées ainsi : imageText.png), `{kebab}` la
24
+ * transforme pour les cibles qui l'exigent.
25
+ */
26
+ export function fillTemplate(template: string, type: string, namespace: string): string {
27
+ const name = blockName(type, namespace)
28
+ return template.replaceAll('{name}', name).replaceAll('{kebab}', toKebabCase(name))
29
+ }
30
+
31
+ /** Libellé lisible par défaut : 'imageText' -> 'Image text'. */
32
+ export function humanizeBlockName(type: string, namespace: string): string {
33
+ const kebab = toKebabCase(blockName(type, namespace))
34
+ if (!kebab) return type
35
+ const words = kebab.split('-')
36
+ const [first = '', ...rest] = words
37
+ return [first.charAt(0).toUpperCase() + first.slice(1), ...rest].join(' ')
38
+ }
@@ -0,0 +1,103 @@
1
+ import type {NcfBoardTag, NcfInternalField} from '../config/types'
2
+ import type {NodeLayout} from './graph'
3
+ import type {PageRow} from './pages'
4
+
5
+ /** Critère qui donne sa couleur à une page. */
6
+ export type ColorBy = 'tag' | 'status' | `field:${string}`
7
+
8
+ /** Couleurs des statuts, alignées sur les tons des badges. */
9
+ export const STATUS_COLORS: Record<PageRow['status'], string> = {
10
+ published: '#43d675',
11
+ modified: '#f5a623',
12
+ draft: '#8a8a8a',
13
+ }
14
+
15
+ /**
16
+ * Applique une opacité à une couleur hexadécimale.
17
+ *
18
+ * Le fond d'une carte doit rester très pâle : à pleine saturation, le texte
19
+ * du Studio devient illisible dans les deux thèmes.
20
+ */
21
+ export function withAlpha(color: string, alpha: number): string {
22
+ const hex = color.trim()
23
+ const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(hex)
24
+ const long = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex)
25
+
26
+ const rgb = short
27
+ ? [short[1], short[2], short[3]].map((c) => parseInt(`${c}${c}`, 16))
28
+ : long
29
+ ? [long[1], long[2], long[3]].map((c) => parseInt(c as string, 16))
30
+ : null
31
+
32
+ // Couleur non hexadécimale (nom CSS, rgb()…) : on la laisse telle quelle
33
+ // plutôt que de produire une valeur invalide.
34
+ if (!rgb) return hex
35
+ return `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, ${alpha})`
36
+ }
37
+
38
+ /**
39
+ * Couleur stable déduite d'une valeur libre. Deux responsables différents
40
+ * reçoivent deux teintes différentes, et la même valeur donne toujours la
41
+ * même couleur d'une session à l'autre.
42
+ */
43
+ export function colorFromString(value: string): string {
44
+ let hash = 0
45
+ for (let i = 0; i < value.length; i += 1) {
46
+ hash = (hash * 31 + value.charCodeAt(i)) % 360
47
+ }
48
+ return `hsl(${hash}, 62%, 55%)`
49
+ }
50
+
51
+ /**
52
+ * Ramène un critère devenu invalide sur l'étiquette. Supprimer la colonne qui
53
+ * sert à colorer laisserait sinon le sélecteur sur une valeur inexistante.
54
+ */
55
+ export function resolveColorBy(
56
+ colorBy: ColorBy,
57
+ fields: readonly {id: string}[],
58
+ ): ColorBy {
59
+ if (colorBy === 'tag' || colorBy === 'status') return colorBy
60
+ const fieldId = colorBy.slice('field:'.length)
61
+ return fields.some((field) => field.id === fieldId) ? colorBy : 'tag'
62
+ }
63
+
64
+ export interface ColorOptions {
65
+ meta: ReadonlyMap<string, NodeLayout>
66
+ tags: readonly NcfBoardTag[]
67
+ fields: readonly NcfInternalField[]
68
+ }
69
+
70
+ export interface RowColor {
71
+ color: string | null
72
+ label: string | null
73
+ }
74
+
75
+ /** Couleur et libellé d'une page selon le critère choisi. */
76
+ export function colorForRow(
77
+ row: PageRow,
78
+ colorBy: ColorBy,
79
+ options: ColorOptions,
80
+ ): RowColor {
81
+ if (colorBy === 'status') {
82
+ return {color: STATUS_COLORS[row.status], label: row.status}
83
+ }
84
+
85
+ const entry = options.meta.get(row.id)
86
+
87
+ if (colorBy === 'tag') {
88
+ const tag = options.tags.find((t) => t.id === entry?.tag)
89
+ return tag ? {color: tag.color, label: tag.label} : {color: null, label: null}
90
+ }
91
+
92
+ const fieldId = colorBy.slice('field:'.length)
93
+ const value = entry?.fields?.[fieldId]
94
+ if (!value) return {color: null, label: null}
95
+
96
+ const field = options.fields.find((f) => f.id === fieldId)
97
+ const choice = field?.options?.find((o) => o.id === value)
98
+ if (choice) {
99
+ return {color: choice.color ?? colorFromString(choice.id), label: choice.label}
100
+ }
101
+ // Champ libre : la teinte est déduite de la valeur saisie.
102
+ return {color: colorFromString(value), label: value}
103
+ }
@@ -0,0 +1,137 @@
1
+ import type {NcfInternalField, NcfInternalFieldOption} from '../config/types'
2
+
3
+ /**
4
+ * Identifiant technique dérivé du nom saisi. Stable et lisible dans le
5
+ * document, contrairement à un identifiant aléatoire.
6
+ * « Rôle de la page » → `role-de-la-page`
7
+ */
8
+ export function columnId(label: string): string {
9
+ const base = label
10
+ .normalize('NFD')
11
+ .replace(/\p{Diacritic}/gu, '')
12
+ .toLowerCase()
13
+ .replace(/[^a-z0-9]+/g, '-')
14
+ .replace(/^-|-$/g, '')
15
+ return base || 'colonne'
16
+ }
17
+
18
+ /** Identifiant unique parmi ceux déjà pris, en suffixant si besoin. */
19
+ export function uniqueColumnId(label: string, taken: readonly string[]): string {
20
+ const base = columnId(label)
21
+ if (!taken.includes(base)) return base
22
+ let n = 2
23
+ while (taken.includes(`${base}-${n}`)) n += 1
24
+ return `${base}-${n}`
25
+ }
26
+
27
+ export interface AddColumnInput {
28
+ label: string
29
+ type?: 'text' | 'select'
30
+ options?: NcfInternalFieldOption[]
31
+ }
32
+
33
+ /** Ajoute une colonne en fin de liste. Un nom vide est refusé. */
34
+ export function addColumn(
35
+ columns: readonly NcfInternalField[],
36
+ input: AddColumnInput,
37
+ ): NcfInternalField[] {
38
+ const label = input.label.trim()
39
+ if (!label) return [...columns]
40
+ const id = uniqueColumnId(label, columns.map((c) => c.id))
41
+ return [
42
+ ...columns,
43
+ {
44
+ id,
45
+ label,
46
+ type: input.type ?? 'text',
47
+ ...(input.options?.length ? {options: input.options} : {}),
48
+ },
49
+ ]
50
+ }
51
+
52
+ /**
53
+ * Renomme une colonne sans toucher à son identifiant : les valeurs déjà
54
+ * saisies y sont rattachées.
55
+ */
56
+ export function renameColumn(
57
+ columns: readonly NcfInternalField[],
58
+ id: string,
59
+ label: string,
60
+ ): NcfInternalField[] {
61
+ const trimmed = label.trim()
62
+ if (!trimmed) return [...columns]
63
+ return columns.map((column) => (column.id === id ? {...column, label: trimmed} : column))
64
+ }
65
+
66
+ export function removeColumn(
67
+ columns: readonly NcfInternalField[],
68
+ id: string,
69
+ ): NcfInternalField[] {
70
+ return columns.filter((column) => column.id !== id)
71
+ }
72
+
73
+ /** Déplace une colonne, pour réordonner le tableau. */
74
+ export function moveColumn(
75
+ columns: readonly NcfInternalField[],
76
+ id: string,
77
+ delta: number,
78
+ ): NcfInternalField[] {
79
+ const index = columns.findIndex((column) => column.id === id)
80
+ if (index === -1) return [...columns]
81
+ const target = index + delta
82
+ if (target < 0 || target >= columns.length) return [...columns]
83
+ const next = [...columns]
84
+ const [moved] = next.splice(index, 1)
85
+ next.splice(target, 0, moved as NcfInternalField)
86
+ return next
87
+ }
88
+
89
+ /** Retire un choix d'une colonne de type liste. */
90
+ export function removeColumnOption(
91
+ columns: readonly NcfInternalField[],
92
+ id: string,
93
+ optionId: string,
94
+ ): NcfInternalField[] {
95
+ return columns.map((column) =>
96
+ column.id === id
97
+ ? {...column, options: (column.options ?? []).filter((option) => option.id !== optionId)}
98
+ : column,
99
+ )
100
+ }
101
+
102
+ /** Change la couleur d'un choix, ou la retire. */
103
+ export function setColumnOptionColor(
104
+ columns: readonly NcfInternalField[],
105
+ id: string,
106
+ optionId: string,
107
+ color: string | null,
108
+ ): NcfInternalField[] {
109
+ return columns.map((column) =>
110
+ column.id === id
111
+ ? {
112
+ ...column,
113
+ options: (column.options ?? []).map((option) =>
114
+ option.id === optionId
115
+ ? {id: option.id, label: option.label, ...(color ? {color} : {})}
116
+ : option,
117
+ ),
118
+ }
119
+ : column,
120
+ )
121
+ }
122
+
123
+ /** Ajoute un choix à une colonne de type liste. */
124
+ export function addColumnOption(
125
+ columns: readonly NcfInternalField[],
126
+ id: string,
127
+ label: string,
128
+ ): NcfInternalField[] {
129
+ const trimmed = label.trim()
130
+ if (!trimmed) return [...columns]
131
+ return columns.map((column) => {
132
+ if (column.id !== id) return column
133
+ const options = column.options ?? []
134
+ const optionId = uniqueColumnId(trimmed, options.map((o) => o.id))
135
+ return {...column, options: [...options, {id: optionId, label: trimmed}]}
136
+ })
137
+ }
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Comparaison de deux états d'un document.
3
+ *
4
+ * Le diff se calcule ici plutôt que sur le serveur : le kit ne doit rien
5
+ * savoir du schéma d'un client, et une comparaison générique de deux objets
6
+ * JSON n'a besoin de rien d'autre que des deux objets.
7
+ */
8
+
9
+ export type ChangeKind = 'added' | 'removed' | 'changed'
10
+
11
+ export interface Change {
12
+ /** Chemin lisible, ex. `seo.metaDescription` ou `sections[2].title`. */
13
+ path: string
14
+ kind: ChangeKind
15
+ before: unknown
16
+ after: unknown
17
+ }
18
+
19
+ /**
20
+ * Champs système de Sanity, écartés du diff.
21
+ *
22
+ * `_rev` et `_updatedAt` changent à chaque enregistrement : les afficher
23
+ * noierait les vraies modifications sous du bruit. `_id` et `_type` ne
24
+ * changent pas sans que ce soit un autre document.
25
+ */
26
+ const SYSTEM_KEYS = new Set(['_rev', '_updatedAt', '_createdAt', '_id', '_type'])
27
+
28
+ /** `_key` identifie un élément de tableau ; il n'a pas de sens pour un lecteur. */
29
+ const NOISE_KEYS = new Set(['_key'])
30
+
31
+ const isObject = (value: unknown): value is Record<string, unknown> =>
32
+ typeof value === 'object' && value !== null && !Array.isArray(value)
33
+
34
+ /**
35
+ * Aplatit un document en chemins terminaux.
36
+ *
37
+ * Les tableaux sont indexés par leur `_key` quand il existe — c'est ce que
38
+ * Sanity garantit stable — et par leur position sinon. Réordonner des
39
+ * sections ne doit pas se lire comme si tout leur contenu avait changé.
40
+ */
41
+ export function flatten(value: unknown, prefix = '', out = new Map<string, unknown>()): Map<string, unknown> {
42
+ if (Array.isArray(value)) {
43
+ value.forEach((item, index) => {
44
+ const key = isObject(item) && typeof item._key === 'string' ? item._key : String(index)
45
+ flatten(item, `${prefix}[${key}]`, out)
46
+ })
47
+ return out
48
+ }
49
+
50
+ if (isObject(value)) {
51
+ const keys = Object.keys(value).filter((key) => !NOISE_KEYS.has(key))
52
+ if (keys.length === 0 && prefix) out.set(prefix, {})
53
+ for (const key of keys) {
54
+ flatten(value[key], prefix ? `${prefix}.${key}` : key, out)
55
+ }
56
+ return out
57
+ }
58
+
59
+ if (prefix) out.set(prefix, value)
60
+ return out
61
+ }
62
+
63
+ const same = (a: unknown, b: unknown): boolean =>
64
+ a === b || (Number.isNaN(a) && Number.isNaN(b)) || JSON.stringify(a) === JSON.stringify(b)
65
+
66
+ /**
67
+ * Modifications entre deux états, triées par chemin.
68
+ *
69
+ * Un état absent — création ou suppression — se compare à un objet vide
70
+ * plutôt que de produire un cas particulier : tout devient « ajouté » ou
71
+ * « retiré », ce qui se lit aussi bien.
72
+ */
73
+ export function diffDocuments(before: unknown, after: unknown): Change[] {
74
+ const left = flatten(before ?? {})
75
+ const right = flatten(after ?? {})
76
+
77
+ const paths = [...new Set([...left.keys(), ...right.keys()])]
78
+ .filter((path) => !isSystemPath(path))
79
+ .sort()
80
+
81
+ const changes: Change[] = []
82
+
83
+ for (const path of paths) {
84
+ const had = left.has(path)
85
+ const has = right.has(path)
86
+ const valueBefore = left.get(path)
87
+ const valueAfter = right.get(path)
88
+
89
+ if (had && has) {
90
+ if (!same(valueBefore, valueAfter)) {
91
+ changes.push({path, kind: 'changed', before: valueBefore, after: valueAfter})
92
+ }
93
+ continue
94
+ }
95
+ if (has) changes.push({path, kind: 'added', before: undefined, after: valueAfter})
96
+ else changes.push({path, kind: 'removed', before: valueBefore, after: undefined})
97
+ }
98
+
99
+ return changes
100
+ }
101
+
102
+ /** Un chemin système, à la racine comme au fond d'un tableau. */
103
+ function isSystemPath(path: string): boolean {
104
+ const last = path.split('.').pop() ?? ''
105
+ return SYSTEM_KEYS.has(last)
106
+ }
107
+
108
+ /**
109
+ * Résumé d'un changement en une ligne.
110
+ *
111
+ * Les valeurs longues sont coupées : une frise doit se parcourir, pas se
112
+ * lire mot à mot.
113
+ */
114
+ export function summarize(value: unknown, max = 80): string {
115
+ if (value === undefined || value === null) return '—'
116
+ const text = typeof value === 'string' ? value : JSON.stringify(value)
117
+ const flat = text.replace(/\s+/g, ' ').trim()
118
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat
119
+ }
120
+
121
+ /* --- Comparaison mot à mot --- */
122
+
123
+ export interface Segment {
124
+ text: string
125
+ kind: 'same' | 'added' | 'removed'
126
+ }
127
+
128
+ const WORDS = /(\s+|[.,;:!?()[\]{}'"«»—–-])/
129
+
130
+ const tokenize = (text: string): string[] => text.split(WORDS).filter((part) => part !== '')
131
+
132
+ /**
133
+ * Découpe deux textes en segments communs, ajoutés et retirés.
134
+ *
135
+ * Signaler « ce champ a changé » ne dit pas *ce qui* a changé : sur une meta
136
+ * description, l'œil doit tomber sur les deux mots remplacés, pas relire la
137
+ * phrase entière.
138
+ *
139
+ * Plus longue sous-séquence commune, au mot. Coût quadratique, borné par
140
+ * `limit` : au-delà, on rend les deux textes en bloc plutôt que de faire
141
+ * ramer le Studio sur un champ de dix mille mots.
142
+ */
143
+ export function diffWords(before: string, after: string, limit = 400): Segment[] {
144
+ const left = tokenize(before)
145
+ const right = tokenize(after)
146
+
147
+ if (left.length > limit || right.length > limit) {
148
+ const segments: Segment[] = []
149
+ if (before) segments.push({text: before, kind: 'removed'})
150
+ if (after) segments.push({text: after, kind: 'added'})
151
+ return segments
152
+ }
153
+
154
+ // table[i][j] : longueur de la plus longue sous-séquence commune des
155
+ // suffixes left[i..] et right[j..].
156
+ const table: number[][] = Array.from({length: left.length + 1}, () =>
157
+ new Array<number>(right.length + 1).fill(0),
158
+ )
159
+ for (let i = left.length - 1; i >= 0; i -= 1) {
160
+ for (let j = right.length - 1; j >= 0; j -= 1) {
161
+ table[i]![j] =
162
+ left[i] === right[j]
163
+ ? (table[i + 1]![j + 1] ?? 0) + 1
164
+ : Math.max(table[i + 1]![j] ?? 0, table[i]![j + 1] ?? 0)
165
+ }
166
+ }
167
+
168
+ const segments: Segment[] = []
169
+ const push = (text: string, kind: Segment['kind']) => {
170
+ const last = segments[segments.length - 1]
171
+ // Les segments voisins de même nature sont fusionnés : un mot par <span>
172
+ // multiplierait les nœuds sans rien apporter à la lecture.
173
+ if (last && last.kind === kind) last.text += text
174
+ else segments.push({text, kind})
175
+ }
176
+
177
+ let i = 0
178
+ let j = 0
179
+ while (i < left.length && j < right.length) {
180
+ if (left[i] === right[j]) {
181
+ push(left[i] as string, 'same')
182
+ i += 1
183
+ j += 1
184
+ } else if ((table[i + 1]![j] ?? 0) >= (table[i]![j + 1] ?? 0)) {
185
+ push(left[i] as string, 'removed')
186
+ i += 1
187
+ } else {
188
+ push(right[j] as string, 'added')
189
+ j += 1
190
+ }
191
+ }
192
+ while (i < left.length) push(left[i++] as string, 'removed')
193
+ while (j < right.length) push(right[j++] as string, 'added')
194
+
195
+ return segments
196
+ }
197
+
198
+ /** Une comparaison mot à mot n'a de sens qu'entre deux textes. */
199
+ export const isTextChange = (before: unknown, after: unknown): boolean =>
200
+ typeof before === 'string' && typeof after === 'string'
@@ -0,0 +1,124 @@
1
+ import type {BoardEdge, BoardNode, Positioned} from './graph'
2
+
3
+ /** Gabarit d'un nœud en vue arborescence. Doit rester synchrone avec PageNode. */
4
+ export const NODE_WIDTH = 220
5
+ export const NODE_HEIGHT = 168
6
+
7
+ /**
8
+ * Gabarit d'une carte portant une capture.
9
+ *
10
+ * Toutes les cartes ont la même taille, et la capture défile à l'intérieur.
11
+ * Adapter la hauteur au format de chaque page semblait plus fidèle, mais le
12
+ * ratio n'est connu qu'une fois l'image chargée : le placement se calculait
13
+ * sur des tailles provisoires puis devait se rejouer, les cartes se
14
+ * recouvraient et le canvas sautait. Une taille fixe rend le placement juste
15
+ * du premier coup.
16
+ */
17
+ export const SHOT_NODE_WIDTH = 280
18
+ export const SHOT_NODE_HEIGHT = 300
19
+
20
+ /** Gabarit compact de la vue cerveau : une pastille, pas une carte. */
21
+ export const BRAIN_NODE_SIZE = 56
22
+
23
+ export type LayoutMode = 'tree' | 'brain'
24
+
25
+ const TREE_OPTIONS: Record<string, string> = {
26
+ 'elk.algorithm': 'layered',
27
+ // Le flux des liens se lit de haut en bas.
28
+ 'elk.direction': 'DOWN',
29
+ 'elk.layered.spacing.nodeNodeBetweenLayers': '90',
30
+ 'elk.spacing.nodeNode': '48',
31
+ 'elk.layered.nodePlacement.strategy': 'BRANDES_KOEPF',
32
+ // Les pages orphelines forment leurs propres composantes : les espacer
33
+ // évite qu'elles se superposent au graphe principal.
34
+ 'elk.spacing.componentComponent': '120',
35
+ 'elk.separateConnectedComponents': 'true',
36
+ }
37
+
38
+ /**
39
+ * Vue « cerveau ». `stress` répartit les nœuds selon la distance dans le
40
+ * graphe : les pages très liées se regroupent, les isolées s'écartent — le
41
+ * rendu attendu d'un graphe de connaissances.
42
+ */
43
+ const BRAIN_OPTIONS: Record<string, string> = {
44
+ 'elk.algorithm': 'stress',
45
+ 'elk.stress.desiredEdgeLength': '220',
46
+ 'elk.spacing.nodeNode': '40',
47
+ 'elk.separateConnectedComponents': 'true',
48
+ 'elk.spacing.componentComponent': '140',
49
+ }
50
+
51
+ export interface LayoutOptions {
52
+ mode: LayoutMode
53
+ /** Tailles manuelles par nœud, pour que le placement en tienne compte. */
54
+ sizes?: ReadonlyMap<string, {width: number; height: number}>
55
+ /** Des captures sont disponibles : les nœuds passent en portrait. */
56
+ withScreenshots?: boolean
57
+ }
58
+
59
+ export function defaultNodeSize(
60
+ mode: LayoutMode,
61
+ withScreenshots = false,
62
+ ): {width: number; height: number} {
63
+ if (mode === 'brain') return {width: BRAIN_NODE_SIZE, height: BRAIN_NODE_SIZE}
64
+ return withScreenshots
65
+ ? {width: SHOT_NODE_WIDTH, height: SHOT_NODE_HEIGHT}
66
+ : {width: NODE_WIDTH, height: NODE_HEIGHT}
67
+ }
68
+
69
+ /**
70
+ * Placement automatique. elkjs pèse 1,5 Mo : il est importé à la demande et
71
+ * jamais au chargement du Studio.
72
+ */
73
+ export async function layoutGraph(
74
+ nodes: readonly BoardNode[],
75
+ edges: readonly BoardEdge[],
76
+ options: LayoutOptions,
77
+ ): Promise<Positioned[]> {
78
+ if (nodes.length === 0) return []
79
+
80
+ const {default: ELK} = await import('elkjs/lib/elk.bundled.js')
81
+ const elk = new ELK()
82
+ const fallbackSize = defaultNodeSize(options.mode, options.withScreenshots)
83
+
84
+ const result = await elk.layout({
85
+ id: 'root',
86
+ layoutOptions: options.mode === 'brain' ? BRAIN_OPTIONS : TREE_OPTIONS,
87
+ children: nodes.map((node) => {
88
+ const size = options.sizes?.get(node.id) ?? fallbackSize
89
+ return {id: node.id, width: size.width, height: size.height}
90
+ }),
91
+ edges: edges.map((edge) => ({
92
+ id: edge.id,
93
+ sources: [edge.source],
94
+ targets: [edge.target],
95
+ })),
96
+ })
97
+
98
+ return (result.children ?? []).map((child) => ({
99
+ id: child.id,
100
+ position: {x: child.x ?? 0, y: child.y ?? 0},
101
+ }))
102
+ }
103
+
104
+ /**
105
+ * Placement de repli, sans elkjs : une grille par profondeur. Sert quand le
106
+ * calcul échoue, pour que le board affiche quand même quelque chose de lisible
107
+ * plutôt qu'un tas de nœuds empilés à l'origine.
108
+ */
109
+ export function fallbackLayout(
110
+ nodes: readonly BoardNode[],
111
+ mode: LayoutMode = 'tree',
112
+ withScreenshots = false,
113
+ ): Positioned[] {
114
+ const {width, height} = defaultNodeSize(mode, withScreenshots)
115
+ const perDepth = new Map<number, number>()
116
+ return nodes.map((node) => {
117
+ const index = perDepth.get(node.depth) ?? 0
118
+ perDepth.set(node.depth, index + 1)
119
+ return {
120
+ id: node.id,
121
+ position: {x: index * (width + 48), y: node.depth * (height + 90)},
122
+ }
123
+ })
124
+ }