@nocode-factory/sanity-kit 2.35.0 → 2.36.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocode-factory/sanity-kit",
3
- "version": "2.35.0",
3
+ "version": "2.36.0",
4
4
  "description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -0,0 +1,187 @@
1
+ import {useEffect, useState} from 'react'
2
+ import {Box, Button, Card, Checkbox, Flex, Spinner, Stack, Text} from '@sanity/ui'
3
+ import {useToast} from '@sanity/ui/toast'
4
+ import type {DocumentActionComponent, DocumentActionProps} from 'sanity'
5
+ import type {ResolvedKitConfig} from '../config/types'
6
+ import {useKitClient} from '../hooks/useKitClient'
7
+ import {translationsOf} from '../lib/translateDocument'
8
+
9
+ type Doc = Record<string, unknown>
10
+ type Referrer = {_id: string; _type: string; title?: string}
11
+ interface Version {
12
+ language: string
13
+ id: string
14
+ selected: boolean
15
+ }
16
+
17
+ /** Identifiants publiés + brouillons d'une liste de documents. */
18
+ export const withDrafts = (ids: string[]): string[] => ids.flatMap((id) => [id, `drafts.${id}`])
19
+
20
+ /**
21
+ * Supprimer la version PRINCIPALE d'un document traduit (page, fiche de collection,
22
+ * réglage par langue) : la fenêtre propose de supprimer aussi ses autres langues
23
+ * (cochées par défaut), en une fois. Bloqué, avec la liste, si un autre document y
24
+ * fait encore référence (comme la suppression native de Sanity). Les liens de
25
+ * traduction sont nettoyés. Sans traduction, ou depuis une autre langue : la
26
+ * suppression native, inchangée.
27
+ */
28
+ export function withTranslationDelete(
29
+ Delete: DocumentActionComponent,
30
+ config: ResolvedKitConfig,
31
+ masterLocale?: string,
32
+ ): DocumentActionComponent {
33
+ const i18n = config.i18n
34
+ const master = masterLocale ?? i18n?.defaultLocale
35
+ const Wrapped: DocumentActionComponent = (props: DocumentActionProps) => {
36
+ const base = Delete(props)
37
+ const client = useKitClient()
38
+ const [versions, setVersions] = useState<Version[] | null>(null)
39
+ const current = (props.draft ?? props.published) as Doc | null
40
+ useEffect(() => {
41
+ if (!i18n || current?.[i18n.field] !== master) return
42
+ let alive = true
43
+ translationsOf(client, props.id)
44
+ .then((list) => alive && setVersions(list.filter((t) => t.id !== props.id).map((t) => ({...t, selected: true}))))
45
+ .catch(() => alive && setVersions([]))
46
+ return () => {
47
+ alive = false
48
+ }
49
+ }, [client, props.id, current?.[i18n?.field ?? 'language']])
50
+ const [open, setOpen] = useState(false)
51
+ if (!base || !i18n || current?.[i18n.field] !== master || !versions?.length) return base
52
+ return {
53
+ ...base,
54
+ onHandle: () => setOpen(true),
55
+ dialog: open
56
+ ? {
57
+ type: 'dialog',
58
+ header: 'Delete this document',
59
+ width: 'medium',
60
+ onClose: () => setOpen(false),
61
+ content: (
62
+ <DeleteDialog
63
+ id={props.id}
64
+ language={String(current?.[i18n.field] ?? '')}
65
+ versions={versions}
66
+ onDone={() => {
67
+ setOpen(false)
68
+ props.onComplete()
69
+ }}
70
+ />
71
+ ),
72
+ }
73
+ : base.dialog,
74
+ }
75
+ }
76
+ return Wrapped
77
+ }
78
+
79
+ function DeleteDialog(props: {id: string; language: string; versions: Version[]; onDone: () => void}) {
80
+ const {id, language, onDone} = props
81
+ const client = useKitClient()
82
+ const toast = useToast()
83
+ const [versions, setVersions] = useState(props.versions)
84
+ const [referrers, setReferrers] = useState<Referrer[] | null>(null)
85
+ const [busy, setBusy] = useState(false)
86
+ const [error, setError] = useState<string | null>(null)
87
+ const ids = [id, ...versions.filter((v) => v.selected).map((v) => v.id)]
88
+ const key = ids.join(',')
89
+
90
+ // Documents (hors versions supprimées et liens de traduction) qui y font référence.
91
+ useEffect(() => {
92
+ setReferrers(null)
93
+ const all = withDrafts(ids)
94
+ client
95
+ .fetch<Referrer[]>(
96
+ `*[references($ids) && !(_id in $all) && _type != "translation.metadata"]{_id, _type, "title": coalesce(title, name, heading, _id)}`,
97
+ {ids, all},
98
+ )
99
+ .then(setReferrers)
100
+ .catch(() => setReferrers([]))
101
+ // eslint-disable-next-line react-hooks/exhaustive-deps
102
+ }, [client, key])
103
+
104
+ const remove = async () => {
105
+ setBusy(true)
106
+ setError(null)
107
+ try {
108
+ const tx = client.transaction()
109
+ for (const docId of withDrafts(ids)) tx.delete(docId)
110
+ // Liens de traduction : retirés pour les versions supprimées, document de
111
+ // liens supprimé s'il ne relie plus rien.
112
+ const meta = await client.fetch<{_id: string; translations?: {_key: string; value?: {_ref?: string}}[]} | null>(
113
+ `*[_type == "translation.metadata" && references($id)][0]{_id, translations}`,
114
+ {id},
115
+ )
116
+ if (meta) {
117
+ const gone = (meta.translations ?? []).filter((t) => ids.includes(t.value?._ref ?? ''))
118
+ if ((meta.translations ?? []).length - gone.length > 1) tx.patch(meta._id, (p) => p.unset(gone.map((t) => `translations[_key == "${t._key}"]`)))
119
+ else tx.delete(meta._id)
120
+ }
121
+ await tx.commit({visibility: 'async'})
122
+ toast.push({status: 'success', title: `Deleted: ${[language, ...versions.filter((v) => v.selected).map((v) => v.language)].map((l) => l.toUpperCase()).join(', ')}`, duration: 6000})
123
+ onDone()
124
+ } catch (cause) {
125
+ setError(`Failed. (${(cause instanceof Error ? cause.message : String(cause)).slice(0, 160)})`)
126
+ setBusy(false)
127
+ }
128
+ }
129
+
130
+ const blocked = !!referrers?.length
131
+ return (
132
+ <Stack gap={4} padding={4}>
133
+ <Text size={1}>
134
+ The {language.toUpperCase()} version will be deleted for good (published and draft). Delete the other language versions too?
135
+ </Text>
136
+ <Stack gap={2}>
137
+ {versions.map((v, index) => (
138
+ <Card key={v.id} padding={3} radius={2} border>
139
+ <Flex as="label" gap={3} align="center">
140
+ <Checkbox checked={v.selected} disabled={busy} onChange={() => setVersions(versions.map((x, i) => (i === index ? {...x, selected: !x.selected} : x)))} />
141
+ <Text size={1} weight="semibold">
142
+ {v.language.toUpperCase()}
143
+ </Text>
144
+ </Flex>
145
+ </Card>
146
+ ))}
147
+ </Stack>
148
+ {referrers === null ? (
149
+ <Flex justify="center">
150
+ <Spinner muted />
151
+ </Flex>
152
+ ) : blocked ? (
153
+ <Card tone="critical" padding={3} radius={2}>
154
+ <Stack gap={2}>
155
+ <Text size={1}>Still referenced by these documents: remove the references first.</Text>
156
+ {referrers.slice(0, 8).map((r) => (
157
+ <Text key={r._id} size={1} muted>
158
+ {r.title} ({r._type})
159
+ </Text>
160
+ ))}
161
+ {referrers.length > 8 && (
162
+ <Text size={1} muted>
163
+ …and {referrers.length - 8} more
164
+ </Text>
165
+ )}
166
+ </Stack>
167
+ </Card>
168
+ ) : null}
169
+ {error && (
170
+ <Card tone="critical" padding={3} radius={2}>
171
+ <Text size={1}>{error}</Text>
172
+ </Card>
173
+ )}
174
+ <Flex justify="flex-end" gap={2}>
175
+ <Box>
176
+ <Button text="Cancel" mode="ghost" onClick={onDone} disabled={busy} />
177
+ </Box>
178
+ <Button
179
+ text={busy ? 'Deleting…' : `Delete ${ids.length > 1 ? `${ids.length} versions` : `${language.toUpperCase()} only`}`}
180
+ tone="critical"
181
+ onClick={() => void remove()}
182
+ disabled={busy || referrers === null || blocked}
183
+ />
184
+ </Flex>
185
+ </Stack>
186
+ )
187
+ }
@@ -1,10 +1,13 @@
1
1
  import {useEffect, useState} from 'react'
2
- import {Stack, Text} from '@sanity/ui'
2
+ import {Card, Checkbox, Flex, Stack, Text} from '@sanity/ui'
3
3
  import {EyeClosedIcon} from '@sanity/icons/EyeClosed'
4
- import type {DocumentActionComponent, DocumentActionProps} from 'sanity'
4
+ import type {DocumentActionComponent, DocumentActionDescription, DocumentActionProps} from 'sanity'
5
5
  import {useKitClient} from '../hooks/useKitClient'
6
+ import type {ResolvedKitConfig} from '../config/types'
7
+ import {translationsOf} from '../lib/translateDocument'
6
8
 
7
9
  type Referrer = {_id: string; _type: string; title?: string}
10
+ type Version = {language: string; id: string; selected: boolean}
8
11
 
9
12
  /**
10
13
  * « Retirer du site » : dépublication native de Sanity, rendue visible et expliquée.
@@ -17,24 +20,60 @@ type Referrer = {_id: string; _type: string; title?: string}
17
20
  * leurs liens vers elle disparaîtront du site. Une référence FORTE (non `weak`)
18
21
  * empêche Sanity de dépublier : le message l'explique au lieu d'une erreur brute.
19
22
  */
20
- export const RemoveFromSiteAction: DocumentActionComponent = (props: DocumentActionProps) => {
23
+ export const RemoveFromSiteAction: DocumentActionComponent = createRemoveFromSite()
24
+
25
+ /**
26
+ * Variante multilingue : sur la version PRINCIPALE d'un document traduit (page ou
27
+ * fiche de collection), la fenêtre propose aussi de retirer du site ses autres
28
+ * langues publiées (cochées par défaut), en une seule opération.
29
+ */
30
+ export function createRemoveFromSite(config?: ResolvedKitConfig, masterLocale?: string): DocumentActionComponent {
31
+ const i18n = config?.i18n
32
+ const master = masterLocale ?? i18n?.defaultLocale
33
+ const Action: DocumentActionComponent = (props: DocumentActionProps) => useRemoveFromSite(props, i18n?.field, master)
34
+ Action.action = 'unpublish'
35
+ return Action
36
+ }
37
+
38
+ function useRemoveFromSite(props: DocumentActionProps, field: string | undefined, master: string | undefined): DocumentActionDescription | null {
21
39
  const client = useKitClient()
40
+ const current = (props.draft ?? props.published) as Record<string, unknown> | null
41
+ const isMaster = !!field && !!master && current?.[field] === master
42
+ const [versions, setVersions] = useState<Version[]>([])
22
43
  const [open, setOpen] = useState(false)
23
44
  const [referrers, setReferrers] = useState<Referrer[] | null>(null)
24
45
  const [busy, setBusy] = useState(false)
25
46
  const [error, setError] = useState<string | null>(null)
26
47
 
48
+ // Autres langues PUBLIÉES de la version principale (proposées, cochées).
49
+ useEffect(() => {
50
+ if (!open || !isMaster) return
51
+ let alive = true
52
+ translationsOf(client, props.id)
53
+ .then(async (list) => {
54
+ const others = list.filter((t) => t.id !== props.id)
55
+ const live = new Set(await client.fetch<string[]>(`*[_id in $ids]._id`, {ids: others.map((t) => t.id)}))
56
+ if (alive) setVersions(others.filter((t) => live.has(t.id)).map((t) => ({...t, selected: true})))
57
+ })
58
+ .catch(() => alive && setVersions([]))
59
+ return () => {
60
+ alive = false
61
+ }
62
+ }, [open, isMaster, client, props.id])
63
+ const ids = [props.id, ...versions.filter((v) => v.selected).map((v) => v.id)]
64
+
27
65
  useEffect(() => {
28
66
  if (!open) return
29
67
  setReferrers(null)
30
68
  client
31
69
  .fetch<Referrer[]>(
32
- `*[references($id) && !(_id in path("drafts.**")) && _type != "translation.metadata"]{_id, _type, "title": coalesce(title, name, _id)}`,
33
- {id: props.id},
70
+ `*[references($ids) && !(_id in path("drafts.**")) && !(_id in $ids) && _type != "translation.metadata"]{_id, _type, "title": coalesce(title, name, _id)}`,
71
+ {ids},
34
72
  )
35
73
  .then(setReferrers)
36
74
  .catch(() => setReferrers([]))
37
- }, [open, client, props.id])
75
+ // eslint-disable-next-line react-hooks/exhaustive-deps
76
+ }, [open, client, ids.join(',')])
38
77
 
39
78
  if (!props.published) return null
40
79
 
@@ -42,11 +81,17 @@ export const RemoveFromSiteAction: DocumentActionComponent = (props: DocumentAct
42
81
  setBusy(true)
43
82
  setError(null)
44
83
  try {
45
- const {_rev, _updatedAt, ...published} = props.published as Record<string, unknown>
46
84
  const tx = client.transaction()
47
- // Le brouillon en cours est conservé tel quel ; sinon il reprend la version en ligne.
48
- if (!props.draft) tx.createIfNotExists({...published, _id: `drafts.${props.id}`} as {_id: string; _type: string})
49
- tx.delete(props.id)
85
+ // Chaque version : le brouillon en cours est conservé tel quel ; sinon il
86
+ // reprend la version en ligne. Puis la version en ligne est supprimée.
87
+ const docs = await client.fetch<Record<string, unknown>[]>(`*[_id in $ids]`, {ids})
88
+ const drafts = new Set(await client.fetch<string[]>(`*[_id in $drafts]._id`, {drafts: ids.map((id) => `drafts.${id}`)}))
89
+ for (const doc of docs) {
90
+ const {_rev, _updatedAt, ...published} = doc
91
+ const id = String(doc._id)
92
+ if (!drafts.has(`drafts.${id}`)) tx.createIfNotExists({...published, _id: `drafts.${id}`} as {_id: string; _type: string})
93
+ tx.delete(id)
94
+ }
50
95
  await tx.commit()
51
96
  setOpen(false)
52
97
  props.onComplete()
@@ -80,21 +125,40 @@ export const RemoveFromSiteAction: DocumentActionComponent = (props: DocumentAct
80
125
  message: (
81
126
  <Stack gap={3}>
82
127
  <Text size={1}>
83
- The page leaves the site (production and staging "Published"). All its content stays in the
84
- draft: to put it back online, publish it.
128
+ It leaves the site (production and staging "Published"). All its content stays in the draft:
129
+ to put it back online, publish it.
85
130
  </Text>
131
+ {versions.length > 0 && (
132
+ <Stack gap={2}>
133
+ <Text size={1} weight="semibold">
134
+ Also remove the other languages from the site:
135
+ </Text>
136
+ {versions.map((v, index) => (
137
+ <Card key={v.id} padding={2} radius={2} border>
138
+ <Flex as="label" gap={3} align="center">
139
+ <Checkbox
140
+ checked={v.selected}
141
+ disabled={busy}
142
+ onChange={() => setVersions(versions.map((x, i) => (i === index ? {...x, selected: !x.selected} : x)))}
143
+ />
144
+ <Text size={1}>{v.language.toUpperCase()}</Text>
145
+ </Flex>
146
+ </Card>
147
+ ))}
148
+ </Stack>
149
+ )}
86
150
  {referrers === null ? (
87
151
  <Text size={1} muted>
88
- Looking for links to this page…
152
+ Looking for links…
89
153
  </Text>
90
154
  ) : referrers.length > 0 ? (
91
155
  <Text size={1}>
92
- These published documents point to it; their links to this page will disappear from the site:{' '}
156
+ These published documents point to it; their links will disappear from the site:{' '}
93
157
  {referrers.map((r) => r.title || r._id).join(', ')}.
94
158
  </Text>
95
159
  ) : (
96
160
  <Text size={1} muted>
97
- No published document points to this page.
161
+ No published document points to it.
98
162
  </Text>
99
163
  )}
100
164
  {error && (
@@ -107,4 +171,3 @@ export const RemoveFromSiteAction: DocumentActionComponent = (props: DocumentAct
107
171
  },
108
172
  }
109
173
  }
110
- RemoveFromSiteAction.action = 'unpublish'
package/src/index.ts CHANGED
@@ -41,12 +41,13 @@ export const NCF_TOOL_NAMES = [
41
41
  * pas le Studio de démarrer : l'onglet concerné affiche le détail à corriger.
42
42
  */
43
43
  import {createOverrideInput} from './form/OverrideInput'
44
- import {RemoveFromSiteAction} from './actions/RemoveFromSite'
44
+ import {RemoveFromSiteAction, createRemoveFromSite} from './actions/RemoveFromSite'
45
45
  import {createSlugUrlInput, isSlugInput} from './form/SlugUrlInput'
46
46
  import {withTranslationTodo} from './form/TranslationTodoInput'
47
47
  import {withPublishedHint} from './form/PublishedHint'
48
48
  import {withLanguageMismatch} from './form/LanguageMismatch'
49
49
  import {withPropagation} from './actions/PropagatePublish'
50
+ import {withTranslationDelete} from './actions/DeleteTranslations'
50
51
 
51
52
  /** Champs du formulaire : adresse sous le Slug d'une page, pastille sur les sections. */
52
53
  function createKitInput(config: Parameters<typeof createOverrideInput>[0]): ComponentType<InputProps> {
@@ -145,24 +146,34 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
145
146
  prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
146
147
  // Pages : « Retirer du site » (dépublication expliquée, liens listés) à la place
147
148
  // du « Unpublish » natif, caché et bloqué sans explication par les références.
149
+ // Supprimer la version principale d'un document traduit : suppression de ses
150
+ // autres langues proposée (cochées par défaut).
148
151
  // Publier la version principale d'une page traduite : propagation proposée aux
149
152
  // brouillons des autres langues (structure et valeurs ; textes « à traduire »).
150
153
  actions: (prev, context) =>
151
154
  config.pageTypeNames.includes(context.schemaType)
152
155
  ? prev.map((action) =>
153
- action.action === 'unpublish' ? RemoveFromSiteAction : action.action === 'publish' && config.i18n ? withPropagation(action, config, undefined, {allowCreate: true}) : action,
156
+ action.action === 'unpublish' ? (config.i18n ? createRemoveFromSite(config) : RemoveFromSiteAction) : action.action === 'publish' && config.i18n ? withPropagation(action, config, undefined, {allowCreate: true}) : action.action === 'delete' && config.i18n ? withTranslationDelete(action, config) : action,
154
157
  )
155
158
  : // Valeurs par défaut des composants : publier celles de la langue source
156
159
  // (anglais en général) propose de retraduire celles des autres langues.
157
160
  context.schemaType === config.componentPreview.defaultsType && config.i18n
158
- ? prev.map((action) => (action.action === 'publish' ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action))
161
+ ? prev.map((action) => (action.action === 'publish' ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action.action === 'delete' ? withTranslationDelete(action, config, config.i18n?.defaultsSourceLocale) : action))
159
162
  : // Tout autre type traduit document par document (collections, réglages
160
163
  // par langue) : même proposition que les pages à la publication de la
161
164
  // version principale (mettre à jour ou créer les autres langues).
162
165
  // Détecté par le champ de langue du schéma : une nouvelle collection
163
166
  // traduite en profite sans réglage.
164
167
  config.i18n && !isKitType(context.schemaType) && hasLanguageField(context.schema.get(context.schemaType), config.i18n.field)
165
- ? prev.map((action) => (action.action === 'publish' ? withPropagation(action, config, undefined, {allowCreate: true}) : action))
168
+ ? prev.map((action) =>
169
+ action.action === 'publish'
170
+ ? withPropagation(action, config, undefined, {allowCreate: true})
171
+ : action.action === 'delete'
172
+ ? withTranslationDelete(action, config)
173
+ : action.action === 'unpublish'
174
+ ? createRemoveFromSite(config)
175
+ : action,
176
+ )
166
177
  : prev,
167
178
  },
168
179
 
package/src/version.ts CHANGED
@@ -3,4 +3,4 @@
3
3
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
4
4
  * le vérifie.
5
5
  */
6
- export const KIT_VERSION = '2.35.0'
6
+ export const KIT_VERSION = '2.36.0'