@nocode-factory/sanity-kit 2.60.0 → 2.61.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.
@@ -1,7 +1,8 @@
1
1
  import {useEffect, useState} from 'react'
2
2
  import {useClient, useDocumentOperation, type LayoutProps} from 'sanity'
3
3
  import {MediaPickerDialog} from '../form/AssetSourceBrowser'
4
- import {isReplaceImageRequest, replaceImagePatch} from '../web/edit/protocol'
4
+ import {isReplaceImageRequest, replaceImagePatch, type ReplaceImageRequest} from '../web/edit/protocol'
5
+ import {parsePath, readAt} from '../web/edit/inherited'
5
6
  import {HelpTextStyle} from './HelpTextStyle'
6
7
 
7
8
  /**
@@ -15,7 +16,7 @@ import {HelpTextStyle} from './HelpTextStyle'
15
16
  * (`window.frames`), depuis l'origine d'un environnement du kit, est pris en
16
17
  * compte ; il ne fait qu'ouvrir le sélecteur, le choix reste à l'utilisateur.
17
18
  */
18
- type Request = {documentId: string; documentType: string; path: string}
19
+ type Request = {documentId: string; documentType: string; path: string; inherited: ReplaceImageRequest['inherited']}
19
20
 
20
21
  /** Le message vient-il d'une sous-fenêtre de ce Studio ? (le tableau de bord sanity.io encastre le Studio : on parcourt window.frames.) */
21
22
  function fromChildFrame(source: MessageEventSource | null): boolean {
@@ -34,7 +35,7 @@ export function PreviewEditBridge({origins}: {origins: readonly string[]}) {
34
35
  if (!origins.includes(event.origin) || !fromChildFrame(event.source) || !isReplaceImageRequest(event.data)) return
35
36
  const documentId = event.data.documentId.replace(/^drafts\./, '')
36
37
  const documentType = event.data.documentType || (await client.fetch<string | null>('*[_id in [$id, "drafts." + $id]][0]._type', {id: documentId}))
37
- if (documentType) setRequest({documentId, documentType, path: event.data.path})
38
+ if (documentType) setRequest({documentId, documentType, path: event.data.path, inherited: event.data.inherited ?? null})
38
39
  }
39
40
  window.addEventListener('message', onMessage)
40
41
  return () => window.removeEventListener('message', onMessage)
@@ -46,6 +47,29 @@ export function PreviewEditBridge({origins}: {origins: readonly string[]}) {
46
47
 
47
48
  function ReplaceImageDialog({request, onDone}: {request: Request; onDone: () => void}) {
48
49
  const {patch} = useDocumentOperation(request.documentId, request.documentType)
50
+ const client = useClient({apiVersion: '2025-02-19'})
51
+
52
+ // Image d'une valeur héritée (liste des valeurs par défaut que la page n'a pas encore) :
53
+ // la valeur BRUTE des valeurs par défaut (brouillon s'il existe) est d'abord recopiée
54
+ // dans la page, puis l'image remplacée, en un seul enregistrement. Si la page a déjà
55
+ // sa propre valeur, rien n'est recopié.
56
+ const inheritedOps = async (): Promise<Record<string, unknown>[]> => {
57
+ const inherited = request.inherited
58
+ if (!inherited) return []
59
+ const target = parsePath(inherited.path)
60
+ const from = parsePath(inherited.sourcePath)
61
+ if (!target || !from) return []
62
+ const [page, defaults] = await Promise.all(
63
+ [request.documentId, inherited.sourceId].map((id) =>
64
+ client.fetch<Record<string, unknown> | null>('coalesce(*[_id == $draft][0], *[_id == $id][0])', {id, draft: `drafts.${id}`}),
65
+ ),
66
+ )
67
+ const own = readAt(page, target)
68
+ if (own !== undefined && !(Array.isArray(own) && own.length === 0)) return []
69
+ const raw = readAt(defaults, from)
70
+ return raw === undefined ? [] : [{set: {[inherited.path]: raw}}]
71
+ }
72
+
49
73
  return (
50
74
  <MediaPickerDialog
51
75
  id="ncf-preview-replace-image"
@@ -53,8 +77,9 @@ function ReplaceImageDialog({request, onDone}: {request: Request; onDone: () =>
53
77
  kind="image"
54
78
  size="wide"
55
79
  onClose={onDone}
56
- onPick={(asset) => {
57
- patch.execute(replaceImagePatch(request.path, asset._id))
80
+ onPick={async (asset) => {
81
+ const before = await inheritedOps().catch(() => [])
82
+ patch.execute([...before, ...replaceImagePatch(request.path, asset._id)])
58
83
  onDone()
59
84
  }}
60
85
  />
package/src/version.ts CHANGED
@@ -3,4 +3,4 @@
3
3
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
4
4
  * le vérifie.
5
5
  */
6
- export const KIT_VERSION = '2.60.0'
6
+ export const KIT_VERSION = '2.61.0'
@@ -0,0 +1,136 @@
1
+ import {useEffect, useState} from 'react'
2
+ import {vercelStegaDecode, VERCEL_STEGA_REGEX} from '@vercel/stega'
3
+ import {CHIP, FONT, type PreviewEditingLabels} from './labels'
4
+ import {isEditMode} from './store'
5
+
6
+ /**
7
+ * CONTRÔLE AUTOMATIQUE de l'édition sur place, page par page (aperçu, mode édition) :
8
+ * le kit repère lui-même ce qui ne se modifierait pas sur place, au lieu de tout
9
+ * tester à la main section par section.
10
+ * - IMAGE du CMS (servie par cdn.sanity.io) sans repère d'édition : pas de « Remplacer
11
+ * cette image » (image affichée sans imageEditAttributes) ;
12
+ * - TEXTE dont le marqueur vise une LISTE ou un objet entier hérité (et non le texte
13
+ * lui-même) : le clic ouvrirait la liste vide dans le panneau.
14
+ * Rien à signaler : rien n'est affiché. Sinon une pastille « N à vérifier » ; un clic
15
+ * entoure les éléments en rouge (et les liste dans la console).
16
+ */
17
+ type Issue = {element: HTMLElement; reason: string}
18
+
19
+ function sanityImageUrl(img: HTMLImageElement): boolean {
20
+ const src = img.currentSrc || img.src || ''
21
+ if (src.includes('cdn.sanity.io')) return true
22
+ try {
23
+ const url = new URL(src, window.location.href).searchParams.get('url')
24
+ return !!url && decodeURIComponent(url).includes('cdn.sanity.io')
25
+ } catch {
26
+ return false
27
+ }
28
+ }
29
+
30
+ /** Chemins des valeurs héritées jointes à la page (listes et objets), pour repérer un texte resté sur la liste. */
31
+ function inheritedPaths(): Set<string> {
32
+ const out = new Set<string>()
33
+ for (const s of document.querySelectorAll<HTMLScriptElement>('script[data-ncf-inherited-source], script[data-ncf-inherited-list]'))
34
+ out.add(s.dataset.ncfInheritedSource ?? s.dataset.ncfInheritedList ?? '')
35
+ return out
36
+ }
37
+
38
+ export function auditEditability(root: ParentNode = document.body): Issue[] {
39
+ const issues: Issue[] = []
40
+ for (const img of root.querySelectorAll<HTMLImageElement>('img')) {
41
+ if (!sanityImageUrl(img) || img.closest('[data-edit-image]') || img.closest('[data-sanity-overlay-element]')) continue
42
+ const box = img.getBoundingClientRect()
43
+ if (box.width < 24 || box.height < 24) continue
44
+ issues.push({element: img, reason: 'image du CMS sans « Remplacer cette image » (imageEditAttributes manquant)'})
45
+ }
46
+ const lists = inheritedPaths()
47
+ if (lists.size) {
48
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
49
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
50
+ const text = n.textContent ?? ''
51
+ if (!VERCEL_STEGA_REGEX.test(text)) continue
52
+ VERCEL_STEGA_REGEX.lastIndex = 0
53
+ const info = vercelStegaDecode(text) as {href?: string} | undefined
54
+ const path = info?.href ? /;path=([^;?&]+)/.exec(decodeURIComponent(info.href))?.[1] : undefined
55
+ if (path && lists.has(path) && n.parentElement) issues.push({element: n.parentElement, reason: `texte rattaché à toute la liste ${path}, pas à son élément`})
56
+ }
57
+ }
58
+ return issues
59
+ }
60
+
61
+ export function EditAudit({labels}: {labels: PreviewEditingLabels}) {
62
+ const [issues, setIssues] = useState<Issue[]>([])
63
+ const [shown, setShown] = useState(false)
64
+
65
+ useEffect(() => {
66
+ let inFrame = true
67
+ try {
68
+ inFrame = window.self !== window.top
69
+ } catch {
70
+ inFrame = true
71
+ }
72
+ if (!inFrame) return
73
+ let timer = 0
74
+ const run = () => {
75
+ window.clearTimeout(timer)
76
+ timer = window.setTimeout(() => setIssues(isEditMode() ? auditEditability() : []), 1500)
77
+ }
78
+ run()
79
+ const observer = new MutationObserver(run)
80
+ observer.observe(document.body, {childList: true, subtree: true})
81
+ window.addEventListener('load', run)
82
+ return () => {
83
+ window.clearTimeout(timer)
84
+ observer.disconnect()
85
+ window.removeEventListener('load', run)
86
+ }
87
+ }, [])
88
+
89
+ // Contour rouge des éléments signalés, le temps de l'affichage.
90
+ useEffect(() => {
91
+ if (!shown) return
92
+ const previous = issues.map(({element}) => [element, element.style.outline, element.style.outlineOffset] as const)
93
+ for (const {element} of issues) {
94
+ element.style.outline = '2px dashed #e5484d'
95
+ element.style.outlineOffset = '2px'
96
+ }
97
+ // eslint-disable-next-line no-console
98
+ console.table(issues.map(({element, reason}) => ({reason, element: element.outerHTML.slice(0, 120)})))
99
+ return () => {
100
+ for (const [el, o, off] of previous) {
101
+ el.style.outline = o
102
+ el.style.outlineOffset = off
103
+ }
104
+ }
105
+ }, [shown, issues])
106
+
107
+ if (!issues.length) return null
108
+ return (
109
+ <button
110
+ type="button"
111
+ onClick={() => setShown((v) => !v)}
112
+ data-sanity-overlay-element
113
+ title={labels.auditHelp}
114
+ style={{
115
+ position: 'fixed',
116
+ left: 16,
117
+ bottom: 16,
118
+ zIndex: 2147482500,
119
+ display: 'flex',
120
+ alignItems: 'center',
121
+ gap: 8,
122
+ padding: '8px 14px 8px 10px',
123
+ border: 0,
124
+ borderRadius: 999,
125
+ background: CHIP,
126
+ color: '#fff',
127
+ boxShadow: '0 8px 24px rgba(0,0,0,0.25)',
128
+ font: `500 12px/1 ${FONT}`,
129
+ cursor: 'pointer',
130
+ }}
131
+ >
132
+ <span aria-hidden style={{width: 8, height: 8, borderRadius: 999, background: '#e5484d'}} />
133
+ {labels.auditIssues.replace('{n}', String(issues.length))}
134
+ </button>
135
+ )
136
+ }
@@ -105,6 +105,13 @@ export function ImageReplaceLayer({label}: {label: string}) {
105
105
  documentId: el.getAttribute('data-edit-doc'),
106
106
  documentType: el.getAttribute('data-edit-type'),
107
107
  path: el.getAttribute('data-edit-image'),
108
+ inherited: (() => {
109
+ try {
110
+ return JSON.parse(el.getAttribute('data-edit-inherited') || 'null')
111
+ } catch {
112
+ return null
113
+ }
114
+ })(),
108
115
  },
109
116
  origin,
110
117
  )
@@ -4,9 +4,9 @@ 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 {inlineEdit, isEditMode, isSpanTextPath, stegaRuns, type InlineTarget} from './store'
10
10
 
11
11
  /**
12
12
  * Éditeur de texte SUR PLACE : au clic sur un texte modifiable, un champ de
@@ -24,7 +24,11 @@ export function InlineTextEditor({labels}: {labels: PreviewEditingLabels}) {
24
24
  const onClick = (event: MouseEvent) => {
25
25
  if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
26
26
  if (!isEditMode()) return
27
- const hovered = inlineEdit.getHovered() ?? inheritedListTarget(event.target)
27
+ const direct = inlineEdit.getHovered() ?? inheritedListTarget(event.target)
28
+ // Texte en plusieurs paragraphes (un seul champ, rendu en <p> successifs) : Sanity
29
+ // n'encadre que le dernier (ses marqueurs sont à la fin du texte). Un clic sur
30
+ // n'importe quel paragraphe ouvre le texte entier, sur tout le bloc.
31
+ const hovered = (direct && paragraphGroup(direct)) ?? direct ?? paragraphGroupAt(event.target)
28
32
  if (!hovered || !(event.target instanceof Node) || !hovered.element.contains(event.target)) return
29
33
  if (inlineEdit.getEditing()?.element === hovered.element) return
30
34
  event.preventDefault()
@@ -38,6 +42,58 @@ export function InlineTextEditor({labels}: {labels: PreviewEditingLabels}) {
38
42
  return createPortal(<EditorSession key={`${target.node.id}:${target.node.path}`} target={target} labels={labels} />, document.body)
39
43
  }
40
44
 
45
+ /* ------------------------------------------------------------------------- */
46
+ /* Texte en plusieurs paragraphes */
47
+ /* ------------------------------------------------------------------------- */
48
+
49
+ const BLOCK = 'p, li, blockquote, h1, h2, h3, h4, h5, h6'
50
+
51
+ /** Un seul texte marqué (stega) dans l'élément ? Renvoie son nœud Sanity. */
52
+ function singleStegaNode(el: Element): SanityNode | null {
53
+ const text = el.textContent ?? ''
54
+ if (stegaRuns(text) !== 1) return null
55
+ const info = vercelStegaDecode(text) as {href?: string} | undefined
56
+ if (!info?.href) return null
57
+ const href = decodeURIComponent(info.href)
58
+ const id = /[;/]id=([^;?]+)/.exec(href)?.[1]?.replace(/^drafts\./, '')
59
+ const type = /;type=([^;?]+)/.exec(href)?.[1]
60
+ const path = /;path=([^;?]+)/.exec(href)?.[1]
61
+ if (!id || !path || /(^|\.)alt$|\.current$|\.children\[[^\]]+\]\.text$/.test(path)) return null
62
+ return {id, type, path} as SanityNode
63
+ }
64
+
65
+ /**
66
+ * Bloc de paragraphes d'un même champ : le parent direct qui contient au moins deux
67
+ * blocs (p, li...) et UN SEUL texte marqué (celui du champ, à la fin du dernier bloc).
68
+ */
69
+ function groupOf(block: Element): InlineTarget | null {
70
+ const parent = block.parentElement
71
+ if (!parent || parent === document.body) return null
72
+ const blocks = Array.from(parent.children).filter((c) => c.matches(BLOCK))
73
+ if (blocks.length < 2 || !blocks.includes(block)) return null
74
+ // Mêmes balises (un texte en paragraphes), et le marqueur dans le DERNIER bloc.
75
+ if (blocks.some((b) => b.tagName !== block.tagName)) return null
76
+ const last = blocks[blocks.length - 1]!
77
+ if (stegaRuns(last.textContent ?? '') !== 1) return null
78
+ const node = singleStegaNode(parent)
79
+ const expect = vercelStegaClean(block.textContent ?? '').replace(/\s+/g, ' ').trim()
80
+ return node && parent instanceof HTMLElement ? {element: parent, node, expect} : null
81
+ }
82
+
83
+ /** Cible déjà trouvée (dernier paragraphe) : élargie au bloc entier quand c'en est un. */
84
+ function paragraphGroup(target: InlineTarget): InlineTarget | null {
85
+ const block = target.element.matches(BLOCK) ? target.element : target.element.closest(BLOCK)
86
+ const group = block ? groupOf(block) : null
87
+ return group && group.node.path === target.node.path ? group : null
88
+ }
89
+
90
+ /** Clic sur un paragraphe SANS marqueur (pas le dernier) : le bloc dont il fait partie. */
91
+ function paragraphGroupAt(target: EventTarget | null): InlineTarget | null {
92
+ const block = target instanceof Element ? target.closest(BLOCK) : null
93
+ if (!block || stegaRuns(block.textContent ?? '') > 0) return null
94
+ return groupOf(block)
95
+ }
96
+
41
97
  /* ------------------------------------------------------------------------- */
42
98
  /* Valeurs héritées jointes à la page (inheritedEditScriptProps) */
43
99
  /* ------------------------------------------------------------------------- */
@@ -57,6 +113,21 @@ function inheritedListFor(path: string): InheritedListData | null {
57
113
  return null
58
114
  }
59
115
 
116
+ type SourceEntry = {path: string; source: {id: string; path: string}}
117
+
118
+ /** Valeur héritée de toute forme : entrée qui couvre ce chemin (source brute des valeurs par défaut). */
119
+ function inheritedSourceFor(path: string): {entry: SourceEntry; rest: string} | null {
120
+ const entries: SourceEntry[] = []
121
+ for (const script of document.querySelectorAll<HTMLScriptElement>('script[data-ncf-inherited-source]')) {
122
+ try {
123
+ entries.push({path: script.dataset.ncfInheritedSource ?? '', source: JSON.parse(script.textContent ?? 'null')})
124
+ } catch {
125
+ // Entrée illisible : ignorée.
126
+ }
127
+ }
128
+ return coveringEntry(entries.filter((e) => e.path && e.source?.id && e.source?.path), path)
129
+ }
130
+
60
131
  function inheritedValueFor(path: string): string | null {
61
132
  for (const script of document.querySelectorAll<HTMLScriptElement>('script[data-ncf-inherited-value]')) {
62
133
  if (script.dataset.ncfInheritedValue !== path) continue
@@ -84,7 +155,7 @@ function inheritedListTarget(target: EventTarget | null): InlineTarget | null {
84
155
  const id = /[;/]id=([^;?]+)/.exec(href)?.[1]?.replace(/^drafts\./, '')
85
156
  const type = /;type=([^;?]+)/.exec(href)?.[1]
86
157
  const path = /;path=([^;?]+)/.exec(href)?.[1]
87
- if (!id || !path || !inheritedListFor(path) || !(el instanceof HTMLElement)) return null
158
+ if (!id || !path || !(inheritedListFor(path) || inheritedSourceFor(path)) || !(el instanceof HTMLElement)) return null
88
159
  return {element: el, node: {id, type, path} as SanityNode}
89
160
  }
90
161
  return null
@@ -147,6 +218,8 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
147
218
  const initial = useRef('')
148
219
  // Texte de départ d'un texte hérité (valeur par défaut) : inchangé = rien à enregistrer.
149
220
  const inheritedStart = useRef('')
221
+ // Valeur héritée de toute forme : brute (valeurs par défaut), à recopier dans la page.
222
+ const rawInherited = useRef<{path: string; raw: unknown; rest: string} | null>(null)
150
223
  const multiline = useRef(false)
151
224
  const rootRef = useRef<HTMLDivElement>(null)
152
225
  const fieldRef = useRef<HTMLTextAreaElement>(null)
@@ -179,14 +252,37 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
179
252
  let cancelled = false
180
253
  getDocument(node.id)
181
254
  .getSnapshot()
182
- .then((doc) => {
255
+ .then(async (doc) => {
183
256
  if (cancelled) return
184
257
  const stored = doc ? getAtPath(parse(node.path), doc) : undefined
185
258
  const list = inheritedListFor(node.path)
186
- const text =
259
+ // Valeur héritée de toute forme : la valeur BRUTE des valeurs par défaut, gardée
260
+ // pour la recopie à l'enregistrement (si la page n'a toujours rien à cet endroit).
261
+ const covering = typeof stored === 'string' && stored !== '' ? null : inheritedSourceFor(node.path)
262
+ let fromSource: string | null = null
263
+ if (covering) {
264
+ const own = doc ? readAt(doc, parsePath(covering.entry.path) ?? []) : undefined
265
+ const empty = own === undefined || (Array.isArray(own) && own.length === 0)
266
+ const defaults = empty ? await getDocument(covering.entry.source.id).getSnapshot().catch(() => null) : null
267
+ const raw = defaults ? readAt(defaults, parsePath(covering.entry.source.path) ?? []) : undefined
268
+ if (raw !== undefined) {
269
+ rawInherited.current = {path: covering.entry.path, raw, rest: covering.rest}
270
+ const v = readAt(raw, parsePath(covering.rest) ?? [])
271
+ fromSource = typeof v === 'string' ? v : null
272
+ }
273
+ }
274
+ if (cancelled) return
275
+ const resolved =
187
276
  typeof stored === 'string' && stored !== ''
188
277
  ? stored
189
- : (inheritedValueFor(node.path) ?? (list ? inheritedListValue(list, node.path) : null) ?? vercelStegaClean(element.textContent ?? '').trim())
278
+ : (fromSource ?? inheritedValueFor(node.path) ?? (list ? inheritedListValue(list, node.path) : null) ?? vercelStegaClean(element.textContent ?? '').trim())
279
+ // Bloc de paragraphes : le paragraphe cliqué doit faire partie de ce texte (sinon
280
+ // c'était un texte voisin, hors champ : on n'ouvre rien).
281
+ if (target.expect && !resolved.replace(/\s+/g, ' ').includes(target.expect)) {
282
+ inlineEdit.close()
283
+ return
284
+ }
285
+ const text = resolved
190
286
  initial.current = typeof stored === 'string' ? stored : ''
191
287
  inheritedStart.current = text
192
288
  multiline.current = text.includes('\n')
@@ -200,7 +296,7 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
200
296
  return () => {
201
297
  cancelled = true
202
298
  }
203
- }, [getDocument, node.id, node.path, element])
299
+ }, [getDocument, node.id, node.path, element, target.expect])
204
300
 
205
301
  useEffect(() => {
206
302
  if (status !== 'editing') return
@@ -241,9 +337,17 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
241
337
  }
242
338
  // Ligne d'une liste héritée que la page n'a pas encore : la liste par défaut est
243
339
  // recopiée dans la page avec cette ligne modifiée (même enregistrement).
340
+ const doc = getDocument(node.id)
341
+ // Valeur héritée de toute forme : la valeur brute des valeurs par défaut est recopiée
342
+ // dans la page avec ce texte modifié, en un seul enregistrement.
343
+ const copy = inherited && rawInherited.current ? writeAt(rawInherited.current.raw, parsePath(rawInherited.current.rest) ?? [], next) : null
344
+ if (copy !== null && rawInherited.current) {
345
+ doc.patch([at(rawInherited.current.path, set(copy))])
346
+ setStatus('saving')
347
+ return
348
+ }
244
349
  const list = inherited ? inheritedListFor(node.path) : null
245
350
  const items = list ? materializeInheritedList(list, node.path, next) : null
246
- const doc = getDocument(node.id)
247
351
  if (list && items) doc.patch([at(list.path, set(items))])
248
352
  // Morceau de texte riche : jamais retiré (un morceau sans texte casse le bloc), vidé.
249
353
  else if (isSpanTextPath(node.path)) doc.patch([at(node.path, set(next))])
@@ -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,9 @@ export type PreviewEditingLabels = {
17
17
  editMode: string
18
18
  browseMode: string
19
19
  modeLabel: string
20
+ /** Contrôle automatique : « {n} à vérifier » (éléments non modifiables sur place). */
21
+ auditIssues: string
22
+ auditHelp: string
20
23
  }
21
24
 
22
25
  export const DEFAULT_PREVIEW_EDITING_LABELS: PreviewEditingLabels = {
@@ -29,6 +32,8 @@ export const DEFAULT_PREVIEW_EDITING_LABELS: PreviewEditingLabels = {
29
32
  editMode: 'Edit mode',
30
33
  browseMode: 'Browse mode',
31
34
  modeLabel: 'Preview mode: edit or browse',
35
+ auditIssues: '{n} to check',
36
+ auditHelp: 'Elements of this page that cannot be edited in place (click to outline them in red)',
32
37
  }
33
38
 
34
39
  /** 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.
@@ -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