-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathplugin.tsx
More file actions
1019 lines (901 loc) · 38 KB
/
Copy pathplugin.tsx
File metadata and controls
1019 lines (901 loc) · 38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Removed commerce plugin tools dependency
import pkg from '../package.json';
import appState from '@builder.io/app-context';
import uniq from 'lodash/uniq';
import isEqual from 'lodash/isEqual';
import {
getTranslationModelTemplate,
getTranslationModel,
translationModelName,
} from './model-template';
import {
registerBulkAction,
registerContentAction,
registerContextMenuAction,
CustomReactEditorProps,
fastClone,
registerEditorOnLoad,
} from './plugin-helpers';
import { SmartlingConfigurationEditor } from './smartling-configuration-editor';
import { SmartlingApi, Project } from './smartling';
import { showJobNotification, showOutdatedNotifications } from './snackbar-utils';
import { Builder } from '@builder.io/react';
import React from 'react';
import { getTranslateableFields } from '@builder.io/utils';
import hash from 'object-hash';
import stringify from 'fast-json-stable-stringify';
// translation status that indicate the content is being queued for translations
const enabledTranslationStatuses = ['pending', 'local'];
// Cache for job existence checks to avoid repeated API calls
const jobExistenceCache = new Map<string, { exists: boolean; timestamp: number }>();
const CACHE_DURATION = 30000; // 30 seconds
// Helper function to check if content is actually in an active translation job
async function isContentInActiveTranslationJob(content: any, api: SmartlingApi): Promise<boolean> {
const translationStatus = content.meta?.get('translationStatus');
const translationJobId = content.meta?.get('translationJobId');
// If no translation status or job ID, definitely not in active translation
if (!enabledTranslationStatuses.includes(translationStatus) || !translationJobId) {
return false;
}
// Check cache first
const cached = jobExistenceCache.get(translationJobId);
const now = Date.now();
if (cached && (now - cached.timestamp) < CACHE_DURATION) {
// If cached result shows job doesn't exist, clean up metadata
if (!cached.exists) {
// await api.cleanupOrphanedTranslationMetadata(content);
}
return cached.exists;
}
// Check if job actually exists
const jobExists = await api.checkTranslationJobExists(translationJobId);
// Update cache
jobExistenceCache.set(translationJobId, { exists: jobExists, timestamp: now });
// If job doesn't exist, clean up metadata
if (!jobExists) {
// await api.cleanupOrphanedTranslationMetadata(content);
return false;
}
return true;
}
// Utility function to clear job existence cache (useful for testing/debugging)
function clearJobExistenceCache(): void {
jobExistenceCache.clear();
}
function updatePublishCTA(content: any, translationModel: any) {
let publishButtonText = undefined;
let publishedToastMessage = undefined;
// establish that it's a job's content entry that we are currently in
if (content?.modelId === translationModel?.id) {
const pluginSettings = appState.user.organization?.value?.settings?.plugins?.get(pkg.name);
if (!pluginSettings) {
return;
}
const enableJobAutoAuthorization = pluginSettings.get('enableJobAutoAuthorization');
const isJobAlreadyPublished = content.published === 'published';
const hasEntries = content.data?.get('entries')?.length > 0;
// Check if the job has been sent to Smartling (status 'pending') - if so, disable CTA
const hasEntriesWithPendingStatus = content.data?.get('entries')?.some((entry: any) => {
return entry?.meta?.translationStatus === 'pending';
});
if (hasEntriesWithPendingStatus) {
// Job has been sent to Smartling, disable the publish button
publishButtonText = undefined;
publishedToastMessage = undefined;
} else {
// Job is still local, allow publishing but remove "Update" language
// if 'enableJobAutoAuthorization' is undefined then assume it to be true and proceed likewise
if (enableJobAutoAuthorization === undefined || enableJobAutoAuthorization === true) {
publishButtonText = 'Authorize';
publishedToastMessage = 'Authorized';
} else {
publishButtonText = 'Send to Smartling';
publishedToastMessage = 'Sent to Smartling';
}
}
}
appState.designerState.editorOptions.publishButtonText = publishButtonText;
appState.designerState.editorOptions.publishedToastMessage = publishedToastMessage;
}
// Register the Smartling plugin
Builder.register('plugin', {
name: 'Smartling',
id: pkg.name,
settings: [
{
name: 'accountUid',
type: 'string',
required: true,
},
{
name: 'userId',
type: 'string',
required: true,
},
{
name: 'tokenSecret',
type: 'password',
required: true,
hideFromUI: false,
},
{
name: 'enableJobAutoAuthorization',
friendlyName: 'Authorize Smartling Jobs through Builder',
type: 'boolean',
defaultValue: true,
advanced: false,
helperText: 'Allows users to authorize Smartling jobs directly from Builder',
requiredPermissions: ['admin'],
},
{
name: 'copySmartlingLocales',
friendlyName: 'Copy Locales from Smartling to Builder',
type: 'boolean',
defaultValue: true,
helperText: 'This will copy locales from Smartling to Builder',
requiredPermissions: ['admin'],
},
{
name: 'defaultProjectId',
friendlyName: 'Default Smartling Project',
type: 'SmartlingProject',
helperText: 'Default project to use for new translation jobs',
advanced: false,
requiredPermissions: ['admin'],
},
{
name: 'enableVisualContextCapture',
friendlyName: 'Enable Visual Context Capture',
type: 'boolean',
defaultValue: false,
helperText: 'Enable automatic visual context capture for translations',
requiredPermissions: ['admin'],
},
],
onSave: async actions => {
const pluginPrivateKey = await appState.globalState.getPluginPrivateKey(pkg.name);
if (!getTranslationModel()) {
actions.addModel(
getTranslationModelTemplate(pluginPrivateKey, appState.user.apiKey, pkg.name) as any
);
}
},
ctaText: `Save plugin settings`,
});
// Create API instance for plugin use
const api = new SmartlingApi();
let isInitialized = false;
// Initialize plugin functionality
const initializeSmartlingPlugin = async () => {
if (isInitialized) {
return;
}
isInitialized = true;
// Wait for API to initialize - this should always happen
await api.loaded;
// Get plugin settings - but don't return early if they don't exist
const pluginSettings = appState.user.organization?.value?.settings?.plugins?.get(pkg.name);
// Ensure enableJobAutoAuthorization defaults to true if settings exist
if (pluginSettings && pluginSettings.get('enableJobAutoAuthorization') === undefined) {
pluginSettings.set('enableJobAutoAuthorization', true);
}
const settings = pluginSettings;
const copySmartlingLocales = settings?.get('copySmartlingLocales');
// Update model template and model exists
const existingModel = getTranslationModel();
if (existingModel) {
const pluginPrivateKey = await appState.globalState.getPluginPrivateKey(pkg.name);
const updatedTemplate = getTranslationModelTemplate(
pluginPrivateKey,
appState.user.apiKey,
pkg.name
);
// Check if webhook URL needs updating - update whenever the URL is different
const currentWebhookUrl = existingModel.webhooks?.[0]?.url;
const newWebhookUrl = updatedTemplate.webhooks[0].url;
if (currentWebhookUrl !== newWebhookUrl) {
// Update the existing model with new webhook configuration
existingModel.webhooks = updatedTemplate.webhooks;
}
}
registerEditorOnLoad(({ safeReaction }) => {
safeReaction(
() => {
return String(appState.designerState.editingContentModel?.lastUpdated || '');
},
async shouldCheck => {
if (!shouldCheck) {
return;
}
updatePublishCTA(appState.designerState.editingContentModel, getTranslationModel());
const translationStatus = appState.designerState.editingContentModel.meta.get(
'translationStatus'
);
const translationRequested = appState.designerState.editingContentModel.meta.get(
'translationRequested'
);
// check if there's pending translation
const isFresh =
appState.designerState.editingContentModel.lastUpdated > new Date(translationRequested);
if (!isFresh) {
return;
}
const content = fastClone(appState.designerState.editingContentModel);
const isPending = translationStatus === 'pending';
const projectId = content.meta?.translationBatch?.projectId;
if (isPending && projectId && content.published === 'published') {
const lastPublishedContent = await fetch(
`https://cdn.builder.io/api/v3/content/${appState.designerState.editingModel.name}/${content.id}?apiKey=${appState.user.apiKey}&cachebust=true`
).then(res => res.json());
const res = await api.getProject(projectId);
const sourceLocale = res.project?.sourceLocaleId;
const translatableFields = getTranslateableFields(
lastPublishedContent,
sourceLocale,
''
);
const currentRevision = hash(stringify(translatableFields), {
encoding: 'base64',
});
appState.designerState.editingContentModel.meta.set(
'translationRevisionLatest',
currentRevision
);
if (currentRevision !== content.meta.translationRevision) {
showOutdatedNotifications(async () => {
appState.globalState.showGlobalBlockingLoading('Contacting Smartling ....');
await api.updateTranslationFile({
translationJobId: lastPublishedContent.meta.translationJobId,
translationModel: translationModelName,
contentId: lastPublishedContent.id,
contentModel: appState.designerState.editingModel.name,
preview: lastPublishedContent.meta.lastPreviewUrl,
});
appState.globalState.hideGlobalBlockingLoading();
});
}
}
},
{
fireImmediately: true,
}
);
});
// assign locales to custom targeting attributes
Builder.nextTick(async () => {
const projectResponse = await api.getAllProjects();
let allProjectsWithLocales: Project[] = [];
for (let index = 0; index < projectResponse.results.length; index++) {
// avoid exceeding rate limit of 5 requests per second from smartling
if (index % 5 === 0) {
await delay(1000);
}
allProjectsWithLocales.push(
await api.getProject(projectResponse.results[index].projectId).then(res => res.project)
);
}
const smartlingLocales = uniq(
allProjectsWithLocales
.map(project =>
project.targetLocales
.filter(locale => locale.enabled)
.map(locale => locale.localeId)
.concat(project.sourceLocaleId)
)
.reduce((acc, val) => acc.concat(val), [])
);
const currentLocales = appState.user.organization.value.customTargetingAttributes
?.get('locale')
?.toJSON();
let combinedLocales = [...new Set([...smartlingLocales, ...currentLocales?.enum || []])];
if (copySmartlingLocales) {
//merge builder locales with smartling locales (all unique locales)
if(!isEqual(currentLocales?.enum, combinedLocales)){
appState.user.organization.value.customTargetingAttributes?.get('locale').set('enum', combinedLocales);
}
}
});
// create a new action on content to add to job
registerBulkAction({
label: 'Translate',
showIf(selectedContentIds, content, model) {
const translationModel = getTranslationModel();
if (!model || !translationModel || model.name === translationModel.name) {
return false;
}
const hasActiveTranslationPending = selectedContentIds.find(id => {
const fullContent = content.find(entry => entry.id === id);
const translationStatus = fullContent.meta?.get('translationStatus');
const translationJobId = fullContent.meta?.get('translationJobId');
const translationRevision = fullContent.meta?.get('translationRevision');
const translationRevisionLatest = fullContent.meta?.get('translationRevisionLatest');
// If content has translation status but no job ID, it's orphaned - allow action
if (enabledTranslationStatuses.includes(translationStatus) && !translationJobId) {
return false; // Not pending (orphaned)
}
// If content has changes (different revisions), allow re-translation
if (translationRevision && translationRevisionLatest && translationRevision !== translationRevisionLatest) {
return false; // Has changes, allow action
}
// If content has active translation status and is currently being edited with unsaved changes, allow action
if (enabledTranslationStatuses.includes(translationStatus) &&
appState.designerState.editingContentModel?.id === fullContent.id &&
appState.designerState.hasUnsavedChanges()) {
return false; // Has unsaved changes in currently edited content, allow action
}
// If content has both status and job ID, check cache
if (enabledTranslationStatuses.includes(translationStatus) && translationJobId) {
// Trigger background validation for each item
isContentInActiveTranslationJob(fullContent, api).catch(() => {});
// Check cache
const cached = jobExistenceCache.get(translationJobId);
if (cached && (Date.now() - cached.timestamp) < CACHE_DURATION) {
return cached.exists; // Return whether job exists
}
// Default to pending while validating
return true;
}
return false; // No translation status
});
return appState.user.can('publish') && !hasActiveTranslationPending;
},
async onClick(actions, selectedContentIds, contentEntries) {
let translationJobId = await pickTranslationJob();
const selectedContent = selectedContentIds.map(id =>
contentEntries.find(entry => entry.id === id)
);
const filteredContent = selectedContent.filter(content => content);
if (translationJobId === null) {
const name = await appState.dialogs.prompt({
placeholderText: 'Enter a name for your new job',
});
if (name) {
// Use enhanced job creation that supports both v1 and v2
const localJob = await api.createTranslationJob(name, filteredContent);
translationJobId = localJob.id;
}
} else if (translationJobId) {
// adding content to an already created job
await api.updateBatchTranslation(translationJobId, filteredContent);
// For changed content that was previously published, update translation files in Smartling
const changedPublishedContent = filteredContent.filter(entry => {
const translationRevision = entry.meta?.get('translationRevision');
const translationRevisionLatest = entry.meta?.get('translationRevisionLatest');
return entry.published === 'published' &&
translationRevision && translationRevisionLatest &&
translationRevision !== translationRevisionLatest;
});
if (changedPublishedContent.length > 0) {
await Promise.all(changedPublishedContent.map(async (entry) => {
try {
await api.updateTranslationFile({
translationJobId,
translationModel: getTranslationModel().name,
contentId: entry.id,
contentModel: appState.designerState.editingModel?.name || 'page',
preview: entry.meta?.get?.('lastPreviewUrl') || entry.meta?.lastPreviewUrl,
});
} catch (error) {
}
}));
}
}
await Promise.all(
filteredContent.map(entry => {
const metaUpdates: any = {
...fastClone(entry.meta),
translationStatus: 'local',
translationJobId,
};
// If content has changes (different revisions), update revision to latest
const translationRevision = entry.meta?.get('translationRevision');
const translationRevisionLatest = entry.meta?.get('translationRevisionLatest');
if (translationRevision && translationRevisionLatest && translationRevision !== translationRevisionLatest) {
metaUpdates.translationRevision = translationRevisionLatest;
}
return appState.updateLatestDraft({
id: entry.id,
modelId: entry.modelId,
meta: metaUpdates,
});
})
);
actions.refreshList();
showJobNotification(translationJobId);
},
});
const transcludedMetaKey = 'excludeFromTranslation';
registerContextMenuAction({
label: 'Exclude from future translations',
showIf(selectedElements) {
if (selectedElements.length !== 1) {
// todo maybe apply for multiple
return false;
}
const element = selectedElements[0];
const isExcluded = element.meta?.get(transcludedMetaKey);
return !isExcluded;
},
onClick(elements) {
elements.forEach(el => el.meta.set('excludeFromTranslation', true));
},
});
registerContextMenuAction({
label: 'Include in future translations',
showIf(selectedElements) {
if (selectedElements.length !== 1) {
// todo maybe apply for multiple
return false;
}
const element = selectedElements[0];
const isExcluded = element.meta?.get(transcludedMetaKey);
return isExcluded;
},
onClick(elements) {
elements.forEach(el => el.meta.set('excludeFromTranslation', false));
},
});
registerContextMenuAction({
label: 'Add String Instructions',
showIf(selectedElements) {
if (selectedElements.length !== 1) {
// todo maybe apply for multiple
return false;
}
const element = selectedElements[0];
return element.meta?.get('instructions') === undefined;
},
async onClick(elements) {
if (elements.length !== 1) {
// todo maybe apply for multiple
return false;
}
const instructions = await appState.dialogs.prompt({
placeholderText: 'Enter string instructions for translation',
});
if (instructions) {
elements[0].meta.set('instructions', instructions);
appState.snackBar.show('String instructions added to content');
}
},
});
registerContextMenuAction({
label: 'Edit String Instructions',
showIf(selectedElements) {
if (selectedElements.length !== 1) {
// todo maybe apply for multiple
return false;
}
const element = selectedElements[0];
return element.meta?.get('instructions') !== undefined;
},
async onClick(elements) {
if (elements.length !== 1) {
// todo maybe apply for multiple
return false;
}
const element = elements[0];
const instructions = element.meta?.get('instructions');
if (instructions !== undefined) {
const newInstructions = await appState.dialogs.prompt({
placeholderText: 'Enter new string instructions for translation',
defaultValue: instructions,
});
if (newInstructions) {
element.meta.set('instructions', newInstructions);
appState.snackBar.show('String instructions updated');
}
}
},
});
registerContextMenuAction({
label: 'Delete String Instructions',
showIf(selectedElements) {
if (selectedElements.length !== 1) {
// todo maybe apply for multiple
return false;
}
const element = selectedElements[0];
return element.meta?.get('instructions') !== undefined;
},
onClick(elements) {
elements[0].meta.delete('instructions');
appState.snackBar.show('String instructions deleted');
},
});
registerContentAction({
label: 'Add to translation job',
showIf(content, model) {
const translationModel = getTranslationModel();
// Always show the action - we'll handle unconfigured state in onClick
if (!translationModel) return true;
const translationStatus = content.meta?.get('translationStatus');
const translationJobId = content.meta?.get('translationJobId');
const translationRevision = content.meta?.get('translationRevision');
const translationRevisionLatest = content.meta?.get('translationRevisionLatest');
// Allow adding if:
// 1. Content is not in a translation model
// 2. AND content is not currently in an active translation job OR has changes
if (model?.name === translationModel.name) {
return false;
}
// If content has translation status but no job ID, allow adding (orphaned status)
if (enabledTranslationStatuses.includes(translationStatus) && !translationJobId) {
return true;
}
// If content has changes (different revisions), allow re-translation
if (translationRevision && translationRevisionLatest && translationRevision !== translationRevisionLatest) {
return true;
}
// If content has active translation status and is currently being edited with unsaved changes, allow re-translation
if (enabledTranslationStatuses.includes(translationStatus) &&
appState.designerState.editingContentModel?.id === content.id &&
appState.designerState.hasUnsavedChanges()) {
return true;
}
// If content has both status and job ID, validate job existence in background
if (enabledTranslationStatuses.includes(translationStatus) && translationJobId) {
// Trigger background validation and cleanup if needed
isContentInActiveTranslationJob(content, api).catch(() => {});
// Check cache for immediate result
const cached = jobExistenceCache.get(translationJobId);
if (cached && (Date.now() - cached.timestamp) < CACHE_DURATION) {
return !cached.exists; // Allow adding if job doesn't exist
}
// Default to hiding the action while we validate
return false;
}
// Content has no translation status, allow adding
return true;
},
async onClick(content) {
const translationModel = getTranslationModel();
if (!translationModel) {
appState.snackBar.show('Please configure the Smartling plugin in the plugins section first.');
return;
}
// If there are unsaved changes, wait for auto-save to complete
if (appState.designerState.hasUnsavedChanges()) {
// Give a moment for auto-save to complete and update metadata
await new Promise(resolve => setTimeout(resolve, 1000));
}
let translationJobId = await pickTranslationJob();
if (translationJobId === null) {
const name = await appState.dialogs.prompt({
placeholderText: 'Enter a name for your new job',
});
if (name) {
// Use enhanced job creation that supports both v1 and v2
const localJob = await api.createTranslationJob(name, [content]);
translationJobId = localJob.id;
} else {
return;
}
} else if (translationJobId) {
// adding content to an already created job
await api.updateBatchTranslation(translationJobId, [content]);
// For changed content that was previously published, update translation file in Smartling
const translationRevision = content.meta?.get('translationRevision');
const translationRevisionLatest = content.meta?.get('translationRevisionLatest');
const isChangedPublishedContent = content.published === 'published' && translationRevision && translationRevisionLatest && translationRevision !== translationRevisionLatest;
if (isChangedPublishedContent) {
try {
await api.updateTranslationFile({
translationJobId,
translationModel: getTranslationModel().name,
contentId: content.id,
contentModel: appState.designerState.editingModel?.name || 'page',
preview: content.meta?.get?.('lastPreviewUrl') || content.meta?.lastPreviewUrl,
});
} catch (error) {
}
}
}
const metaUpdates: any = {
...fastClone(content.meta),
translationStatus: 'local',
translationJobId,
translationBy: pkg.name,
};
// If content has changes (different revisions), update revision to latest
const translationRevision = content.meta?.get('translationRevision');
const translationRevisionLatest = content.meta?.get('translationRevisionLatest');
if (translationRevision && translationRevisionLatest && translationRevision !== translationRevisionLatest) {
metaUpdates.translationRevision = translationRevisionLatest;
}
await appState.updateLatestDraft({
id: content.id,
modelId: content.modelId,
meta: metaUpdates,
});
showJobNotification(translationJobId);
},
isDisabled() {
return false; // Allow action even with unsaved changes for re-translation scenarios
},
disabledTooltip: 'Will save changes automatically before adding to translation job',
});
registerContentAction({
label: 'Request an updated translation',
showIf(content, model) {
// Disabled: Users cannot currently update existing translation jobs
return false;
},
async onClick(content) {
appState.globalState.showGlobalBlockingLoading('Contacting Smartling ....');
const lastPublishedContent = await fetch(
`https://cdn.builder.io/api/v3/content/${appState.designerState.editingModel.name}/${content.id}?apiKey=${appState.user.apiKey}&cachebust=true`
).then(res => res.json());
await api.updateTranslationFile({
translationJobId: lastPublishedContent.meta.translationJobId,
translationModel: getTranslationModel().name,
contentId: lastPublishedContent.id,
contentModel: appState.designerState.editingModel.name,
preview: lastPublishedContent.meta.lastPreviewUrl,
});
appState.globalState.hideGlobalBlockingLoading();
},
});
registerContentAction({
label: 'Apply Translation',
showIf(content, model) {
const translationModel = getTranslationModel();
if (!translationModel) return false;
return content.published === 'published' && model?.name === translationModel.name;
},
async onClick(localTranslationJob) {
const translationModel = getTranslationModel();
appState.globalState.showGlobalBlockingLoading();
await api.applyTranslation(localTranslationJob.id, translationModel.name);
appState.globalState.hideGlobalBlockingLoading();
appState.snackBar.show('Done!');
},
});
registerContentAction({
label: 'View job in smartling',
showIf(content, model) {
const translationModel = getTranslationModel();
if (!translationModel) return false;
if (!model?.name || model.name !== translationModel.name) return false;
// translationBatch is set by backend after job is published
if (!content.meta || !content.data) return false;
const meta = fastClone(content.meta);
const data = content.data;
// Get project ID from jobDetails
const projectId = data?.get?.('jobDetails')?.get?.('project') || data?.get?.('jobDetails')?.project;
// Get job UID from translationBatch (only available after job is authorized in Smartling)
const translationJobUid = meta?.translationBatch?.translationJobUid;
return (
projectId &&
translationJobUid
);
},
async onClick(translationJob) {
if (!translationJob) {
appState.snackBar.show('Job information not available');
return;
}
if (!translationJob.meta || !translationJob.data) {
appState.snackBar.show('Job information not available');
return;
}
const meta = fastClone(translationJob.meta);
const data = translationJob.data;
// Get project ID from jobDetails
const projectId = data?.get?.('jobDetails')?.get?.('project') || data?.get?.('jobDetails')?.project;
// Get job UID from translationBatch
const translationJobUid = meta?.translationBatch?.translationJobUid;
if (!projectId || !translationJobUid) {
appState.snackBar.show('Job information not available');
return;
}
// Construct Smartling job URL with format: projectId:translationJobUid
const smartlingJobUrl = `https://dashboard.smartling.com/app/projects/${projectId}/account-jobs/${projectId}:${translationJobUid}`;
window.open(smartlingJobUrl, '_blank', 'noreferrer,noopener');
},
});
registerContentAction({
label: 'View translation job',
showIf(content, model) {
const translationModel = getTranslationModel();
if (!translationModel) {
return false;
}
const translationJobId = content.meta?.get('translationJobId');
if (model?.name === translationModel.name) {
return false;
}
if (!translationJobId) {
return false;
}
return true;
},
async onClick(content) {
const translationJobId = content.meta.get('translationJobId');
const translationModel = getTranslationModel();
if (translationJobId && translationModel) {
// Navigate to the specific translation job in Builder
appState.location.go(`/content/${translationJobId}`);
} else {
appState.snackBar.show('Translation job not found');
}
},
});
registerContentAction({
label: 'View translation strings in smartling',
showIf(content, model) {
const translationModel = getTranslationModel();
if (!translationModel) return false;
return model?.name !== translationModel.name && content.meta?.get('translationStatus') && ['completed', 'pending', 'local'].includes(content.meta?.get('translationStatus'));
},
async onClick(content) {
const translationBatch = fastClone(content.meta).translationBatch;
// Filter by file URI (content ID) to show all translations across all jobs
const smartlingFile = `https://dashboard.smartling.com/app/projects/${translationBatch.projectId}/strings/?urlsFilter.urls=${content.id}&limit=200&offset=0`;
window.open(smartlingFile, '_blank', 'noreferrer,noopener');
},
});
registerContentAction({
label: 'Clear translation metadata',
showIf(content, model) {
const translationModel = getTranslationModel();
if (!translationModel) return false;
const translationStatus = content.meta?.get('translationStatus');
const translationJobId = content.meta?.get('translationJobId');
// Show for content that has translation metadata but is not actively being translated
return (
model?.name !== translationModel.name &&
(translationJobId || translationStatus) &&
!enabledTranslationStatuses.includes(translationStatus)
);
},
async onClick(content) {
const result = await appState.dialogs.confirm({
message: 'This will clear all translation metadata from this content. Are you sure?',
});
if (result) {
const updatedMeta = { ...content.meta?.toJS() };
delete updatedMeta.translationStatus;
delete updatedMeta.translationJobId;
delete updatedMeta.translationBy;
delete updatedMeta.translationRevision;
delete updatedMeta.translationRevisionLatest;
delete updatedMeta.translationBatch;
delete updatedMeta.translationRequested;
await appState.updateLatestDraft({
id: content.id,
modelId: content.modelId,
meta: updatedMeta,
});
appState.snackBar.show('Translation metadata cleared.');
}
},
});
registerContentAction({
label: 'Remove from translation job',
showIf(content, model) {
const translationModel = getTranslationModel();
if (!translationModel) return false;
const translationStatus = content.meta?.get('translationStatus');
const translationJobId = content.meta?.get('translationJobId');
if (model?.name === translationModel.name) {
return false;
}
// Only show if content has both job ID and active status
if (!translationJobId || !enabledTranslationStatuses.includes(translationStatus)) {
return false;
}
// Trigger background validation and cleanup if needed
isContentInActiveTranslationJob(content, api).catch(() => {});
// Check cache for immediate result
const cached = jobExistenceCache.get(translationJobId);
if (cached && (Date.now() - cached.timestamp) < CACHE_DURATION) {
return cached.exists; // Show only if job exists
}
// Default to showing while we validate
return true;
},
async onClick(content) {
appState.globalState.showGlobalBlockingLoading();
await api.removeContentFromTranslationJob({
contentId: content.id,
contentModel: appState.designerState.editingModel.name,
translationJobId: content.meta.get('translationJobId'),
translationModel: translationModelName,
});
appState.globalState.hideGlobalBlockingLoading();
appState.snackBar.show('Removed from translation job.');
},
});
Builder.registerEditor({
name: 'SmartlingConfiguration',
component: (props: CustomReactEditorProps) => {
return <SmartlingConfigurationEditor {...props} api={api} />;
},
});
};
// Register SmartlingProject editor for project selection - must be outside async init
Builder.registerEditor({
name: 'SmartlingProject',
component: (props: any) => {
const [projects, setProjects] = React.useState<Project[]>([]);
const [loading, setLoading] = React.useState(false);
React.useEffect(() => {
const loadProjects = async () => {
setLoading(true);
try {
const response = await api.getAllProjects();
const projectsWithDetails = [];
for (const proj of response.results) {
const details = await api.getProject(proj.projectId);
projectsWithDetails.push(details.project);
}
setProjects(projectsWithDetails);
} catch (error) {
// If we can't load projects, set an empty array so the select still renders
setProjects([]);
}
setLoading(false);
};
loadProjects();
}, []);
return React.createElement(
React.Fragment,
{},
loading
? React.createElement(
'div',
{ style: { textAlign: 'center' } },
React.createElement('span', {}, 'Loading projects...')
)
: React.createElement(
'select',
{
value: props.value || '',
onChange: (e: any) => props.onChange(e.target.value),
disabled: loading,
style: {
width: '100%',
padding: '8px 12px',
border: '1px solid #ccc',
borderRadius: '4px',
fontSize: '14px',
cursor: 'pointer',
fontFamily: 'inherit'
}
},
[
React.createElement('option', { key: '', value: '' }, 'Select a project...'),
...projects.map(project =>
React.createElement('option', {
key: project.projectId,
value: project.projectId
}, project.projectName)
)
]
)
);
},
});
// Initialize the plugin when settings are available
Builder.nextTick(() => {
initializeSmartlingPlugin();
});
function pickTranslationJob() {