@nocode-factory/sanity-kit 2.56.0 → 2.58.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.
- package/README.md +45 -8
- package/bin/item-types.mjs +131 -0
- package/bin/ncf-kit.mjs +97 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +6908 -6820
- package/dist/index.js.map +1 -1
- package/dist/inherited-DZvM35P6.js +101 -0
- package/dist/inherited-DZvM35P6.js.map +1 -0
- package/dist/protocol-Bl7Yj2Ro.js +31 -0
- package/dist/protocol-Bl7Yj2Ro.js.map +1 -0
- package/dist/web-edit.d.ts +192 -0
- package/dist/web-edit.js +144 -0
- package/dist/web-edit.js.map +1 -0
- package/dist/web-editing.d.ts +51 -0
- package/dist/web-editing.js +693 -0
- package/dist/web-editing.js.map +1 -0
- package/package.json +22 -2
- package/scripts/use-client.mjs +1 -1
- package/src/form/AssetSourceBrowser.tsx +68 -39
- package/src/index.ts +3 -2
- package/src/tools/collections/CollectionTable.tsx +116 -89
- package/src/ui/PreviewEditBridge.tsx +74 -0
- package/src/version.ts +1 -1
- package/src/web/edit/ImageReplaceLayer.tsx +174 -0
- package/src/web/edit/InlineTextEditor.tsx +365 -0
- package/src/web/edit/InlineTextOverlay.tsx +43 -0
- package/src/web/edit/PreviewEditing.tsx +191 -0
- package/src/web/edit/index.ts +18 -0
- package/src/web/edit/inherited.ts +174 -0
- package/src/web/edit/labels.ts +37 -0
- package/src/web/edit/protocol.ts +47 -0
- package/src/web/edit/store.ts +98 -0
- package/src/web/edit/targets.ts +186 -0
- package/src/web/editing.ts +18 -0
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
import {useCallback, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type CSSProperties, type KeyboardEvent} from 'react'
|
|
2
|
+
import {createPortal} from 'react-dom'
|
|
3
|
+
import {useDocuments, type SanityNode} from '@sanity/visual-editing'
|
|
4
|
+
import {at, set, unset} from '@sanity/mutate'
|
|
5
|
+
import {getAtPath, parse} from '@sanity/mutate/path'
|
|
6
|
+
import {vercelStegaClean, vercelStegaDecode} from '@vercel/stega'
|
|
7
|
+
import {inheritedListValue, materializeInheritedList} from './inherited'
|
|
8
|
+
import {ACCENT, CHIP, FONT, type PreviewEditingLabels} from './labels'
|
|
9
|
+
import {inlineEdit, isEditMode, isSpanTextPath, type InlineTarget} from './store'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Éditeur de texte SUR PLACE : au clic sur un texte modifiable, un champ de
|
|
13
|
+
* saisie prend sa place exacte, dans sa typographie. Entrée ou clic ailleurs =
|
|
14
|
+
* enregistré dans le BROUILLON (patch du seul champ, par le canal de l'aperçu),
|
|
15
|
+
* Échap = annulé. Le panneau du Studio s'ouvre en même temps sur le champ
|
|
16
|
+
* (comportement de Sanity, conservé). Rien n'est publié.
|
|
17
|
+
*/
|
|
18
|
+
export function InlineTextEditor({labels}: {labels: PreviewEditingLabels}) {
|
|
19
|
+
const target = useSyncExternalStore(inlineEdit.subscribe, inlineEdit.getEditing, () => null)
|
|
20
|
+
|
|
21
|
+
// Écoute en capture sur la fenêtre : passe avant le clic que Sanity intercepte sur
|
|
22
|
+
// l'élément (sans l'arrêter, pour que le panneau s'ouvre aussi sur le champ).
|
|
23
|
+
useEffect(() => {
|
|
24
|
+
const onClick = (event: MouseEvent) => {
|
|
25
|
+
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
|
|
26
|
+
if (!isEditMode()) return
|
|
27
|
+
const hovered = inlineEdit.getHovered() ?? inheritedListTarget(event.target)
|
|
28
|
+
if (!hovered || !(event.target instanceof Node) || !hovered.element.contains(event.target)) return
|
|
29
|
+
if (inlineEdit.getEditing()?.element === hovered.element) return
|
|
30
|
+
event.preventDefault()
|
|
31
|
+
inlineEdit.open(hovered)
|
|
32
|
+
}
|
|
33
|
+
window.addEventListener('click', onClick, {capture: true})
|
|
34
|
+
return () => window.removeEventListener('click', onClick, {capture: true})
|
|
35
|
+
}, [])
|
|
36
|
+
|
|
37
|
+
if (!target) return null
|
|
38
|
+
return createPortal(<EditorSession key={`${target.node.id}:${target.node.path}`} target={target} labels={labels} />, document.body)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/* ------------------------------------------------------------------------- */
|
|
42
|
+
/* Valeurs héritées jointes à la page (inheritedEditScriptProps) */
|
|
43
|
+
/* ------------------------------------------------------------------------- */
|
|
44
|
+
|
|
45
|
+
type InheritedListData = {path: string; items: Record<string, unknown>[]}
|
|
46
|
+
|
|
47
|
+
function inheritedListFor(path: string): InheritedListData | null {
|
|
48
|
+
for (const script of document.querySelectorAll<HTMLScriptElement>('script[data-ncf-inherited-list]')) {
|
|
49
|
+
const listPath = script.dataset.ncfInheritedList ?? ''
|
|
50
|
+
if (!listPath || !path.startsWith(`${listPath}[`)) continue
|
|
51
|
+
try {
|
|
52
|
+
return {path: listPath, items: JSON.parse(script.textContent ?? '[]')}
|
|
53
|
+
} catch {
|
|
54
|
+
return null
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return null
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function inheritedValueFor(path: string): string | null {
|
|
61
|
+
for (const script of document.querySelectorAll<HTMLScriptElement>('script[data-ncf-inherited-value]')) {
|
|
62
|
+
if (script.dataset.ncfInheritedValue !== path) continue
|
|
63
|
+
try {
|
|
64
|
+
const value = JSON.parse(script.textContent ?? 'null')
|
|
65
|
+
return typeof value === 'string' ? value : null
|
|
66
|
+
} catch {
|
|
67
|
+
return null
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return null
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Ligne d'une liste héritée : Sanity n'active pas son composant sur un élément
|
|
75
|
+
* que la page n'a pas encore (pas de crayon), mais chaque texte porte sa ligne
|
|
76
|
+
* exacte (stega). Le clic sur un tel texte ouvre l'éditeur directement.
|
|
77
|
+
*/
|
|
78
|
+
function inheritedListTarget(target: EventTarget | null): InlineTarget | null {
|
|
79
|
+
let el = target instanceof Element ? target : null
|
|
80
|
+
for (let depth = 0; el && depth < 5; depth++, el = el.parentElement) {
|
|
81
|
+
const info = vercelStegaDecode(el.textContent ?? '') as {href?: string} | undefined
|
|
82
|
+
if (!info?.href) continue
|
|
83
|
+
const href = decodeURIComponent(info.href)
|
|
84
|
+
const id = /[;/]id=([^;?]+)/.exec(href)?.[1]?.replace(/^drafts\./, '')
|
|
85
|
+
const type = /;type=([^;?]+)/.exec(href)?.[1]
|
|
86
|
+
const path = /;path=([^;?]+)/.exec(href)?.[1]
|
|
87
|
+
if (!id || !path || !inheritedListFor(path) || !(el instanceof HTMLElement)) return null
|
|
88
|
+
return {element: el, node: {id, type, path} as SanityNode}
|
|
89
|
+
}
|
|
90
|
+
return null
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/* ------------------------------------------------------------------------- */
|
|
94
|
+
/* Session d'édition */
|
|
95
|
+
/* ------------------------------------------------------------------------- */
|
|
96
|
+
|
|
97
|
+
type Status = 'loading' | 'editing' | 'saving'
|
|
98
|
+
type Box = {top: number; left: number; width: number; height: number}
|
|
99
|
+
|
|
100
|
+
const TYPO_PROPS = ['font-family', 'font-size', 'font-weight', 'font-style', 'font-variant', 'font-feature-settings', 'line-height', 'letter-spacing', 'word-spacing', 'text-transform', 'text-align', 'color'] as const
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Typographie du texte affiché : celle de l'élément qui porte le premier morceau
|
|
104
|
+
* de texte (un titre découpé pour une animation garde ses mots dans des sous-éléments).
|
|
105
|
+
*/
|
|
106
|
+
function textStyle(element: HTMLElement): CSSProperties {
|
|
107
|
+
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, {
|
|
108
|
+
acceptNode: (n) => (n.textContent?.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP),
|
|
109
|
+
})
|
|
110
|
+
const host = (walker.nextNode()?.parentElement as HTMLElement | null) ?? element
|
|
111
|
+
const cs = getComputedStyle(host)
|
|
112
|
+
const style: Record<string, string> = {}
|
|
113
|
+
for (const prop of TYPO_PROPS) style[prop.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase())] = cs.getPropertyValue(prop)
|
|
114
|
+
return style as CSSProperties
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const sameBox = (a: Box | null, b: Box) => !!a && a.top === b.top && a.left === b.left && a.width === b.width && a.height === b.height
|
|
118
|
+
|
|
119
|
+
const CHIP_STYLE: CSSProperties = {
|
|
120
|
+
position: 'absolute',
|
|
121
|
+
left: 0,
|
|
122
|
+
display: 'flex',
|
|
123
|
+
alignItems: 'center',
|
|
124
|
+
gap: 4,
|
|
125
|
+
padding: 4,
|
|
126
|
+
borderRadius: 999,
|
|
127
|
+
background: CHIP,
|
|
128
|
+
color: '#fff',
|
|
129
|
+
boxShadow: '0 8px 24px rgba(0,0,0,0.25)',
|
|
130
|
+
font: `500 13px/1 ${FONT}`,
|
|
131
|
+
fontStyle: 'normal',
|
|
132
|
+
textTransform: 'none',
|
|
133
|
+
letterSpacing: 'normal',
|
|
134
|
+
whiteSpace: 'nowrap',
|
|
135
|
+
}
|
|
136
|
+
const BUTTON_STYLE: CSSProperties = {display: 'flex', alignItems: 'center', gap: 8, padding: '7px 12px', border: 0, borderRadius: 999, font: 'inherit', cursor: 'pointer'}
|
|
137
|
+
const KBD_STYLE: CSSProperties = {font: `11px/1 ${FONT}`, opacity: 0.7}
|
|
138
|
+
|
|
139
|
+
function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewEditingLabels}) {
|
|
140
|
+
const {element, node} = target
|
|
141
|
+
const {getDocument} = useDocuments()
|
|
142
|
+
const [status, setStatus] = useState<Status>('loading')
|
|
143
|
+
const [value, setValue] = useState('')
|
|
144
|
+
const [inherited, setInherited] = useState(false)
|
|
145
|
+
const [box, setBox] = useState<Box | null>(null)
|
|
146
|
+
const [typo] = useState(() => textStyle(element))
|
|
147
|
+
const initial = useRef('')
|
|
148
|
+
// Texte de départ d'un texte hérité (valeur par défaut) : inchangé = rien à enregistrer.
|
|
149
|
+
const inheritedStart = useRef('')
|
|
150
|
+
const multiline = useRef(false)
|
|
151
|
+
const rootRef = useRef<HTMLDivElement>(null)
|
|
152
|
+
const fieldRef = useRef<HTMLTextAreaElement>(null)
|
|
153
|
+
|
|
154
|
+
// Le texte d'origine est masqué (mise en page conservée) le temps de l'édition.
|
|
155
|
+
useEffect(() => {
|
|
156
|
+
const previous = element.style.visibility
|
|
157
|
+
element.style.visibility = 'hidden'
|
|
158
|
+
return () => {
|
|
159
|
+
element.style.visibility = previous
|
|
160
|
+
}
|
|
161
|
+
}, [element])
|
|
162
|
+
|
|
163
|
+
// Suit l'élément (défilement, défilement doux, redimensionnement).
|
|
164
|
+
useEffect(() => {
|
|
165
|
+
let frame = 0
|
|
166
|
+
const tick = () => {
|
|
167
|
+
const r = element.getBoundingClientRect()
|
|
168
|
+
const next = {top: r.top, left: r.left, width: r.width, height: r.height}
|
|
169
|
+
setBox((prev) => (sameBox(prev, next) ? prev : next))
|
|
170
|
+
frame = requestAnimationFrame(tick)
|
|
171
|
+
}
|
|
172
|
+
tick()
|
|
173
|
+
return () => cancelAnimationFrame(frame)
|
|
174
|
+
}, [element])
|
|
175
|
+
|
|
176
|
+
// Valeur réelle du champ dans le brouillon. Champ vide = valeur HÉRITÉE : on part
|
|
177
|
+
// de la valeur par défaut exacte jointe à la page, jamais du texte affiché.
|
|
178
|
+
useEffect(() => {
|
|
179
|
+
let cancelled = false
|
|
180
|
+
getDocument(node.id)
|
|
181
|
+
.getSnapshot()
|
|
182
|
+
.then((doc) => {
|
|
183
|
+
if (cancelled) return
|
|
184
|
+
const stored = doc ? getAtPath(parse(node.path), doc) : undefined
|
|
185
|
+
const list = inheritedListFor(node.path)
|
|
186
|
+
const text =
|
|
187
|
+
typeof stored === 'string' && stored !== ''
|
|
188
|
+
? stored
|
|
189
|
+
: (inheritedValueFor(node.path) ?? (list ? inheritedListValue(list, node.path) : null) ?? vercelStegaClean(element.textContent ?? '').trim())
|
|
190
|
+
initial.current = typeof stored === 'string' ? stored : ''
|
|
191
|
+
inheritedStart.current = text
|
|
192
|
+
multiline.current = text.includes('\n')
|
|
193
|
+
setInherited(typeof stored !== 'string' || stored === '')
|
|
194
|
+
setValue(text)
|
|
195
|
+
setStatus('editing')
|
|
196
|
+
})
|
|
197
|
+
.catch(() => {
|
|
198
|
+
if (!cancelled) inlineEdit.close()
|
|
199
|
+
})
|
|
200
|
+
return () => {
|
|
201
|
+
cancelled = true
|
|
202
|
+
}
|
|
203
|
+
}, [getDocument, node.id, node.path, element])
|
|
204
|
+
|
|
205
|
+
useEffect(() => {
|
|
206
|
+
if (status !== 'editing') return
|
|
207
|
+
const field = fieldRef.current
|
|
208
|
+
if (!field) return
|
|
209
|
+
const focusField = () => {
|
|
210
|
+
field.focus({preventScroll: true})
|
|
211
|
+
field.setSelectionRange(field.value.length, field.value.length)
|
|
212
|
+
}
|
|
213
|
+
focusField()
|
|
214
|
+
// Le Studio ouvre le champ dans son panneau juste après le clic et y place le
|
|
215
|
+
// curseur : l'aperçu le reprend pendant ce court instant (sinon la saisie partirait
|
|
216
|
+
// dans le champ du Studio).
|
|
217
|
+
const until = performance.now() + 1500
|
|
218
|
+
const onBlur = () => {
|
|
219
|
+
if (performance.now() < until) window.setTimeout(focusField, 0)
|
|
220
|
+
}
|
|
221
|
+
window.addEventListener('blur', onBlur)
|
|
222
|
+
const retry = window.setTimeout(focusField, 300)
|
|
223
|
+
return () => {
|
|
224
|
+
window.removeEventListener('blur', onBlur)
|
|
225
|
+
window.clearTimeout(retry)
|
|
226
|
+
}
|
|
227
|
+
}, [status])
|
|
228
|
+
|
|
229
|
+
useLayoutEffect(() => {
|
|
230
|
+
const field = fieldRef.current
|
|
231
|
+
if (!field) return
|
|
232
|
+
field.style.height = 'auto'
|
|
233
|
+
field.style.height = `${field.scrollHeight}px`
|
|
234
|
+
}, [value, box?.width, status])
|
|
235
|
+
|
|
236
|
+
const save = useCallback(() => {
|
|
237
|
+
const next = multiline.current ? value : value.replace(/\s*\n\s*/g, ' ')
|
|
238
|
+
if (next === initial.current || (inherited && next.trim() === inheritedStart.current.trim())) {
|
|
239
|
+
inlineEdit.close()
|
|
240
|
+
return
|
|
241
|
+
}
|
|
242
|
+
// Ligne d'une liste héritée que la page n'a pas encore : la liste par défaut est
|
|
243
|
+
// recopiée dans la page avec cette ligne modifiée (même enregistrement).
|
|
244
|
+
const list = inherited ? inheritedListFor(node.path) : null
|
|
245
|
+
const items = list ? materializeInheritedList(list, node.path, next) : null
|
|
246
|
+
const doc = getDocument(node.id)
|
|
247
|
+
if (list && items) doc.patch([at(list.path, set(items))])
|
|
248
|
+
// Morceau de texte riche : jamais retiré (un morceau sans texte casse le bloc), vidé.
|
|
249
|
+
else if (isSpanTextPath(node.path)) doc.patch([at(node.path, set(next))])
|
|
250
|
+
else doc.patch([at(node.path, next.trim() === '' ? unset() : set(next))])
|
|
251
|
+
setStatus('saving')
|
|
252
|
+
}, [value, inherited, getDocument, node.id, node.path])
|
|
253
|
+
|
|
254
|
+
// Enregistré : le texte saisi reste affiché jusqu'à ce que l'aperçu montre la
|
|
255
|
+
// nouvelle valeur (pas de retour éclair à l'ancien texte), 6 s au plus.
|
|
256
|
+
useEffect(() => {
|
|
257
|
+
if (status !== 'saving') return
|
|
258
|
+
const expected = value.replace(/\s+/g, ' ').trim()
|
|
259
|
+
const started = performance.now()
|
|
260
|
+
const timer = window.setInterval(() => {
|
|
261
|
+
const shown = vercelStegaClean(element.textContent ?? '').replace(/\s+/g, ' ').trim()
|
|
262
|
+
if (shown.includes(expected) || expected === '' || performance.now() - started > 6000) inlineEdit.close()
|
|
263
|
+
}, 150)
|
|
264
|
+
return () => window.clearInterval(timer)
|
|
265
|
+
}, [status, value, element])
|
|
266
|
+
|
|
267
|
+
// Clic ailleurs dans l'aperçu = enregistrer.
|
|
268
|
+
useEffect(() => {
|
|
269
|
+
if (status !== 'editing') return
|
|
270
|
+
const onPointerDown = (event: PointerEvent) => {
|
|
271
|
+
if (event.target instanceof Node && rootRef.current?.contains(event.target)) return
|
|
272
|
+
save()
|
|
273
|
+
}
|
|
274
|
+
window.addEventListener('pointerdown', onPointerDown, {capture: true})
|
|
275
|
+
return () => window.removeEventListener('pointerdown', onPointerDown, {capture: true})
|
|
276
|
+
}, [status, save])
|
|
277
|
+
|
|
278
|
+
const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
|
|
279
|
+
if (event.key === 'Escape') {
|
|
280
|
+
event.preventDefault()
|
|
281
|
+
inlineEdit.close()
|
|
282
|
+
} else if (event.key === 'Enter' && !(event.shiftKey && multiline.current)) {
|
|
283
|
+
event.preventDefault()
|
|
284
|
+
save()
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (!box) return null
|
|
289
|
+
const below = box.top + box.height + 56 < window.innerHeight
|
|
290
|
+
const place: CSSProperties = below ? {top: '100%', marginTop: 12} : {bottom: '100%', marginBottom: 12}
|
|
291
|
+
|
|
292
|
+
return (
|
|
293
|
+
<div
|
|
294
|
+
ref={rootRef}
|
|
295
|
+
data-sanity-overlay-element
|
|
296
|
+
style={{position: 'fixed', zIndex: 2147483000, top: box.top, left: box.left, width: box.width, minHeight: box.height}}
|
|
297
|
+
>
|
|
298
|
+
<textarea
|
|
299
|
+
ref={fieldRef}
|
|
300
|
+
value={value}
|
|
301
|
+
rows={1}
|
|
302
|
+
spellCheck
|
|
303
|
+
readOnly={status !== 'editing'}
|
|
304
|
+
aria-label={labels.fieldLabel}
|
|
305
|
+
onChange={(e) => setValue(e.target.value)}
|
|
306
|
+
onKeyDown={onKeyDown}
|
|
307
|
+
style={{
|
|
308
|
+
...typo,
|
|
309
|
+
display: 'block',
|
|
310
|
+
width: '100%',
|
|
311
|
+
minHeight: box.height,
|
|
312
|
+
margin: 0,
|
|
313
|
+
padding: 0,
|
|
314
|
+
border: 0,
|
|
315
|
+
borderRadius: 2,
|
|
316
|
+
resize: 'none',
|
|
317
|
+
overflow: 'hidden',
|
|
318
|
+
background: 'transparent',
|
|
319
|
+
caretColor: ACCENT,
|
|
320
|
+
outline: `2px solid ${ACCENT}`,
|
|
321
|
+
outlineOffset: 4,
|
|
322
|
+
opacity: status === 'loading' ? 0 : 1,
|
|
323
|
+
}}
|
|
324
|
+
/>
|
|
325
|
+
<div style={{...CHIP_STYLE, ...place}}>
|
|
326
|
+
{status === 'saving' ? (
|
|
327
|
+
<span style={{padding: '6px 10px'}}>{labels.saved}</span>
|
|
328
|
+
) : (
|
|
329
|
+
<>
|
|
330
|
+
<button type="button" onClick={save} disabled={status !== 'editing'} style={{...BUTTON_STYLE, background: ACCENT, color: '#fff'}}>
|
|
331
|
+
{labels.save}
|
|
332
|
+
<kbd style={KBD_STYLE}>↵</kbd>
|
|
333
|
+
</button>
|
|
334
|
+
<button type="button" onClick={() => inlineEdit.close()} style={{...BUTTON_STYLE, background: 'transparent', color: 'rgba(255,255,255,0.85)'}}>
|
|
335
|
+
{labels.cancel}
|
|
336
|
+
<kbd style={KBD_STYLE}>Esc</kbd>
|
|
337
|
+
</button>
|
|
338
|
+
</>
|
|
339
|
+
)}
|
|
340
|
+
</div>
|
|
341
|
+
{inherited && status === 'editing' && (
|
|
342
|
+
<p
|
|
343
|
+
style={{
|
|
344
|
+
position: 'absolute',
|
|
345
|
+
left: 0,
|
|
346
|
+
...(below ? {top: '100%', marginTop: 56} : {bottom: '100%', marginBottom: 56}),
|
|
347
|
+
width: 'max-content',
|
|
348
|
+
maxWidth: 'min(28rem, 90vw)',
|
|
349
|
+
padding: '8px 12px',
|
|
350
|
+
borderRadius: 6,
|
|
351
|
+
background: '#fff',
|
|
352
|
+
color: '#1b1d21',
|
|
353
|
+
boxShadow: '0 8px 24px rgba(0,0,0,0.18)',
|
|
354
|
+
font: `12px/1.35 ${FONT}`,
|
|
355
|
+
fontStyle: 'normal',
|
|
356
|
+
textTransform: 'none',
|
|
357
|
+
letterSpacing: 'normal',
|
|
358
|
+
}}
|
|
359
|
+
>
|
|
360
|
+
{labels.inheritedNote}
|
|
361
|
+
</p>
|
|
362
|
+
)}
|
|
363
|
+
</div>
|
|
364
|
+
)
|
|
365
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import {useEffect} from 'react'
|
|
2
|
+
import type {OverlayComponentProps} from '@sanity/visual-editing/unstable_overlay-components'
|
|
3
|
+
import {ACCENT} from './labels'
|
|
4
|
+
import {inlineEdit} from './store'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Monté par l'overlay de Sanity au survol d'un texte modifiable sur place : crayon
|
|
8
|
+
* en haut à droite du cadre, et inscription comme cible du prochain clic
|
|
9
|
+
* (`InlineTextEditor` écoute le clic avant Sanity).
|
|
10
|
+
*/
|
|
11
|
+
export function InlineTextOverlay({element, node}: OverlayComponentProps) {
|
|
12
|
+
useEffect(() => {
|
|
13
|
+
if (!(element instanceof HTMLElement)) return
|
|
14
|
+
inlineEdit.setHovered({element, node})
|
|
15
|
+
return () => inlineEdit.clearHovered(element)
|
|
16
|
+
}, [element, node])
|
|
17
|
+
|
|
18
|
+
return (
|
|
19
|
+
<span
|
|
20
|
+
aria-hidden
|
|
21
|
+
style={{
|
|
22
|
+
pointerEvents: 'none',
|
|
23
|
+
position: 'absolute',
|
|
24
|
+
top: -12,
|
|
25
|
+
right: -12,
|
|
26
|
+
display: 'flex',
|
|
27
|
+
width: 24,
|
|
28
|
+
height: 24,
|
|
29
|
+
alignItems: 'center',
|
|
30
|
+
justifyContent: 'center',
|
|
31
|
+
borderRadius: 999,
|
|
32
|
+
background: ACCENT,
|
|
33
|
+
color: '#fff',
|
|
34
|
+
boxShadow: '0 4px 12px rgba(0,0,0,0.2)',
|
|
35
|
+
}}
|
|
36
|
+
>
|
|
37
|
+
<svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
|
|
38
|
+
<path d="M10.5 2.5l3 3L6 13H3v-3l7.5-7.5z" />
|
|
39
|
+
<path d="M9 4l3 3" />
|
|
40
|
+
</svg>
|
|
41
|
+
</span>
|
|
42
|
+
)
|
|
43
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import {useEffect, useRef, useState} from 'react'
|
|
2
|
+
import type {OverlayComponentResolver} from '@sanity/visual-editing'
|
|
3
|
+
import {ImageReplaceLayer} from './ImageReplaceLayer'
|
|
4
|
+
import {InlineTextEditor} from './InlineTextEditor'
|
|
5
|
+
import {InlineTextOverlay} from './InlineTextOverlay'
|
|
6
|
+
import {CHIP, FONT, DEFAULT_PREVIEW_EDITING_LABELS, type PreviewEditingLabels} from './labels'
|
|
7
|
+
import {EDIT_MODE_ATTRIBUTE, EDIT_MODE_STORAGE_KEY, PREVIEW_EDIT_ATTRIBUTE, isEditMode, isInlineEditablePath, setEditModeResolver} from './store'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* ÉDITION SUR PLACE dans l'aperçu (Presentation), à monter à côté de
|
|
11
|
+
* `<VisualEditing/>` en mode brouillon :
|
|
12
|
+
*
|
|
13
|
+
* ```tsx
|
|
14
|
+
* <VisualEditing refresh={useNcfPreviewRefresh()} components={ncfOverlayComponents} />
|
|
15
|
+
* <NcfPreviewEditing labels={messages.previewEditing} />
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* - texte (champ chaîne, ligne d'un titre en texte riche) : crayon au survol, au
|
|
19
|
+
* clic un champ de saisie à sa place exacte ; enregistré dans le brouillon ;
|
|
20
|
+
* - image : « Replace this image » au survol, au clic le Studio ouvre la
|
|
21
|
+
* médiathèque (pont monté par le plugin du kit) ;
|
|
22
|
+
* - « Mode édition / Mode visite » : en visite, un clic suit les liens.
|
|
23
|
+
*/
|
|
24
|
+
export const ncfOverlayComponents: OverlayComponentResolver = (context) => {
|
|
25
|
+
if (isEditMode() && isInlineEditablePath(context.type, context.node.path, context.element)) return InlineTextOverlay
|
|
26
|
+
return undefined
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export type NcfPreviewEditingProps = {
|
|
30
|
+
/** Libellés (anglais par défaut) : passer ceux de la langue du projet. */
|
|
31
|
+
labels?: Partial<PreviewEditingLabels>
|
|
32
|
+
/**
|
|
33
|
+
* `'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
|
+
* interrupteur d'animations) ; le kit n'affiche alors rien.
|
|
36
|
+
*/
|
|
37
|
+
editMode?: 'toggle' | (() => boolean)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* En mode édition, la zone cliquable étendue d'un lien (carte entièrement
|
|
42
|
+
* cliquable : `a::after` en plein cadre) est transparente à la souris : texte et
|
|
43
|
+
* images de la carte redeviennent atteignables.
|
|
44
|
+
*/
|
|
45
|
+
const EDIT_CSS = `html[${PREVIEW_EDIT_ATTRIBUTE}] a::after, html[${PREVIEW_EDIT_ATTRIBUTE}] a::before { pointer-events: none !important; }`
|
|
46
|
+
|
|
47
|
+
export function NcfPreviewEditing({labels, editMode = 'toggle'}: NcfPreviewEditingProps) {
|
|
48
|
+
const text = {...DEFAULT_PREVIEW_EDITING_LABELS, ...labels}
|
|
49
|
+
const custom = typeof editMode === 'function' ? editMode : null
|
|
50
|
+
// Dernière fonction du projet, sans relancer l'effet à chaque rendu.
|
|
51
|
+
const customRef = useRef(custom)
|
|
52
|
+
customRef.current = custom
|
|
53
|
+
const hasCustom = custom !== null
|
|
54
|
+
useOverlayRectRefresh()
|
|
55
|
+
|
|
56
|
+
useEffect(() => {
|
|
57
|
+
setEditModeResolver(hasCustom ? () => customRef.current?.() ?? false : null)
|
|
58
|
+
const root = document.documentElement
|
|
59
|
+
// Ne touche l'attribut que s'il doit changer : l'observateur ci-dessous ne se
|
|
60
|
+
// relance pas lui-même.
|
|
61
|
+
const sync = () => {
|
|
62
|
+
const want = isEditMode()
|
|
63
|
+
if (want && !root.hasAttribute(PREVIEW_EDIT_ATTRIBUTE)) root.setAttribute(PREVIEW_EDIT_ATTRIBUTE, '')
|
|
64
|
+
else if (!want && root.hasAttribute(PREVIEW_EDIT_ATTRIBUTE)) root.removeAttribute(PREVIEW_EDIT_ATTRIBUTE)
|
|
65
|
+
}
|
|
66
|
+
sync()
|
|
67
|
+
// Le mode peut changer sans rechargement (interrupteur du kit ou du projet,
|
|
68
|
+
// qui posent un attribut sur <html>) : on resynchronise à chaque changement.
|
|
69
|
+
const observer = new MutationObserver(sync)
|
|
70
|
+
observer.observe(root, {attributes: true})
|
|
71
|
+
return () => {
|
|
72
|
+
observer.disconnect()
|
|
73
|
+
root.removeAttribute(PREVIEW_EDIT_ATTRIBUTE)
|
|
74
|
+
setEditModeResolver(null)
|
|
75
|
+
}
|
|
76
|
+
}, [hasCustom])
|
|
77
|
+
|
|
78
|
+
return (
|
|
79
|
+
<>
|
|
80
|
+
<style>{EDIT_CSS}</style>
|
|
81
|
+
<InlineTextEditor labels={text} />
|
|
82
|
+
<ImageReplaceLayer label={text.replaceImage} />
|
|
83
|
+
{!hasCustom && <EditModeToggle labels={text} />}
|
|
84
|
+
</>
|
|
85
|
+
)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Interrupteur « Edit mode / Browse mode » : affiché dans l'aperçu du Studio seulement. */
|
|
89
|
+
function EditModeToggle({labels}: {labels: PreviewEditingLabels}) {
|
|
90
|
+
const [embedded, setEmbedded] = useState(false)
|
|
91
|
+
const [edit, setEdit] = useState(true)
|
|
92
|
+
|
|
93
|
+
useEffect(() => {
|
|
94
|
+
let inFrame = true
|
|
95
|
+
try {
|
|
96
|
+
inFrame = window.self !== window.top
|
|
97
|
+
} catch {
|
|
98
|
+
inFrame = true
|
|
99
|
+
}
|
|
100
|
+
setEmbedded(inFrame)
|
|
101
|
+
let stored: string | null = null
|
|
102
|
+
try {
|
|
103
|
+
stored = window.localStorage.getItem(EDIT_MODE_STORAGE_KEY)
|
|
104
|
+
} catch {
|
|
105
|
+
stored = null
|
|
106
|
+
}
|
|
107
|
+
const next = stored !== 'browse'
|
|
108
|
+
setEdit(next)
|
|
109
|
+
document.documentElement.setAttribute(EDIT_MODE_ATTRIBUTE, next ? 'edit' : 'browse')
|
|
110
|
+
return () => document.documentElement.removeAttribute(EDIT_MODE_ATTRIBUTE)
|
|
111
|
+
}, [])
|
|
112
|
+
|
|
113
|
+
if (!embedded) return null
|
|
114
|
+
const toggle = () => {
|
|
115
|
+
const next = !edit
|
|
116
|
+
setEdit(next)
|
|
117
|
+
document.documentElement.setAttribute(EDIT_MODE_ATTRIBUTE, next ? 'edit' : 'browse')
|
|
118
|
+
try {
|
|
119
|
+
window.localStorage.setItem(EDIT_MODE_STORAGE_KEY, next ? 'edit' : 'browse')
|
|
120
|
+
} catch {
|
|
121
|
+
// Stockage indisponible : le choix vaut pour cette page seulement.
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return (
|
|
126
|
+
<button
|
|
127
|
+
type="button"
|
|
128
|
+
role="switch"
|
|
129
|
+
aria-checked={edit}
|
|
130
|
+
aria-label={labels.modeLabel}
|
|
131
|
+
onClick={toggle}
|
|
132
|
+
data-sanity-overlay-element
|
|
133
|
+
style={{
|
|
134
|
+
position: 'fixed',
|
|
135
|
+
left: 16,
|
|
136
|
+
bottom: 16,
|
|
137
|
+
zIndex: 2147482500,
|
|
138
|
+
display: 'flex',
|
|
139
|
+
alignItems: 'center',
|
|
140
|
+
gap: 8,
|
|
141
|
+
padding: '8px 14px 8px 10px',
|
|
142
|
+
border: 0,
|
|
143
|
+
borderRadius: 999,
|
|
144
|
+
background: CHIP,
|
|
145
|
+
color: '#fff',
|
|
146
|
+
boxShadow: '0 8px 24px rgba(0,0,0,0.25)',
|
|
147
|
+
font: `500 12px/1 ${FONT}`,
|
|
148
|
+
cursor: 'pointer',
|
|
149
|
+
}}
|
|
150
|
+
>
|
|
151
|
+
<span aria-hidden style={{width: 8, height: 8, borderRadius: 999, background: edit ? '#3ecf8e' : 'rgba(255,255,255,0.45)'}} />
|
|
152
|
+
{edit ? labels.editMode : labels.browseMode}
|
|
153
|
+
</button>
|
|
154
|
+
)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Cadres de Sanity à la bonne place. L'overlay mémorise la position de chaque
|
|
159
|
+
* élément et ne la remesure qu'au redimensionnement : une page qui se décale
|
|
160
|
+
* après le chargement (photos différées, effets liés au défilement) laissait les
|
|
161
|
+
* cadres à l'ancienne place. On demande la remesure quand la hauteur de la page
|
|
162
|
+
* change, quand une image finit de charger et à la fin d'un défilement, par le
|
|
163
|
+
* signal que Sanity écoute déjà : un événement « scroll » sur <body> (il ne
|
|
164
|
+
* remonte pas jusqu'à la fenêtre : aucun effet de défilement ne le reçoit).
|
|
165
|
+
*/
|
|
166
|
+
function useOverlayRectRefresh() {
|
|
167
|
+
useEffect(() => {
|
|
168
|
+
let frame = 0
|
|
169
|
+
let timer = 0
|
|
170
|
+
const refresh = () => {
|
|
171
|
+
cancelAnimationFrame(frame)
|
|
172
|
+
frame = requestAnimationFrame(() => document.body.dispatchEvent(new Event('scroll')))
|
|
173
|
+
}
|
|
174
|
+
const onScroll = () => {
|
|
175
|
+
window.clearTimeout(timer)
|
|
176
|
+
timer = window.setTimeout(refresh, 120)
|
|
177
|
+
}
|
|
178
|
+
const ro = new ResizeObserver(refresh)
|
|
179
|
+
ro.observe(document.body)
|
|
180
|
+
window.addEventListener('scroll', onScroll, {passive: true})
|
|
181
|
+
document.addEventListener('load', refresh, true)
|
|
182
|
+
refresh()
|
|
183
|
+
return () => {
|
|
184
|
+
ro.disconnect()
|
|
185
|
+
cancelAnimationFrame(frame)
|
|
186
|
+
window.clearTimeout(timer)
|
|
187
|
+
window.removeEventListener('scroll', onScroll)
|
|
188
|
+
document.removeEventListener('load', refresh, true)
|
|
189
|
+
}
|
|
190
|
+
}, [])
|
|
191
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ÉDITION DANS L'APERÇU, côté données. Module neutre (ni `'use client'` ni API
|
|
3
|
+
* serveur) : requêtes en brouillon, `<Sections/>`, composants d'image.
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* import {annotateImageEditTargets, withPreviewEditTargets, rekeyOwnImageTargets, imageEditAttributes, imageAlt, inheritedEditScriptProps} from '@nocode-factory/sanity-kit/web/edit'
|
|
7
|
+
* ```
|
|
8
|
+
*
|
|
9
|
+
* Les composants (éditeur, pastille d'image, interrupteur) sont dans
|
|
10
|
+
* `@nocode-factory/sanity-kit/web` (`NcfPreviewEditing`, `ncfOverlayComponents`).
|
|
11
|
+
* Dépendances : `@sanity/visual-editing` (fourni par next-sanity).
|
|
12
|
+
*/
|
|
13
|
+
export {annotateImageEditTargets, withPreviewEditTargets, rekeyOwnImageTargets, imageEditAttributes, imageAlt} from './targets'
|
|
14
|
+
export type {ImageEditValue, ImageEditOptions, ImageEditAttributes} from './targets'
|
|
15
|
+
export {retagInheritedList, inheritedEditScriptProps, inheritedListValue, materializeInheritedList} from './inherited'
|
|
16
|
+
export type {InheritedEdit} from './inherited'
|
|
17
|
+
export {REPLACE_IMAGE_MESSAGE, isReplaceImageRequest, replaceImagePatch} from './protocol'
|
|
18
|
+
export type {ReplaceImageRequest} from './protocol'
|