-
-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathmain.js
6072 lines (5585 loc) · 181 KB
/
main.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
/**
* 良いCSSとは - Qiita
* https://qiita.com/horikowa/items/7e6eb7c4bbb422241d9d
*
* CSSテストサイト
* https://www.w3schools.com/css/tryit.asp?filename=trycss_sel_attribute_end
* https://codepen.io/pen/
*/
// XD拡張APIのクラスをインポート
const {
Artboard,
Color,
ImageFill,
Rectangle,
GraphicNode,
SceneNode,
ScrollableGroup,
SymbolInstance,
root,
selection,
} = require('scenegraph')
const scenegraph = require('scenegraph')
const application = require('application')
const fs = require('uxp').storage.localFileSystem
const commands = require('commands')
const strings = require('./strings.json')
// 全体にかけるスケール
let globalScale = 1.0
//
/**
* 出力するフォルダ
* @type {Folder|null}
*/
let globalOutputFolder = null
let globalAddtionalCssFolder = null
// エキスポートフラグを見るかどうか
let globalCheckMarkedForExport = false
// 画像を出力するかどうか
let globalFlagImageNoExport = false
// コンテンツの変更のみかどうか
let globalFlagChangeContentOnly = false
// SymbolInstanceをPrefabにするかどうか
let globalFlagSymbolInstanceAsPrefab = false
// 初期状態の可視情報
// globalVisibleInfo[node.guid]
let globalVisibleInfo = null
// コンバートファイル依存関係
let globalOutputFileDependency = {}
/**
* レスポンシブパラメータを保存する
* @type {BoundsToRectTransform[]}
*/
let globalResponsiveBounds = null
/**
* @type {{selector:CssSelector, declarations:CssDeclarations, at_rule:string }[]}
*/
let globalCssRules = null
let globalCssVars = {}
let globalErrorLog = []
let cacheParseNodeName = {}
let cacheNodeNameAndStyle = {}
/**
* グローバル変数をリセットする 再コンバートに必要なものだけのリセット
* Rootをコンバートする前にリセットする
*/
function resetGlobalVariables() {
globalVisibleInfo = {}
globalResponsiveBounds = {}
globalCssRules = null
globalCssVars = {}
cacheParseNodeName = {}
cacheNodeNameAndStyle = {}
// こちらの値はRootをまたいで必要になる情報のためリセットしない
// globalSymbolIdToPrefabGuid = {}
// globalErrorLog = []
// globalExternalCssFolder = null
}
const STR_CONTENT = 'content'
const STR_VERTICAL = 'vertical'
const STR_HORIZONTAL = 'horizontal'
const STR_PREFERRED = 'preferred'
const STR_GRID = 'grid'
// オプション文字列 全て小文字 数字を含まない
// OPTION名に H V X Yといった、高さ方向をしめすものはできるだけ出さないようにする
const STYLE_ALIGN = 'align' // テキストの縦横のアライメントの設定が可能 XDの設定に上書き
const STYLE_BLANK = 'blank'
const STYLE_BUTTON = 'button'
const STYLE_BUTTON_TRANSITION = 'button-transition'
const STYLE_BUTTON_TRANSITION_TARGET_GRAPHIC =
'button-transition-target-graphic'
const STYLE_BUTTON_TRANSITION_HIGHLIGHTED_SPRITE =
'button-transition-highlighted-sprite'
const STYLE_BUTTON_TRANSITION_PRESSED_SPRITE =
'button-transition-pressed-sprite'
const STYLE_BUTTON_TRANSITION_SELECTED_SPRITE =
'button-transition-selected-sprite'
const STYLE_BUTTON_TRANSITION_DISABLED_SPRITE =
'button-transition-disabled-sprite'
const STYLE_CANVAS_GROUP = 'canvas-group' // 削除予定
const STYLE_COMMENT_OUT = 'comment-out'
const STYLE_COMPONENT = 'component'
const STYLE_CONTENT_SIZE_FITTER = 'content-size-fitter' //自身のSizeFitterオプション
const STYLE_CONTENT_SIZE_FITTER_HORIZONTAL_FIT =
'content-size-fitter-horizontal-fit'
const STYLE_CONTENT_SIZE_FITTER_VERTICAL_FIT =
'content-size-fitter-vertical-fit'
const STYLE_FIX = 'fix'
const STYLE_IMAGE = 'image'
const STYLE_IMAGE_SCALE = 'image-scale'
const STYLE_IMAGE_SLICE = 'image-slice' // 9スライス ドット数を指定する
const STYLE_IMAGE_TYPE = 'image-type' // sliced/tiled/simple/filled
const STYLE_IMAGE_FIT_PARENT_BOUNDS = 'image-fit-parent-bounds' // 親と同じ大きさで画像を作成する
const STYLE_LAYER = 'layer'
const STYLE_LAYOUT_ELEMENT = 'layout-element'
const STYLE_LAYOUT_ELEMENT_IGNORE_LAYOUT = 'layout-element-ignore-layout'
const STYLE_LAYOUT_ELEMENT_PREFERRED_WIDTH = 'layout-element-preferred-width'
const STYLE_LAYOUT_ELEMENT_PREFERRED_HEIGHT = 'layout-element-preferred-height'
const STYLE_LAYOUT_GROUP = 'layout-group' //子供を自動的にどうならべるかのオプション
const STYLE_LAYOUT_GROUP_CHILD_ALIGNMENT = 'layout-group-child-alignment'
const STYLE_LAYOUT_GROUP_CHILD_FORCE_EXPAND = 'layout-group-child-force-expand'
const STYLE_LAYOUT_GROUP_CHILD_CONTROL_SIZE = 'layout-group-child-control-size'
const STYLE_LAYOUT_GROUP_SPACING_X = 'layout-group-spacing-x'
const STYLE_LAYOUT_GROUP_SPACING_Y = 'layout-group-spacing-y'
const STYLE_LAYOUT_GROUP_CELL_SIZE_X = 'layout-group-cell-size-x'
const STYLE_LAYOUT_GROUP_CELL_SIZE_Y = 'layout-group-cell-size-y'
const STYLE_LAYOUT_GROUP_START_AXIS = 'layout-group-start-axis'
const STYLE_LAYOUT_GROUP_USE_CHILD_SCALE = 'layout-group-use-child-scale'
const STYLE_LAYOUT_GROUP_CHILDREN_ORDER = 'layout-group-children-order'
const STYLE_MATCH_LOG = 'match-log'
const STYLE_PRESERVE_ASPECT = 'preserve-aspect'
const STYLE_LOCK_ASPECT = 'lock-aspect' // preserve-aspectと同じ動作にする アスペクト比を維持する
const STYLE_RAYCAST_TARGET = 'raycast-target' // 削除予定
const STYLE_RECT_MASK_2D = 'rect-mask-twod'
const STYLE_RECT_TRANSFORM_ANCHORS_OFFSETS_X =
'rect-transform-anchors-offsets-x' // offset-min offset-max anchors-min anchors-maxの順
const STYLE_RECT_TRANSFORM_ANCHORS_OFFSETS_Y =
'rect-transform-anchors-offsets-y' // offset-min offset-max anchors-min anchors-maxの順
const STYLE_RECT_TRANSFORM_ANCHORS_X = 'rect-transform-anchors-x' // anchors-min anchors-maxの順
const STYLE_RECT_TRANSFORM_ANCHORS_Y = 'rect-transform-anchors-y' // anchors-min anchors-maxの順
const STYLE_REPEATGRID_ATTACH_TEXT_DATA_SERIES =
'repeatgrid-attach-text-data-series'
const STYLE_REPEATGRID_ATTACH_IMAGE_DATA_SERIES =
'repeatgrid-attach-image-data-series'
const STYLE_SCROLLBAR = 'scrollbar'
const STYLE_SCROLLBAR_DIRECTION = 'scrollbar-direction'
const STYLE_SCROLLBAR_HANDLE_TARGET = 'scrollbar-handle-target'
const STYLE_SCROLL_RECT = 'scroll-rect'
const STYLE_SCROLL_RECT_CONTENT = 'scroll-rect-content'
const STYLE_SCROLL_RECT_HORIZONTAL = 'scroll-rect-horizontal'
const STYLE_SCROLL_RECT_VERTICAL = 'scroll-rect-vertical'
const STYLE_SCROLL_RECT_HORIZONTAL_SCROLLBAR =
'scroll-rect-horizontal-scrollbar'
const STYLE_SCROLL_RECT_VERTICAL_SCROLLBAR = 'scroll-rect-vertical-scrollbar'
const STYLE_SLIDER = 'slider'
const STYLE_SLIDER_DIRECTION = 'slider-direction'
const STYLE_SLIDER_FILL_RECT_TARGET = 'slider-fill-rect-target'
const STYLE_SLIDER_HANDLE_RECT_TARGET = 'slider-handle-rect-target'
const STYLE_TEXT = 'text'
const STYLE_TEXTMP = 'textmp' // TextMeshPro
const STYLE_TEXT_SET_TEXT = 'text-set-text'
const STYLE_TOGGLE = 'toggle'
const STYLE_TOGGLE_TRANSITION = 'toggle-transition'
const STYLE_TOGGLE_TRANSITION_TARGET_GRAPHIC =
'toggle-transition-target-graphic'
const STYLE_TOGGLE_TRANSITION_HIGHLIGHTED_SPRITE =
'toggle-transition-highlighted-sprite'
const STYLE_TOGGLE_TRANSITION_PRESSED_SPRITE =
'toggle-transition-pressed-sprite'
const STYLE_TOGGLE_TRANSITION_SELECTED_SPRITE =
'toggle-transition-selected-sprite'
const STYLE_TOGGLE_TRANSITION_DISABLED_SPRITE =
'toggle-transition-disabled-sprite'
const STYLE_TOGGLE_ON_GRAPHIC = 'toggle-on-graphic'
const STYLE_TOGGLE_GRAPHIC_SWAP = 'toggle-graphic-swap' // on/off でイメージを変更する
const STYLE_TOGGLE_GROUP = 'toggle-group'
const STYLE_INPUT = 'input'
const STYLE_INPUT_TRANSITION = 'input-transition'
const STYLE_INPUT_GRAPHIC_NAME = 'input-graphic-target'
const STYLE_INPUT_TARGET_GRAPHIC_NAME = 'input-transition-target-graphic-target'
const STYLE_INPUT_TRANSITION_HIGHLIGHTED_SPRITE_TARGET =
'input-transition-highlighted-sprite-target'
const STYLE_INPUT_TRANSITION_PRESSED_SPRITE_TARGET =
'input-transition-pressed-sprite-target'
const STYLE_INPUT_TRANSITION_SELECTED_SPRITE_TARGET =
'input-transition-selected-sprite-target'
const STYLE_INPUT_TRANSITION_DISABLED_SPRITE_TARGET =
'input-transition-disabled-sprite-target'
const STYLE_INPUT_TEXT_TARGET = 'input-text-target'
const STYLE_INPUT_PLACEHOLDER_TARGET = 'input-placeholder-target'
const STYLE_CREATE_CONTENT = 'create-content'
const STYLE_CREATE_CONTENT_BOUNDS = 'create-content-bounds'
const STYLE_CREATE_CONTENT_NAME = 'create-content-name'
const STYLE_V_ALIGN = 'v-align' //テキストの縦方向のアライメント XDの設定に追記される
const STYLE_ADD_COMPONENT = 'add-component'
const STYLE_MASK = 'mask'
const STYLE_SHOW_MASK_GRAPHIC = 'mask-show-mask-graphic'
const STYLE_UNITY_NAME = 'unity-name'
const STYLE_CHECK_LOG = 'check-log'
const STYLE_INSTANCE_IF_POSSIBLE = 'instance-if-possible'
const STYLE_WRAP_VERTICAL_ITEM = 'wrap-vertical-item'
const STYLE_WRAP_HORIZONTAL_ITEM = 'wrap-horizontal-item'
const STYLE_WRAP_MOVE_LAYOUT_ELEMENT = 'wrap-move-layout-element'
const appLanguage = application.appLanguage
//const appLanguage = 'en'
/**
*
* @returns {string}
*/
function getString(multiLangStr) {
/**
* @type {string[]}
*/
if (!multiLangStr) {
return 'no text(strings.json problem)'
}
let str = multiLangStr[appLanguage]
if (str) return str
// 英語にフォールする
str = multiLangStr['en']
if (str) return str
// 日本語にフォールする
str = multiLangStr['ja']
if (str) return str
return 'no text(strings.json problem)'
}
/**
* @param {Folder} currentFolder
* @param {string} filename
* @return {Promise<{selector: CssSelector, declarations: CssDeclarations, at_rule: string}[]>}
*/
async function loadCssRules(currentFolder, filename) {
if (!currentFolder) return null
// console.log(`${filename}の読み込みを開始します`)
let file
try {
file = await currentFolder.getEntry(filename)
} catch (e) {
// console.log(`${currentFolder.nativePath}/${filename}が読み込めません`)
return null
}
const contents = await file.read()
let parsed = parseCss(contents)
for (let parsedElement of parsed) {
const atRule = parsedElement.at_rule
if (atRule) {
const importTokenizer = /\s*@import\s*url\("(?<file_name>.*)"\);/
let token = importTokenizer.exec(atRule)
const importFileName = token.groups.file_name
if (importFileName) {
const p = await loadCssRules(currentFolder, importFileName)
//TODO: 接続する位置とループ対策
parsed = parsed.concat(p)
}
}
}
// console.log(`${file.name} loaded.`)
return parsed
}
/**
* cssRules内、 :root にある --ではじまる変数定期を抽出する
* @param {{selector:CssSelector, declarations:CssDeclarations, at_rule:string }[]} cssRules
*/
function createCssVars(cssRules) {
const vars = {}
for (let cssRule of cssRules) {
if (cssRule.selector && cssRule.selector.isRoot()) {
// console.log("root:をみつけました")
const properties = cssRule.declarations.properties()
for (let property of properties) {
if (property.startsWith('--')) {
const values = cssRule.declarations.values(property)
// console.log(`変数${property}=${values}`)
vars[property] = values[0]
}
}
}
}
return vars
}
/**
* CSS Parser
* ruleブロック selectorとdeclaration部に分ける
* 正規表現テスト https://regex101.com/r/QIifBs/
* @param {string} text
* @param errorThrow
* @return {{selector:CssSelector, declarations:CssDeclarations, at_rule:string }[]}
*/
function parseCss(text, errorThrow = true) {
// コメントアウト処理 エラー時に行数を表示するため、コメント内の改行を残す
//TODO: 文字列内の /* */について正しく処理できない
text = text.replace(/\/\*[\s\S]*?\*\//g, str => {
let replace = ''
for (let c of str) {
if (c === '\n') replace += c
}
return replace
})
// declaration部がなくてもSelectorだけで取得できるようにする NodeNameのパースに使うため
// const tokenizer = /(?<at_rule>\s*@[^;]+;\s*)|((?<selector>(("([^"\\]|\\.)*")|[^{"]+)+)({(?<decl_block>(("([^"\\]|\\.)*")|[^}"]*)*)}\s*)?)/gi
// シングルクオーテーション
const tokenizer = /(?<at_rule>\s*@[^;]+;\s*)|((?<selector>(('([^'\\]|\\.)*')|[^{']+)+)({(?<decl_block>(('([^'\\]|\\.)*')|[^}']*)*)}\s*)?)/gi
const rules = []
let token
while ((token = tokenizer.exec(text))) {
try {
const tokenAtRule = token.groups.at_rule
const tokenSelector = token.groups.selector
const tokenDeclBlock = token.groups.decl_block
if (tokenAtRule) {
rules.push({ at_rule: tokenAtRule })
} else if (tokenSelector) {
const selector = new CssSelector(tokenSelector)
let declarations = null
if (tokenDeclBlock) {
declarations = new CssDeclarations(tokenDeclBlock)
}
rules.push({
selector,
declarations,
})
}
} catch (e) {
if (errorThrow) {
// エラー行の算出
const parsedText = text.substr(0, token.index) // エラーの起きた文字列までを抜き出す
const lines = parsedText.split(/\n/)
//const errorIndex = text.indexOf()
//const errorLastIndex = text.lastIndexOf("\n",token.index)
const errorLine = text.substring(token.index - 30, token.index + 30)
const errorText =
`CSSのパースに失敗した: ${lines.length}行目:${errorLine}\n` +
e.message
console.log(errorText)
// console.log(e.stack)
// console.log(text)
throw errorText
}
}
}
return rules
}
class CssDeclarations {
/**
* @param {null|string} declarationBlock
*/
constructor(declarationBlock = null) {
/**
* @type {string[][]}
*/
if (declarationBlock) {
this.declarations = parseCssDeclarationBlock(declarationBlock)
} else {
this.declarations = {}
}
}
/**
* @return {string[]}
*/
properties() {
return Object.keys(this.declarations)
}
/**
* @param property
* @return {string[]}
*/
values(property) {
return this.declarations[property]
}
/**
* @param {string} property
* @return {*|null}
*/
first(property) {
const values = this.values(property)
if (values == null) return null
return values[0]
}
setFirst(property, value) {
let values = this.values(property)
if (!values) {
values = this.declarations[property] = []
}
values[0] = value
}
firstAsBool(property) {
return asBool(this.first(property))
}
/**
* @param property
* @return {null|boolean}
*/
firstAsNullOrBool(property) {
const first = this.first(property)
if (first === null) return null
return asBool(first)
}
}
/**
* @param {string} declarationBlock
* @return {string[][]}
*/
function parseCssDeclarationBlock(declarationBlock) {
declarationBlock = declarationBlock.trim()
// const tokenizer = /(?<property>[^:";\s]+)\s*:\s*|(?<value>"(?<string>([^"\\]|\\.)*)"|var\([^\)]+\)|[^";:\s]+)/gi
const tokenizer = /(?<property>[^:';\s]+)\s*:\s*|(?<value>'(?<string>([^'\\]|\\.)*)'|var\([^\)]+\)|[^';:\s]+)/gi
/** @type {string[][]} */
let values = {}
/** @type {string[]} */
let currentValues = null
let token
while ((token = tokenizer.exec(declarationBlock))) {
const property = token.groups.property
if (property) {
currentValues = []
values[property] = currentValues
}
let value = token.groups.value
if (value) {
if (token.groups.string) {
value = token.groups.string
}
if (!currentValues) {
// Propertyが無いのに値がある場合
throw 'DeclarationBlockのパースに失敗した'
}
currentValues.push(value)
}
}
return values
}
/**
* folder/name{css-declarations} でパースする
* 例
* MainMenu/vertex#scroller.image {fix:t v a}
* folder:MainMenu id:scroller name:vertex#scroller.image name_without_class:vertex#scroller
* folderの最後の文字に"/"は付かないようにする
* @param {string} nodeName
* @return {{css_declarations: string|null, name: string|null, name_without_class: string|null, folder: string|null}}
*/
function parseNodeName(nodeName) {
// https://regex101.com/r/MdGDaC/3
const pattern = /(?<comment_out>\/\/)?((?<folder>[^{]*)\/)?(?<name>[^{\/]*)(?<css_declarations>{.*})?/g
const r = pattern.exec(nodeName)
if (r.groups.comment_out) {
return {}
}
let name = r.groups.name ? r.groups.name.trim() : null
let name_without_class = name
if (name) {
// name の中にはクラス名もはいっている
const firstDotIndex = name.indexOf('.')
if (firstDotIndex > 0) {
name_without_class = name.substring(0, firstDotIndex).trim()
}
}
let folder = r.groups.folder ? r.groups.folder.trim() : null
let css_declarations = r.groups.css_declarations
return {
folder,
name,
name_without_class,
css_declarations,
}
}
function getSubFolderNameFromNode(node) {
const { folder } = parseNodeName(node.name)
return folder
}
/**
* 拡張子なし
* @param node
* @return {string}
*/
function getLayoutFileNameFromNode(node) {
const unityName = getUnityName(node)
return replaceToFileName(unityName)
}
function getLayoutPathFromNode(node) {
const masterSubFolderName = getSubFolderNameFromNode(node)
const masterName =
(masterSubFolderName ? masterSubFolderName + '/' : '') +
getLayoutFileNameFromNode(node)
return masterName
}
/**
* 自身がインスタンスであり、PrefabになるNodeがいる場合True
* @param {SymbolInstance} node
* @return {boolean}
*/
function isPrefabInstanceNode(node) {
if (!node) return false
const masterNode = getPrefabNodeFromNode(node)
return !!masterNode
}
/**
* Prefabを作成できる条件
* - Componentのマスターである
* - マスターの指定がないと、どれが基準かわからなくなるため
* - 出力サブフォルダーが指定してある
* @param {SceneNodeClass} node
* @return {boolean}
*/
function isPrefabNode(node) {
if (!node) return false
if (!node.symbolId || !node.isMaster) return false
const subFolderName = getSubFolderNameFromNode(node)
// console.log('subfoldername', subFolderName)
if (!subFolderName) return false
return true
}
/**
* NodeNameをCSSパースする これによりローカルCSSも取得する
* WARN: ※ここの戻り値を変更するとキャッシュも変更されてしまう
* NodeNameとは node.nameのこと
* tagNameはCSSパースにより取得される名前 2バイト文字は"_"になる
* // によるコメントアウト処理もここでする
* folder/name{css-declarations} でパースする
* @param {string} nodeName
* @param nodeName
* @return {{folder:string, classNames:string[], id:string, tagName:string, declarations:CssDeclarations}}
*/
function cssParseNodeName(nodeName) {
nodeName = nodeName.trim()
const cache = cacheParseNodeName[nodeName]
if (cache) {
return cache
}
// コメントアウトチェック
let result = null
if (nodeName.startsWith('//')) {
// コメントアウトのスタイルを追加する
const declarations = new CssDeclarations()
declarations.setFirst(STYLE_COMMENT_OUT, true)
result = { declarations }
} else {
// folder/name{css-declarations} でパースする
let { name, folder, css_declarations, name_without_class } = parseNodeName(
nodeName,
)
if (!name) name = nodeName
if (!css_declarations) css_declarations = ''
// console.log(`parseNodeName: folder:${folder} name:${name} css_decl:${r.groups.css_declarations}`)
try {
// 名前をできるだけパースできる文字列に変換する
// そうしないと名前の後ろにつけたローカルCSSの変換ができない
const asciiName = name
.replace(/[^\x01-\x7E]/g, function(s) {
return '_'
}) // - ascii文字以外(2バイト文字、漢字など) _ に変換
.replace(/[^0-9a-zA-Z\-\.]/g, '_') // パース出来ない文字を _に変換する
.replace(/^[^a-zA-Z_\.]/, '_') // 行頭の数字を _に変換する
.replace(/[ ]/g, '') // - スペースはつめる '.class1 .class2' を '.class1.class2' として、クラスのパースができるようにする
// console.log(`parseCss(${asciiName})`)
// name部分とcss-declarationsを結合パースする
const cssString = (asciiName + css_declarations).trim()
let rules = parseCss(cssString, false)
if (cssString.length !== 0 && (!rules || rules.length === 0)) {
// parse 失敗
globalErrorLog.push(`waring: css parse error.(${cssString})`)
}
if (!rules || rules.length === 0 || !rules[0].selector) {
// パースできなかった場合はそのまま返す
result = { folder, name, name_without_class, tagName: nodeName }
} else {
// 一番外側の{}をはずす ここで tagNameがくる tagNameはasciiNameをパースしてくるものなのでマルチバイト文字が_になる
result = rules[0].selector.json['rule']
Object.assign(result, {
folder,
name,
name_without_class,
declarations: rules[0].declarations,
})
}
} catch (e) {
console.log(`***exception: parseNodeName(${nodeName})`)
result = { folder, name, name_without_class, tagName: nodeName }
}
}
cacheParseNodeName[nodeName] = result
return result
}
class MinMaxSize {
constructor() {
this.minWidth = null
this.minHeight = null
this.maxWidth = null
this.maxHeight = null
}
addSize(w, h) {
if (this.minWidth == null || this.minWidth > w) {
this.minWidth = w
}
if (this.maxWidth == null || this.maxWidth < w) {
this.maxWidth = w
}
if (this.minHeight == null || this.minHeight > h) {
this.minHeight = h
}
if (this.maxHeight == null || this.maxHeight < h) {
this.maxHeight = h
}
}
}
class CalcBounds {
constructor() {
this.sx = null
this.sy = null
this.ex = null
this.ey = null
}
addBoundsParam(x, y, w, h) {
if (this.sx == null || this.sx > x) {
this.sx = x
}
if (this.sy == null || this.sy > y) {
this.sy = y
}
const ex = x + w
const ey = y + h
if (this.ex == null || this.ex < ex) {
this.ex = ex
}
if (this.ey == null || this.ey < ey) {
this.ey = ey
}
}
/**
* @param {Bounds} bounds
*/
addBounds(bounds) {
this.addBoundsParam(bounds.x, bounds.y, bounds.width, bounds.height)
}
/**
* @returns {Bounds}
*/
get bounds() {
return {
x: this.sx,
y: this.sy,
width: this.ex - this.sx,
height: this.ey - this.sy,
ex: this.ex,
ey: this.ey,
}
}
}
class GlobalBounds {
/**
* @param {SceneNodeClass} node
*/
constructor(node) {
if (node == null) return
this.visible = globalVisibleInfo[node.guid]
this.global_bounds = getGlobalBounds(node)
this.global_draw_bounds = getGlobalDrawBounds(node)
if (hasContentBounds(node)) {
// Mask(もしくはViewport)をふくむ、含まないで、それぞれのBoundsが必要
// マスクありでBoundsが欲しいとき → 全体コンテンツBoundsがほしいとき とくに、Childrenが大幅にかたよっているときなど
// マスク抜きでBoundsが欲しいとき → List内コンテンツのPaddingの計算
const { style } = getNodeNameAndStyle(node)
const contents = node.children.filter(child => {
return isContentChild(child)
})
const contentBounds = calcGlobalBounds(contents)
this.content_global_bounds = contentBounds.global_bounds
this.content_global_draw_bounds = contentBounds.global_draw_bounds
const viewport = getViewport(node)
if (viewport) {
const viewportContents = contents.concat(viewport)
const viewportContentsBounds = calcGlobalBounds(viewportContents)
this.viewport_content_global_bounds =
viewportContentsBounds.global_bounds
this.viewport_content_global_draw_bounds =
viewportContentsBounds.global_draw_bounds
}
}
}
}
class BoundsToRectTransform {
constructor(node) {
this.node = node
}
updateBeforeBounds() {
// Before
this.before = new GlobalBounds(this.node)
}
updateAfterBounds() {
this.after = new GlobalBounds(this.node)
{
const beforeX = this.before.global_bounds.x
const beforeDrawX = this.before.global_draw_bounds.x
const beforeDrawSizeX = beforeDrawX - beforeX
const afterX = this.after.global_bounds.x
const afterDrawX = this.after.global_draw_bounds.x
const afterDrawSizeX = afterDrawX - afterX
// global
if (!approxEqual(beforeDrawSizeX, afterDrawSizeX)) {
console.log(
`${this.node.name} ${beforeDrawSizeX -
afterDrawSizeX}リサイズ後のBounds.x取得が正確ではないようです`,
)
// beforeのサイズ差をもとに、afterを修正する
this.after.global_draw_bounds.x =
this.after.global_bounds.x + beforeDrawSizeX
}
}
{
const beforeY = this.before.global_bounds.y
const beforeDrawY = this.before.global_draw_bounds.y
const beforeDrawSizeY = beforeDrawY - beforeY
const afterY = this.after.global_bounds.y
const afterDrawY = this.after.global_draw_bounds.y
const afterDrawSizeY = afterDrawY - afterY
if (!approxEqual(beforeDrawSizeY, afterDrawSizeY)) {
console.log(
`${this.node.name} ${beforeDrawSizeY -
afterDrawSizeY}リサイズ後のBounds.y取得がうまくいっていないようです`,
)
// beforeのサイズ差をもとに、afterを修正する
this.after.global_draw_bounds.y =
this.after.global_bounds.y + beforeDrawSizeY
}
}
{
const beforeX = this.before.global_bounds.ex
const beforeDrawX = this.before.global_draw_bounds.ex
const beforeDrawSizeX = beforeDrawX - beforeX
const afterX = this.after.global_bounds.ex
const afterDrawX = this.after.global_draw_bounds.ex
const afterDrawSizeX = afterDrawX - afterX
if (!approxEqual(beforeDrawSizeX, afterDrawSizeX)) {
console.log(
`${this.node.name} ${beforeDrawSizeX -
afterDrawSizeX}リサイズ後のBounds.ex取得がうまくいっていないようです`,
)
// beforeのサイズ差をもとに、afterを修正する
this.after.global_draw_bounds.ex =
this.after.global_bounds.ex + beforeDrawSizeX
}
}
{
const beforeY = this.before.global_bounds.ey
const beforeDrawY = this.before.global_draw_bounds.ey
const beforeDrawSizeY = beforeDrawY - beforeY
const afterY = this.after.global_bounds.ey
const afterDrawY = this.after.global_draw_bounds.ey
const afterDrawSizeY = afterDrawY - afterY
if (!approxEqual(beforeDrawSizeY, afterDrawSizeY)) {
console.log(
`${this.node.name} ${beforeDrawSizeY -
afterDrawSizeY}リサイズ後のBounds.ey取得がうまくいっていないようです`,
)
// beforeのサイズ差をもとに、afterを修正する
this.after.global_draw_bounds.ey =
this.after.global_bounds.ey + beforeDrawSizeY
}
}
this.after.global_draw_bounds.width =
this.after.global_draw_bounds.ex - this.after.global_draw_bounds.x
this.after.global_draw_bounds.height =
this.after.global_draw_bounds.ey - this.after.global_draw_bounds.y
}
updateRestoreBounds() {
this.restore = new GlobalBounds(this.node)
}
calcRectTransform() {
// DrawBoundsでのレスポンシブパラメータ(場合によっては不正確)
this.responsiveParameter = calcRectTransform(this.node)
// GlobalBoundsでのレスポンシブパラメータ(場合によっては不正確)
this.responsiveParameterGlobal = calcRectTransform(this.node, false)
}
}
/**
* ファイル名につかえる文字列に変換する
* @param {string} name
* @param {boolean} convertDot ドットも変換対象にするか
* @return {string}
*/
function replaceToFileName(name, convertDot = false) {
if (convertDot) {
return name.replace(/[\\/:*?"<>|#\x00-\x1F\x7F\.]/g, '_')
}
return name.replace(/[\\/:*?"<>|#\x00-\x1F\x7F]/g, '_')
}
/**
* 誤差範囲での差があるか
* epsの値はこのアプリケーション内では共通にする
* after-bounds before-boundsの変形で誤差が許容範囲と判定したにもかかわらず、
* 後のcalcRectTransformで許容範囲外と判定してまうなどの事故を防ぐため
* @param {number} a
* @param {number} b
*/
function approxEqual(a, b) {
const eps = 0.001 // リサイズして元にもどしたとき、これぐらいの誤差がでる
return Math.abs(a - b) < eps
}
/**
* ラベル名につかえる文字列に変換する
* @param {string} name
* @return {string}
*/
function convertToLabel(name) {
return name.replace(/[\\/:*?"<>|# \x00-\x1F\x7F]/g, '_')
}
/**
* Alphaを除きRGBで6桁16進の色の値を取得する
* @param {number} color
*/
function getRGB(color) {
return ('000000' + color.toString(16)).substr(-6)
}
/**
* 親をさかのぼり、Artboardを探し出す
* @param {SceneNode|SceneNodeClass} node
* @returns {Artboard|null}
*/
function getArtboard(node) {
let parent = node
while (parent != null) {
if (parent.constructor.name === 'Artboard') {
return parent
}
parent = parent.parent
}
return null
}
/**
* @param node
* @returns {RepeatGrid}
*/
function getAncestorRepeatGrid(node) {
let parent = node
while (parent != null) {
if (parent.constructor.name === 'RepeatGrid') {
return parent
}
parent = parent.parent
}
return null
}
/**
* nodeからスケールを考慮したglobalBoundsを取得する
* Artboardであった場合の、viewportHeightも考慮する
* ex,eyがつく
* ハッシュをつかわない
* @param node
* @return {{ex: number, ey: number, x: number, width: number, y: number, height: number}}
*/
function getGlobalBounds(node) {
const bounds = node.globalBounds
// Artboardにあるスクロール領域のボーダー
const viewPortHeight = node.viewportHeight
if (viewPortHeight != null) bounds.height = viewPortHeight
return {
x: bounds.x * globalScale,
y: bounds.y * globalScale,
width: bounds.width * globalScale,
height: bounds.height * globalScale,
ex: (bounds.x + bounds.width) * globalScale,
ey: (bounds.y + bounds.height) * globalScale,
}
}
/**
* nodeからスケールを考慮したglobalDrawBoundsを取得する
* Artboardであった場合の、viewportHeightも考慮する
* ex,eyがつく
* ハッシュをつかわないで取得する
* Textのフォントサイズ情報など、描画サイズにかかわるものを取得する
* アートボードの伸縮でサイズが変わってしまうために退避できるように
* @param {SceneNode|SceneNodeClass} node
* @return {{ex: number, ey: number, x: number, width: number, y: number, height: number}}
*/
function getGlobalDrawBounds(node) {
let bounds = node.globalDrawBounds
const viewPortHeight = node.viewportHeight
if (viewPortHeight != null) bounds.height = viewPortHeight
let b = {
x: bounds.x * globalScale,
y: bounds.y * globalScale,
width: bounds.width * globalScale,
height: bounds.height * globalScale,
ex: (bounds.x + bounds.width) * globalScale,
ey: (bounds.y + bounds.height) * globalScale,
}
// console.log('node.constructor.name:' + node.constructor.name)
if (node.constructor.name === 'Text') {
Object.assign(b, {
text: {
fontSize: node.fontSize,
},
})
}
return b
}
/**
* リサイズされる前のグローバル座標とサイズを取得する
* @param {SceneNode|SceneNodeClass} node
* @return {{ex: number, ey: number, x: number, width: number, y: number, height: number}}
*/
function getBeforeGlobalBounds(node) {
const hashBounds = globalResponsiveBounds
let bounds = null
if (hashBounds != null) {
const hBounds = hashBounds[node.guid]
if (hBounds && hBounds.before) {
bounds = Object.assign({}, hBounds.before.global_bounds)
}
}
if (bounds) return bounds
console.log(
'**error** リサイズ前のGlobalBoundsの情報がありません' + node.name,
)
return null
}
function getBeforeTextFontSize(node) {
const hBounds = globalResponsiveBounds[node.guid]
return hBounds.before.global_draw_bounds.text.fontSize
}
/**
* リサイズされる前のグローバル座標とサイズを取得する
* ハッシュからデータを取得する
* @param {SceneNode|SceneNodeClass} node
* @return {{ex: number, ey: number, x: number, width: number, y: number, height: number}}
*/