@nocode-factory/sanity-kit 2.37.1 → 2.38.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/fixCrossLanguageReferences-CTQ58gmP.js +519 -0
- package/dist/fixCrossLanguageReferences-CTQ58gmP.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +60 -170
- package/dist/index.js.map +1 -1
- package/dist/schema.d.ts +42 -1
- package/dist/schema.js +2 -2
- package/package.json +1 -1
- package/src/actions/DeleteTranslations.tsx +34 -7
- package/src/actions/TranslationRedirects.tsx +36 -0
- package/src/index.ts +2 -1
- package/src/lib/translateDocument.ts +7 -0
- package/src/lib/translationRedirects.ts +123 -0
- package/src/schema/index.ts +1 -0
- package/src/version.ts +1 -1
- package/dist/fixCrossLanguageReferences-CagQ_Vvk.js +0 -263
- package/dist/fixCrossLanguageReferences-CagQ_Vvk.js.map +0 -1
package/dist/schema.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { a as componentDefaultsMainDocument, c as defineComponentDefaults, i as DEFAULT_COMPONENT_DEFAULTS_TYPE, l as requiredUnlessDefault, n as fixCrossLanguageReferences, o as componentDefaultsMainDocuments, r as withSameLanguageReferences, s as defaultsFieldName, t as CrossLanguageReport, u as requiredUnlessDefaultFor } from "./fixCrossLanguageReferences-D4phJn84.js";
|
|
2
|
+
import { SanityClient } from "sanity";
|
|
2
3
|
/**
|
|
3
4
|
* Onglets du formulaire d'un document : Content, Sections, SEO, Settings.
|
|
4
5
|
*
|
|
@@ -36,5 +37,45 @@ export declare function formTabOf(name: string, pageBuilderField?: string): (typ
|
|
|
36
37
|
export declare function withNcfFormTabs<T>(types: readonly T[], options?: {
|
|
37
38
|
pageBuilderField?: string;
|
|
38
39
|
}): T[];
|
|
39
|
-
|
|
40
|
+
interface TranslationRedirectOptions {
|
|
41
|
+
/** Champ de langue des documents. */
|
|
42
|
+
field?: string;
|
|
43
|
+
/** Langue principale : son slug est le slug « d'origine ». */
|
|
44
|
+
defaultLocale: string;
|
|
45
|
+
/** Types qui ont une page par document (préfixe d'adresse du registre). */
|
|
46
|
+
types: {
|
|
47
|
+
type: string;
|
|
48
|
+
pathPrefix?: string | null;
|
|
49
|
+
slugField?: string;
|
|
50
|
+
}[];
|
|
51
|
+
/** Type de document des redirections (champs from, to, permanent, note). */
|
|
52
|
+
redirectType?: string;
|
|
53
|
+
/** `false` : simulation, rien n'est écrit. Défaut : true. */
|
|
54
|
+
apply?: boolean;
|
|
55
|
+
}
|
|
56
|
+
interface TranslationRedirect {
|
|
57
|
+
id: string;
|
|
58
|
+
from: string;
|
|
59
|
+
to: string;
|
|
60
|
+
note: string;
|
|
61
|
+
}
|
|
62
|
+
/** Identifiant stable de la redirection d'une version (mise à jour, jamais dupliquée). */
|
|
63
|
+
export declare const translationRedirectId: (versionId: string) => string;
|
|
64
|
+
/**
|
|
65
|
+
* RÈGLE D'OR DU MULTILINGUE, adresses : chaque version a un slug dans SA langue, et
|
|
66
|
+
* l'adresse « slug d'origine dans cette langue » redirige vers elle (une page
|
|
67
|
+
* /rouge, traduite /en/red : /en/rouge redirige vers /en/red). Enregistré comme
|
|
68
|
+
* une vraie redirection (visible dans le Studio, « Redirects »), une par version,
|
|
69
|
+
* mise à jour si un slug change. Rien quand le slug est le même, ni quand l'adresse
|
|
70
|
+
* d'origine est déjà une vraie page de cette langue.
|
|
71
|
+
*
|
|
72
|
+
* `seeds` : documents dont on traite le groupe de traductions (tous si absent).
|
|
73
|
+
* `override` : valeurs d'une version en cours de publication (pas encore lisibles).
|
|
74
|
+
*/
|
|
75
|
+
export declare function syncTranslationRedirects(client: SanityClient, options: TranslationRedirectOptions, seeds?: string[], override?: {
|
|
76
|
+
id: string;
|
|
77
|
+
slug?: string | null;
|
|
78
|
+
language?: string | null;
|
|
79
|
+
}): Promise<TranslationRedirect[]>;
|
|
80
|
+
export { type CrossLanguageReport, DEFAULT_COMPONENT_DEFAULTS_TYPE, type TranslationRedirect, type TranslationRedirectOptions, componentDefaultsMainDocument, componentDefaultsMainDocuments, defaultsFieldName, defineComponentDefaults, fixCrossLanguageReferences, requiredUnlessDefault, requiredUnlessDefaultFor, withSameLanguageReferences };
|
|
40
81
|
//# sourceMappingURL=schema.d.ts.map
|
package/dist/schema.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as componentDefaultsMainDocuments, c as requiredUnlessDefault,
|
|
1
|
+
import { T as DEFAULT_PAGE_BUILDER_FIELD, a as componentDefaultsMainDocuments, c as requiredUnlessDefault, d as translationRedirectId, i as componentDefaultsMainDocument, l as requiredUnlessDefaultFor, n as withSameLanguageReferences, o as defaultsFieldName, r as DEFAULT_COMPONENT_DEFAULTS_TYPE, s as defineComponentDefaults, t as fixCrossLanguageReferences, u as syncTranslationRedirects } from "./fixCrossLanguageReferences-CTQ58gmP.js";
|
|
2
2
|
/**
|
|
3
3
|
* Onglets du formulaire d'un document : Content, Sections, SEO, Settings.
|
|
4
4
|
*
|
|
@@ -74,6 +74,6 @@ function withNcfFormTabs(types, options = {}) {
|
|
|
74
74
|
});
|
|
75
75
|
});
|
|
76
76
|
}
|
|
77
|
-
export { DEFAULT_COMPONENT_DEFAULTS_TYPE, componentDefaultsMainDocument, componentDefaultsMainDocuments, defaultsFieldName, defineComponentDefaults, fixCrossLanguageReferences, formTabOf, requiredUnlessDefault, requiredUnlessDefaultFor, withNcfFormTabs, withSameLanguageReferences };
|
|
77
|
+
export { DEFAULT_COMPONENT_DEFAULTS_TYPE, componentDefaultsMainDocument, componentDefaultsMainDocuments, defaultsFieldName, defineComponentDefaults, fixCrossLanguageReferences, formTabOf, requiredUnlessDefault, requiredUnlessDefaultFor, syncTranslationRedirects, translationRedirectId, withNcfFormTabs, withSameLanguageReferences };
|
|
78
78
|
|
|
79
79
|
//# sourceMappingURL=schema.js.map
|
package/package.json
CHANGED
|
@@ -5,6 +5,8 @@ import type {DocumentActionComponent, DocumentActionProps} from 'sanity'
|
|
|
5
5
|
import type {ResolvedKitConfig} from '../config/types'
|
|
6
6
|
import {useKitClient} from '../hooks/useKitClient'
|
|
7
7
|
import {translationsOf} from '../lib/translateDocument'
|
|
8
|
+
import {translationRedirectId, translationRedirectOptions, type TranslationRedirectOptions} from '../lib/translationRedirects'
|
|
9
|
+
import {toPath} from '../lib/paths'
|
|
8
10
|
|
|
9
11
|
type Doc = Record<string, unknown>
|
|
10
12
|
type Referrer = {_id: string; _type: string; title?: string}
|
|
@@ -32,6 +34,9 @@ export function withTranslationDelete(
|
|
|
32
34
|
): DocumentActionComponent {
|
|
33
35
|
const i18n = config.i18n
|
|
34
36
|
const master = masterLocale ?? i18n?.defaultLocale
|
|
37
|
+
// Types à pages : toute suppression passe par la fenêtre du kit, qui retire aussi
|
|
38
|
+
// les redirections menant à la page supprimée (sinon : une 404 de plus).
|
|
39
|
+
const redirects = translationRedirectOptions(config)
|
|
35
40
|
const Wrapped: DocumentActionComponent = (props: DocumentActionProps) => {
|
|
36
41
|
const base = Delete(props)
|
|
37
42
|
const client = useKitClient()
|
|
@@ -48,7 +53,10 @@ export function withTranslationDelete(
|
|
|
48
53
|
}
|
|
49
54
|
}, [client, props.id, current?.[i18n?.field ?? 'language']])
|
|
50
55
|
const [open, setOpen] = useState(false)
|
|
51
|
-
|
|
56
|
+
const isMaster = !!i18n && current?.[i18n.field] === master
|
|
57
|
+
const hasPage = !!redirects?.types.some((t) => t.type === props.type)
|
|
58
|
+
if (!base || !i18n) return base
|
|
59
|
+
if (isMaster ? versions === null || (!versions.length && !hasPage) : !hasPage) return base
|
|
52
60
|
return {
|
|
53
61
|
...base,
|
|
54
62
|
onHandle: () => setOpen(true),
|
|
@@ -62,7 +70,8 @@ export function withTranslationDelete(
|
|
|
62
70
|
<DeleteDialog
|
|
63
71
|
id={props.id}
|
|
64
72
|
language={String(current?.[i18n.field] ?? '')}
|
|
65
|
-
versions={versions}
|
|
73
|
+
versions={isMaster ? (versions ?? []) : []}
|
|
74
|
+
redirects={hasPage ? redirects : null}
|
|
66
75
|
onDone={() => {
|
|
67
76
|
setOpen(false)
|
|
68
77
|
props.onComplete()
|
|
@@ -76,8 +85,8 @@ export function withTranslationDelete(
|
|
|
76
85
|
return Wrapped
|
|
77
86
|
}
|
|
78
87
|
|
|
79
|
-
function DeleteDialog(props: {id: string; language: string; versions: Version[]; onDone: () => void}) {
|
|
80
|
-
const {id, language, onDone} = props
|
|
88
|
+
function DeleteDialog(props: {id: string; language: string; versions: Version[]; redirects: TranslationRedirectOptions | null; onDone: () => void}) {
|
|
89
|
+
const {id, language, onDone, redirects} = props
|
|
81
90
|
const client = useKitClient()
|
|
82
91
|
const toast = useToast()
|
|
83
92
|
const [versions, setVersions] = useState(props.versions)
|
|
@@ -118,6 +127,22 @@ function DeleteDialog(props: {id: string; language: string; versions: Version[];
|
|
|
118
127
|
if ((meta.translations ?? []).length - gone.length > 1) tx.patch(meta._id, (p) => p.unset(gone.map((t) => `translations[_key == "${t._key}"]`)))
|
|
119
128
|
else tx.delete(meta._id)
|
|
120
129
|
}
|
|
130
|
+
// Redirections qui mèneraient aux pages supprimées : retirées (avec celles des
|
|
131
|
+
// adresses traduites de ces versions).
|
|
132
|
+
if (redirects) {
|
|
133
|
+
const field = redirects.field ?? 'language'
|
|
134
|
+
const gone = await client.fetch<{_type: string; slug?: string; language?: string}[]>(
|
|
135
|
+
`*[_id in $ids]{_type, "slug": slug.current, "language": ${field}}`,
|
|
136
|
+
{ids},
|
|
137
|
+
)
|
|
138
|
+
const i18nPaths = {field, defaultLocale: redirects.defaultLocale, locales: [], defaultsSourceLocale: redirects.defaultLocale}
|
|
139
|
+
const paths = gone
|
|
140
|
+
.map((d) => toPath({slug: d.slug, pathPrefix: redirects.types.find((t) => t.type === d._type)?.pathPrefix, locale: d.language}, i18nPaths))
|
|
141
|
+
.filter((x): x is string => !!x)
|
|
142
|
+
const redirectType = redirects.redirectType ?? 'redirect'
|
|
143
|
+
const leading = paths.length ? await client.fetch<string[]>(`*[_type == $redirectType && to in $paths]._id`, {redirectType, paths}) : []
|
|
144
|
+
for (const rid of new Set([...leading, ...ids.map(translationRedirectId)])) tx.delete(rid)
|
|
145
|
+
}
|
|
121
146
|
await tx.commit({visibility: 'async'})
|
|
122
147
|
toast.push({status: 'success', title: `Deleted: ${[language, ...versions.filter((v) => v.selected).map((v) => v.language)].map((l) => l.toUpperCase()).join(', ')}`, duration: 6000})
|
|
123
148
|
onDone()
|
|
@@ -131,9 +156,11 @@ function DeleteDialog(props: {id: string; language: string; versions: Version[];
|
|
|
131
156
|
return (
|
|
132
157
|
<Stack gap={4} padding={4}>
|
|
133
158
|
<Text size={1}>
|
|
134
|
-
The {language.toUpperCase()} version will be deleted for good (published and draft).
|
|
159
|
+
The {language.toUpperCase()} version will be deleted for good (published and draft).
|
|
160
|
+
{versions.length ? ' Delete the other language versions too?' : ''}
|
|
161
|
+
{redirects ? ' Redirects leading to it are removed.' : ''}
|
|
135
162
|
</Text>
|
|
136
|
-
<Stack gap={2}>
|
|
163
|
+
{versions.length > 0 && (<Stack gap={2}>
|
|
137
164
|
{versions.map((v, index) => (
|
|
138
165
|
<Card key={v.id} padding={3} radius={2} border>
|
|
139
166
|
<Flex as="label" gap={3} align="center">
|
|
@@ -144,7 +171,7 @@ function DeleteDialog(props: {id: string; language: string; versions: Version[];
|
|
|
144
171
|
</Flex>
|
|
145
172
|
</Card>
|
|
146
173
|
))}
|
|
147
|
-
</Stack>
|
|
174
|
+
</Stack>)}
|
|
148
175
|
{referrers === null ? (
|
|
149
176
|
<Flex justify="center">
|
|
150
177
|
<Spinner muted />
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type {DocumentActionComponent, DocumentActionProps} from 'sanity'
|
|
2
|
+
import type {ResolvedKitConfig} from '../config/types'
|
|
3
|
+
import {useKitClient} from '../hooks/useKitClient'
|
|
4
|
+
import {syncTranslationRedirects, translationRedirectOptions} from '../lib/translationRedirects'
|
|
5
|
+
|
|
6
|
+
type Doc = Record<string, unknown>
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Publier une version d'une page ou d'une fiche traduite : les redirections
|
|
10
|
+
* « slug d'origine dans cette langue → slug traduit » de son groupe de traductions
|
|
11
|
+
* sont mises à jour (créées, corrigées si un slug change, retirées si inutiles).
|
|
12
|
+
* Jamais bloquant : un échec est seulement signalé dans la console.
|
|
13
|
+
*/
|
|
14
|
+
export function withTranslationRedirects(Publish: DocumentActionComponent, config: ResolvedKitConfig): DocumentActionComponent {
|
|
15
|
+
const options = translationRedirectOptions(config)
|
|
16
|
+
if (!options) return Publish
|
|
17
|
+
const Wrapped: DocumentActionComponent = (props: DocumentActionProps) => {
|
|
18
|
+
const base = Publish(props)
|
|
19
|
+
const client = useKitClient()
|
|
20
|
+
if (!base) return base
|
|
21
|
+
return {
|
|
22
|
+
...base,
|
|
23
|
+
onHandle: () => {
|
|
24
|
+
const draft = props.draft as Doc | null
|
|
25
|
+
const slugField = options.types.find((t) => t.type === props.type)?.slugField ?? 'slug'
|
|
26
|
+
const slug = (draft?.[slugField] as {current?: string} | undefined)?.current
|
|
27
|
+
const language = draft?.[options.field ?? 'language'] as string | undefined
|
|
28
|
+
base.onHandle?.()
|
|
29
|
+
void syncTranslationRedirects(client, options, [props.id], {id: props.id, slug, language}).catch((cause) =>
|
|
30
|
+
console.error('Redirections de traduction non mises à jour :', cause),
|
|
31
|
+
)
|
|
32
|
+
},
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return Wrapped
|
|
36
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -48,6 +48,7 @@ import {withPublishedHint} from './form/PublishedHint'
|
|
|
48
48
|
import {withLanguageMismatch} from './form/LanguageMismatch'
|
|
49
49
|
import {withPropagation} from './actions/PropagatePublish'
|
|
50
50
|
import {withTranslationDelete} from './actions/DeleteTranslations'
|
|
51
|
+
import {withTranslationRedirects} from './actions/TranslationRedirects'
|
|
51
52
|
|
|
52
53
|
/** Champs du formulaire : adresse sous le Slug d'une page, pastille sur les sections. */
|
|
53
54
|
function createKitInput(config: Parameters<typeof createOverrideInput>[0]): ComponentType<InputProps> {
|
|
@@ -153,7 +154,7 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
|
|
|
153
154
|
actions: (prev, context) =>
|
|
154
155
|
config.pageTypeNames.includes(context.schemaType)
|
|
155
156
|
? prev.map((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,
|
|
157
|
+
action.action === 'unpublish' ? (config.i18n ? createRemoveFromSite(config) : RemoveFromSiteAction) : action.action === 'publish' && config.i18n ? withTranslationRedirects(withPropagation(action, config, undefined, {allowCreate: true}), config) : action.action === 'delete' && config.i18n ? withTranslationDelete(action, config) : action,
|
|
157
158
|
)
|
|
158
159
|
: // Valeurs par défaut des composants : publier celles de la langue source
|
|
159
160
|
// (anglais en général) propose de retraduire celles des autres langues.
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import {localizeReferences} from './localizeReferences'
|
|
2
|
+
import {syncTranslationRedirects, translationRedirectOptions} from './translationRedirects'
|
|
2
3
|
import type {SanityClient} from 'sanity'
|
|
3
4
|
import type {ResolvedKitConfig} from '../config/types'
|
|
4
5
|
import {TRANSLATION_TODO_TYPE, translationTodoId} from '../schema/translationTodo'
|
|
@@ -139,6 +140,9 @@ export async function createTranslatedVersion(opts: {
|
|
|
139
140
|
slug = `${base}-${n}`
|
|
140
141
|
doc[slugField] = {_type: 'slug', current: slug}
|
|
141
142
|
}
|
|
143
|
+
// Slug non traduit (titre resté dans la langue source) : marqué « To translate »
|
|
144
|
+
// avec le titre, la règle d'or veut un slug dans la langue de la version.
|
|
145
|
+
if (slugField && remaining.includes(pageType?.titleField ?? 'title') && !remaining.includes(slugField)) remaining = [...remaining, slugField]
|
|
142
146
|
const published = ai && !remaining.length && !aiError
|
|
143
147
|
await client.createOrReplace({...doc, _id: published ? id : `drafts.${id}`, _type: type} as {_id: string; _type: string})
|
|
144
148
|
if (remaining.length)
|
|
@@ -152,6 +156,9 @@ export async function createTranslatedVersion(opts: {
|
|
|
152
156
|
})
|
|
153
157
|
await recordTrace(client, id, written, {sourceId, sourceLanguage})
|
|
154
158
|
await linkTranslations(client, sourceId, sourceLanguage, type, [{language, id}])
|
|
159
|
+
// Version publiée : « slug d'origine dans cette langue » redirige vers elle.
|
|
160
|
+
const redirects = published ? translationRedirectOptions(config) : null
|
|
161
|
+
if (redirects) await syncTranslationRedirects(client, redirects, [sourceId]).catch(() => {})
|
|
155
162
|
return {id, published, aiError}
|
|
156
163
|
}
|
|
157
164
|
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import type {SanityClient} from 'sanity'
|
|
2
|
+
import {toPath} from './paths'
|
|
3
|
+
|
|
4
|
+
type Obj = Record<string, unknown>
|
|
5
|
+
|
|
6
|
+
export interface TranslationRedirectOptions {
|
|
7
|
+
/** Champ de langue des documents. */
|
|
8
|
+
field?: string
|
|
9
|
+
/** Langue principale : son slug est le slug « d'origine ». */
|
|
10
|
+
defaultLocale: string
|
|
11
|
+
/** Types qui ont une page par document (préfixe d'adresse du registre). */
|
|
12
|
+
types: {type: string; pathPrefix?: string | null; slugField?: string}[]
|
|
13
|
+
/** Type de document des redirections (champs from, to, permanent, note). */
|
|
14
|
+
redirectType?: string
|
|
15
|
+
/** `false` : simulation, rien n'est écrit. Défaut : true. */
|
|
16
|
+
apply?: boolean
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface TranslationRedirect {
|
|
20
|
+
id: string
|
|
21
|
+
from: string
|
|
22
|
+
to: string
|
|
23
|
+
note: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Identifiant stable de la redirection d'une version (mise à jour, jamais dupliquée). */
|
|
27
|
+
export const translationRedirectId = (versionId: string) => `redirect-translation-${versionId.replace(/^drafts\./, '').replace(/[^A-Za-z0-9_-]/g, '-')}`
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* RÈGLE D'OR DU MULTILINGUE, adresses : chaque version a un slug dans SA langue, et
|
|
31
|
+
* l'adresse « slug d'origine dans cette langue » redirige vers elle (une page
|
|
32
|
+
* /rouge, traduite /en/red : /en/rouge redirige vers /en/red). Enregistré comme
|
|
33
|
+
* une vraie redirection (visible dans le Studio, « Redirects »), une par version,
|
|
34
|
+
* mise à jour si un slug change. Rien quand le slug est le même, ni quand l'adresse
|
|
35
|
+
* d'origine est déjà une vraie page de cette langue.
|
|
36
|
+
*
|
|
37
|
+
* `seeds` : documents dont on traite le groupe de traductions (tous si absent).
|
|
38
|
+
* `override` : valeurs d'une version en cours de publication (pas encore lisibles).
|
|
39
|
+
*/
|
|
40
|
+
export async function syncTranslationRedirects(
|
|
41
|
+
client: SanityClient,
|
|
42
|
+
options: TranslationRedirectOptions,
|
|
43
|
+
seeds?: string[],
|
|
44
|
+
override?: {id: string; slug?: string | null; language?: string | null},
|
|
45
|
+
): Promise<TranslationRedirect[]> {
|
|
46
|
+
const field = options.field ?? 'language'
|
|
47
|
+
const redirectType = options.redirectType ?? 'redirect'
|
|
48
|
+
const byType = new Map(options.types.map((t) => [t.type, t]))
|
|
49
|
+
const c = client.withConfig({perspective: 'raw'})
|
|
50
|
+
const types = [...byType.keys()]
|
|
51
|
+
if (!types.length) return []
|
|
52
|
+
|
|
53
|
+
// Groupes de traductions des types à pages (publiés).
|
|
54
|
+
const groups = await c.fetch<{translations?: {language?: string; _key?: string; value?: {_ref?: string}}[]}[]>(
|
|
55
|
+
seeds?.length
|
|
56
|
+
? `*[_type == "translation.metadata" && count(translations[value._ref in $seeds]) > 0]{translations}`
|
|
57
|
+
: `*[_type == "translation.metadata" && count(schemaTypes[@ in $types]) > 0]{translations}`,
|
|
58
|
+
{seeds: (seeds ?? []).map((s) => s.replace(/^drafts\./, '')), types},
|
|
59
|
+
)
|
|
60
|
+
const ids = [...new Set(groups.flatMap((g) => (g.translations ?? []).map((t) => t.value?._ref).filter((x): x is string => !!x)))]
|
|
61
|
+
if (!ids.length) return []
|
|
62
|
+
const docs = await c.fetch<Obj[]>(`*[_id in $ids]{_id, _type, ${field}, "slugs": {"slug": slug.current}, title}`, {ids})
|
|
63
|
+
const byId = new Map(docs.map((d) => [String(d._id), d]))
|
|
64
|
+
const slugOf = (d: Obj | undefined) => {
|
|
65
|
+
if (!d) return null
|
|
66
|
+
if (override && d._id === override.id && override.slug !== undefined) return override.slug
|
|
67
|
+
return ((d.slugs as Obj | undefined)?.slug as string | undefined) ?? null
|
|
68
|
+
}
|
|
69
|
+
const langOf = (d: Obj | undefined) => (override && d?._id === override.id && override.language ? override.language : (d?.[field] as string | undefined))
|
|
70
|
+
|
|
71
|
+
const wanted: TranslationRedirect[] = []
|
|
72
|
+
const stale: string[] = []
|
|
73
|
+
for (const g of groups) {
|
|
74
|
+
const versions = (g.translations ?? []).map((t) => byId.get(t.value?._ref ?? '')).filter((d): d is Obj => !!d)
|
|
75
|
+
const master = versions.find((d) => langOf(d) === options.defaultLocale)
|
|
76
|
+
const masterSlug = slugOf(master)
|
|
77
|
+
for (const v of versions) {
|
|
78
|
+
if (v === master) continue
|
|
79
|
+
const id = translationRedirectId(String(v._id))
|
|
80
|
+
const t = byType.get(String(v._type))
|
|
81
|
+
const language = langOf(v)
|
|
82
|
+
const slug = slugOf(v)
|
|
83
|
+
const from = t && masterSlug && language ? toPath({slug: masterSlug, pathPrefix: t.pathPrefix, locale: language}, {field, defaultLocale: options.defaultLocale, locales: [], defaultsSourceLocale: options.defaultLocale}) : null
|
|
84
|
+
const to = t && slug && language ? toPath({slug, pathPrefix: t.pathPrefix, locale: language}, {field, defaultLocale: options.defaultLocale, locales: [], defaultsSourceLocale: options.defaultLocale}) : null
|
|
85
|
+
if (!from || !to || from === to) {
|
|
86
|
+
stale.push(id)
|
|
87
|
+
continue
|
|
88
|
+
}
|
|
89
|
+
// L'adresse d'origine est une vraie page de cette langue : pas de redirection.
|
|
90
|
+
const taken = await c.fetch<number>(
|
|
91
|
+
`count(*[_type == $type && ${field} == $language && slug.current == $slug && !(_id in path("drafts.**")) && _id != $self])`,
|
|
92
|
+
{type: v._type, language, slug: masterSlug, self: v._id},
|
|
93
|
+
)
|
|
94
|
+
if (taken) {
|
|
95
|
+
stale.push(id)
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
wanted.push({id, from, to, note: `Created automatically: ${language?.toUpperCase()} version of "${String(master?.title ?? masterSlug)}" (translated address)`})
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (options.apply !== false) {
|
|
103
|
+
const tx = c.transaction()
|
|
104
|
+
// Une redirection qui partirait d'une adresse devenue une vraie page est retirée.
|
|
105
|
+
const targets = wanted.map((w) => w.to)
|
|
106
|
+
const loops = targets.length ? await c.fetch<string[]>(`*[_type == $redirectType && from in $targets]._id`, {redirectType, targets}) : []
|
|
107
|
+
for (const id of loops) if (!wanted.some((w) => w.id === id)) tx.delete(id)
|
|
108
|
+
for (const w of wanted) tx.createOrReplace({_id: w.id, _type: redirectType, from: w.from, to: w.to, permanent: true, note: w.note})
|
|
109
|
+
for (const id of stale) tx.delete(id)
|
|
110
|
+
await tx.commit({visibility: 'async'})
|
|
111
|
+
}
|
|
112
|
+
return wanted
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Options de `syncTranslationRedirects` tirées de la configuration du kit (types à pages avec slug). */
|
|
116
|
+
export function translationRedirectOptions(config: {
|
|
117
|
+
i18n: {field: string; defaultLocale: string} | null
|
|
118
|
+
pageTypes: {type: string; slugField: string | null; path: string | null; pathPrefix: string | null}[]
|
|
119
|
+
}): TranslationRedirectOptions | null {
|
|
120
|
+
if (!config.i18n) return null
|
|
121
|
+
const types = config.pageTypes.filter((t) => t.slugField && !t.path).map((t) => ({type: t.type, pathPrefix: t.pathPrefix, slugField: t.slugField ?? 'slug'}))
|
|
122
|
+
return types.length ? {field: config.i18n.field, defaultLocale: config.i18n.defaultLocale, types} : null
|
|
123
|
+
}
|
package/src/schema/index.ts
CHANGED
|
@@ -21,3 +21,4 @@ export {withNcfFormTabs, formTabOf} from './formTabs'
|
|
|
21
21
|
|
|
22
22
|
export {withSameLanguageReferences} from './sameLanguageReferences'
|
|
23
23
|
export {fixCrossLanguageReferences, type CrossLanguageReport} from '../lib/fixCrossLanguageReferences'
|
|
24
|
+
export {syncTranslationRedirects, translationRedirectId, type TranslationRedirectOptions, type TranslationRedirect} from '../lib/translationRedirects'
|
package/src/version.ts
CHANGED
|
@@ -1,263 +0,0 @@
|
|
|
1
|
-
import { defineField, defineType } from "sanity";
|
|
2
|
-
const DEFAULT_PAGE_BUILDER_FIELD = "sections", DEFAULT_SLUG_FIELD = "slug", DEFAULT_TITLE_FIELD = "title", DEFAULT_NOINDEX_FIELDS = ["seo.noindex", "noindex"], DEFAULT_I18N = {
|
|
3
|
-
field: "language",
|
|
4
|
-
defaultLocale: "fr",
|
|
5
|
-
locales: []
|
|
6
|
-
}, DEFAULT_COMPONENT_PREVIEW = {
|
|
7
|
-
provider: "designSystemPage",
|
|
8
|
-
path: "/design-system",
|
|
9
|
-
anchor: "{name}",
|
|
10
|
-
thumbnail: "/sections/{name}.png",
|
|
11
|
-
defaultsType: "componentDefaults",
|
|
12
|
-
live: "/design-system/composant?type={name}"
|
|
13
|
-
}, DEFAULT_TOOLS = {
|
|
14
|
-
pages: !0,
|
|
15
|
-
components: !0,
|
|
16
|
-
history: !0,
|
|
17
|
-
designSystem: !0
|
|
18
|
-
}, DEFAULT_TOOLBAR_MORE = [
|
|
19
|
-
"vision",
|
|
20
|
-
"releases",
|
|
21
|
-
"schedules"
|
|
22
|
-
], DEFAULT_BOARD_TAGS = [
|
|
23
|
-
{
|
|
24
|
-
id: "en-cours",
|
|
25
|
-
label: "In progress",
|
|
26
|
-
color: "#f5a623"
|
|
27
|
-
},
|
|
28
|
-
{
|
|
29
|
-
id: "fait",
|
|
30
|
-
label: "Done",
|
|
31
|
-
color: "#43d675"
|
|
32
|
-
},
|
|
33
|
-
{
|
|
34
|
-
id: "a-relire",
|
|
35
|
-
label: "To review",
|
|
36
|
-
color: "#2276fc"
|
|
37
|
-
},
|
|
38
|
-
{
|
|
39
|
-
id: "a-refondre",
|
|
40
|
-
label: "To rework",
|
|
41
|
-
color: "#f03e3e"
|
|
42
|
-
}
|
|
43
|
-
], DEFAULT_INTERNAL_FIELDS = [
|
|
44
|
-
{
|
|
45
|
-
id: "owner",
|
|
46
|
-
label: "Owner",
|
|
47
|
-
type: "text"
|
|
48
|
-
},
|
|
49
|
-
{
|
|
50
|
-
id: "audience",
|
|
51
|
-
label: "Audience",
|
|
52
|
-
type: "text"
|
|
53
|
-
},
|
|
54
|
-
{
|
|
55
|
-
id: "role",
|
|
56
|
-
label: "Page role",
|
|
57
|
-
type: "text"
|
|
58
|
-
}
|
|
59
|
-
], DEFAULT_SERVICE_ENDPOINT = "https://dkoxgivytgsmvqmjvmjt.supabase.co/functions/v1", DEFAULT_COMPONENT_DEFAULTS_TYPE = "componentDefaults";
|
|
60
|
-
/** Nom du champ d'un composant dans le document des valeurs par défaut : `section.cta` -> `cta`. */
|
|
61
|
-
function defaultsFieldName(type, namespace = "section.") {
|
|
62
|
-
return type.startsWith(namespace) ? type.slice(namespace.length) : type;
|
|
63
|
-
}
|
|
64
|
-
const relax = (f) => {
|
|
65
|
-
let { validation: _v, initialValue: _i, ...rest } = f;
|
|
66
|
-
return {
|
|
67
|
-
...rest,
|
|
68
|
-
...rest.fields ? { fields: rest.fields.map(relax) } : {},
|
|
69
|
-
...rest.of ? { of: rest.of.map(relax) } : {}
|
|
70
|
-
};
|
|
71
|
-
};
|
|
72
|
-
/** Document « Composants : valeurs par défaut », généré depuis les sections. */
|
|
73
|
-
function defineComponentDefaults(options) {
|
|
74
|
-
let { name = DEFAULT_COMPONENT_DEFAULTS_TYPE, title = "🧩 Components: default values", namespace = "section." } = options;
|
|
75
|
-
return defineType({
|
|
76
|
-
name,
|
|
77
|
-
title,
|
|
78
|
-
type: "document",
|
|
79
|
-
description: "Values applied to every instance of a component whose field is empty. A field filled in an instance takes precedence (override).",
|
|
80
|
-
fields: options.sections.map((t) => defineField({
|
|
81
|
-
name: defaultsFieldName(t.name, namespace),
|
|
82
|
-
title: t.title || t.name,
|
|
83
|
-
type: "object",
|
|
84
|
-
description: "Default values of this component. Empty = design system value.",
|
|
85
|
-
options: {
|
|
86
|
-
collapsible: !0,
|
|
87
|
-
collapsed: !0
|
|
88
|
-
},
|
|
89
|
-
fields: t.fields.map(relax)
|
|
90
|
-
})),
|
|
91
|
-
preview: { prepare: () => ({ title: title.replace(/^\S+\s/, "") }) }
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
const isEmpty = (v) => v == null || v === "" || Array.isArray(v) && v.length === 0;
|
|
95
|
-
/**
|
|
96
|
-
* Règle « obligatoire SAUF si le composant a une valeur par défaut » pour un autre
|
|
97
|
-
* type de document des valeurs par défaut ou un autre espace de noms.
|
|
98
|
-
* `validation: requiredUnlessDefaultFor({type: 'mesDefauts'})`
|
|
99
|
-
*/
|
|
100
|
-
function requiredUnlessDefaultFor(options = {}) {
|
|
101
|
-
let { type: defaultsType = DEFAULT_COMPONENT_DEFAULTS_TYPE, namespace = "section." } = options;
|
|
102
|
-
return (rule) => rule.custom(async (value, context) => {
|
|
103
|
-
if (!isEmpty(value)) return !0;
|
|
104
|
-
let type = context.parent?._type, field = context.path?.[context.path.length - 1], name = type ? defaultsFieldName(type, namespace) : "";
|
|
105
|
-
if (!type?.startsWith(namespace) || typeof field != "string" || !/^\w+$/.test(name) || !/^\w+$/.test(field)) return "Required.";
|
|
106
|
-
let language = context.document?.language ?? null, inherited = await context.getClient({ apiVersion: "2024-10-01" }).fetch(`*[_type == $defaultsType && !(_id in path("drafts.**")) && ($language == null || language == $language)][0].${name}.${field}`, {
|
|
107
|
-
defaultsType,
|
|
108
|
-
language
|
|
109
|
-
});
|
|
110
|
-
return !isEmpty(inherited) || "Required (or set it in Components > default values).";
|
|
111
|
-
});
|
|
112
|
-
}
|
|
113
|
-
/**
|
|
114
|
-
* Champ de section obligatoire, SAUF si le composant a une valeur par défaut
|
|
115
|
-
* pour ce champ (elle s'affichera). Tout type de champ.
|
|
116
|
-
* `validation: requiredUnlessDefault`
|
|
117
|
-
*/
|
|
118
|
-
const requiredUnlessDefault = requiredUnlessDefaultFor();
|
|
119
|
-
/**
|
|
120
|
-
* Presentation : la page qui rend un composant seul (par défaut
|
|
121
|
-
* `/design-system/composant`) a pour document principal les valeurs par défaut.
|
|
122
|
-
* Rendu réel et réglages côte à côte, en direct.
|
|
123
|
-
* `presentationTool({resolve: {mainDocuments: defineDocuments([componentDefaultsMainDocument({language: 'fr'})])}})`
|
|
124
|
-
*/
|
|
125
|
-
function componentDefaultsMainDocument(options = {}) {
|
|
126
|
-
let { language, route = "/design-system/composant", type = DEFAULT_COMPONENT_DEFAULTS_TYPE } = options, safeLang = language && /^[a-z]{2}(-[A-Za-z]{2})?$/.test(language) ? language : null;
|
|
127
|
-
return {
|
|
128
|
-
route,
|
|
129
|
-
filter: `_type == "${type}"${safeLang ? ` && language == "${safeLang}"` : ""}`
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
|
-
/**
|
|
133
|
-
* Presentation : les pages du design system ont pour document principal les valeurs
|
|
134
|
-
* par défaut des composants. `/design-system` (toute la bibliothèque) et
|
|
135
|
-
* `/design-system/composant` (un composant seul) : cliquer un composant ouvre ses
|
|
136
|
-
* réglages globaux, et un style changé change le composant partout où il n'est
|
|
137
|
-
* pas surchargé.
|
|
138
|
-
* `presentationTool({resolve: {mainDocuments: defineDocuments(componentDefaultsMainDocuments({language: 'fr'}))}})`
|
|
139
|
-
*/
|
|
140
|
-
function componentDefaultsMainDocuments(options = {}) {
|
|
141
|
-
let { routes = ["/design-system/composant", "/design-system"], ...rest } = options;
|
|
142
|
-
return routes.map((route) => componentDefaultsMainDocument({
|
|
143
|
-
...rest,
|
|
144
|
-
route
|
|
145
|
-
}));
|
|
146
|
-
}
|
|
147
|
-
const isObj$1 = (v) => {
|
|
148
|
-
if (!v || typeof v != "object" || Array.isArray(v) || "$$typeof" in v) return !1;
|
|
149
|
-
let proto = Object.getPrototypeOf(v);
|
|
150
|
-
return proto === Object.prototype || proto === null;
|
|
151
|
-
};
|
|
152
|
-
/**
|
|
153
|
-
* RÈGLE D'OR DU MULTILINGUE : une référence ne propose que des documents de la
|
|
154
|
-
* MÊME langue que le document en cours (un article EN ne voit que les catégories EN,
|
|
155
|
-
* une page FR que les pages FR). Les documents sans langue (logos, régions, assets…)
|
|
156
|
-
* restent proposés. Un document commun à toutes les langues (Navigation…) vise la
|
|
157
|
-
* langue principale.
|
|
158
|
-
*
|
|
159
|
-
* Pose ce filtre sur TOUS les champs de référence des types donnés (champs, listes,
|
|
160
|
-
* objets imbriqués, annotations du texte riche), combiné avec un filtre déjà présent.
|
|
161
|
-
* À appliquer aux types du projet :
|
|
162
|
-
*
|
|
163
|
-
* ```ts
|
|
164
|
-
* schema: {types: withSameLanguageReferences(schemaTypes, ncfOptions)}
|
|
165
|
-
* ```
|
|
166
|
-
*/
|
|
167
|
-
function withSameLanguageReferences(types, options) {
|
|
168
|
-
let i18n = options.i18n;
|
|
169
|
-
if (!i18n) return types;
|
|
170
|
-
let field = i18n.field ?? "language", fallback = i18n.defaultLocale ?? i18n.locales?.[0], condition = `(!defined(${field}) || ${field} == $ncfLanguage)`, languageOf = (document) => typeof document?.[field] == "string" && document[field] || fallback, wrap = (opts) => {
|
|
171
|
-
let previous = opts?.filter, previousParams = opts?.filterParams ?? {}, filter = async (context) => {
|
|
172
|
-
let base = typeof previous == "function" ? await previous(context) ?? {} : typeof previous == "string" ? {
|
|
173
|
-
filter: previous,
|
|
174
|
-
params: previousParams
|
|
175
|
-
} : {};
|
|
176
|
-
return {
|
|
177
|
-
filter: base.filter ? `(${base.filter}) && ${condition}` : condition,
|
|
178
|
-
params: {
|
|
179
|
-
...base.params ?? {},
|
|
180
|
-
ncfLanguage: languageOf(context.document)
|
|
181
|
-
}
|
|
182
|
-
};
|
|
183
|
-
}, { filterParams: _ignored, ...rest } = opts ?? {};
|
|
184
|
-
return {
|
|
185
|
-
...rest,
|
|
186
|
-
filter
|
|
187
|
-
};
|
|
188
|
-
}, visit = (node) => {
|
|
189
|
-
if (Array.isArray(node)) return node.map(visit);
|
|
190
|
-
if (!isObj$1(node)) return node;
|
|
191
|
-
let out = {};
|
|
192
|
-
for (let [key, value] of Object.entries(node)) out[key] = key === "options" || key === "initialValue" || key === "validation" ? value : visit(value);
|
|
193
|
-
return node.type === "reference" && Array.isArray(node.to) && (out.options = wrap(node.options)), out;
|
|
194
|
-
};
|
|
195
|
-
return types.map((t) => visit(t));
|
|
196
|
-
}
|
|
197
|
-
const isObj = (v) => !!v && typeof v == "object" && !Array.isArray(v), bare = (id) => id.replace(/^drafts\./, "");
|
|
198
|
-
/** Références d'une valeur, avec leur chemin de patch (`a.b[_key=="x"].c`). */
|
|
199
|
-
function refs(value, path, out) {
|
|
200
|
-
if (Array.isArray(value)) {
|
|
201
|
-
value.forEach((item, i) => refs(item, `${path}[${isObj(item) && typeof item._key == "string" ? `_key=="${item._key}"` : i}]`, out));
|
|
202
|
-
return;
|
|
203
|
-
}
|
|
204
|
-
if (isObj(value)) {
|
|
205
|
-
typeof value._ref == "string" && !/^(image|file)-/.test(value._ref) && out.push({
|
|
206
|
-
path: `${path}._ref`,
|
|
207
|
-
ref: value._ref
|
|
208
|
-
});
|
|
209
|
-
for (let [k, v] of Object.entries(value)) k.startsWith("_") || refs(v, path ? `${path}.${k}` : k, out);
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
/**
|
|
213
|
-
* RÈGLE D'OR DU MULTILINGUE, côté données : chaque référence d'un document vise un
|
|
214
|
-
* document de SA langue (document sans langue : la langue principale). Une
|
|
215
|
-
* référence croisée est repointée vers la traduction de la bonne langue (liens de
|
|
216
|
-
* traduction) ; sans traduction, elle est signalée et laissée. Publiés et
|
|
217
|
-
* brouillons. `apply: false` : simulation.
|
|
218
|
-
*
|
|
219
|
-
* ```ts
|
|
220
|
-
* // studio/scripts/references-same-language.ts (sanity exec --with-user-token)
|
|
221
|
-
* const report = await fixCrossLanguageReferences(getCliClient(...), {defaultLocale: 'fr', apply})
|
|
222
|
-
* ```
|
|
223
|
-
*/
|
|
224
|
-
async function fixCrossLanguageReferences(client, options) {
|
|
225
|
-
let field = options.field ?? "language", c = client.withConfig({ perspective: "raw" }), docs = await c.fetch("*[!(_type match \"system.*\") && !(_type match \"sanity.*\") && !(_type match \"ncf.*\") && _type != \"translation.metadata\"]"), language = /* @__PURE__ */ new Map();
|
|
226
|
-
for (let d of docs) typeof d[field] == "string" && language.set(bare(String(d._id)), String(d[field]));
|
|
227
|
-
let metas = await c.fetch("*[_type == \"translation.metadata\"]{translations}"), equivalent = /* @__PURE__ */ new Map();
|
|
228
|
-
for (let m of metas) {
|
|
229
|
-
let group = /* @__PURE__ */ new Map();
|
|
230
|
-
for (let t of m.translations ?? []) t.value?._ref && group.set(t.language ?? t._key ?? "", t.value._ref);
|
|
231
|
-
for (let id of group.values()) equivalent.set(id, group);
|
|
232
|
-
}
|
|
233
|
-
let report = {
|
|
234
|
-
fixed: [],
|
|
235
|
-
missing: []
|
|
236
|
-
};
|
|
237
|
-
for (let d of docs) {
|
|
238
|
-
let own = typeof d[field] == "string" ? String(d[field]) : options.defaultLocale, found = [];
|
|
239
|
-
for (let [k, v] of Object.entries(d)) k.startsWith("_") || refs(v, k, found);
|
|
240
|
-
let set = {};
|
|
241
|
-
for (let { path, ref } of found) {
|
|
242
|
-
let target = language.get(bare(ref));
|
|
243
|
-
if (!target || target === own) continue;
|
|
244
|
-
let to = equivalent.get(bare(ref))?.get(own);
|
|
245
|
-
to ? (set[path] = to, report.fixed.push({
|
|
246
|
-
documentId: String(d._id),
|
|
247
|
-
path,
|
|
248
|
-
from: ref,
|
|
249
|
-
to
|
|
250
|
-
})) : report.missing.push({
|
|
251
|
-
documentId: String(d._id),
|
|
252
|
-
path,
|
|
253
|
-
ref,
|
|
254
|
-
language: own
|
|
255
|
-
});
|
|
256
|
-
}
|
|
257
|
-
options.apply && Object.keys(set).length && await c.patch(String(d._id)).ifRevisionId(String(d._rev)).set(set).commit({ visibility: "async" });
|
|
258
|
-
}
|
|
259
|
-
return report;
|
|
260
|
-
}
|
|
261
|
-
export { DEFAULT_SLUG_FIELD as _, componentDefaultsMainDocuments as a, DEFAULT_TOOLS as b, requiredUnlessDefault as c, DEFAULT_COMPONENT_PREVIEW as d, DEFAULT_I18N as f, DEFAULT_SERVICE_ENDPOINT as g, DEFAULT_PAGE_BUILDER_FIELD as h, componentDefaultsMainDocument as i, requiredUnlessDefaultFor as l, DEFAULT_NOINDEX_FIELDS as m, withSameLanguageReferences as n, defaultsFieldName as o, DEFAULT_INTERNAL_FIELDS as p, DEFAULT_COMPONENT_DEFAULTS_TYPE as r, defineComponentDefaults as s, fixCrossLanguageReferences as t, DEFAULT_BOARD_TAGS as u, DEFAULT_TITLE_FIELD as v, DEFAULT_TOOLBAR_MORE as y };
|
|
262
|
-
|
|
263
|
-
//# sourceMappingURL=fixCrossLanguageReferences-CagQ_Vvk.js.map
|