@sanity/document-internationalization 2.1.2 → 3.0.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.
Files changed (34) hide show
  1. package/dist/index.d.mts +90 -0
  2. package/dist/index.d.ts +3 -1
  3. package/dist/index.esm.js +764 -1167
  4. package/dist/index.esm.js.map +1 -1
  5. package/dist/index.js +749 -1177
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +1043 -0
  8. package/dist/index.mjs.map +1 -0
  9. package/package.json +28 -32
  10. package/src/actions/DeleteMetadataAction.tsx +5 -5
  11. package/src/actions/DeleteTranslationAction.tsx +6 -2
  12. package/src/badges/index.tsx +1 -1
  13. package/src/components/BulkPublish/DocumentCheck.tsx +1 -1
  14. package/src/components/BulkPublish/InfoIcon.tsx +4 -3
  15. package/src/components/BulkPublish/index.tsx +3 -2
  16. package/src/components/ConstrainedBox.tsx +1 -1
  17. package/src/components/DeleteTranslationDialog/index.tsx +1 -1
  18. package/src/components/DeleteTranslationDialog/separateReferences.ts +1 -1
  19. package/src/components/DocumentInternationalizationContext.tsx +2 -2
  20. package/src/components/DocumentInternationalizationMenu.tsx +3 -2
  21. package/src/components/LanguageManage.tsx +1 -0
  22. package/src/components/LanguageOption.tsx +4 -2
  23. package/src/components/LanguagePatch.tsx +2 -2
  24. package/src/components/OptimisticallyStrengthen/ReferencePatcher.tsx +2 -2
  25. package/src/components/OptimisticallyStrengthen/index.tsx +1 -1
  26. package/src/components/Warning.tsx +1 -1
  27. package/src/constants.ts +1 -1
  28. package/src/hooks/useLanguageMetadata.tsx +1 -1
  29. package/src/hooks/useOpenInNewPane.tsx +2 -2
  30. package/src/plugin.tsx +4 -4
  31. package/src/schema/translation/metadata.ts +2 -4
  32. package/src/utils/createReference.ts +1 -1
  33. package/src/utils/excludePaths.ts +4 -4
  34. package/dist/index.cjs.mjs +0 -7
package/dist/index.mjs ADDED
@@ -0,0 +1,1043 @@
1
+ import { jsx, jsxs, Fragment } from "react/jsx-runtime";
2
+ import { TrashIcon, CogIcon, SplitVerticalIcon, CheckmarkIcon, AddIcon, EditIcon, TranslateIcon, InfoOutlineIcon } from "@sanity/icons";
3
+ import { Flex, Spinner, Stack, Text, Card, Grid, Button, useToast, Tooltip, Box, Badge, useClickOutside, TextInput, Popover, Inline, Dialog } from "@sanity/ui";
4
+ import { useMemo, useEffect, createContext, useContext, useState, useCallback } from "react";
5
+ import { useSchema, Preview, useClient, useWorkspace, isDocumentSchemaType, pathToString, useEditState, useValidationStatus, TextWithTone, PatchEvent, unset, defineType, defineField, definePlugin, isSanityDocument } from "sanity";
6
+ import { Feedback, useListeningQuery } from "sanity-plugin-utils";
7
+ import { uuid } from "@sanity/uuid";
8
+ import { RouterContext } from "sanity/router";
9
+ import { usePaneRouter, useDocumentPane } from "sanity/structure";
10
+ import { Mutation, extractWithPath } from "@sanity/mutator";
11
+ import { styled } from "styled-components";
12
+ import { internationalizedArray } from "sanity-plugin-internationalized-array";
13
+ function DocumentPreview(props) {
14
+ const schemaType = useSchema().get(props.type);
15
+ return schemaType ? /* @__PURE__ */ jsx(Preview, { value: props.value, schemaType }) : /* @__PURE__ */ jsx(Feedback, { tone: "critical", title: "Schema type not found" });
16
+ }
17
+ const METADATA_SCHEMA_NAME = "translation.metadata", TRANSLATIONS_ARRAY_NAME = "translations", API_VERSION = "2023-05-22", DEFAULT_CONFIG = {
18
+ supportedLanguages: [],
19
+ schemaTypes: [],
20
+ languageField: "language",
21
+ weakReferences: !1,
22
+ bulkPublish: !1,
23
+ metadataFields: [],
24
+ apiVersion: API_VERSION
25
+ };
26
+ function separateReferences(data = []) {
27
+ const translations = [], otherReferences = [];
28
+ return data && data.length > 0 && data.forEach((doc) => {
29
+ doc._type === METADATA_SCHEMA_NAME ? translations.push(doc) : otherReferences.push(doc);
30
+ }), { translations, otherReferences };
31
+ }
32
+ function DeleteTranslationDialog(props) {
33
+ const { doc, documentId, setTranslations } = props, { data, loading } = useListeningQuery(
34
+ "*[references($id)]{_id, _type}",
35
+ { params: { id: documentId }, initialValue: [] }
36
+ ), { translations, otherReferences } = useMemo(
37
+ () => separateReferences(data),
38
+ [data]
39
+ );
40
+ return useEffect(() => {
41
+ setTranslations(translations);
42
+ }, [setTranslations, translations]), loading ? /* @__PURE__ */ jsx(Flex, { padding: 4, align: "center", justify: "center", children: /* @__PURE__ */ jsx(Spinner, {}) }) : /* @__PURE__ */ jsxs(Stack, { space: 4, children: [
43
+ translations && translations.length > 0 ? /* @__PURE__ */ jsx(Text, { children: "This document is a language-specific version which other translations depend on." }) : /* @__PURE__ */ jsx(Text, { children: "This document does not have connected translations." }),
44
+ /* @__PURE__ */ jsx(Card, { border: !0, padding: 3, children: /* @__PURE__ */ jsxs(Stack, { space: 4, children: [
45
+ /* @__PURE__ */ jsx(Text, { size: 1, weight: "semibold", children: translations && translations.length > 0 ? /* @__PURE__ */ jsx(Fragment, { children: "Before this document can be deleted" }) : /* @__PURE__ */ jsx(Fragment, { children: "This document can now be deleted" }) }),
46
+ /* @__PURE__ */ jsx(DocumentPreview, { value: doc, type: doc._type }),
47
+ translations && translations.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
48
+ /* @__PURE__ */ jsx(Card, { borderTop: !0 }),
49
+ /* @__PURE__ */ jsxs(Text, { size: 1, weight: "semibold", children: [
50
+ "The reference in",
51
+ " ",
52
+ translations.length === 1 ? "this translations document" : "these translations documents",
53
+ " ",
54
+ "must be removed"
55
+ ] }),
56
+ translations.map((translation) => /* @__PURE__ */ jsx(
57
+ DocumentPreview,
58
+ {
59
+ value: translation,
60
+ type: translation._type
61
+ },
62
+ translation._id
63
+ ))
64
+ ] }) : null,
65
+ otherReferences && otherReferences.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
66
+ /* @__PURE__ */ jsx(Card, { borderTop: !0 }),
67
+ /* @__PURE__ */ jsxs(Text, { size: 1, weight: "semibold", children: [
68
+ otherReferences.length === 1 ? "There is an additional reference" : "There are additional references",
69
+ " ",
70
+ "to this document"
71
+ ] }),
72
+ otherReferences.map((reference) => /* @__PURE__ */ jsx(
73
+ DocumentPreview,
74
+ {
75
+ value: reference,
76
+ type: reference._type
77
+ },
78
+ reference._id
79
+ ))
80
+ ] }) : null
81
+ ] }) }),
82
+ otherReferences.length === 0 ? /* @__PURE__ */ jsx(Text, { children: "This document has no other references." }) : /* @__PURE__ */ jsx(Text, { children: "You may not be able to delete this document because other documents refer to it." })
83
+ ] });
84
+ }
85
+ function DeleteTranslationFooter(props) {
86
+ const { translations, onClose, onProceed } = props;
87
+ return /* @__PURE__ */ jsxs(Grid, { columns: 2, gap: 2, children: [
88
+ /* @__PURE__ */ jsx(Button, { text: "Cancel", onClick: onClose, mode: "ghost" }),
89
+ /* @__PURE__ */ jsx(
90
+ Button,
91
+ {
92
+ text: translations && translations.length > 0 ? "Unset translation reference" : "Delete document",
93
+ onClick: onProceed,
94
+ tone: "critical"
95
+ }
96
+ )
97
+ ] });
98
+ }
99
+ const isPromise = (promise) => typeof promise == "object" && typeof promise.then == "function", globalCache = [];
100
+ function shallowEqualArrays(arrA, arrB, equal = (a, b) => a === b) {
101
+ if (arrA === arrB)
102
+ return !0;
103
+ if (!arrA || !arrB)
104
+ return !1;
105
+ const len = arrA.length;
106
+ if (arrB.length !== len)
107
+ return !1;
108
+ for (let i = 0; i < len; i++)
109
+ if (!equal(arrA[i], arrB[i]))
110
+ return !1;
111
+ return !0;
112
+ }
113
+ function query$1(fn, keys = null, preload = !1, config = {}) {
114
+ keys === null && (keys = [fn]);
115
+ for (const entry2 of globalCache)
116
+ if (shallowEqualArrays(keys, entry2.keys, entry2.equal)) {
117
+ if (preload)
118
+ return;
119
+ if (Object.prototype.hasOwnProperty.call(entry2, "error"))
120
+ throw entry2.error;
121
+ if (Object.prototype.hasOwnProperty.call(entry2, "response"))
122
+ return config.lifespan && config.lifespan > 0 && (entry2.timeout && clearTimeout(entry2.timeout), entry2.timeout = setTimeout(entry2.remove, config.lifespan)), entry2.response;
123
+ if (!preload)
124
+ throw entry2.promise;
125
+ }
126
+ const entry = {
127
+ keys,
128
+ equal: config.equal,
129
+ remove: () => {
130
+ const index = globalCache.indexOf(entry);
131
+ index !== -1 && globalCache.splice(index, 1);
132
+ },
133
+ promise: (
134
+ // Execute the promise
135
+ (isPromise(fn) ? fn : fn(...keys)).then((response) => {
136
+ entry.response = response, config.lifespan && config.lifespan > 0 && (entry.timeout = setTimeout(entry.remove, config.lifespan));
137
+ }).catch((error) => entry.error = error)
138
+ )
139
+ };
140
+ if (globalCache.push(entry), !preload)
141
+ throw entry.promise;
142
+ }
143
+ const suspend = (fn, keys, config) => query$1(fn, keys, !1, config), DocumentInternationalizationContext = createContext(DEFAULT_CONFIG);
144
+ function useDocumentInternationalizationContext() {
145
+ return useContext(DocumentInternationalizationContext);
146
+ }
147
+ function DocumentInternationalizationProvider(props) {
148
+ const { pluginConfig } = props, client = useClient({ apiVersion: pluginConfig.apiVersion }), workspace = useWorkspace(), supportedLanguages = Array.isArray(pluginConfig.supportedLanguages) ? pluginConfig.supportedLanguages : (
149
+ // eslint-disable-next-line require-await
150
+ suspend(async () => typeof pluginConfig.supportedLanguages == "function" ? pluginConfig.supportedLanguages(client) : pluginConfig.supportedLanguages, [workspace])
151
+ );
152
+ return /* @__PURE__ */ jsx(
153
+ DocumentInternationalizationContext.Provider,
154
+ {
155
+ value: { ...pluginConfig, supportedLanguages },
156
+ children: props.renderDefault(props)
157
+ }
158
+ );
159
+ }
160
+ const DeleteTranslationAction = (props) => {
161
+ const { id: documentId, published, draft } = props, doc = draft || published, { languageField } = useDocumentInternationalizationContext(), [isDialogOpen, setDialogOpen] = useState(!1), [translations, setTranslations] = useState([]), onClose = useCallback(() => setDialogOpen(!1), []), documentLanguage = doc ? doc[languageField] : null, toast = useToast(), client = useClient({ apiVersion: API_VERSION }), onProceed = useCallback(() => {
162
+ const tx = client.transaction();
163
+ let operation = "DELETE";
164
+ documentLanguage && translations.length > 0 ? (operation = "UNSET", translations.forEach((translation) => {
165
+ tx.patch(
166
+ translation._id,
167
+ (patch) => patch.unset([
168
+ `${TRANSLATIONS_ARRAY_NAME}[_key == "${documentLanguage}"]`
169
+ ])
170
+ );
171
+ })) : (tx.delete(documentId), tx.delete(`drafts.${documentId}`)), tx.commit().then(() => {
172
+ operation === "DELETE" && onClose(), toast.push({
173
+ status: "success",
174
+ title: operation === "UNSET" ? "Translation reference unset" : "Document deleted",
175
+ description: operation === "UNSET" ? "The document can now be deleted" : null
176
+ });
177
+ }).catch((err) => {
178
+ toast.push({
179
+ status: "error",
180
+ title: operation === "unset" ? "Failed to unset translation reference" : "Failed to delete document",
181
+ description: err.message
182
+ });
183
+ });
184
+ }, [client, documentLanguage, translations, documentId, onClose, toast]);
185
+ return {
186
+ label: "Delete translation...",
187
+ disabled: !doc || !documentLanguage,
188
+ icon: TrashIcon,
189
+ tone: "critical",
190
+ onHandle: () => {
191
+ setDialogOpen(!0);
192
+ },
193
+ dialog: isDialogOpen && {
194
+ type: "dialog",
195
+ onClose,
196
+ header: "Delete translation",
197
+ content: doc ? /* @__PURE__ */ jsx(
198
+ DeleteTranslationDialog,
199
+ {
200
+ doc,
201
+ documentId,
202
+ setTranslations
203
+ }
204
+ ) : null,
205
+ footer: /* @__PURE__ */ jsx(
206
+ DeleteTranslationFooter,
207
+ {
208
+ onClose,
209
+ onProceed,
210
+ translations
211
+ }
212
+ )
213
+ }
214
+ };
215
+ }, query = `*[_type == $translationSchema && $id in translations[].value._ref]{
216
+ _id,
217
+ _createdAt,
218
+ translations
219
+ }`;
220
+ function useTranslationMetadata(id) {
221
+ const { data, loading, error } = useListeningQuery(query, {
222
+ params: { id, translationSchema: METADATA_SCHEMA_NAME }
223
+ });
224
+ return { data, loading, error };
225
+ }
226
+ function useOpenInNewPane(id, type) {
227
+ const routerContext = useContext(RouterContext), { routerPanesState, groupIndex } = usePaneRouter();
228
+ return useCallback(() => {
229
+ if (!routerContext || !id || !type)
230
+ return;
231
+ if (!routerPanesState.length) {
232
+ routerContext.navigateIntent("edit", { id, type });
233
+ return;
234
+ }
235
+ const panes = [...routerPanesState];
236
+ panes.splice(groupIndex + 1, 0, [
237
+ {
238
+ id,
239
+ params: { type }
240
+ }
241
+ ]);
242
+ const href = routerContext.resolvePathFromState({ panes });
243
+ routerContext.navigateUrl({ path: href });
244
+ }, [id, type, routerContext, routerPanesState, groupIndex]);
245
+ }
246
+ function LanguageManage(props) {
247
+ const { id } = props, open = useOpenInNewPane(id, METADATA_SCHEMA_NAME);
248
+ return /* @__PURE__ */ jsx(
249
+ Tooltip,
250
+ {
251
+ animate: !0,
252
+ content: id ? null : /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: "Document has no other translations" }) }),
253
+ fallbackPlacements: ["right", "left"],
254
+ placement: "top",
255
+ portal: !0,
256
+ children: /* @__PURE__ */ jsx(Stack, { children: /* @__PURE__ */ jsx(
257
+ Button,
258
+ {
259
+ disabled: !id,
260
+ mode: "ghost",
261
+ text: "Manage Translations",
262
+ icon: CogIcon,
263
+ onClick: () => open()
264
+ }
265
+ ) })
266
+ }
267
+ );
268
+ }
269
+ function createReference(key, ref, type, strengthenOnPublish = !0) {
270
+ return {
271
+ _key: key,
272
+ _type: "internationalizedArrayReferenceValue",
273
+ value: {
274
+ _type: "reference",
275
+ _ref: ref,
276
+ _weak: !0,
277
+ // If the user has configured weakReferences, we won't want to strengthen them
278
+ ...strengthenOnPublish ? { _strengthenOnPublish: { type } } : {}
279
+ }
280
+ };
281
+ }
282
+ function removeExcludedPaths(doc, schemaType) {
283
+ if (!isDocumentSchemaType(schemaType) || !doc)
284
+ return doc;
285
+ const pathsToExclude = extractPaths(doc, schemaType, []).filter(
286
+ (field) => {
287
+ var _a, _b, _c;
288
+ return ((_c = (_b = (_a = field.schemaType) == null ? void 0 : _a.options) == null ? void 0 : _b.documentInternationalization) == null ? void 0 : _c.exclude) === !0;
289
+ }
290
+ ).map((field) => pathToString(field.path));
291
+ return new Mutation({
292
+ mutations: [
293
+ {
294
+ patch: {
295
+ id: doc._id,
296
+ unset: pathsToExclude
297
+ }
298
+ }
299
+ ]
300
+ }).apply(doc);
301
+ }
302
+ function extractPaths(doc, schemaType, path) {
303
+ return schemaType.fields.reduce((acc, field) => {
304
+ var _a, _b;
305
+ const fieldPath = [...path, field.name], fieldSchema = field.type, { value } = (_a = extractWithPath(pathToString(fieldPath), doc)[0]) != null ? _a : {};
306
+ if (!value)
307
+ return acc;
308
+ const thisFieldWithPath = {
309
+ path: fieldPath,
310
+ name: field.name,
311
+ schemaType: fieldSchema,
312
+ value
313
+ };
314
+ if (fieldSchema.jsonType === "object") {
315
+ const innerFields = extractPaths(doc, fieldSchema, fieldPath);
316
+ return [...acc, thisFieldWithPath, ...innerFields];
317
+ } else if (fieldSchema.jsonType === "array" && fieldSchema.of.length && fieldSchema.of.some((item) => "fields" in item)) {
318
+ const { value: arrayValue } = (_b = extractWithPath(pathToString(fieldPath), doc)[0]) != null ? _b : {};
319
+ let arrayPaths = [];
320
+ if (arrayValue != null && arrayValue.length)
321
+ for (const item of arrayValue) {
322
+ const itemPath = [...fieldPath, { _key: item._key }];
323
+ let itemSchema = fieldSchema.of.find((t) => t.name === item._type);
324
+ if (item._type || (itemSchema = fieldSchema.of[0]), item._key && itemSchema) {
325
+ const innerFields = extractPaths(
326
+ doc,
327
+ itemSchema,
328
+ itemPath
329
+ ), arrayMember = {
330
+ path: itemPath,
331
+ name: item._key,
332
+ schemaType: itemSchema,
333
+ value: item
334
+ };
335
+ arrayPaths = [...arrayPaths, arrayMember, ...innerFields];
336
+ }
337
+ }
338
+ return [...acc, thisFieldWithPath, ...arrayPaths];
339
+ }
340
+ return [...acc, thisFieldWithPath];
341
+ }, []);
342
+ }
343
+ function LanguageOption(props) {
344
+ var _a;
345
+ const {
346
+ language,
347
+ schemaType,
348
+ documentId,
349
+ current,
350
+ source,
351
+ sourceLanguageId,
352
+ metadata: metadata2,
353
+ metadataId
354
+ } = props, disabled = props.disabled || current || !source || !sourceLanguageId || !metadataId, translation = metadata2 != null && metadata2.translations.length ? metadata2.translations.find((t) => t._key === language.id) : void 0, { apiVersion, languageField, weakReferences } = useDocumentInternationalizationContext(), client = useClient({ apiVersion }), toast = useToast(), open = useOpenInNewPane((_a = translation == null ? void 0 : translation.value) == null ? void 0 : _a._ref, schemaType.name), handleOpen = useCallback(() => open(), [open]), handleCreate = useCallback(async () => {
355
+ if (!source)
356
+ throw new Error("Cannot create translation without source document");
357
+ if (!sourceLanguageId)
358
+ throw new Error("Cannot create translation without source language ID");
359
+ if (!metadataId)
360
+ throw new Error("Cannot create translation without a metadata ID");
361
+ const transaction = client.transaction(), newTranslationDocumentId = uuid();
362
+ let newTranslationDocument = {
363
+ ...source,
364
+ _id: `drafts.${newTranslationDocumentId}`,
365
+ // 2. Update language of the translation
366
+ [languageField]: language.id
367
+ };
368
+ newTranslationDocument = removeExcludedPaths(
369
+ newTranslationDocument,
370
+ schemaType
371
+ ), transaction.create(newTranslationDocument);
372
+ const sourceReference = createReference(
373
+ sourceLanguageId,
374
+ documentId,
375
+ schemaType.name,
376
+ !weakReferences
377
+ ), newTranslationReference = createReference(
378
+ language.id,
379
+ newTranslationDocumentId,
380
+ schemaType.name,
381
+ !weakReferences
382
+ ), newMetadataDocument = {
383
+ _id: metadataId,
384
+ _type: METADATA_SCHEMA_NAME,
385
+ schemaTypes: [schemaType.name],
386
+ translations: [sourceReference]
387
+ };
388
+ transaction.createIfNotExists(newMetadataDocument);
389
+ const metadataPatch = client.patch(metadataId).setIfMissing({ translations: [sourceReference] }).insert("after", "translations[-1]", [newTranslationReference]);
390
+ transaction.patch(metadataPatch), transaction.commit().then(() => {
391
+ const metadataExisted = !!(metadata2 != null && metadata2._createdAt);
392
+ return toast.push({
393
+ status: "success",
394
+ title: `Created "${language.title}" translation`,
395
+ description: metadataExisted ? "Updated Translations Metadata" : "Created Translations Metadata"
396
+ });
397
+ }).catch((err) => (console.error(err), toast.push({
398
+ status: "error",
399
+ title: "Error creating translation",
400
+ description: err.message
401
+ })));
402
+ }, [
403
+ client,
404
+ documentId,
405
+ language.id,
406
+ language.title,
407
+ languageField,
408
+ metadata2 == null ? void 0 : metadata2._createdAt,
409
+ metadataId,
410
+ schemaType,
411
+ source,
412
+ sourceLanguageId,
413
+ toast,
414
+ weakReferences
415
+ ]);
416
+ let message;
417
+ return current ? message = "Current document" : translation ? message = `Open ${language.title} translation` : translation || (message = `Create new ${language.title} translation`), /* @__PURE__ */ jsx(
418
+ Tooltip,
419
+ {
420
+ animate: !0,
421
+ content: /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: message }) }),
422
+ fallbackPlacements: ["right", "left"],
423
+ placement: "top",
424
+ portal: !0,
425
+ children: /* @__PURE__ */ jsx(
426
+ Button,
427
+ {
428
+ onClick: translation ? handleOpen : handleCreate,
429
+ mode: current && disabled ? "default" : "bleed",
430
+ disabled,
431
+ children: /* @__PURE__ */ jsxs(Flex, { gap: 3, align: "center", children: [
432
+ disabled && !current ? /* @__PURE__ */ jsx(Spinner, {}) : /* @__PURE__ */ jsx(Text, { size: 2, children: translation ? /* @__PURE__ */ jsx(SplitVerticalIcon, {}) : current ? /* @__PURE__ */ jsx(CheckmarkIcon, {}) : /* @__PURE__ */ jsx(AddIcon, {}) }),
433
+ /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Text, { children: language.title }) }),
434
+ /* @__PURE__ */ jsx(Badge, { tone: disabled || current ? "default" : "primary", children: language.id })
435
+ ] })
436
+ }
437
+ )
438
+ }
439
+ );
440
+ }
441
+ function LanguagePatch(props) {
442
+ const { language, source } = props, { apiVersion, languageField } = useDocumentInternationalizationContext(), disabled = props.disabled || !source, client = useClient({ apiVersion }), toast = useToast(), handleClick = useCallback(() => {
443
+ if (!source)
444
+ throw new Error("Cannot patch missing document");
445
+ const currentId = source._id;
446
+ client.patch(currentId).set({ [languageField]: language.id }).commit().then(() => {
447
+ toast.push({
448
+ title: `Set document language to ${language.title}`,
449
+ status: "success"
450
+ });
451
+ }).catch((err) => (console.error(err), toast.push({
452
+ title: `Failed to set document language to ${language.title}`,
453
+ status: "error"
454
+ })));
455
+ }, [source, client, languageField, language, toast]);
456
+ return /* @__PURE__ */ jsx(
457
+ Button,
458
+ {
459
+ mode: "bleed",
460
+ onClick: handleClick,
461
+ disabled,
462
+ justify: "flex-start",
463
+ children: /* @__PURE__ */ jsxs(Flex, { gap: 3, align: "center", children: [
464
+ /* @__PURE__ */ jsx(Text, { size: 2, children: /* @__PURE__ */ jsx(EditIcon, {}) }),
465
+ /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Text, { children: language.title }) }),
466
+ /* @__PURE__ */ jsx(Badge, { children: language.id })
467
+ ] })
468
+ }
469
+ );
470
+ }
471
+ var ConstrainedBox = styled(Box)`
472
+ max-width: 280px;
473
+ `;
474
+ function Warning({ children }) {
475
+ return /* @__PURE__ */ jsx(Card, { tone: "caution", padding: 3, children: /* @__PURE__ */ jsx(Flex, { justify: "center", children: /* @__PURE__ */ jsx(ConstrainedBox, { children: /* @__PURE__ */ jsx(Text, { size: 1, align: "center", children }) }) }) });
476
+ }
477
+ function DocumentInternationalizationMenu(props) {
478
+ const { documentId } = props, schemaType = props.schemaType, { languageField, supportedLanguages } = useDocumentInternationalizationContext(), [query2, setQuery] = useState(""), handleQuery = useCallback((event) => {
479
+ event.currentTarget.value ? setQuery(event.currentTarget.value) : setQuery("");
480
+ }, []), [open, setOpen] = useState(!1), handleClick = useCallback(() => setOpen((o) => !o), []), [button, setButton] = useState(null), [popover, setPopover] = useState(null), handleClickOutside = useCallback(() => setOpen(!1), []);
481
+ useClickOutside(handleClickOutside, [button, popover]);
482
+ const { data, loading, error } = useTranslationMetadata(documentId), metadata2 = Array.isArray(data) && data.length ? data[0] : null, metadataId = useMemo(() => {
483
+ var _a;
484
+ return loading ? null : (_a = metadata2 == null ? void 0 : metadata2._id) != null ? _a : uuid();
485
+ }, [loading, metadata2 == null ? void 0 : metadata2._id]), { draft, published } = useEditState(documentId, schemaType.name), source = draft || published, documentIsInOneMetadataDocument = useMemo(() => Array.isArray(data) && data.length <= 1, [data]), sourceLanguageId = source == null ? void 0 : source[languageField], sourceLanguageIsValid = supportedLanguages.some(
486
+ (l) => l.id === sourceLanguageId
487
+ ), allLanguagesAreValid = useMemo(() => {
488
+ const valid = supportedLanguages.every((l) => l.id && l.title);
489
+ return valid || console.warn(
490
+ 'Not all languages are valid. It should be an array of objects with an "id" and "title" property. Or a function that returns an array of objects with an "id" and "title" property.',
491
+ supportedLanguages
492
+ ), valid;
493
+ }, [supportedLanguages]), content = /* @__PURE__ */ jsx(Box, { padding: 1, children: error ? /* @__PURE__ */ jsx(Card, { tone: "critical", padding: 1, children: /* @__PURE__ */ jsx(Text, { children: "There was an error returning translations metadata" }) }) : /* @__PURE__ */ jsxs(Stack, { space: 1, children: [
494
+ /* @__PURE__ */ jsx(LanguageManage, { id: metadata2 == null ? void 0 : metadata2._id }),
495
+ supportedLanguages.length > 4 ? /* @__PURE__ */ jsx(
496
+ TextInput,
497
+ {
498
+ onChange: handleQuery,
499
+ value: query2,
500
+ placeholder: "Filter languages"
501
+ }
502
+ ) : null,
503
+ supportedLanguages.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
504
+ loading ? null : /* @__PURE__ */ jsxs(Fragment, { children: [
505
+ data && documentIsInOneMetadataDocument ? null : /* @__PURE__ */ jsx(Warning, { children: "This document has been found in more than one Translations Metadata documents" }),
506
+ allLanguagesAreValid ? null : /* @__PURE__ */ jsx(Warning, { children: "Not all language objects are valid. See the console." }),
507
+ sourceLanguageId ? null : /* @__PURE__ */ jsxs(Warning, { children: [
508
+ "Choose a language to apply to",
509
+ " ",
510
+ /* @__PURE__ */ jsx("strong", { children: "this Document" })
511
+ ] }),
512
+ sourceLanguageId && !sourceLanguageIsValid ? /* @__PURE__ */ jsxs(Warning, { children: [
513
+ "Select a supported language. Current language value:",
514
+ " ",
515
+ /* @__PURE__ */ jsx("code", { children: sourceLanguageId })
516
+ ] }) : null
517
+ ] }),
518
+ supportedLanguages.filter((language) => query2 ? language.title.toLowerCase().includes(query2.toLowerCase()) : !0).map(
519
+ (language) => {
520
+ var _a;
521
+ return !loading && sourceLanguageId && sourceLanguageIsValid ? (
522
+ // Button to duplicate this document to a new translation
523
+ // And either create or update the metadata document
524
+ /* @__PURE__ */ jsx(
525
+ LanguageOption,
526
+ {
527
+ language,
528
+ schemaType,
529
+ documentId,
530
+ disabled: loading || !allLanguagesAreValid,
531
+ current: language.id === sourceLanguageId,
532
+ metadata: metadata2,
533
+ metadataId,
534
+ source,
535
+ sourceLanguageId
536
+ },
537
+ language.id
538
+ )
539
+ ) : (
540
+ // Button to set a language field on *this* document
541
+ /* @__PURE__ */ jsx(
542
+ LanguagePatch,
543
+ {
544
+ source,
545
+ language,
546
+ disabled: (_a = loading || !allLanguagesAreValid || (metadata2 == null ? void 0 : metadata2.translations.filter((t) => {
547
+ var _a2;
548
+ return ((_a2 = t == null ? void 0 : t.value) == null ? void 0 : _a2._ref) !== documentId;
549
+ }).some((t) => t._key === language.id))) != null ? _a : !1
550
+ },
551
+ language.id
552
+ )
553
+ );
554
+ }
555
+ )
556
+ ] }) : null
557
+ ] }) }), issueWithTranslations = !loading && sourceLanguageId && !sourceLanguageIsValid;
558
+ return !documentId || !schemaType || !schemaType.name ? null : /* @__PURE__ */ jsx(
559
+ Popover,
560
+ {
561
+ animate: !0,
562
+ constrainSize: !0,
563
+ content,
564
+ open,
565
+ portal: !0,
566
+ ref: setPopover,
567
+ overflow: "auto",
568
+ tone: "default",
569
+ children: /* @__PURE__ */ jsx(
570
+ Button,
571
+ {
572
+ text: "Translations",
573
+ mode: "bleed",
574
+ disabled: !source,
575
+ tone: !source || loading || !issueWithTranslations ? void 0 : "caution",
576
+ icon: TranslateIcon,
577
+ onClick: handleClick,
578
+ ref: setButton,
579
+ selected: open
580
+ }
581
+ )
582
+ }
583
+ );
584
+ }
585
+ const DeleteMetadataAction = (props) => {
586
+ const { id: documentId, published, draft, onComplete } = props, doc = draft || published, [isDialogOpen, setDialogOpen] = useState(!1), onClose = useCallback(() => setDialogOpen(!1), []), translations = useMemo(
587
+ () => doc && Array.isArray(doc[TRANSLATIONS_ARRAY_NAME]) ? doc[TRANSLATIONS_ARRAY_NAME] : [],
588
+ [doc]
589
+ ), toast = useToast(), client = useClient({ apiVersion: API_VERSION }), onProceed = useCallback(() => {
590
+ const tx = client.transaction();
591
+ tx.patch(documentId, (patch) => patch.unset([TRANSLATIONS_ARRAY_NAME])), translations.length > 0 && translations.forEach((translation) => {
592
+ tx.delete(translation.value._ref), tx.delete(`drafts.${translation.value._ref}`);
593
+ }), tx.delete(documentId), tx.delete(`drafts.${documentId}`), tx.commit().then(() => {
594
+ onClose(), toast.push({
595
+ status: "success",
596
+ title: "Deleted document and translations"
597
+ });
598
+ }).catch((err) => {
599
+ toast.push({
600
+ status: "error",
601
+ title: "Failed to delete document and translations",
602
+ description: err.message
603
+ });
604
+ });
605
+ }, [client, translations, documentId, onClose, toast]);
606
+ return {
607
+ label: "Delete all translations",
608
+ disabled: !doc || !translations.length,
609
+ icon: TrashIcon,
610
+ tone: "critical",
611
+ onHandle: () => {
612
+ setDialogOpen(!0);
613
+ },
614
+ dialog: isDialogOpen && {
615
+ type: "confirm",
616
+ onCancel: onComplete,
617
+ onConfirm: () => {
618
+ onProceed(), onComplete();
619
+ },
620
+ tone: "critical",
621
+ message: translations.length === 1 ? "Delete 1 translation and this document" : `Delete all ${translations.length} translations and this document`
622
+ }
623
+ };
624
+ };
625
+ function LanguageBadge(props) {
626
+ var _a, _b;
627
+ const source = (props == null ? void 0 : props.draft) || (props == null ? void 0 : props.published), { languageField, supportedLanguages } = useDocumentInternationalizationContext(), languageId = source == null ? void 0 : source[languageField];
628
+ if (!languageId)
629
+ return null;
630
+ const language = Array.isArray(supportedLanguages) ? supportedLanguages.find((l) => l.id === languageId) : null;
631
+ return {
632
+ label: (_a = language == null ? void 0 : language.id) != null ? _a : String(languageId),
633
+ title: (_b = language == null ? void 0 : language.title) != null ? _b : void 0,
634
+ color: "primary"
635
+ };
636
+ }
637
+ function DocumentCheck(props) {
638
+ const {
639
+ id,
640
+ onCheckComplete,
641
+ addInvalidId,
642
+ removeInvalidId,
643
+ addDraftId,
644
+ removeDraftId
645
+ } = props, editState = useEditState(id, ""), { isValidating, validation } = useValidationStatus(id, ""), schema = useSchema(), validationHasErrors = useMemo(() => !isValidating && validation.length > 0 && validation.some((item) => item.level === "error"), [isValidating, validation]);
646
+ if (useEffect(() => {
647
+ validationHasErrors ? addInvalidId(id) : removeInvalidId(id), editState.draft ? addDraftId(id) : removeDraftId(id), isValidating || onCheckComplete(id);
648
+ }, [
649
+ addDraftId,
650
+ addInvalidId,
651
+ editState.draft,
652
+ id,
653
+ isValidating,
654
+ onCheckComplete,
655
+ removeDraftId,
656
+ removeInvalidId,
657
+ validationHasErrors
658
+ ]), !editState.draft)
659
+ return null;
660
+ const schemaType = schema.get(editState.draft._type);
661
+ return /* @__PURE__ */ jsx(
662
+ Card,
663
+ {
664
+ border: !0,
665
+ padding: 2,
666
+ tone: validationHasErrors ? "critical" : "positive",
667
+ children: editState.draft && schemaType ? /* @__PURE__ */ jsx(
668
+ Preview,
669
+ {
670
+ layout: "default",
671
+ value: editState.draft,
672
+ schemaType
673
+ }
674
+ ) : /* @__PURE__ */ jsx(Spinner, {})
675
+ }
676
+ );
677
+ }
678
+ function InfoIcon(props) {
679
+ const { text, icon, tone, children } = props;
680
+ return /* @__PURE__ */ jsx(
681
+ Tooltip,
682
+ {
683
+ animate: !0,
684
+ portal: !0,
685
+ content: children ? /* @__PURE__ */ jsx(Fragment, { children }) : /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { size: 1, children: text }) }),
686
+ children: /* @__PURE__ */ jsx(TextWithTone, { tone, size: 1, children: /* @__PURE__ */ jsx(icon, {}) })
687
+ }
688
+ );
689
+ }
690
+ function Info() {
691
+ return /* @__PURE__ */ jsx(InfoIcon, { icon: InfoOutlineIcon, tone: "primary", children: /* @__PURE__ */ jsxs(Stack, { padding: 3, space: 4, style: { maxWidth: 250 }, children: [
692
+ /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { size: 1, children: "Bulk publishing uses the Scheduling API." }) }),
693
+ /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { size: 1, children: "Customized Document Actions in the Studio will not execute. Webhooks will execute." }) }),
694
+ /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { size: 1, children: "Validation is checked before rendering the button below, but the Scheduling API will not check for \u2013 or enforce \u2013 validation." }) })
695
+ ] }) });
696
+ }
697
+ function BulkPublish(props) {
698
+ const { translations } = props, client = useClient({ apiVersion: API_VERSION }), { projectId, dataset } = useWorkspace(), toast = useToast(), [invalidIds, setInvalidIds] = useState(null), [checkedIds, setCheckedIds] = useState([]), onCheckComplete = useCallback((id) => {
699
+ setCheckedIds((ids) => Array.from(/* @__PURE__ */ new Set([...ids, id])));
700
+ }, []), [open, setOpen] = useState(!1), onOpen = useCallback(() => setOpen(!0), []), onClose = useCallback(() => setOpen(!1), []), addInvalidId = useCallback((id) => {
701
+ setInvalidIds((ids) => ids ? Array.from(/* @__PURE__ */ new Set([...ids, id])) : [id]);
702
+ }, []), removeInvalidId = useCallback((id) => {
703
+ setInvalidIds((ids) => ids ? ids.filter((i) => i !== id) : []);
704
+ }, []), [draftIds, setDraftIds] = useState([]), addDraftId = useCallback((id) => {
705
+ setDraftIds((ids) => Array.from(/* @__PURE__ */ new Set([...ids, id])));
706
+ }, []), removeDraftId = useCallback((id) => {
707
+ setDraftIds((ids) => ids.filter((i) => i !== id));
708
+ }, []), handleBulkPublish = useCallback(() => {
709
+ const body = translations.map((translation) => ({
710
+ documentId: translation.value._ref
711
+ }));
712
+ client.request({
713
+ uri: `/publish/${projectId}/${dataset}`,
714
+ method: "POST",
715
+ body
716
+ }).then(() => {
717
+ toast.push({
718
+ status: "success",
719
+ title: "Success",
720
+ description: "Bulk publish complete"
721
+ });
722
+ }).catch((err) => {
723
+ console.error(err), toast.push({
724
+ status: "error",
725
+ title: "Error",
726
+ description: "Bulk publish failed"
727
+ });
728
+ });
729
+ }, [translations, client, projectId, dataset, toast]), disabled = (
730
+ // Not all documents have been checked
731
+ checkedIds.length !== translations.length || // Some document(s) are invalid
732
+ !!(invalidIds && (invalidIds == null ? void 0 : invalidIds.length) > 0) || // No documents are drafts
733
+ !draftIds.length
734
+ );
735
+ return (translations == null ? void 0 : translations.length) > 0 ? /* @__PURE__ */ jsx(Card, { padding: 4, border: !0, radius: 2, children: /* @__PURE__ */ jsxs(Stack, { space: 3, children: [
736
+ /* @__PURE__ */ jsxs(Inline, { space: 3, children: [
737
+ /* @__PURE__ */ jsx(Text, { weight: "bold", size: 1, children: "Bulk publishing" }),
738
+ /* @__PURE__ */ jsx(Info, {})
739
+ ] }),
740
+ /* @__PURE__ */ jsx(Stack, { children: /* @__PURE__ */ jsx(
741
+ Button,
742
+ {
743
+ onClick: onOpen,
744
+ text: "Prepare bulk publishing",
745
+ mode: "ghost"
746
+ }
747
+ ) }),
748
+ open && /* @__PURE__ */ jsx(
749
+ Dialog,
750
+ {
751
+ animate: !0,
752
+ header: "Bulk publishing",
753
+ id: "bulk-publish-dialog",
754
+ onClose,
755
+ zOffset: 1e3,
756
+ width: 3,
757
+ children: /* @__PURE__ */ jsxs(Stack, { space: 4, padding: 4, children: [
758
+ draftIds.length > 0 ? /* @__PURE__ */ jsxs(Stack, { space: 2, children: [
759
+ /* @__PURE__ */ jsxs(Text, { size: 1, children: [
760
+ "There",
761
+ " ",
762
+ draftIds.length === 1 ? "is 1 draft document" : `are ${draftIds.length} draft documents`,
763
+ "."
764
+ ] }),
765
+ invalidIds && invalidIds.length > 0 ? /* @__PURE__ */ jsxs(TextWithTone, { tone: "critical", size: 1, children: [
766
+ invalidIds && invalidIds.length === 1 ? "1 draft document has" : `${invalidIds && invalidIds.length} draft documents have`,
767
+ " ",
768
+ "validation issues that must addressed first"
769
+ ] }) : /* @__PURE__ */ jsx(TextWithTone, { tone: "positive", size: 1, children: "All drafts are valid and can be bulk published" })
770
+ ] }) : null,
771
+ /* @__PURE__ */ jsx(Stack, { space: 1, children: translations.filter((translation) => {
772
+ var _a;
773
+ return (_a = translation == null ? void 0 : translation.value) == null ? void 0 : _a._ref;
774
+ }).map((translation) => /* @__PURE__ */ jsx(
775
+ DocumentCheck,
776
+ {
777
+ id: translation.value._ref,
778
+ onCheckComplete,
779
+ addInvalidId,
780
+ removeInvalidId,
781
+ addDraftId,
782
+ removeDraftId
783
+ },
784
+ translation._key
785
+ )) }),
786
+ draftIds.length > 0 ? /* @__PURE__ */ jsx(
787
+ Button,
788
+ {
789
+ mode: "ghost",
790
+ tone: invalidIds && (invalidIds == null ? void 0 : invalidIds.length) > 0 ? "caution" : "positive",
791
+ text: draftIds.length === 1 ? "Publish draft document" : `Bulk publish ${draftIds.length} draft documents`,
792
+ onClick: handleBulkPublish,
793
+ disabled
794
+ }
795
+ ) : /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: "No draft documents to publish" })
796
+ ] })
797
+ }
798
+ )
799
+ ] }) }) : null;
800
+ }
801
+ function ReferencePatcher(props) {
802
+ const { translation, documentType, metadataId } = props, editState = useEditState(translation.value._ref, documentType), client = useClient({ apiVersion: API_VERSION }), { onChange } = useDocumentPane();
803
+ return useEffect(() => {
804
+ if (
805
+ // We have a reference
806
+ translation.value._ref && // It's still weak and not-yet-strengthened
807
+ translation.value._weak && // We also want to keep this check because maybe the user *configured* weak refs
808
+ translation.value._strengthenOnPublish && // The referenced document has just been published
809
+ !editState.draft && editState.published && editState.ready
810
+ ) {
811
+ const referencePathBase = [
812
+ "translations",
813
+ { _key: translation._key },
814
+ "value"
815
+ ];
816
+ onChange(
817
+ new PatchEvent([
818
+ unset([...referencePathBase, "_weak"]),
819
+ unset([...referencePathBase, "_strengthenOnPublish"])
820
+ ])
821
+ );
822
+ }
823
+ }, [translation, editState, metadataId, client, onChange]), null;
824
+ }
825
+ function OptimisticallyStrengthen(props) {
826
+ const { translations = [], metadataId } = props;
827
+ return translations.length ? /* @__PURE__ */ jsx(Fragment, { children: translations.map(
828
+ (translation) => {
829
+ var _a;
830
+ return (_a = translation.value._strengthenOnPublish) != null && _a.type ? /* @__PURE__ */ jsx(
831
+ ReferencePatcher,
832
+ {
833
+ translation,
834
+ documentType: translation.value._strengthenOnPublish.type,
835
+ metadataId
836
+ },
837
+ translation._key
838
+ ) : null;
839
+ }
840
+ ) }) : null;
841
+ }
842
+ var metadata = (schemaTypes, metadataFields) => defineType({
843
+ type: "document",
844
+ name: METADATA_SCHEMA_NAME,
845
+ title: "Translation metadata",
846
+ icon: TranslateIcon,
847
+ liveEdit: !0,
848
+ fields: [
849
+ defineField({
850
+ name: TRANSLATIONS_ARRAY_NAME,
851
+ type: "internationalizedArrayReference"
852
+ }),
853
+ defineField({
854
+ name: "schemaTypes",
855
+ description: "Optional: Used to filter the reference fields above so all translations share the same types.",
856
+ type: "array",
857
+ of: [{ type: "string" }],
858
+ options: { list: schemaTypes },
859
+ readOnly: ({ value }) => !!value
860
+ }),
861
+ ...metadataFields
862
+ ],
863
+ preview: {
864
+ select: {
865
+ translations: TRANSLATIONS_ARRAY_NAME,
866
+ documentSchemaTypes: "schemaTypes"
867
+ },
868
+ prepare(selection) {
869
+ const { translations = [], documentSchemaTypes = [] } = selection, title = translations.length === 1 ? "1 Translation" : `${translations.length} Translations`, languageKeys = translations.length ? translations.map((t) => t._key.toUpperCase()).join(", ") : "", subtitle = [
870
+ languageKeys ? `(${languageKeys})` : null,
871
+ documentSchemaTypes != null && documentSchemaTypes.length ? documentSchemaTypes.map((s) => s).join(", ") : ""
872
+ ].filter(Boolean).join(" ");
873
+ return {
874
+ title,
875
+ subtitle
876
+ };
877
+ }
878
+ }
879
+ });
880
+ const documentInternationalization = definePlugin(
881
+ (config) => {
882
+ const pluginConfig = { ...DEFAULT_CONFIG, ...config }, {
883
+ supportedLanguages,
884
+ schemaTypes,
885
+ languageField,
886
+ bulkPublish,
887
+ metadataFields
888
+ } = pluginConfig;
889
+ if (schemaTypes.length === 0)
890
+ throw new Error(
891
+ "You must specify at least one schema type on which to enable document internationalization. Update the `schemaTypes` option in the documentInternationalization() configuration."
892
+ );
893
+ return {
894
+ name: "@sanity/document-internationalization",
895
+ studio: {
896
+ components: {
897
+ layout: (props) => DocumentInternationalizationProvider({ ...props, pluginConfig })
898
+ }
899
+ },
900
+ // Adds:
901
+ // - A bulk-publishing UI component to the form
902
+ // - Will only work for projects on a compatible plan
903
+ form: {
904
+ components: {
905
+ input: (props) => {
906
+ var _a, _b, _c;
907
+ if (props.id === "root" && props.schemaType.name === METADATA_SCHEMA_NAME && isSanityDocument(props == null ? void 0 : props.value)) {
908
+ const metadataId = (_a = props == null ? void 0 : props.value) == null ? void 0 : _a._id, translations = (_c = (_b = props == null ? void 0 : props.value) == null ? void 0 : _b.translations) != null ? _c : [], weakAndTypedTranslations = translations.filter(
909
+ ({ value }) => (value == null ? void 0 : value._weak) && value._strengthenOnPublish
910
+ );
911
+ return /* @__PURE__ */ jsxs(Stack, { space: 5, children: [
912
+ bulkPublish ? /* @__PURE__ */ jsx(BulkPublish, { translations }) : null,
913
+ weakAndTypedTranslations.length > 0 ? /* @__PURE__ */ jsx(
914
+ OptimisticallyStrengthen,
915
+ {
916
+ metadataId,
917
+ translations: weakAndTypedTranslations
918
+ }
919
+ ) : null,
920
+ props.renderDefault(props)
921
+ ] });
922
+ }
923
+ return props.renderDefault(props);
924
+ }
925
+ }
926
+ },
927
+ // Adds:
928
+ // - The `Translations` dropdown to the editing form
929
+ // - `Badges` to documents with a language value
930
+ // - The `DeleteMetadataAction` action to the metadata document type
931
+ document: {
932
+ unstable_languageFilter: (prev, ctx) => {
933
+ const { schemaType, documentId } = ctx;
934
+ return schemaTypes.includes(schemaType) && documentId ? [
935
+ ...prev,
936
+ (props) => DocumentInternationalizationMenu({ ...props, documentId })
937
+ ] : prev;
938
+ },
939
+ badges: (prev, { schemaType }) => schemaTypes.includes(schemaType) ? [(props) => LanguageBadge(props), ...prev] : prev,
940
+ actions: (prev, { schemaType }) => schemaType === METADATA_SCHEMA_NAME ? [...prev, DeleteMetadataAction] : prev
941
+ },
942
+ // Adds:
943
+ // - The `Translations metadata` document type to the schema
944
+ schema: {
945
+ // Create the metadata document type
946
+ types: [metadata(schemaTypes, metadataFields)],
947
+ // For every schema type this plugin is enabled on
948
+ // Create an initial value template to set the language
949
+ templates: (prev, { schema }) => {
950
+ if (!Array.isArray(supportedLanguages))
951
+ return prev;
952
+ const parameterizedTemplates = schemaTypes.map((schemaType) => {
953
+ var _a, _b;
954
+ return {
955
+ id: `${schemaType}-parameterized`,
956
+ title: `${(_b = (_a = schema == null ? void 0 : schema.get(schemaType)) == null ? void 0 : _a.title) != null ? _b : schemaType}: with Language`,
957
+ schemaType,
958
+ parameters: [
959
+ { name: "languageId", title: "Language ID", type: "string" }
960
+ ],
961
+ value: ({ languageId }) => ({
962
+ [languageField]: languageId
963
+ })
964
+ };
965
+ }), staticTemplates = schemaTypes.flatMap((schemaType) => supportedLanguages.map((language) => {
966
+ var _a, _b;
967
+ return {
968
+ id: `${schemaType}-${language.id}`,
969
+ title: `${language.title} ${(_b = (_a = schema == null ? void 0 : schema.get(schemaType)) == null ? void 0 : _a.title) != null ? _b : schemaType}`,
970
+ schemaType,
971
+ value: {
972
+ [languageField]: language.id
973
+ }
974
+ };
975
+ }));
976
+ return [...prev, ...parameterizedTemplates, ...staticTemplates];
977
+ }
978
+ },
979
+ // Uses:
980
+ // - `sanity-plugin-internationalized-array` to maintain the translations array
981
+ plugins: [
982
+ // Translation metadata stores its references using this plugin
983
+ // It cuts down on attribute usage and gives UI conveniences to add new translations
984
+ internationalizedArray({
985
+ languages: supportedLanguages,
986
+ fieldTypes: [
987
+ defineField(
988
+ {
989
+ name: "reference",
990
+ type: "reference",
991
+ to: schemaTypes.map((type) => ({ type })),
992
+ weak: pluginConfig.weakReferences,
993
+ // Reference filters don't actually enforce validation!
994
+ validation: (Rule) => (
995
+ // @ts-expect-error - fix typings
996
+ Rule.custom(async (item, context) => {
997
+ var _a;
998
+ if (!((_a = item == null ? void 0 : item.value) != null && _a._ref) || !(item != null && item._key))
999
+ return !0;
1000
+ const valueLanguage = await context.getClient({ apiVersion: API_VERSION }).fetch(
1001
+ `*[_id in [$ref, $draftRef]][0].${languageField}`,
1002
+ {
1003
+ ref: item.value._ref,
1004
+ draftRef: `drafts.${item.value._ref}`
1005
+ }
1006
+ );
1007
+ return valueLanguage && valueLanguage === item._key ? !0 : "Referenced document does not have the correct language value";
1008
+ })
1009
+ ),
1010
+ options: {
1011
+ // @ts-expect-error - Update type once it knows the values of this filter
1012
+ filter: ({ parent, document }) => {
1013
+ if (!parent)
1014
+ return null;
1015
+ const language = (Array.isArray(parent) ? parent : [parent]).find((p) => p._key);
1016
+ return language != null && language._key ? document.schemaTypes ? {
1017
+ filter: `_type in $schemaTypes && ${languageField} == $language`,
1018
+ params: {
1019
+ schemaTypes: document.schemaTypes,
1020
+ language: language._key
1021
+ }
1022
+ } : {
1023
+ filter: `${languageField} == $language`,
1024
+ params: { language: language._key }
1025
+ } : null;
1026
+ }
1027
+ }
1028
+ },
1029
+ { strict: !1 }
1030
+ )
1031
+ ]
1032
+ })
1033
+ ]
1034
+ };
1035
+ }
1036
+ );
1037
+ export {
1038
+ DeleteTranslationAction,
1039
+ DocumentInternationalizationMenu,
1040
+ documentInternationalization,
1041
+ useDocumentInternationalizationContext
1042
+ };
1043
+ //# sourceMappingURL=index.mjs.map