@nocode-factory/sanity-kit 2.65.0-rc.7 → 2.66.0-rc.2

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.
@@ -7,7 +7,7 @@ import {vercelStegaClean, vercelStegaDecode} from '@vercel/stega'
7
7
  import {coveringEntry, inheritedListValue, materializeInheritedList, parsePath, readAt, writeAt} from './inherited'
8
8
  import {ACCENT, CHIP, FONT, type PreviewEditingLabels} from './labels'
9
9
  import {READ_DEFAULTS_MESSAGE, READ_DEFAULTS_RESULT} from './protocol'
10
- import {inlineEdit, isEditMode, isSpanTextPath, stegaRuns, type InlineTarget} from './store'
10
+ import {formatNumberInput, inlineEdit, isEditMode, isSpanTextPath, parseNumberInput, stegaRuns, type InlineTarget} from './store'
11
11
 
12
12
  /**
13
13
  * Éditeur de texte SUR PLACE : au clic sur un texte modifiable, un champ de
@@ -31,7 +31,8 @@ export function InlineTextEditor({labels}: {labels: PreviewEditingLabels}) {
31
31
  // n'importe quel paragraphe ouvre le texte entier, sur tout le bloc.
32
32
  const clicked = event.target instanceof Node ? event.target : null
33
33
  const own = direct && clicked && direct.element.contains(clicked) ? direct : null
34
- const hovered = (own && paragraphGroup(own)) ?? own ?? paragraphGroupAt(event.target)
34
+ // Un chiffre reste seul (jamais regroupé avec les paragraphes voisins).
35
+ const hovered = (own && own.kind !== 'number' ? paragraphGroup(own) : null) ?? own ?? paragraphGroupAt(event.target)
35
36
  const area = hovered?.parts ?? (hovered ? [hovered.element] : [])
36
37
  if (!hovered || !clicked || !area.some((el) => el.contains(clicked))) return
37
38
  if (inlineEdit.getEditing()?.element === hovered.element) return
@@ -243,6 +244,31 @@ function textStyle(element: HTMLElement): CSSProperties {
243
244
  return style as CSSProperties
244
245
  }
245
246
 
247
+ /** Texte en cours d'édition : seul le texte s'efface, fonds, bordures et images restent. */
248
+ export const EDITING_ATTR = 'data-ncf-inline-editing'
249
+ const EDITING_CSS = `[${EDITING_ATTR}],[${EDITING_ATTR}] *{color:transparent!important;-webkit-text-fill-color:transparent!important;text-shadow:none!important;text-decoration-color:transparent!important}`
250
+ export function ensureEditingStyle() {
251
+ if (document.getElementById('ncf-inline-editing-style')) return
252
+ const style = document.createElement('style')
253
+ style.id = 'ncf-inline-editing-style'
254
+ style.textContent = EDITING_CSS
255
+ document.head.appendChild(style)
256
+ }
257
+
258
+ /** Padding de l'élément édité (un seul élément ; un bloc de paragraphes n'en a pas). */
259
+ export function paddingOf(parts: HTMLElement[]): string {
260
+ if (parts.length !== 1) return '0'
261
+ const cs = getComputedStyle(parts[0]!)
262
+ return `${cs.paddingTop} ${cs.paddingRight} ${cs.paddingBottom} ${cs.paddingLeft}`
263
+ }
264
+
265
+ /** Couleur lisible pour la saisie : celle du texte, sauf si elle est transparente (texte en dégradé). */
266
+ export function readableColor(color: string | undefined): string | undefined {
267
+ const m = color?.match(/rgba?\(([^)]+)\)/)
268
+ const alpha = m ? Number(m[1]!.split(',')[3] ?? 1) : 1
269
+ return !color || color === 'transparent' || alpha === 0 ? '#1b1d21' : color
270
+ }
271
+
246
272
  const sameBox = (a: Box | null, b: Box) => !!a && a.top === b.top && a.left === b.left && a.width === b.width && a.height === b.height
247
273
 
248
274
  const CHIP_STYLE: CSSProperties = {
@@ -275,6 +301,9 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
275
301
  // Bloc de paragraphes : tous ses paragraphes ; sinon l'élément seul.
276
302
  const parts = target.parts?.length ? target.parts : [element]
277
303
  const [typo] = useState(() => textStyle(parts[0]!))
304
+ // Marges intérieures de l'élément édité (un bouton : son padding) : le texte saisi reste à
305
+ // sa place, centré dans le bouton, au lieu de remonter en haut à gauche (vu sur JAF).
306
+ const [padding] = useState(() => paddingOf(parts))
278
307
  const initial = useRef('')
279
308
  // Texte de départ d'un texte hérité (valeur par défaut) : inchangé = rien à enregistrer.
280
309
  const inheritedStart = useRef('')
@@ -282,21 +311,40 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
282
311
  const rawInherited = useRef<{path: string; raw: unknown; rest: string} | null>(null)
283
312
  const multiline = useRef(false)
284
313
  const [breaks, setBreaks] = useState(false)
314
+ // Chiffre (champ nombre) : saisie numérique, validée avant d'enregistrer.
315
+ const isNumber = target.kind === 'number'
316
+ const [invalid, setInvalid] = useState(false)
317
+ // Langue de la page (séparateurs de la saisie : « 98,5 », « 1 200 »).
318
+ const [locale] = useState(() => element.closest('[lang]')?.getAttribute('lang') || document.documentElement.lang || undefined)
285
319
  const rootRef = useRef<HTMLDivElement>(null)
286
320
  const fieldRef = useRef<HTMLTextAreaElement>(null)
287
321
 
288
- // Le texte d'origine est masqué (mise en page conservée) le temps de l'édition.
322
+ // Le TEXTE d'origine est rendu transparent le temps de l'édition (mise en page
323
+ // conservée). Jamais l'élément entier (kit >= 2.64.1) : il porte parfois le fond d'un
324
+ // bouton ou contient une image ; les masquer laissait un texte blanc sur une page
325
+ // blanche, ou une zone vide à la place de l'image.
289
326
  useEffect(() => {
290
- const previous = parts.map((el) => el.style.visibility)
291
- for (const el of parts) el.style.visibility = 'hidden'
327
+ ensureEditingStyle()
328
+ for (const el of parts) el.setAttribute(EDITING_ATTR, '')
292
329
  return () => {
293
- parts.forEach((el, i) => {
294
- el.style.visibility = previous[i] ?? ''
295
- })
330
+ for (const el of parts) el.removeAttribute(EDITING_ATTR)
296
331
  }
297
332
  // eslint-disable-next-line react-hooks/exhaustive-deps
298
333
  }, [element])
299
334
 
335
+ // Échap annule même si la saisie a perdu le focus (clic ailleurs dans l'aperçu) :
336
+ // la barre affiche « Esc » (vu sur JAF : la touche ne faisait rien).
337
+ useEffect(() => {
338
+ const onKey = (event: globalThis.KeyboardEvent) => {
339
+ if (event.key !== 'Escape') return
340
+ event.preventDefault()
341
+ event.stopPropagation()
342
+ inlineEdit.close()
343
+ }
344
+ window.addEventListener('keydown', onKey, {capture: true})
345
+ return () => window.removeEventListener('keydown', onKey, {capture: true})
346
+ }, [])
347
+
300
348
  // Suit l'élément (défilement, défilement doux, redimensionnement).
301
349
  useEffect(() => {
302
350
  let frame = 0
@@ -324,6 +372,33 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
324
372
  .then(async (doc) => {
325
373
  if (cancelled) return
326
374
  const stored = doc ? getAtPath(parse(node.path), doc) : undefined
375
+ if (isNumber) {
376
+ // Chiffre : la valeur ENREGISTRÉE (98.5), jamais le chiffre affiché (animé,
377
+ // formaté « 98,5 »). Vide dans la page : celle des valeurs par défaut.
378
+ let start = typeof stored === 'number' ? formatNumberInput(stored, locale) : ''
379
+ if (typeof stored !== 'number') {
380
+ const covering = inheritedSourceFor(node.path)
381
+ if (covering) {
382
+ const own = doc ? readAt(doc, parsePath(covering.entry.path) ?? []) : undefined
383
+ const empty = own === undefined || (Array.isArray(own) && own.length === 0)
384
+ const raw = empty ? await readDefaults(covering.entry.source.id, covering.entry.source.path).catch(() => undefined) : undefined
385
+ if (raw !== undefined) {
386
+ rawInherited.current = {path: covering.entry.path, raw, rest: covering.rest}
387
+ const v = readAt(raw, parsePath(covering.rest) ?? [])
388
+ if (typeof v === 'number') start = formatNumberInput(v, locale)
389
+ }
390
+ }
391
+ }
392
+ if (cancelled) return
393
+ initial.current = typeof stored === 'number' ? formatNumberInput(stored, locale) : ''
394
+ inheritedStart.current = start
395
+ multiline.current = false
396
+ setBreaks(false)
397
+ setInherited(typeof stored !== 'number')
398
+ setValue(start)
399
+ setStatus('editing')
400
+ return
401
+ }
327
402
  const list = inheritedListFor(node.path)
328
403
  // Valeur héritée de toute forme : la valeur BRUTE des valeurs par défaut, gardée
329
404
  // pour la recopie à l'enregistrement (si la page n'a toujours rien à cet endroit).
@@ -376,7 +451,10 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
376
451
  if (!field) return
377
452
  const focusField = () => {
378
453
  field.focus({preventScroll: true})
379
- field.setSelectionRange(field.value.length, field.value.length)
454
+ // Chiffre : tout est présélectionné, on tape directement le nouveau (sinon « 100 »
455
+ // puis « 120 » donnait « 100120 », vu sur JAF). Texte : curseur à la fin.
456
+ if (isNumber) field.select()
457
+ else field.setSelectionRange(field.value.length, field.value.length)
380
458
  }
381
459
  focusField()
382
460
  // Le Studio ouvre le champ dans son panneau juste après le clic et y place le
@@ -402,6 +480,31 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
402
480
  }, [value, box?.width, status])
403
481
 
404
482
  const save = useCallback(() => {
483
+ if (isNumber) {
484
+ const parsed = parseNumberInput(value, locale)
485
+ if (Number.isNaN(parsed)) {
486
+ setInvalid(true)
487
+ return
488
+ }
489
+ const same = parsed === (initial.current === '' ? null : parseNumberInput(initial.current, locale))
490
+ if (same || (inherited && parsed !== null && parsed === parseNumberInput(inheritedStart.current, locale))) {
491
+ inlineEdit.close()
492
+ return
493
+ }
494
+ const doc = getDocument(node.id)
495
+ // Chiffre hérité : la valeur brute des valeurs par défaut est recopiée dans la page
496
+ // avec ce chiffre modifié (un seul enregistrement), comme pour un texte hérité.
497
+ if (inherited && rawInherited.current) {
498
+ if (parsed === null) {
499
+ inlineEdit.close()
500
+ return
501
+ }
502
+ const copy = writeAt(rawInherited.current.raw, parsePath(rawInherited.current.rest) ?? [], parsed)
503
+ doc.patch([at(rawInherited.current.path, set(copy))])
504
+ } else doc.patch([at(node.path, parsed === null ? unset() : set(parsed))])
505
+ setStatus('saving')
506
+ return
507
+ }
405
508
  const next = multiline.current ? value : value.replace(/\s*\n\s*/g, ' ')
406
509
  if (next === initial.current || (inherited && next.trim() === inheritedStart.current.trim())) {
407
510
  inlineEdit.close()
@@ -441,12 +544,18 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
441
544
  else if (isSpanTextPath(node.path)) doc.patch([at(node.path, set(next))])
442
545
  else doc.patch([at(node.path, next.trim() === '' ? unset() : set(next))])
443
546
  setStatus('saving')
444
- }, [value, inherited, getDocument, node.id, node.path])
547
+ }, [value, inherited, getDocument, node.id, node.path, isNumber])
445
548
 
446
549
  // Enregistré : le texte saisi reste affiché jusqu'à ce que l'aperçu montre la
447
550
  // nouvelle valeur (pas de retour éclair à l'ancien texte), 6 s au plus.
448
551
  useEffect(() => {
449
552
  if (status !== 'saving') return
553
+ // Chiffre : l'affichage est formaté (et parfois animé), on ne peut pas le comparer à la
554
+ // saisie ; l'aperçu se rafraîchit, l'éditeur se ferme après un court instant.
555
+ if (isNumber) {
556
+ const done = window.setTimeout(() => inlineEdit.close(), 700)
557
+ return () => window.clearTimeout(done)
558
+ }
450
559
  const expected = value.replace(/\s+/g, ' ').trim()
451
560
  const started = performance.now()
452
561
  const timer = window.setInterval(() => {
@@ -494,15 +603,25 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
494
603
  spellCheck
495
604
  readOnly={status !== 'editing'}
496
605
  aria-label={labels.fieldLabel}
497
- onChange={(e) => setValue(e.target.value)}
606
+ onChange={(e) => {
607
+ setValue(e.target.value)
608
+ if (invalid) setInvalid(false)
609
+ }}
610
+ inputMode={isNumber ? 'decimal' : undefined}
611
+ wrap={isNumber ? 'off' : undefined}
498
612
  onKeyDown={onKeyDown}
499
613
  style={{
500
614
  ...typo,
615
+ color: readableColor(typo.color as string | undefined),
501
616
  display: 'block',
502
- width: '100%',
617
+ // Chiffre : toujours sur une ligne, la saisie s'élargit si la valeur dépasse le
618
+ // chiffre affiché (« 98.5 » passait sur deux lignes, vu sur JAF).
619
+ width: isNumber ? `max(100%, ${value.length + 2}ch)` : '100%',
620
+ whiteSpace: isNumber ? 'nowrap' : undefined,
503
621
  minHeight: box.height,
504
622
  margin: 0,
505
- padding: 0,
623
+ padding,
624
+ boxSizing: 'border-box',
506
625
  border: 0,
507
626
  borderRadius: 2,
508
627
  resize: 'none',
@@ -536,7 +655,30 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
536
655
  </>
537
656
  )}
538
657
  </div>
539
- {inherited && status === 'editing' && (
658
+ {isNumber && invalid && status === 'editing' && (
659
+ <p
660
+ role="alert"
661
+ style={{
662
+ position: 'absolute',
663
+ left: 0,
664
+ ...(below ? {top: '100%', marginTop: 56} : {bottom: '100%', marginBottom: 56}),
665
+ width: 'max-content',
666
+ maxWidth: 'min(28rem, 90vw)',
667
+ padding: '8px 12px',
668
+ borderRadius: 6,
669
+ background: '#fff',
670
+ color: '#b42318',
671
+ boxShadow: '0 8px 24px rgba(0,0,0,0.18)',
672
+ font: `12px/1.35 ${FONT}`,
673
+ fontStyle: 'normal',
674
+ textTransform: 'none',
675
+ letterSpacing: 'normal',
676
+ }}
677
+ >
678
+ {labels.numberExpected}
679
+ </p>
680
+ )}
681
+ {inherited && status === 'editing' && !invalid && (
540
682
  <p
541
683
  style={{
542
684
  position: 'absolute',
@@ -11,7 +11,7 @@ import {inlineEdit} from './store'
11
11
  export function InlineTextOverlay({element, node}: OverlayComponentProps) {
12
12
  useEffect(() => {
13
13
  if (!(element instanceof HTMLElement)) return
14
- inlineEdit.setHovered({element, node})
14
+ inlineEdit.setHovered({element, node, ...(element.hasAttribute('data-edit-number') ? {kind: 'number' as const} : {})})
15
15
  return () => inlineEdit.clearHovered(element)
16
16
  }, [element, node])
17
17
 
@@ -10,8 +10,8 @@
10
10
  * `@nocode-factory/sanity-kit/web` (`NcfPreviewEditing`, `ncfOverlayComponents`).
11
11
  * Dépendances : `@sanity/visual-editing` (fourni par next-sanity).
12
12
  */
13
- export {annotateImageEditTargets, withPreviewEditTargets, rekeyOwnImageTargets, imageEditAttributes, imageAlt} from './targets'
14
- export type {ImageEditValue, ImageEditOptions, ImageEditAttributes} from './targets'
13
+ export {annotateImageEditTargets, withPreviewEditTargets, rekeyOwnImageTargets, imageEditAttributes, imageAlt, numberEditAttributes} from './targets'
14
+ export type {ImageEditValue, ImageEditOptions, ImageEditAttributes, NumberEditAttributes} from './targets'
15
15
  export {retagInheritedList, inheritedEditScriptProps, inheritedListValue, materializeInheritedList} from './inherited'
16
16
  export type {InheritedEdit} from './inherited'
17
17
  export {REPLACE_IMAGE_MESSAGE, isReplaceImageRequest, replaceImagePatch} from './protocol'
@@ -22,6 +22,8 @@ export type PreviewEditingLabels = {
22
22
  /** Contrôle automatique : « {n} à vérifier » (éléments non modifiables sur place). */
23
23
  auditIssues: string
24
24
  auditHelp: string
25
+ /** Chiffre (champ nombre) : saisie qui n'est pas un nombre, rien n'est enregistré. */
26
+ numberExpected: string
25
27
  }
26
28
 
27
29
  export const DEFAULT_PREVIEW_EDITING_LABELS: PreviewEditingLabels = {
@@ -37,6 +39,7 @@ export const DEFAULT_PREVIEW_EDITING_LABELS: PreviewEditingLabels = {
37
39
  newLine: 'New line',
38
40
  auditIssues: '{n} to check',
39
41
  auditHelp: 'Elements of this page that cannot be edited in place (click to outline them in red)',
42
+ numberExpected: 'Number expected (e.g. 98.5): nothing saved.',
40
43
  }
41
44
 
42
45
  /** Couleurs : surchargeables par le projet (variables CSS sur :root). */
@@ -16,6 +16,8 @@ export type InlineTarget = {
16
16
  expect?: string
17
17
  /** Bloc de paragraphes : tous les paragraphes du champ (masqués, cadre = leur union). */
18
18
  parts?: HTMLElement[]
19
+ /** Chiffre (champ nombre, `numberEditAttributes`) : saisie numérique (kit >= 2.66.0). */
20
+ kind?: 'number'
19
21
  }
20
22
 
21
23
  let hovered: InlineTarget | null = null
@@ -93,6 +95,8 @@ export function stegaRuns(text: string): number {
93
95
  * un slug (une adresse se change dans le panneau, qui crée la 301).
94
96
  */
95
97
  export function isInlineEditablePath(type: string, path: string, element: Element): boolean {
98
+ // Chiffre : seulement l'élément que le site a marqué (numberEditAttributes).
99
+ if (type === 'number') return element.hasAttribute('data-edit-number')
96
100
  if (type !== 'string') return false
97
101
  if (/(^|\.)alt$/.test(path)) return false
98
102
  if (element.matches('img, picture, video, svg, canvas, iframe') || !element.textContent?.trim()) return false
@@ -103,3 +107,29 @@ export function isInlineEditablePath(type: string, path: string, element: Elemen
103
107
 
104
108
  /** Chemin d'un morceau de texte riche (jamais retiré, seulement vidé). */
105
109
  export const isSpanTextPath = (path: string) => /\.children\[[^\]]+\]\.text$/.test(path)
110
+
111
+ /**
112
+ * Saisie d'un chiffre : « 98,5 », « 98.5 », « 1 200 » (espaces, espaces insécables) ;
113
+ * vide = retour à la valeur par défaut (null) ; autre chose = NaN (rien n'est enregistré).
114
+ */
115
+ export function parseNumberInput(text: string, locale?: string): number | null {
116
+ // Séparateurs de la langue de la page : décimale « , » (fr) ou « . » (en), milliers
117
+ // « 1 200 » (fr) ou « 1,200 » (en). Sans langue : virgule et point acceptés en décimale.
118
+ const parts = locale ? new Intl.NumberFormat(locale).formatToParts(12345.6) : []
119
+ const group = parts.find((p) => p.type === 'group')?.value
120
+ const decimal = parts.find((p) => p.type === 'decimal')?.value
121
+ let clean = text.replace(/[\s\u00a0\u202f]/g, '')
122
+ if (group && !/\s/.test(group) && group !== decimal) clean = clean.split(group).join('')
123
+ clean = decimal && decimal !== '.' ? clean.split(decimal).join('.') : clean.replace(',', '.')
124
+ if (clean === '') return null
125
+ return /^-?\d+(\.\d+)?$/.test(clean) ? Number(clean) : Number.NaN
126
+ }
127
+
128
+ /** Chiffre affiché dans la saisie au format de la langue de la page (« 98,5 », « 1 200 »). */
129
+ export function formatNumberInput(value: number, locale?: string): string {
130
+ try {
131
+ return new Intl.NumberFormat(locale, {maximumFractionDigits: 20}).format(value)
132
+ } catch {
133
+ return String(value)
134
+ }
135
+ }
@@ -57,6 +57,35 @@ function mark(value: Marked, id: string, type: string, path: string, extra: Reco
57
57
  value._editType = type
58
58
  }
59
59
 
60
+ /**
61
+ * CHIFFRES (kit >= 2.66.0) : un champ NOMBRE ne peut pas porter de stega (caractères
62
+ * invisibles), il était donc invisible pour l'édition sur place. Dans l'aperçu, l'objet
63
+ * qui le contient (élément de liste, section) reçoit `_editNumbers` : pour chaque champ
64
+ * nombre, son repère Sanity (document + chemin exact). Le composant le pose avec
65
+ * `numberEditAttributes(objet, 'champ')` sur l'élément qui affiche le chiffre.
66
+ */
67
+ type WithNumbers = {_editNumbers?: Record<string, string>}
68
+ function markNumbers(value: Record<string, unknown>, id: string, type: string, path: string, baseUrl: string) {
69
+ const numbers: Record<string, string> = {}
70
+ for (const [k, v] of Object.entries(value))
71
+ if (!k.startsWith('_') && typeof v === 'number' && Number.isFinite(v)) numbers[k] = createDataAttribute({baseUrl, id, type, path: `${path}.${k}`}).toString()
72
+ if (Object.keys(numbers).length) (value as WithNumbers)._editNumbers = {...(value as WithNumbers)._editNumbers, ...numbers}
73
+ }
74
+
75
+ export type NumberEditAttributes = {'data-sanity'?: string; 'data-edit-number'?: string}
76
+
77
+ /**
78
+ * Attributs à poser sur l'élément qui affiche un chiffre (champ nombre `field` de
79
+ * `value`, élément de liste ou section) : crayon au survol, édition sur place au clic.
80
+ * Vide pour les visiteurs. Ex. : `<span {...numberEditAttributes(item, 'value')}>`.
81
+ * L'élément ne doit contenir QUE le chiffre (préfixe et suffixe à côté, dans leurs
82
+ * propres éléments), sinon ils s'effacent avec lui pendant l'édition.
83
+ */
84
+ export function numberEditAttributes(value: unknown, field: string): NumberEditAttributes {
85
+ const target = value && typeof value === 'object' ? (value as WithNumbers)._editNumbers?.[field] : undefined
86
+ return target ? {'data-sanity': target, 'data-edit-number': field} : {}
87
+ }
88
+
60
89
  export type ImageEditOptions = {
61
90
  /** Adresse du Studio (celle de `stega.studioUrl`). */
62
91
  studioUrl: string
@@ -209,7 +238,11 @@ function retagDeep(value: unknown, path: string, page: {id: string; type: string
209
238
  copy._editInherited = inherited
210
239
  return copy
211
240
  }
212
- return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, k.startsWith('_') ? v : retagDeep(v, `${path}.${k}`, page, inherited, options)]))
241
+ const copy = Object.fromEntries(Object.entries(value).map(([k, v]) => [k, k.startsWith('_') ? v : retagDeep(v, `${path}.${k}`, page, inherited, options)]))
242
+ // Chiffres hérités : visent leur chemin dans la PAGE (la valeur par défaut est recopiée
243
+ // dans la page à la première modification, comme pour les textes).
244
+ markNumbers(copy, page.id, page.type, path, options.studioUrl)
245
+ return copy
213
246
  }
214
247
 
215
248
  /**
@@ -233,6 +266,10 @@ export function rekeyOwnImageTargets<T>(section: T, source: Source, key: string
233
266
  if (value._editDoc === pageId) mark(value, pageId, source.type, path, {baseUrl: options.studioUrl})
234
267
  return
235
268
  }
269
+ // Document lié (témoignage, carte...) : ses chiffres ne sont pas ceux de la page.
270
+ const id = (value as {_id?: unknown})._id
271
+ if (typeof id === 'string' && id.replace(/^drafts\./, '') !== pageId) return
272
+ markNumbers(value as Record<string, unknown>, pageId, source.type, path, options.studioUrl)
236
273
  for (const [k, child] of Object.entries(value)) if (!k.startsWith('_')) visit(child, `${path}.${k}`)
237
274
  }
238
275
  visit(section, sectionBase(source, key))
@@ -1,41 +0,0 @@
1
- // Contrôle des traductions faites AVANT le kit 2.65.0 (lu par `doctor`) : une mise à jour du
2
- // kit ne les corrige pas. Compare une version traduite à sa version principale, élément par
3
- // élément (mêmes _key) :
4
- // - ancre (champ « anchor » ou « …Anchor ») DIFFÉRENTE de la version principale : l'IA
5
- // l'avait traduite (« start of school year »), les liens qui la visent sont cassés ;
6
- // - texte alternatif d'image (« alt ») IDENTIQUE à la version principale : jamais traduit.
7
- // Pur (sans réseau), testé dans test/translationAudit.test.ts.
8
-
9
- const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)
10
- const ANCHOR = /^(anchor|.*Anchor)$/
11
-
12
- /**
13
- * Écarts d'une version traduite : {anchors: [chemin...], alts: [chemin...]}.
14
- * Seuls les éléments présents des deux côtés (même chemin, mêmes _key) sont comparés.
15
- */
16
- export function auditTranslation(master, translated) {
17
- const anchors = []
18
- const alts = []
19
- const walk = (a, b, path) => {
20
- if (Array.isArray(a) && Array.isArray(b)) {
21
- const byKey = new Map(b.filter((i) => isObj(i) && i._key).map((i) => [i._key, i]))
22
- for (const item of a) if (isObj(item) && item._key && byKey.has(item._key)) walk(item, byKey.get(item._key), `${path}[${item._key}]`)
23
- return
24
- }
25
- if (!isObj(a) || !isObj(b)) return
26
- for (const [k, v] of Object.entries(a)) {
27
- if (k.startsWith('_')) continue
28
- const w = b[k]
29
- const at = path ? `${path}.${k}` : k
30
- // Ancre d'une section ou d'un lien, et lien « adresse » vers une ancre de la page
31
- // (href « #pratique », vu sur JAF : le bouton restait sur « #practical »).
32
- if (typeof v === 'string' && (ANCHOR.test(k) || (k === 'href' && v.startsWith('#')))) {
33
- if (v && typeof w === 'string' && w && w !== v) anchors.push(at)
34
- } else if (typeof v === 'string' && k === 'alt' && isObj(a.asset)) {
35
- if (v.trim() && w === v) alts.push(at)
36
- } else walk(v, w, at)
37
- }
38
- }
39
- walk(master, translated, '')
40
- return {anchors, alts}
41
- }
@@ -1,51 +0,0 @@
1
- import type {SanityClient} from 'sanity'
2
-
3
- type Doc = Record<string, unknown>
4
-
5
- /** Identifiants des documents référencés par `doc` (liens, pages liées...), hors images et fichiers. */
6
- export function referencedIds(doc: unknown): string[] {
7
- const out = new Set<string>()
8
- const walk = (node: unknown) => {
9
- if (Array.isArray(node)) return node.forEach(walk)
10
- if (!node || typeof node !== 'object') return
11
- const ref = (node as {_ref?: unknown})._ref
12
- if (typeof ref === 'string' && !/^(image|file)-/.test(ref)) out.add(ref.replace(/^drafts\./, ''))
13
- for (const [k, v] of Object.entries(node)) if (!k.startsWith('_')) walk(v)
14
- }
15
- walk(doc)
16
- return [...out]
17
- }
18
-
19
- /**
20
- * Pages liées depuis `doc` qui n'ont pas de version PUBLIÉE dans chacune des `languages`
21
- * (kit >= 2.65.0). La version traduite d'un document qui les vise ne peut pas être
22
- * publiée (« Cette page est en FR et n'a pas de version EN », vu sur JAF) : on le dit
23
- * AVANT de la créer, avec les pages à traduire d'abord.
24
- */
25
- export async function linkedWithoutVersion(
26
- client: SanityClient,
27
- doc: Doc,
28
- languages: string[],
29
- field = 'language',
30
- ): Promise<Map<string, string[]>> {
31
- const result = new Map<string, string[]>()
32
- const ids = referencedIds(doc)
33
- if (!ids.length || !languages.length) return result
34
- const linked = await client.fetch<{_id: string; title: string; language?: string; versions: {language?: string; id?: string}[] | null}[]>(
35
- `*[_id in $ids && defined(${field})]{
36
- _id, "title": coalesce(title, name, slug.current, _id), "language": ${field},
37
- "versions": *[_type == "translation.metadata" && references(^._id)][0].translations[]{"language": coalesce(language, _key), "id": value._ref}
38
- }`,
39
- {ids},
40
- )
41
- const versionIds = linked.flatMap((d) => (d.versions ?? []).map((v) => v.id ?? '')).filter(Boolean)
42
- const published = new Set(versionIds.length ? await client.fetch<string[]>(`*[_id in $ids]._id`, {ids: versionIds}) : [])
43
- for (const language of languages)
44
- for (const d of linked) {
45
- if (d.language === language) continue
46
- const version = (d.versions ?? []).find((v) => v.language === language)
47
- if (version?.id && published.has(version.id)) continue
48
- result.set(language, [...(result.get(language) ?? []), d.title])
49
- }
50
- return result
51
- }