forked from newsdev/ai2html
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ai2html.js
4648 lines (4179 loc) · 157 KB
/
ai2html.js
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
// ai2html is a script for Adobe Illustrator that converts your Illustrator document into html and css.
// Copyright (c) 2011-2018 The New York Times Company
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this library except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =====================================
// How to install ai2html
// =====================================
// - Move the ai2html.js file into the Illustrator folder where scripts are located.
// - For example, on Mac OS X running Adobe Illustrator CC 2014, the path would be: // Adobe Illustrator CC 2014/Presets/en_US/Scripts/ai2html.jsx
// =====================================
// How to use ai2html
// =====================================
// - Create your Illustrator artwork.
// - Size the artboard to the dimensions that you want the div to appear on the web page.
// - Make sure your Document Color Mode is set to RGB.
// - Use Arial or Georgia unless you have added your own fonts to the fonts array in the script.
// - Run the script by choosing: File > Scripts > ai2html
// - Go to the folder containing your Illustrator file. Inside will be a folder called ai2html-output.
// - Open the html files in your browser to preview your output.
function main() {
// Enclosing scripts in a named function (and not an anonymous, self-executing
// function) has been recommended as a way to minimise intermittent "MRAP" errors.
// (This advice may be superstitious, need more evidence to decide.)
// See (for example) https://forums.adobe.com/thread/1810764 and
// http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/pdf/illustrator/scripting/Readme.txt
// How to update the version number:
// - Increment middle digit for new functionality or breaking changes
// or increment final digit for simple bug fixes or other minor changes.
// - Update the version number in package.json
// - Add an entry to CHANGELOG.md
// - Run 'npm publish' to create a new GitHub release
var scriptVersion = '0.120.0';
// ================================================
// ai2html and config settings
// ================================================
// These are base settings that are overridden by text block settings in
// the .ai document and settings contained in ai2html-config.json files
var defaultSettings = {
"namespace": "g-",
"settings_version": scriptVersion,
"create_promo_image": false,
"promo_image_width": 1024,
"image_format": ["auto"], // Options: auto, png, png24, jpg, svg
"write_image_files": true,
"responsiveness": "fixed", // Options: fixed, dynamic
"max_width": "",
"output": "one-file", // Options: one-file, multiple-files
"project_name": "", // Defaults to the name of the AI file
"html_output_path": "ai2html-output/",
"html_output_extension": ".html",
"image_output_path": "ai2html-output/",
"image_source_path": "",
"image_alt_text": "", // Generally, use alt_text instead
"cache_bust_token": null, // Append a token to the url of image urls: ?v=<cache_bust_token>
"create_config_file": false,
"create_settings_block": true, // Create a text block in the AI doc with common settings
"config_file_path": "",
"local_preview_template": "",
"png_transparent": false,
"png_number_of_colors": 128, // Number of colors in 8-bit PNG image (1-256)
"jpg_quality": 60,
"center_html_output": true,
"use_2x_images_if_possible": true,
"use_lazy_loader": false,
"include_resizer_classes": false, // Triggers an error (feature was removed)
"include_resizer_widths": true,
"include_resizer_script": false,
"inline_svg": false, // Embed background image SVG in HTML instead of loading a file
"svg_id_prefix": "", // Prefix SVG ids with a string to disambiguate from other ids on the page
"svg_embed_images": false,
"render_text_as": "html", // Options: html, image
"render_rotated_skewed_text_as": "html", // Options: html, image
"testing_mode": false, // Render text in both bg image and HTML to test HTML text placement
"show_completion_dialog_box": true,
"clickable_link": "", // Add a URL to make the entire graphic a clickable link
"last_updated_text": "",
"headline": "",
"leadin": "",
"summary": "",
"notes": "",
"sources": "",
"credit": "",
// List of settings to include in the "ai2html-settings" text block
"settings_block": [
"settings_version",
"image_format",
"responsiveness",
"include_resizer_script",
"use_lazy_loader",
"output",
"html_output_path",
// "html_output_extension", // removed from settings block in v0.115.6
"image_output_path",
"image_source_path",
"local_preview_template",
"png_number_of_colors",
"jpg_quality",
"headline",
"leadin",
"notes",
"sources",
"credit"
],
// list of settings to include in the config.yml file
"config_file": [
"headline",
"leadin",
"summary",
"notes",
"sources",
"credit"
]
};
// These settings override the default settings in NYT preview/birdkit projects
var nytOverrideSettings = {
"image_source_path": "_assets/", // path for <img src="">
"use_lazy_loader": true,
"include_resizer_script": true,
"min_width": 280, // added as workaround for a scoop bug affecting ai2html-type graphics
"accessibility": true,
"settings_block": [
"settings_version",
"responsiveness",
"image_format",
// "write_image_files",
// "max_width",
"png_transparent",
"png_number_of_colors",
"jpg_quality",
"inline_svg",
"output"
// "clickable_link"
// "use_lazy_loader"
],
"config_file": []
};
var nytPreviewSettings = {
"project_type": "nyt-preview",
"html_output_path": "../src/",
"image_output_path": "../public/_assets/"
};
var nytBirdkitSettings = {
"project_type": "freebird",
"html_output_path": "../src/lib/graphics/",
"image_output_path": "../public/_assets/"
};
var nytBirdkitEmbedSettings = {
"project_type": "ai2html",
"html_output_path": "../public/",
"image_output_path": "../public/_assets/",
"dark_mode_compatible": false,
"create_json_config_files": true,
"create_promo_image": false,
"credit": "By The New York Times",
"aria_role": "figure",
"alt_text": "",
"page_template": "vi-article-embed",
"display_for_promotion_only": false,
"section": "",
"size": "full", // changed from "medium" to "full"
"settings_block": [
"settings_version",
"responsiveness",
"alt_text",
"max_width",
"image_format",
"png_number_of_colors",
"jpg_quality",
"last_updated_text",
"section",
"headline",
"leadin",
"summary",
"notes",
"sources",
"credit",
"display_for_promotion_only",
"dark_mode_compatible",
"size"
],
"config_file": [
"last_updated_text",
"alt_text",
"section",
"headline",
"leadin",
"summary",
"notes",
"sources",
"credit",
"page_template",
"display_for_promotion_only",
"size"
]
};
// Override settings for simple NYT Preview ai2html embed graphics
var nytPreviewEmbedSettings = {
"project_type": "ai2html",
"html_output_path": "../public/",
"image_output_path": "../public/_assets/",
"dark_mode_compatible": false,
"create_config_file": true,
"config_file_path": "../config.yml",
"create_promo_image": true,
"credit": "By The New York Times",
"aria_role": "figure",
"alt_text": "",
"publish_system": "scoop",
"page_template": "vi-article-embed",
"environment": "production",
"show_in_compatible_apps": true,
"display_for_promotion_only": false,
"constrain_width_to_text_column": false,
"compatibility": "inline",
"size": "full", // changed from "medium" to "full"
"scoop_publish_fields": true,
"scoop_asset_id": "",
"scoop_username": "",
"scoop_slug": "",
"scoop_external_edit_key": "",
"settings_block": [
"settings_version",
"responsiveness",
"alt_text",
"max_width",
"image_format",
// "write_image_files",
// "output",
"png_number_of_colors",
"jpg_quality",
// "use_lazy_loader",
// "show_completion_dialog_box",
"last_updated_text",
"headline",
"leadin",
"summary",
"notes",
"sources",
"credit",
"show_in_compatible_apps",
"display_for_promotion_only",
"constrain_width_to_text_column",
"dark_mode_compatible",
"size",
"scoop_asset_id",
"scoop_username",
"scoop_slug",
"scoop_external_edit_key"
],
"config_file": [
"last_updated_text",
"headline",
"leadin",
"summary",
"notes",
"sources",
"credit",
"page_template",
"publish_system",
"environment",
"show_in_compatible_apps",
"display_for_promotion_only",
"constrain_width_to_text_column",
"compatibility",
"size",
"scoop_publish_fields",
"scoop_asset_id",
"scoop_username",
"scoop_slug",
"scoop_external_edit_key"
]
};
// Rules for converting AI fonts to CSS
// vshift shifts text vertically, to compensate for vertical misalignment caused
// by a difference between vertical placement in Illustrator (of a system font) and
// browsers (of the web font equivalent). vshift values are percentage of font size. Positive
// values correspond to a downward shift.
var fonts = [
{"aifont":"ArialMT","family":"arial,helvetica,sans-serif","weight":"","style":""},
{"aifont":"Arial-BoldMT","family":"arial,helvetica,sans-serif","weight":"bold","style":""},
{"aifont":"Arial-ItalicMT","family":"arial,helvetica,sans-serif","weight":"","style":"italic"},
{"aifont":"Arial-BoldItalicMT","family":"arial,helvetica,sans-serif","weight":"bold","style":"italic"},
{"aifont":"Georgia","family":"georgia,'times new roman',times,serif","weight":"","style":""},
{"aifont":"Georgia-Bold","family":"georgia,'times new roman',times,serif","weight":"bold","style":""},
{"aifont":"Georgia-Italic","family":"georgia,'times new roman',times,serif","weight":"","style":"italic"},
{"aifont":"Georgia-BoldItalic","family":"georgia,'times new roman',times,serif","weight":"bold","style":"italic"},
// NYT fonts
{"aifont":"NYTFranklin-Light","family":"nyt-franklin,arial,helvetica,sans-serif","weight":"300","style":"", "vshift": "8%"},
{"aifont":"NYTFranklin-Medium","family":"nyt-franklin,arial,helvetica,sans-serif","weight":"500","style":"", "vshift": "8%"},
{"aifont":"NYTFranklin-SemiBold","family":"nyt-franklin,arial,helvetica,sans-serif","weight":"600","style":"", "vshift": "8%"},
{"aifont":"NYTFranklin-Semibold","family":"nyt-franklin,arial,helvetica,sans-serif","weight":"600","style":"", "vshift": "8%"},
{"aifont":"NYTFranklinSemiBold-Regular","family":"nyt-franklin,arial,helvetica,sans-serif","weight":"600","style":"", "vshift": "8%"},
{"aifont":"NYTFranklin-SemiboldItalic","family":"nyt-franklin,arial,helvetica,sans-serif","weight":"600","style":"italic", "vshift": "8%"},
{"aifont":"NYTFranklin-Bold","family":"nyt-franklin,arial,helvetica,sans-serif","weight":"700","style":"", "vshift": "8%"},
{"aifont":"NYTFranklin-LightItalic","family":"nyt-franklin,arial,helvetica,sans-serif","weight":"300","style":"italic", "vshift": "8%"},
{"aifont":"NYTFranklin-MediumItalic","family":"nyt-franklin,arial,helvetica,sans-serif","weight":"500","style":"italic", "vshift": "8%"},
{"aifont":"NYTFranklin-BoldItalic","family":"nyt-franklin,arial,helvetica,sans-serif","weight":"700","style":"italic", "vshift": "8%"},
{"aifont":"NYTFranklin-ExtraBold","family":"nyt-franklin,arial,helvetica,sans-serif","weight":"800","style":"", "vshift": "8%"},
{"aifont":"NYTFranklin-ExtraBoldItalic","family":"nyt-franklin,arial,helvetica,sans-serif","weight":"800","style":"italic", "vshift": "8%"},
{"aifont":"NYTFranklin-Headline","family":"nyt-franklin,arial,helvetica,sans-serif","weight":"bold","style":"", "vshift": "8%"},
{"aifont":"NYTFranklin-HeadlineItalic","family":"nyt-franklin,arial,helvetica,sans-serif","weight":"bold","style":"italic", "vshift": "8%"},
// Chelt.
{"aifont":"NYTCheltenham-ExtraLight","family":"nyt-cheltenham,georgia,serif","weight":"200","style":""},
{"aifont":"NYTCheltenhamExtLt-Regular","family":"nyt-cheltenham,georgia,serif","weight":"200","style":""},
{"aifont":"NYTCheltenham-Light","family":"nyt-cheltenham,georgia,serif","weight":"300","style":""},
{"aifont":"NYTCheltenhamLt-Regular","family":"nyt-cheltenham,georgia,serif","weight":"300","style":""},
{"aifont":"NYTCheltenham-LightSC","family":"nyt-cheltenham,georgia,serif","weight":"300","style":""},
{"aifont":"NYTCheltenham-Book","family":"nyt-cheltenham,georgia,serif","weight":"400","style":""},
{"aifont":"NYTCheltenhamBook-Regular","family":"nyt-cheltenham,georgia,serif","weight":"400","style":""},
{"aifont":"NYTCheltenham-Wide","family":"nyt-cheltenham,georgia,serif","weight":"","style":""},
{"aifont":"NYTCheltenhamMedium-Regular","family":"nyt-cheltenham,georgia,serif","weight":"500","style":""},
{"aifont":"NYTCheltenham-Medium","family":"nyt-cheltenham,georgia,serif","weight":"500","style":""},
{"aifont":"NYTCheltenham-Bold","family":"nyt-cheltenham,georgia,serif","weight":"700","style":""},
{"aifont":"NYTCheltenham-BoldCond","family":"nyt-cheltenham,georgia,serif","weight":"bold","style":""},
{"aifont":"NYTCheltenhamCond-BoldXC","family":"nyt-cheltenham-extra-cn-bd,georgia,serif","weight":"bold","style":""},
{"aifont":"NYTCheltenham-BoldExtraCond","family":"nyt-cheltenham,georgia,serif","weight":"bold","style":""},
{"aifont":"NYTCheltenham-ExtraBold","family":"nyt-cheltenham,georgia,serif","weight":"bold","style":""},
{"aifont":"NYTCheltenham-ExtraLightIt","family":"nyt-cheltenham,georgia,serif","weight":"","style":"italic"},
{"aifont":"NYTCheltenham-ExtraLightItal","family":"nyt-cheltenham,georgia,serif","weight":"","style":"italic"},
{"aifont":"NYTCheltenham-LightItalic","family":"nyt-cheltenham,georgia,serif","weight":"","style":"italic"},
{"aifont":"NYTCheltenham-BookItalic","family":"nyt-cheltenham,georgia,serif","weight":"","style":"italic"},
{"aifont":"NYTCheltenham-WideItalic","family":"nyt-cheltenham,georgia,serif","weight":"","style":"italic"},
{"aifont":"NYTCheltenham-MediumItalic","family":"nyt-cheltenham,georgia,serif","weight":"","style":"italic"},
{"aifont":"NYTCheltenham-BoldItalic","family":"nyt-cheltenham,georgia,serif","weight":"700","style":"italic"},
{"aifont":"NYTCheltenham-ExtraBoldItal","family":"nyt-cheltenham,georgia,serif","weight":"bold","style":"italic"},
{"aifont":"NYTCheltenham-ExtraBoldItalic","family":"nyt-cheltenham,georgia,serif","weight":"bold","style":"italic"},
{"aifont":"NYTCheltenhamSH-Regular","family":"nyt-cheltenham-sh,nyt-cheltenham,georgia,serif","weight":"400","style":""},
{"aifont":"NYTCheltenhamSH-Italic","family":"nyt-cheltenham-sh,nyt-cheltenham,georgia,serif","weight":"400","style":"italic"},
{"aifont":"NYTCheltenhamSH-Bold","family":"nyt-cheltenham-sh,nyt-cheltenham,georgia,serif","weight":"700","style":""},
{"aifont":"NYTCheltenhamSH-BoldItalic","family":"nyt-cheltenham-sh,nyt-cheltenham,georgia,serif","weight":"700","style":"italic"},
{"aifont":"NYTCheltenhamWide-Regular","family":"nyt-cheltenham,georgia,serif","weight":"500","style":""},
{"aifont":"NYTCheltenhamWide-Italic","family":"nyt-cheltenham,georgia,serif","weight":"500","style":"italic"},
// Imperial
{"aifont":"NYTImperial-Regular","family":"nyt-imperial,georgia,serif","weight":"400","style":""},
{"aifont":"NYTImperial-Italic","family":"nyt-imperial,georgia,serif","weight":"400","style":"italic"},
{"aifont":"NYTImperial-Semibold","family":"nyt-imperial,georgia,serif","weight":"600","style":""},
{"aifont":"NYTImperial-SemiboldItalic","family":"nyt-imperial,georgia,serif","weight":"600","style":"italic"},
{"aifont":"NYTImperial-Bold","family":"nyt-imperial,georgia,serif","weight":"700","style":""},
{"aifont":"NYTImperial-BoldItalic","family":"nyt-imperial,georgia,serif","weight":"700","style":"italic"},
// Others
{"aifont":"NYTKarnakText-Regular","family":"nyt-karnak-display-130124,georgia,serif","weight":"400","style":""},
{"aifont":"NYTKarnakDisplay-Regular","family":"nyt-karnak-display-130124,georgia,serif","weight":"400","style":""},
{"aifont":"NYTStymieLight-Regular","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"300","style":""},
{"aifont":"NYTStymieMedium-Regular","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"500","style":""},
{"aifont":"StymieNYT-Light","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"300","style":""},
{"aifont":"StymieNYT-LightPhoenetic","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"300","style":""},
{"aifont":"StymieNYT-Lightitalic","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"300","style":"italic"},
{"aifont":"StymieNYT-Medium","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"500","style":""},
{"aifont":"StymieNYT-MediumItalic","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"500","style":"italic"},
{"aifont":"StymieNYT-Bold","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"700","style":""},
{"aifont":"StymieNYT-BoldItalic","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"700","style":"italic"},
{"aifont":"StymieNYT-ExtraBold","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"700","style":""},
{"aifont":"StymieNYT-ExtraBoldText","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"700","style":""},
{"aifont":"StymieNYT-ExtraBoldTextItal","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"700","style":"italic"},
{"aifont":"StymieNYTBlack-Regular","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"700","style":""},
{"aifont":"StymieBT-ExtraBold","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"700","style":""},
{"aifont":"Stymie-Thin","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"300","style":""},
{"aifont":"Stymie-UltraLight","family":"nyt-stymie,arial,helvetica,sans-serif","weight":"300","style":""},
{"aifont":"NYTMagSans-Regular","family":"'nyt-magsans',arial,helvetica,sans-serif","weight":"500","style":""},
{"aifont":"NYTMagSans-Bold","family":"'nyt-magsans',arial,helvetica,sans-serif","weight":"700","style":""}
];
// ================================================
// Constant data
// ================================================
// html entity substitution
var basicCharacterReplacements = [["\x26","&"], ["\x22","""], ["\x3C","<"], ["\x3E",">"]];
var extraCharacterReplacements = [["\xA0"," "], ["\xA1","¡"], ["\xA2","¢"], ["\xA3","£"], ["\xA4","¤"], ["\xA5","¥"], ["\xA6","¦"], ["\xA7","§"], ["\xA8","¨"], ["\xA9","©"], ["\xAA","ª"], ["\xAB","«"], ["\xAC","¬"], ["\xAD","­"], ["\xAE","®"], ["\xAF","¯"], ["\xB0","°"], ["\xB1","±"], ["\xB2","²"], ["\xB3","³"], ["\xB4","´"], ["\xB5","µ"], ["\xB6","¶"], ["\xB7","·"], ["\xB8","¸"], ["\xB9","¹"], ["\xBA","º"], ["\xBB","»"], ["\xBC","¼"], ["\xBD","½"], ["\xBE","¾"], ["\xBF","¿"], ["\xD7","×"], ["\xF7","÷"], ["\u0192","ƒ"], ["\u02C6","ˆ"], ["\u02DC","˜"], ["\u2002"," "], ["\u2003"," "], ["\u2009"," "], ["\u200C","‌"], ["\u200D","‍"], ["\u200E","‎"], ["\u200F","‏"], ["\u2013","–"], ["\u2014","—"], ["\u2018","‘"], ["\u2019","’"], ["\u201A","‚"], ["\u201C","“"], ["\u201D","”"], ["\u201E","„"], ["\u2020","†"], ["\u2021","‡"], ["\u2022","•"], ["\u2026","…"], ["\u2030","‰"], ["\u2032","′"], ["\u2033","″"], ["\u2039","‹"], ["\u203A","›"], ["\u203E","‾"], ["\u2044","⁄"], ["\u20AC","€"], ["\u2111","ℑ"], ["\u2113",""], ["\u2116",""], ["\u2118","℘"], ["\u211C","ℜ"], ["\u2122","™"], ["\u2135","ℵ"], ["\u2190","←"], ["\u2191","↑"], ["\u2192","→"], ["\u2193","↓"], ["\u2194","↔"], ["\u21B5","↵"], ["\u21D0","⇐"], ["\u21D1","⇑"], ["\u21D2","⇒"], ["\u21D3","⇓"], ["\u21D4","⇔"], ["\u2200","∀"], ["\u2202","∂"], ["\u2203","∃"], ["\u2205","∅"], ["\u2207","∇"], ["\u2208","∈"], ["\u2209","∉"], ["\u220B","∋"], ["\u220F","∏"], ["\u2211","∑"], ["\u2212","−"], ["\u2217","∗"], ["\u221A","√"], ["\u221D","∝"], ["\u221E","∞"], ["\u2220","∠"], ["\u2227","∧"], ["\u2228","∨"], ["\u2229","∩"], ["\u222A","∪"], ["\u222B","∫"], ["\u2234","∴"], ["\u223C","∼"], ["\u2245","≅"], ["\u2248","≈"], ["\u2260","≠"], ["\u2261","≡"], ["\u2264","≤"], ["\u2265","≥"], ["\u2282","⊂"], ["\u2283","⊃"], ["\u2284","⊄"], ["\u2286","⊆"], ["\u2287","⊇"], ["\u2295","⊕"], ["\u2297","⊗"], ["\u22A5","⊥"], ["\u22C5","⋅"], ["\u2308","⌈"], ["\u2309","⌉"], ["\u230A","⌊"], ["\u230B","⌋"], ["\u2329","⟨"], ["\u232A","⟩"], ["\u25CA","◊"], ["\u2660","♠"], ["\u2663","♣"], ["\u2665","♥"], ["\u2666","♦"]];
// CSS text-transform equivalents
var caps = [
{"ai":"FontCapsOption.NORMALCAPS","html":"none"},
{"ai":"FontCapsOption.ALLCAPS","html":"uppercase"},
{"ai":"FontCapsOption.SMALLCAPS","html":"uppercase"}
];
// CSS text-align equivalents
var align = [
{"ai":"Justification.LEFT","html":"left"},
{"ai":"Justification.RIGHT","html":"right"},
{"ai":"Justification.CENTER","html":"center"},
{"ai":"Justification.FULLJUSTIFY","html":"justify"},
{"ai":"Justification.FULLJUSTIFYLASTLINELEFT","html":"justify"},
{"ai":"Justification.FULLJUSTIFYLASTLINECENTER","html":"justify"},
{"ai":"Justification.FULLJUSTIFYLASTLINERIGHT","html":"justify"}
];
var blendModes = [
{ai: "BlendModes.MULTIPLY", html: "multiply"}
];
// list of CSS properties used for translating AI text styles
// (used for creating a unique identifier for each style)
var cssTextStyleProperties = [
//'top' // used with vshift; not independent of other properties
'position',
'font-family',
'font-size',
'font-weight',
'font-style',
'color',
'line-height',
'height', // used for point-type paragraph styles
'letter-spacing',
'opacity',
'padding-top',
'padding-bottom',
'text-align',
'text-transform',
'mix-blend-mode',
'vertical-align' // for superscript
];
var cssPrecision = 4;
// ================================
// Global variable declarations
// ================================
// This can be overridden by settings
var nameSpace = 'g-';
// vars to hold warnings and informational messages at the end
var feedback = [];
var warnings = [];
var errors = [];
var oneTimeWarnings = [];
var startTime = +new Date();
var textFramesToUnhide = [];
var objectsToRelock = [];
var docSettings;
var textBlockData;
var doc, docPath, docSlug, docIsSaved;
var progressBar;
var JSON;
initJSON();
// Simple interface to help find performance bottlenecks. Usage:
// T.start('<label>');
// ...
// T.stop('<label>'); // prints a message in the final popup window
//
var T = {
times: {},
start: function(key) {
if (key in T.times) return;
T.times[key] = +new Date();
},
stop: function(key) {
var startTime = T.times[key];
var elapsed = roundTo((+new Date() - startTime) / 1000, 1);
delete T.times[key];
message(key + ' - ' + elapsed + 's');
}
};
// If running in Node.js, export functions for testing and exit
if (runningInNode()) {
exportFunctionsForTesting();
return;
}
try {
if (!isTestedIllustratorVersion(app.version)) {
warn('Ai2html has not been tested on this version of Illustrator.');
}
if (!app.documents.length) {
error('No documents are open');
}
if (!String(app.activeDocument.fullName)) {
error('Ai2html is unable to run because Illustrator is confused by this document\'s file path.' +
' Does the path contain any forward slashes or other unusual characters?');
}
if (!String(app.activeDocument.path)) {
error('You need to save your Illustrator file before running this script');
}
if (app.activeDocument.documentColorSpace != DocumentColorSpace.RGB) {
error('You should change the document color mode to "RGB" before running ai2html (File>Document Color Mode>RGB Color).');
}
if (app.activeDocument.activeLayer.name == 'Isolation Mode') {
error('Ai2html is unable to run because the document is in Isolation Mode.');
}
if (app.activeDocument.activeLayer.name == '<Opacity Mask>' && app.activeDocument.layers.length == 1) {
// TODO: find a better way to detect this condition (mask can be renamed)
error('Ai2html is unable to run because you are editing an Opacity Mask.');
}
// initialize script settings
doc = app.activeDocument;
docPath = doc.path + '/';
docIsSaved = doc.saved;
textBlockData = initSpecialTextBlocks();
docSettings = initDocumentSettings(textBlockData.settings);
docSlug = docSettings.project_name || makeDocumentSlug(getRawDocumentName());
nameSpace = docSettings.namespace || nameSpace;
extendFontList(fonts, docSettings.fonts || []);
if (!textBlockData.settings && isTrue(docSettings.create_settings_block)) {
createSettingsBlock(docSettings);
}
// render the document
render(docSettings, textBlockData.code);
} catch(e) {
errors.push(formatError(e));
}
restoreDocumentState();
if (progressBar) progressBar.close();
// ==========================================
// Save the AI document (if needed)
// ==========================================
if (docIsSaved) {
// If document was originally in a saved state, reset the document's
// saved flag (the document goes to unsaved state during the script,
// because of unlocking / relocking of objects
doc.saved = true;
} else if (errors.length === 0) {
var saveOptions = new IllustratorSaveOptions();
saveOptions.pdfCompatible = false;
doc.saveAs(new File(docPath + doc.name), saveOptions);
// doc.save(); // why not do this? (why set pdfCompatible = false?)
message('Your Illustrator file was saved.');
}
// =========================================================
// Show alert box, optionally prompt to generate promo image
// =========================================================
if (errors.length > 0) {
showCompletionAlert();
} else if (isTrue(docSettings.show_completion_dialog_box )) {
message('Script ran in', ((+new Date() - startTime) / 1000).toFixed(1), 'seconds');
var promptForPromo = isTrue(docSettings.write_image_files) && isTrue(docSettings.create_promo_image);
var showPromo = showCompletionAlert(promptForPromo);
if (showPromo) createPromoImage(docSettings);
}
// =================================
// ai2html render function
// =================================
function render(settings, customBlocks) {
// warn about duplicate artboard names
validateArtboardNames(docSettings);
// Fix for issue #50
// If a text range is selected when the script runs, it interferes
// with script-driven selection. The fix is to clear this kind of selection.
if (doc.selection && doc.selection.typename) {
clearSelection();
}
// ================================================
// Generate HTML, CSS and images for each artboard
// ================================================
progressBar = new ProgressBar({name: 'Ai2html progress', steps: calcProgressBarSteps()});
unlockObjects(); // Unlock containers and clipping masks
var masks = findMasks(); // identify all clipping masks and their contents
var fileContentArr = [];
forEachUsableArtboard(function(activeArtboard, abIndex) {
var abSettings = getArtboardSettings(activeArtboard);
var docArtboardName = getDocumentArtboardName(activeArtboard);
var textFrames, textData, imageData, specialData;
var artboardContent = {html: '', css: '', js: ''};
doc.artboards.setActiveArtboardIndex(abIndex);
// detect videos and other special layers
specialData = convertSpecialLayers(activeArtboard, settings);
if (specialData) {
forEach(specialData.layers, function(lyr) {
lyr.visible = false;
});
}
// ========================
// Convert text objects
// ========================
if (abSettings.image_only || settings.render_text_as == 'image') {
// don't convert text objects to HTML
textFrames = [];
textData = {html: '', styles: []};
} else {
progressBar.setTitle(docArtboardName + ': Generating text...');
textFrames = getTextFramesByArtboard(activeArtboard, masks, settings);
textData = convertTextFrames(textFrames, activeArtboard, settings);
}
progressBar.step();
// ==========================
// Generate artboard image(s)
// ==========================
if (isTrue(settings.write_image_files)) {
progressBar.setTitle(docArtboardName + ': Capturing image...');
imageData = convertArtItems(activeArtboard, textFrames, masks, settings);
} else {
imageData = {html: ''};
}
if (specialData) {
imageData.html = specialData.video + specialData.html_before +
imageData.html + specialData.html_after;
forEach(specialData.layers, function(lyr) {
lyr.visible = true;
});
if (specialData.video && !isTrue(settings.png_transparent)) {
warn('Background videos may be covered up without png_transparent:true');
}
}
progressBar.step();
//=====================================
// Finish generating artboard HTML and CSS
//=====================================
artboardContent.html += '\r\t<!-- Artboard: ' + getArtboardName(activeArtboard) + ' -->\r' +
generateArtboardDiv(activeArtboard, settings) +
imageData.html +
textData.html +
'\t</div>\r';
var abStyles = textData.styles;
if (specialData && specialData.video) {
// make videos tap/clickable (so they can be played manually if autoplay
// is disabled, e.g. in mobile low-power mode).
abStyles.push('> div { pointer-events: none; }\r');
abStyles.push('> img { pointer-events: none; }\r');
}
artboardContent.css += generateArtboardCss(activeArtboard, abStyles, settings);
var oname = settings.output == 'one-file' ? getRawDocumentName() : docArtboardName;
// kludge to identify legacy embed projects
if (settings.output == 'one-file' &&
settings.project_type == 'ai2html' &&
!isTrue(settings.create_json_config_files)) {
oname = 'index';
}
assignArtboardContentToFile(oname, artboardContent, fileContentArr);
}); // end artboard loop
if (fileContentArr.length === 0) {
error('No usable artboards were found');
}
//=====================================
// Output html file(s)
//=====================================
forEach(fileContentArr, function(fileContent) {
addCustomContent(fileContent, customBlocks);
generateOutputHtml(fileContent, fileContent.name, settings);
});
//=====================================
// Post-output operations
//=====================================
if (isTrue(settings.create_json_config_files)) {
// Create JSON config files, one for each .ai file
var jsonStr = generateJsonSettingsFileContent(settings);
var jsonPath = docPath + getRawDocumentName() + '.json';
saveTextFile(jsonPath, jsonStr);
} else if (isTrue(settings.create_config_file)) {
// Create one top-level config.yml file
// (This is being replaced by multiple JSON config files for NYT projects)
var yamlPath = docPath + (settings.config_file_path || 'config.yml'),
yamlStr = generateYamlFileContent(settings);
checkForOutputFolder(yamlPath.replace(/[^\/]+$/, ''), 'configFileFolder');
saveTextFile(yamlPath, yamlStr);
}
if (settings.cache_bust_token) {
incrementCacheBustToken(settings);
}
} // end render()
// =================================
// JS utility functions
// =================================
function forEach(arr, cb) {
for (var i=0, n=arr.length; i<n; i++) {
cb(arr[i], i);
}
}
function map(arr, cb) {
var arr2 = [];
for (var i=0, n=arr.length; i<n; i++) {
arr2.push(cb(arr[i], i));
}
return arr2;
}
function filter(arr, test) {
var filtered = [];
for (var i=0, n=arr.length; i<n; i++) {
if (test(arr[i], i)) {
filtered.push(arr[i]);
}
}
return filtered;
}
// obj: value or test function
function indexOf(arr, obj) {
var test = typeof obj == 'function' ? obj : null;
for (var i=0, n=arr.length; i<n; i++) {
if (test ? test(arr[i]) : arr[i] === obj) {
return i;
}
}
return -1;
}
function find(arr, obj) {
var i = indexOf(arr, obj);
return i == -1 ? null : arr[i];
}
function contains(arr, obj) {
return indexOf(arr, obj) >= 0;
}
// alias for contains() with function arg
function some(arr, cb) {
return indexOf(arr, cb) >= 0;
}
function extend(o) {
for (var i=1; i<arguments.length; i++) {
forEachProperty(arguments[i], add);
}
function add(v, k) {
o[k] = v;
}
return o;
}
function forEachProperty(o, cb) {
for (var k in o) {
if (o.hasOwnProperty(k)) {
cb(o[k], k);
}
}
}
// Return new object containing properties of a that are missing or different in b
// Return null if output object would be empty
// a, b: JS objects
function objectDiff(a, b) {
var diff = null;
for (var k in a) {
if (a[k] != b[k] && a.hasOwnProperty(k)) {
diff = diff || {};
diff[k] = a[k];
}
}
return diff;
}
// return elements in array "a" but not in array "b"
function arraySubtract(a, b) {
var diff = [],
alen = a.length,
blen = b.length,
i, j;
for (i=0; i<alen; i++) {
diff.push(a[i]);
for (j=0; j<blen; j++) {
if (a[i] === b[j]) {
diff.pop();
break;
}
}
}
return diff;
}
// Copy elements of an array-like object to an array
function toArray(obj) {
var arr = [];
for (var i=0, n=obj.length; i<n; i++) {
arr[i] = obj[i]; // about 2x faster than push() (apparently)
// arr.push(obj[i]);
}
return arr;
}
// multiple key sorting function based on https://github.com/Teun/thenBy.js
// first by length of name, then by population, then by ID
// data.sort(
// firstBy(function (v1, v2) { return v1.name.length - v2.name.length; })
// .thenBy(function (v1, v2) { return v1.population - v2.population; })
// .thenBy(function (v1, v2) { return v1.id - v2.id; });
// );
function firstBy(f1, f2) {
var compare = f2 ? function(a, b) {return f1(a, b) || f2(a, b);} : f1;
compare.thenBy = function(f) {return firstBy(compare, f);};
return compare;
}
// Remove whitespace from beginning and end of a string
function trim(s) {
return s.replace(/^[\s\uFEFF\xA0\x03]+|[\s\uFEFF\xA0\x03]+$/g, '');
}
// splits a string into non-empty lines
function stringToLines(str) {
var empty = /^\s*$/;
return filter(str.split(/[\r\n\x03]+/), function(line) {
return !empty.test(line);
});
}
function zeroPad(val, digits) {
var str = String(val);
while (str.length < digits) str = '0' + str;
return str;
}
function truncateString(str, maxlen, useEllipsis) {
// TODO: add ellipsis, truncate at word boundary
if (str.length > maxlen) {
str = str.substr(0, maxlen);
if (useEllipsis) str += '...';
}
return str;
}
function makeKeyword(text) {
return text.replace( /[^A-Za-z0-9_-]+/g , '_' );
}
// TODO: don't convert ampersand in pre-existing entities (e.g. """ -> "&quot;")
function encodeHtmlEntities(text) {
return replaceChars(text, basicCharacterReplacements.concat(extraCharacterReplacements));
}
function cleanHtmlText(text) {
// Characters "<>& are not replaced
return replaceChars(text, extraCharacterReplacements);
}
function replaceChars(str, replacements) {
var charCode;
for (var i=0, n=replacements.length; i < n; i++) {
charCode = replacements[i];
if (str.indexOf(charCode[0]) > -1) {
str = str.replace(new RegExp(charCode[0],'g'), charCode[1]);
}
}
return str;
}
function straightenCurlyQuotesInsideAngleBrackets(text) {
// This function's purpose is to fix quoted properties in HTML tags that were
// typed into text blocks (Illustrator tends to automatically change single
// and double quotes to curly quotes).
// thanks to jashkenas
// var quoteFinder = /[\u201C‘’\u201D]([^\n]*?)[\u201C‘’\u201D]/g;
var tagFinder = /<[^\n]+?>/g;
return text.replace(tagFinder, function(tag){
return straightenCurlyQuotes(tag);
});
}
function straightenCurlyQuotes(str) {
return str.replace( /[\u201C\u201D]/g , '"' ).replace( /[‘’]/g , "'" );
}
// Not very robust -- good enough for printing a warning
function findHtmlTag(str) {
var match;
if (str.indexOf('<') > -1) { // bypass regex check
match = /<(\w+)[^>]*>/.exec(str);
}
return match ? match[1] : null;
}
function addEnclosingTag(tagName, str) {
var openTag = '<' + tagName;
var closeTag = '</' + tagName + '>';
if ((new RegExp(openTag)).test(str) === false) {
str = openTag + '>\r' + str;
}
if ((new RegExp(closeTag)).test(str) === false) {
str = str + '\r' + closeTag;
}
return str;
}
function stripTag(tagName, str) {
var open = new RegExp('<' + tagName + '[^>]*>', 'g');
var close = new RegExp('</' + tagName + '>', 'g');
return str.replace(open, '').replace(close, '');
}
// precision: number of decimals in rounded number
function roundTo(number, precision) {
var d = Math.pow(10, precision || 0);
return Math.round(number * d) / d;
}
function getDateTimeStamp() {
var d = new Date();
var year = d.getFullYear();
var date = zeroPad(d.getDate(),2);
var month = zeroPad(d.getMonth() + 1,2);
var hour = zeroPad(d.getHours(),2);
var min = zeroPad(d.getMinutes(),2);
return year + '-' + month + '-' + date + ' ' + hour + ':' + min;
}
// obj: JS object containing css properties and values
// indentStr: string to use as block CSS indentation
function formatCss(obj, indentStr) {
var css = '';
var isBlock = !!indentStr;
for (var key in obj) {
if (isBlock) {
css += '\r' + indentStr;
}
css += key + ':' + obj[key]+ ';';
}
if (css && isBlock) {
css += '\r';
}
return css;
}
function getCssColor(r, g, b, opacity) {
var col, o;
if (opacity > 0 && opacity < 100) {
o = roundTo(opacity / 100, 2);
col = 'rgba(' + r + ',' + g + ',' + b + ',' + o + ')';
} else {
col = 'rgb(' + r + ',' + g + ',' + b + ')';
}
return col;
}
// Test if two rectangles are the same, to within a given tolerance
// a, b: two arrays containing AI rectangle coordinates
// maxOffs: maximum pixel deviation on any side
function testSimilarBounds(a, b, maxOffs) {
if (maxOffs >= 0 === false) maxOffs = 1;
for (var i=0; i<4; i++) {
if (Math.abs(a[i] - b[i]) > maxOffs) return false;
}
return true;
}
// Apply very basic string substitution to a template
function applyTemplate(template, replacements) {