@nocode-factory/sanity-kit 2.37.1 → 2.39.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/bin/ncf-kit.mjs +11 -0
- package/dist/fixCrossLanguageReferences-DIdE0jOt.js +521 -0
- package/dist/fixCrossLanguageReferences-DIdE0jOt.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +70 -180
- 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/config/defaults.ts +4 -2
- package/src/config/resolve.ts +14 -8
- package/src/config/validate.ts +8 -0
- package/src/index.ts +2 -1
- package/src/lib/grouping.ts +1 -1
- package/src/lib/pages.ts +6 -6
- package/src/lib/sectionsMap.ts +1 -1
- package/src/lib/translateDocument.ts +7 -0
- package/src/lib/translationRedirects.ts +123 -0
- package/src/schema/index.ts +1 -0
- package/src/tools/components/ComponentsTool.tsx +1 -1
- 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-DIdE0jOt.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/config/defaults.ts
CHANGED
|
@@ -18,9 +18,11 @@ export const DEFAULT_BLOCK_NAMESPACE = ''
|
|
|
18
18
|
*/
|
|
19
19
|
export const DEFAULT_NOINDEX_FIELDS = ['seo.noindex', 'noindex']
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
// Aucune langue par défaut : la langue principale (master) vient TOUJOURS du projet
|
|
22
|
+
// (`defaultLocale`, sinon la première de `locales`). Un site peut avoir le français,
|
|
23
|
+
// l'anglais ou toute autre langue comme master.
|
|
24
|
+
export const DEFAULT_I18N: Omit<Required<NcfI18nConfig>, 'defaultsSourceLocale' | 'defaultLocale'> = {
|
|
22
25
|
field: 'language',
|
|
23
|
-
defaultLocale: 'fr',
|
|
24
26
|
locales: [],
|
|
25
27
|
}
|
|
26
28
|
|
package/src/config/resolve.ts
CHANGED
|
@@ -75,14 +75,20 @@ export function resolveConfig(input: NcfKitConfig): ResolvedKitConfig {
|
|
|
75
75
|
const i18n =
|
|
76
76
|
input.i18n === false || input.i18n === undefined
|
|
77
77
|
? null
|
|
78
|
-
: {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
78
|
+
: (() => {
|
|
79
|
+
const locales = (input.i18n.locales ?? DEFAULT_I18N.locales).map((l) => l.trim()).filter(Boolean)
|
|
80
|
+
// Master : `defaultLocale`, sinon la première langue. Jamais une langue écrite
|
|
81
|
+
// dans le kit (absente : signalé par validateConfig).
|
|
82
|
+
const defaultLocale = input.i18n.defaultLocale?.trim() || locales[0] || ''
|
|
83
|
+
return {
|
|
84
|
+
field: input.i18n.field?.trim() || DEFAULT_I18N.field,
|
|
85
|
+
defaultLocale,
|
|
86
|
+
locales,
|
|
87
|
+
// Valeurs par défaut des composants : écrites dans la langue master,
|
|
88
|
+
// traduites vers les autres (sauf choix explicite du projet).
|
|
89
|
+
defaultsSourceLocale: input.i18n.defaultsSourceLocale?.trim() || defaultLocale,
|
|
90
|
+
}
|
|
91
|
+
})()
|
|
86
92
|
|
|
87
93
|
return {
|
|
88
94
|
pageTypes,
|
package/src/config/validate.ts
CHANGED
|
@@ -21,6 +21,14 @@ export function validateConfig(config: ResolvedKitConfig): ConfigIssue[] {
|
|
|
21
21
|
const warn = (path: string, message: string, tools?: NcfToolName[]) =>
|
|
22
22
|
issues.push({level: 'warning', path, message, ...(tools ? {tools} : {})})
|
|
23
23
|
|
|
24
|
+
/* --- i18n --- */
|
|
25
|
+
if (config.i18n && !config.i18n.defaultLocale) {
|
|
26
|
+
error(
|
|
27
|
+
'i18n.defaultLocale',
|
|
28
|
+
'Multilingual site without a main language: set `i18n.defaultLocale` (or `i18n.locales`, the first one is the main language). The kit never assumes a language.',
|
|
29
|
+
)
|
|
30
|
+
}
|
|
31
|
+
|
|
24
32
|
/* --- pageTypes --- */
|
|
25
33
|
if (config.pageTypes.length === 0) {
|
|
26
34
|
error(
|
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.
|
package/src/lib/grouping.ts
CHANGED
|
@@ -103,7 +103,7 @@ export function groupPageRows(
|
|
|
103
103
|
seen.add(value)
|
|
104
104
|
}
|
|
105
105
|
}
|
|
106
|
-
for (const value of [...buckets.keys()].sort((a, b) => a.localeCompare(b, '
|
|
106
|
+
for (const value of [...buckets.keys()].sort((a, b) => a.localeCompare(b, undefined, {sensitivity: 'base'}))) {
|
|
107
107
|
if (value && !seen.has(value)) ordered.push(value)
|
|
108
108
|
}
|
|
109
109
|
if (buckets.has('')) ordered.push('')
|
package/src/lib/pages.ts
CHANGED
|
@@ -129,21 +129,21 @@ const compare = (a: PageRow, b: PageRow, key: SortKey, options: SortOptions): nu
|
|
|
129
129
|
// Un type hors liste passe après ceux qui y sont.
|
|
130
130
|
return index === -1 ? order.length : index
|
|
131
131
|
}
|
|
132
|
-
return rank(a) - rank(b) || a.title.localeCompare(b.title, '
|
|
132
|
+
return rank(a) - rank(b) || a.title.localeCompare(b.title, undefined, {sensitivity: 'base'})
|
|
133
133
|
}
|
|
134
134
|
case 'title':
|
|
135
|
-
return a.title.localeCompare(b.title, '
|
|
135
|
+
return a.title.localeCompare(b.title, undefined, {sensitivity: 'base'})
|
|
136
136
|
case 'type':
|
|
137
|
-
return a.type.localeCompare(b.type, '
|
|
137
|
+
return a.type.localeCompare(b.type, undefined, {sensitivity: 'base'}) || a.title.localeCompare(b.title, undefined, {sensitivity: 'base'})
|
|
138
138
|
case 'path':
|
|
139
139
|
// Les pages sans chemin en dernier : elles n'ont pas de place dans l'arbre.
|
|
140
140
|
if (a.path === null || b.path === null) {
|
|
141
141
|
return Number(a.path === null) - Number(b.path === null)
|
|
142
142
|
}
|
|
143
|
-
return a.path.localeCompare(b.path, '
|
|
143
|
+
return a.path.localeCompare(b.path, undefined, {sensitivity: 'base'})
|
|
144
144
|
case 'status':
|
|
145
145
|
return STATUS_ORDER[a.status] - STATUS_ORDER[b.status] ||
|
|
146
|
-
a.title.localeCompare(b.title, '
|
|
146
|
+
a.title.localeCompare(b.title, undefined, {sensitivity: 'base'})
|
|
147
147
|
case 'updatedAt':
|
|
148
148
|
// Jamais modifié = le plus ancien possible.
|
|
149
149
|
return (a.updatedAt ?? '').localeCompare(b.updatedAt ?? '')
|
|
@@ -174,7 +174,7 @@ export interface PageFilters {
|
|
|
174
174
|
|
|
175
175
|
const normalize = (value: string): string =>
|
|
176
176
|
value
|
|
177
|
-
.toLocaleLowerCase(
|
|
177
|
+
.toLocaleLowerCase()
|
|
178
178
|
.normalize('NFD')
|
|
179
179
|
.replace(/\p{Diacritic}/gu, '')
|
|
180
180
|
|
package/src/lib/sectionsMap.ts
CHANGED
|
@@ -34,7 +34,7 @@ type Entry = {block: BlockTypeInfo; occurrence: BlockOccurrence}
|
|
|
34
34
|
function compareBy(order: SectionOrder): (a: Entry, b: Entry) => number {
|
|
35
35
|
if (order === 'usage') return (a, b) => b.occurrence.count - a.occurrence.count
|
|
36
36
|
if (order === 'unused') return (a, b) => a.occurrence.count - b.occurrence.count
|
|
37
|
-
return (a, b) => a.block.name.localeCompare(b.block.name, '
|
|
37
|
+
return (a, b) => a.block.name.localeCompare(b.block.name, undefined, {sensitivity: 'base'})
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
/**
|
|
@@ -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'
|
|
@@ -40,7 +40,7 @@ export function ComponentsTool() {
|
|
|
40
40
|
|
|
41
41
|
if (order === 'schema') return rows
|
|
42
42
|
if (order === 'type') {
|
|
43
|
-
return [...rows].sort((a, b) => a.block.name.localeCompare(b.block.name, '
|
|
43
|
+
return [...rows].sort((a, b) => a.block.name.localeCompare(b.block.name, undefined, {sensitivity: 'base'}))
|
|
44
44
|
}
|
|
45
45
|
if (order === 'unused') {
|
|
46
46
|
return [...rows].sort((a, b) => a.occurrence.count - b.occurrence.count)
|
package/src/version.ts
CHANGED