@nocode-factory/sanity-kit 2.60.0 → 2.61.1-rc.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.
@@ -4,9 +4,10 @@ import {useDocuments, type SanityNode} from '@sanity/visual-editing'
4
4
  import {at, set, unset} from '@sanity/mutate'
5
5
  import {getAtPath, parse} from '@sanity/mutate/path'
6
6
  import {vercelStegaClean, vercelStegaDecode} from '@vercel/stega'
7
- import {inheritedListValue, materializeInheritedList} from './inherited'
7
+ import {coveringEntry, inheritedListValue, materializeInheritedList, parsePath, readAt, writeAt} from './inherited'
8
8
  import {ACCENT, CHIP, FONT, type PreviewEditingLabels} from './labels'
9
- import {inlineEdit, isEditMode, isSpanTextPath, type InlineTarget} from './store'
9
+ import {READ_DEFAULTS_MESSAGE, READ_DEFAULTS_RESULT} from './protocol'
10
+ import {inlineEdit, isEditMode, isSpanTextPath, stegaRuns, type InlineTarget} from './store'
10
11
 
11
12
  /**
12
13
  * Éditeur de texte SUR PLACE : au clic sur un texte modifiable, un champ de
@@ -24,7 +25,11 @@ export function InlineTextEditor({labels}: {labels: PreviewEditingLabels}) {
24
25
  const onClick = (event: MouseEvent) => {
25
26
  if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
26
27
  if (!isEditMode()) return
27
- const hovered = inlineEdit.getHovered() ?? inheritedListTarget(event.target)
28
+ const direct = inlineEdit.getHovered() ?? inheritedListTarget(event.target)
29
+ // Texte en plusieurs paragraphes (un seul champ, rendu en <p> successifs) : Sanity
30
+ // n'encadre que le dernier (ses marqueurs sont à la fin du texte). Un clic sur
31
+ // n'importe quel paragraphe ouvre le texte entier, sur tout le bloc.
32
+ const hovered = (direct && paragraphGroup(direct)) ?? direct ?? paragraphGroupAt(event.target)
28
33
  if (!hovered || !(event.target instanceof Node) || !hovered.element.contains(event.target)) return
29
34
  if (inlineEdit.getEditing()?.element === hovered.element) return
30
35
  event.preventDefault()
@@ -38,6 +43,67 @@ export function InlineTextEditor({labels}: {labels: PreviewEditingLabels}) {
38
43
  return createPortal(<EditorSession key={`${target.node.id}:${target.node.path}`} target={target} labels={labels} />, document.body)
39
44
  }
40
45
 
46
+ /* ------------------------------------------------------------------------- */
47
+ /* Texte en plusieurs paragraphes */
48
+ /* ------------------------------------------------------------------------- */
49
+
50
+ const BLOCK = 'p, li, blockquote, h1, h2, h3, h4, h5, h6'
51
+
52
+ /** L'élément (ou le premier qui porte du texte) affiche-t-il les retours à la ligne ? */
53
+ function keepsLineBreaks(element: HTMLElement): boolean {
54
+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, {
55
+ acceptNode: (n) => (n.textContent?.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP),
56
+ })
57
+ const host = (walker.nextNode()?.parentElement as HTMLElement | null) ?? element
58
+ return /^(pre|pre-wrap|pre-line|break-spaces)$/.test(getComputedStyle(host).whiteSpace) || /^(pre|pre-wrap|pre-line|break-spaces)$/.test(getComputedStyle(element).whiteSpace)
59
+ }
60
+
61
+ /** Un seul texte marqué (stega) dans l'élément ? Renvoie son nœud Sanity. */
62
+ function singleStegaNode(el: Element): SanityNode | null {
63
+ const text = el.textContent ?? ''
64
+ if (stegaRuns(text) !== 1) return null
65
+ const info = vercelStegaDecode(text) as {href?: string} | undefined
66
+ if (!info?.href) return null
67
+ const href = decodeURIComponent(info.href)
68
+ const id = /[;/]id=([^;?]+)/.exec(href)?.[1]?.replace(/^drafts\./, '')
69
+ const type = /;type=([^;?]+)/.exec(href)?.[1]
70
+ const path = /;path=([^;?]+)/.exec(href)?.[1]
71
+ if (!id || !path || /(^|\.)alt$|\.current$|\.children\[[^\]]+\]\.text$/.test(path)) return null
72
+ return {id, type, path} as SanityNode
73
+ }
74
+
75
+ /**
76
+ * Bloc de paragraphes d'un même champ : le parent direct qui contient au moins deux
77
+ * blocs (p, li...) et UN SEUL texte marqué (celui du champ, à la fin du dernier bloc).
78
+ */
79
+ function groupOf(block: Element): InlineTarget | null {
80
+ const parent = block.parentElement
81
+ if (!parent || parent === document.body) return null
82
+ const blocks = Array.from(parent.children).filter((c) => c.matches(BLOCK))
83
+ if (blocks.length < 2 || !blocks.includes(block)) return null
84
+ // Mêmes balises (un texte en paragraphes), et le marqueur dans le DERNIER bloc.
85
+ if (blocks.some((b) => b.tagName !== block.tagName)) return null
86
+ const last = blocks[blocks.length - 1]!
87
+ if (stegaRuns(last.textContent ?? '') !== 1) return null
88
+ const node = singleStegaNode(parent)
89
+ const expect = vercelStegaClean(block.textContent ?? '').replace(/\s+/g, ' ').trim()
90
+ return node && parent instanceof HTMLElement ? {element: parent, node, expect} : null
91
+ }
92
+
93
+ /** Cible déjà trouvée (dernier paragraphe) : élargie au bloc entier quand c'en est un. */
94
+ function paragraphGroup(target: InlineTarget): InlineTarget | null {
95
+ const block = target.element.matches(BLOCK) ? target.element : target.element.closest(BLOCK)
96
+ const group = block ? groupOf(block) : null
97
+ return group && group.node.path === target.node.path ? group : null
98
+ }
99
+
100
+ /** Clic sur un paragraphe SANS marqueur (pas le dernier) : le bloc dont il fait partie. */
101
+ function paragraphGroupAt(target: EventTarget | null): InlineTarget | null {
102
+ const block = target instanceof Element ? target.closest(BLOCK) : null
103
+ if (!block || stegaRuns(block.textContent ?? '') > 0) return null
104
+ return groupOf(block)
105
+ }
106
+
41
107
  /* ------------------------------------------------------------------------- */
42
108
  /* Valeurs héritées jointes à la page (inheritedEditScriptProps) */
43
109
  /* ------------------------------------------------------------------------- */
@@ -57,6 +123,58 @@ function inheritedListFor(path: string): InheritedListData | null {
57
123
  return null
58
124
  }
59
125
 
126
+ type SourceEntry = {path: string; source: {id: string; path: string}}
127
+
128
+ /** Origine du Studio qui affiche l'aperçu. */
129
+ function studioOrigin(): string | null {
130
+ const ancestor = window.location.ancestorOrigins?.[0]
131
+ if (ancestor) return ancestor
132
+ try {
133
+ return document.referrer ? new URL(document.referrer).origin : null
134
+ } catch {
135
+ return null
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Valeur BRUTE d'un champ des valeurs par défaut, lue par le Studio (le document des
141
+ * valeurs par défaut n'est pas un document de la page : l'aperçu ne peut pas le lire
142
+ * lui-même). undefined si le Studio ne répond pas (4 s) ou ne trouve rien.
143
+ */
144
+ function readDefaults(id: string, path: string): Promise<unknown> {
145
+ const origin = studioOrigin()
146
+ if (!origin || window.parent === window) return Promise.resolve(undefined)
147
+ const requestId = `${Date.now()}-${Math.random().toString(36).slice(2)}`
148
+ return new Promise((done) => {
149
+ const timer = window.setTimeout(() => finish(undefined), 4000)
150
+ const onMessage = (event: MessageEvent) => {
151
+ const d = event.data as {type?: string; requestId?: string; value?: unknown; found?: boolean} | null
152
+ if (event.origin !== origin || event.source !== window.parent || d?.type !== READ_DEFAULTS_RESULT || d.requestId !== requestId) return
153
+ finish(d.found ? d.value : undefined)
154
+ }
155
+ const finish = (value: unknown) => {
156
+ window.clearTimeout(timer)
157
+ window.removeEventListener('message', onMessage)
158
+ done(value)
159
+ }
160
+ window.addEventListener('message', onMessage)
161
+ window.parent.postMessage({type: READ_DEFAULTS_MESSAGE, requestId, id, path}, origin)
162
+ })
163
+ }
164
+
165
+ /** Valeur héritée de toute forme : entrée qui couvre ce chemin (source brute des valeurs par défaut). */
166
+ function inheritedSourceFor(path: string): {entry: SourceEntry; rest: string} | null {
167
+ const entries: SourceEntry[] = []
168
+ for (const script of document.querySelectorAll<HTMLScriptElement>('script[data-ncf-inherited-source]')) {
169
+ try {
170
+ entries.push({path: script.dataset.ncfInheritedSource ?? '', source: JSON.parse(script.textContent ?? 'null')})
171
+ } catch {
172
+ // Entrée illisible : ignorée.
173
+ }
174
+ }
175
+ return coveringEntry(entries.filter((e) => e.path && e.source?.id && e.source?.path), path)
176
+ }
177
+
60
178
  function inheritedValueFor(path: string): string | null {
61
179
  for (const script of document.querySelectorAll<HTMLScriptElement>('script[data-ncf-inherited-value]')) {
62
180
  if (script.dataset.ncfInheritedValue !== path) continue
@@ -84,7 +202,7 @@ function inheritedListTarget(target: EventTarget | null): InlineTarget | null {
84
202
  const id = /[;/]id=([^;?]+)/.exec(href)?.[1]?.replace(/^drafts\./, '')
85
203
  const type = /;type=([^;?]+)/.exec(href)?.[1]
86
204
  const path = /;path=([^;?]+)/.exec(href)?.[1]
87
- if (!id || !path || !inheritedListFor(path) || !(el instanceof HTMLElement)) return null
205
+ if (!id || !path || !(inheritedListFor(path) || inheritedSourceFor(path)) || !(el instanceof HTMLElement)) return null
88
206
  return {element: el, node: {id, type, path} as SanityNode}
89
207
  }
90
208
  return null
@@ -147,7 +265,10 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
147
265
  const initial = useRef('')
148
266
  // Texte de départ d'un texte hérité (valeur par défaut) : inchangé = rien à enregistrer.
149
267
  const inheritedStart = useRef('')
268
+ // Valeur héritée de toute forme : brute (valeurs par défaut), à recopier dans la page.
269
+ const rawInherited = useRef<{path: string; raw: unknown; rest: string} | null>(null)
150
270
  const multiline = useRef(false)
271
+ const [breaks, setBreaks] = useState(false)
151
272
  const rootRef = useRef<HTMLDivElement>(null)
152
273
  const fieldRef = useRef<HTMLTextAreaElement>(null)
153
274
 
@@ -179,17 +300,43 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
179
300
  let cancelled = false
180
301
  getDocument(node.id)
181
302
  .getSnapshot()
182
- .then((doc) => {
303
+ .then(async (doc) => {
183
304
  if (cancelled) return
184
305
  const stored = doc ? getAtPath(parse(node.path), doc) : undefined
185
306
  const list = inheritedListFor(node.path)
186
- const text =
307
+ // Valeur héritée de toute forme : la valeur BRUTE des valeurs par défaut, gardée
308
+ // pour la recopie à l'enregistrement (si la page n'a toujours rien à cet endroit).
309
+ const covering = typeof stored === 'string' && stored !== '' ? null : inheritedSourceFor(node.path)
310
+ let fromSource: string | null = null
311
+ if (covering) {
312
+ const own = doc ? readAt(doc, parsePath(covering.entry.path) ?? []) : undefined
313
+ const empty = own === undefined || (Array.isArray(own) && own.length === 0)
314
+ const raw = empty ? await readDefaults(covering.entry.source.id, covering.entry.source.path).catch(() => undefined) : undefined
315
+ if (raw !== undefined) {
316
+ rawInherited.current = {path: covering.entry.path, raw, rest: covering.rest}
317
+ const v = readAt(raw, parsePath(covering.rest) ?? [])
318
+ fromSource = typeof v === 'string' ? v : null
319
+ }
320
+ }
321
+ if (cancelled) return
322
+ const resolved =
187
323
  typeof stored === 'string' && stored !== ''
188
324
  ? stored
189
- : (inheritedValueFor(node.path) ?? (list ? inheritedListValue(list, node.path) : null) ?? vercelStegaClean(element.textContent ?? '').trim())
325
+ : (fromSource ?? inheritedValueFor(node.path) ?? (list ? inheritedListValue(list, node.path) : null) ?? vercelStegaClean(element.textContent ?? '').trim())
326
+ // Bloc de paragraphes : le paragraphe cliqué doit faire partie de ce texte (sinon
327
+ // c'était un texte voisin, hors champ : on n'ouvre rien).
328
+ if (target.expect && !resolved.replace(/\s+/g, ' ').includes(target.expect)) {
329
+ inlineEdit.close()
330
+ return
331
+ }
332
+ const text = resolved
190
333
  initial.current = typeof stored === 'string' ? stored : ''
191
334
  inheritedStart.current = text
192
- multiline.current = text.includes('\n')
335
+ // Retour à la ligne (Maj + Entrée) permis quand le texte peut l'afficher : il en a
336
+ // déjà, c'est un bloc de paragraphes, ou l'élément garde les retours à la ligne
337
+ // (white-space: pre-line / pre-wrap / pre). Un titre sur une ligne n'en reçoit pas.
338
+ multiline.current = text.includes('\n') || !!target.expect || keepsLineBreaks(element)
339
+ setBreaks(multiline.current)
193
340
  setInherited(typeof stored !== 'string' || stored === '')
194
341
  setValue(text)
195
342
  setStatus('editing')
@@ -200,7 +347,7 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
200
347
  return () => {
201
348
  cancelled = true
202
349
  }
203
- }, [getDocument, node.id, node.path, element])
350
+ }, [getDocument, node.id, node.path, element, target.expect])
204
351
 
205
352
  useEffect(() => {
206
353
  if (status !== 'editing') return
@@ -241,9 +388,23 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
241
388
  }
242
389
  // Ligne d'une liste héritée que la page n'a pas encore : la liste par défaut est
243
390
  // recopiée dans la page avec cette ligne modifiée (même enregistrement).
391
+ const doc = getDocument(node.id)
392
+ // Valeur héritée de toute forme : la valeur brute des valeurs par défaut est recopiée
393
+ // dans la page avec ce texte modifié, en un seul enregistrement.
394
+ const copy = inherited && rawInherited.current ? writeAt(rawInherited.current.raw, parsePath(rawInherited.current.rest) ?? [], next) : null
395
+ if (copy !== null && rawInherited.current) {
396
+ doc.patch([at(rawInherited.current.path, set(copy))])
397
+ setStatus('saving')
398
+ return
399
+ }
244
400
  const list = inherited ? inheritedListFor(node.path) : null
245
401
  const items = list ? materializeInheritedList(list, node.path, next) : null
246
- const doc = getDocument(node.id)
402
+ // Héritée d'une valeur que la page n'a pas encore, sans valeur brute lisible (Studio
403
+ // trop ancien, réseau) : rien n'est écrit plutôt qu'un enregistrement incomplet.
404
+ if (inherited && !items && inheritedSourceFor(node.path)) {
405
+ inlineEdit.close()
406
+ return
407
+ }
247
408
  if (list && items) doc.patch([at(list.path, set(items))])
248
409
  // Morceau de texte riche : jamais retiré (un morceau sans texte casse le bloc), vidé.
249
410
  else if (isSpanTextPath(node.path)) doc.patch([at(node.path, set(next))])
@@ -331,6 +492,12 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
331
492
  {labels.save}
332
493
  <kbd style={KBD_STYLE}>↵</kbd>
333
494
  </button>
495
+ {breaks && (
496
+ <span style={{display: 'flex', alignItems: 'center', gap: 6, padding: '7px 8px', color: 'rgba(255,255,255,0.7)'}}>
497
+ {labels.newLine}
498
+ <kbd style={KBD_STYLE}>⇧ ↵</kbd>
499
+ </span>
500
+ )}
334
501
  <button type="button" onClick={() => inlineEdit.close()} style={{...BUTTON_STYLE, background: 'transparent', color: 'rgba(255,255,255,0.85)'}}>
335
502
  {labels.cancel}
336
503
  <kbd style={KBD_STYLE}>Esc</kbd>
@@ -1,5 +1,6 @@
1
1
  import {useEffect, useRef, useState} from 'react'
2
2
  import type {OverlayComponentResolver} from '@sanity/visual-editing'
3
+ import {EditAudit} from './EditAudit'
3
4
  import {ImageReplaceLayer} from './ImageReplaceLayer'
4
5
  import {InlineTextEditor} from './InlineTextEditor'
5
6
  import {InlineTextOverlay} from './InlineTextOverlay'
@@ -31,7 +32,7 @@ export type NcfPreviewEditingProps = {
31
32
  labels?: Partial<PreviewEditingLabels>
32
33
  /**
33
34
  * `'toggle'` (défaut) : interrupteur « Edit mode / Browse mode » du kit, en bas
34
- * à gauche de l'aperçu, mémorisé. Une fonction : le projet décide (ex. son propre
35
+ * à droite de l'aperçu, mémorisé. Une fonction : le projet décide (ex. son propre
35
36
  * interrupteur d'animations) ; le kit n'affiche alors rien.
36
37
  */
37
38
  editMode?: 'toggle' | (() => boolean)
@@ -80,6 +81,7 @@ export function NcfPreviewEditing({labels, editMode = 'toggle'}: NcfPreviewEditi
80
81
  <style>{EDIT_CSS}</style>
81
82
  <InlineTextEditor labels={text} />
82
83
  <ImageReplaceLayer label={text.replaceImage} />
84
+ <EditAudit labels={text} />
83
85
  {!hasCustom && <EditModeToggle labels={text} />}
84
86
  </>
85
87
  )
@@ -132,7 +134,7 @@ function EditModeToggle({labels}: {labels: PreviewEditingLabels}) {
132
134
  data-sanity-overlay-element
133
135
  style={{
134
136
  position: 'fixed',
135
- left: 16,
137
+ right: 16,
136
138
  bottom: 16,
137
139
  zIndex: 2147482500,
138
140
  display: 'flex',
@@ -27,7 +27,17 @@ import {createEditUrl} from '@sanity/client/csm'
27
27
  * (`<script type="application/json" data-ncf-inherited-…>`, voir
28
28
  * `inheritedEditScriptProps`).
29
29
  */
30
- export type InheritedEdit = {path: string; items: Record<string, unknown>[]} | {path: string; value: string}
30
+ export type InheritedEdit =
31
+ | {path: string; items: Record<string, unknown>[]}
32
+ | {path: string; value: string}
33
+ /**
34
+ * Valeur héritée de N'IMPORTE QUELLE forme (liste avec images, liens, texte riche,
35
+ * objet) : sa source BRUTE est le champ du document des valeurs par défaut
36
+ * (`source.id`, `source.path`), relu tel qu'enregistré au moment de la recopie (jamais
37
+ * la version projetée par la requête du site, qui peut porter des champs vides ou
38
+ * résolus). Même recopie que « Edit default items » du kit.
39
+ */
40
+ | {path: string; source: {id: string; path: string}}
31
41
 
32
42
  type Source = {id: string; type: string}
33
43
 
@@ -68,7 +78,7 @@ function isPlainBlocks(value: unknown): value is Block[] {
68
78
  }
69
79
 
70
80
  /** Réétiquette un texte (stega) vers un autre chemin du document de la page. */
71
- function retag(text: string, source: Source, path: string): string {
81
+ export function retag(text: string, source: Source, path: string): string {
72
82
  const info = vercelStegaDecode(text) as {origin?: string; href?: string} | undefined
73
83
  if (!info?.href) return text
74
84
  const url = new URL(info.href, 'https://studio.invalid')
@@ -114,8 +124,8 @@ export function retagInheritedList(value: unknown, listPath: string, source: Sou
114
124
  export function inheritedEditScriptProps(entry: InheritedEdit) {
115
125
  return {
116
126
  type: 'application/json',
117
- ...('items' in entry ? {'data-ncf-inherited-list': entry.path} : {'data-ncf-inherited-value': entry.path}),
118
- dangerouslySetInnerHTML: {__html: JSON.stringify('items' in entry ? entry.items : entry.value).replace(/</g, '\\u003c')},
127
+ ...('items' in entry ? {'data-ncf-inherited-list': entry.path} : 'source' in entry ? {'data-ncf-inherited-source': entry.path} : {'data-ncf-inherited-value': entry.path}),
128
+ dangerouslySetInnerHTML: {__html: JSON.stringify('items' in entry ? entry.items : 'source' in entry ? entry.source : entry.value).replace(/</g, '\\u003c')},
119
129
  }
120
130
  }
121
131
 
@@ -172,3 +182,65 @@ export function materializeInheritedList(list: {path: string; items: Record<stri
172
182
  return null
173
183
  }
174
184
  }
185
+
186
+ /* ------------------------------------------------------------------------- */
187
+ /* Chemins Sanity : lecture et écriture dans une valeur brute (pur, testé) */
188
+ /* ------------------------------------------------------------------------- */
189
+
190
+ export type PathStep = {key: string} | {index: number} | {field: string}
191
+
192
+ /** `sections[_key=="a"].items[2].title` → étapes ; null si le chemin est illisible. */
193
+ export function parsePath(path: string): PathStep[] | null {
194
+ const out: PathStep[] = []
195
+ let consumed = 0
196
+ for (const m of path.matchAll(/\[_key=="([^"]+)"\]|\[(\d+)\]|\.?([A-Za-z_][\w-]*)/g)) {
197
+ if (m.index !== consumed) return null
198
+ consumed += m[0].length
199
+ out.push(m[1] !== undefined ? {key: m[1]} : m[2] !== undefined ? {index: Number(m[2])} : {field: m[3] as string})
200
+ }
201
+ return consumed === path.length && out.length ? out : null
202
+ }
203
+
204
+ /** Valeur au chemin (étapes), ou undefined. */
205
+ export function readAt(root: unknown, steps: PathStep[]): unknown {
206
+ let value = root
207
+ for (const step of steps) {
208
+ if ('key' in step) value = Array.isArray(value) ? value.find((v) => v?._key === step.key) : undefined
209
+ else if ('index' in step) value = Array.isArray(value) ? value[step.index] : undefined
210
+ else value = value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>)[step.field] : undefined
211
+ if (value === undefined) return undefined
212
+ }
213
+ return value
214
+ }
215
+
216
+ /** Copie de `root` avec `next` écrit au chemin ; null si un élément du chemin manque. */
217
+ export function writeAt(root: unknown, steps: PathStep[], next: unknown): unknown {
218
+ const write = (value: unknown, i: number): unknown => {
219
+ if (i === steps.length) return next
220
+ const step = steps[i]!
221
+ if ('key' in step || 'index' in step) {
222
+ if (!Array.isArray(value)) throw new Error('absent')
223
+ const at = 'key' in step ? value.findIndex((v) => v?._key === step.key) : step.index
224
+ if (at < 0 || at >= value.length) throw new Error('absent')
225
+ return value.map((v, j) => (j === at ? write(v, i + 1) : v))
226
+ }
227
+ if (value !== undefined && (typeof value !== 'object' || value === null || Array.isArray(value))) throw new Error('absent')
228
+ if (value === undefined && i < steps.length - 1 && !('field' in steps[i + 1]!)) throw new Error('absent')
229
+ const obj = (value ?? {}) as Record<string, unknown>
230
+ return {...obj, [step.field]: write(obj[step.field], i + 1)}
231
+ }
232
+ try {
233
+ return write(root, 0)
234
+ } catch {
235
+ return null
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Entrée héritée qui couvre `path` (le chemin d'un texte ou d'une image dans la page) :
241
+ * son chemin est un préfixe exact (suivi de `[` ou `.`). Renvoie aussi le reste du chemin.
242
+ */
243
+ export function coveringEntry<T extends {path: string}>(entries: T[], path: string): {entry: T; rest: string} | null {
244
+ const entry = entries.filter((e) => path.startsWith(`${e.path}[`) || path.startsWith(`${e.path}.`)).sort((a, b) => b.path.length - a.path.length)[0]
245
+ return entry ? {entry, rest: path.slice(entry.path.length)} : null
246
+ }
@@ -17,6 +17,11 @@ export type PreviewEditingLabels = {
17
17
  editMode: string
18
18
  browseMode: string
19
19
  modeLabel: string
20
+ /** Indication sous un texte à plusieurs lignes : Maj + Entrée = retour à la ligne. */
21
+ newLine: string
22
+ /** Contrôle automatique : « {n} à vérifier » (éléments non modifiables sur place). */
23
+ auditIssues: string
24
+ auditHelp: string
20
25
  }
21
26
 
22
27
  export const DEFAULT_PREVIEW_EDITING_LABELS: PreviewEditingLabels = {
@@ -29,6 +34,9 @@ export const DEFAULT_PREVIEW_EDITING_LABELS: PreviewEditingLabels = {
29
34
  editMode: 'Edit mode',
30
35
  browseMode: 'Browse mode',
31
36
  modeLabel: 'Preview mode: edit or browse',
37
+ newLine: 'New line',
38
+ auditIssues: '{n} to check',
39
+ auditHelp: 'Elements of this page that cannot be edited in place (click to outline them in red)',
32
40
  }
33
41
 
34
42
  /** Couleurs : surchargeables par le projet (variables CSS sur :root). */
@@ -15,6 +15,12 @@ export type ReplaceImageRequest = {
15
15
  documentType: string | null
16
16
  /** Chemin EXACT du champ image (`sections[_key=="a"].items[_key=="b"].image`). */
17
17
  path: string
18
+ /**
19
+ * Image DANS une valeur héritée des valeurs par défaut (liste...) que la page n'a pas
20
+ * encore : le champ `path` de la page reçoit d'abord la valeur brute du champ
21
+ * `sourcePath` du document `sourceId` (recopie, comme « Edit default items »).
22
+ */
23
+ inherited?: {path: string; sourceId: string; sourcePath: string} | null
18
24
  }
19
25
 
20
26
  /** Chemin de champ Sanity sûr : lettres, chiffres, clés entre guillemets, rien d'autre. */
@@ -30,10 +36,17 @@ export function isReplaceImageRequest(data: unknown): data is ReplaceImageReques
30
36
  d.documentId.length > 0 &&
31
37
  typeof d.path === 'string' &&
32
38
  SAFE_PATH.test(d.path) &&
33
- (d.documentType === null || d.documentType === undefined || typeof d.documentType === 'string')
39
+ (d.documentType === null || d.documentType === undefined || typeof d.documentType === 'string') &&
40
+ (d.inherited === null || d.inherited === undefined || isInherited(d.inherited))
34
41
  )
35
42
  }
36
43
 
44
+ function isInherited(v: unknown): v is NonNullable<ReplaceImageRequest['inherited']> {
45
+ if (!v || typeof v !== 'object') return false
46
+ const i = v as Record<string, unknown>
47
+ return typeof i.path === 'string' && SAFE_PATH.test(i.path) && typeof i.sourcePath === 'string' && SAFE_PATH.test(i.sourcePath) && typeof i.sourceId === 'string' && /^[\w.-]+$/.test(i.sourceId)
48
+ }
49
+
37
50
  /**
38
51
  * Patch du remplacement : l'image choisie remplace celle du champ. Cadrage et
39
52
  * point focal sont retirés : calés sur l'ancienne photo, ils seraient faux.
@@ -45,3 +58,20 @@ export function replaceImagePatch(path: string, assetId: string) {
45
58
  {unset: [`${path}.crop`, `${path}.hotspot`]},
46
59
  ]
47
60
  }
61
+
62
+ /**
63
+ * Lecture d'une valeur BRUTE des valeurs par défaut (recopie d'une liste héritée à la
64
+ * première modification d'un texte) : l'aperçu la demande au Studio, qui la lit dans le
65
+ * document (brouillon s'il existe) et répond à la seule fenêtre qui a demandé.
66
+ */
67
+ export const READ_DEFAULTS_MESSAGE = 'ncf-kit/read-defaults'
68
+ export const READ_DEFAULTS_RESULT = 'ncf-kit/read-defaults-result'
69
+
70
+ export type ReadDefaultsRequest = {type: typeof READ_DEFAULTS_MESSAGE; requestId: string; id: string; path: string}
71
+ export type ReadDefaultsResult = {type: typeof READ_DEFAULTS_RESULT; requestId: string; value: unknown; found: boolean}
72
+
73
+ export function isReadDefaultsRequest(data: unknown): data is ReadDefaultsRequest {
74
+ if (!data || typeof data !== 'object') return false
75
+ const d = data as Record<string, unknown>
76
+ return d.type === READ_DEFAULTS_MESSAGE && typeof d.requestId === 'string' && typeof d.id === 'string' && /^[\w.-]+$/.test(d.id) && typeof d.path === 'string' && SAFE_PATH.test(d.path)
77
+ }
@@ -9,7 +9,12 @@ import {VERCEL_STEGA_REGEX} from '@vercel/stega'
9
9
  * des overlays : Sanity démonte ses composants dès que la souris quitte
10
10
  * l'élément, la saisie ne doit pas dépendre du survol.
11
11
  */
12
- export type InlineTarget = {element: HTMLElement; node: SanityNode}
12
+ export type InlineTarget = {
13
+ element: HTMLElement
14
+ node: SanityNode
15
+ /** Bloc de paragraphes : texte du paragraphe cliqué, qui doit figurer dans la valeur. */
16
+ expect?: string
17
+ }
13
18
 
14
19
  let hovered: InlineTarget | null = null
15
20
  let editing: InlineTarget | null = null
@@ -1,7 +1,8 @@
1
1
  import {createDataAttribute} from '@sanity/visual-editing/create-data-attribute'
2
2
  import {resolveEditInfo, studioPath, type ContentSourceMap, type ContentSourceMapParsedPath} from '@sanity/client/csm'
3
3
  import {vercelStegaClean} from '@vercel/stega'
4
- import {retagInheritedList, type InheritedEdit} from './inherited'
4
+ import {retag, retagInheritedList, type InheritedEdit} from './inherited'
5
+ import {vercelStegaDecode} from '@vercel/stega'
5
6
 
6
7
  /**
7
8
  * ÉDITION DANS L'APERÇU, IMAGES (mode brouillon seulement) : chaque image est
@@ -30,9 +31,11 @@ export type ImageEditValue = {
30
31
  _editPath?: string
31
32
  _editDoc?: string
32
33
  _editType?: string
34
+ /** Image héritée DANS une valeur par défaut (liste...) : champ à recopier d'abord. */
35
+ _editInherited?: {path: string; sourceId: string; sourcePath: string}
33
36
  } | null | undefined
34
37
 
35
- type Marked = {asset: {_ref: string}; _editTarget?: string; _editPath?: string; _editDoc?: string; _editType?: string}
38
+ type Marked = {asset: {_ref: string}; _editTarget?: string; _editPath?: string; _editDoc?: string; _editType?: string; _editInherited?: {path: string; sourceId: string; sourcePath: string}; _editDefaults?: {id: string; path: string}}
36
39
  type Segment = ContentSourceMapParsedPath[number]
37
40
 
38
41
  function isImageValue(value: unknown): value is Marked {
@@ -71,10 +74,16 @@ export function annotateImageEditTargets<T>(data: T, sourceMap: ContentSourceMap
71
74
  const defaultsType = options.defaultsType ?? 'componentDefaults'
72
75
  const fromSourceMap = (value: Marked, path: ContentSourceMapParsedPath) => {
73
76
  const info = resolveEditInfo({studioUrl: options.studioUrl, resultSourceMap: sourceMap, resultPath: [...path, 'asset', '_ref']})
74
- if (!info || info.type === defaultsType) return
77
+ if (!info) return
75
78
  const full = typeof info.path === 'string' ? info.path : studioPath.toString(info.path as never)
76
79
  const imagePath = full.replace(/\.asset\._ref$/, '')
77
80
  if (!imagePath || imagePath === full) return
81
+ // Image des valeurs par défaut : pas de repère (il modifierait TOUTES les pages), mais
82
+ // sa source brute, pour la recopier dans la page au remplacement.
83
+ if (info.type === defaultsType) {
84
+ value._editDefaults = {id: info.id.replace(/^drafts\./, ''), path: imagePath}
85
+ return
86
+ }
78
87
  mark(value, info.id, info.type, imagePath, {
79
88
  baseUrl: info.baseUrl,
80
89
  workspace: info.workspace,
@@ -129,18 +138,80 @@ export function withPreviewEditTargets(onInherit: OnInherit, source: Source, key
129
138
  }
130
139
  return (value, path) => {
131
140
  const out = onInherit(value, path)
132
- if (out && typeof out === 'object' && !Array.isArray(out)) {
133
- const copy = isImageValue(out) ? {...out} : out
134
- markInherited(copy, `${base}.${path.join('.')}`)
141
+ const entryPath = `${base}.${path.join('.')}`
142
+ if (typeof out === 'string') {
143
+ collected.push({path: entryPath, value: vercelStegaClean(out)})
144
+ return out
145
+ }
146
+ if (!out || typeof out !== 'object') return out
147
+ // Image héritée seule : elle vise le champ de l'instance (choisir crée l'image de la page).
148
+ if (isImageValue(out)) {
149
+ const copy = {...out}
150
+ markInherited(copy, entryPath)
135
151
  return copy
136
152
  }
137
- if (typeof out === 'string') collected.push({path: `${base}.${path.join('.')}`, value: vercelStegaClean(out)})
138
- // Liste héritée directement par un champ de la section (le parent existe dans la page).
139
- if (Array.isArray(out) && path.length === 1) return retagInheritedList(out, `${base}.${path[0]}`, source, collected)
153
+ // Valeur héritée de N'IMPORTE QUELLE forme (liste, objet) : chaque texte et chaque image
154
+ // vise son chemin EXACT dans la page ; à la première modification, la valeur brute des
155
+ // valeurs par défaut est recopiée dans la page (source lue dans les marqueurs).
156
+ const raw = defaultsSourceOf(value, path[path.length - 1] as string)
157
+ if (raw) {
158
+ collected.push({path: entryPath, source: raw})
159
+ return retagDeep(out, entryPath, {...source, id: pageId}, {path: entryPath, sourceId: raw.id, sourcePath: raw.path}, options)
160
+ }
161
+ // Sans source repérable : l'ancienne règle (listes simples seulement).
162
+ if (Array.isArray(out) && path.length === 1) return retagInheritedList(out, entryPath, source, collected)
163
+ markInherited(out, entryPath)
140
164
  return out
141
165
  }
142
166
  }
143
167
 
168
+ /** Champ des valeurs par défaut d'où vient une valeur héritée : lu dans un texte (stega) ou une image. */
169
+ function defaultsSourceOf(value: unknown, field: string): {id: string; path: string} | null {
170
+ let found: {id: string; full: string} | null = null
171
+ const visit = (v: unknown) => {
172
+ if (found || v === null || v === undefined) return
173
+ if (typeof v === 'string') {
174
+ const info = vercelStegaDecode(v) as {href?: string} | undefined
175
+ if (!info?.href) return
176
+ const href = decodeURIComponent(info.href)
177
+ const id = /[;/]id=([^;?&]+)/.exec(href)?.[1]
178
+ const full = /;path=([^;?&]+)/.exec(href)?.[1]
179
+ if (id && full) found = {id: id.replace(/^drafts\./, ''), full}
180
+ return
181
+ }
182
+ if (Array.isArray(v)) return v.forEach(visit)
183
+ if (typeof v === 'object') {
184
+ const d = (v as Marked)._editDefaults
185
+ if (d) found = {id: d.id, full: d.path}
186
+ else for (const [k, x] of Object.entries(v)) if (!k.startsWith('_')) visit(x)
187
+ }
188
+ }
189
+ visit(value)
190
+ if (!found) return null
191
+ const {id, full} = found as {id: string; full: string}
192
+ // Chemin du champ dans le document des valeurs par défaut : jusqu'au segment `field`.
193
+ const m = new RegExp(`^(.*?(?:^|\\.)${field.replace(/[^\w]/g, '')})(?=[.[]|$)`).exec(full)
194
+ return m?.[1] ? {id, path: m[1]} : null
195
+ }
196
+
197
+ /** Réétiquette chaque texte et marque chaque image d'une valeur héritée, à son chemin exact. */
198
+ function retagDeep(value: unknown, path: string, page: {id: string; type: string}, inherited: {path: string; sourceId: string; sourcePath: string}, options: ImageEditOptions): unknown {
199
+ if (typeof value === 'string') return retag(value, page, path)
200
+ if (Array.isArray(value))
201
+ return value.map((item, index) => {
202
+ const k = item && typeof item === 'object' ? (item as {_key?: unknown})._key : undefined
203
+ return retagDeep(item, typeof k === 'string' ? `${path}[_key=="${k}"]` : `${path}[${index}]`, page, inherited, options)
204
+ })
205
+ if (!value || typeof value !== 'object') return value
206
+ if (isImageValue(value)) {
207
+ const copy: Marked = {...value}
208
+ mark(copy, page.id, page.type, path, {baseUrl: options.studioUrl})
209
+ copy._editInherited = inherited
210
+ return copy
211
+ }
212
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, k.startsWith('_') ? v : retagDeep(v, `${path}.${k}`, page, inherited, options)]))
213
+ }
214
+
144
215
  /**
145
216
  * Chemin EXACT des images qui appartiennent à la page, recalculé avec les clés
146
217
  * `_key` de la section. La carte des sources donne parfois un rang au lieu de la
@@ -168,12 +239,18 @@ export function rekeyOwnImageTargets<T>(section: T, source: Source, key: string
168
239
  return section
169
240
  }
170
241
 
171
- export type ImageEditAttributes = {'data-sanity'?: string; 'data-edit-image'?: string; 'data-edit-doc'?: string; 'data-edit-type'?: string}
242
+ export type ImageEditAttributes = {'data-sanity'?: string; 'data-edit-image'?: string; 'data-edit-doc'?: string; 'data-edit-type'?: string; 'data-edit-inherited'?: string}
172
243
 
173
244
  /** Attributs à poser sur le cadre d'une image marquée ; vide pour les visiteurs. */
174
245
  export function imageEditAttributes(image: ImageEditValue): ImageEditAttributes {
175
246
  if (!image?._editTarget || !image._editPath || !image._editDoc || !image._editType) return {}
176
- return {'data-sanity': image._editTarget, 'data-edit-image': image._editPath, 'data-edit-doc': image._editDoc, 'data-edit-type': image._editType}
247
+ return {
248
+ 'data-sanity': image._editTarget,
249
+ 'data-edit-image': image._editPath,
250
+ 'data-edit-doc': image._editDoc,
251
+ 'data-edit-type': image._editType,
252
+ ...(image._editInherited ? {'data-edit-inherited': JSON.stringify(image._editInherited)} : {}),
253
+ }
177
254
  }
178
255
 
179
256
  /**