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

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 {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,38 @@ 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)
285
317
  const rootRef = useRef<HTMLDivElement>(null)
286
318
  const fieldRef = useRef<HTMLTextAreaElement>(null)
287
319
 
288
- // Le texte d'origine est masqué (mise en page conservée) le temps de l'édition.
320
+ // Le TEXTE d'origine est rendu transparent le temps de l'édition (mise en page
321
+ // conservée). Jamais l'élément entier (kit >= 2.64.1) : il porte parfois le fond d'un
322
+ // bouton ou contient une image ; les masquer laissait un texte blanc sur une page
323
+ // blanche, ou une zone vide à la place de l'image.
289
324
  useEffect(() => {
290
- const previous = parts.map((el) => el.style.visibility)
291
- for (const el of parts) el.style.visibility = 'hidden'
325
+ ensureEditingStyle()
326
+ for (const el of parts) el.setAttribute(EDITING_ATTR, '')
292
327
  return () => {
293
- parts.forEach((el, i) => {
294
- el.style.visibility = previous[i] ?? ''
295
- })
328
+ for (const el of parts) el.removeAttribute(EDITING_ATTR)
296
329
  }
297
330
  // eslint-disable-next-line react-hooks/exhaustive-deps
298
331
  }, [element])
299
332
 
333
+ // Échap annule même si la saisie a perdu le focus (clic ailleurs dans l'aperçu) :
334
+ // la barre affiche « Esc » (vu sur JAF : la touche ne faisait rien).
335
+ useEffect(() => {
336
+ const onKey = (event: globalThis.KeyboardEvent) => {
337
+ if (event.key !== 'Escape') return
338
+ event.preventDefault()
339
+ event.stopPropagation()
340
+ inlineEdit.close()
341
+ }
342
+ window.addEventListener('keydown', onKey, {capture: true})
343
+ return () => window.removeEventListener('keydown', onKey, {capture: true})
344
+ }, [])
345
+
300
346
  // Suit l'élément (défilement, défilement doux, redimensionnement).
301
347
  useEffect(() => {
302
348
  let frame = 0
@@ -324,6 +370,33 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
324
370
  .then(async (doc) => {
325
371
  if (cancelled) return
326
372
  const stored = doc ? getAtPath(parse(node.path), doc) : undefined
373
+ if (isNumber) {
374
+ // Chiffre : la valeur ENREGISTRÉE (98.5), jamais le chiffre affiché (animé,
375
+ // formaté « 98,5 »). Vide dans la page : celle des valeurs par défaut.
376
+ let start = typeof stored === 'number' ? String(stored) : ''
377
+ if (typeof stored !== 'number') {
378
+ const covering = inheritedSourceFor(node.path)
379
+ if (covering) {
380
+ const own = doc ? readAt(doc, parsePath(covering.entry.path) ?? []) : undefined
381
+ const empty = own === undefined || (Array.isArray(own) && own.length === 0)
382
+ const raw = empty ? await readDefaults(covering.entry.source.id, covering.entry.source.path).catch(() => undefined) : undefined
383
+ if (raw !== undefined) {
384
+ rawInherited.current = {path: covering.entry.path, raw, rest: covering.rest}
385
+ const v = readAt(raw, parsePath(covering.rest) ?? [])
386
+ if (typeof v === 'number') start = String(v)
387
+ }
388
+ }
389
+ }
390
+ if (cancelled) return
391
+ initial.current = typeof stored === 'number' ? String(stored) : ''
392
+ inheritedStart.current = start
393
+ multiline.current = false
394
+ setBreaks(false)
395
+ setInherited(typeof stored !== 'number')
396
+ setValue(start)
397
+ setStatus('editing')
398
+ return
399
+ }
327
400
  const list = inheritedListFor(node.path)
328
401
  // Valeur héritée de toute forme : la valeur BRUTE des valeurs par défaut, gardée
329
402
  // pour la recopie à l'enregistrement (si la page n'a toujours rien à cet endroit).
@@ -402,6 +475,31 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
402
475
  }, [value, box?.width, status])
403
476
 
404
477
  const save = useCallback(() => {
478
+ if (isNumber) {
479
+ const parsed = parseNumberInput(value)
480
+ if (Number.isNaN(parsed)) {
481
+ setInvalid(true)
482
+ return
483
+ }
484
+ const same = parsed === (initial.current === '' ? null : Number(initial.current))
485
+ if (same || (inherited && parsed !== null && String(parsed) === inheritedStart.current)) {
486
+ inlineEdit.close()
487
+ return
488
+ }
489
+ const doc = getDocument(node.id)
490
+ // Chiffre hérité : la valeur brute des valeurs par défaut est recopiée dans la page
491
+ // avec ce chiffre modifié (un seul enregistrement), comme pour un texte hérité.
492
+ if (inherited && rawInherited.current) {
493
+ if (parsed === null) {
494
+ inlineEdit.close()
495
+ return
496
+ }
497
+ const copy = writeAt(rawInherited.current.raw, parsePath(rawInherited.current.rest) ?? [], parsed)
498
+ doc.patch([at(rawInherited.current.path, set(copy))])
499
+ } else doc.patch([at(node.path, parsed === null ? unset() : set(parsed))])
500
+ setStatus('saving')
501
+ return
502
+ }
405
503
  const next = multiline.current ? value : value.replace(/\s*\n\s*/g, ' ')
406
504
  if (next === initial.current || (inherited && next.trim() === inheritedStart.current.trim())) {
407
505
  inlineEdit.close()
@@ -441,12 +539,18 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
441
539
  else if (isSpanTextPath(node.path)) doc.patch([at(node.path, set(next))])
442
540
  else doc.patch([at(node.path, next.trim() === '' ? unset() : set(next))])
443
541
  setStatus('saving')
444
- }, [value, inherited, getDocument, node.id, node.path])
542
+ }, [value, inherited, getDocument, node.id, node.path, isNumber])
445
543
 
446
544
  // Enregistré : le texte saisi reste affiché jusqu'à ce que l'aperçu montre la
447
545
  // nouvelle valeur (pas de retour éclair à l'ancien texte), 6 s au plus.
448
546
  useEffect(() => {
449
547
  if (status !== 'saving') return
548
+ // Chiffre : l'affichage est formaté (et parfois animé), on ne peut pas le comparer à la
549
+ // saisie ; l'aperçu se rafraîchit, l'éditeur se ferme après un court instant.
550
+ if (isNumber) {
551
+ const done = window.setTimeout(() => inlineEdit.close(), 700)
552
+ return () => window.clearTimeout(done)
553
+ }
450
554
  const expected = value.replace(/\s+/g, ' ').trim()
451
555
  const started = performance.now()
452
556
  const timer = window.setInterval(() => {
@@ -494,15 +598,21 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
494
598
  spellCheck
495
599
  readOnly={status !== 'editing'}
496
600
  aria-label={labels.fieldLabel}
497
- onChange={(e) => setValue(e.target.value)}
601
+ onChange={(e) => {
602
+ setValue(e.target.value)
603
+ if (invalid) setInvalid(false)
604
+ }}
605
+ inputMode={isNumber ? 'decimal' : undefined}
498
606
  onKeyDown={onKeyDown}
499
607
  style={{
500
608
  ...typo,
609
+ color: readableColor(typo.color as string | undefined),
501
610
  display: 'block',
502
611
  width: '100%',
503
612
  minHeight: box.height,
504
613
  margin: 0,
505
- padding: 0,
614
+ padding,
615
+ boxSizing: 'border-box',
506
616
  border: 0,
507
617
  borderRadius: 2,
508
618
  resize: 'none',
@@ -536,7 +646,30 @@ function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewE
536
646
  </>
537
647
  )}
538
648
  </div>
539
- {inherited && status === 'editing' && (
649
+ {isNumber && invalid && status === 'editing' && (
650
+ <p
651
+ role="alert"
652
+ style={{
653
+ position: 'absolute',
654
+ left: 0,
655
+ ...(below ? {top: '100%', marginTop: 56} : {bottom: '100%', marginBottom: 56}),
656
+ width: 'max-content',
657
+ maxWidth: 'min(28rem, 90vw)',
658
+ padding: '8px 12px',
659
+ borderRadius: 6,
660
+ background: '#fff',
661
+ color: '#b42318',
662
+ boxShadow: '0 8px 24px rgba(0,0,0,0.18)',
663
+ font: `12px/1.35 ${FONT}`,
664
+ fontStyle: 'normal',
665
+ textTransform: 'none',
666
+ letterSpacing: 'normal',
667
+ }}
668
+ >
669
+ {labels.numberExpected}
670
+ </p>
671
+ )}
672
+ {inherited && status === 'editing' && !invalid && (
540
673
  <p
541
674
  style={{
542
675
  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,13 @@ 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): number | null {
116
+ const clean = text.replace(/[\s\u00a0\u202f]/g, '').replace(',', '.')
117
+ if (clean === '') return null
118
+ return /^-?\d+(\.\d+)?$/.test(clean) ? Number(clean) : Number.NaN
119
+ }
@@ -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
- }