@sanity/document-internationalization 3.0.1 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -12,7 +12,8 @@ const METADATA_SCHEMA_NAME = "translation.metadata", TRANSLATIONS_ARRAY_NAME = "
12
12
  weakReferences: !1,
13
13
  bulkPublish: !1,
14
14
  metadataFields: [],
15
- apiVersion: API_VERSION
15
+ apiVersion: API_VERSION,
16
+ allowCreateMetaDoc: !1
16
17
  };
17
18
  function separateReferences(data = []) {
18
19
  const translations = [], otherReferences = [];
@@ -101,7 +102,7 @@ function shallowEqualArrays(arrA, arrB, equal = (a, b) => a === b) {
101
102
  return !1;
102
103
  return !0;
103
104
  }
104
- function query$1(fn, keys = null, preload = !1, config = {}) {
105
+ function query$1(fn, keys = null, preload = !1, config2 = {}) {
105
106
  keys === null && (keys = [fn]);
106
107
  for (const entry2 of globalCache)
107
108
  if (shallowEqualArrays(keys, entry2.keys, entry2.equal)) {
@@ -110,13 +111,13 @@ function query$1(fn, keys = null, preload = !1, config = {}) {
110
111
  if (Object.prototype.hasOwnProperty.call(entry2, "error"))
111
112
  throw entry2.error;
112
113
  if (Object.prototype.hasOwnProperty.call(entry2, "response"))
113
- return config.lifespan && config.lifespan > 0 && (entry2.timeout && clearTimeout(entry2.timeout), entry2.timeout = setTimeout(entry2.remove, config.lifespan)), entry2.response;
114
+ return config2.lifespan && config2.lifespan > 0 && (entry2.timeout && clearTimeout(entry2.timeout), entry2.timeout = setTimeout(entry2.remove, config2.lifespan)), entry2.response;
114
115
  if (!preload)
115
116
  throw entry2.promise;
116
117
  }
117
118
  const entry = {
118
119
  keys,
119
- equal: config.equal,
120
+ equal: config2.equal,
120
121
  remove: () => {
121
122
  const index = globalCache.indexOf(entry);
122
123
  index !== -1 && globalCache.splice(index, 1);
@@ -124,14 +125,14 @@ function query$1(fn, keys = null, preload = !1, config = {}) {
124
125
  promise: (
125
126
  // Execute the promise
126
127
  (isPromise(fn) ? fn : fn(...keys)).then((response) => {
127
- entry.response = response, config.lifespan && config.lifespan > 0 && (entry.timeout = setTimeout(entry.remove, config.lifespan));
128
+ entry.response = response, config2.lifespan && config2.lifespan > 0 && (entry.timeout = setTimeout(entry.remove, config2.lifespan));
128
129
  }).catch((error) => entry.error = error)
129
130
  )
130
131
  };
131
132
  if (globalCache.push(entry), !preload)
132
133
  throw entry.promise;
133
134
  }
134
- const suspend = (fn, keys, config) => query$1(fn, keys, !1, config), DocumentInternationalizationContext = react.createContext(DEFAULT_CONFIG);
135
+ const suspend = (fn, keys, config2) => query$1(fn, keys, !1, config2), DocumentInternationalizationContext = react.createContext(DEFAULT_CONFIG);
135
136
  function useDocumentInternationalizationContext() {
136
137
  return react.useContext(DocumentInternationalizationContext);
137
138
  }
@@ -203,7 +204,392 @@ const DeleteTranslationAction = (props) => {
203
204
  )
204
205
  }
205
206
  };
206
- }, query = `*[_type == $translationSchema && $id in translations[].value._ref]{
207
+ };
208
+ var extendStatics = function(d, b) {
209
+ return extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
210
+ d2.__proto__ = b2;
211
+ } || function(d2, b2) {
212
+ for (var p in b2)
213
+ Object.prototype.hasOwnProperty.call(b2, p) && (d2[p] = b2[p]);
214
+ }, extendStatics(d, b);
215
+ };
216
+ function __extends(d, b) {
217
+ if (typeof b != "function" && b !== null)
218
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
219
+ extendStatics(d, b);
220
+ function __() {
221
+ this.constructor = d;
222
+ }
223
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
224
+ }
225
+ function __values(o) {
226
+ var s = typeof Symbol == "function" && Symbol.iterator, m = s && o[s], i = 0;
227
+ if (m)
228
+ return m.call(o);
229
+ if (o && typeof o.length == "number")
230
+ return {
231
+ next: function() {
232
+ return o && i >= o.length && (o = void 0), { value: o && o[i++], done: !o };
233
+ }
234
+ };
235
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
236
+ }
237
+ function __read(o, n) {
238
+ var m = typeof Symbol == "function" && o[Symbol.iterator];
239
+ if (!m)
240
+ return o;
241
+ var i = m.call(o), r, ar = [], e;
242
+ try {
243
+ for (; (n === void 0 || n-- > 0) && !(r = i.next()).done; )
244
+ ar.push(r.value);
245
+ } catch (error) {
246
+ e = { error };
247
+ } finally {
248
+ try {
249
+ r && !r.done && (m = i.return) && m.call(i);
250
+ } finally {
251
+ if (e)
252
+ throw e.error;
253
+ }
254
+ }
255
+ return ar;
256
+ }
257
+ function __spreadArray(to, from, pack) {
258
+ if (pack || arguments.length === 2)
259
+ for (var i = 0, l = from.length, ar; i < l; i++)
260
+ (ar || !(i in from)) && (ar || (ar = Array.prototype.slice.call(from, 0, i)), ar[i] = from[i]);
261
+ return to.concat(ar || Array.prototype.slice.call(from));
262
+ }
263
+ function isFunction(value) {
264
+ return typeof value == "function";
265
+ }
266
+ function createErrorClass(createImpl) {
267
+ var _super = function(instance) {
268
+ Error.call(instance), instance.stack = new Error().stack;
269
+ }, ctorFunc = createImpl(_super);
270
+ return ctorFunc.prototype = Object.create(Error.prototype), ctorFunc.prototype.constructor = ctorFunc, ctorFunc;
271
+ }
272
+ var UnsubscriptionError = createErrorClass(function(_super) {
273
+ return function(errors) {
274
+ _super(this), this.message = errors ? errors.length + ` errors occurred during unsubscription:
275
+ ` + errors.map(function(err, i) {
276
+ return i + 1 + ") " + err.toString();
277
+ }).join(`
278
+ `) : "", this.name = "UnsubscriptionError", this.errors = errors;
279
+ };
280
+ });
281
+ function arrRemove(arr, item) {
282
+ if (arr) {
283
+ var index = arr.indexOf(item);
284
+ 0 <= index && arr.splice(index, 1);
285
+ }
286
+ }
287
+ var Subscription = function() {
288
+ function Subscription2(initialTeardown) {
289
+ this.initialTeardown = initialTeardown, this.closed = !1, this._parentage = null, this._finalizers = null;
290
+ }
291
+ return Subscription2.prototype.unsubscribe = function() {
292
+ var e_1, _a, e_2, _b, errors;
293
+ if (!this.closed) {
294
+ this.closed = !0;
295
+ var _parentage = this._parentage;
296
+ if (_parentage)
297
+ if (this._parentage = null, Array.isArray(_parentage))
298
+ try {
299
+ for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
300
+ var parent_1 = _parentage_1_1.value;
301
+ parent_1.remove(this);
302
+ }
303
+ } catch (e_1_1) {
304
+ e_1 = { error: e_1_1 };
305
+ } finally {
306
+ try {
307
+ _parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return) && _a.call(_parentage_1);
308
+ } finally {
309
+ if (e_1)
310
+ throw e_1.error;
311
+ }
312
+ }
313
+ else
314
+ _parentage.remove(this);
315
+ var initialFinalizer = this.initialTeardown;
316
+ if (isFunction(initialFinalizer))
317
+ try {
318
+ initialFinalizer();
319
+ } catch (e) {
320
+ errors = e instanceof UnsubscriptionError ? e.errors : [e];
321
+ }
322
+ var _finalizers = this._finalizers;
323
+ if (_finalizers) {
324
+ this._finalizers = null;
325
+ try {
326
+ for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
327
+ var finalizer = _finalizers_1_1.value;
328
+ try {
329
+ execFinalizer(finalizer);
330
+ } catch (err) {
331
+ errors = errors != null ? errors : [], err instanceof UnsubscriptionError ? errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors)) : errors.push(err);
332
+ }
333
+ }
334
+ } catch (e_2_1) {
335
+ e_2 = { error: e_2_1 };
336
+ } finally {
337
+ try {
338
+ _finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return) && _b.call(_finalizers_1);
339
+ } finally {
340
+ if (e_2)
341
+ throw e_2.error;
342
+ }
343
+ }
344
+ }
345
+ if (errors)
346
+ throw new UnsubscriptionError(errors);
347
+ }
348
+ }, Subscription2.prototype.add = function(teardown) {
349
+ var _a;
350
+ if (teardown && teardown !== this)
351
+ if (this.closed)
352
+ execFinalizer(teardown);
353
+ else {
354
+ if (teardown instanceof Subscription2) {
355
+ if (teardown.closed || teardown._hasParent(this))
356
+ return;
357
+ teardown._addParent(this);
358
+ }
359
+ (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
360
+ }
361
+ }, Subscription2.prototype._hasParent = function(parent) {
362
+ var _parentage = this._parentage;
363
+ return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
364
+ }, Subscription2.prototype._addParent = function(parent) {
365
+ var _parentage = this._parentage;
366
+ this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
367
+ }, Subscription2.prototype._removeParent = function(parent) {
368
+ var _parentage = this._parentage;
369
+ _parentage === parent ? this._parentage = null : Array.isArray(_parentage) && arrRemove(_parentage, parent);
370
+ }, Subscription2.prototype.remove = function(teardown) {
371
+ var _finalizers = this._finalizers;
372
+ _finalizers && arrRemove(_finalizers, teardown), teardown instanceof Subscription2 && teardown._removeParent(this);
373
+ }, Subscription2.EMPTY = function() {
374
+ var empty = new Subscription2();
375
+ return empty.closed = !0, empty;
376
+ }(), Subscription2;
377
+ }();
378
+ function isSubscription(value) {
379
+ return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
380
+ }
381
+ function execFinalizer(finalizer) {
382
+ isFunction(finalizer) ? finalizer() : finalizer.unsubscribe();
383
+ }
384
+ var config = {
385
+ onUnhandledError: null,
386
+ onStoppedNotification: null,
387
+ Promise: void 0,
388
+ useDeprecatedSynchronousErrorHandling: !1,
389
+ useDeprecatedNextContext: !1
390
+ }, timeoutProvider = {
391
+ setTimeout: function(handler, timeout) {
392
+ for (var args = [], _i = 2; _i < arguments.length; _i++)
393
+ args[_i - 2] = arguments[_i];
394
+ return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
395
+ },
396
+ clearTimeout: function(handle) {
397
+ return clearTimeout(handle);
398
+ },
399
+ delegate: void 0
400
+ };
401
+ function reportUnhandledError(err) {
402
+ timeoutProvider.setTimeout(function() {
403
+ throw err;
404
+ });
405
+ }
406
+ function noop() {
407
+ }
408
+ var Subscriber = function(_super) {
409
+ __extends(Subscriber2, _super);
410
+ function Subscriber2(destination) {
411
+ var _this = _super.call(this) || this;
412
+ return _this.isStopped = !1, destination ? (_this.destination = destination, isSubscription(destination) && destination.add(_this)) : _this.destination = EMPTY_OBSERVER, _this;
413
+ }
414
+ return Subscriber2.create = function(next, error, complete) {
415
+ return new SafeSubscriber(next, error, complete);
416
+ }, Subscriber2.prototype.next = function(value) {
417
+ this.isStopped || this._next(value);
418
+ }, Subscriber2.prototype.error = function(err) {
419
+ this.isStopped || (this.isStopped = !0, this._error(err));
420
+ }, Subscriber2.prototype.complete = function() {
421
+ this.isStopped || (this.isStopped = !0, this._complete());
422
+ }, Subscriber2.prototype.unsubscribe = function() {
423
+ this.closed || (this.isStopped = !0, _super.prototype.unsubscribe.call(this), this.destination = null);
424
+ }, Subscriber2.prototype._next = function(value) {
425
+ this.destination.next(value);
426
+ }, Subscriber2.prototype._error = function(err) {
427
+ try {
428
+ this.destination.error(err);
429
+ } finally {
430
+ this.unsubscribe();
431
+ }
432
+ }, Subscriber2.prototype._complete = function() {
433
+ try {
434
+ this.destination.complete();
435
+ } finally {
436
+ this.unsubscribe();
437
+ }
438
+ }, Subscriber2;
439
+ }(Subscription), _bind = Function.prototype.bind;
440
+ function bind(fn, thisArg) {
441
+ return _bind.call(fn, thisArg);
442
+ }
443
+ var ConsumerObserver = function() {
444
+ function ConsumerObserver2(partialObserver) {
445
+ this.partialObserver = partialObserver;
446
+ }
447
+ return ConsumerObserver2.prototype.next = function(value) {
448
+ var partialObserver = this.partialObserver;
449
+ if (partialObserver.next)
450
+ try {
451
+ partialObserver.next(value);
452
+ } catch (error) {
453
+ handleUnhandledError(error);
454
+ }
455
+ }, ConsumerObserver2.prototype.error = function(err) {
456
+ var partialObserver = this.partialObserver;
457
+ if (partialObserver.error)
458
+ try {
459
+ partialObserver.error(err);
460
+ } catch (error) {
461
+ handleUnhandledError(error);
462
+ }
463
+ else
464
+ handleUnhandledError(err);
465
+ }, ConsumerObserver2.prototype.complete = function() {
466
+ var partialObserver = this.partialObserver;
467
+ if (partialObserver.complete)
468
+ try {
469
+ partialObserver.complete();
470
+ } catch (error) {
471
+ handleUnhandledError(error);
472
+ }
473
+ }, ConsumerObserver2;
474
+ }(), SafeSubscriber = function(_super) {
475
+ __extends(SafeSubscriber2, _super);
476
+ function SafeSubscriber2(observerOrNext, error, complete) {
477
+ var _this = _super.call(this) || this, partialObserver;
478
+ if (isFunction(observerOrNext) || !observerOrNext)
479
+ partialObserver = {
480
+ next: observerOrNext != null ? observerOrNext : void 0,
481
+ error: error != null ? error : void 0,
482
+ complete: complete != null ? complete : void 0
483
+ };
484
+ else {
485
+ var context_1;
486
+ _this && config.useDeprecatedNextContext ? (context_1 = Object.create(observerOrNext), context_1.unsubscribe = function() {
487
+ return _this.unsubscribe();
488
+ }, partialObserver = {
489
+ next: observerOrNext.next && bind(observerOrNext.next, context_1),
490
+ error: observerOrNext.error && bind(observerOrNext.error, context_1),
491
+ complete: observerOrNext.complete && bind(observerOrNext.complete, context_1)
492
+ }) : partialObserver = observerOrNext;
493
+ }
494
+ return _this.destination = new ConsumerObserver(partialObserver), _this;
495
+ }
496
+ return SafeSubscriber2;
497
+ }(Subscriber);
498
+ function handleUnhandledError(error) {
499
+ reportUnhandledError(error);
500
+ }
501
+ function defaultErrorHandler(err) {
502
+ throw err;
503
+ }
504
+ var EMPTY_OBSERVER = {
505
+ closed: !0,
506
+ next: noop,
507
+ error: defaultErrorHandler,
508
+ complete: noop
509
+ };
510
+ function hasLift(source) {
511
+ return isFunction(source == null ? void 0 : source.lift);
512
+ }
513
+ function operate(init) {
514
+ return function(source) {
515
+ if (hasLift(source))
516
+ return source.lift(function(liftedSource) {
517
+ try {
518
+ return init(liftedSource, this);
519
+ } catch (err) {
520
+ this.error(err);
521
+ }
522
+ });
523
+ throw new TypeError("Unable to lift unknown Observable type");
524
+ };
525
+ }
526
+ function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
527
+ return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
528
+ }
529
+ var OperatorSubscriber = function(_super) {
530
+ __extends(OperatorSubscriber2, _super);
531
+ function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
532
+ var _this = _super.call(this, destination) || this;
533
+ return _this.onFinalize = onFinalize, _this.shouldUnsubscribe = shouldUnsubscribe, _this._next = onNext ? function(value) {
534
+ try {
535
+ onNext(value);
536
+ } catch (err) {
537
+ destination.error(err);
538
+ }
539
+ } : _super.prototype._next, _this._error = onError ? function(err) {
540
+ try {
541
+ onError(err);
542
+ } catch (err2) {
543
+ destination.error(err2);
544
+ } finally {
545
+ this.unsubscribe();
546
+ }
547
+ } : _super.prototype._error, _this._complete = onComplete ? function() {
548
+ try {
549
+ onComplete();
550
+ } catch (err) {
551
+ destination.error(err);
552
+ } finally {
553
+ this.unsubscribe();
554
+ }
555
+ } : _super.prototype._complete, _this;
556
+ }
557
+ return OperatorSubscriber2.prototype.unsubscribe = function() {
558
+ var _a;
559
+ if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
560
+ var closed_1 = this.closed;
561
+ _super.prototype.unsubscribe.call(this), !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 || _a.call(this));
562
+ }
563
+ }, OperatorSubscriber2;
564
+ }(Subscriber), EmptyError = createErrorClass(function(_super) {
565
+ return function() {
566
+ _super(this), this.name = "EmptyError", this.message = "no elements in sequence";
567
+ };
568
+ });
569
+ function firstValueFrom(source, config2) {
570
+ var hasConfig = typeof config2 == "object";
571
+ return new Promise(function(resolve, reject) {
572
+ var subscriber = new SafeSubscriber({
573
+ next: function(value) {
574
+ resolve(value), subscriber.unsubscribe();
575
+ },
576
+ error: reject,
577
+ complete: function() {
578
+ hasConfig ? resolve(config2.defaultValue) : reject(new EmptyError());
579
+ }
580
+ });
581
+ source.subscribe(subscriber);
582
+ });
583
+ }
584
+ function filter(predicate, thisArg) {
585
+ return operate(function(source, subscriber) {
586
+ var index = 0;
587
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
588
+ return predicate.call(thisArg, value, index++) && subscriber.next(value);
589
+ }));
590
+ });
591
+ }
592
+ const query = `*[_type == $translationSchema && $id in translations[].value._ref]{
207
593
  _id,
208
594
  _createdAt,
209
595
  translations
@@ -214,6 +600,131 @@ function useTranslationMetadata(id) {
214
600
  });
215
601
  return { data, loading, error };
216
602
  }
603
+ const documenti18nLocaleNamespace = "document-internationalization", documentInternationalizationUsEnglishLocaleBundle = sanity.defineLocaleResourceBundle({
604
+ locale: "en-US",
605
+ namespace: documenti18nLocaleNamespace,
606
+ resources: () => Promise.resolve().then(function() {
607
+ return require("./_chunks-cjs/resources.js");
608
+ })
609
+ }), DISABLED_REASON_KEY = {
610
+ METADATA_NOT_FOUND: "action.duplicate.disabled.missing-metadata",
611
+ MULTIPLE_METADATA: "action.duplicate.disabled.multiple-metadata",
612
+ NOTHING_TO_DUPLICATE: "action.duplicate.disabled.nothing-to-duplicate",
613
+ NOT_READY: "action.duplicate.disabled.not-ready"
614
+ }, DuplicateWithTranslationsAction = ({
615
+ id,
616
+ type,
617
+ onComplete
618
+ }) => {
619
+ const documentStore = sanity.useDocumentStore(), { duplicate } = sanity.useDocumentOperation(id, type), { navigateIntent } = router.useRouter(), [isDuplicating, setDuplicating] = react.useState(!1), [permissions, isPermissionsLoading] = sanity.useDocumentPairPermissions({
620
+ id,
621
+ type,
622
+ permission: "duplicate"
623
+ }), { data, loading: isMetadataDocumentLoading } = useTranslationMetadata(id), hasOneMetadataDocument = react.useMemo(() => Array.isArray(data) && data.length <= 1, [data]), metadataDocument = Array.isArray(data) && data.length ? data[0] : null, client = sanity.useClient(sanity.DEFAULT_STUDIO_CLIENT_OPTIONS), toast = ui.useToast(), { t: s } = sanity.useTranslation(structure.structureLocaleNamespace), { t: d } = sanity.useTranslation(documenti18nLocaleNamespace), currentUser = sanity.useCurrentUser(), handle = react.useCallback(async () => {
624
+ setDuplicating(!0);
625
+ try {
626
+ if (!metadataDocument)
627
+ throw new Error("Metadata document not found");
628
+ const translations = /* @__PURE__ */ new Map();
629
+ await Promise.all(
630
+ metadataDocument[TRANSLATIONS_ARRAY_NAME].map(async (translation) => {
631
+ var _a;
632
+ const dupeId2 = uuid.uuid(), locale = translation._key, docId = (_a = translation.value) == null ? void 0 : _a._ref;
633
+ if (!docId)
634
+ throw new Error("Translation document not found");
635
+ const { duplicate: duplicateTranslation } = await firstValueFrom(
636
+ documentStore.pair.editOperations(docId, type).pipe(filter((op) => op.duplicate.disabled !== "NOT_READY"))
637
+ );
638
+ if (duplicateTranslation.disabled)
639
+ throw new Error("Cannot duplicate document");
640
+ const duplicateTranslationSuccess = firstValueFrom(
641
+ documentStore.pair.operationEvents(docId, type).pipe(filter((e) => e.op === "duplicate" && e.type === "success"))
642
+ );
643
+ duplicateTranslation.execute(dupeId2), await duplicateTranslationSuccess, translations.set(locale, dupeId2);
644
+ })
645
+ );
646
+ const { duplicate: duplicateMetadata } = await firstValueFrom(
647
+ documentStore.pair.editOperations(metadataDocument._id, METADATA_SCHEMA_NAME).pipe(filter((op) => op.duplicate.disabled !== "NOT_READY"))
648
+ );
649
+ if (duplicateMetadata.disabled)
650
+ throw new Error("Cannot duplicate document");
651
+ const duplicateMetadataSuccess = firstValueFrom(
652
+ documentStore.pair.operationEvents(metadataDocument._id, METADATA_SCHEMA_NAME).pipe(filter((e) => e.op === "duplicate" && e.type === "success"))
653
+ ), dupeId = uuid.uuid();
654
+ duplicateMetadata.execute(dupeId), await duplicateMetadataSuccess;
655
+ const patch = {
656
+ set: Object.fromEntries(
657
+ Array.from(translations.entries()).map(([locale, documentId]) => [
658
+ `${TRANSLATIONS_ARRAY_NAME}[_key == "${locale}"].value._ref`,
659
+ documentId
660
+ ])
661
+ )
662
+ };
663
+ await client.transaction().patch(dupeId, patch).commit(), navigateIntent("edit", {
664
+ id: Array.from(translations.values()).at(0),
665
+ type
666
+ }), onComplete();
667
+ } catch (error) {
668
+ console.error(error), toast.push({
669
+ status: "error",
670
+ title: "Error duplicating document",
671
+ description: error instanceof Error ? error.message : "Failed to duplicate document"
672
+ });
673
+ } finally {
674
+ setDuplicating(!1);
675
+ }
676
+ }, [
677
+ client,
678
+ documentStore.pair,
679
+ metadataDocument,
680
+ navigateIntent,
681
+ onComplete,
682
+ toast,
683
+ type
684
+ ]);
685
+ return react.useMemo(() => !isPermissionsLoading && !(permissions != null && permissions.granted) ? {
686
+ icon: icons.CopyIcon,
687
+ disabled: !0,
688
+ label: d("action.duplicate.label"),
689
+ title: /* @__PURE__ */ jsxRuntime.jsx(
690
+ sanity.InsufficientPermissionsMessage,
691
+ {
692
+ context: "duplicate-document",
693
+ currentUser
694
+ }
695
+ )
696
+ } : !isMetadataDocumentLoading && !metadataDocument ? {
697
+ icon: icons.CopyIcon,
698
+ disabled: !0,
699
+ label: d("action.duplicate.label"),
700
+ title: d(DISABLED_REASON_KEY.METADATA_NOT_FOUND)
701
+ } : hasOneMetadataDocument ? {
702
+ icon: icons.CopyIcon,
703
+ disabled: isDuplicating || !!duplicate.disabled || isPermissionsLoading || isMetadataDocumentLoading,
704
+ label: isDuplicating ? s("action.duplicate.running.label") : d("action.duplicate.label"),
705
+ title: duplicate.disabled ? s(DISABLED_REASON_KEY[duplicate.disabled]) : "",
706
+ onHandle: handle
707
+ } : {
708
+ icon: icons.CopyIcon,
709
+ disabled: !0,
710
+ label: d("action.duplicate.label"),
711
+ title: d(DISABLED_REASON_KEY.MULTIPLE_METADATA)
712
+ }, [
713
+ currentUser,
714
+ duplicate.disabled,
715
+ handle,
716
+ hasOneMetadataDocument,
717
+ isDuplicating,
718
+ isMetadataDocumentLoading,
719
+ isPermissionsLoading,
720
+ metadataDocument,
721
+ permissions == null ? void 0 : permissions.granted,
722
+ s,
723
+ d
724
+ ]);
725
+ };
726
+ DuplicateWithTranslationsAction.action = "duplicate";
727
+ DuplicateWithTranslationsAction.displayName = "DuplicateWithTranslationsAction";
217
728
  function useOpenInNewPane(id, type) {
218
729
  const routerContext = react.useContext(router.RouterContext), { routerPanesState, groupIndex } = structure.usePaneRouter();
219
730
  return react.useCallback(() => {
@@ -234,42 +745,75 @@ function useOpenInNewPane(id, type) {
234
745
  routerContext.navigateUrl({ path: href });
235
746
  }, [id, type, routerContext, routerPanesState, groupIndex]);
236
747
  }
748
+ function createReference(key, ref, type, strengthenOnPublish = !0) {
749
+ return {
750
+ _key: key,
751
+ _type: "internationalizedArrayReferenceValue",
752
+ value: {
753
+ _type: "reference",
754
+ _ref: ref,
755
+ _weak: !0,
756
+ // If the user has configured weakReferences, we won't want to strengthen them
757
+ ...strengthenOnPublish ? { _strengthenOnPublish: { type } } : {}
758
+ }
759
+ };
760
+ }
237
761
  function LanguageManage(props) {
238
- const { id } = props, open = useOpenInNewPane(id, METADATA_SCHEMA_NAME);
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 = sanity.useClient({ apiVersion }), [userHasClicked, setUserHasClicked] = react.useState(!1), canCreate = !id && !!metadataId && allowCreateMetaDoc, handleClick = react.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
+ ]);
239
794
  return /* @__PURE__ */ jsxRuntime.jsx(
240
795
  ui.Tooltip,
241
796
  {
242
797
  animate: !0,
243
- content: id ? null : /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { padding: 2, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { muted: !0, size: 1, children: "Document has no other translations" }) }),
798
+ content: /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { padding: 2, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { muted: !0, size: 1, children: "Document has no other translations" }) }),
244
799
  fallbackPlacements: ["right", "left"],
245
800
  placement: "top",
246
801
  portal: !0,
802
+ disabled: !!id || canCreate,
247
803
  children: /* @__PURE__ */ jsxRuntime.jsx(ui.Stack, { children: /* @__PURE__ */ jsxRuntime.jsx(
248
804
  ui.Button,
249
805
  {
250
- disabled: !id,
806
+ disabled: !id && !canCreate || canCreate && !sourceLanguageId || userHasClicked,
251
807
  mode: "ghost",
252
808
  text: "Manage Translations",
253
809
  icon: icons.CogIcon,
254
- onClick: () => open()
810
+ loading: userHasClicked,
811
+ onClick: handleClick
255
812
  }
256
813
  ) })
257
814
  }
258
815
  );
259
816
  }
260
- function createReference(key, ref, type, strengthenOnPublish = !0) {
261
- return {
262
- _key: key,
263
- _type: "internationalizedArrayReferenceValue",
264
- value: {
265
- _type: "reference",
266
- _ref: ref,
267
- _weak: !0,
268
- // If the user has configured weakReferences, we won't want to strengthen them
269
- ...strengthenOnPublish ? { _strengthenOnPublish: { type } } : {}
270
- }
271
- };
272
- }
273
817
  function removeExcludedPaths(doc, schemaType) {
274
818
  if (!sanity.isDocumentSchemaType(schemaType) || !doc)
275
819
  return doc;
@@ -487,7 +1031,16 @@ function DocumentInternationalizationMenu(props) {
487
1031
  supportedLanguages
488
1032
  ), valid;
489
1033
  }, [supportedLanguages]), content = /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { padding: 1, children: error ? /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { tone: "critical", padding: 1, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { children: "There was an error returning translations metadata" }) }) : /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { space: 1, children: [
490
- /* @__PURE__ */ jsxRuntime.jsx(LanguageManage, { id: metadata2 == null ? void 0 : metadata2._id }),
1034
+ /* @__PURE__ */ jsxRuntime.jsx(
1035
+ LanguageManage,
1036
+ {
1037
+ id: metadata2 == null ? void 0 : metadata2._id,
1038
+ documentId,
1039
+ metadataId,
1040
+ schemaType,
1041
+ sourceLanguageId
1042
+ }
1043
+ ),
491
1044
  supportedLanguages.length > 4 ? /* @__PURE__ */ jsxRuntime.jsx(
492
1045
  ui.TextInput,
493
1046
  {
@@ -874,8 +1427,8 @@ var metadata = (schemaTypes, metadataFields) => sanity.defineType({
874
1427
  }
875
1428
  });
876
1429
  const documentInternationalization = sanity.definePlugin(
877
- (config) => {
878
- const pluginConfig = { ...DEFAULT_CONFIG, ...config }, {
1430
+ (config2) => {
1431
+ const pluginConfig = { ...DEFAULT_CONFIG, ...config2 }, {
879
1432
  supportedLanguages,
880
1433
  schemaTypes,
881
1434
  languageField,
@@ -893,6 +1446,9 @@ const documentInternationalization = sanity.definePlugin(
893
1446
  layout: (props) => DocumentInternationalizationProvider({ ...props, pluginConfig })
894
1447
  }
895
1448
  },
1449
+ i18n: {
1450
+ bundles: [documentInternationalizationUsEnglishLocaleBundle]
1451
+ },
896
1452
  // Adds:
897
1453
  // - A bulk-publishing UI component to the form
898
1454
  // - Will only work for projects on a compatible plan
@@ -1032,6 +1588,7 @@ const documentInternationalization = sanity.definePlugin(
1032
1588
  );
1033
1589
  exports.DeleteTranslationAction = DeleteTranslationAction;
1034
1590
  exports.DocumentInternationalizationMenu = DocumentInternationalizationMenu;
1591
+ exports.DuplicateWithTranslationsAction = DuplicateWithTranslationsAction;
1035
1592
  exports.documentInternationalization = documentInternationalization;
1036
1593
  exports.useDocumentInternationalizationContext = useDocumentInternationalizationContext;
1037
1594
  //# sourceMappingURL=index.js.map