-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathBatchRenamer.jsx
More file actions
executable file
·1728 lines (1503 loc) · 57.8 KB
/
BatchRenamer.jsx
File metadata and controls
executable file
·1728 lines (1503 loc) · 57.8 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
/*
BatchRenamer.jsx for Adobe Illustrator
Description: Script for batch renaming artboards, layers & selected items manually or by placeholders.
Find & Replace supports regular expressions.
Date: January, 2022
Modification date: September, 2025
Original idea by Qwertyfly:
https://community.adobe.com/t5/illustrator-discussions/is-there-a-way-to-batch-rename-artboards-in-illustrator-cc/m-p/7243667#M153618
Modification by Sergey Osokin, email: hi@sergosokin.ru
Installation: https://github.com/creold/illustrator-scripts#how-to-run-scripts
Release notes:
1.6 The placeholders have been replaced with a selectable dropdown list.
Prefixes and suffixes are set by index range, and checkboxes have been removed.
Added case conversion modes.
Minor improvements
1.5 Added custom range for Find and Replace. Minor improvements
1.4 Added import names from txt and export names into txt from active tab
1.3.3 Added display symbol object names
1.3.2 Fixed rename bug
1.3.1 Added display of text frame content as name if it is empty
1.3 Info about number of artboards, layers, selected document objects added to {nu}, {nd} placeholder text. Minor improvements
1.2.4a Fixed problem launching through LAScripts extension
1.2.4 Added {f} placeholder to insert a filename
1.2.3 Added new units API for CC 2023 v27.1.1
1.2.2 Added size correction in large canvas mode
1.2.1 Added custom RGB color (idxColor) for artboard indexes
1.2 Added more units (yards, meters, etc.) support if the document is saved
1.1.1 Fixed load user settings
1.1 Minor improvements
1.0 Fixed variables, scrollbar in original script by Qwertyfly
Added tabs for batch rename Artboards, Layers, Paths
Added 'Select all' checkboxes, 'Find and Replace' algorithm
Addedd save and load user settings
Added placeholders for batch rename
Donate (optional):
If you find this script helpful, you can buy me a coffee
- via Buymeacoffee: https://www.buymeacoffee.com/aiscripts
- via Donatty https://donatty.com/sergosokin
- via DonatePay https://new.donatepay.ru/en/@osokin
- via YooMoney https://yoomoney.ru/to/410011149615582
NOTICE:
Tested with Adobe Illustrator CC 2019-2025 (Mac/Win).
This script is provided "as is" without warranty of any kind.
Free to use, not for sale
Released under the MIT license
http://opensource.org/licenses/mit-license.php
Check my other scripts: https://github.com/creold
*/
//@target illustrator
app.preferences.setBooleanPreference('ShowExternalJSXWarning', false); // Fix drag and drop a .jsx file
// MAIN DIALOG
function main() {
if (!/illustrator/i.test(app.name)) {
alert('Wrong application\nRun script from Adobe Illustrator', 'Script error');
return;
}
if (!app.documents.length) {
alert('No documents\nOpen a document and try again', 'Script error');
return;
}
var SCRIPT = {
name: 'Batch Renamer',
version: 'v1.6'
};
// CONFIG
var CFG = {
rows: 7, // Enter amount of visible rows
precision: 2, // Decimal places. Rounding object width and height
decimal: ',', // Decimal separator for width and height
isShowIndex: true, // Show (true) or not (false) temporary artboard indexes
indexColor: [255, 0, 0], // Color for temporary artboard indexes
tmpLayer: 'ARTBOARD_INDEX', // Layer for temporary artboard indexes
isFind: false, // Default Find and Replace state
sf: app.activeDocument.scaleFactor ? app.activeDocument.scaleFactor : 1, // Scale factor for Large Canvas mode
isUndo: false,
uiOpacity: .97, // UI window opacity. Range 0-1
};
// Calculate height of list of names
CFG.listHeight = CFG.rows * 32;
var doc = app.activeDocument;
var absLength = doc.artboards.length;
var lyrsLength = doc.layers.length;
var selLength = app.selection.length;
// PLACEHOLDERS
var PH = {
color: '{c}',
date: '{d}',
time: '{t}',
file: '{f}',
height: '{h}',
dateDMY: '{dmy}',
dateMDY: '{mdy}',
dateYMD: '{ymd}',
numDown: '{nd:0}',
numUp: '{nu:0}',
units: '{u}',
width: '{w}',
};
// PLACEHOLDERS MAP
var PH_MAP = [
{ placeholder: '', description: '@', isAllTab: true }, // Dummy top item
{ placeholder: PH.width, description: PH.width + ' - Width', isAllTab: false }, // Not used for layers tab
{ placeholder: PH.height, description: PH.height + ' - Height', isAllTab: false }, // Not used for layers tab
{ placeholder: PH.units, description: PH.units + ' - Ruler Units', isAllTab: false }, // Not used for layers tab
{ placeholder: PH.numUp.replace(/\d+/g, absLength), description: PH.numUp + ' - Auto-Number Up', isAllTab: true },
{ placeholder: PH.numDown.replace(/\d+/g, absLength), description: PH.numDown + ' - Auto-Number Down', isAllTab: true },
{ placeholder: PH.color, description: PH.color + ' - Color Space', isAllTab: true },
{ placeholder: PH.dateDMY, description: PH.dateDMY + ' - Date ' + getCurrentDate(PH.dateDMY), isAllTab: true },
{ placeholder: PH.dateMDY, description: PH.dateMDY + ' - Date ' + getCurrentDate(PH.dateMDY), isAllTab: true },
{ placeholder: PH.dateYMD, description: PH.dateYMD + ' - Date ' + getCurrentDate(PH.dateYMD), isAllTab: true },
{ placeholder: PH.time, description: PH.time + ' - Time HH:MM', isAllTab: true },
{ placeholder: PH.file, description: PH.file + ' - File Name', isAllTab: true },
];
var MSG = {
all: 'All Names',
cancel: 'Cancel',
caseTitle: 'Name Case Conversion',
copyright: 'Visit Github',
empty: 'No Objects Are Selected',
enable: 'Enable',
exportBtn: 'Export',
exportTitle: 'Choose a folder to export TXT file...',
exportHint: 'Export names from active tab\ninto a TXT file',
exportSuccess: 'Your file @ has been saved successfully',
find: 'Find:',
findHint: 'Tip: Find Supports RegExp. Example: ^.*$ - Find Full Name',
findTitle: 'Find and Replace',
importBtn: 'Import',
importTitle: 'Choose TXT file...',
importHint: 'Import names to active tab\nfrom a TXT file. Start each name\non a new line',
importSuccess: 'Your file * has been imported successfully into the active tab',
nameAb: 'Artboard Names',
nameLyr: 'Layer Names',
namePath: 'Object Names',
ok: 'OK',
prefix: 'Prefix:',
previewBtn: 'Preview',
previewOn: 'PREVIEW ON',
range: 'Range:',
rangeEg: 'E.g. "1, 3-5, 9" > 1, 3, 4, 5, 9',
replace: 'Replace With:',
suffix: 'Suffix:',
tabAb: 'ARTBOARDS',
tabLyr: 'LAYERS',
tabPath: 'OBJECTS',
};
var SETTINGS = {
name: SCRIPT.name.replace(/\s/g, '_') + '_data.json',
folder: Folder.myDocuments + '/Adobe Scripts/'
};
var abs = initObject(CFG.isFind, 'artboards'); // Artboards
var lyrs = initObject(CFG.isFind, 'layers'); // Layers
var paths = initObject(CFG.isFind, 'selection'); // Selected objects
var absPH = initPlaceholders('artboards', PH); // Artboard placeholders
var lyrsPH = initPlaceholders('layers', PH); // Layers placeholders
var pathsPH = initPlaceholders('paths', PH); // Paths placeholders
var rowItem = []; // List rows
// Init prefix, index, original name and suffix
abs.state = initData(doc.artboards);
lyrs.state = initData(doc.layers);
paths.state = initData(app.selection);
// DIALOG
var win = new Window('dialog', SCRIPT.name + ' ' + SCRIPT.version);
win.orientation = 'row';
win.alignChildren = ['fill', 'fill'];
win.opacity = CFG.uiOpacity;
// LEFT WRAPPER FOR MAIN CONTROLS
var lWrapper = win.add('group');
lWrapper.orientation = 'column';
lWrapper.alignChildren = ['fill', 'top'];
// TABS
var tabPnl = lWrapper.add('tabbedpanel');
tabPnl.alignChildren = ['fill', 'top'];
var absTab = tabPnl.add('tab', undefined, MSG.tabAb); // Artboard
var lyrsTab = tabPnl.add('tab', undefined, MSG.tabLyr); // Layer
var pathsTab = tabPnl.add('tab', undefined, MSG.tabPath); // Path
absTab.margins = lyrsTab.margins = pathsTab.margins = [10, 20, 0, 5];
tabPnl.selection = 0;
// FILL TABS CONTENT
var absTabData = addTabContent(absTab, abs, MSG, MSG.nameAb, PH_MAP);
var lyrsTabData = addTabContent(lyrsTab, lyrs, MSG, MSG.nameLyr, PH_MAP);
var pathsTabData = addTabContent(pathsTab, paths, MSG, MSG.namePath, PH_MAP);
// RIGHT WRAPPER FOR BUTTONS AND INFO
var rWrapper = win.add('group');
rWrapper.orientation = 'column';
rWrapper.spacing = 20;
rWrapper.alignChildren = ['fill', 'fill'];
var btns1 = rWrapper.add('group');
btns1.orientation = 'column';
btns1.alignment = ['fill', 'top'];
var ok = btns1.add('button', undefined, MSG.ok, { name: 'ok' });
var cancel = btns1.add('button', undefined, MSG.cancel, { name: 'cancel' });
var btns2 = rWrapper.add('group');
btns2.orientation = 'column';
btns2.alignment = ['fill', 'top'];
var previewBtn = btns2.add('button', undefined, MSG.previewBtn);
var importBtn = btns2.add('button', undefined, MSG.importBtn);
importBtn.helpTip = MSG.importHint;
var exportBtn = btns2.add('button', undefined, MSG.exportBtn);
exportBtn.helpTip = MSG.exportHint;
var copyright = rWrapper.add('statictext', undefined, MSG.copyright);
copyright.justify = 'center';
copyright.alignment = ['fill', 'bottom'];
// DIALOG EVENTS
loadSettings(SETTINGS);
cancel.onClick = win.close;
ok.onClick = okClick;
// DIALOG LOCAL FUNCTIONS
win.onShow = function () {
if (CFG.isShowIndex) {
showArboardIndex(CFG.tmpLayer, CFG.indexColor);
}
adjustScrollMax(absTabData, 20);
adjustScrollMax(lyrsTabData, 20);
adjustScrollMax(pathsTabData, 20);
}
win.onClose = function () {
try {
if (CFG.isUndo) app.undo();
} catch (err) {}
isUndo = false;
}
/**
* Open a dialog to select a text file, parses its contents, and updates the selected objects
*/
importBtn.onClick = function() {
// Determine the file type filter based on the operating system
var type = ($.os.match('Windows')) ? '*.txt;' : function(f) {
return f instanceof Folder || (f instanceof File && f.name.match(/(.txt)$/));
};
var f = File.openDialog(MSG.importTitle, type, false); // Open a dialog to select a file
var txtArr = parseFromText(f); // Parse the selected file into an array of text lines
// Determine the object to update based on the current selection
var obj = tabPnl.selection.text.match(MSG.tabAb) ? abs : (tabPnl.selection.text.match(MSG.tabLyr) ? lyrs : paths);
var min = Math.min(txtArr.length, obj.names.length);
// Iterate over the text array and updates the object names
for (var i = 0; i < min; i++) {
var str = txtArr[i];
if (isEmpty(str)) continue;
obj.names[i].text = str;
obj.state[i].customName = str;
}
alert( MSG.importSuccess.replace(/\*/, decodeURIComponent(f.name)) );
}
/**
* Prompts the user to select a folder, processes the selected items, and exports the result as a text file
*/
exportBtn.onClick = function() {
var path = Folder.selectDialog(MSG.exportTitle);
if (path == null) return;
var type = tabPnl.selection.text.replace(/\s+.+/g, '').toLowerCase();
var f = new File(path + '/' + doc.name.replace(/\.[^\.]+$/, '') + '_' + type + '.txt');
var txtArr = [];
if (tabPnl.selection.text.match(MSG.tabAb)) {
txtArr = generateNames(doc.artboards, CFG, PH, abs, absPH);
} else if (tabPnl.selection.text.match(MSG.tabLyr)) {
txtArr = generateNames(doc.layers, CFG, PH, lyrs, lyrsPH);
} else {
txtArr = generateNames(app.selection, CFG, PH, paths, pathsPH);
}
if (txtArr.length) {
writeToText(txtArr.join('\n'), f);
alert( MSG.exportSuccess.replace(/\@/, decodeURIComponent(f.name)) );
}
}
/**
* Update the preview title text and triggers preview names for artboards, layers, and selected items
*/
previewBtn.onClick = function () {
this.active = true;
this.active = false;
// Update the preview title text for different tabs
absTabData.prvwTitle.text = lyrsTabData.prvwTitle.text = MSG.previewOn;
// Check if paths tab has preview title and update it
if (pathsTabData.hasOwnProperty('prvwTitle')) {
pathsTabData.prvwTitle.text = MSG.previewOn;
}
// Trigger preview names for artboards, layers, and selected paths
previewNames(doc.artboards, CFG, PH, abs, absPH);
previewNames(doc.layers, CFG, PH, lyrs, lyrsPH);
previewNames(app.selection, CFG, PH, paths, pathsPH);
try {
if (CFG.isUndo) {
doc.swatches.add().remove();
app.undo();
}
renameObjects(doc.artboards, CFG, PH, abs, absPH);
renameObjects(doc.layers, CFG, PH, lyrs, lyrsPH);
renameObjects(app.selection, CFG, PH, paths, pathsPH);
var tempPath = doc.layers[0].pathItems.rectangle(0, 0, 1, 1);
tempPath.stroked = false;
tempPath.filled = false;
tempPath.hidden = true;
tempPath.hidden = false;
app.redraw();
CFG.isUndo = true;
} catch (err) {}
}
/**
* Add content to a specified tab in the UI
* @param {Object} tab - The tab object to which content will be added
* @param {Object} data - The data object containing state information
* @param {Object} txt - The text object containing UI text elements
* @param {string} name - The name of the tab
* @param {Array} phMap - The placeholder map for dropdown lists
* @returns {Object} An object containing references to UI elements
*/
function addTabContent(tab, data, txt, name, phMap) {
// Paths tab when nothing is selected
if (tab.text === txt.tabPath && !selLength) {
var pathList = tab.add('group');
pathList.alignment = 'center';
pathList.add('statictext', undefined, txt.empty);
return {};
}
var tabList = tab.add('group');
tabList.orientation = 'column';
// TITLE
var header = tabList.add('group');
header.alignment = 'left';
header.add('statictext', undefined, name);
var prvwTitle = header.add('statictext', undefined, '');
prvwTitle.preferredSize.width = 100;
// ITEM ROWS
var scrollWin = tabList.add('group');
scrollWin.alignChildren = 'fill';
var pageListPanel = scrollWin.add('panel');
pageListPanel.alignChildren = 'left';
// GENERATE LIST
if (data.state.length <= CFG.rows) { // Without scroll
for (var i = 0, osLen = data.state.length; i < osLen; i++) {
rowItem = pageListPanel.add('group');
// rowItem.margins = [3, 0, 0, 0];
addNewRow(tab, i, rowItem, data);
}
} else { // With scroll
pageListPanel.maximumSize.height = CFG.listHeight;
var smallList = pageListPanel.add('group');
smallList.orientation = 'column';
smallList.alignment = 'left';
smallList.maximumSize.height = data.state.length * 200;
var scroll = scrollWin.add('scrollbar');
scroll.stepdelta = 30;
scroll.preferredSize.width = 12;
scroll.maximumSize.height = pageListPanel.maximumSize.height;
for (var i = 0, osLen = data.state.length; i < osLen; i++) {
rowItem = smallList.add('group');
addNewRow(tab, i, rowItem, data);
}
scroll.onChanging = function() {
smallList.location.y = -1 * this.value;
}
}
// PLACEHOLDER DROPDOWN
var phDescrList = [];
var phKeyList = [];
for (var i = 0; i < phMap.length; i++) {
if (tab.text === txt.tabLyr && !phMap[i].isAllTab) continue;
phDescrList.push(phMap[i].description);
phKeyList.push(phMap[i].placeholder);
}
// PREFIX AND SUFFIX
var extra = tab.add('group');
extra.orientation = 'column';
extra.alignChildren = ['fill', 'top'];
extra.margins = [5, 20, 5, 0];
var preSuffGrp = extra.add('group');
preSuffGrp.orientation = 'column';
preSuffGrp.alignChildren = ['fill', 'top'];
preSuffGrp.margins = [0, 0, 0, 10];
var prefixGrp = preSuffGrp.add('group');
prefixGrp.orientation = 'row';
prefixGrp.alignChildren = ['fill', 'center'];
prefixGrp.add('statictext', undefined, txt.prefix);
var prefixInp = prefixGrp.add('edittext', undefined, '');
prefixInp.preferredSize.width = 139;
var prefixPhDdl = prefixGrp.add('dropdownlist', undefined, phDescrList);
prefixPhDdl.maximumSize.width = 40;
prefixPhDdl.selection = 0;
prefixGrp.add('statictext', undefined, txt.range);
var prefixRangeInp = prefixGrp.add('edittext', undefined, '1-' + data.state.length);
prefixRangeInp.preferredSize.width = 90;
prefixRangeInp.helpTip = txt.rangeEg;
var suffixGrp = preSuffGrp.add('group');
suffixGrp.orientation = 'row';
suffixGrp.alignChildren = ['fill', 'center'];
suffixGrp.add('statictext', undefined, txt.suffix);
var suffixInp = suffixGrp.add('edittext', undefined, '');
suffixInp.preferredSize.width = 140;
var suffixPhDdl = suffixGrp.add('dropdownlist', undefined, phDescrList);
suffixPhDdl.maximumSize.width = 40;
suffixPhDdl.selection = 0;
suffixGrp.add('statictext', undefined, txt.range);
var suffixRangeInp = suffixGrp.add('edittext', undefined, '1-' + data.state.length);
suffixRangeInp.preferredSize.width = 90;
suffixRangeInp.helpTip = txt.rangeEg;
// FIND AND REPLACE
var findRplcPnl = extra.add('panel', undefined, txt.findTitle);
findRplcPnl.alignChildren = ['fill', 'top'];
findRplcPnl.margins = [10, 15, 10, 10];
var isFindRplc = findRplcPnl.add('checkbox', undefined, txt.enable);
isFindRplc.value = CFG.isFind;
var findStrGrp = findRplcPnl.add('group');
findStrGrp.orientation = 'row';
findStrGrp.alignChildren = ['fill', 'top'];
var findGrp = findStrGrp.add('group');
findGrp.add('statictext', undefined, txt.find);
var findInp = findGrp.add('edittext', undefined, '');
findInp.preferredSize.width = 110;
findInp.enabled = CFG.isFind;
var rplcGrp = findStrGrp.add('group');
rplcGrp.add('statictext', undefined, txt.replace);
var replaceInp = rplcGrp.add('edittext', undefined, '');
replaceInp.preferredSize.width = 110;
replaceInp.enabled = CFG.isFind;
var findHint = findRplcPnl.add('statictext', undefined, txt.findHint);
findHint.addEventListener('mousedown', function () {
if (!isFindRplc.value) return;
findInp.active = true;
findInp.textselection = findInp.text + '^.*$';
});
var rangeStrGrp = findRplcPnl.add('group');
rangeStrGrp.margins = [0, 10, 0, 0];
var rangeRadioGrp = rangeStrGrp.add('group');
rangeRadioGrp.enabled = CFG.isFind;
var findAllRange = rangeRadioGrp.add('radiobutton', undefined, txt.all);
findAllRange.value = true;
var findCstmRange = rangeRadioGrp.add('radiobutton', undefined, txt.range);
var findRangeInp = rangeRadioGrp.add('edittext', undefined, '1-' + data.state.length);
findRangeInp.preferredSize.width = 205;
findRangeInp.helpTip = txt.rangeEg;
findRangeInp.enabled = CFG.isFind;
// CASE CONVERTER
var casePnl = extra.add('panel', undefined, txt.caseTitle);
casePnl.orientation = 'row';
casePnl.alignChildren = ['fill', 'center'];
casePnl.margins = [10, 15, 10, 10];
var caseList = [
'Original', 'lower case', 'UPPER CASE',
'Title Case', 'Sentence case', 'camelCase',
'PascalCase', 'snake_case', 'kebab-case', 'CONSTANT_CASE'];
var caseDdl = casePnl.add('dropdownlist', undefined, caseList);
caseDdl.preferredSize.width = 210;
caseDdl.selection = 0;
casePnl.add('statictext', undefined, txt.range);
var caseRangeInp = casePnl.add('edittext', undefined, '1-' + data.state.length);
caseRangeInp.preferredSize.width = 90;
caseRangeInp.helpTip = txt.rangeEg;
// DEFAULT DATA
data.prefixRange = '1-' + data.state.length;
data.suffixRange = '1-' + data.state.length;
data.caseRange = '1-' + data.state.length;
data.caseStyle = caseList[0];
// TAB EVENTS
isFindRplc.onClick = function () {
changeTabName(tab);
findInp.enabled = replaceInp.enabled = this.value;
data.isFind = this.value;
rangeRadioGrp.enabled = this.value;
data.findRange = '1-' + data.state.length;
}
// Set prefix
prefixInp.onChange = function() {
data.prefix = this.text;
changeTabName(tab);
}
prefixPhDdl.onChange = function () {
this.active = true;
if (this.children.length > 1 && this.selection === null) {
this.selection = 0;
}
if (this.selection.index > 0) {
prefixInp.active = true;
prefixInp.textselection = prefixInp.text + phKeyList[this.selection.index];
this.selection = 0;
prefixInp.active = true;
}
}
prefixRangeInp.onChange = function() {
data.prefixRange = this.text;
changeTabName(tab);
}
// Set suffix
suffixInp.onChange = function() {
data.suffix = suffixInp.text;
changeTabName(tab);
}
suffixPhDdl.onChange = function () {
this.active = true;
if (this.children.length > 1 && this.selection === null) {
this.selection = 0;
}
if (this.selection.index > 0) {
suffixInp.active = true;
suffixInp.textselection = suffixInp.text + phKeyList[this.selection.index];
this.selection = 0;
suffixInp.active = true;
}
}
suffixRangeInp.onChange = function() {
data.suffixRange = this.text;
changeTabName(tab);
}
// Find and replace
findInp.onChange = function() {
data.find = this.text;
changeTabName(tab);
}
replaceInp.onChange = function() {
data.replace = this.text;
changeTabName(tab);
}
findAllRange.onClick = function () {
findRangeInp.enabled = false;
data.findRange = '1-' + data.state.length;
}
findCstmRange.onClick = function () {
findRangeInp.enabled = true;
data.findRange = findRangeInp.text;
}
findRangeInp.onChange = function() {
this.text = this.text.replace(/;/g, ',')
data.findRange = this.text;
changeTabName(tab);
}
// Change Case
caseDdl.onChange = function () {
this.active = true;
if (this.children.length > 1 && this.selection === null) {
this.selection = 0;
}
data.caseStyle = this.selection.text;
changeTabName(tab);
}
caseRangeInp.onChange = function() {
this.text = this.text.replace(/;/g, ',')
data.caseRange = this.text;
changeTabName(tab);
}
// Name inputs handler
var parent = (data.state.length <= CFG.rows) ? pageListPanel : smallList;
for (var i = 0, pcLen = parent.children.length; i < pcLen; i++) {
// Use the keyboard to navigate between fields
goToNextPrevName(data, i, prefixInp, scroll, parent);
// Reset preview when activating name field [2]
parent.children[i].children[1].onActivate = function() {
if (!isEmpty(prvwTitle.text)) {
for (var j = 0, nLen = data.names.length; j < nLen; j++) {
data.names[j].text = data.state[j].customName; // Restore original name
}
}
prvwTitle.text = '';
// Restore original names in document
if (CFG.isUndo) {
app.undo();
var tempPath = doc.layers[0].pathItems.rectangle(0, 0, 1, 1);
tempPath.stroked = false;
tempPath.filled = false;
tempPath.hidden = true;
tempPath.hidden = false;
tempPath.remove();
app.redraw();
CFG.isUndo = false;
}
}
}
var obj = {
prefix: extra ? prefixInp : undefined,
prefixRange: extra ? prefixRangeInp : undefined,
suffix: extra ? suffixInp : undefined,
suffixRange: extra ? suffixRangeInp : undefined,
find: extra ? findInp : undefined,
replace: extra ? replaceInp : undefined,
findRange: extra ? findRangeInp : undefined,
caseRange: extra ? caseRangeInp : undefined,
prvwTitle: prvwTitle ? prvwTitle : undefined,
scroll: scroll ? scroll : undefined,
smallList: scroll ? smallList : undefined,
pageListPanel: scroll ? pageListPanel : undefined,
}
return obj;
}
/**
* Add a new row to the specified tab with object name
* @param {Object} tab - The tab object to which the row will be added
* @param {number} idx - The index of the row
* @param {Object} row - The row object to be added
* @param {Object} obj - The object containing state information
*/
function addNewRow(tab, idx, row, obj) {
var isMac = /mac/i.test($.os);
// Add order number
var order = row.add('statictext');
order.text = padZero(idx + 1, Math.max(3, obj.state.length.toString().length));
obj.names[idx] = row.add('edittext', [0, 0, isMac ? 310 : 320, 20]);
obj.names[idx].text = obj.state[idx].origName;
obj.names[idx].onChange = function () {
if (isEmpty(this.text)) {
this.text = obj.state[idx].origName;
} else {
obj.state[idx].customName = this.text;
}
changeTabName(tab);
}
}
/**
* Change the tab name to indicate changes
* @param {Object} tab - The tab object whose name will be changed
*/
function changeTabName(tab) {
if (!/\*/g.test(tab.text)) tab.text += ' *';
}
/**
* Set up event listeners for navigating through names using Up and Down arrow keys
* @param {Object} obj - The object containing names and other related properties
* @param {number} idx - The current index in the names array
* @param {Object} prefix - The prefix object to focus on when navigating past the last name
* @param {Object} scroll - The scrollbar object associated with the list
* @param {Object} scrollList - The list object that is being scrolled
*/
function goToNextPrevName(obj, idx, prefix, scroll, scrollList) {
var length = obj.names.length;
obj.names[idx].addEventListener('keydown', function (kd) {
// Go to next name
if (kd.keyName == 'Down' && (idx + 1) < length) {
// Update the scrollbar position when the Down key is pressed
if (idx !== 0 && scroll) {
scroll.value = (idx + 1) * (scroll.maxvalue / length);
scrollList.location.y += -1 * scroll.stepdelta;
}
obj.names[idx + 1].active = true;
win.update();
kd.preventDefault();
}
// Go to previous name
if (kd.keyName == 'Up' && (idx - 1 >= 0)) {
// Update the scrollbar position when the Up key is pressed
if ((idx + 1 < length) && scroll && scrollList.location.y < 0) {
scroll.value = (idx - 1) * (scroll.maxvalue / length);
scrollList.location.y += 1 * scroll.stepdelta;
}
obj.names[idx - 1].active = true;
win.update();
kd.preventDefault();
}
// Go to prefix after last name
if (kd.keyName == 'Down' && (idx + 1) == length) {
prefix.active = true;
win.update();
kd.preventDefault();
}
});
prefix.addEventListener('keydown', function (kd) {
// Go to last name from prefix
if (kd.keyName == 'Up') {
obj.names[obj.names.length - 1].active = true;
win.update();
kd.preventDefault();
}
});
}
/**
* Adjust the maximum scroll value for a given object's scrollbar
* This function is used to fix the scrollbar size
* @param {Object} obj - The object containing the scrollbar properties
* @param {number} delta - The additional offset to adjust the scrollbar size
*/
function adjustScrollMax(obj, delta) {
if (obj.scroll !== undefined && obj.scroll.hasOwnProperty('maxvalue')) {
obj.scroll.maxvalue = obj.smallList.size.height - obj.pageListPanel.size.height + delta;
}
}
/**
* Event listener for the copyright link click
* Opens the GitHub URL when the copyright link is clicked
*/
copyright.addEventListener('mousedown', function () {
openURL('https://github.com/creold/');
});
/**
* Save UI options to a file
* @param {object} prefs - Object containing preferences
*/
function saveSettings(prefs) {
if (!Folder(prefs.folder).exists) {
Folder(prefs.folder).create();
}
var f = new File(SETTINGS.folder + SETTINGS.name);
f.encoding = 'UTF-8';
f.open('w');
var absPrefs = setSettingsString(abs);
var lyrsPrefs = setSettingsString(lyrs);
var pathsPrefs = setSettingsString(paths);
var activeTab = 0;
if (tabPnl.selection.text.match(MSG.tabLyr)) activeTab = 1;
if (tabPnl.selection.text.match(MSG.tabPath)) activeTab = 2;
var data = {};
data.win_x = win.location.x;
data.win_y = win.location.y;
data.abs = absPrefs;
data.layers = lyrsPrefs;
data.paths = pathsPrefs;
data.tab = activeTab;
f.write( stringify(data) );
f.close();
}
/**
* Convert an object's properties to a string
* @param {Object} obj - The object containing settings
* @returns {string} A string representation of the object's properties
*/
function setSettingsString(obj) {
return [
obj.prefix,
obj.prefixRange,
obj.suffix,
obj.suffixRange,
obj.find,
obj.replace,
obj.findRange,
obj.caseRange
].join(';');
}
/**
* Load options from a file
* @param {object} prefs - Object containing preferences
*/
function loadSettings(prefs) {
var f = File(prefs.folder + prefs.name);
if (!f.exists) return;
try {
f.encoding = 'UTF-8';
f.open('r');
var json = f.readln();
try { var data = new Function('return (' + json + ')')(); }
catch (err) { return; }
f.close();
if (typeof data != 'undefined') {
win.location = [
data.win_x && !isNaN(parseInt(data.win_x)) ? parseInt(data.win_x) : 300,
data.win_y && !isNaN(parseInt(data.win_y)) ? parseInt(data.win_y) : 300
];
loadSettingsString(abs, absTabData, data.abs.split(';'));
loadSettingsString(lyrs, lyrsTabData, data.layers.split(';'));
loadSettingsString(paths, pathsTabData, data.paths.split(';'));
tabPnl.selection = isNaN(data.tab) ? 0 : data.tab * 1;
}
} catch (err) {
return;
}
}
/**
* Load settings from a string into an object and updates the UI
* @param {Object} obj - The object to load settings into
* @param {Object} tabData - The UI data object
* @param {Array} arr - The array of settings to load
*/
function loadSettingsString(obj, tabData, arr) {
if (arr.length < 7) return; // Stop load for old script
if (tabData.hasOwnProperty('prefix')) {
if (arr[0]) obj.prefix = tabData.prefix.text = arr[0];
if (arr[1]) obj.prefixRange = tabData.prefixRange.text = arr[1];
if (arr[2]) obj.suffix = tabData.suffix.text = arr[2];
if (arr[3]) obj.suffixRange = tabData.suffixRange.text = arr[3];
if (arr[4]) obj.find = tabData.find.text = arr[4];
if (arr[5]) obj.replace = tabData.replace.text = arr[5];
if (arr[6]) obj.findRange = tabData.findRange.text = arr[6];
if (arr[7]) obj.caseRange = tabData.caseRange.text = arr[7];
}
}
/**
* Handle the OK button click event
* Rename objects based on current settings and save them
*/
function okClick() {
if (CFG.isUndo) {
app.undo();
CFG.isUndo = false;
}
renameObjects(doc.artboards, CFG, PH, abs, absPH);
renameObjects(doc.layers, CFG, PH, lyrs, lyrsPH);
renameObjects(app.selection, CFG, PH, paths, pathsPH);
saveSettings(SETTINGS);
win.close();
}
win.show();
}
// GLOBAL FUNCTIONS
/**
* Initialize an object to store data
* @param {boolean} isFind - A flag indicating is enabled Find and Replace
* @param {string} type - Adobe Illustrator document collection type
* @returns {Object} An object containing properties for renaming
*/
function initObject(isFind, type) {
return {
isFind: isFind,
find: '',
replace: '',
findRange: '',
prefix: '',
prefixRange: '',
suffix: '',
suffixRange: '',
caseStyle: '',
caseRange: '',
names: [],
state: [],
type: type
};
}
/**
* Initialize placeholders for a specific type of element
* @param {string} type - The type of element
* @param {Object} ph - The placeholder object containing element properties
* @returns {Object} An object containing the initialized placeholders
*/
function initPlaceholders(type, ph) {
var obj = {
numDown: ph.numDown,
numUp: ph.numUp,
color: ph.color,
dateDMY: ph.dateDMY,
dateMDY: ph.dateMDY,
dateYMD: ph.dateYMD,
time: ph.time,
file: ph.file,
};
if (type === 'artboards' || type === 'paths') {
obj.height = ph.height;
obj.width = ph.width;
obj.units = ph.units;
}
return obj;
}
/**
* Initialize data by collecting prefix, object name, suffix, and index
* @param {Array} coll - The collection of objects to process
* @returns {Array} resultData - An array of arrays, each containing object name and index
*/
function initData(coll) {
var resultData = [];
for (var i = 0, len = coll.length; i < len; i++) {
var name = getName(coll[i]);
resultData.push({ origName: name, customName: name, index: i});
}
return resultData;
}
/**
* Get the name of an item, considering its type
* @param {Object} item - The item for which to get the name
* @returns {string} str - The name of the item
*/
function getName(item) {
if (!item || !item.typename) return item.name || '';
// If part of a compound path, set item
var compound = getCompound(item);
if (compound) item = compound;
// If item has a direct name, return it