@nocode-factory/sanity-kit 2.51.1 → 2.53.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 +5 -4
- package/dist/index.d.ts +35 -4
- package/dist/index.js +679 -106
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/form/AssetSourceBrowser.tsx +110 -0
- package/src/hooks/useAssetDelete.ts +60 -0
- package/src/hooks/useAssetUpload.ts +46 -0
- package/src/hooks/useBoardLayout.ts +25 -1
- package/src/index.ts +26 -1
- package/src/lib/assetRefs.ts +53 -0
- package/src/lib/i18nTemplates.ts +40 -0
- package/src/lib/pageOrder.ts +36 -0
- package/src/lib/pages.ts +11 -1
- package/src/schema/boardLayout.ts +7 -0
- package/src/tools/assets/AssetCard.tsx +8 -10
- package/src/tools/assets/AssetDetail.tsx +97 -2
- package/src/tools/assets/AssetsTool.tsx +90 -13
- package/src/tools/assets/AssetsToolbar.tsx +17 -0
- package/src/tools/pages/PagesTool.tsx +15 -9
- package/src/tools/presentation/PagesNavigator.tsx +51 -6
- package/src/version.ts +1 -1
package/package.json
CHANGED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import {useMemo, useState} from 'react'
|
|
2
|
+
import {Box, Button, Card, Dialog, Flex, Grid, Spinner, Stack, Text, TextInput} from '@sanity/ui'
|
|
3
|
+
import {SearchIcon} from '@sanity/icons/Search'
|
|
4
|
+
import type {AssetSourceComponentProps} from 'sanity'
|
|
5
|
+
import {useAssets} from '../hooks/useAssets'
|
|
6
|
+
import {useAssetMeta} from '../hooks/useAssetMeta'
|
|
7
|
+
import {assetName, assetsInFolder, assignmentMap, countByFolder, filterAssets, isImageAsset, sortAssets, thumbnailUrl, type AssetDoc, type FolderSelection} from '../lib/assets'
|
|
8
|
+
import {FolderSidebar} from '../tools/assets/FolderSidebar'
|
|
9
|
+
import {MONO} from '../ui/tokens'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Source d'asset « NCF Médias » : le sélecteur d'image/fichier d'un champ montre
|
|
13
|
+
* les mêmes DOSSIERS et la même recherche que l'onglet Assets. Sans ça,
|
|
14
|
+
* l'organisation ne servirait qu'à l'onglet et pas au choix d'un média.
|
|
15
|
+
*/
|
|
16
|
+
export function AssetSourceBrowser(props: AssetSourceComponentProps) {
|
|
17
|
+
const {assetType, onSelect, onClose, dialogHeaderTitle} = props
|
|
18
|
+
const {data, loading} = useAssets()
|
|
19
|
+
const meta = useAssetMeta()
|
|
20
|
+
const [search, setSearch] = useState('')
|
|
21
|
+
const [selection, setSelection] = useState<FolderSelection>(null)
|
|
22
|
+
|
|
23
|
+
// Le sélecteur d'un champ image ne propose que des images, celui d'un fichier
|
|
24
|
+
// que des fichiers.
|
|
25
|
+
const wantImages = assetType !== 'file'
|
|
26
|
+
const all = useMemo(() => (data ?? []).filter((asset) => (wantImages ? isImageAsset(asset) : !isImageAsset(asset))), [data, wantImages])
|
|
27
|
+
|
|
28
|
+
const folderMap = useMemo(() => assignmentMap(meta.assignments), [meta.assignments])
|
|
29
|
+
const counts = useMemo(() => countByFolder(all, folderMap), [all, folderMap])
|
|
30
|
+
const visible = useMemo(() => sortAssets(filterAssets(assetsInFolder(all, folderMap, selection), {search}), 'date', 'desc'), [all, folderMap, selection, search])
|
|
31
|
+
|
|
32
|
+
const pick = (asset: AssetDoc) => {
|
|
33
|
+
onSelect([{kind: 'assetDocumentId', value: asset._id}])
|
|
34
|
+
onClose()
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return (
|
|
38
|
+
<Dialog id="ncf-asset-source" header={dialogHeaderTitle || 'NCF Médias'} width={3} onClose={onClose}>
|
|
39
|
+
<Flex style={{minHeight: 420}} align="stretch">
|
|
40
|
+
<Box padding={3} style={{width: 220, flex: 'none', borderRight: '1px solid var(--card-border-color)'}} overflow="auto">
|
|
41
|
+
<FolderSidebar
|
|
42
|
+
folders={meta.folders}
|
|
43
|
+
counts={counts}
|
|
44
|
+
total={all.length}
|
|
45
|
+
selection={selection}
|
|
46
|
+
onSelect={setSelection}
|
|
47
|
+
onCreate={meta.createFolder}
|
|
48
|
+
onRename={meta.renameFolder}
|
|
49
|
+
onDelete={(id) => {
|
|
50
|
+
if (selection === id) setSelection(null)
|
|
51
|
+
meta.deleteFolder(id)
|
|
52
|
+
}}
|
|
53
|
+
/>
|
|
54
|
+
</Box>
|
|
55
|
+
|
|
56
|
+
<Stack flex={1} gap={3} padding={3} style={{minWidth: 0}}>
|
|
57
|
+
<TextInput
|
|
58
|
+
value={search}
|
|
59
|
+
onChange={(event) => setSearch(event.currentTarget.value)}
|
|
60
|
+
placeholder="Rechercher un média"
|
|
61
|
+
icon={SearchIcon}
|
|
62
|
+
clearButton={search.length > 0}
|
|
63
|
+
onClear={() => setSearch('')}
|
|
64
|
+
fontSize={1}
|
|
65
|
+
radius={2}
|
|
66
|
+
/>
|
|
67
|
+
<Box flex={1} overflow="auto">
|
|
68
|
+
{loading && all.length === 0 ? (
|
|
69
|
+
<Flex align="center" justify="center" padding={5}>
|
|
70
|
+
<Spinner muted />
|
|
71
|
+
</Flex>
|
|
72
|
+
) : visible.length === 0 ? (
|
|
73
|
+
<Flex align="center" justify="center" padding={5}>
|
|
74
|
+
<Text size={1} muted>
|
|
75
|
+
Aucun média{selection ? ' dans ce dossier' : ''}.
|
|
76
|
+
</Text>
|
|
77
|
+
</Flex>
|
|
78
|
+
) : (
|
|
79
|
+
<Grid gridTemplateColumns={[2, 3, 4]} gap={3}>
|
|
80
|
+
{visible.map((asset) => {
|
|
81
|
+
const thumb = thumbnailUrl(asset, {w: 240, h: 180})
|
|
82
|
+
return (
|
|
83
|
+
<Card
|
|
84
|
+
key={asset._id}
|
|
85
|
+
radius={2}
|
|
86
|
+
shadow={1}
|
|
87
|
+
padding={0}
|
|
88
|
+
as="button"
|
|
89
|
+
onClick={() => pick(asset)}
|
|
90
|
+
style={{overflow: 'hidden', cursor: 'pointer', textAlign: 'left', border: 0}}
|
|
91
|
+
>
|
|
92
|
+
<Box style={{aspectRatio: '4 / 3', background: 'var(--card-muted-bg-color, rgba(127,127,127,0.08))'}}>
|
|
93
|
+
{thumb ? <img src={thumb} alt="" loading="lazy" style={{width: '100%', height: '100%', objectFit: 'cover', display: 'block'}} /> : null}
|
|
94
|
+
</Box>
|
|
95
|
+
<Box padding={2}>
|
|
96
|
+
<Text size={0} textOverflow="ellipsis" style={MONO}>
|
|
97
|
+
{assetName(asset)}
|
|
98
|
+
</Text>
|
|
99
|
+
</Box>
|
|
100
|
+
</Card>
|
|
101
|
+
)
|
|
102
|
+
})}
|
|
103
|
+
</Grid>
|
|
104
|
+
)}
|
|
105
|
+
</Box>
|
|
106
|
+
</Stack>
|
|
107
|
+
</Flex>
|
|
108
|
+
</Dialog>
|
|
109
|
+
)
|
|
110
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import {useCallback} from 'react'
|
|
2
|
+
import {useKitClient} from './useKitClient'
|
|
3
|
+
import {assetUnsetPaths} from '../lib/assetRefs'
|
|
4
|
+
|
|
5
|
+
export interface AssetUsage {
|
|
6
|
+
/** Id (sans le préfixe brouillon). */
|
|
7
|
+
id: string
|
|
8
|
+
type: string
|
|
9
|
+
title: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface AssetDeleteState {
|
|
13
|
+
/** Documents qui utilisent l'asset (dédoublonnés brouillon/publié). */
|
|
14
|
+
usage: (assetId: string) => Promise<AssetUsage[]>
|
|
15
|
+
/** Retire l'asset de tous les documents (champs vidés) puis le supprime. */
|
|
16
|
+
remove: (assetId: string) => Promise<void>
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const baseId = (id: string): string => id.replace(/^drafts\./, '')
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Suppression d'un asset depuis l'outil Assets. Sanity refuse de supprimer un
|
|
23
|
+
* asset référencé : on retire d'abord l'asset de chaque document (le champ
|
|
24
|
+
* devient vide), puis on supprime, dans une seule transaction.
|
|
25
|
+
*/
|
|
26
|
+
export function useAssetDelete(): AssetDeleteState {
|
|
27
|
+
const client = useKitClient()
|
|
28
|
+
|
|
29
|
+
const usage = useCallback(
|
|
30
|
+
async (assetId: string): Promise<AssetUsage[]> => {
|
|
31
|
+
const docs = await client.fetch<{_id: string; _type: string; title?: string}[]>(
|
|
32
|
+
`*[references($id)]{_id, _type, "title": coalesce(title, name, originalFilename, slug.current, _id)}`,
|
|
33
|
+
{id: assetId},
|
|
34
|
+
)
|
|
35
|
+
const seen = new Map<string, AssetUsage>()
|
|
36
|
+
for (const doc of docs ?? []) {
|
|
37
|
+
const id = baseId(doc._id)
|
|
38
|
+
if (!seen.has(id)) seen.set(id, {id, type: doc._type, title: doc.title ?? id})
|
|
39
|
+
}
|
|
40
|
+
return [...seen.values()]
|
|
41
|
+
},
|
|
42
|
+
[client],
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
const remove = useCallback(
|
|
46
|
+
async (assetId: string): Promise<void> => {
|
|
47
|
+
const docs = await client.fetch<Record<string, unknown>[]>(`*[references($id)]`, {id: assetId})
|
|
48
|
+
const transaction = client.transaction()
|
|
49
|
+
for (const doc of docs ?? []) {
|
|
50
|
+
const paths = assetUnsetPaths(doc, assetId)
|
|
51
|
+
if (paths.length) transaction.patch(doc._id as string, {unset: paths})
|
|
52
|
+
}
|
|
53
|
+
transaction.delete(assetId)
|
|
54
|
+
await transaction.commit({visibility: 'async'})
|
|
55
|
+
},
|
|
56
|
+
[client],
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
return {usage, remove}
|
|
60
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import {useCallback, useState} from 'react'
|
|
2
|
+
import {useKitClient} from './useKitClient'
|
|
3
|
+
|
|
4
|
+
export interface AssetUploadState {
|
|
5
|
+
/** Téléverse des fichiers ; `onUploaded` reçoit l'id de chaque asset créé. */
|
|
6
|
+
upload: (files: FileList | readonly File[], onUploaded?: (assetId: string) => void) => Promise<void>
|
|
7
|
+
/** Nombre de fichiers en cours de téléversement. */
|
|
8
|
+
uploading: number
|
|
9
|
+
error: Error | null
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Détermine le type d'asset Sanity d'après le fichier. */
|
|
13
|
+
const assetKind = (file: File): 'image' | 'file' => (file.type.startsWith('image/') ? 'image' : 'file')
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Téléverse des assets dans le dataset depuis l'outil Assets
|
|
17
|
+
* (`client.assets.upload`). La liste se met à jour toute seule (écoute des
|
|
18
|
+
* mutations d'assets) ; `onUploaded` permet de ranger l'asset dans un dossier.
|
|
19
|
+
*/
|
|
20
|
+
export function useAssetUpload(): AssetUploadState {
|
|
21
|
+
const client = useKitClient()
|
|
22
|
+
const [uploading, setUploading] = useState(0)
|
|
23
|
+
const [error, setError] = useState<Error | null>(null)
|
|
24
|
+
|
|
25
|
+
const upload = useCallback(
|
|
26
|
+
async (files: FileList | readonly File[], onUploaded?: (assetId: string) => void) => {
|
|
27
|
+
const list = Array.from(files)
|
|
28
|
+
if (!list.length) return
|
|
29
|
+
setError(null)
|
|
30
|
+
setUploading((count) => count + list.length)
|
|
31
|
+
for (const file of list) {
|
|
32
|
+
try {
|
|
33
|
+
const asset = await client.assets.upload(assetKind(file), file, {filename: file.name})
|
|
34
|
+
onUploaded?.(asset._id)
|
|
35
|
+
} catch (cause) {
|
|
36
|
+
setError(cause instanceof Error ? cause : new Error(String(cause)))
|
|
37
|
+
} finally {
|
|
38
|
+
setUploading((count) => Math.max(0, count - 1))
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
[client],
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
return {upload, uploading, error}
|
|
46
|
+
}
|
|
@@ -53,6 +53,9 @@ export interface BoardLayoutState {
|
|
|
53
53
|
/** Notes et formes posées sur les canvas. */
|
|
54
54
|
annotations: Annotation[]
|
|
55
55
|
saveAnnotations: (next: readonly Annotation[]) => void
|
|
56
|
+
/** Ordre manuel des pages (liste d'ids), partagé Presentation / onglet Pages. */
|
|
57
|
+
pageOrder: string[]
|
|
58
|
+
savePageOrder: (ids: readonly string[]) => void
|
|
56
59
|
/** Accès direct par identifiant de page, pour le rendu des nœuds. */
|
|
57
60
|
byId: Map<string, NodeLayout>
|
|
58
61
|
loading: boolean
|
|
@@ -117,6 +120,7 @@ export function useBoardLayoutState(): BoardLayoutState {
|
|
|
117
120
|
const [columns, setColumns] = useState<NcfInternalField[]>([])
|
|
118
121
|
const [columnsSet, setColumnsSet] = useState(false)
|
|
119
122
|
const [annotations, setAnnotations] = useState<Annotation[]>([])
|
|
123
|
+
const [pageOrder, setPageOrder] = useState<string[]>([])
|
|
120
124
|
const [loading, setLoading] = useState(true)
|
|
121
125
|
const [saveError, setSaveError] = useState<Error | null>(null)
|
|
122
126
|
|
|
@@ -129,7 +133,8 @@ export function useBoardLayoutState(): BoardLayoutState {
|
|
|
129
133
|
columns?: StoredColumn[]
|
|
130
134
|
columnsSet?: boolean
|
|
131
135
|
annotations?: StoredAnnotation[]
|
|
132
|
-
|
|
136
|
+
pageOrder?: string[]
|
|
137
|
+
} | null>(`*[_id == $id][0]{nodes, sections, columns, columnsSet, annotations, pageOrder}`, {
|
|
133
138
|
id: BOARD_LAYOUT_ID,
|
|
134
139
|
})
|
|
135
140
|
.then((doc) => {
|
|
@@ -146,6 +151,7 @@ export function useBoardLayoutState(): BoardLayoutState {
|
|
|
146
151
|
)
|
|
147
152
|
setColumnsSet(Boolean(doc?.columnsSet))
|
|
148
153
|
setAnnotations((doc?.annotations ?? []).map(({_key, ...rest}) => ({...rest})))
|
|
154
|
+
setPageOrder(Array.isArray(doc?.pageOrder) ? doc!.pageOrder.filter((id): id is string => typeof id === 'string') : [])
|
|
149
155
|
})
|
|
150
156
|
.catch(() => {
|
|
151
157
|
// Pas de disposition lisible : on part du placement automatique
|
|
@@ -156,6 +162,7 @@ export function useBoardLayoutState(): BoardLayoutState {
|
|
|
156
162
|
setColumns([])
|
|
157
163
|
setColumnsSet(false)
|
|
158
164
|
setAnnotations([])
|
|
165
|
+
setPageOrder([])
|
|
159
166
|
}
|
|
160
167
|
})
|
|
161
168
|
.finally(() => {
|
|
@@ -181,11 +188,13 @@ export function useBoardLayoutState(): BoardLayoutState {
|
|
|
181
188
|
const columnsRef = useRef<NcfInternalField[]>([])
|
|
182
189
|
const columnsSetRef = useRef(false)
|
|
183
190
|
const annotationsRef = useRef<Annotation[]>([])
|
|
191
|
+
const pageOrderRef = useRef<string[]>([])
|
|
184
192
|
layoutRef.current = layout
|
|
185
193
|
sectionsRef.current = sections
|
|
186
194
|
columnsRef.current = columns
|
|
187
195
|
columnsSetRef.current = columnsSet
|
|
188
196
|
annotationsRef.current = annotations
|
|
197
|
+
pageOrderRef.current = pageOrder
|
|
189
198
|
|
|
190
199
|
const write = useCallback(
|
|
191
200
|
(next?: {
|
|
@@ -194,12 +203,14 @@ export function useBoardLayoutState(): BoardLayoutState {
|
|
|
194
203
|
columns?: NcfInternalField[]
|
|
195
204
|
columnsSet?: boolean
|
|
196
205
|
annotations?: Annotation[]
|
|
206
|
+
pageOrder?: string[]
|
|
197
207
|
}) => {
|
|
198
208
|
const nodes = next?.nodes ?? layoutRef.current
|
|
199
209
|
const nextSections = next?.sections ?? sectionsRef.current
|
|
200
210
|
const nextColumns = next?.columns ?? columnsRef.current
|
|
201
211
|
const nextColumnsSet = next?.columnsSet ?? columnsSetRef.current
|
|
202
212
|
const nextAnnotations = next?.annotations ?? annotationsRef.current
|
|
213
|
+
const nextPageOrder = next?.pageOrder ?? pageOrderRef.current
|
|
203
214
|
client
|
|
204
215
|
.createOrReplace({
|
|
205
216
|
_id: BOARD_LAYOUT_ID,
|
|
@@ -235,6 +246,7 @@ export function useBoardLayoutState(): BoardLayoutState {
|
|
|
235
246
|
})),
|
|
236
247
|
})),
|
|
237
248
|
columnsSet: nextColumnsSet,
|
|
249
|
+
pageOrder: nextPageOrder,
|
|
238
250
|
annotations: nextAnnotations.map((annotation) => ({
|
|
239
251
|
_key: annotation.id,
|
|
240
252
|
_type: 'ncfAnnotation',
|
|
@@ -364,6 +376,16 @@ export function useBoardLayoutState(): BoardLayoutState {
|
|
|
364
376
|
write({sections: []})
|
|
365
377
|
}, [write])
|
|
366
378
|
|
|
379
|
+
const savePageOrder = useCallback(
|
|
380
|
+
(ids: readonly string[]) => {
|
|
381
|
+
const value = [...ids]
|
|
382
|
+
setPageOrder(value)
|
|
383
|
+
if (timer.current) clearTimeout(timer.current)
|
|
384
|
+
timer.current = setTimeout(() => write({pageOrder: value}), 800)
|
|
385
|
+
},
|
|
386
|
+
[write],
|
|
387
|
+
)
|
|
388
|
+
|
|
367
389
|
const sectionsByName = useMemo(
|
|
368
390
|
() => new Map(sections.map((entry) => [entry.blockName, entry])),
|
|
369
391
|
[sections],
|
|
@@ -390,6 +412,8 @@ export function useBoardLayoutState(): BoardLayoutState {
|
|
|
390
412
|
saveColumns,
|
|
391
413
|
annotations,
|
|
392
414
|
saveAnnotations,
|
|
415
|
+
pageOrder,
|
|
416
|
+
savePageOrder,
|
|
393
417
|
reset,
|
|
394
418
|
resetSections,
|
|
395
419
|
}
|
package/src/index.ts
CHANGED
|
@@ -18,6 +18,7 @@ import {HistoryTool} from './tools/history/HistoryTool'
|
|
|
18
18
|
import {DesignSystemTool} from './tools/designSystem/DesignSystemTool'
|
|
19
19
|
import {AssetsTool} from './tools/assets/AssetsTool'
|
|
20
20
|
import {BOARD_LAYOUT_TYPE, isKitType, kitSchemaTypes} from './schema/boardLayout'
|
|
21
|
+
import {dropRedundantLanguageTemplates} from './lib/i18nTemplates'
|
|
21
22
|
import type {NcfKitConfig, NcfToolName} from './config/types'
|
|
22
23
|
|
|
23
24
|
/** Noms des outils dans la barre du Studio. Exportés pour filtrer `tools`. */
|
|
@@ -27,6 +28,14 @@ export const NCF_HISTORY_TOOL = 'ncf-history'
|
|
|
27
28
|
export const NCF_DESIGN_SYSTEM_TOOL = 'ncf-design-system'
|
|
28
29
|
export const NCF_ASSETS_TOOL = 'ncf-assets'
|
|
29
30
|
|
|
31
|
+
/** Source d'asset « NCF Médias » (dossiers + recherche dans le sélecteur d'un champ). */
|
|
32
|
+
const ncfAssetSource: AssetSource = {
|
|
33
|
+
name: 'ncf-media',
|
|
34
|
+
title: 'NCF Médias',
|
|
35
|
+
icon: ImagesIcon,
|
|
36
|
+
component: AssetSourceBrowser,
|
|
37
|
+
}
|
|
38
|
+
|
|
30
39
|
export const NCF_TOOL_NAMES = [
|
|
31
40
|
NCF_PAGES_TOOL,
|
|
32
41
|
NCF_COMPONENTS_TOOL,
|
|
@@ -51,6 +60,8 @@ import type {ConfigIssue} from './config/types'
|
|
|
51
60
|
import {RemoveFromSiteAction, createRemoveFromSite} from './actions/RemoveFromSite'
|
|
52
61
|
import {createSlugUrlInput, isSlugInput} from './form/SlugUrlInput'
|
|
53
62
|
import {createArrayNamesInput} from './form/ArrayNamesInput'
|
|
63
|
+
import {AssetSourceBrowser} from './form/AssetSourceBrowser'
|
|
64
|
+
import type {AssetSource} from 'sanity'
|
|
54
65
|
import {withTranslationTodo} from './form/TranslationTodoInput'
|
|
55
66
|
import {withPublishedHint} from './form/PublishedHint'
|
|
56
67
|
import {withLanguageMismatch} from './form/LanguageMismatch'
|
|
@@ -184,8 +195,11 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
|
|
|
184
195
|
},
|
|
185
196
|
|
|
186
197
|
document: {
|
|
198
|
+
// On masque le singleton de board, puis — en monolingue — le doublon
|
|
199
|
+
// « + Français Article » que document-internationalization ajoute à côté
|
|
200
|
+
// du « + Article » de base (voir dropRedundantLanguageTemplates).
|
|
187
201
|
newDocumentOptions: (prev) =>
|
|
188
|
-
prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
|
|
202
|
+
dropRedundantLanguageTemplates(prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE)),
|
|
189
203
|
// Pages : « Retirer du site » (dépublication expliquée, liens listés) à la place
|
|
190
204
|
// du « Unpublish » natif, caché et bloqué sans explication par les références.
|
|
191
205
|
// Supprimer la version principale d'un document traduit : suppression de ses
|
|
@@ -235,6 +249,14 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
|
|
|
235
249
|
// Slug d'une page : son adresse complète en ligne (Copier, Ouvrir).
|
|
236
250
|
form: {
|
|
237
251
|
components: {input: createKitInput(config, issues)},
|
|
252
|
+
// Sélecteur d'un champ image/fichier : source « NCF Médias » (mêmes dossiers
|
|
253
|
+
// et recherche que l'onglet Assets). En tête = proposée en premier.
|
|
254
|
+
...(config.tools.assets
|
|
255
|
+
? {
|
|
256
|
+
image: {assetSources: (prev: AssetSource[]) => [ncfAssetSource, ...prev]},
|
|
257
|
+
file: {assetSources: (prev: AssetSource[]) => [ncfAssetSource, ...prev]},
|
|
258
|
+
}
|
|
259
|
+
: {}),
|
|
238
260
|
},
|
|
239
261
|
}
|
|
240
262
|
})
|
|
@@ -329,6 +351,9 @@ export type {
|
|
|
329
351
|
export {nameMap, groupMap, withCustomNames, groupComponents} from './lib/componentMeta'
|
|
330
352
|
export type {ComponentGroup, ComponentEntry, ComponentGrouping} from './lib/componentMeta'
|
|
331
353
|
export {useComponentNames} from './hooks/useComponentNames'
|
|
354
|
+
export {useAssetUpload} from './hooks/useAssetUpload'
|
|
355
|
+
export type {AssetUploadState} from './hooks/useAssetUpload'
|
|
356
|
+
export {AssetSourceBrowser} from './form/AssetSourceBrowser'
|
|
332
357
|
export {
|
|
333
358
|
buildPagesQuery,
|
|
334
359
|
buildContentsQuery,
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trouve, dans un document, les endroits qui référencent un asset — pour les
|
|
3
|
+
* vider avant de supprimer l'asset (Sanity refuse de supprimer un asset encore
|
|
4
|
+
* référencé). Pur : testable sans Sanity.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
type Rec = Record<string, unknown>
|
|
8
|
+
const isObj = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
9
|
+
|
|
10
|
+
type PathSegment = string | number | {_key: string}
|
|
11
|
+
|
|
12
|
+
/** Chemins (segments) des objets du document qui pointent vers `assetId`. */
|
|
13
|
+
export function findAssetRefPaths(value: unknown, assetId: string, path: PathSegment[] = []): PathSegment[][] {
|
|
14
|
+
const out: PathSegment[][] = []
|
|
15
|
+
const walk = (node: unknown, current: PathSegment[]) => {
|
|
16
|
+
if (Array.isArray(node)) {
|
|
17
|
+
node.forEach((item, index) => {
|
|
18
|
+
const segment: PathSegment = isObj(item) && typeof item._key === 'string' ? {_key: item._key} : index
|
|
19
|
+
walk(item, [...current, segment])
|
|
20
|
+
})
|
|
21
|
+
return
|
|
22
|
+
}
|
|
23
|
+
if (!isObj(node)) return
|
|
24
|
+
// Objet image/fichier (`{asset: {_ref}}`) ou référence directe vers l'asset.
|
|
25
|
+
const assetRef = isObj(node.asset) ? node.asset._ref : undefined
|
|
26
|
+
if (assetRef === assetId || (node._type === 'reference' && node._ref === assetId)) {
|
|
27
|
+
out.push(current)
|
|
28
|
+
return
|
|
29
|
+
}
|
|
30
|
+
for (const [key, child] of Object.entries(node)) {
|
|
31
|
+
if (key.startsWith('_')) continue
|
|
32
|
+
walk(child, [...current, key])
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
walk(value, path)
|
|
36
|
+
return out
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Chemin Sanity (`gallery[_key=="ab"].asset`) depuis des segments. */
|
|
40
|
+
export function toPatchPath(segments: readonly PathSegment[]): string {
|
|
41
|
+
let out = ''
|
|
42
|
+
for (const segment of segments) {
|
|
43
|
+
if (typeof segment === 'string') out += out ? `.${segment}` : segment
|
|
44
|
+
else if (typeof segment === 'number') out += `[${segment}]`
|
|
45
|
+
else out += `[_key=="${segment._key}"]`
|
|
46
|
+
}
|
|
47
|
+
return out
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Chemins Sanity (chaînes) à retirer d'un document pour en ôter l'asset. */
|
|
51
|
+
export function assetUnsetPaths(doc: unknown, assetId: string): string[] {
|
|
52
|
+
return findAssetRefPaths(doc, assetId).map(toPatchPath).filter(Boolean)
|
|
53
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Menu « + » du Studio en situation monolingue. Pur.
|
|
3
|
+
*
|
|
4
|
+
* `@sanity/document-internationalization` ajoute, pour chaque type traduit, un
|
|
5
|
+
* template « paramétré » (`${type}-parameterized`) et un template statique par
|
|
6
|
+
* langue (`${type}-${langue}`, p. ex. `article-fr`, titré « Français Article »).
|
|
7
|
+
* Avec une seule langue branchée, ces deux-là font doublon avec le « + Article »
|
|
8
|
+
* de base : le menu de création montre « + Article » ET « + Français Article ».
|
|
9
|
+
*
|
|
10
|
+
* On ne garde alors que la base. Avec plusieurs langues on ne touche à rien
|
|
11
|
+
* (« + master » et « + langues » sont voulus).
|
|
12
|
+
*
|
|
13
|
+
* Détection sans connaître la liste des langues : le template `-parameterized`
|
|
14
|
+
* est la signature du plugin ; s'il n'existe qu'UN statique pour ce type (et que
|
|
15
|
+
* la base du type est bien présente), on est en monolingue pour ce type. Zéro ou
|
|
16
|
+
* plusieurs statiques : on laisse tout, par prudence — jamais retirer la seule
|
|
17
|
+
* façon de créer un document.
|
|
18
|
+
*/
|
|
19
|
+
export function dropRedundantLanguageTemplates<T extends {templateId: string}>(options: readonly T[]): T[] {
|
|
20
|
+
const ids = new Set(options.map((option) => option.templateId))
|
|
21
|
+
const remove = new Set<string>()
|
|
22
|
+
const suffix = '-parameterized'
|
|
23
|
+
|
|
24
|
+
for (const {templateId} of options) {
|
|
25
|
+
if (!templateId.endsWith(suffix)) continue
|
|
26
|
+
const base = templateId.slice(0, -suffix.length)
|
|
27
|
+
// Pas de type de base dans le menu : on ne retire rien.
|
|
28
|
+
if (!ids.has(base)) continue
|
|
29
|
+
const statics = options.filter(
|
|
30
|
+
(option) => option.templateId !== templateId && option.templateId.startsWith(`${base}-`),
|
|
31
|
+
)
|
|
32
|
+
// Exactement une langue : monolingue → la base suffit.
|
|
33
|
+
const only = statics.length === 1 ? statics[0] : undefined
|
|
34
|
+
if (!only) continue
|
|
35
|
+
remove.add(templateId)
|
|
36
|
+
remove.add(only.templateId)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return options.filter((option) => !remove.has(option.templateId))
|
|
40
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ordre manuel des pages, partagé par le navigateur de Presentation et l'onglet
|
|
3
|
+
* Pages. Stocké comme une liste d'ids (board singleton `pageOrder`). Pur.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Ordonne des éléments par la liste d'ids `order` : ceux présents d'abord (dans
|
|
8
|
+
* l'ordre de `order`), les autres ensuite dans leur ordre d'entrée (donc une
|
|
9
|
+
* page nouvelle, absente de l'ordre manuel, apparaît à la fin).
|
|
10
|
+
*/
|
|
11
|
+
export function orderByIds<T extends {id: string}>(items: readonly T[], order: readonly string[]): T[] {
|
|
12
|
+
if (order.length === 0) return [...items]
|
|
13
|
+
const rank = new Map(order.map((id, index) => [id, index]))
|
|
14
|
+
return [...items].sort((a, b) => {
|
|
15
|
+
const ra = rank.get(a.id)
|
|
16
|
+
const rb = rank.get(b.id)
|
|
17
|
+
if (ra === undefined && rb === undefined) return 0
|
|
18
|
+
if (ra === undefined) return 1
|
|
19
|
+
if (rb === undefined) return -1
|
|
20
|
+
return ra - rb
|
|
21
|
+
})
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Déplace `dragged` juste avant `target` dans la séquence d'ids `ordered`
|
|
26
|
+
* (l'ordre courant complet). `target` null = place en fin. Filtre-sûr : on
|
|
27
|
+
* travaille sur les ids, pas sur une vue filtrée.
|
|
28
|
+
*/
|
|
29
|
+
export function reorderBefore(ordered: readonly string[], dragged: string, target: string | null): string[] {
|
|
30
|
+
if (dragged === target) return [...ordered]
|
|
31
|
+
const without = ordered.filter((id) => id !== dragged)
|
|
32
|
+
if (target === null) return [...without, dragged]
|
|
33
|
+
const index = without.indexOf(target)
|
|
34
|
+
if (index < 0) return [...without, dragged]
|
|
35
|
+
return [...without.slice(0, index), dragged, ...without.slice(index)]
|
|
36
|
+
}
|
package/src/lib/pages.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import {finalPath, type RedirectMap} from './finalUrl'
|
|
2
|
+
import {orderByIds} from './pageOrder'
|
|
2
3
|
import type {ResolvedDocumentColumn, ResolvedKitConfig} from '../config/types'
|
|
3
4
|
import {pageTypeFor, toPath, toUrl} from './paths'
|
|
4
5
|
import {DATA_PREFIX} from './query'
|
|
@@ -99,6 +100,7 @@ export function buildPageRows(
|
|
|
99
100
|
*/
|
|
100
101
|
export type SortKey =
|
|
101
102
|
| 'structure'
|
|
103
|
+
| 'manual'
|
|
102
104
|
| 'title'
|
|
103
105
|
| 'type'
|
|
104
106
|
| 'path'
|
|
@@ -113,9 +115,11 @@ const STATUS_ORDER: Record<PageStatus, number> = {modified: 0, draft: 1, publish
|
|
|
113
115
|
export interface SortOptions {
|
|
114
116
|
/** Ordre de déclaration des types, pour le tri « structure ». */
|
|
115
117
|
typeOrder?: readonly string[]
|
|
118
|
+
/** Ordre manuel (liste d'ids), pour le tri « manual ». */
|
|
119
|
+
pageOrder?: readonly string[]
|
|
116
120
|
}
|
|
117
121
|
|
|
118
|
-
const compare = (a: PageRow, b: PageRow, key: SortKey, options: SortOptions): number => {
|
|
122
|
+
const compare = (a: PageRow, b: PageRow, key: Exclude<SortKey, 'manual'>, options: SortOptions): number => {
|
|
119
123
|
switch (key) {
|
|
120
124
|
case 'structure': {
|
|
121
125
|
const order = options.typeOrder ?? []
|
|
@@ -153,6 +157,12 @@ export function sortRows(
|
|
|
153
157
|
direction: SortDirection,
|
|
154
158
|
options: SortOptions = {},
|
|
155
159
|
): PageRow[] {
|
|
160
|
+
// Ordre manuel : séquence d'ids stockée ; les pages hors liste après, par titre.
|
|
161
|
+
if (key === 'manual') {
|
|
162
|
+
const byTitle = [...rows].sort((a, b) => a.title.localeCompare(b.title, undefined, {sensitivity: 'base'}))
|
|
163
|
+
const sorted = orderByIds(byTitle, options.pageOrder ?? [])
|
|
164
|
+
return direction === 'asc' ? sorted : sorted.reverse()
|
|
165
|
+
}
|
|
156
166
|
const sorted = [...rows].sort((a, b) => compare(a, b, key, options))
|
|
157
167
|
return direction === 'asc' ? sorted : sorted.reverse()
|
|
158
168
|
}
|
|
@@ -168,6 +168,13 @@ const boardLayoutType = defineType({
|
|
|
168
168
|
type: 'array',
|
|
169
169
|
of: [{type: SECTION_NODE_TYPE}],
|
|
170
170
|
}),
|
|
171
|
+
// Ordre manuel des pages (liste d'ids), partagé Presentation / onglet Pages.
|
|
172
|
+
defineField({
|
|
173
|
+
name: 'pageOrder',
|
|
174
|
+
title: 'Manual page order',
|
|
175
|
+
type: 'array',
|
|
176
|
+
of: [{type: 'string'}],
|
|
177
|
+
}),
|
|
171
178
|
defineField({
|
|
172
179
|
name: 'updatedBy',
|
|
173
180
|
title: 'Modified by',
|
|
@@ -15,20 +15,18 @@ export interface AssetCardProps {
|
|
|
15
15
|
export function AssetCard(props: AssetCardProps) {
|
|
16
16
|
const {asset, selected, onToggleSelect, onOpen} = props
|
|
17
17
|
const [failed, setFailed] = useState(false)
|
|
18
|
-
const thumb = thumbnailUrl(asset, {w:
|
|
18
|
+
const thumb = thumbnailUrl(asset, {w: 500})
|
|
19
19
|
const unused = asset.uses === 0
|
|
20
|
+
// Vrai ratio de l'image (portrait / paysage visible sans cliquer). Borné pour
|
|
21
|
+
// éviter des tuiles absurdes ; un fichier sans image garde un ratio neutre.
|
|
22
|
+
const natural = asset.dimensions?.width && asset.dimensions?.height ? asset.dimensions.width / asset.dimensions.height : 4 / 3
|
|
23
|
+
const ratio = thumb ? Math.min(2, Math.max(0.56, natural)) : 4 / 3
|
|
20
24
|
const meta = [formatBytes(asset.size), asset.dimensions?.width ? `${asset.dimensions.width}×${asset.dimensions.height}` : null, asset.extension?.toUpperCase()]
|
|
21
25
|
.filter(Boolean)
|
|
22
26
|
.join(' · ')
|
|
23
27
|
|
|
24
28
|
return (
|
|
25
|
-
<Card
|
|
26
|
-
radius={3}
|
|
27
|
-
shadow={1}
|
|
28
|
-
padding={0}
|
|
29
|
-
tone={selected ? 'primary' : 'default'}
|
|
30
|
-
style={{height: '100%', overflow: 'hidden', position: 'relative'}}
|
|
31
|
-
>
|
|
29
|
+
<Card radius={3} shadow={1} padding={0} tone={selected ? 'primary' : 'default'} style={{overflow: 'hidden', position: 'relative', width: '100%'}}>
|
|
32
30
|
{/* Sélection : coin haut-gauche, n'ouvre pas le détail. */}
|
|
33
31
|
<Box style={{position: 'absolute', top: 8, left: 8, zIndex: 1}} onClick={(e) => e.stopPropagation()}>
|
|
34
32
|
<Card radius={2} padding={1} tone="default" style={{opacity: selected ? 1 : 0.85}}>
|
|
@@ -40,9 +38,9 @@ export function AssetCard(props: AssetCardProps) {
|
|
|
40
38
|
gap={0}
|
|
41
39
|
as="button"
|
|
42
40
|
onClick={onOpen}
|
|
43
|
-
style={{
|
|
41
|
+
style={{width: '100%', textAlign: 'left', cursor: 'pointer', background: 'transparent', border: 0, padding: 0}}
|
|
44
42
|
>
|
|
45
|
-
<Box style={{aspectRatio:
|
|
43
|
+
<Box style={{aspectRatio: ratio, overflow: 'hidden', background: 'var(--card-muted-bg-color, rgba(127,127,127,0.08))'}}>
|
|
46
44
|
{thumb && !failed ? (
|
|
47
45
|
<img
|
|
48
46
|
src={thumb}
|