@sanity/document-internationalization 4.1.0 → 5.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 (52) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +11 -35
  3. package/dist/_chunks-es/{resources.mjs → resources.js} +1 -1
  4. package/dist/{_chunks-cjs → _chunks-es}/resources.js.map +1 -1
  5. package/dist/index.d.ts +59 -92
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +997 -1327
  8. package/dist/index.js.map +1 -1
  9. package/package.json +35 -73
  10. package/dist/_chunks-cjs/resources.js +0 -8
  11. package/dist/_chunks-es/resources.mjs.map +0 -1
  12. package/dist/_legacy/resources.esm.js +0 -9
  13. package/dist/_legacy/resources.esm.js.map +0 -1
  14. package/dist/index.d.mts +0 -110
  15. package/dist/index.esm.js +0 -1647
  16. package/dist/index.esm.js.map +0 -1
  17. package/dist/index.mjs +0 -1647
  18. package/dist/index.mjs.map +0 -1
  19. package/sanity.json +0 -8
  20. package/src/actions/DeleteMetadataAction.tsx +0 -93
  21. package/src/actions/DeleteTranslationAction.tsx +0 -102
  22. package/src/actions/DuplicateWithTranslationsAction.tsx +0 -251
  23. package/src/badges/index.tsx +0 -27
  24. package/src/components/BulkPublish/DocumentCheck.tsx +0 -90
  25. package/src/components/BulkPublish/Info.tsx +0 -28
  26. package/src/components/BulkPublish/InfoIcon.tsx +0 -34
  27. package/src/components/BulkPublish/index.tsx +0 -181
  28. package/src/components/ConstrainedBox.tsx +0 -6
  29. package/src/components/DeleteTranslationDialog/DocumentPreview.tsx +0 -19
  30. package/src/components/DeleteTranslationDialog/index.tsx +0 -111
  31. package/src/components/DeleteTranslationDialog/separateReferences.ts +0 -23
  32. package/src/components/DeleteTranslationFooter.tsx +0 -28
  33. package/src/components/DocumentInternationalizationContext.tsx +0 -47
  34. package/src/components/DocumentInternationalizationMenu.tsx +0 -235
  35. package/src/components/LanguageManage.tsx +0 -108
  36. package/src/components/LanguageOption.tsx +0 -259
  37. package/src/components/LanguagePatch.tsx +0 -67
  38. package/src/components/OptimisticallyStrengthen/ReferencePatcher.tsx +0 -50
  39. package/src/components/OptimisticallyStrengthen/index.tsx +0 -34
  40. package/src/components/Warning.tsx +0 -18
  41. package/src/constants.ts +0 -16
  42. package/src/hooks/useLanguageMetadata.tsx +0 -26
  43. package/src/hooks/useOpenInNewPane.tsx +0 -33
  44. package/src/i18n/index.ts +0 -21
  45. package/src/i18n/resources.ts +0 -7
  46. package/src/index.ts +0 -6
  47. package/src/plugin.tsx +0 -239
  48. package/src/schema/translation/metadata.ts +0 -68
  49. package/src/types.ts +0 -99
  50. package/src/utils/createReference.ts +0 -20
  51. package/src/utils/excludePaths.ts +0 -123
  52. package/v2-incompatible.js +0 -11
package/dist/index.mjs DELETED
@@ -1,1647 +0,0 @@
1
- import { jsx, jsxs, Fragment } from "react/jsx-runtime";
2
- import { TrashIcon, CopyIcon, 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, defineLocaleResourceBundle, useDocumentStore, useDocumentOperation, useDocumentPairPermissions, DEFAULT_STUDIO_CLIENT_OPTIONS, useTranslation, useCurrentUser, InsufficientPermissionsMessage, 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 { useRouter, RouterContext } from "sanity/router";
9
- import { structureLocaleNamespace, 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 = "2025-02-19", DEFAULT_CONFIG = {
18
- supportedLanguages: [],
19
- schemaTypes: [],
20
- languageField: "language",
21
- weakReferences: !1,
22
- bulkPublish: !1,
23
- metadataFields: [],
24
- apiVersion: API_VERSION,
25
- allowCreateMetaDoc: !1,
26
- callback: null
27
- };
28
- function separateReferences(data = []) {
29
- const translations = [], otherReferences = [];
30
- return data && data.length > 0 && data.forEach((doc) => {
31
- doc._type === METADATA_SCHEMA_NAME ? translations.push(doc) : otherReferences.push(doc);
32
- }), { translations, otherReferences };
33
- }
34
- function DeleteTranslationDialog(props) {
35
- const { doc, documentId, setTranslations } = props, { data, loading } = useListeningQuery(
36
- "*[references($id)]{_id, _type}",
37
- { params: { id: documentId }, initialValue: [] }
38
- ), { translations, otherReferences } = useMemo(
39
- () => separateReferences(data),
40
- [data]
41
- );
42
- return useEffect(() => {
43
- setTranslations(translations);
44
- }, [setTranslations, translations]), loading ? /* @__PURE__ */ jsx(Flex, { padding: 4, align: "center", justify: "center", children: /* @__PURE__ */ jsx(Spinner, {}) }) : /* @__PURE__ */ jsxs(Stack, { space: 4, children: [
45
- 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." }),
46
- /* @__PURE__ */ jsx(Card, { border: !0, padding: 3, children: /* @__PURE__ */ jsxs(Stack, { space: 4, children: [
47
- /* @__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" }) }),
48
- /* @__PURE__ */ jsx(DocumentPreview, { value: doc, type: doc._type }),
49
- translations && translations.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
50
- /* @__PURE__ */ jsx(Card, { borderTop: !0 }),
51
- /* @__PURE__ */ jsxs(Text, { size: 1, weight: "semibold", children: [
52
- "The reference in",
53
- " ",
54
- translations.length === 1 ? "this translations document" : "these translations documents",
55
- " ",
56
- "must be removed"
57
- ] }),
58
- translations.map((translation) => /* @__PURE__ */ jsx(
59
- DocumentPreview,
60
- {
61
- value: translation,
62
- type: translation._type
63
- },
64
- translation._id
65
- ))
66
- ] }) : null,
67
- otherReferences && otherReferences.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
68
- /* @__PURE__ */ jsx(Card, { borderTop: !0 }),
69
- /* @__PURE__ */ jsxs(Text, { size: 1, weight: "semibold", children: [
70
- otherReferences.length === 1 ? "There is an additional reference" : "There are additional references",
71
- " ",
72
- "to this document"
73
- ] }),
74
- otherReferences.map((reference) => /* @__PURE__ */ jsx(
75
- DocumentPreview,
76
- {
77
- value: reference,
78
- type: reference._type
79
- },
80
- reference._id
81
- ))
82
- ] }) : null
83
- ] }) }),
84
- 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." })
85
- ] });
86
- }
87
- function DeleteTranslationFooter(props) {
88
- const { translations, onClose, onProceed } = props;
89
- return /* @__PURE__ */ jsxs(Grid, { columns: 2, gap: 2, children: [
90
- /* @__PURE__ */ jsx(Button, { text: "Cancel", onClick: onClose, mode: "ghost" }),
91
- /* @__PURE__ */ jsx(
92
- Button,
93
- {
94
- text: translations && translations.length > 0 ? "Unset translation reference" : "Delete document",
95
- onClick: onProceed,
96
- tone: "critical"
97
- }
98
- )
99
- ] });
100
- }
101
- const isPromise = (promise) => typeof promise == "object" && typeof promise.then == "function", globalCache = [];
102
- function shallowEqualArrays(arrA, arrB, equal = (a, b) => a === b) {
103
- if (arrA === arrB)
104
- return !0;
105
- if (!arrA || !arrB)
106
- return !1;
107
- const len = arrA.length;
108
- if (arrB.length !== len)
109
- return !1;
110
- for (let i = 0; i < len; i++)
111
- if (!equal(arrA[i], arrB[i]))
112
- return !1;
113
- return !0;
114
- }
115
- function query$1(fn, keys = null, preload = !1, config2 = {}) {
116
- keys === null && (keys = [fn]);
117
- for (const entry2 of globalCache)
118
- if (shallowEqualArrays(keys, entry2.keys, entry2.equal)) {
119
- if (preload)
120
- return;
121
- if (Object.prototype.hasOwnProperty.call(entry2, "error"))
122
- throw entry2.error;
123
- if (Object.prototype.hasOwnProperty.call(entry2, "response"))
124
- return config2.lifespan && config2.lifespan > 0 && (entry2.timeout && clearTimeout(entry2.timeout), entry2.timeout = setTimeout(entry2.remove, config2.lifespan)), entry2.response;
125
- if (!preload)
126
- throw entry2.promise;
127
- }
128
- const entry = {
129
- keys,
130
- equal: config2.equal,
131
- remove: () => {
132
- const index = globalCache.indexOf(entry);
133
- index !== -1 && globalCache.splice(index, 1);
134
- },
135
- promise: (
136
- // Execute the promise
137
- (isPromise(fn) ? fn : fn(...keys)).then((response) => {
138
- entry.response = response, config2.lifespan && config2.lifespan > 0 && (entry.timeout = setTimeout(entry.remove, config2.lifespan));
139
- }).catch((error) => entry.error = error)
140
- )
141
- };
142
- if (globalCache.push(entry), !preload)
143
- throw entry.promise;
144
- }
145
- const suspend = (fn, keys, config2) => query$1(fn, keys, !1, config2);
146
- var __defProp$3 = Object.defineProperty, __defProps$2 = Object.defineProperties, __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$3 = Object.getOwnPropertySymbols, __hasOwnProp$3 = Object.prototype.hasOwnProperty, __propIsEnum$3 = Object.prototype.propertyIsEnumerable, __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$3 = (a, b) => {
147
- for (var prop in b || (b = {}))
148
- __hasOwnProp$3.call(b, prop) && __defNormalProp$3(a, prop, b[prop]);
149
- if (__getOwnPropSymbols$3)
150
- for (var prop of __getOwnPropSymbols$3(b))
151
- __propIsEnum$3.call(b, prop) && __defNormalProp$3(a, prop, b[prop]);
152
- return a;
153
- }, __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
154
- const DocumentInternationalizationContext = createContext(DEFAULT_CONFIG);
155
- function useDocumentInternationalizationContext() {
156
- return useContext(DocumentInternationalizationContext);
157
- }
158
- function DocumentInternationalizationProvider(props) {
159
- const { pluginConfig } = props, client = useClient({ apiVersion: pluginConfig.apiVersion }), workspace = useWorkspace(), supportedLanguages = Array.isArray(pluginConfig.supportedLanguages) ? pluginConfig.supportedLanguages : (
160
- // eslint-disable-next-line require-await
161
- suspend(async () => typeof pluginConfig.supportedLanguages == "function" ? pluginConfig.supportedLanguages(client) : pluginConfig.supportedLanguages, [workspace])
162
- );
163
- return /* @__PURE__ */ jsx(
164
- DocumentInternationalizationContext.Provider,
165
- {
166
- value: __spreadProps$2(__spreadValues$3({}, pluginConfig), { supportedLanguages }),
167
- children: props.renderDefault(props)
168
- }
169
- );
170
- }
171
- const DeleteTranslationAction = (props) => {
172
- 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(() => {
173
- const tx = client.transaction();
174
- let operation = "DELETE";
175
- documentLanguage && translations.length > 0 ? (operation = "UNSET", translations.forEach((translation) => {
176
- tx.patch(
177
- translation._id,
178
- (patch) => patch.unset([
179
- `${TRANSLATIONS_ARRAY_NAME}[_key == "${documentLanguage}"]`
180
- ])
181
- );
182
- })) : (tx.delete(documentId), tx.delete(`drafts.${documentId}`)), tx.commit().then(() => {
183
- operation === "DELETE" && onClose(), toast.push({
184
- status: "success",
185
- title: operation === "UNSET" ? "Translation reference unset" : "Document deleted",
186
- description: operation === "UNSET" ? "The document can now be deleted" : null
187
- });
188
- }).catch((err) => {
189
- toast.push({
190
- status: "error",
191
- title: operation === "unset" ? "Failed to unset translation reference" : "Failed to delete document",
192
- description: err.message
193
- });
194
- });
195
- }, [client, documentLanguage, translations, documentId, onClose, toast]);
196
- return {
197
- label: "Delete translation...",
198
- disabled: !doc || !documentLanguage,
199
- icon: TrashIcon,
200
- tone: "critical",
201
- onHandle: () => {
202
- setDialogOpen(!0);
203
- },
204
- dialog: isDialogOpen && {
205
- type: "dialog",
206
- onClose,
207
- header: "Delete translation",
208
- content: doc ? /* @__PURE__ */ jsx(
209
- DeleteTranslationDialog,
210
- {
211
- doc,
212
- documentId,
213
- setTranslations
214
- }
215
- ) : null,
216
- footer: /* @__PURE__ */ jsx(
217
- DeleteTranslationFooter,
218
- {
219
- onClose,
220
- onProceed,
221
- translations
222
- }
223
- )
224
- }
225
- };
226
- };
227
- var extendStatics = function(d, b) {
228
- return extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
229
- d2.__proto__ = b2;
230
- } || function(d2, b2) {
231
- for (var p in b2)
232
- Object.prototype.hasOwnProperty.call(b2, p) && (d2[p] = b2[p]);
233
- }, extendStatics(d, b);
234
- };
235
- function __extends(d, b) {
236
- if (typeof b != "function" && b !== null)
237
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
238
- extendStatics(d, b);
239
- function __() {
240
- this.constructor = d;
241
- }
242
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
243
- }
244
- function __values(o) {
245
- var s = typeof Symbol == "function" && Symbol.iterator, m = s && o[s], i = 0;
246
- if (m)
247
- return m.call(o);
248
- if (o && typeof o.length == "number")
249
- return {
250
- next: function() {
251
- return o && i >= o.length && (o = void 0), { value: o && o[i++], done: !o };
252
- }
253
- };
254
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
255
- }
256
- function __read(o, n) {
257
- var m = typeof Symbol == "function" && o[Symbol.iterator];
258
- if (!m)
259
- return o;
260
- var i = m.call(o), r, ar = [], e;
261
- try {
262
- for (; (n === void 0 || n-- > 0) && !(r = i.next()).done; )
263
- ar.push(r.value);
264
- } catch (error) {
265
- e = { error };
266
- } finally {
267
- try {
268
- r && !r.done && (m = i.return) && m.call(i);
269
- } finally {
270
- if (e)
271
- throw e.error;
272
- }
273
- }
274
- return ar;
275
- }
276
- function __spreadArray(to, from, pack) {
277
- if (pack || arguments.length === 2)
278
- for (var i = 0, l = from.length, ar; i < l; i++)
279
- (ar || !(i in from)) && (ar || (ar = Array.prototype.slice.call(from, 0, i)), ar[i] = from[i]);
280
- return to.concat(ar || Array.prototype.slice.call(from));
281
- }
282
- function isFunction(value) {
283
- return typeof value == "function";
284
- }
285
- function createErrorClass(createImpl) {
286
- var _super = function(instance) {
287
- Error.call(instance), instance.stack = new Error().stack;
288
- }, ctorFunc = createImpl(_super);
289
- return ctorFunc.prototype = Object.create(Error.prototype), ctorFunc.prototype.constructor = ctorFunc, ctorFunc;
290
- }
291
- var UnsubscriptionError = createErrorClass(function(_super) {
292
- return function(errors) {
293
- _super(this), this.message = errors ? errors.length + ` errors occurred during unsubscription:
294
- ` + errors.map(function(err, i) {
295
- return i + 1 + ") " + err.toString();
296
- }).join(`
297
- `) : "", this.name = "UnsubscriptionError", this.errors = errors;
298
- };
299
- });
300
- function arrRemove(arr, item) {
301
- if (arr) {
302
- var index = arr.indexOf(item);
303
- 0 <= index && arr.splice(index, 1);
304
- }
305
- }
306
- var Subscription = function() {
307
- function Subscription2(initialTeardown) {
308
- this.initialTeardown = initialTeardown, this.closed = !1, this._parentage = null, this._finalizers = null;
309
- }
310
- return Subscription2.prototype.unsubscribe = function() {
311
- var e_1, _a, e_2, _b, errors;
312
- if (!this.closed) {
313
- this.closed = !0;
314
- var _parentage = this._parentage;
315
- if (_parentage)
316
- if (this._parentage = null, Array.isArray(_parentage))
317
- try {
318
- for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
319
- var parent_1 = _parentage_1_1.value;
320
- parent_1.remove(this);
321
- }
322
- } catch (e_1_1) {
323
- e_1 = { error: e_1_1 };
324
- } finally {
325
- try {
326
- _parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return) && _a.call(_parentage_1);
327
- } finally {
328
- if (e_1)
329
- throw e_1.error;
330
- }
331
- }
332
- else
333
- _parentage.remove(this);
334
- var initialFinalizer = this.initialTeardown;
335
- if (isFunction(initialFinalizer))
336
- try {
337
- initialFinalizer();
338
- } catch (e) {
339
- errors = e instanceof UnsubscriptionError ? e.errors : [e];
340
- }
341
- var _finalizers = this._finalizers;
342
- if (_finalizers) {
343
- this._finalizers = null;
344
- try {
345
- for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
346
- var finalizer = _finalizers_1_1.value;
347
- try {
348
- execFinalizer(finalizer);
349
- } catch (err) {
350
- errors = errors != null ? errors : [], err instanceof UnsubscriptionError ? errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors)) : errors.push(err);
351
- }
352
- }
353
- } catch (e_2_1) {
354
- e_2 = { error: e_2_1 };
355
- } finally {
356
- try {
357
- _finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return) && _b.call(_finalizers_1);
358
- } finally {
359
- if (e_2)
360
- throw e_2.error;
361
- }
362
- }
363
- }
364
- if (errors)
365
- throw new UnsubscriptionError(errors);
366
- }
367
- }, Subscription2.prototype.add = function(teardown) {
368
- var _a;
369
- if (teardown && teardown !== this)
370
- if (this.closed)
371
- execFinalizer(teardown);
372
- else {
373
- if (teardown instanceof Subscription2) {
374
- if (teardown.closed || teardown._hasParent(this))
375
- return;
376
- teardown._addParent(this);
377
- }
378
- (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
379
- }
380
- }, Subscription2.prototype._hasParent = function(parent) {
381
- var _parentage = this._parentage;
382
- return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
383
- }, Subscription2.prototype._addParent = function(parent) {
384
- var _parentage = this._parentage;
385
- this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
386
- }, Subscription2.prototype._removeParent = function(parent) {
387
- var _parentage = this._parentage;
388
- _parentage === parent ? this._parentage = null : Array.isArray(_parentage) && arrRemove(_parentage, parent);
389
- }, Subscription2.prototype.remove = function(teardown) {
390
- var _finalizers = this._finalizers;
391
- _finalizers && arrRemove(_finalizers, teardown), teardown instanceof Subscription2 && teardown._removeParent(this);
392
- }, Subscription2.EMPTY = function() {
393
- var empty = new Subscription2();
394
- return empty.closed = !0, empty;
395
- }(), Subscription2;
396
- }();
397
- function isSubscription(value) {
398
- return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
399
- }
400
- function execFinalizer(finalizer) {
401
- isFunction(finalizer) ? finalizer() : finalizer.unsubscribe();
402
- }
403
- var config = {
404
- onUnhandledError: null,
405
- onStoppedNotification: null,
406
- Promise: void 0,
407
- useDeprecatedSynchronousErrorHandling: !1,
408
- useDeprecatedNextContext: !1
409
- }, timeoutProvider = {
410
- setTimeout: function(handler, timeout) {
411
- for (var args = [], _i = 2; _i < arguments.length; _i++)
412
- args[_i - 2] = arguments[_i];
413
- return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
414
- },
415
- clearTimeout: function(handle) {
416
- return clearTimeout(handle);
417
- },
418
- delegate: void 0
419
- };
420
- function reportUnhandledError(err) {
421
- timeoutProvider.setTimeout(function() {
422
- throw err;
423
- });
424
- }
425
- function noop() {
426
- }
427
- var Subscriber = function(_super) {
428
- __extends(Subscriber2, _super);
429
- function Subscriber2(destination) {
430
- var _this = _super.call(this) || this;
431
- return _this.isStopped = !1, destination ? (_this.destination = destination, isSubscription(destination) && destination.add(_this)) : _this.destination = EMPTY_OBSERVER, _this;
432
- }
433
- return Subscriber2.create = function(next, error, complete) {
434
- return new SafeSubscriber(next, error, complete);
435
- }, Subscriber2.prototype.next = function(value) {
436
- this.isStopped || this._next(value);
437
- }, Subscriber2.prototype.error = function(err) {
438
- this.isStopped || (this.isStopped = !0, this._error(err));
439
- }, Subscriber2.prototype.complete = function() {
440
- this.isStopped || (this.isStopped = !0, this._complete());
441
- }, Subscriber2.prototype.unsubscribe = function() {
442
- this.closed || (this.isStopped = !0, _super.prototype.unsubscribe.call(this), this.destination = null);
443
- }, Subscriber2.prototype._next = function(value) {
444
- this.destination.next(value);
445
- }, Subscriber2.prototype._error = function(err) {
446
- try {
447
- this.destination.error(err);
448
- } finally {
449
- this.unsubscribe();
450
- }
451
- }, Subscriber2.prototype._complete = function() {
452
- try {
453
- this.destination.complete();
454
- } finally {
455
- this.unsubscribe();
456
- }
457
- }, Subscriber2;
458
- }(Subscription), _bind = Function.prototype.bind;
459
- function bind(fn, thisArg) {
460
- return _bind.call(fn, thisArg);
461
- }
462
- var ConsumerObserver = function() {
463
- function ConsumerObserver2(partialObserver) {
464
- this.partialObserver = partialObserver;
465
- }
466
- return ConsumerObserver2.prototype.next = function(value) {
467
- var partialObserver = this.partialObserver;
468
- if (partialObserver.next)
469
- try {
470
- partialObserver.next(value);
471
- } catch (error) {
472
- handleUnhandledError(error);
473
- }
474
- }, ConsumerObserver2.prototype.error = function(err) {
475
- var partialObserver = this.partialObserver;
476
- if (partialObserver.error)
477
- try {
478
- partialObserver.error(err);
479
- } catch (error) {
480
- handleUnhandledError(error);
481
- }
482
- else
483
- handleUnhandledError(err);
484
- }, ConsumerObserver2.prototype.complete = function() {
485
- var partialObserver = this.partialObserver;
486
- if (partialObserver.complete)
487
- try {
488
- partialObserver.complete();
489
- } catch (error) {
490
- handleUnhandledError(error);
491
- }
492
- }, ConsumerObserver2;
493
- }(), SafeSubscriber = function(_super) {
494
- __extends(SafeSubscriber2, _super);
495
- function SafeSubscriber2(observerOrNext, error, complete) {
496
- var _this = _super.call(this) || this, partialObserver;
497
- if (isFunction(observerOrNext) || !observerOrNext)
498
- partialObserver = {
499
- next: observerOrNext != null ? observerOrNext : void 0,
500
- error: error != null ? error : void 0,
501
- complete: complete != null ? complete : void 0
502
- };
503
- else {
504
- var context_1;
505
- _this && config.useDeprecatedNextContext ? (context_1 = Object.create(observerOrNext), context_1.unsubscribe = function() {
506
- return _this.unsubscribe();
507
- }, partialObserver = {
508
- next: observerOrNext.next && bind(observerOrNext.next, context_1),
509
- error: observerOrNext.error && bind(observerOrNext.error, context_1),
510
- complete: observerOrNext.complete && bind(observerOrNext.complete, context_1)
511
- }) : partialObserver = observerOrNext;
512
- }
513
- return _this.destination = new ConsumerObserver(partialObserver), _this;
514
- }
515
- return SafeSubscriber2;
516
- }(Subscriber);
517
- function handleUnhandledError(error) {
518
- reportUnhandledError(error);
519
- }
520
- function defaultErrorHandler(err) {
521
- throw err;
522
- }
523
- var EMPTY_OBSERVER = {
524
- closed: !0,
525
- next: noop,
526
- error: defaultErrorHandler,
527
- complete: noop
528
- };
529
- function hasLift(source) {
530
- return isFunction(source == null ? void 0 : source.lift);
531
- }
532
- function operate(init) {
533
- return function(source) {
534
- if (hasLift(source))
535
- return source.lift(function(liftedSource) {
536
- try {
537
- return init(liftedSource, this);
538
- } catch (err) {
539
- this.error(err);
540
- }
541
- });
542
- throw new TypeError("Unable to lift unknown Observable type");
543
- };
544
- }
545
- function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
546
- return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
547
- }
548
- var OperatorSubscriber = function(_super) {
549
- __extends(OperatorSubscriber2, _super);
550
- function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
551
- var _this = _super.call(this, destination) || this;
552
- return _this.onFinalize = onFinalize, _this.shouldUnsubscribe = shouldUnsubscribe, _this._next = onNext ? function(value) {
553
- try {
554
- onNext(value);
555
- } catch (err) {
556
- destination.error(err);
557
- }
558
- } : _super.prototype._next, _this._error = onError ? function(err) {
559
- try {
560
- onError(err);
561
- } catch (err2) {
562
- destination.error(err2);
563
- } finally {
564
- this.unsubscribe();
565
- }
566
- } : _super.prototype._error, _this._complete = onComplete ? function() {
567
- try {
568
- onComplete();
569
- } catch (err) {
570
- destination.error(err);
571
- } finally {
572
- this.unsubscribe();
573
- }
574
- } : _super.prototype._complete, _this;
575
- }
576
- return OperatorSubscriber2.prototype.unsubscribe = function() {
577
- var _a;
578
- if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
579
- var closed_1 = this.closed;
580
- _super.prototype.unsubscribe.call(this), !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 || _a.call(this));
581
- }
582
- }, OperatorSubscriber2;
583
- }(Subscriber), EmptyError = createErrorClass(function(_super) {
584
- return function() {
585
- _super(this), this.name = "EmptyError", this.message = "no elements in sequence";
586
- };
587
- });
588
- function firstValueFrom(source, config2) {
589
- return new Promise(function(resolve, reject) {
590
- var subscriber = new SafeSubscriber({
591
- next: function(value) {
592
- resolve(value), subscriber.unsubscribe();
593
- },
594
- error: reject,
595
- complete: function() {
596
- reject(new EmptyError());
597
- }
598
- });
599
- source.subscribe(subscriber);
600
- });
601
- }
602
- function filter(predicate, thisArg) {
603
- return operate(function(source, subscriber) {
604
- var index = 0;
605
- source.subscribe(createOperatorSubscriber(subscriber, function(value) {
606
- return predicate.call(thisArg, value, index++) && subscriber.next(value);
607
- }));
608
- });
609
- }
610
- const query = `*[_type == $translationSchema && $id in translations[].value._ref]{
611
- _id,
612
- _createdAt,
613
- translations
614
- }`;
615
- function useTranslationMetadata(id) {
616
- const { data, loading, error } = useListeningQuery(query, {
617
- params: { id, translationSchema: METADATA_SCHEMA_NAME }
618
- });
619
- return { data, loading, error };
620
- }
621
- const documenti18nLocaleNamespace = "document-internationalization", documentInternationalizationUsEnglishLocaleBundle = defineLocaleResourceBundle({
622
- locale: "en-US",
623
- namespace: documenti18nLocaleNamespace,
624
- resources: () => import("./_chunks-es/resources.mjs")
625
- }), DISABLED_REASON_KEY = {
626
- METADATA_NOT_FOUND: "action.duplicate.disabled.missing-metadata",
627
- MULTIPLE_METADATA: "action.duplicate.disabled.multiple-metadata",
628
- NOTHING_TO_DUPLICATE: "action.duplicate.disabled.nothing-to-duplicate",
629
- NOT_READY: "action.duplicate.disabled.not-ready"
630
- }, DuplicateWithTranslationsAction = ({
631
- id,
632
- type,
633
- onComplete
634
- }) => {
635
- const documentStore = useDocumentStore(), { duplicate } = useDocumentOperation(id, type), { navigateIntent } = useRouter(), [isDuplicating, setDuplicating] = useState(!1), [permissions, isPermissionsLoading] = useDocumentPairPermissions({
636
- id,
637
- type,
638
- permission: "duplicate"
639
- }), { data, loading: isMetadataDocumentLoading } = useTranslationMetadata(id), hasOneMetadataDocument = useMemo(() => Array.isArray(data) && data.length <= 1, [data]), metadataDocument = Array.isArray(data) && data.length ? data[0] : null, client = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS), toast = useToast(), { t: s } = useTranslation(structureLocaleNamespace), { t: d } = useTranslation(documenti18nLocaleNamespace), currentUser = useCurrentUser(), handle = useCallback(async () => {
640
- setDuplicating(!0);
641
- try {
642
- if (!metadataDocument)
643
- throw new Error("Metadata document not found");
644
- const translations = /* @__PURE__ */ new Map();
645
- await Promise.all(
646
- metadataDocument[TRANSLATIONS_ARRAY_NAME].map(async (translation) => {
647
- var _a;
648
- const dupeId2 = uuid(), locale = translation._key, docId = (_a = translation.value) == null ? void 0 : _a._ref;
649
- if (!docId)
650
- throw new Error("Translation document not found");
651
- const { duplicate: duplicateTranslation } = await firstValueFrom(
652
- documentStore.pair.editOperations(docId, type).pipe(filter((op) => op.duplicate.disabled !== "NOT_READY"))
653
- );
654
- if (duplicateTranslation.disabled)
655
- throw new Error("Cannot duplicate document");
656
- const duplicateTranslationSuccess = firstValueFrom(
657
- documentStore.pair.operationEvents(docId, type).pipe(filter((e) => e.op === "duplicate" && e.type === "success"))
658
- );
659
- duplicateTranslation.execute(dupeId2), await duplicateTranslationSuccess, translations.set(locale, dupeId2);
660
- })
661
- );
662
- const { duplicate: duplicateMetadata } = await firstValueFrom(
663
- documentStore.pair.editOperations(metadataDocument._id, METADATA_SCHEMA_NAME).pipe(filter((op) => op.duplicate.disabled !== "NOT_READY"))
664
- );
665
- if (duplicateMetadata.disabled)
666
- throw new Error("Cannot duplicate document");
667
- const duplicateMetadataSuccess = firstValueFrom(
668
- documentStore.pair.operationEvents(metadataDocument._id, METADATA_SCHEMA_NAME).pipe(filter((e) => e.op === "duplicate" && e.type === "success"))
669
- ), dupeId = uuid();
670
- duplicateMetadata.execute(dupeId), await duplicateMetadataSuccess;
671
- const patch = {
672
- set: Object.fromEntries(
673
- Array.from(translations.entries()).map(([locale, documentId]) => [
674
- `${TRANSLATIONS_ARRAY_NAME}[_key == "${locale}"].value._ref`,
675
- documentId
676
- ])
677
- )
678
- };
679
- await client.transaction().patch(dupeId, patch).commit(), navigateIntent("edit", {
680
- id: Array.from(translations.values()).at(0),
681
- type
682
- }), onComplete();
683
- } catch (error) {
684
- console.error(error), toast.push({
685
- status: "error",
686
- title: "Error duplicating document",
687
- description: error instanceof Error ? error.message : "Failed to duplicate document"
688
- });
689
- } finally {
690
- setDuplicating(!1);
691
- }
692
- }, [
693
- client,
694
- documentStore.pair,
695
- metadataDocument,
696
- navigateIntent,
697
- onComplete,
698
- toast,
699
- type
700
- ]);
701
- return useMemo(() => !isPermissionsLoading && !(permissions != null && permissions.granted) ? {
702
- icon: CopyIcon,
703
- disabled: !0,
704
- label: d("action.duplicate.label"),
705
- title: /* @__PURE__ */ jsx(
706
- InsufficientPermissionsMessage,
707
- {
708
- context: "duplicate-document",
709
- currentUser
710
- }
711
- )
712
- } : !isMetadataDocumentLoading && !metadataDocument ? {
713
- icon: CopyIcon,
714
- disabled: !0,
715
- label: d("action.duplicate.label"),
716
- title: d(DISABLED_REASON_KEY.METADATA_NOT_FOUND)
717
- } : hasOneMetadataDocument ? {
718
- icon: CopyIcon,
719
- disabled: isDuplicating || !!duplicate.disabled || isPermissionsLoading || isMetadataDocumentLoading,
720
- label: isDuplicating ? s("action.duplicate.running.label") : d("action.duplicate.label"),
721
- title: duplicate.disabled ? s(DISABLED_REASON_KEY[duplicate.disabled]) : "",
722
- onHandle: handle
723
- } : {
724
- icon: CopyIcon,
725
- disabled: !0,
726
- label: d("action.duplicate.label"),
727
- title: d(DISABLED_REASON_KEY.MULTIPLE_METADATA)
728
- }, [
729
- currentUser,
730
- duplicate.disabled,
731
- handle,
732
- hasOneMetadataDocument,
733
- isDuplicating,
734
- isMetadataDocumentLoading,
735
- isPermissionsLoading,
736
- metadataDocument,
737
- permissions == null ? void 0 : permissions.granted,
738
- s,
739
- d
740
- ]);
741
- };
742
- DuplicateWithTranslationsAction.action = "duplicate";
743
- DuplicateWithTranslationsAction.displayName = "DuplicateWithTranslationsAction";
744
- function useOpenInNewPane(id, type) {
745
- const routerContext = useContext(RouterContext), { routerPanesState, groupIndex } = usePaneRouter();
746
- return useCallback(() => {
747
- if (!routerContext || !id || !type)
748
- return;
749
- if (!routerPanesState.length) {
750
- routerContext.navigateIntent("edit", { id, type });
751
- return;
752
- }
753
- const panes = [...routerPanesState];
754
- panes.splice(groupIndex + 1, 0, [
755
- {
756
- id,
757
- params: { type }
758
- }
759
- ]);
760
- const href = routerContext.resolvePathFromState({ panes });
761
- routerContext.navigateUrl({ path: href });
762
- }, [id, type, routerContext, routerPanesState, groupIndex]);
763
- }
764
- var __defProp$2 = Object.defineProperty, __getOwnPropSymbols$2 = Object.getOwnPropertySymbols, __hasOwnProp$2 = Object.prototype.hasOwnProperty, __propIsEnum$2 = Object.prototype.propertyIsEnumerable, __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$2 = (a, b) => {
765
- for (var prop in b || (b = {}))
766
- __hasOwnProp$2.call(b, prop) && __defNormalProp$2(a, prop, b[prop]);
767
- if (__getOwnPropSymbols$2)
768
- for (var prop of __getOwnPropSymbols$2(b))
769
- __propIsEnum$2.call(b, prop) && __defNormalProp$2(a, prop, b[prop]);
770
- return a;
771
- };
772
- function createReference(key, ref, type, strengthenOnPublish = !0) {
773
- return {
774
- _key: key,
775
- _type: "internationalizedArrayReferenceValue",
776
- value: __spreadValues$2({
777
- _type: "reference",
778
- _ref: ref,
779
- _weak: !0
780
- }, strengthenOnPublish ? { _strengthenOnPublish: { type } } : {})
781
- };
782
- }
783
- function LanguageManage(props) {
784
- const { id, metadataId, schemaType, documentId, sourceLanguageId } = props, open = useOpenInNewPane(id, METADATA_SCHEMA_NAME), openCreated = useOpenInNewPane(metadataId, METADATA_SCHEMA_NAME), { allowCreateMetaDoc, apiVersion, weakReferences } = useDocumentInternationalizationContext(), client = useClient({ apiVersion }), [userHasClicked, setUserHasClicked] = useState(!1), canCreate = !id && !!metadataId && allowCreateMetaDoc, handleClick = useCallback(() => {
785
- if (!id && metadataId && sourceLanguageId) {
786
- setUserHasClicked(!0);
787
- const transaction = client.transaction(), sourceReference = createReference(
788
- sourceLanguageId,
789
- documentId,
790
- schemaType.name,
791
- !weakReferences
792
- ), newMetadataDocument = {
793
- _id: metadataId,
794
- _type: METADATA_SCHEMA_NAME,
795
- schemaTypes: [schemaType.name],
796
- translations: [sourceReference]
797
- };
798
- transaction.createIfNotExists(newMetadataDocument), transaction.commit().then(() => {
799
- setUserHasClicked(!1), openCreated();
800
- }).catch((err) => {
801
- console.error(err), setUserHasClicked(!1);
802
- });
803
- } else
804
- open();
805
- }, [
806
- id,
807
- metadataId,
808
- sourceLanguageId,
809
- client,
810
- documentId,
811
- schemaType.name,
812
- weakReferences,
813
- openCreated,
814
- open
815
- ]);
816
- return /* @__PURE__ */ jsx(
817
- Tooltip,
818
- {
819
- animate: !0,
820
- content: /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: "Document has no other translations" }) }),
821
- fallbackPlacements: ["right", "left"],
822
- placement: "top",
823
- portal: !0,
824
- disabled: !!id || canCreate,
825
- children: /* @__PURE__ */ jsx(Stack, { children: /* @__PURE__ */ jsx(
826
- Button,
827
- {
828
- disabled: !id && !canCreate || canCreate && !sourceLanguageId || userHasClicked,
829
- mode: "ghost",
830
- text: "Manage Translations",
831
- icon: CogIcon,
832
- loading: userHasClicked,
833
- onClick: handleClick
834
- }
835
- ) })
836
- }
837
- );
838
- }
839
- function removeExcludedPaths(doc, schemaType) {
840
- if (!isDocumentSchemaType(schemaType) || !doc)
841
- return doc;
842
- const pathsToExclude = extractPaths(doc, schemaType, []).filter(
843
- (field) => {
844
- var _a, _b, _c;
845
- return ((_c = (_b = (_a = field.schemaType) == null ? void 0 : _a.options) == null ? void 0 : _b.documentInternationalization) == null ? void 0 : _c.exclude) === !0;
846
- }
847
- ).map((field) => pathToString(field.path));
848
- return new Mutation({
849
- mutations: [
850
- {
851
- patch: {
852
- id: doc._id,
853
- unset: pathsToExclude
854
- }
855
- }
856
- ]
857
- }).apply(doc);
858
- }
859
- function extractPaths(doc, schemaType, path) {
860
- return schemaType.fields.reduce((acc, field) => {
861
- var _a, _b;
862
- const fieldPath = [...path, field.name], fieldSchema = field.type, { value } = (_a = extractWithPath(pathToString(fieldPath), doc)[0]) != null ? _a : {};
863
- if (!value)
864
- return acc;
865
- const thisFieldWithPath = {
866
- path: fieldPath,
867
- name: field.name,
868
- schemaType: fieldSchema,
869
- value
870
- };
871
- if (fieldSchema.jsonType === "object") {
872
- const innerFields = extractPaths(doc, fieldSchema, fieldPath);
873
- return [...acc, thisFieldWithPath, ...innerFields];
874
- } else if (fieldSchema.jsonType === "array" && fieldSchema.of.length && fieldSchema.of.some((item) => "fields" in item)) {
875
- const { value: arrayValue } = (_b = extractWithPath(pathToString(fieldPath), doc)[0]) != null ? _b : {};
876
- let arrayPaths = [];
877
- if (arrayValue != null && arrayValue.length)
878
- for (const item of arrayValue) {
879
- const itemPath = [...fieldPath, { _key: item._key }];
880
- let itemSchema = fieldSchema.of.find((t) => t.name === item._type);
881
- if (item._type || (itemSchema = fieldSchema.of[0]), item._key && itemSchema) {
882
- const innerFields = extractPaths(
883
- doc,
884
- itemSchema,
885
- itemPath
886
- ), arrayMember = {
887
- path: itemPath,
888
- name: item._key,
889
- schemaType: itemSchema,
890
- value: item
891
- };
892
- arrayPaths = [...arrayPaths, arrayMember, ...innerFields];
893
- }
894
- }
895
- return [...acc, thisFieldWithPath, ...arrayPaths];
896
- }
897
- return [...acc, thisFieldWithPath];
898
- }, []);
899
- }
900
- var __defProp$1 = Object.defineProperty, __defProps$1 = Object.defineProperties, __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$1 = Object.getOwnPropertySymbols, __hasOwnProp$1 = Object.prototype.hasOwnProperty, __propIsEnum$1 = Object.prototype.propertyIsEnumerable, __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$1 = (a, b) => {
901
- for (var prop in b || (b = {}))
902
- __hasOwnProp$1.call(b, prop) && __defNormalProp$1(a, prop, b[prop]);
903
- if (__getOwnPropSymbols$1)
904
- for (var prop of __getOwnPropSymbols$1(b))
905
- __propIsEnum$1.call(b, prop) && __defNormalProp$1(a, prop, b[prop]);
906
- return a;
907
- }, __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
908
- function LanguageOption(props) {
909
- var _a;
910
- const {
911
- language,
912
- schemaType,
913
- documentId,
914
- current,
915
- source,
916
- sourceLanguageId,
917
- metadata: metadata2,
918
- metadataId
919
- } = props, [userHasClicked, setUserHasClicked] = useState(!1), disabled = props.disabled || userHasClicked || current || !source || !sourceLanguageId || !metadataId, translation = metadata2 != null && metadata2.translations.length ? metadata2.translations.find((t) => t._key === language.id) : void 0, { apiVersion, languageField, weakReferences, callback } = 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]);
920
- useEffect(() => {
921
- setUserHasClicked(!1);
922
- }, [!!translation]);
923
- const handleCreate = useCallback(async () => {
924
- if (!source)
925
- throw new Error("Cannot create translation without source document");
926
- if (!sourceLanguageId)
927
- throw new Error("Cannot create translation without source language ID");
928
- if (!metadataId)
929
- throw new Error("Cannot create translation without a metadata ID");
930
- setUserHasClicked(!0);
931
- const transaction = client.transaction(), newTranslationDocumentId = uuid();
932
- let newTranslationDocument = __spreadProps$1(__spreadValues$1({}, source), {
933
- _id: `drafts.${newTranslationDocumentId}`,
934
- // 2. Update language of the translation
935
- [languageField]: language.id
936
- });
937
- newTranslationDocument = removeExcludedPaths(
938
- newTranslationDocument,
939
- schemaType
940
- ), transaction.create(newTranslationDocument);
941
- const sourceReference = createReference(
942
- sourceLanguageId,
943
- documentId,
944
- schemaType.name,
945
- !weakReferences
946
- ), newTranslationReference = createReference(
947
- language.id,
948
- newTranslationDocumentId,
949
- schemaType.name,
950
- !weakReferences
951
- ), newMetadataDocument = {
952
- _id: metadataId,
953
- _type: METADATA_SCHEMA_NAME,
954
- schemaTypes: [schemaType.name],
955
- translations: [sourceReference]
956
- };
957
- transaction.createIfNotExists(newMetadataDocument);
958
- const metadataPatch = client.patch(metadataId).setIfMissing({ translations: [sourceReference] }).insert("after", "translations[-1]", [newTranslationReference]);
959
- transaction.patch(metadataPatch), transaction.commit().then(() => {
960
- const metadataExisted = !!(metadata2 != null && metadata2._createdAt);
961
- return callback == null || callback({
962
- client,
963
- sourceLanguageId,
964
- sourceDocument: source,
965
- newDocument: newTranslationDocument,
966
- destinationLanguageId: language.id,
967
- metaDocumentId: metadataId
968
- }).catch((err) => {
969
- toast.push({
970
- status: "error",
971
- title: "Callback",
972
- description: `Error while running callback - ${err}.`
973
- });
974
- }), toast.push({
975
- status: "success",
976
- title: `Created "${language.title}" translation`,
977
- description: metadataExisted ? "Updated Translations Metadata" : "Created Translations Metadata"
978
- });
979
- }).catch((err) => (console.error(err), setUserHasClicked(!1), toast.push({
980
- status: "error",
981
- title: "Error creating translation",
982
- description: err.message
983
- })));
984
- }, [
985
- client,
986
- documentId,
987
- language.id,
988
- language.title,
989
- languageField,
990
- metadata2 == null ? void 0 : metadata2._createdAt,
991
- metadataId,
992
- schemaType,
993
- source,
994
- sourceLanguageId,
995
- toast,
996
- weakReferences,
997
- callback
998
- ]);
999
- let message;
1000
- return current ? message = "Current document" : translation ? message = `Open ${language.title} translation` : translation || (message = `Create new ${language.title} translation`), /* @__PURE__ */ jsx(
1001
- Tooltip,
1002
- {
1003
- animate: !0,
1004
- content: /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: message }) }),
1005
- fallbackPlacements: ["right", "left"],
1006
- placement: "top",
1007
- portal: !0,
1008
- children: /* @__PURE__ */ jsx(
1009
- Button,
1010
- {
1011
- onClick: translation ? handleOpen : handleCreate,
1012
- mode: current && disabled ? "default" : "bleed",
1013
- disabled,
1014
- children: /* @__PURE__ */ jsxs(Flex, { gap: 3, align: "center", children: [
1015
- disabled && !current ? /* @__PURE__ */ jsx(Spinner, {}) : /* @__PURE__ */ jsx(Text, { size: 2, children: translation ? /* @__PURE__ */ jsx(SplitVerticalIcon, {}) : current ? /* @__PURE__ */ jsx(CheckmarkIcon, {}) : /* @__PURE__ */ jsx(AddIcon, {}) }),
1016
- /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Text, { children: language.title }) }),
1017
- /* @__PURE__ */ jsx(Badge, { tone: disabled || current ? "default" : "primary", children: language.id })
1018
- ] })
1019
- }
1020
- )
1021
- }
1022
- );
1023
- }
1024
- function LanguagePatch(props) {
1025
- const { language, source } = props, { apiVersion, languageField } = useDocumentInternationalizationContext(), disabled = props.disabled || !source, client = useClient({ apiVersion }), toast = useToast(), handleClick = useCallback(() => {
1026
- if (!source)
1027
- throw new Error("Cannot patch missing document");
1028
- const currentId = source._id;
1029
- client.patch(currentId).set({ [languageField]: language.id }).commit().then(() => {
1030
- toast.push({
1031
- title: `Set document language to ${language.title}`,
1032
- status: "success"
1033
- });
1034
- }).catch((err) => (console.error(err), toast.push({
1035
- title: `Failed to set document language to ${language.title}`,
1036
- status: "error"
1037
- })));
1038
- }, [source, client, languageField, language, toast]);
1039
- return /* @__PURE__ */ jsx(
1040
- Button,
1041
- {
1042
- mode: "bleed",
1043
- onClick: handleClick,
1044
- disabled,
1045
- justify: "flex-start",
1046
- children: /* @__PURE__ */ jsxs(Flex, { gap: 3, align: "center", children: [
1047
- /* @__PURE__ */ jsx(Text, { size: 2, children: /* @__PURE__ */ jsx(EditIcon, {}) }),
1048
- /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Text, { children: language.title }) }),
1049
- /* @__PURE__ */ jsx(Badge, { children: language.id })
1050
- ] })
1051
- }
1052
- );
1053
- }
1054
- var ConstrainedBox = styled(Box)`
1055
- max-width: 280px;
1056
- `;
1057
- function Warning({ children }) {
1058
- 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 }) }) }) });
1059
- }
1060
- function DocumentInternationalizationMenu(props) {
1061
- const { documentId } = props, schemaType = props.schemaType, { languageField, supportedLanguages } = useDocumentInternationalizationContext(), [query2, setQuery] = useState(""), handleQuery = useCallback((event) => {
1062
- event.currentTarget.value ? setQuery(event.currentTarget.value) : setQuery("");
1063
- }, []), [open, setOpen] = useState(!1), handleClick = useCallback(() => setOpen((o) => !o), []), [button, setButton] = useState(null), [popover, setPopover] = useState(null), handleClickOutside = useCallback(() => setOpen(!1), []);
1064
- useClickOutside(handleClickOutside, [button, popover]);
1065
- const { data, loading, error } = useTranslationMetadata(documentId), metadata2 = Array.isArray(data) && data.length ? data[0] : null, metadataId = useMemo(() => {
1066
- var _a;
1067
- return loading ? null : (_a = metadata2 == null ? void 0 : metadata2._id) != null ? _a : uuid();
1068
- }, [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(
1069
- (l) => l.id === sourceLanguageId
1070
- ), allLanguagesAreValid = useMemo(() => {
1071
- const valid = supportedLanguages.every((l) => l.id && l.title);
1072
- return valid || console.warn(
1073
- '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.',
1074
- supportedLanguages
1075
- ), valid;
1076
- }, [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: [
1077
- /* @__PURE__ */ jsx(
1078
- LanguageManage,
1079
- {
1080
- id: metadata2 == null ? void 0 : metadata2._id,
1081
- documentId,
1082
- metadataId,
1083
- schemaType,
1084
- sourceLanguageId
1085
- }
1086
- ),
1087
- supportedLanguages.length > 4 ? /* @__PURE__ */ jsx(
1088
- TextInput,
1089
- {
1090
- onChange: handleQuery,
1091
- value: query2,
1092
- placeholder: "Filter languages"
1093
- }
1094
- ) : null,
1095
- supportedLanguages.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
1096
- loading ? null : /* @__PURE__ */ jsxs(Fragment, { children: [
1097
- data && documentIsInOneMetadataDocument ? null : /* @__PURE__ */ jsx(Warning, { children: "This document has been found in more than one Translations Metadata documents" }),
1098
- allLanguagesAreValid ? null : /* @__PURE__ */ jsx(Warning, { children: "Not all language objects are valid. See the console." }),
1099
- sourceLanguageId ? null : /* @__PURE__ */ jsxs(Warning, { children: [
1100
- "Choose a language to apply to",
1101
- " ",
1102
- /* @__PURE__ */ jsx("strong", { children: "this Document" })
1103
- ] }),
1104
- sourceLanguageId && !sourceLanguageIsValid ? /* @__PURE__ */ jsxs(Warning, { children: [
1105
- "Select a supported language. Current language value:",
1106
- " ",
1107
- /* @__PURE__ */ jsx("code", { children: sourceLanguageId })
1108
- ] }) : null
1109
- ] }),
1110
- supportedLanguages.filter((language) => query2 ? language.title.toLowerCase().includes(query2.toLowerCase()) : !0).map(
1111
- (language) => {
1112
- var _a;
1113
- return !loading && sourceLanguageId && sourceLanguageIsValid ? (
1114
- // Button to duplicate this document to a new translation
1115
- // And either create or update the metadata document
1116
- /* @__PURE__ */ jsx(
1117
- LanguageOption,
1118
- {
1119
- language,
1120
- schemaType,
1121
- documentId,
1122
- disabled: loading || !allLanguagesAreValid,
1123
- current: language.id === sourceLanguageId,
1124
- metadata: metadata2,
1125
- metadataId,
1126
- source,
1127
- sourceLanguageId
1128
- },
1129
- language.id
1130
- )
1131
- ) : (
1132
- // Button to set a language field on *this* document
1133
- /* @__PURE__ */ jsx(
1134
- LanguagePatch,
1135
- {
1136
- source,
1137
- language,
1138
- disabled: (_a = loading || !allLanguagesAreValid || (metadata2 == null ? void 0 : metadata2.translations.filter((t) => {
1139
- var _a2;
1140
- return ((_a2 = t == null ? void 0 : t.value) == null ? void 0 : _a2._ref) !== documentId;
1141
- }).some((t) => t._key === language.id))) != null ? _a : !1
1142
- },
1143
- language.id
1144
- )
1145
- );
1146
- }
1147
- )
1148
- ] }) : null
1149
- ] }) }), issueWithTranslations = !loading && sourceLanguageId && !sourceLanguageIsValid;
1150
- return !documentId || !schemaType || !schemaType.name ? null : /* @__PURE__ */ jsx(
1151
- Popover,
1152
- {
1153
- animate: !0,
1154
- constrainSize: !0,
1155
- content,
1156
- open,
1157
- portal: !0,
1158
- ref: setPopover,
1159
- overflow: "auto",
1160
- tone: "default",
1161
- children: /* @__PURE__ */ jsx(
1162
- Button,
1163
- {
1164
- text: "Translations",
1165
- mode: "bleed",
1166
- disabled: !source,
1167
- tone: !source || loading || !issueWithTranslations ? void 0 : "caution",
1168
- icon: TranslateIcon,
1169
- onClick: handleClick,
1170
- ref: setButton,
1171
- selected: open
1172
- }
1173
- )
1174
- }
1175
- );
1176
- }
1177
- const DeleteMetadataAction = (props) => {
1178
- const { id: documentId, published, draft, onComplete } = props, doc = draft || published, [isDialogOpen, setDialogOpen] = useState(!1), onClose = useCallback(() => setDialogOpen(!1), []), translations = useMemo(
1179
- () => doc && Array.isArray(doc[TRANSLATIONS_ARRAY_NAME]) ? doc[TRANSLATIONS_ARRAY_NAME] : [],
1180
- [doc]
1181
- ), toast = useToast(), client = useClient({ apiVersion: API_VERSION }), onProceed = useCallback(() => {
1182
- const tx = client.transaction();
1183
- tx.patch(documentId, (patch) => patch.unset([TRANSLATIONS_ARRAY_NAME])), translations.length > 0 && translations.forEach((translation) => {
1184
- tx.delete(translation.value._ref), tx.delete(`drafts.${translation.value._ref}`);
1185
- }), tx.delete(documentId), tx.delete(`drafts.${documentId}`), tx.commit().then(() => {
1186
- onClose(), toast.push({
1187
- status: "success",
1188
- title: "Deleted document and translations"
1189
- });
1190
- }).catch((err) => {
1191
- toast.push({
1192
- status: "error",
1193
- title: "Failed to delete document and translations",
1194
- description: err.message
1195
- });
1196
- });
1197
- }, [client, translations, documentId, onClose, toast]);
1198
- return {
1199
- label: "Delete all translations",
1200
- disabled: !doc || !translations.length,
1201
- icon: TrashIcon,
1202
- tone: "critical",
1203
- onHandle: () => {
1204
- setDialogOpen(!0);
1205
- },
1206
- dialog: isDialogOpen && {
1207
- type: "confirm",
1208
- onCancel: onComplete,
1209
- onConfirm: () => {
1210
- onProceed(), onComplete();
1211
- },
1212
- tone: "critical",
1213
- message: translations.length === 1 ? "Delete 1 translation and this document" : `Delete all ${translations.length} translations and this document`
1214
- }
1215
- };
1216
- };
1217
- function LanguageBadge(props) {
1218
- var _a, _b;
1219
- const source = (props == null ? void 0 : props.draft) || (props == null ? void 0 : props.published), { languageField, supportedLanguages } = useDocumentInternationalizationContext(), languageId = source == null ? void 0 : source[languageField];
1220
- if (!languageId)
1221
- return null;
1222
- const language = Array.isArray(supportedLanguages) ? supportedLanguages.find((l) => l.id === languageId) : null;
1223
- return {
1224
- label: (_a = language == null ? void 0 : language.id) != null ? _a : String(languageId),
1225
- title: (_b = language == null ? void 0 : language.title) != null ? _b : void 0,
1226
- color: "primary"
1227
- };
1228
- }
1229
- function DocumentCheck(props) {
1230
- const {
1231
- id,
1232
- onCheckComplete,
1233
- addInvalidId,
1234
- removeInvalidId,
1235
- addDraftId,
1236
- removeDraftId
1237
- } = props, editState = useEditState(id, ""), { isValidating, validation } = useValidationStatus(id, ""), schema = useSchema(), validationHasErrors = useMemo(() => !isValidating && validation.length > 0 && validation.some((item) => item.level === "error"), [isValidating, validation]);
1238
- if (useEffect(() => {
1239
- validationHasErrors ? addInvalidId(id) : removeInvalidId(id), editState.draft ? addDraftId(id) : removeDraftId(id), isValidating || onCheckComplete(id);
1240
- }, [
1241
- addDraftId,
1242
- addInvalidId,
1243
- editState.draft,
1244
- id,
1245
- isValidating,
1246
- onCheckComplete,
1247
- removeDraftId,
1248
- removeInvalidId,
1249
- validationHasErrors
1250
- ]), !editState.draft)
1251
- return null;
1252
- const schemaType = schema.get(editState.draft._type);
1253
- return /* @__PURE__ */ jsx(
1254
- Card,
1255
- {
1256
- border: !0,
1257
- padding: 2,
1258
- tone: validationHasErrors ? "critical" : "positive",
1259
- children: editState.draft && schemaType ? /* @__PURE__ */ jsx(
1260
- Preview,
1261
- {
1262
- layout: "default",
1263
- value: editState.draft,
1264
- schemaType
1265
- }
1266
- ) : /* @__PURE__ */ jsx(Spinner, {})
1267
- }
1268
- );
1269
- }
1270
- function InfoIcon(props) {
1271
- const { text, icon, tone, children } = props;
1272
- return /* @__PURE__ */ jsx(
1273
- Tooltip,
1274
- {
1275
- animate: !0,
1276
- portal: !0,
1277
- content: children ? /* @__PURE__ */ jsx(Fragment, { children }) : /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { size: 1, children: text }) }),
1278
- children: /* @__PURE__ */ jsx(TextWithTone, { tone, size: 1, children: /* @__PURE__ */ jsx(icon, {}) })
1279
- }
1280
- );
1281
- }
1282
- function Info() {
1283
- return /* @__PURE__ */ jsx(InfoIcon, { icon: InfoOutlineIcon, tone: "primary", children: /* @__PURE__ */ jsxs(Stack, { padding: 3, space: 4, style: { maxWidth: 250 }, children: [
1284
- /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { size: 1, children: "Bulk publishing uses the Scheduling API." }) }),
1285
- /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { size: 1, children: "Customized Document Actions in the Studio will not execute. Webhooks will execute." }) }),
1286
- /* @__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." }) })
1287
- ] }) });
1288
- }
1289
- function BulkPublish(props) {
1290
- const { translations } = props, client = useClient({ apiVersion: API_VERSION }), { projectId, dataset } = useWorkspace(), toast = useToast(), [invalidIds, setInvalidIds] = useState(null), [checkedIds, setCheckedIds] = useState([]), onCheckComplete = useCallback((id) => {
1291
- setCheckedIds((ids) => Array.from(/* @__PURE__ */ new Set([...ids, id])));
1292
- }, []), [open, setOpen] = useState(!1), onOpen = useCallback(() => setOpen(!0), []), onClose = useCallback(() => setOpen(!1), []), addInvalidId = useCallback((id) => {
1293
- setInvalidIds((ids) => ids ? Array.from(/* @__PURE__ */ new Set([...ids, id])) : [id]);
1294
- }, []), removeInvalidId = useCallback((id) => {
1295
- setInvalidIds((ids) => ids ? ids.filter((i) => i !== id) : []);
1296
- }, []), [draftIds, setDraftIds] = useState([]), addDraftId = useCallback((id) => {
1297
- setDraftIds((ids) => Array.from(/* @__PURE__ */ new Set([...ids, id])));
1298
- }, []), removeDraftId = useCallback((id) => {
1299
- setDraftIds((ids) => ids.filter((i) => i !== id));
1300
- }, []), handleBulkPublish = useCallback(() => {
1301
- const body = translations.map((translation) => ({
1302
- documentId: translation.value._ref
1303
- }));
1304
- client.request({
1305
- uri: `/publish/${projectId}/${dataset}`,
1306
- method: "POST",
1307
- body
1308
- }).then(() => {
1309
- toast.push({
1310
- status: "success",
1311
- title: "Success",
1312
- description: "Bulk publish complete"
1313
- });
1314
- }).catch((err) => {
1315
- console.error(err), toast.push({
1316
- status: "error",
1317
- title: "Error",
1318
- description: "Bulk publish failed"
1319
- });
1320
- });
1321
- }, [translations, client, projectId, dataset, toast]), disabled = (
1322
- // Not all documents have been checked
1323
- checkedIds.length !== translations.length || // Some document(s) are invalid
1324
- !!(invalidIds && (invalidIds == null ? void 0 : invalidIds.length) > 0) || // No documents are drafts
1325
- !draftIds.length
1326
- );
1327
- return (translations == null ? void 0 : translations.length) > 0 ? /* @__PURE__ */ jsx(Card, { padding: 4, border: !0, radius: 2, children: /* @__PURE__ */ jsxs(Stack, { space: 3, children: [
1328
- /* @__PURE__ */ jsxs(Inline, { space: 3, children: [
1329
- /* @__PURE__ */ jsx(Text, { weight: "bold", size: 1, children: "Bulk publishing" }),
1330
- /* @__PURE__ */ jsx(Info, {})
1331
- ] }),
1332
- /* @__PURE__ */ jsx(Stack, { children: /* @__PURE__ */ jsx(
1333
- Button,
1334
- {
1335
- onClick: onOpen,
1336
- text: "Prepare bulk publishing",
1337
- mode: "ghost"
1338
- }
1339
- ) }),
1340
- open && /* @__PURE__ */ jsx(
1341
- Dialog,
1342
- {
1343
- animate: !0,
1344
- header: "Bulk publishing",
1345
- id: "bulk-publish-dialog",
1346
- onClose,
1347
- zOffset: 1e3,
1348
- width: 3,
1349
- children: /* @__PURE__ */ jsxs(Stack, { space: 4, padding: 4, children: [
1350
- draftIds.length > 0 ? /* @__PURE__ */ jsxs(Stack, { space: 2, children: [
1351
- /* @__PURE__ */ jsxs(Text, { size: 1, children: [
1352
- "There",
1353
- " ",
1354
- draftIds.length === 1 ? "is 1 draft document" : `are ${draftIds.length} draft documents`,
1355
- "."
1356
- ] }),
1357
- invalidIds && invalidIds.length > 0 ? /* @__PURE__ */ jsxs(TextWithTone, { tone: "critical", size: 1, children: [
1358
- invalidIds && invalidIds.length === 1 ? "1 draft document has" : `${invalidIds && invalidIds.length} draft documents have`,
1359
- " ",
1360
- "validation issues that must addressed first"
1361
- ] }) : /* @__PURE__ */ jsx(TextWithTone, { tone: "positive", size: 1, children: "All drafts are valid and can be bulk published" })
1362
- ] }) : null,
1363
- /* @__PURE__ */ jsx(Stack, { space: 1, children: translations.filter((translation) => {
1364
- var _a;
1365
- return (_a = translation == null ? void 0 : translation.value) == null ? void 0 : _a._ref;
1366
- }).map((translation) => /* @__PURE__ */ jsx(
1367
- DocumentCheck,
1368
- {
1369
- id: translation.value._ref,
1370
- onCheckComplete,
1371
- addInvalidId,
1372
- removeInvalidId,
1373
- addDraftId,
1374
- removeDraftId
1375
- },
1376
- translation._key
1377
- )) }),
1378
- draftIds.length > 0 ? /* @__PURE__ */ jsx(
1379
- Button,
1380
- {
1381
- mode: "ghost",
1382
- tone: invalidIds && (invalidIds == null ? void 0 : invalidIds.length) > 0 ? "caution" : "positive",
1383
- text: draftIds.length === 1 ? "Publish draft document" : `Bulk publish ${draftIds.length} draft documents`,
1384
- onClick: handleBulkPublish,
1385
- disabled
1386
- }
1387
- ) : /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: "No draft documents to publish" })
1388
- ] })
1389
- }
1390
- )
1391
- ] }) }) : null;
1392
- }
1393
- function ReferencePatcher(props) {
1394
- const { translation, documentType, metadataId } = props, editState = useEditState(translation.value._ref, documentType), client = useClient({ apiVersion: API_VERSION }), { onChange } = useDocumentPane();
1395
- return useEffect(() => {
1396
- if (
1397
- // We have a reference
1398
- translation.value._ref && // It's still weak and not-yet-strengthened
1399
- translation.value._weak && // We also want to keep this check because maybe the user *configured* weak refs
1400
- translation.value._strengthenOnPublish && // The referenced document has just been published
1401
- !editState.draft && editState.published && editState.ready
1402
- ) {
1403
- const referencePathBase = [
1404
- "translations",
1405
- { _key: translation._key },
1406
- "value"
1407
- ];
1408
- onChange(
1409
- new PatchEvent([
1410
- unset([...referencePathBase, "_weak"]),
1411
- unset([...referencePathBase, "_strengthenOnPublish"])
1412
- ])
1413
- );
1414
- }
1415
- }, [translation, editState, metadataId, client, onChange]), null;
1416
- }
1417
- function OptimisticallyStrengthen(props) {
1418
- const { translations = [], metadataId } = props;
1419
- return translations.length ? /* @__PURE__ */ jsx(Fragment, { children: translations.map(
1420
- (translation) => {
1421
- var _a;
1422
- return (_a = translation.value._strengthenOnPublish) != null && _a.type ? /* @__PURE__ */ jsx(
1423
- ReferencePatcher,
1424
- {
1425
- translation,
1426
- documentType: translation.value._strengthenOnPublish.type,
1427
- metadataId
1428
- },
1429
- translation._key
1430
- ) : null;
1431
- }
1432
- ) }) : null;
1433
- }
1434
- var metadata = (schemaTypes, metadataFields) => defineType({
1435
- type: "document",
1436
- name: METADATA_SCHEMA_NAME,
1437
- title: "Translation metadata",
1438
- icon: TranslateIcon,
1439
- liveEdit: !0,
1440
- fields: [
1441
- defineField({
1442
- name: TRANSLATIONS_ARRAY_NAME,
1443
- type: "internationalizedArrayReference"
1444
- }),
1445
- defineField({
1446
- name: "schemaTypes",
1447
- description: "Optional: Used to filter the reference fields above so all translations share the same types.",
1448
- type: "array",
1449
- of: [{ type: "string" }],
1450
- options: { list: schemaTypes },
1451
- readOnly: ({ value }) => !!value
1452
- }),
1453
- ...metadataFields
1454
- ],
1455
- preview: {
1456
- select: {
1457
- translations: TRANSLATIONS_ARRAY_NAME,
1458
- documentSchemaTypes: "schemaTypes"
1459
- },
1460
- prepare(selection) {
1461
- const { translations = [], documentSchemaTypes = [] } = selection, title = translations.length === 1 ? "1 Translation" : `${translations.length} Translations`, languageKeys = translations.length ? translations.map((t) => t._key.toUpperCase()).join(", ") : "", subtitle = [
1462
- languageKeys ? `(${languageKeys})` : null,
1463
- documentSchemaTypes != null && documentSchemaTypes.length ? documentSchemaTypes.map((s) => s).join(", ") : ""
1464
- ].filter(Boolean).join(" ");
1465
- return {
1466
- title,
1467
- subtitle
1468
- };
1469
- }
1470
- }
1471
- }), __defProp = Object.defineProperty, __defProps = Object.defineProperties, __getOwnPropDescs = Object.getOwnPropertyDescriptors, __getOwnPropSymbols = Object.getOwnPropertySymbols, __hasOwnProp = Object.prototype.hasOwnProperty, __propIsEnum = Object.prototype.propertyIsEnumerable, __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues = (a, b) => {
1472
- for (var prop in b || (b = {}))
1473
- __hasOwnProp.call(b, prop) && __defNormalProp(a, prop, b[prop]);
1474
- if (__getOwnPropSymbols)
1475
- for (var prop of __getOwnPropSymbols(b))
1476
- __propIsEnum.call(b, prop) && __defNormalProp(a, prop, b[prop]);
1477
- return a;
1478
- }, __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1479
- const documentInternationalization = definePlugin(
1480
- (config2) => {
1481
- const pluginConfig = __spreadValues(__spreadValues({}, DEFAULT_CONFIG), config2), {
1482
- supportedLanguages,
1483
- schemaTypes,
1484
- languageField,
1485
- bulkPublish,
1486
- metadataFields
1487
- } = pluginConfig;
1488
- if (schemaTypes.length === 0)
1489
- throw new Error(
1490
- "You must specify at least one schema type on which to enable document internationalization. Update the `schemaTypes` option in the documentInternationalization() configuration."
1491
- );
1492
- return {
1493
- name: "@sanity/document-internationalization",
1494
- studio: {
1495
- components: {
1496
- layout: (props) => DocumentInternationalizationProvider(__spreadProps(__spreadValues({}, props), { pluginConfig }))
1497
- }
1498
- },
1499
- i18n: {
1500
- bundles: [documentInternationalizationUsEnglishLocaleBundle]
1501
- },
1502
- // Adds:
1503
- // - A bulk-publishing UI component to the form
1504
- // - Will only work for projects on a compatible plan
1505
- form: {
1506
- components: {
1507
- input: (props) => {
1508
- var _a, _b, _c;
1509
- if (props.id === "root" && props.schemaType.name === METADATA_SCHEMA_NAME && isSanityDocument(props == null ? void 0 : props.value)) {
1510
- 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(
1511
- ({ value }) => (value == null ? void 0 : value._weak) && value._strengthenOnPublish
1512
- );
1513
- return /* @__PURE__ */ jsxs(Stack, { space: 5, children: [
1514
- bulkPublish ? /* @__PURE__ */ jsx(BulkPublish, { translations }) : null,
1515
- weakAndTypedTranslations.length > 0 ? /* @__PURE__ */ jsx(
1516
- OptimisticallyStrengthen,
1517
- {
1518
- metadataId,
1519
- translations: weakAndTypedTranslations
1520
- }
1521
- ) : null,
1522
- props.renderDefault(props)
1523
- ] });
1524
- }
1525
- return props.renderDefault(props);
1526
- }
1527
- }
1528
- },
1529
- // Adds:
1530
- // - The `Translations` dropdown to the editing form
1531
- // - `Badges` to documents with a language value
1532
- // - The `DeleteMetadataAction` action to the metadata document type
1533
- document: {
1534
- unstable_languageFilter: (prev, ctx) => {
1535
- const { schemaType, documentId } = ctx;
1536
- return schemaTypes.includes(schemaType) && documentId ? [
1537
- ...prev,
1538
- (props) => DocumentInternationalizationMenu(__spreadProps(__spreadValues({}, props), { documentId }))
1539
- ] : prev;
1540
- },
1541
- badges: (prev, { schemaType }) => schemaTypes.includes(schemaType) ? [(props) => LanguageBadge(props), ...prev] : prev,
1542
- actions: (prev, { schemaType }) => schemaType === METADATA_SCHEMA_NAME ? [...prev, DeleteMetadataAction] : prev
1543
- },
1544
- // Adds:
1545
- // - The `Translations metadata` document type to the schema
1546
- schema: {
1547
- // Create the metadata document type
1548
- types: [metadata(schemaTypes, metadataFields)],
1549
- // For every schema type this plugin is enabled on
1550
- // Create an initial value template to set the language
1551
- templates: (prev, { schema }) => {
1552
- if (!Array.isArray(supportedLanguages))
1553
- return prev;
1554
- const parameterizedTemplates = schemaTypes.map((schemaType) => {
1555
- var _a, _b;
1556
- return {
1557
- id: `${schemaType}-parameterized`,
1558
- title: `${(_b = (_a = schema == null ? void 0 : schema.get(schemaType)) == null ? void 0 : _a.title) != null ? _b : schemaType}: with Language`,
1559
- schemaType,
1560
- parameters: [
1561
- { name: "languageId", title: "Language ID", type: "string" }
1562
- ],
1563
- value: ({ languageId }) => ({
1564
- [languageField]: languageId
1565
- })
1566
- };
1567
- }), staticTemplates = schemaTypes.flatMap((schemaType) => supportedLanguages.map((language) => {
1568
- var _a, _b;
1569
- return {
1570
- id: `${schemaType}-${language.id}`,
1571
- title: `${language.title} ${(_b = (_a = schema == null ? void 0 : schema.get(schemaType)) == null ? void 0 : _a.title) != null ? _b : schemaType}`,
1572
- schemaType,
1573
- value: {
1574
- [languageField]: language.id
1575
- }
1576
- };
1577
- }));
1578
- return [...prev, ...parameterizedTemplates, ...staticTemplates];
1579
- }
1580
- },
1581
- // Uses:
1582
- // - `sanity-plugin-internationalized-array` to maintain the translations array
1583
- plugins: [
1584
- // Translation metadata stores its references using this plugin
1585
- // It cuts down on attribute usage and gives UI conveniences to add new translations
1586
- internationalizedArray({
1587
- apiVersion: pluginConfig.apiVersion,
1588
- languages: supportedLanguages,
1589
- fieldTypes: [
1590
- defineField(
1591
- {
1592
- name: "reference",
1593
- type: "reference",
1594
- to: schemaTypes.map((type) => ({ type })),
1595
- weak: pluginConfig.weakReferences,
1596
- // Reference filters don't actually enforce validation!
1597
- validation: (Rule) => (
1598
- // @ts-expect-error - fix typings
1599
- Rule.custom(async (item, context) => {
1600
- var _a;
1601
- if (!((_a = item == null ? void 0 : item.value) != null && _a._ref) || !(item != null && item._key))
1602
- return !0;
1603
- const valueLanguage = await context.getClient({ apiVersion: API_VERSION }).fetch(
1604
- `*[_id in [$ref, $draftRef]][0].${languageField}`,
1605
- {
1606
- ref: item.value._ref,
1607
- draftRef: `drafts.${item.value._ref}`
1608
- }
1609
- );
1610
- return valueLanguage && valueLanguage === item._key ? !0 : "Referenced document does not have the correct language value";
1611
- })
1612
- ),
1613
- options: {
1614
- // @ts-expect-error - Update type once it knows the values of this filter
1615
- filter: ({ parent, document }) => {
1616
- if (!parent)
1617
- return null;
1618
- const language = (Array.isArray(parent) ? parent : [parent]).find((p) => p._key);
1619
- return language != null && language._key ? document.schemaTypes ? {
1620
- filter: `_type in $schemaTypes && ${languageField} == $language`,
1621
- params: {
1622
- schemaTypes: document.schemaTypes,
1623
- language: language._key
1624
- }
1625
- } : {
1626
- filter: `${languageField} == $language`,
1627
- params: { language: language._key }
1628
- } : null;
1629
- }
1630
- }
1631
- },
1632
- { strict: !1 }
1633
- )
1634
- ]
1635
- })
1636
- ]
1637
- };
1638
- }
1639
- );
1640
- export {
1641
- DeleteTranslationAction,
1642
- DocumentInternationalizationMenu,
1643
- DuplicateWithTranslationsAction,
1644
- documentInternationalization,
1645
- useDocumentInternationalizationContext
1646
- };
1647
- //# sourceMappingURL=index.mjs.map