@nocode-factory/sanity-kit 2.13.0 → 2.14.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/dist/index.d.ts +9 -2
- package/dist/index.js +332 -6
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
- package/scripts/sync-version.mjs +11 -0
- package/src/actions/BatchPublish.tsx +290 -0
- package/src/config/resolve.ts +1 -0
- package/src/config/types.ts +6 -0
- package/src/index.ts +6 -0
- package/src/lib/batchPublish.ts +104 -0
- package/src/version.ts +3 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nocode-factory/sanity-kit",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.14.0",
|
|
4
4
|
"description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"private": false,
|
|
@@ -47,7 +47,8 @@
|
|
|
47
47
|
"dev": "pkg-utils watch",
|
|
48
48
|
"typecheck": "tsc --noEmit",
|
|
49
49
|
"test": "vitest run",
|
|
50
|
-
"test:watch": "vitest"
|
|
50
|
+
"test:watch": "vitest",
|
|
51
|
+
"version": "node scripts/sync-version.mjs && git add src/version.ts"
|
|
51
52
|
},
|
|
52
53
|
"dependencies": {
|
|
53
54
|
"@sanity/client": "^7.27.0",
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Recopie la version de package.json dans src/version.ts. Lancé par `npm version`
|
|
2
|
+
// (script "version") : la version affichée dans le Studio ne peut plus dériver.
|
|
3
|
+
import {readFileSync, writeFileSync} from 'node:fs'
|
|
4
|
+
|
|
5
|
+
const {version} = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
|
|
6
|
+
const file = new URL('../src/version.ts', import.meta.url)
|
|
7
|
+
const source = readFileSync(file, 'utf8')
|
|
8
|
+
const next = source.replace(/export const KIT_VERSION = '[^']*'/, `export const KIT_VERSION = '${version}'`)
|
|
9
|
+
if (!next.includes(`'${version}'`)) throw new Error('KIT_VERSION introuvable dans src/version.ts')
|
|
10
|
+
writeFileSync(file, next)
|
|
11
|
+
console.log(`KIT_VERSION = ${version}`)
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import {useCallback, useEffect, useMemo, useState} from 'react'
|
|
2
|
+
import {Badge, Box, Button, Card, Checkbox, Flex, Spinner, Stack, Text} from '@sanity/ui'
|
|
3
|
+
import {useToast} from '@sanity/ui/toast'
|
|
4
|
+
import {PublishIcon} from '@sanity/icons/Publish'
|
|
5
|
+
import {
|
|
6
|
+
Preview,
|
|
7
|
+
useSchema,
|
|
8
|
+
useSyncState,
|
|
9
|
+
useValidationStatus,
|
|
10
|
+
type DocumentActionComponent,
|
|
11
|
+
type DocumentActionProps,
|
|
12
|
+
} from 'sanity'
|
|
13
|
+
import {useKitClient} from '../hooks/useKitClient'
|
|
14
|
+
import {isKitType} from '../schema/boardLayout'
|
|
15
|
+
import {
|
|
16
|
+
DRAFTS_QUERY,
|
|
17
|
+
PUBLISHED_IDS_QUERY,
|
|
18
|
+
explainPublishError,
|
|
19
|
+
publishActions,
|
|
20
|
+
publishLabel,
|
|
21
|
+
publishableDrafts,
|
|
22
|
+
publishedIdOf,
|
|
23
|
+
sinceLabel,
|
|
24
|
+
type DraftEntry,
|
|
25
|
+
type DraftRow,
|
|
26
|
+
} from '../lib/batchPublish'
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Brouillons du projet, tenus à jour en direct : chaque modification, publication ou
|
|
30
|
+
* suppression relance la requête (regroupées, une fois par demi-seconde au plus).
|
|
31
|
+
*/
|
|
32
|
+
function useDrafts(currentId: string | null) {
|
|
33
|
+
const client = useKitClient()
|
|
34
|
+
const schema = useSchema()
|
|
35
|
+
const [rows, setRows] = useState<{drafts: DraftRow[]; published: string[]} | null>(null)
|
|
36
|
+
|
|
37
|
+
useEffect(() => {
|
|
38
|
+
let cancelled = false
|
|
39
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
40
|
+
const load = async () => {
|
|
41
|
+
const drafts = await client.fetch<DraftRow[]>(DRAFTS_QUERY)
|
|
42
|
+
const published = await client.fetch<string[]>(PUBLISHED_IDS_QUERY, {ids: drafts.map((d) => publishedIdOf(d._id))})
|
|
43
|
+
if (!cancelled) setRows({drafts, published})
|
|
44
|
+
}
|
|
45
|
+
load().catch(() => {
|
|
46
|
+
if (!cancelled) setRows({drafts: [], published: []})
|
|
47
|
+
})
|
|
48
|
+
const subscription = client
|
|
49
|
+
.listen(`*[_id in path("drafts.**") || _id in path("*")]`, {}, {visibility: 'query', includeResult: false, events: ['mutation']})
|
|
50
|
+
.subscribe(() => {
|
|
51
|
+
clearTimeout(timer)
|
|
52
|
+
timer = setTimeout(() => void load().catch(() => {}), 500)
|
|
53
|
+
})
|
|
54
|
+
return () => {
|
|
55
|
+
cancelled = true
|
|
56
|
+
clearTimeout(timer)
|
|
57
|
+
subscription.unsubscribe()
|
|
58
|
+
}
|
|
59
|
+
}, [client])
|
|
60
|
+
|
|
61
|
+
const drafts = useMemo(
|
|
62
|
+
() =>
|
|
63
|
+
rows
|
|
64
|
+
? publishableDrafts(rows.drafts, rows.published, {
|
|
65
|
+
isDocumentType: (type) => schema.get(type)?.jsonType === 'object' && isDocumentSchema(schema.get(type)),
|
|
66
|
+
isInternalType: isKitType,
|
|
67
|
+
currentId,
|
|
68
|
+
})
|
|
69
|
+
: null,
|
|
70
|
+
[rows, schema, currentId],
|
|
71
|
+
)
|
|
72
|
+
return drafts
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function isDocumentSchema(type: unknown): boolean {
|
|
76
|
+
let current = type as {name?: string; type?: unknown} | undefined
|
|
77
|
+
while (current) {
|
|
78
|
+
if (current.name === 'document') return true
|
|
79
|
+
current = current.type as typeof current
|
|
80
|
+
}
|
|
81
|
+
return false
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Remplace le bouton « Publier » du document : il ouvre la liste de TOUS les
|
|
86
|
+
* brouillons du projet, cochés par défaut. On publie tout d'un coup ou on décoche
|
|
87
|
+
* ce qui n'est pas prêt. Avec un seul brouillon (celui qu'on édite), le bouton
|
|
88
|
+
* d'origine est gardé tel quel : pas de fenêtre pour rien.
|
|
89
|
+
*
|
|
90
|
+
* En perspective de release ou de variante, l'action d'origine reste aussi : la
|
|
91
|
+
* publication groupée ne concerne que les brouillons.
|
|
92
|
+
*/
|
|
93
|
+
export function createBatchPublishAction(original: DocumentActionComponent): DocumentActionComponent {
|
|
94
|
+
const BatchPublishAction: DocumentActionComponent = (props: DocumentActionProps) => {
|
|
95
|
+
const base = original(props)
|
|
96
|
+
const drafts = useDrafts(props.id)
|
|
97
|
+
const [open, setOpen] = useState(false)
|
|
98
|
+
|
|
99
|
+
if (!base || props.release || props.version || !drafts) return base
|
|
100
|
+
const current = publishedIdOf(props.id)
|
|
101
|
+
const others = drafts.filter((d) => d.publishedId !== current)
|
|
102
|
+
if (others.length === 0) return base
|
|
103
|
+
|
|
104
|
+
return {
|
|
105
|
+
...base,
|
|
106
|
+
label: `Publier… (${drafts.length})`,
|
|
107
|
+
title: 'Choisir les brouillons à publier, ensemble',
|
|
108
|
+
icon: PublishIcon,
|
|
109
|
+
disabled: false,
|
|
110
|
+
onHandle: () => setOpen(true),
|
|
111
|
+
dialog: open
|
|
112
|
+
? {
|
|
113
|
+
type: 'dialog',
|
|
114
|
+
width: 'medium',
|
|
115
|
+
header: 'Publier les modifications',
|
|
116
|
+
onClose: () => setOpen(false),
|
|
117
|
+
content: <BatchPublishDialog drafts={drafts} currentId={current} currentType={props.type} onDone={() => setOpen(false)} />,
|
|
118
|
+
}
|
|
119
|
+
: null,
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
BatchPublishAction.action = original.action
|
|
123
|
+
BatchPublishAction.displayName = 'NcfBatchPublishAction'
|
|
124
|
+
return BatchPublishAction
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function BatchPublishDialog(props: {drafts: DraftEntry[]; currentId: string; currentType: string; onDone: () => void}) {
|
|
128
|
+
const {drafts, currentId, currentType, onDone} = props
|
|
129
|
+
const client = useKitClient()
|
|
130
|
+
const toast = useToast()
|
|
131
|
+
// Les décochés, pas les cochés : un brouillon apparu pendant que la fenêtre est
|
|
132
|
+
// ouverte arrive coché, comme les autres.
|
|
133
|
+
const [unchecked, setUnchecked] = useState<Set<string>>(() => new Set())
|
|
134
|
+
const [invalid, setInvalid] = useState<Set<string>>(() => new Set())
|
|
135
|
+
const [busy, setBusy] = useState(false)
|
|
136
|
+
const [error, setError] = useState<string | null>(null)
|
|
137
|
+
// Le document ouvert peut avoir des frappes pas encore enregistrées.
|
|
138
|
+
const {isSyncing} = useSyncState(currentId, currentType)
|
|
139
|
+
|
|
140
|
+
const report = useCallback((id: string, hasErrors: boolean) => {
|
|
141
|
+
setInvalid((prev) => {
|
|
142
|
+
if (prev.has(id) === hasErrors) return prev
|
|
143
|
+
const next = new Set(prev)
|
|
144
|
+
if (hasErrors) next.add(id)
|
|
145
|
+
else next.delete(id)
|
|
146
|
+
return next
|
|
147
|
+
})
|
|
148
|
+
}, [])
|
|
149
|
+
|
|
150
|
+
const selectable = drafts.filter((d) => !invalid.has(d._id))
|
|
151
|
+
const selected = selectable.filter((d) => !unchecked.has(d._id))
|
|
152
|
+
const allChecked = selected.length === selectable.length && selectable.length > 0
|
|
153
|
+
|
|
154
|
+
const toggle = (id: string) =>
|
|
155
|
+
setUnchecked((prev) => {
|
|
156
|
+
const next = new Set(prev)
|
|
157
|
+
if (next.has(id)) next.delete(id)
|
|
158
|
+
else next.add(id)
|
|
159
|
+
return next
|
|
160
|
+
})
|
|
161
|
+
const toggleAll = () => setUnchecked(allChecked ? new Set(selectable.map((d) => d._id)) : new Set())
|
|
162
|
+
|
|
163
|
+
const publish = async () => {
|
|
164
|
+
setBusy(true)
|
|
165
|
+
setError(null)
|
|
166
|
+
try {
|
|
167
|
+
await client.action(publishActions(selected))
|
|
168
|
+
toast.push({
|
|
169
|
+
status: 'success',
|
|
170
|
+
title: selected.length > 1 ? `${selected.length} documents publiés` : 'Document publié',
|
|
171
|
+
})
|
|
172
|
+
onDone()
|
|
173
|
+
} catch (cause) {
|
|
174
|
+
setError(explainPublishError(cause))
|
|
175
|
+
} finally {
|
|
176
|
+
setBusy(false)
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return (
|
|
181
|
+
<Stack gap={4} padding={4}>
|
|
182
|
+
<Flex align="center" justify="space-between" gap={3}>
|
|
183
|
+
<Text size={1} muted>
|
|
184
|
+
{drafts.length} document{drafts.length > 1 ? 's' : ''} en brouillon. Décochez ce qui n'est pas prêt.
|
|
185
|
+
</Text>
|
|
186
|
+
<Button mode="bleed" fontSize={1} padding={2} text={allChecked ? 'Tout décocher' : 'Tout cocher'} onClick={toggleAll} disabled={busy} />
|
|
187
|
+
</Flex>
|
|
188
|
+
|
|
189
|
+
<Card radius={2} border style={{maxHeight: '55vh', overflowY: 'auto'}}>
|
|
190
|
+
<Stack>
|
|
191
|
+
{drafts.map((draft, index) => (
|
|
192
|
+
<DraftLine
|
|
193
|
+
key={draft._id}
|
|
194
|
+
draft={draft}
|
|
195
|
+
current={draft.publishedId === currentId}
|
|
196
|
+
checked={!unchecked.has(draft._id) && !invalid.has(draft._id)}
|
|
197
|
+
invalid={invalid.has(draft._id)}
|
|
198
|
+
onToggle={() => toggle(draft._id)}
|
|
199
|
+
onValidation={report}
|
|
200
|
+
divider={index > 0}
|
|
201
|
+
disabled={busy}
|
|
202
|
+
/>
|
|
203
|
+
))}
|
|
204
|
+
</Stack>
|
|
205
|
+
</Card>
|
|
206
|
+
|
|
207
|
+
{error && (
|
|
208
|
+
<Card padding={3} radius={2} tone="critical">
|
|
209
|
+
<Text size={1}>{error}</Text>
|
|
210
|
+
</Card>
|
|
211
|
+
)}
|
|
212
|
+
|
|
213
|
+
<Flex justify="flex-end" align="center" gap={2}>
|
|
214
|
+
{isSyncing && (
|
|
215
|
+
<Flex align="center" gap={2}>
|
|
216
|
+
<Spinner muted />
|
|
217
|
+
<Text size={1} muted>
|
|
218
|
+
Enregistrement en cours…
|
|
219
|
+
</Text>
|
|
220
|
+
</Flex>
|
|
221
|
+
)}
|
|
222
|
+
<Button mode="bleed" text="Annuler" onClick={onDone} disabled={busy} />
|
|
223
|
+
<Button
|
|
224
|
+
tone="positive"
|
|
225
|
+
icon={busy ? Spinner : PublishIcon}
|
|
226
|
+
text={busy ? 'Publication…' : publishLabel(selected.length)}
|
|
227
|
+
disabled={busy || isSyncing || selected.length === 0}
|
|
228
|
+
onClick={publish}
|
|
229
|
+
/>
|
|
230
|
+
</Flex>
|
|
231
|
+
</Stack>
|
|
232
|
+
)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function DraftLine(props: {
|
|
236
|
+
draft: DraftEntry
|
|
237
|
+
current: boolean
|
|
238
|
+
checked: boolean
|
|
239
|
+
invalid: boolean
|
|
240
|
+
disabled: boolean
|
|
241
|
+
divider: boolean
|
|
242
|
+
onToggle: () => void
|
|
243
|
+
onValidation: (id: string, hasErrors: boolean) => void
|
|
244
|
+
}) {
|
|
245
|
+
const {draft, current, checked, invalid, disabled, divider, onToggle, onValidation} = props
|
|
246
|
+
const schema = useSchema()
|
|
247
|
+
const schemaType = schema.get(draft._type)
|
|
248
|
+
// Mêmes règles que le bouton « Publier » de Sanity : un document invalide ne part pas.
|
|
249
|
+
// Les références vers des contenus jamais publiés sont laissées à la transaction, qui
|
|
250
|
+
// les accepte quand le contenu référencé part avec.
|
|
251
|
+
const {validation, isValidating} = useValidationStatus(draft._id, draft._type, false)
|
|
252
|
+
const hasErrors = validation.some((marker) => marker.level === 'error')
|
|
253
|
+
useEffect(() => {
|
|
254
|
+
if (!isValidating) onValidation(draft._id, hasErrors)
|
|
255
|
+
}, [draft._id, hasErrors, isValidating, onValidation])
|
|
256
|
+
|
|
257
|
+
return (
|
|
258
|
+
<Card
|
|
259
|
+
as="label"
|
|
260
|
+
padding={2}
|
|
261
|
+
paddingX={3}
|
|
262
|
+
tone={invalid ? 'critical' : current ? 'primary' : 'default'}
|
|
263
|
+
style={{cursor: invalid || disabled ? 'default' : 'pointer', borderTop: divider ? '1px solid var(--card-border-color)' : undefined}}
|
|
264
|
+
>
|
|
265
|
+
<Flex align="center" gap={3}>
|
|
266
|
+
<Checkbox checked={checked} disabled={invalid || disabled} onChange={onToggle} />
|
|
267
|
+
<Box flex={1} style={{minWidth: 0}}>
|
|
268
|
+
{schemaType ? (
|
|
269
|
+
<Preview schemaType={schemaType} value={{_id: draft._id, _type: draft._type}} layout="default" />
|
|
270
|
+
) : (
|
|
271
|
+
<Text size={1}>{draft.publishedId}</Text>
|
|
272
|
+
)}
|
|
273
|
+
</Box>
|
|
274
|
+
<Stack gap={2} style={{flex: 'none', textAlign: 'right'}}>
|
|
275
|
+
<Flex gap={1} justify="flex-end">
|
|
276
|
+
{current && <Badge tone="primary">Ouvert</Badge>}
|
|
277
|
+
{invalid ? (
|
|
278
|
+
<Badge tone="critical">Erreurs à corriger</Badge>
|
|
279
|
+
) : (
|
|
280
|
+
<Badge tone={draft.published ? 'caution' : 'positive'}>{draft.published ? 'Modifié' : 'Nouveau'}</Badge>
|
|
281
|
+
)}
|
|
282
|
+
</Flex>
|
|
283
|
+
<Text size={0} muted>
|
|
284
|
+
{schemaType?.title ?? draft._type} · {sinceLabel(draft._updatedAt)}
|
|
285
|
+
</Text>
|
|
286
|
+
</Stack>
|
|
287
|
+
</Flex>
|
|
288
|
+
</Card>
|
|
289
|
+
)
|
|
290
|
+
}
|
package/src/config/resolve.ts
CHANGED
|
@@ -115,6 +115,7 @@ export function resolveConfig(input: NcfKitConfig): ResolvedKitConfig {
|
|
|
115
115
|
: null,
|
|
116
116
|
tools: {...DEFAULT_TOOLS, ...input.tools},
|
|
117
117
|
moreTools: input.moreTools === false ? [] : (input.moreTools ?? DEFAULT_TOOLBAR_MORE),
|
|
118
|
+
batchPublish: input.batchPublish !== false,
|
|
118
119
|
boardTags: input.boardTags?.length ? input.boardTags : DEFAULT_BOARD_TAGS,
|
|
119
120
|
internalFields: input.internalFields?.length
|
|
120
121
|
? input.internalFields
|
package/src/config/types.ts
CHANGED
|
@@ -208,6 +208,11 @@ export interface NcfKitConfig {
|
|
|
208
208
|
* (« Scheduled drafts » / Releases, nom d'outil `releases`). `false` : aucun.
|
|
209
209
|
*/
|
|
210
210
|
moreTools?: string[] | false
|
|
211
|
+
/**
|
|
212
|
+
* « Publier » ouvre la liste de tous les brouillons du projet, cochés : on publie
|
|
213
|
+
* vingt modifications d'un coup, ou on décoche ce qui n'est pas prêt. Défaut : `true`.
|
|
214
|
+
*/
|
|
215
|
+
batchPublish?: boolean
|
|
211
216
|
/**
|
|
212
217
|
* Étiquettes de suivi du board. Remplacent entièrement les valeurs par
|
|
213
218
|
* défaut quand elles sont fournies.
|
|
@@ -269,6 +274,7 @@ export interface ResolvedKitConfig {
|
|
|
269
274
|
tools: Required<NcfToolsConfig>
|
|
270
275
|
/** Outils rangés dans le menu « Plus » de la barre (noms d'outils). */
|
|
271
276
|
moreTools: string[]
|
|
277
|
+
batchPublish: boolean
|
|
272
278
|
boardTags: NcfBoardTag[]
|
|
273
279
|
internalFields: NcfInternalField[]
|
|
274
280
|
documentColumns: ResolvedDocumentColumn[]
|
package/src/index.ts
CHANGED
|
@@ -12,6 +12,7 @@ import {PagesTool} from './tools/pages/PagesTool'
|
|
|
12
12
|
import {ComponentsTool} from './tools/components/ComponentsTool'
|
|
13
13
|
import {HistoryTool} from './tools/history/HistoryTool'
|
|
14
14
|
import {DesignSystemTool} from './tools/designSystem/DesignSystemTool'
|
|
15
|
+
import {createBatchPublishAction} from './actions/BatchPublish'
|
|
15
16
|
import {BOARD_LAYOUT_TYPE, isKitType, kitSchemaTypes} from './schema/boardLayout'
|
|
16
17
|
import type {NcfKitConfig, NcfToolName} from './config/types'
|
|
17
18
|
|
|
@@ -122,6 +123,11 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
|
|
|
122
123
|
document: {
|
|
123
124
|
newDocumentOptions: (prev) =>
|
|
124
125
|
prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
|
|
126
|
+
// « Publier » : choisir parmi tous les brouillons du projet et les publier ensemble.
|
|
127
|
+
actions: (prev) =>
|
|
128
|
+
config.batchPublish
|
|
129
|
+
? prev.map((action) => (action.action === 'publish' ? createBatchPublishAction(action) : action))
|
|
130
|
+
: prev,
|
|
125
131
|
},
|
|
126
132
|
|
|
127
133
|
// Le lanceur d'aperçu s'ajoute à droite des outils, dans la barre du haut
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Publication groupée : logique pure (testée), sans React ni Studio.
|
|
3
|
+
*
|
|
4
|
+
* On modifie vingt documents, on publie tout d'un coup, ou seulement ce qu'on a
|
|
5
|
+
* coché. La publication passe par l'API Actions de Sanity, en UNE transaction :
|
|
6
|
+
* tout part ensemble ou rien ne part (un document qui en référence un autre encore
|
|
7
|
+
* jamais publié peut ainsi partir avec lui).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const DRAFTS_PREFIX = 'drafts.'
|
|
11
|
+
|
|
12
|
+
export interface DraftRow {
|
|
13
|
+
_id: string
|
|
14
|
+
_rev: string
|
|
15
|
+
_type: string
|
|
16
|
+
_updatedAt: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface DraftEntry extends DraftRow {
|
|
20
|
+
publishedId: string
|
|
21
|
+
/** `false` : jamais publié (ce sera une création). */
|
|
22
|
+
published: boolean
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface PublishDocumentAction {
|
|
26
|
+
actionType: 'sanity.action.document.publish'
|
|
27
|
+
draftId: string
|
|
28
|
+
publishedId: string
|
|
29
|
+
ifDraftRevisionId: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Brouillons (`drafts.*`) de tous les documents, sans les versions de release. */
|
|
33
|
+
export const DRAFTS_QUERY = `*[_id in path("drafts.**")]{_id, _rev, _type, _updatedAt}`
|
|
34
|
+
/** Parmi ces ids publiés, ceux qui existent déjà. */
|
|
35
|
+
export const PUBLISHED_IDS_QUERY = `*[_id in $ids]._id`
|
|
36
|
+
|
|
37
|
+
export const publishedIdOf = (id: string): string =>
|
|
38
|
+
id.startsWith(DRAFTS_PREFIX) ? id.slice(DRAFTS_PREFIX.length) : id
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Brouillons publiables : types du schéma (documents), hors types internes (kit,
|
|
42
|
+
* `sanity.*`). Le document ouvert d'abord, puis du plus récent au plus ancien.
|
|
43
|
+
*/
|
|
44
|
+
export function publishableDrafts(
|
|
45
|
+
rows: DraftRow[],
|
|
46
|
+
publishedIds: Iterable<string>,
|
|
47
|
+
options: {isDocumentType: (type: string) => boolean; isInternalType?: (type: string) => boolean; currentId?: string | null},
|
|
48
|
+
): DraftEntry[] {
|
|
49
|
+
const published = new Set(publishedIds)
|
|
50
|
+
const current = options.currentId ? publishedIdOf(options.currentId) : null
|
|
51
|
+
return rows
|
|
52
|
+
.filter((row) => row._id.startsWith(DRAFTS_PREFIX) && !row._id.slice(DRAFTS_PREFIX.length).includes('.'))
|
|
53
|
+
.filter((row) => !row._type.startsWith('sanity.') && options.isDocumentType(row._type) && !options.isInternalType?.(row._type))
|
|
54
|
+
.map((row) => ({...row, publishedId: publishedIdOf(row._id), published: published.has(publishedIdOf(row._id))}))
|
|
55
|
+
.sort((a, b) => {
|
|
56
|
+
if (a.publishedId === current) return -1
|
|
57
|
+
if (b.publishedId === current) return 1
|
|
58
|
+
return b._updatedAt.localeCompare(a._updatedAt)
|
|
59
|
+
})
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Actions de publication. `ifDraftRevisionId` : on publie exactement la version
|
|
64
|
+
* affichée ; si quelqu'un l'a modifiée entre-temps, la transaction est refusée
|
|
65
|
+
* plutôt que de publier un contenu que personne n'a relu.
|
|
66
|
+
*/
|
|
67
|
+
export function publishActions(selected: DraftEntry[]): PublishDocumentAction[] {
|
|
68
|
+
return selected.map((draft) => ({
|
|
69
|
+
actionType: 'sanity.action.document.publish',
|
|
70
|
+
draftId: draft._id,
|
|
71
|
+
publishedId: draft.publishedId,
|
|
72
|
+
ifDraftRevisionId: draft._rev,
|
|
73
|
+
}))
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Libellé du bouton : « Publier 1 document », « Publier 12 documents ». */
|
|
77
|
+
export function publishLabel(count: number): string {
|
|
78
|
+
if (count === 0) return 'Rien à publier'
|
|
79
|
+
return `Publier ${count} document${count > 1 ? 's' : ''}`
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Erreur de l'API rendue lisible. */
|
|
83
|
+
export function explainPublishError(error: unknown): string {
|
|
84
|
+
const err = error as {statusCode?: number; message?: string; details?: {description?: string; items?: Array<{error?: {description?: string}}>}}
|
|
85
|
+
const description = err?.details?.description ?? err?.details?.items?.[0]?.error?.description ?? err?.message ?? ''
|
|
86
|
+
if (/revision|mismatch|ifDraftRevisionId/i.test(description)) {
|
|
87
|
+
return "Un des documents a été modifié pendant que la fenêtre était ouverte : la liste vient d'être mise à jour, relancez la publication."
|
|
88
|
+
}
|
|
89
|
+
if (/reference/i.test(description)) {
|
|
90
|
+
return `Un document référence un contenu jamais publié qui n'est pas coché : cochez-le aussi, ou retirez la référence. (${description})`
|
|
91
|
+
}
|
|
92
|
+
if (err?.statusCode === 403 || /permission/i.test(description)) return "Vous n'avez pas le droit de publier un de ces documents."
|
|
93
|
+
return description ? `Publication refusée : ${description}` : 'Publication refusée.'
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** « à l'instant », « il y a 5 min », « il y a 3 h », « il y a 2 j ». */
|
|
97
|
+
export function sinceLabel(iso: string, now = Date.now()): string {
|
|
98
|
+
const minutes = Math.max(0, Math.round((now - Date.parse(iso)) / 60_000))
|
|
99
|
+
if (minutes < 1) return "à l'instant"
|
|
100
|
+
if (minutes < 60) return `il y a ${minutes} min`
|
|
101
|
+
const hours = Math.round(minutes / 60)
|
|
102
|
+
if (hours < 24) return `il y a ${hours} h`
|
|
103
|
+
return `il y a ${Math.round(hours / 24)} j`
|
|
104
|
+
}
|
package/src/version.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Version du kit, rapportée au service pour savoir quels projets tournent sur
|
|
3
|
-
* quelle version.
|
|
3
|
+
* quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
|
|
4
|
+
* le vérifie.
|
|
4
5
|
*/
|
|
5
|
-
export const KIT_VERSION = '2.
|
|
6
|
+
export const KIT_VERSION = '2.14.0'
|