@sanity/document-internationalization 4.1.1 → 5.0.1

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 +44 -36
  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 +112 -88
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +1075 -1337
  8. package/dist/index.js.map +1 -1
  9. package/package.json +35 -69
  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 -108
  15. package/dist/index.esm.js +0 -1625
  16. package/dist/index.esm.js.map +0 -1
  17. package/dist/index.mjs +0 -1625
  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 -97
  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.esm.js DELETED
@@ -1,1625 +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, config = {}) {
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 config.lifespan && config.lifespan > 0 && (entry2.timeout && clearTimeout(entry2.timeout), entry2.timeout = setTimeout(entry2.remove, config.lifespan)), entry2.response;
125
- if (!preload)
126
- throw entry2.promise;
127
- }
128
- const entry = {
129
- keys,
130
- equal: config.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, config.lifespan && config.lifespan > 0 && (entry.timeout = setTimeout(entry.remove, config.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, config) => query$1(fn, keys, !1, config);
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 timeoutProvider = {
404
- setTimeout: function(handler, timeout) {
405
- for (var args = [], _i = 2; _i < arguments.length; _i++)
406
- args[_i - 2] = arguments[_i];
407
- return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
408
- },
409
- clearTimeout: function(handle) {
410
- return clearTimeout(handle);
411
- },
412
- delegate: void 0
413
- };
414
- function reportUnhandledError(err) {
415
- timeoutProvider.setTimeout(function() {
416
- throw err;
417
- });
418
- }
419
- function noop() {
420
- }
421
- var Subscriber = function(_super) {
422
- __extends(Subscriber2, _super);
423
- function Subscriber2(destination) {
424
- var _this = _super.call(this) || this;
425
- return _this.isStopped = !1, destination ? (_this.destination = destination, isSubscription(destination) && destination.add(_this)) : _this.destination = EMPTY_OBSERVER, _this;
426
- }
427
- return Subscriber2.create = function(next, error, complete) {
428
- return new SafeSubscriber(next, error, complete);
429
- }, Subscriber2.prototype.next = function(value) {
430
- this.isStopped || this._next(value);
431
- }, Subscriber2.prototype.error = function(err) {
432
- this.isStopped || (this.isStopped = !0, this._error(err));
433
- }, Subscriber2.prototype.complete = function() {
434
- this.isStopped || (this.isStopped = !0, this._complete());
435
- }, Subscriber2.prototype.unsubscribe = function() {
436
- this.closed || (this.isStopped = !0, _super.prototype.unsubscribe.call(this), this.destination = null);
437
- }, Subscriber2.prototype._next = function(value) {
438
- this.destination.next(value);
439
- }, Subscriber2.prototype._error = function(err) {
440
- try {
441
- this.destination.error(err);
442
- } finally {
443
- this.unsubscribe();
444
- }
445
- }, Subscriber2.prototype._complete = function() {
446
- try {
447
- this.destination.complete();
448
- } finally {
449
- this.unsubscribe();
450
- }
451
- }, Subscriber2;
452
- }(Subscription), ConsumerObserver = function() {
453
- function ConsumerObserver2(partialObserver) {
454
- this.partialObserver = partialObserver;
455
- }
456
- return ConsumerObserver2.prototype.next = function(value) {
457
- var partialObserver = this.partialObserver;
458
- if (partialObserver.next)
459
- try {
460
- partialObserver.next(value);
461
- } catch (error) {
462
- handleUnhandledError(error);
463
- }
464
- }, ConsumerObserver2.prototype.error = function(err) {
465
- var partialObserver = this.partialObserver;
466
- if (partialObserver.error)
467
- try {
468
- partialObserver.error(err);
469
- } catch (error) {
470
- handleUnhandledError(error);
471
- }
472
- else
473
- handleUnhandledError(err);
474
- }, ConsumerObserver2.prototype.complete = function() {
475
- var partialObserver = this.partialObserver;
476
- if (partialObserver.complete)
477
- try {
478
- partialObserver.complete();
479
- } catch (error) {
480
- handleUnhandledError(error);
481
- }
482
- }, ConsumerObserver2;
483
- }(), SafeSubscriber = function(_super) {
484
- __extends(SafeSubscriber2, _super);
485
- function SafeSubscriber2(observerOrNext, error, complete) {
486
- var _this = _super.call(this) || this, partialObserver;
487
- return isFunction(observerOrNext) || !observerOrNext ? partialObserver = {
488
- next: observerOrNext != null ? observerOrNext : void 0,
489
- error: error != null ? error : void 0,
490
- complete: complete != null ? complete : void 0
491
- } : partialObserver = observerOrNext, _this.destination = new ConsumerObserver(partialObserver), _this;
492
- }
493
- return SafeSubscriber2;
494
- }(Subscriber);
495
- function handleUnhandledError(error) {
496
- reportUnhandledError(error);
497
- }
498
- function defaultErrorHandler(err) {
499
- throw err;
500
- }
501
- var EMPTY_OBSERVER = {
502
- closed: !0,
503
- next: noop,
504
- error: defaultErrorHandler,
505
- complete: noop
506
- };
507
- function hasLift(source) {
508
- return isFunction(source == null ? void 0 : source.lift);
509
- }
510
- function operate(init) {
511
- return function(source) {
512
- if (hasLift(source))
513
- return source.lift(function(liftedSource) {
514
- try {
515
- return init(liftedSource, this);
516
- } catch (err) {
517
- this.error(err);
518
- }
519
- });
520
- throw new TypeError("Unable to lift unknown Observable type");
521
- };
522
- }
523
- function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
524
- return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
525
- }
526
- var OperatorSubscriber = function(_super) {
527
- __extends(OperatorSubscriber2, _super);
528
- function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
529
- var _this = _super.call(this, destination) || this;
530
- return _this.onFinalize = onFinalize, _this.shouldUnsubscribe = shouldUnsubscribe, _this._next = onNext ? function(value) {
531
- try {
532
- onNext(value);
533
- } catch (err) {
534
- destination.error(err);
535
- }
536
- } : _super.prototype._next, _this._error = onError ? function(err) {
537
- try {
538
- onError(err);
539
- } catch (err2) {
540
- destination.error(err2);
541
- } finally {
542
- this.unsubscribe();
543
- }
544
- } : _super.prototype._error, _this._complete = onComplete ? function() {
545
- try {
546
- onComplete();
547
- } catch (err) {
548
- destination.error(err);
549
- } finally {
550
- this.unsubscribe();
551
- }
552
- } : _super.prototype._complete, _this;
553
- }
554
- return OperatorSubscriber2.prototype.unsubscribe = function() {
555
- var _a;
556
- if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
557
- var closed_1 = this.closed;
558
- _super.prototype.unsubscribe.call(this), !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 || _a.call(this));
559
- }
560
- }, OperatorSubscriber2;
561
- }(Subscriber), EmptyError = createErrorClass(function(_super) {
562
- return function() {
563
- _super(this), this.name = "EmptyError", this.message = "no elements in sequence";
564
- };
565
- });
566
- function firstValueFrom(source, config) {
567
- return new Promise(function(resolve, reject) {
568
- var subscriber = new SafeSubscriber({
569
- next: function(value) {
570
- resolve(value), subscriber.unsubscribe();
571
- },
572
- error: reject,
573
- complete: function() {
574
- reject(new EmptyError());
575
- }
576
- });
577
- source.subscribe(subscriber);
578
- });
579
- }
580
- function filter(predicate, thisArg) {
581
- return operate(function(source, subscriber) {
582
- var index = 0;
583
- source.subscribe(createOperatorSubscriber(subscriber, function(value) {
584
- return predicate.call(thisArg, value, index++) && subscriber.next(value);
585
- }));
586
- });
587
- }
588
- const query = `*[_type == $translationSchema && $id in translations[].value._ref]{
589
- _id,
590
- _createdAt,
591
- translations
592
- }`;
593
- function useTranslationMetadata(id) {
594
- const { data, loading, error } = useListeningQuery(query, {
595
- params: { id, translationSchema: METADATA_SCHEMA_NAME }
596
- });
597
- return { data, loading, error };
598
- }
599
- const documenti18nLocaleNamespace = "document-internationalization", documentInternationalizationUsEnglishLocaleBundle = defineLocaleResourceBundle({
600
- locale: "en-US",
601
- namespace: documenti18nLocaleNamespace,
602
- resources: () => import("./_legacy/resources.esm.js")
603
- }), DISABLED_REASON_KEY = {
604
- METADATA_NOT_FOUND: "action.duplicate.disabled.missing-metadata",
605
- MULTIPLE_METADATA: "action.duplicate.disabled.multiple-metadata",
606
- NOTHING_TO_DUPLICATE: "action.duplicate.disabled.nothing-to-duplicate",
607
- NOT_READY: "action.duplicate.disabled.not-ready"
608
- }, DuplicateWithTranslationsAction = ({
609
- id,
610
- type,
611
- onComplete
612
- }) => {
613
- const documentStore = useDocumentStore(), { duplicate } = useDocumentOperation(id, type), { navigateIntent } = useRouter(), [isDuplicating, setDuplicating] = useState(!1), [permissions, isPermissionsLoading] = useDocumentPairPermissions({
614
- id,
615
- type,
616
- permission: "duplicate"
617
- }), { 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 () => {
618
- setDuplicating(!0);
619
- try {
620
- if (!metadataDocument)
621
- throw new Error("Metadata document not found");
622
- const translations = /* @__PURE__ */ new Map();
623
- await Promise.all(
624
- metadataDocument[TRANSLATIONS_ARRAY_NAME].map(async (translation) => {
625
- var _a;
626
- const dupeId2 = uuid(), locale = translation._key, docId = (_a = translation.value) == null ? void 0 : _a._ref;
627
- if (!docId)
628
- throw new Error("Translation document not found");
629
- const { duplicate: duplicateTranslation } = await firstValueFrom(
630
- documentStore.pair.editOperations(docId, type).pipe(filter((op) => op.duplicate.disabled !== "NOT_READY"))
631
- );
632
- if (duplicateTranslation.disabled)
633
- throw new Error("Cannot duplicate document");
634
- const duplicateTranslationSuccess = firstValueFrom(
635
- documentStore.pair.operationEvents(docId, type).pipe(filter((e) => e.op === "duplicate" && e.type === "success"))
636
- );
637
- duplicateTranslation.execute(dupeId2), await duplicateTranslationSuccess, translations.set(locale, dupeId2);
638
- })
639
- );
640
- const { duplicate: duplicateMetadata } = await firstValueFrom(
641
- documentStore.pair.editOperations(metadataDocument._id, METADATA_SCHEMA_NAME).pipe(filter((op) => op.duplicate.disabled !== "NOT_READY"))
642
- );
643
- if (duplicateMetadata.disabled)
644
- throw new Error("Cannot duplicate document");
645
- const duplicateMetadataSuccess = firstValueFrom(
646
- documentStore.pair.operationEvents(metadataDocument._id, METADATA_SCHEMA_NAME).pipe(filter((e) => e.op === "duplicate" && e.type === "success"))
647
- ), dupeId = uuid();
648
- duplicateMetadata.execute(dupeId), await duplicateMetadataSuccess;
649
- const patch = {
650
- set: Object.fromEntries(
651
- Array.from(translations.entries()).map(([locale, documentId]) => [
652
- `${TRANSLATIONS_ARRAY_NAME}[_key == "${locale}"].value._ref`,
653
- documentId
654
- ])
655
- )
656
- };
657
- await client.transaction().patch(dupeId, patch).commit(), navigateIntent("edit", {
658
- id: Array.from(translations.values()).at(0),
659
- type
660
- }), onComplete();
661
- } catch (error) {
662
- console.error(error), toast.push({
663
- status: "error",
664
- title: "Error duplicating document",
665
- description: error instanceof Error ? error.message : "Failed to duplicate document"
666
- });
667
- } finally {
668
- setDuplicating(!1);
669
- }
670
- }, [
671
- client,
672
- documentStore.pair,
673
- metadataDocument,
674
- navigateIntent,
675
- onComplete,
676
- toast,
677
- type
678
- ]);
679
- return useMemo(() => !isPermissionsLoading && !(permissions != null && permissions.granted) ? {
680
- icon: CopyIcon,
681
- disabled: !0,
682
- label: d("action.duplicate.label"),
683
- title: /* @__PURE__ */ jsx(
684
- InsufficientPermissionsMessage,
685
- {
686
- context: "duplicate-document",
687
- currentUser
688
- }
689
- )
690
- } : !isMetadataDocumentLoading && !metadataDocument ? {
691
- icon: CopyIcon,
692
- disabled: !0,
693
- label: d("action.duplicate.label"),
694
- title: d(DISABLED_REASON_KEY.METADATA_NOT_FOUND)
695
- } : hasOneMetadataDocument ? {
696
- icon: CopyIcon,
697
- disabled: isDuplicating || !!duplicate.disabled || isPermissionsLoading || isMetadataDocumentLoading,
698
- label: isDuplicating ? s("action.duplicate.running.label") : d("action.duplicate.label"),
699
- title: duplicate.disabled ? s(DISABLED_REASON_KEY[duplicate.disabled]) : "",
700
- onHandle: handle
701
- } : {
702
- icon: CopyIcon,
703
- disabled: !0,
704
- label: d("action.duplicate.label"),
705
- title: d(DISABLED_REASON_KEY.MULTIPLE_METADATA)
706
- }, [
707
- currentUser,
708
- duplicate.disabled,
709
- handle,
710
- hasOneMetadataDocument,
711
- isDuplicating,
712
- isMetadataDocumentLoading,
713
- isPermissionsLoading,
714
- metadataDocument,
715
- permissions == null ? void 0 : permissions.granted,
716
- s,
717
- d
718
- ]);
719
- };
720
- DuplicateWithTranslationsAction.action = "duplicate";
721
- DuplicateWithTranslationsAction.displayName = "DuplicateWithTranslationsAction";
722
- function useOpenInNewPane(id, type) {
723
- const routerContext = useContext(RouterContext), { routerPanesState, groupIndex } = usePaneRouter();
724
- return useCallback(() => {
725
- if (!routerContext || !id || !type)
726
- return;
727
- if (!routerPanesState.length) {
728
- routerContext.navigateIntent("edit", { id, type });
729
- return;
730
- }
731
- const panes = [...routerPanesState];
732
- panes.splice(groupIndex + 1, 0, [
733
- {
734
- id,
735
- params: { type }
736
- }
737
- ]);
738
- const href = routerContext.resolvePathFromState({ panes });
739
- routerContext.navigateUrl({ path: href });
740
- }, [id, type, routerContext, routerPanesState, groupIndex]);
741
- }
742
- 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) => {
743
- for (var prop in b || (b = {}))
744
- __hasOwnProp$2.call(b, prop) && __defNormalProp$2(a, prop, b[prop]);
745
- if (__getOwnPropSymbols$2)
746
- for (var prop of __getOwnPropSymbols$2(b))
747
- __propIsEnum$2.call(b, prop) && __defNormalProp$2(a, prop, b[prop]);
748
- return a;
749
- };
750
- function createReference(key, ref, type, strengthenOnPublish = !0) {
751
- return {
752
- _key: key,
753
- _type: "internationalizedArrayReferenceValue",
754
- value: __spreadValues$2({
755
- _type: "reference",
756
- _ref: ref,
757
- _weak: !0
758
- }, strengthenOnPublish ? { _strengthenOnPublish: { type } } : {})
759
- };
760
- }
761
- function LanguageManage(props) {
762
- 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(() => {
763
- if (!id && metadataId && sourceLanguageId) {
764
- setUserHasClicked(!0);
765
- const transaction = client.transaction(), sourceReference = createReference(
766
- sourceLanguageId,
767
- documentId,
768
- schemaType.name,
769
- !weakReferences
770
- ), newMetadataDocument = {
771
- _id: metadataId,
772
- _type: METADATA_SCHEMA_NAME,
773
- schemaTypes: [schemaType.name],
774
- translations: [sourceReference]
775
- };
776
- transaction.createIfNotExists(newMetadataDocument), transaction.commit().then(() => {
777
- setUserHasClicked(!1), openCreated();
778
- }).catch((err) => {
779
- console.error(err), setUserHasClicked(!1);
780
- });
781
- } else
782
- open();
783
- }, [
784
- id,
785
- metadataId,
786
- sourceLanguageId,
787
- client,
788
- documentId,
789
- schemaType.name,
790
- weakReferences,
791
- openCreated,
792
- open
793
- ]);
794
- return /* @__PURE__ */ jsx(
795
- Tooltip,
796
- {
797
- animate: !0,
798
- content: /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: "Document has no other translations" }) }),
799
- fallbackPlacements: ["right", "left"],
800
- placement: "top",
801
- portal: !0,
802
- disabled: !!id || canCreate,
803
- children: /* @__PURE__ */ jsx(Stack, { children: /* @__PURE__ */ jsx(
804
- Button,
805
- {
806
- disabled: !id && !canCreate || canCreate && !sourceLanguageId || userHasClicked,
807
- mode: "ghost",
808
- text: "Manage Translations",
809
- icon: CogIcon,
810
- loading: userHasClicked,
811
- onClick: handleClick
812
- }
813
- ) })
814
- }
815
- );
816
- }
817
- function removeExcludedPaths(doc, schemaType) {
818
- if (!isDocumentSchemaType(schemaType) || !doc)
819
- return doc;
820
- const pathsToExclude = extractPaths(doc, schemaType, []).filter(
821
- (field) => {
822
- var _a, _b, _c;
823
- return ((_c = (_b = (_a = field.schemaType) == null ? void 0 : _a.options) == null ? void 0 : _b.documentInternationalization) == null ? void 0 : _c.exclude) === !0;
824
- }
825
- ).map((field) => pathToString(field.path));
826
- return new Mutation({
827
- mutations: [
828
- {
829
- patch: {
830
- id: doc._id,
831
- unset: pathsToExclude
832
- }
833
- }
834
- ]
835
- }).apply(doc);
836
- }
837
- function extractPaths(doc, schemaType, path) {
838
- return schemaType.fields.reduce((acc, field) => {
839
- var _a, _b;
840
- const fieldPath = [...path, field.name], fieldSchema = field.type, { value } = (_a = extractWithPath(pathToString(fieldPath), doc)[0]) != null ? _a : {};
841
- if (!value)
842
- return acc;
843
- const thisFieldWithPath = {
844
- path: fieldPath,
845
- name: field.name,
846
- schemaType: fieldSchema,
847
- value
848
- };
849
- if (fieldSchema.jsonType === "object") {
850
- const innerFields = extractPaths(doc, fieldSchema, fieldPath);
851
- return [...acc, thisFieldWithPath, ...innerFields];
852
- } else if (fieldSchema.jsonType === "array" && fieldSchema.of.length && fieldSchema.of.some((item) => "fields" in item)) {
853
- const { value: arrayValue } = (_b = extractWithPath(pathToString(fieldPath), doc)[0]) != null ? _b : {};
854
- let arrayPaths = [];
855
- if (arrayValue != null && arrayValue.length)
856
- for (const item of arrayValue) {
857
- const itemPath = [...fieldPath, { _key: item._key }];
858
- let itemSchema = fieldSchema.of.find((t) => t.name === item._type);
859
- if (item._type || (itemSchema = fieldSchema.of[0]), item._key && itemSchema) {
860
- const innerFields = extractPaths(
861
- doc,
862
- itemSchema,
863
- itemPath
864
- ), arrayMember = {
865
- path: itemPath,
866
- name: item._key,
867
- schemaType: itemSchema,
868
- value: item
869
- };
870
- arrayPaths = [...arrayPaths, arrayMember, ...innerFields];
871
- }
872
- }
873
- return [...acc, thisFieldWithPath, ...arrayPaths];
874
- }
875
- return [...acc, thisFieldWithPath];
876
- }, []);
877
- }
878
- 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) => {
879
- for (var prop in b || (b = {}))
880
- __hasOwnProp$1.call(b, prop) && __defNormalProp$1(a, prop, b[prop]);
881
- if (__getOwnPropSymbols$1)
882
- for (var prop of __getOwnPropSymbols$1(b))
883
- __propIsEnum$1.call(b, prop) && __defNormalProp$1(a, prop, b[prop]);
884
- return a;
885
- }, __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
886
- function LanguageOption(props) {
887
- var _a;
888
- const {
889
- language,
890
- schemaType,
891
- documentId,
892
- current,
893
- source,
894
- sourceLanguageId,
895
- metadata: metadata2,
896
- metadataId
897
- } = 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]);
898
- useEffect(() => {
899
- setUserHasClicked(!1);
900
- }, [!!translation]);
901
- const handleCreate = useCallback(async () => {
902
- if (!source)
903
- throw new Error("Cannot create translation without source document");
904
- if (!sourceLanguageId)
905
- throw new Error("Cannot create translation without source language ID");
906
- if (!metadataId)
907
- throw new Error("Cannot create translation without a metadata ID");
908
- setUserHasClicked(!0);
909
- const transaction = client.transaction(), newTranslationDocumentId = uuid();
910
- let newTranslationDocument = __spreadProps$1(__spreadValues$1({}, source), {
911
- _id: `drafts.${newTranslationDocumentId}`,
912
- // 2. Update language of the translation
913
- [languageField]: language.id
914
- });
915
- newTranslationDocument = removeExcludedPaths(
916
- newTranslationDocument,
917
- schemaType
918
- ), transaction.create(newTranslationDocument);
919
- const sourceReference = createReference(
920
- sourceLanguageId,
921
- documentId,
922
- schemaType.name,
923
- !weakReferences
924
- ), newTranslationReference = createReference(
925
- language.id,
926
- newTranslationDocumentId,
927
- schemaType.name,
928
- !weakReferences
929
- ), newMetadataDocument = {
930
- _id: metadataId,
931
- _type: METADATA_SCHEMA_NAME,
932
- schemaTypes: [schemaType.name],
933
- translations: [sourceReference]
934
- };
935
- transaction.createIfNotExists(newMetadataDocument);
936
- const metadataPatch = client.patch(metadataId).setIfMissing({ translations: [sourceReference] }).insert("after", "translations[-1]", [newTranslationReference]);
937
- transaction.patch(metadataPatch), transaction.commit().then(() => {
938
- const metadataExisted = !!(metadata2 != null && metadata2._createdAt);
939
- return callback == null || callback({
940
- client,
941
- sourceLanguageId,
942
- sourceDocument: source,
943
- newDocument: newTranslationDocument,
944
- destinationLanguageId: language.id,
945
- metaDocumentId: metadataId
946
- }).catch((err) => {
947
- toast.push({
948
- status: "error",
949
- title: "Callback",
950
- description: `Error while running callback - ${err}.`
951
- });
952
- }), toast.push({
953
- status: "success",
954
- title: `Created "${language.title}" translation`,
955
- description: metadataExisted ? "Updated Translations Metadata" : "Created Translations Metadata"
956
- });
957
- }).catch((err) => (console.error(err), setUserHasClicked(!1), toast.push({
958
- status: "error",
959
- title: "Error creating translation",
960
- description: err.message
961
- })));
962
- }, [
963
- client,
964
- documentId,
965
- language.id,
966
- language.title,
967
- languageField,
968
- metadata2 == null ? void 0 : metadata2._createdAt,
969
- metadataId,
970
- schemaType,
971
- source,
972
- sourceLanguageId,
973
- toast,
974
- weakReferences,
975
- callback
976
- ]);
977
- let message;
978
- return current ? message = "Current document" : translation ? message = `Open ${language.title} translation` : translation || (message = `Create new ${language.title} translation`), /* @__PURE__ */ jsx(
979
- Tooltip,
980
- {
981
- animate: !0,
982
- content: /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: message }) }),
983
- fallbackPlacements: ["right", "left"],
984
- placement: "top",
985
- portal: !0,
986
- children: /* @__PURE__ */ jsx(
987
- Button,
988
- {
989
- onClick: translation ? handleOpen : handleCreate,
990
- mode: current && disabled ? "default" : "bleed",
991
- disabled,
992
- children: /* @__PURE__ */ jsxs(Flex, { gap: 3, align: "center", children: [
993
- disabled && !current ? /* @__PURE__ */ jsx(Spinner, {}) : /* @__PURE__ */ jsx(Text, { size: 2, children: translation ? /* @__PURE__ */ jsx(SplitVerticalIcon, {}) : current ? /* @__PURE__ */ jsx(CheckmarkIcon, {}) : /* @__PURE__ */ jsx(AddIcon, {}) }),
994
- /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Text, { children: language.title }) }),
995
- /* @__PURE__ */ jsx(Badge, { tone: disabled || current ? "default" : "primary", children: language.id })
996
- ] })
997
- }
998
- )
999
- }
1000
- );
1001
- }
1002
- function LanguagePatch(props) {
1003
- const { language, source } = props, { apiVersion, languageField } = useDocumentInternationalizationContext(), disabled = props.disabled || !source, client = useClient({ apiVersion }), toast = useToast(), handleClick = useCallback(() => {
1004
- if (!source)
1005
- throw new Error("Cannot patch missing document");
1006
- const currentId = source._id;
1007
- client.patch(currentId).set({ [languageField]: language.id }).commit().then(() => {
1008
- toast.push({
1009
- title: `Set document language to ${language.title}`,
1010
- status: "success"
1011
- });
1012
- }).catch((err) => (console.error(err), toast.push({
1013
- title: `Failed to set document language to ${language.title}`,
1014
- status: "error"
1015
- })));
1016
- }, [source, client, languageField, language, toast]);
1017
- return /* @__PURE__ */ jsx(
1018
- Button,
1019
- {
1020
- mode: "bleed",
1021
- onClick: handleClick,
1022
- disabled,
1023
- justify: "flex-start",
1024
- children: /* @__PURE__ */ jsxs(Flex, { gap: 3, align: "center", children: [
1025
- /* @__PURE__ */ jsx(Text, { size: 2, children: /* @__PURE__ */ jsx(EditIcon, {}) }),
1026
- /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Text, { children: language.title }) }),
1027
- /* @__PURE__ */ jsx(Badge, { children: language.id })
1028
- ] })
1029
- }
1030
- );
1031
- }
1032
- var ConstrainedBox = styled(Box)`
1033
- max-width: 280px;
1034
- `;
1035
- function Warning({ children }) {
1036
- 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 }) }) }) });
1037
- }
1038
- function DocumentInternationalizationMenu(props) {
1039
- const { documentId } = props, schemaType = props.schemaType, { languageField, supportedLanguages } = useDocumentInternationalizationContext(), [query2, setQuery] = useState(""), handleQuery = useCallback((event) => {
1040
- event.currentTarget.value ? setQuery(event.currentTarget.value) : setQuery("");
1041
- }, []), [open, setOpen] = useState(!1), handleClick = useCallback(() => setOpen((o) => !o), []), [button, setButton] = useState(null), [popover, setPopover] = useState(null), handleClickOutside = useCallback(() => setOpen(!1), []);
1042
- useClickOutside(handleClickOutside, [button, popover]);
1043
- const { data, loading, error } = useTranslationMetadata(documentId), metadata2 = Array.isArray(data) && data.length ? data[0] : null, metadataId = useMemo(() => {
1044
- var _a;
1045
- return loading ? null : (_a = metadata2 == null ? void 0 : metadata2._id) != null ? _a : uuid();
1046
- }, [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(
1047
- (l) => l.id === sourceLanguageId
1048
- ), allLanguagesAreValid = useMemo(() => {
1049
- const valid = supportedLanguages.every((l) => l.id && l.title);
1050
- return valid || console.warn(
1051
- '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.',
1052
- supportedLanguages
1053
- ), valid;
1054
- }, [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: [
1055
- /* @__PURE__ */ jsx(
1056
- LanguageManage,
1057
- {
1058
- id: metadata2 == null ? void 0 : metadata2._id,
1059
- documentId,
1060
- metadataId,
1061
- schemaType,
1062
- sourceLanguageId
1063
- }
1064
- ),
1065
- supportedLanguages.length > 4 ? /* @__PURE__ */ jsx(
1066
- TextInput,
1067
- {
1068
- onChange: handleQuery,
1069
- value: query2,
1070
- placeholder: "Filter languages"
1071
- }
1072
- ) : null,
1073
- supportedLanguages.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
1074
- loading ? null : /* @__PURE__ */ jsxs(Fragment, { children: [
1075
- data && documentIsInOneMetadataDocument ? null : /* @__PURE__ */ jsx(Warning, { children: "This document has been found in more than one Translations Metadata documents" }),
1076
- allLanguagesAreValid ? null : /* @__PURE__ */ jsx(Warning, { children: "Not all language objects are valid. See the console." }),
1077
- sourceLanguageId ? null : /* @__PURE__ */ jsxs(Warning, { children: [
1078
- "Choose a language to apply to",
1079
- " ",
1080
- /* @__PURE__ */ jsx("strong", { children: "this Document" })
1081
- ] }),
1082
- sourceLanguageId && !sourceLanguageIsValid ? /* @__PURE__ */ jsxs(Warning, { children: [
1083
- "Select a supported language. Current language value:",
1084
- " ",
1085
- /* @__PURE__ */ jsx("code", { children: sourceLanguageId })
1086
- ] }) : null
1087
- ] }),
1088
- supportedLanguages.filter((language) => query2 ? language.title.toLowerCase().includes(query2.toLowerCase()) : !0).map(
1089
- (language) => {
1090
- var _a;
1091
- return !loading && sourceLanguageId && sourceLanguageIsValid ? (
1092
- // Button to duplicate this document to a new translation
1093
- // And either create or update the metadata document
1094
- /* @__PURE__ */ jsx(
1095
- LanguageOption,
1096
- {
1097
- language,
1098
- schemaType,
1099
- documentId,
1100
- disabled: loading || !allLanguagesAreValid,
1101
- current: language.id === sourceLanguageId,
1102
- metadata: metadata2,
1103
- metadataId,
1104
- source,
1105
- sourceLanguageId
1106
- },
1107
- language.id
1108
- )
1109
- ) : (
1110
- // Button to set a language field on *this* document
1111
- /* @__PURE__ */ jsx(
1112
- LanguagePatch,
1113
- {
1114
- source,
1115
- language,
1116
- disabled: (_a = loading || !allLanguagesAreValid || (metadata2 == null ? void 0 : metadata2.translations.filter((t) => {
1117
- var _a2;
1118
- return ((_a2 = t == null ? void 0 : t.value) == null ? void 0 : _a2._ref) !== documentId;
1119
- }).some((t) => t._key === language.id))) != null ? _a : !1
1120
- },
1121
- language.id
1122
- )
1123
- );
1124
- }
1125
- )
1126
- ] }) : null
1127
- ] }) }), issueWithTranslations = !loading && sourceLanguageId && !sourceLanguageIsValid;
1128
- return !documentId || !schemaType || !schemaType.name ? null : /* @__PURE__ */ jsx(
1129
- Popover,
1130
- {
1131
- animate: !0,
1132
- constrainSize: !0,
1133
- content,
1134
- open,
1135
- portal: !0,
1136
- ref: setPopover,
1137
- overflow: "auto",
1138
- tone: "default",
1139
- children: /* @__PURE__ */ jsx(
1140
- Button,
1141
- {
1142
- text: "Translations",
1143
- mode: "bleed",
1144
- disabled: !source,
1145
- tone: !source || loading || !issueWithTranslations ? void 0 : "caution",
1146
- icon: TranslateIcon,
1147
- onClick: handleClick,
1148
- ref: setButton,
1149
- selected: open
1150
- }
1151
- )
1152
- }
1153
- );
1154
- }
1155
- const DeleteMetadataAction = (props) => {
1156
- const { id: documentId, published, draft, onComplete } = props, doc = draft || published, [isDialogOpen, setDialogOpen] = useState(!1), onClose = useCallback(() => setDialogOpen(!1), []), translations = useMemo(
1157
- () => doc && Array.isArray(doc[TRANSLATIONS_ARRAY_NAME]) ? doc[TRANSLATIONS_ARRAY_NAME] : [],
1158
- [doc]
1159
- ), toast = useToast(), client = useClient({ apiVersion: API_VERSION }), onProceed = useCallback(() => {
1160
- const tx = client.transaction();
1161
- tx.patch(documentId, (patch) => patch.unset([TRANSLATIONS_ARRAY_NAME])), translations.length > 0 && translations.forEach((translation) => {
1162
- tx.delete(translation.value._ref), tx.delete(`drafts.${translation.value._ref}`);
1163
- }), tx.delete(documentId), tx.delete(`drafts.${documentId}`), tx.commit().then(() => {
1164
- onClose(), toast.push({
1165
- status: "success",
1166
- title: "Deleted document and translations"
1167
- });
1168
- }).catch((err) => {
1169
- toast.push({
1170
- status: "error",
1171
- title: "Failed to delete document and translations",
1172
- description: err.message
1173
- });
1174
- });
1175
- }, [client, translations, documentId, onClose, toast]);
1176
- return {
1177
- label: "Delete all translations",
1178
- disabled: !doc || !translations.length,
1179
- icon: TrashIcon,
1180
- tone: "critical",
1181
- onHandle: () => {
1182
- setDialogOpen(!0);
1183
- },
1184
- dialog: isDialogOpen && {
1185
- type: "confirm",
1186
- onCancel: onComplete,
1187
- onConfirm: () => {
1188
- onProceed(), onComplete();
1189
- },
1190
- tone: "critical",
1191
- message: translations.length === 1 ? "Delete 1 translation and this document" : `Delete all ${translations.length} translations and this document`
1192
- }
1193
- };
1194
- };
1195
- function LanguageBadge(props) {
1196
- var _a, _b;
1197
- const source = (props == null ? void 0 : props.draft) || (props == null ? void 0 : props.published), { languageField, supportedLanguages } = useDocumentInternationalizationContext(), languageId = source == null ? void 0 : source[languageField];
1198
- if (!languageId)
1199
- return null;
1200
- const language = Array.isArray(supportedLanguages) ? supportedLanguages.find((l) => l.id === languageId) : null;
1201
- return {
1202
- label: (_a = language == null ? void 0 : language.id) != null ? _a : String(languageId),
1203
- title: (_b = language == null ? void 0 : language.title) != null ? _b : void 0,
1204
- color: "primary"
1205
- };
1206
- }
1207
- function DocumentCheck(props) {
1208
- const {
1209
- id,
1210
- onCheckComplete,
1211
- addInvalidId,
1212
- removeInvalidId,
1213
- addDraftId,
1214
- removeDraftId
1215
- } = props, editState = useEditState(id, ""), { isValidating, validation } = useValidationStatus(id, ""), schema = useSchema(), validationHasErrors = useMemo(() => !isValidating && validation.length > 0 && validation.some((item) => item.level === "error"), [isValidating, validation]);
1216
- if (useEffect(() => {
1217
- validationHasErrors ? addInvalidId(id) : removeInvalidId(id), editState.draft ? addDraftId(id) : removeDraftId(id), isValidating || onCheckComplete(id);
1218
- }, [
1219
- addDraftId,
1220
- addInvalidId,
1221
- editState.draft,
1222
- id,
1223
- isValidating,
1224
- onCheckComplete,
1225
- removeDraftId,
1226
- removeInvalidId,
1227
- validationHasErrors
1228
- ]), !editState.draft)
1229
- return null;
1230
- const schemaType = schema.get(editState.draft._type);
1231
- return /* @__PURE__ */ jsx(
1232
- Card,
1233
- {
1234
- border: !0,
1235
- padding: 2,
1236
- tone: validationHasErrors ? "critical" : "positive",
1237
- children: editState.draft && schemaType ? /* @__PURE__ */ jsx(
1238
- Preview,
1239
- {
1240
- layout: "default",
1241
- value: editState.draft,
1242
- schemaType
1243
- }
1244
- ) : /* @__PURE__ */ jsx(Spinner, {})
1245
- }
1246
- );
1247
- }
1248
- function InfoIcon(props) {
1249
- const { text, icon, tone, children } = props;
1250
- return /* @__PURE__ */ jsx(
1251
- Tooltip,
1252
- {
1253
- animate: !0,
1254
- portal: !0,
1255
- content: children ? /* @__PURE__ */ jsx(Fragment, { children }) : /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { size: 1, children: text }) }),
1256
- children: /* @__PURE__ */ jsx(TextWithTone, { tone, size: 1, children: /* @__PURE__ */ jsx(icon, {}) })
1257
- }
1258
- );
1259
- }
1260
- function Info() {
1261
- return /* @__PURE__ */ jsx(InfoIcon, { icon: InfoOutlineIcon, tone: "primary", children: /* @__PURE__ */ jsxs(Stack, { padding: 3, space: 4, style: { maxWidth: 250 }, children: [
1262
- /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { size: 1, children: "Bulk publishing uses the Scheduling API." }) }),
1263
- /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { size: 1, children: "Customized Document Actions in the Studio will not execute. Webhooks will execute." }) }),
1264
- /* @__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." }) })
1265
- ] }) });
1266
- }
1267
- function BulkPublish(props) {
1268
- const { translations } = props, client = useClient({ apiVersion: API_VERSION }), { projectId, dataset } = useWorkspace(), toast = useToast(), [invalidIds, setInvalidIds] = useState(null), [checkedIds, setCheckedIds] = useState([]), onCheckComplete = useCallback((id) => {
1269
- setCheckedIds((ids) => Array.from(/* @__PURE__ */ new Set([...ids, id])));
1270
- }, []), [open, setOpen] = useState(!1), onOpen = useCallback(() => setOpen(!0), []), onClose = useCallback(() => setOpen(!1), []), addInvalidId = useCallback((id) => {
1271
- setInvalidIds((ids) => ids ? Array.from(/* @__PURE__ */ new Set([...ids, id])) : [id]);
1272
- }, []), removeInvalidId = useCallback((id) => {
1273
- setInvalidIds((ids) => ids ? ids.filter((i) => i !== id) : []);
1274
- }, []), [draftIds, setDraftIds] = useState([]), addDraftId = useCallback((id) => {
1275
- setDraftIds((ids) => Array.from(/* @__PURE__ */ new Set([...ids, id])));
1276
- }, []), removeDraftId = useCallback((id) => {
1277
- setDraftIds((ids) => ids.filter((i) => i !== id));
1278
- }, []), handleBulkPublish = useCallback(() => {
1279
- const body = translations.map((translation) => ({
1280
- documentId: translation.value._ref
1281
- }));
1282
- client.request({
1283
- uri: `/publish/${projectId}/${dataset}`,
1284
- method: "POST",
1285
- body
1286
- }).then(() => {
1287
- toast.push({
1288
- status: "success",
1289
- title: "Success",
1290
- description: "Bulk publish complete"
1291
- });
1292
- }).catch((err) => {
1293
- console.error(err), toast.push({
1294
- status: "error",
1295
- title: "Error",
1296
- description: "Bulk publish failed"
1297
- });
1298
- });
1299
- }, [translations, client, projectId, dataset, toast]), disabled = (
1300
- // Not all documents have been checked
1301
- checkedIds.length !== translations.length || // Some document(s) are invalid
1302
- !!(invalidIds && (invalidIds == null ? void 0 : invalidIds.length) > 0) || // No documents are drafts
1303
- !draftIds.length
1304
- );
1305
- return (translations == null ? void 0 : translations.length) > 0 ? /* @__PURE__ */ jsx(Card, { padding: 4, border: !0, radius: 2, children: /* @__PURE__ */ jsxs(Stack, { space: 3, children: [
1306
- /* @__PURE__ */ jsxs(Inline, { space: 3, children: [
1307
- /* @__PURE__ */ jsx(Text, { weight: "bold", size: 1, children: "Bulk publishing" }),
1308
- /* @__PURE__ */ jsx(Info, {})
1309
- ] }),
1310
- /* @__PURE__ */ jsx(Stack, { children: /* @__PURE__ */ jsx(
1311
- Button,
1312
- {
1313
- onClick: onOpen,
1314
- text: "Prepare bulk publishing",
1315
- mode: "ghost"
1316
- }
1317
- ) }),
1318
- open && /* @__PURE__ */ jsx(
1319
- Dialog,
1320
- {
1321
- animate: !0,
1322
- header: "Bulk publishing",
1323
- id: "bulk-publish-dialog",
1324
- onClose,
1325
- zOffset: 1e3,
1326
- width: 3,
1327
- children: /* @__PURE__ */ jsxs(Stack, { space: 4, padding: 4, children: [
1328
- draftIds.length > 0 ? /* @__PURE__ */ jsxs(Stack, { space: 2, children: [
1329
- /* @__PURE__ */ jsxs(Text, { size: 1, children: [
1330
- "There",
1331
- " ",
1332
- draftIds.length === 1 ? "is 1 draft document" : `are ${draftIds.length} draft documents`,
1333
- "."
1334
- ] }),
1335
- invalidIds && invalidIds.length > 0 ? /* @__PURE__ */ jsxs(TextWithTone, { tone: "critical", size: 1, children: [
1336
- invalidIds && invalidIds.length === 1 ? "1 draft document has" : `${invalidIds && invalidIds.length} draft documents have`,
1337
- " ",
1338
- "validation issues that must addressed first"
1339
- ] }) : /* @__PURE__ */ jsx(TextWithTone, { tone: "positive", size: 1, children: "All drafts are valid and can be bulk published" })
1340
- ] }) : null,
1341
- /* @__PURE__ */ jsx(Stack, { space: 1, children: translations.filter((translation) => {
1342
- var _a;
1343
- return (_a = translation == null ? void 0 : translation.value) == null ? void 0 : _a._ref;
1344
- }).map((translation) => /* @__PURE__ */ jsx(
1345
- DocumentCheck,
1346
- {
1347
- id: translation.value._ref,
1348
- onCheckComplete,
1349
- addInvalidId,
1350
- removeInvalidId,
1351
- addDraftId,
1352
- removeDraftId
1353
- },
1354
- translation._key
1355
- )) }),
1356
- draftIds.length > 0 ? /* @__PURE__ */ jsx(
1357
- Button,
1358
- {
1359
- mode: "ghost",
1360
- tone: invalidIds && (invalidIds == null ? void 0 : invalidIds.length) > 0 ? "caution" : "positive",
1361
- text: draftIds.length === 1 ? "Publish draft document" : `Bulk publish ${draftIds.length} draft documents`,
1362
- onClick: handleBulkPublish,
1363
- disabled
1364
- }
1365
- ) : /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: "No draft documents to publish" })
1366
- ] })
1367
- }
1368
- )
1369
- ] }) }) : null;
1370
- }
1371
- function ReferencePatcher(props) {
1372
- const { translation, documentType, metadataId } = props, editState = useEditState(translation.value._ref, documentType), client = useClient({ apiVersion: API_VERSION }), { onChange } = useDocumentPane();
1373
- return useEffect(() => {
1374
- if (
1375
- // We have a reference
1376
- translation.value._ref && // It's still weak and not-yet-strengthened
1377
- translation.value._weak && // We also want to keep this check because maybe the user *configured* weak refs
1378
- translation.value._strengthenOnPublish && // The referenced document has just been published
1379
- !editState.draft && editState.published && editState.ready
1380
- ) {
1381
- const referencePathBase = [
1382
- "translations",
1383
- { _key: translation._key },
1384
- "value"
1385
- ];
1386
- onChange(
1387
- new PatchEvent([
1388
- unset([...referencePathBase, "_weak"]),
1389
- unset([...referencePathBase, "_strengthenOnPublish"])
1390
- ])
1391
- );
1392
- }
1393
- }, [translation, editState, metadataId, client, onChange]), null;
1394
- }
1395
- function OptimisticallyStrengthen(props) {
1396
- const { translations = [], metadataId } = props;
1397
- return translations.length ? /* @__PURE__ */ jsx(Fragment, { children: translations.map(
1398
- (translation) => {
1399
- var _a;
1400
- return (_a = translation.value._strengthenOnPublish) != null && _a.type ? /* @__PURE__ */ jsx(
1401
- ReferencePatcher,
1402
- {
1403
- translation,
1404
- documentType: translation.value._strengthenOnPublish.type,
1405
- metadataId
1406
- },
1407
- translation._key
1408
- ) : null;
1409
- }
1410
- ) }) : null;
1411
- }
1412
- var metadata = (schemaTypes, metadataFields) => defineType({
1413
- type: "document",
1414
- name: METADATA_SCHEMA_NAME,
1415
- title: "Translation metadata",
1416
- icon: TranslateIcon,
1417
- liveEdit: !0,
1418
- fields: [
1419
- defineField({
1420
- name: TRANSLATIONS_ARRAY_NAME,
1421
- type: "internationalizedArrayReference"
1422
- }),
1423
- defineField({
1424
- name: "schemaTypes",
1425
- description: "Optional: Used to filter the reference fields above so all translations share the same types.",
1426
- type: "array",
1427
- of: [{ type: "string" }],
1428
- options: { list: schemaTypes },
1429
- readOnly: ({ value }) => !!value
1430
- }),
1431
- ...metadataFields
1432
- ],
1433
- preview: {
1434
- select: {
1435
- translations: TRANSLATIONS_ARRAY_NAME,
1436
- documentSchemaTypes: "schemaTypes"
1437
- },
1438
- prepare(selection) {
1439
- const { translations = [], documentSchemaTypes = [] } = selection, title = translations.length === 1 ? "1 Translation" : `${translations.length} Translations`, languageKeys = translations.length ? translations.map((t) => t._key.toUpperCase()).join(", ") : "", subtitle = [
1440
- languageKeys ? `(${languageKeys})` : null,
1441
- documentSchemaTypes != null && documentSchemaTypes.length ? documentSchemaTypes.map((s) => s).join(", ") : ""
1442
- ].filter(Boolean).join(" ");
1443
- return {
1444
- title,
1445
- subtitle
1446
- };
1447
- }
1448
- }
1449
- }), __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) => {
1450
- for (var prop in b || (b = {}))
1451
- __hasOwnProp.call(b, prop) && __defNormalProp(a, prop, b[prop]);
1452
- if (__getOwnPropSymbols)
1453
- for (var prop of __getOwnPropSymbols(b))
1454
- __propIsEnum.call(b, prop) && __defNormalProp(a, prop, b[prop]);
1455
- return a;
1456
- }, __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1457
- const documentInternationalization = definePlugin(
1458
- (config) => {
1459
- const pluginConfig = __spreadValues(__spreadValues({}, DEFAULT_CONFIG), config), {
1460
- supportedLanguages,
1461
- schemaTypes,
1462
- languageField,
1463
- bulkPublish,
1464
- metadataFields
1465
- } = pluginConfig;
1466
- if (schemaTypes.length === 0)
1467
- throw new Error(
1468
- "You must specify at least one schema type on which to enable document internationalization. Update the `schemaTypes` option in the documentInternationalization() configuration."
1469
- );
1470
- return {
1471
- name: "@sanity/document-internationalization",
1472
- studio: {
1473
- components: {
1474
- layout: (props) => DocumentInternationalizationProvider(__spreadProps(__spreadValues({}, props), { pluginConfig }))
1475
- }
1476
- },
1477
- i18n: {
1478
- bundles: [documentInternationalizationUsEnglishLocaleBundle]
1479
- },
1480
- // Adds:
1481
- // - A bulk-publishing UI component to the form
1482
- // - Will only work for projects on a compatible plan
1483
- form: {
1484
- components: {
1485
- input: (props) => {
1486
- var _a, _b, _c;
1487
- if (props.id === "root" && props.schemaType.name === METADATA_SCHEMA_NAME && isSanityDocument(props == null ? void 0 : props.value)) {
1488
- 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(
1489
- ({ value }) => (value == null ? void 0 : value._weak) && value._strengthenOnPublish
1490
- );
1491
- return /* @__PURE__ */ jsxs(Stack, { space: 5, children: [
1492
- bulkPublish ? /* @__PURE__ */ jsx(BulkPublish, { translations }) : null,
1493
- weakAndTypedTranslations.length > 0 ? /* @__PURE__ */ jsx(
1494
- OptimisticallyStrengthen,
1495
- {
1496
- metadataId,
1497
- translations: weakAndTypedTranslations
1498
- }
1499
- ) : null,
1500
- props.renderDefault(props)
1501
- ] });
1502
- }
1503
- return props.renderDefault(props);
1504
- }
1505
- }
1506
- },
1507
- // Adds:
1508
- // - The `Translations` dropdown to the editing form
1509
- // - `Badges` to documents with a language value
1510
- // - The `DeleteMetadataAction` action to the metadata document type
1511
- document: {
1512
- unstable_languageFilter: (prev, ctx) => {
1513
- const { schemaType, documentId } = ctx;
1514
- return schemaTypes.includes(schemaType) && documentId ? [
1515
- ...prev,
1516
- (props) => DocumentInternationalizationMenu(__spreadProps(__spreadValues({}, props), { documentId }))
1517
- ] : prev;
1518
- },
1519
- badges: (prev, { schemaType }) => schemaTypes.includes(schemaType) ? [(props) => LanguageBadge(props), ...prev] : prev,
1520
- actions: (prev, { schemaType }) => schemaType === METADATA_SCHEMA_NAME ? [...prev, DeleteMetadataAction] : prev
1521
- },
1522
- // Adds:
1523
- // - The `Translations metadata` document type to the schema
1524
- schema: {
1525
- // Create the metadata document type
1526
- types: [metadata(schemaTypes, metadataFields)],
1527
- // For every schema type this plugin is enabled on
1528
- // Create an initial value template to set the language
1529
- templates: (prev, { schema }) => {
1530
- if (!Array.isArray(supportedLanguages))
1531
- return prev;
1532
- const parameterizedTemplates = schemaTypes.map((schemaType) => {
1533
- var _a, _b;
1534
- return {
1535
- id: `${schemaType}-parameterized`,
1536
- title: `${(_b = (_a = schema == null ? void 0 : schema.get(schemaType)) == null ? void 0 : _a.title) != null ? _b : schemaType}: with Language`,
1537
- schemaType,
1538
- parameters: [
1539
- { name: "languageId", title: "Language ID", type: "string" }
1540
- ],
1541
- value: ({ languageId }) => ({
1542
- [languageField]: languageId
1543
- })
1544
- };
1545
- }), staticTemplates = schemaTypes.flatMap((schemaType) => supportedLanguages.map((language) => {
1546
- var _a, _b;
1547
- return {
1548
- id: `${schemaType}-${language.id}`,
1549
- title: `${language.title} ${(_b = (_a = schema == null ? void 0 : schema.get(schemaType)) == null ? void 0 : _a.title) != null ? _b : schemaType}`,
1550
- schemaType,
1551
- value: {
1552
- [languageField]: language.id
1553
- }
1554
- };
1555
- }));
1556
- return [...prev, ...parameterizedTemplates, ...staticTemplates];
1557
- }
1558
- },
1559
- // Uses:
1560
- // - `sanity-plugin-internationalized-array` to maintain the translations array
1561
- plugins: [
1562
- // Translation metadata stores its references using this plugin
1563
- // It cuts down on attribute usage and gives UI conveniences to add new translations
1564
- internationalizedArray({
1565
- apiVersion: pluginConfig.apiVersion,
1566
- languages: supportedLanguages,
1567
- fieldTypes: [
1568
- defineField(
1569
- {
1570
- name: "reference",
1571
- type: "reference",
1572
- to: schemaTypes.map((type) => ({ type })),
1573
- weak: pluginConfig.weakReferences,
1574
- // Reference filters don't actually enforce validation!
1575
- validation: (Rule) => (
1576
- // @ts-expect-error - fix typings
1577
- Rule.custom(async (item, context) => {
1578
- var _a;
1579
- if (!((_a = item == null ? void 0 : item.value) != null && _a._ref) || !(item != null && item._key))
1580
- return !0;
1581
- const valueLanguage = await context.getClient({ apiVersion: API_VERSION }).fetch(
1582
- `*[_id in [$ref, $draftRef]][0].${languageField}`,
1583
- {
1584
- ref: item.value._ref,
1585
- draftRef: `drafts.${item.value._ref}`
1586
- }
1587
- );
1588
- return valueLanguage && valueLanguage === item._key ? !0 : "Referenced document does not have the correct language value";
1589
- })
1590
- ),
1591
- options: {
1592
- // @ts-expect-error - Update type once it knows the values of this filter
1593
- filter: ({ parent, document }) => {
1594
- if (!parent)
1595
- return null;
1596
- const language = (Array.isArray(parent) ? parent : [parent]).find((p) => p._key);
1597
- return language != null && language._key ? document.schemaTypes ? {
1598
- filter: `_type in $schemaTypes && ${languageField} == $language`,
1599
- params: {
1600
- schemaTypes: document.schemaTypes,
1601
- language: language._key
1602
- }
1603
- } : {
1604
- filter: `${languageField} == $language`,
1605
- params: { language: language._key }
1606
- } : null;
1607
- }
1608
- }
1609
- },
1610
- { strict: !1 }
1611
- )
1612
- ]
1613
- })
1614
- ]
1615
- };
1616
- }
1617
- );
1618
- export {
1619
- DeleteTranslationAction,
1620
- DocumentInternationalizationMenu,
1621
- DuplicateWithTranslationsAction,
1622
- documentInternationalization,
1623
- useDocumentInternationalizationContext
1624
- };
1625
- //# sourceMappingURL=index.esm.js.map