@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
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import {useCallback, useMemo, useRef, useState} from 'react'
|
|
1
|
+
import {useCallback, useMemo, useRef, useState, type ComponentType} from 'react'
|
|
2
2
|
import {Badge, Box, Flex, Spinner, Stack, Text} from '@sanity/ui'
|
|
3
3
|
import {ChevronDownIcon} from '@sanity/icons/ChevronDown'
|
|
4
4
|
import {ChevronUpIcon} from '@sanity/icons/ChevronUp'
|
|
5
|
+
import {DocumentIcon} from '@sanity/icons/Document'
|
|
5
6
|
import {usePaneRouter} from 'sanity/structure'
|
|
6
7
|
import {useRouter} from 'sanity/router'
|
|
7
8
|
import {useSchema} from 'sanity'
|
|
@@ -12,7 +13,7 @@ import {downloadText} from '../../lib/download'
|
|
|
12
13
|
import {deriveCollectionColumns, type CollectionColumn} from '../../lib/collectionColumns'
|
|
13
14
|
import type {SchemaTypeLike} from '../../lib/schemaColumns'
|
|
14
15
|
import type {CollectionRow} from '../../lib/collectionRows'
|
|
15
|
-
import {BORDER, BORDER_SOFT,
|
|
16
|
+
import {BORDER, BORDER_SOFT, TABULAR} from '../../ui/tokens'
|
|
16
17
|
import {QueryError} from '../../ui/QueryError'
|
|
17
18
|
import {CollectionToolbar, type CollectionView} from './CollectionToolbar'
|
|
18
19
|
|
|
@@ -20,6 +21,8 @@ import {CollectionToolbar, type CollectionView} from './CollectionToolbar'
|
|
|
20
21
|
const DEFAULT_MAX = 6
|
|
21
22
|
/** Largeur minimale d'une colonne au redimensionnement. */
|
|
22
23
|
const MIN_WIDTH = 80
|
|
24
|
+
/** Côté de la vignette d'icône (vue liste), calé sur la liste native de Sanity. */
|
|
25
|
+
const MEDIA = '2.0625rem'
|
|
23
26
|
|
|
24
27
|
function defaultVisible(columns: readonly CollectionColumn[]): string[] {
|
|
25
28
|
const title = columns.find((c) => c.key === 'title') ?? columns.find((c) => c.kind === 'text')
|
|
@@ -29,7 +32,7 @@ function defaultVisible(columns: readonly CollectionColumn[]): string[] {
|
|
|
29
32
|
|
|
30
33
|
/** Largeur par défaut d'une colonne : le titre large, le reste selon le type. */
|
|
31
34
|
function defaultWidth(column: CollectionColumn, isFirst: boolean): number {
|
|
32
|
-
if (isFirst) return
|
|
35
|
+
if (isFirst) return 340
|
|
33
36
|
switch (column.kind) {
|
|
34
37
|
case 'number':
|
|
35
38
|
return 110
|
|
@@ -79,25 +82,23 @@ export function CollectionTable({type, filter, params, newTemplate}: CollectionT
|
|
|
79
82
|
const [selected, setSelected] = useState<string[] | null>(null)
|
|
80
83
|
const [sort, setSort] = useState<CollectionSort>({key: null, direction: 'asc'})
|
|
81
84
|
const [search, setSearch] = useState('')
|
|
82
|
-
const [columnFilters, setColumnFilters] = useState<Record<string, string>>({})
|
|
83
85
|
const [widths, setWidths] = useState<Record<string, number>>({})
|
|
84
86
|
|
|
85
87
|
// Toutes les colonnes viennent du schéma (sans requête) : elles fixent le
|
|
86
88
|
// défaut et alimentent le sélecteur. Seules les visibles sont ensuite
|
|
87
89
|
// projetées par le hook de données.
|
|
88
90
|
const schema = useSchema()
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
)
|
|
91
|
+
const schemaType = schema.get(type) as SchemaTypeLike | undefined
|
|
92
|
+
const TypeIcon = (schemaType as {icon?: ComponentType} | undefined)?.icon
|
|
93
|
+
const allColumns = useMemo(() => deriveCollectionColumns(schemaType), [schemaType])
|
|
93
94
|
const visibleKeys = useMemo(() => selected ?? defaultVisible(allColumns), [selected, allColumns])
|
|
94
95
|
|
|
95
96
|
const {visibleColumns, rows, loading, error, refresh} = useCollection(type, visibleKeys, {filter, params})
|
|
96
97
|
|
|
97
98
|
const visible = useMemo(() => {
|
|
98
|
-
const filtered = filterRows(rows, {search, columns:
|
|
99
|
+
const filtered = filterRows(rows, {search, columns: {}}, visibleColumns)
|
|
99
100
|
return sortRows(filtered, sort, visibleColumns)
|
|
100
|
-
}, [rows, search,
|
|
101
|
+
}, [rows, search, visibleColumns, sort])
|
|
101
102
|
|
|
102
103
|
// Largeur effective de chaque colonne visible (état ou défaut selon le type).
|
|
103
104
|
const cols = useMemo(
|
|
@@ -112,12 +113,6 @@ export function CollectionTable({type, filter, params, newTemplate}: CollectionT
|
|
|
112
113
|
const base = current ?? defaultVisible(allColumns)
|
|
113
114
|
return base.includes(key) ? base.filter((k) => k !== key) : [...base, key]
|
|
114
115
|
})
|
|
115
|
-
// Un filtre sur une colonne qu'on masque n'a plus de sens.
|
|
116
|
-
setColumnFilters((current) => {
|
|
117
|
-
if (!current[key]) return current
|
|
118
|
-
const {[key]: _removed, ...rest} = current
|
|
119
|
-
return rest
|
|
120
|
-
})
|
|
121
116
|
},
|
|
122
117
|
[allColumns],
|
|
123
118
|
)
|
|
@@ -134,10 +129,6 @@ export function CollectionTable({type, filter, params, newTemplate}: CollectionT
|
|
|
134
129
|
downloadText(`${type}.csv`, toCsv(visible, visibleColumns))
|
|
135
130
|
}, [type, visible, visibleColumns])
|
|
136
131
|
|
|
137
|
-
const onColumnFilter = useCallback((key: string, value: string) => {
|
|
138
|
-
setColumnFilters((current) => ({...current, [key]: value}))
|
|
139
|
-
}, [])
|
|
140
|
-
|
|
141
132
|
// Création : applique le template du niveau feuille (langue, catégorie…) s'il
|
|
142
133
|
// est fourni, sinon un document nu du type.
|
|
143
134
|
const onCreate = useCallback(() => {
|
|
@@ -184,7 +175,12 @@ export function CollectionTable({type, filter, params, newTemplate}: CollectionT
|
|
|
184
175
|
? `${rows.length} item${rows.length > 1 ? 's' : ''}`
|
|
185
176
|
: `${visible.length} of ${rows.length}`
|
|
186
177
|
|
|
187
|
-
const
|
|
178
|
+
const titleKey = visibleColumns[0]?.key
|
|
179
|
+
// Sous-titre de la vue liste : un slug/chemin/URL si présent, sinon la
|
|
180
|
+
// première colonne texte après le titre (façon liste native).
|
|
181
|
+
const subtitleKey =
|
|
182
|
+
visibleColumns.find((c, i) => i > 0 && /slug|path|url|email/i.test(c.key))?.key ??
|
|
183
|
+
visibleColumns.find((c, i) => i > 0 && c.kind === 'text')?.key
|
|
188
184
|
|
|
189
185
|
return (
|
|
190
186
|
<Stack gap={3}>
|
|
@@ -217,12 +213,12 @@ export function CollectionTable({type, filter, params, newTemplate}: CollectionT
|
|
|
217
213
|
</Text>
|
|
218
214
|
</Box>
|
|
219
215
|
) : view === 'list' ? (
|
|
220
|
-
<Box style={{border: `1px solid ${BORDER_SOFT}`, borderRadius: 6}}>
|
|
221
|
-
<style>{`.ncf-coll-body a{display:
|
|
216
|
+
<Box style={{border: `1px solid ${BORDER_SOFT}`, borderRadius: 6, overflow: 'hidden'}}>
|
|
217
|
+
<style>{`.ncf-coll-body a{display:block;color:inherit;text-decoration:none}`}</style>
|
|
222
218
|
<Box className="ncf-coll-body">
|
|
223
219
|
{visible.map((row) => (
|
|
224
220
|
<ChildLink key={row.id} childId={row.id}>
|
|
225
|
-
<ListRowView row={row} titleKey={
|
|
221
|
+
<ListRowView row={row} titleKey={titleKey} subtitleKey={subtitleKey} Icon={TypeIcon} />
|
|
226
222
|
</ChildLink>
|
|
227
223
|
))}
|
|
228
224
|
{visible.length === 0 && (
|
|
@@ -238,22 +234,23 @@ export function CollectionTable({type, filter, params, newTemplate}: CollectionT
|
|
|
238
234
|
<Box style={{overflowX: 'auto', border: `1px solid ${BORDER_SOFT}`, borderRadius: 6}}>
|
|
239
235
|
<style>{`.ncf-coll-body a{display:contents;color:inherit;text-decoration:none}`}</style>
|
|
240
236
|
<Box style={{width: totalWidth, minWidth: '100%'}}>
|
|
241
|
-
{/* En-tête : libellé triable + déplaçable, poignée de largeur
|
|
237
|
+
{/* En-tête : libellé triable + déplaçable, poignée de largeur. */}
|
|
242
238
|
<Flex
|
|
243
239
|
paddingX={3}
|
|
244
|
-
paddingY={
|
|
245
|
-
align="
|
|
240
|
+
paddingY={3}
|
|
241
|
+
align="center"
|
|
246
242
|
style={{
|
|
247
243
|
borderBottom: `1px solid ${BORDER}`,
|
|
248
244
|
position: 'sticky',
|
|
249
245
|
top: 0,
|
|
250
|
-
background: 'var(--card-bg-color, inherit)',
|
|
246
|
+
background: 'var(--card-muted-bg-color, var(--card-bg-color, inherit))',
|
|
251
247
|
zIndex: 2,
|
|
252
248
|
}}
|
|
253
249
|
>
|
|
254
250
|
{cols.map(({column, width}) => {
|
|
255
251
|
const active = sort.key === column.key
|
|
256
252
|
const Arrow = sort.direction === 'asc' ? ChevronUpIcon : ChevronDownIcon
|
|
253
|
+
const alignEnd = column.kind === 'number'
|
|
257
254
|
return (
|
|
258
255
|
<Box
|
|
259
256
|
key={column.key}
|
|
@@ -273,46 +270,27 @@ export function CollectionTable({type, filter, params, newTemplate}: CollectionT
|
|
|
273
270
|
borderLeft: dragOverKey === column.key ? `2px solid var(--card-focus-ring-color, #2276fc)` : '2px solid transparent',
|
|
274
271
|
}}
|
|
275
272
|
>
|
|
276
|
-
<
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
<input
|
|
298
|
-
type="text"
|
|
299
|
-
value={columnFilters[column.key] ?? ''}
|
|
300
|
-
placeholder="Filter…"
|
|
301
|
-
onChange={(event) => onColumnFilter(column.key, event.currentTarget.value)}
|
|
302
|
-
style={{
|
|
303
|
-
width: '100%',
|
|
304
|
-
boxSizing: 'border-box',
|
|
305
|
-
font: 'inherit',
|
|
306
|
-
fontSize: 11,
|
|
307
|
-
padding: '3px 6px',
|
|
308
|
-
borderRadius: 3,
|
|
309
|
-
border: `1px solid ${BORDER_SOFT}`,
|
|
310
|
-
background: 'var(--card-bg-color)',
|
|
311
|
-
color: 'var(--card-fg-color)',
|
|
312
|
-
outline: 'none',
|
|
313
|
-
}}
|
|
314
|
-
/>
|
|
315
|
-
</Stack>
|
|
273
|
+
<Flex
|
|
274
|
+
align="center"
|
|
275
|
+
gap={1}
|
|
276
|
+
justify={alignEnd ? 'flex-end' : 'flex-start'}
|
|
277
|
+
draggable
|
|
278
|
+
onDragStart={() => {
|
|
279
|
+
dragKeyRef.current = column.key
|
|
280
|
+
}}
|
|
281
|
+
onDragEnd={() => {
|
|
282
|
+
dragKeyRef.current = null
|
|
283
|
+
setDragOverKey(null)
|
|
284
|
+
}}
|
|
285
|
+
onClick={() => onSort(column.key)}
|
|
286
|
+
style={{cursor: 'grab', userSelect: 'none'}}
|
|
287
|
+
title={`Sort by ${column.label.toLowerCase()} — drag to reorder`}
|
|
288
|
+
>
|
|
289
|
+
<Text size={1} weight="semibold" muted={!active} textOverflow="ellipsis">
|
|
290
|
+
{column.label}
|
|
291
|
+
</Text>
|
|
292
|
+
{active && <Arrow style={{fontSize: 14, opacity: 0.7, flex: 'none'}} />}
|
|
293
|
+
</Flex>
|
|
316
294
|
{/* Poignée de redimensionnement (bord droit). */}
|
|
317
295
|
<div
|
|
318
296
|
onPointerDown={onResizeStart(column.key, width)}
|
|
@@ -335,7 +313,7 @@ export function CollectionTable({type, filter, params, newTemplate}: CollectionT
|
|
|
335
313
|
<Box className="ncf-coll-body">
|
|
336
314
|
{visible.map((row) => (
|
|
337
315
|
<ChildLink key={row.id} childId={row.id}>
|
|
338
|
-
<TableRowView row={row} cols={cols} />
|
|
316
|
+
<TableRowView row={row} cols={cols} Icon={TypeIcon} />
|
|
339
317
|
</ChildLink>
|
|
340
318
|
))}
|
|
341
319
|
|
|
@@ -354,15 +332,36 @@ export function CollectionTable({type, filter, params, newTemplate}: CollectionT
|
|
|
354
332
|
)
|
|
355
333
|
}
|
|
356
334
|
|
|
335
|
+
/** Pastille de statut : vert = publié, ambre = brouillon jamais publié. */
|
|
336
|
+
function StatusDot(props: {draftOnly?: boolean}) {
|
|
337
|
+
return (
|
|
338
|
+
<span
|
|
339
|
+
title={props.draftOnly ? 'Not published' : 'Published'}
|
|
340
|
+
style={{
|
|
341
|
+
flex: 'none',
|
|
342
|
+
width: 9,
|
|
343
|
+
height: 9,
|
|
344
|
+
borderRadius: '50%',
|
|
345
|
+
background: props.draftOnly ? '#f5a623' : '#43d675',
|
|
346
|
+
}}
|
|
347
|
+
/>
|
|
348
|
+
)
|
|
349
|
+
}
|
|
350
|
+
|
|
357
351
|
/** Ligne de la vue TABLE : une cellule par colonne, largeurs fixes. */
|
|
358
|
-
function TableRowView(props: {
|
|
359
|
-
|
|
352
|
+
function TableRowView(props: {
|
|
353
|
+
row: CollectionRow
|
|
354
|
+
cols: readonly {column: CollectionColumn; width: number}[]
|
|
355
|
+
Icon?: ComponentType
|
|
356
|
+
}) {
|
|
357
|
+
const {row, cols, Icon} = props
|
|
360
358
|
const [hovered, setHovered] = useState(false)
|
|
361
359
|
|
|
362
360
|
return (
|
|
363
361
|
<Flex
|
|
364
362
|
paddingX={3}
|
|
365
363
|
paddingY={2}
|
|
364
|
+
align="center"
|
|
366
365
|
onMouseEnter={() => setHovered(true)}
|
|
367
366
|
onMouseLeave={() => setHovered(false)}
|
|
368
367
|
style={{
|
|
@@ -374,18 +373,32 @@ function TableRowView(props: {row: CollectionRow; cols: readonly {column: Collec
|
|
|
374
373
|
{cols.map(({column, width}, index) => {
|
|
375
374
|
const cell = row.cells[column.key]
|
|
376
375
|
const empty = !cell || cell.raw === null || cell.text === ''
|
|
376
|
+
const first = index === 0
|
|
377
|
+
const alignEnd = column.kind === 'number'
|
|
377
378
|
return (
|
|
378
|
-
<Flex
|
|
379
|
+
<Flex
|
|
380
|
+
key={column.key}
|
|
381
|
+
align="center"
|
|
382
|
+
gap={2}
|
|
383
|
+
paddingRight={2}
|
|
384
|
+
justify={alignEnd ? 'flex-end' : 'flex-start'}
|
|
385
|
+
style={{width, flex: 'none', boxSizing: 'border-box'}}
|
|
386
|
+
>
|
|
387
|
+
{first && (
|
|
388
|
+
<Text size={1} muted style={{flex: 'none', display: 'flex'}}>
|
|
389
|
+
{Icon ? <Icon /> : <DocumentIcon />}
|
|
390
|
+
</Text>
|
|
391
|
+
)}
|
|
379
392
|
<Text
|
|
380
|
-
size={
|
|
393
|
+
size={1}
|
|
381
394
|
muted={empty}
|
|
382
|
-
weight={
|
|
395
|
+
weight={first ? 'medium' : 'regular'}
|
|
383
396
|
textOverflow="ellipsis"
|
|
384
|
-
style={{flex: 1, minWidth: 0, ...(column.kind === 'number' || column.kind === 'date' ? TABULAR : null)}}
|
|
397
|
+
style={{flex: alignEnd ? 'none' : 1, minWidth: 0, ...(column.kind === 'number' || column.kind === 'date' ? TABULAR : null)}}
|
|
385
398
|
>
|
|
386
399
|
{empty ? '—' : cell.text}
|
|
387
400
|
</Text>
|
|
388
|
-
{
|
|
401
|
+
{first && row.draftOnly && (
|
|
389
402
|
<Badge tone="caution" fontSize={0} style={{flex: 'none'}}>
|
|
390
403
|
Draft
|
|
391
404
|
</Badge>
|
|
@@ -397,9 +410,9 @@ function TableRowView(props: {row: CollectionRow; cols: readonly {column: Collec
|
|
|
397
410
|
)
|
|
398
411
|
}
|
|
399
412
|
|
|
400
|
-
/** Ligne de la vue LISTE : titre + sous-titre, façon liste native. */
|
|
401
|
-
function ListRowView(props: {row: CollectionRow; titleKey?: string; subtitleKey?: string}) {
|
|
402
|
-
const {row, titleKey, subtitleKey} = props
|
|
413
|
+
/** Ligne de la vue LISTE : vignette + titre + sous-titre, façon liste native. */
|
|
414
|
+
function ListRowView(props: {row: CollectionRow; titleKey?: string; subtitleKey?: string; Icon?: ComponentType}) {
|
|
415
|
+
const {row, titleKey, subtitleKey, Icon} = props
|
|
403
416
|
const [hovered, setHovered] = useState(false)
|
|
404
417
|
const title = titleKey ? row.cells[titleKey]?.text : ''
|
|
405
418
|
const subtitle = subtitleKey ? row.cells[subtitleKey]?.text : ''
|
|
@@ -407,9 +420,8 @@ function ListRowView(props: {row: CollectionRow; titleKey?: string; subtitleKey?
|
|
|
407
420
|
return (
|
|
408
421
|
<Flex
|
|
409
422
|
align="center"
|
|
410
|
-
gap={
|
|
411
|
-
|
|
412
|
-
paddingY={2}
|
|
423
|
+
gap={3}
|
|
424
|
+
padding={2}
|
|
413
425
|
onMouseEnter={() => setHovered(true)}
|
|
414
426
|
onMouseLeave={() => setHovered(false)}
|
|
415
427
|
style={{
|
|
@@ -418,21 +430,36 @@ function ListRowView(props: {row: CollectionRow; titleKey?: string; subtitleKey?
|
|
|
418
430
|
background: hovered ? 'var(--card-muted-bg-color, rgba(127,127,127,0.08))' : 'transparent',
|
|
419
431
|
}}
|
|
420
432
|
>
|
|
433
|
+
{/* Vignette : icône du type dans un cadre, calée sur la liste native. */}
|
|
434
|
+
<Flex
|
|
435
|
+
align="center"
|
|
436
|
+
justify="center"
|
|
437
|
+
style={{
|
|
438
|
+
width: MEDIA,
|
|
439
|
+
height: MEDIA,
|
|
440
|
+
flex: 'none',
|
|
441
|
+
border: `1px solid ${BORDER_SOFT}`,
|
|
442
|
+
borderRadius: 3,
|
|
443
|
+
color: 'var(--card-muted-fg-color)',
|
|
444
|
+
}}
|
|
445
|
+
>
|
|
446
|
+
<Text size={2} muted style={{display: 'flex'}}>
|
|
447
|
+
{Icon ? <Icon /> : <DocumentIcon />}
|
|
448
|
+
</Text>
|
|
449
|
+
</Flex>
|
|
450
|
+
|
|
421
451
|
<Stack gap={2} flex={1} style={{minWidth: 0}}>
|
|
422
|
-
<Text size={1}
|
|
452
|
+
<Text size={1} textOverflow="ellipsis">
|
|
423
453
|
{title || 'Untitled'}
|
|
424
454
|
</Text>
|
|
425
455
|
{subtitle ? (
|
|
426
|
-
<Text size={
|
|
456
|
+
<Text size={1} muted textOverflow="ellipsis">
|
|
427
457
|
{subtitle}
|
|
428
458
|
</Text>
|
|
429
459
|
) : null}
|
|
430
460
|
</Stack>
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
Draft
|
|
434
|
-
</Badge>
|
|
435
|
-
)}
|
|
461
|
+
|
|
462
|
+
<StatusDot draftOnly={row.draftOnly} />
|
|
436
463
|
</Flex>
|
|
437
464
|
)
|
|
438
465
|
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import {useEffect, useState} from 'react'
|
|
2
|
+
import {useClient, useDocumentOperation, type LayoutProps} from 'sanity'
|
|
3
|
+
import {MediaPickerDialog} from '../form/AssetSourceBrowser'
|
|
4
|
+
import {isReplaceImageRequest, replaceImagePatch} from '../web/edit/protocol'
|
|
5
|
+
import {HelpTextStyle} from './HelpTextStyle'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* « Replace this image » depuis l'aperçu (Presentation) : un clic sur une image de
|
|
9
|
+
* l'aperçu (`NcfPreviewEditing`) envoie un message ; le Studio ouvre la médiathèque
|
|
10
|
+
* en quasi plein écran (masonry, dossiers, recherche : comme l'onglet Assets) et
|
|
11
|
+
* l'image choisie remplace celle du champ dans le BROUILLON (même chemin que le
|
|
12
|
+
* formulaire). Cadrage et point focal de l'ancienne image retirés.
|
|
13
|
+
*
|
|
14
|
+
* Sécurité : seul un message venu d'une fenêtre affichée par ce Studio
|
|
15
|
+
* (`window.frames`), depuis l'origine d'un environnement du kit, est pris en
|
|
16
|
+
* compte ; il ne fait qu'ouvrir le sélecteur, le choix reste à l'utilisateur.
|
|
17
|
+
*/
|
|
18
|
+
type Request = {documentId: string; documentType: string; path: string}
|
|
19
|
+
|
|
20
|
+
/** 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
|
+
function fromChildFrame(source: MessageEventSource | null): boolean {
|
|
22
|
+
if (!source) return false
|
|
23
|
+
for (let i = 0; i < window.frames.length; i++) if (window.frames[i] === source) return true
|
|
24
|
+
return false
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function PreviewEditBridge({origins}: {origins: readonly string[]}) {
|
|
28
|
+
const client = useClient({apiVersion: '2025-02-19'})
|
|
29
|
+
const [request, setRequest] = useState<Request | null>(null)
|
|
30
|
+
|
|
31
|
+
useEffect(() => {
|
|
32
|
+
if (!origins.length) return
|
|
33
|
+
const onMessage = async (event: MessageEvent) => {
|
|
34
|
+
if (!origins.includes(event.origin) || !fromChildFrame(event.source) || !isReplaceImageRequest(event.data)) return
|
|
35
|
+
const documentId = event.data.documentId.replace(/^drafts\./, '')
|
|
36
|
+
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
|
+
}
|
|
39
|
+
window.addEventListener('message', onMessage)
|
|
40
|
+
return () => window.removeEventListener('message', onMessage)
|
|
41
|
+
}, [client, origins])
|
|
42
|
+
|
|
43
|
+
if (!request) return null
|
|
44
|
+
return <ReplaceImageDialog key={`${request.documentId}:${request.path}`} request={request} onDone={() => setRequest(null)} />
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function ReplaceImageDialog({request, onDone}: {request: Request; onDone: () => void}) {
|
|
48
|
+
const {patch} = useDocumentOperation(request.documentId, request.documentType)
|
|
49
|
+
return (
|
|
50
|
+
<MediaPickerDialog
|
|
51
|
+
id="ncf-preview-replace-image"
|
|
52
|
+
title="Replace image"
|
|
53
|
+
kind="image"
|
|
54
|
+
size="wide"
|
|
55
|
+
onClose={onDone}
|
|
56
|
+
onPick={(asset) => {
|
|
57
|
+
patch.execute(replaceImagePatch(request.path, asset._id))
|
|
58
|
+
onDone()
|
|
59
|
+
}}
|
|
60
|
+
/>
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Habillage du Studio posé par le plugin : feuille de style des aides + pont de l'aperçu. */
|
|
65
|
+
export function createKitLayout(origins: readonly string[]) {
|
|
66
|
+
return function KitLayout(props: LayoutProps) {
|
|
67
|
+
return (
|
|
68
|
+
<>
|
|
69
|
+
<HelpTextStyle {...props} />
|
|
70
|
+
<PreviewEditBridge origins={origins} />
|
|
71
|
+
</>
|
|
72
|
+
)
|
|
73
|
+
}
|
|
74
|
+
}
|
package/src/version.ts
CHANGED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import {useEffect, useState} from 'react'
|
|
2
|
+
import {createPortal} from 'react-dom'
|
|
3
|
+
import {CHIP, FONT} from './labels'
|
|
4
|
+
import {REPLACE_IMAGE_MESSAGE} from './protocol'
|
|
5
|
+
import {isEditMode} from './store'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* « Replace this image » dans l'aperçu, INDÉPENDANT du mécanisme de composants de
|
|
9
|
+
* Sanity (qui ne s'active pas sur toutes les images : éléments de liste, images
|
|
10
|
+
* héritées). Chaque image éditable porte son document et son chemin exacts
|
|
11
|
+
* (attributs `data-edit-*`, `imageEditAttributes`) :
|
|
12
|
+
* - au survol, une pastille en haut de la partie VISIBLE de l'image (sous le
|
|
13
|
+
* header, dans les cadres qui la rognent) ; transparente à la souris ;
|
|
14
|
+
* - au clic, le Studio (fenêtre parente) ouvre la médiathèque pour ce champ (pont
|
|
15
|
+
* monté par le plugin du kit). Le message ne vise que l'origine du Studio.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const SELECTOR = '[data-edit-image][data-edit-doc][data-edit-type]'
|
|
19
|
+
|
|
20
|
+
function studioOrigin(): string | null {
|
|
21
|
+
const ancestor = window.location.ancestorOrigins?.[0]
|
|
22
|
+
if (ancestor) return ancestor
|
|
23
|
+
try {
|
|
24
|
+
return document.referrer ? new URL(document.referrer).origin : null
|
|
25
|
+
} catch {
|
|
26
|
+
return null
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Hauteur du header du site (`--header-height`, px ou rem), 0 sinon. */
|
|
31
|
+
function headerHeight(): number {
|
|
32
|
+
const root = getComputedStyle(document.documentElement)
|
|
33
|
+
const raw = root.getPropertyValue('--header-height').trim()
|
|
34
|
+
return (parseFloat(raw) || 0) * (raw.endsWith('rem') ? parseFloat(root.fontSize) || 16 : 1)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Rectangle visible : rogné par les ancêtres qui coupent, la fenêtre et le header. */
|
|
38
|
+
function visibleRect(element: Element) {
|
|
39
|
+
const r = element.getBoundingClientRect()
|
|
40
|
+
let top = Math.max(r.top, headerHeight())
|
|
41
|
+
let left = Math.max(r.left, 0)
|
|
42
|
+
let right = Math.min(r.right, window.innerWidth)
|
|
43
|
+
let bottom = Math.min(r.bottom, window.innerHeight)
|
|
44
|
+
for (let n = element.parentElement; n && n !== document.body; n = n.parentElement) {
|
|
45
|
+
const cs = getComputedStyle(n)
|
|
46
|
+
if (cs.overflowX === 'visible' && cs.overflowY === 'visible') continue
|
|
47
|
+
const c = n.getBoundingClientRect()
|
|
48
|
+
top = Math.max(top, c.top)
|
|
49
|
+
left = Math.max(left, c.left)
|
|
50
|
+
right = Math.min(right, c.right)
|
|
51
|
+
bottom = Math.min(bottom, c.bottom)
|
|
52
|
+
}
|
|
53
|
+
return {top, left, right, bottom}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Image éditable sous la souris, même RECOUVERTE par des calques décoratifs
|
|
58
|
+
* (dégradé, voile, bloc de titre en plein cadre) : on parcourt la pile d'éléments
|
|
59
|
+
* sous le point et on traverse tout calque sans texte. Un vrai texte (ou un champ
|
|
60
|
+
* de saisie) posé sur l'image garde la priorité, pour rester modifiable.
|
|
61
|
+
*/
|
|
62
|
+
const VISIBLE_TEXT = /[^\s-]/
|
|
63
|
+
function hasOwnText(el: Element) {
|
|
64
|
+
for (const n of el.childNodes) if (n.nodeType === Node.TEXT_NODE && VISIBLE_TEXT.test(n.textContent ?? '')) return true
|
|
65
|
+
return false
|
|
66
|
+
}
|
|
67
|
+
export function imageAt(x: number, y: number): HTMLElement | null {
|
|
68
|
+
for (const el of document.elementsFromPoint(x, y)) {
|
|
69
|
+
const image = el.closest(SELECTOR) as HTMLElement | null
|
|
70
|
+
if (image) return image
|
|
71
|
+
if (hasOwnText(el) || el.matches('input, textarea, select, button, [contenteditable]')) return null
|
|
72
|
+
}
|
|
73
|
+
return null
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function ImageReplaceLayer({label}: {label: string}) {
|
|
77
|
+
const [target, setTarget] = useState<HTMLElement | null>(null)
|
|
78
|
+
const [pos, setPos] = useState<{top: number; left: number} | null>(null)
|
|
79
|
+
|
|
80
|
+
useEffect(() => {
|
|
81
|
+
if (window.parent === window) return
|
|
82
|
+
let frame = 0
|
|
83
|
+
const onMove = (event: PointerEvent) => {
|
|
84
|
+
const {clientX, clientY} = event
|
|
85
|
+
cancelAnimationFrame(frame)
|
|
86
|
+
frame = requestAnimationFrame(() => {
|
|
87
|
+
const el = isEditMode() ? imageAt(clientX, clientY) : null
|
|
88
|
+
setTarget((prev) => (prev === el ? prev : el))
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
const onLeaveWindow = (event: PointerEvent) => {
|
|
92
|
+
if (!event.relatedTarget) setTarget(null)
|
|
93
|
+
}
|
|
94
|
+
const onClick = (event: MouseEvent) => {
|
|
95
|
+
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || !isEditMode()) return
|
|
96
|
+
const el = imageAt(event.clientX, event.clientY)
|
|
97
|
+
const origin = studioOrigin()
|
|
98
|
+
if (!el || !origin) return
|
|
99
|
+
// Le clic sert à remplacer l'image : jamais suivre un lien posé au-dessus.
|
|
100
|
+
event.preventDefault()
|
|
101
|
+
setTarget(null)
|
|
102
|
+
window.parent.postMessage(
|
|
103
|
+
{
|
|
104
|
+
type: REPLACE_IMAGE_MESSAGE,
|
|
105
|
+
documentId: el.getAttribute('data-edit-doc'),
|
|
106
|
+
documentType: el.getAttribute('data-edit-type'),
|
|
107
|
+
path: el.getAttribute('data-edit-image'),
|
|
108
|
+
},
|
|
109
|
+
origin,
|
|
110
|
+
)
|
|
111
|
+
}
|
|
112
|
+
document.addEventListener('pointermove', onMove, {passive: true})
|
|
113
|
+
document.documentElement.addEventListener('pointerout', onLeaveWindow, {passive: true})
|
|
114
|
+
window.addEventListener('click', onClick, {capture: true})
|
|
115
|
+
return () => {
|
|
116
|
+
cancelAnimationFrame(frame)
|
|
117
|
+
document.removeEventListener('pointermove', onMove)
|
|
118
|
+
document.documentElement.removeEventListener('pointerout', onLeaveWindow)
|
|
119
|
+
window.removeEventListener('click', onClick, {capture: true})
|
|
120
|
+
}
|
|
121
|
+
}, [])
|
|
122
|
+
|
|
123
|
+
// Suit l'image (défilement, parallaxe) tant qu'elle est survolée.
|
|
124
|
+
useEffect(() => {
|
|
125
|
+
if (!target) return
|
|
126
|
+
let frame = 0
|
|
127
|
+
const measure = () => {
|
|
128
|
+
const v = visibleRect(target)
|
|
129
|
+
const half = 110
|
|
130
|
+
const center = Math.min(Math.max((v.left + v.right) / 2, half + 8), window.innerWidth - half - 8)
|
|
131
|
+
const next = v.bottom - v.top < 40 || v.right - v.left < 40 ? null : {top: Math.round(v.top + 16), left: Math.round(center)}
|
|
132
|
+
setPos((prev) => (prev && next && prev.top === next.top && prev.left === next.left ? prev : next))
|
|
133
|
+
frame = requestAnimationFrame(measure)
|
|
134
|
+
}
|
|
135
|
+
measure()
|
|
136
|
+
return () => {
|
|
137
|
+
cancelAnimationFrame(frame)
|
|
138
|
+
setPos(null)
|
|
139
|
+
}
|
|
140
|
+
}, [target])
|
|
141
|
+
|
|
142
|
+
if (!target || !pos) return null
|
|
143
|
+
return createPortal(
|
|
144
|
+
<span
|
|
145
|
+
aria-hidden
|
|
146
|
+
style={{
|
|
147
|
+
pointerEvents: 'none',
|
|
148
|
+
position: 'fixed',
|
|
149
|
+
zIndex: 2147482000,
|
|
150
|
+
top: pos.top,
|
|
151
|
+
left: pos.left,
|
|
152
|
+
transform: 'translateX(-50%)',
|
|
153
|
+
display: 'flex',
|
|
154
|
+
alignItems: 'center',
|
|
155
|
+
gap: 8,
|
|
156
|
+
padding: '6px 12px 6px 8px',
|
|
157
|
+
borderRadius: 999,
|
|
158
|
+
background: CHIP,
|
|
159
|
+
color: '#fff',
|
|
160
|
+
boxShadow: '0 8px 24px rgba(0,0,0,0.25)',
|
|
161
|
+
font: `500 13px/1 ${FONT}`,
|
|
162
|
+
whiteSpace: 'nowrap',
|
|
163
|
+
}}
|
|
164
|
+
>
|
|
165
|
+
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
|
|
166
|
+
<rect x="2" y="3" width="12" height="10" rx="1.5" />
|
|
167
|
+
<circle cx="6" cy="6.5" r="1.2" />
|
|
168
|
+
<path d="M14 10.5l-3.5-3.5L4 13" />
|
|
169
|
+
</svg>
|
|
170
|
+
{label}
|
|
171
|
+
</span>,
|
|
172
|
+
document.body,
|
|
173
|
+
)
|
|
174
|
+
}
|