-
Notifications
You must be signed in to change notification settings - Fork 134
/
index.ts
1218 lines (1045 loc) · 31.2 KB
/
index.ts
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
// @ts-ignore
import type {
AttrDoubleQuoted,
AttrSingleQuoted,
} from '@shopify/prettier-plugin-liquid/dist/types.js'
import * as astTypes from 'ast-types'
// @ts-ignore
import jsesc from 'jsesc'
// @ts-ignore
import lineColumn from 'line-column'
import type { Parser, ParserOptions, Printer } from 'prettier'
import * as prettierParserAngular from 'prettier/plugins/angular'
import * as prettierParserBabel from 'prettier/plugins/babel'
// @ts-ignore
import * as recast from 'recast'
import { getTailwindConfig } from './config.js'
import { getCustomizations } from './options.js'
import { loadPlugins } from './plugins.js'
import { sortClasses, sortClassList } from './sorting.js'
import type {
Customizations,
StringChange,
TransformerContext,
TransformerEnv,
TransformerMetadata,
} from './types'
import { spliceChangesIntoString, visit } from './utils.js'
let base = await loadPlugins()
function createParser(
parserFormat: string,
transform: (ast: any, context: TransformerContext) => void,
meta: TransformerMetadata = {},
) {
let customizationDefaults: Customizations = {
staticAttrs: new Set(meta.staticAttrs ?? []),
dynamicAttrs: new Set(meta.dynamicAttrs ?? []),
functions: new Set(meta.functions ?? []),
}
return {
...base.parsers[parserFormat],
preprocess(code: string, options: ParserOptions) {
let original = base.originalParser(parserFormat, options)
return original.preprocess ? original.preprocess(code, options) : code
},
async parse(text: string, options: ParserOptions) {
let { context, generateRules } = await getTailwindConfig(options)
let original = base.originalParser(parserFormat, options)
if (original.astFormat in printers) {
options.printer = printers[original.astFormat]
}
// @ts-ignore: We pass three options in the case of plugins that support Prettier 2 _and_ 3.
let ast = await original.parse(text, options, options)
let customizations = getCustomizations(
options,
parserFormat,
customizationDefaults,
)
let changes: any[] = []
transform(ast, {
env: { context, customizations, generateRules, parsers: {}, options },
changes,
})
if (parserFormat === 'svelte') {
ast.changes = changes
}
return ast
},
}
}
function tryParseAngularAttribute(value: string, env: TransformerEnv) {
let parsers = [
// Try parsing as an angular directive
prettierParserAngular.parsers.__ng_directive,
// If this fails we fall back to arbitrary parsing of a JS expression
{ parse: env.parsers.__js_expression },
]
let errors: unknown[] = []
for (const parser of parsers) {
try {
return parser.parse(value, env.parsers, env.options)
} catch (err) {
errors.push(err)
}
}
console.warn('prettier-plugin-tailwindcss: Unable to parse angular directive')
errors.forEach((err) => console.warn(err))
}
function transformDynamicAngularAttribute(attr: any, env: TransformerEnv) {
let directiveAst = tryParseAngularAttribute(attr.value, env)
// If we've reached this point we couldn't parse the expression we we should bail
// `tryParseAngularAttribute` will display some warnings/errors
// But we shouldn't fail outright — just miss parsing some attributes
if (!directiveAst) {
return
}
let changes: StringChange[] = []
visit(directiveAst, {
StringLiteral(node, path) {
if (!node.value) return
let concat = path.find((entry) => {
return (
entry.parent &&
entry.parent.type === 'BinaryExpression' &&
entry.parent.operator === '+'
)
})
changes.push({
start: node.start + 1,
end: node.end - 1,
before: node.value,
after: sortClasses(node.value, {
env,
collapseWhitespace: {
start: concat?.key !== 'right',
end: concat?.key !== 'left',
},
}),
})
},
})
attr.value = spliceChangesIntoString(attr.value, changes)
}
function transformDynamicJsAttribute(attr: any, env: TransformerEnv) {
let { functions } = env.customizations
let ast = recast.parse(`let __prettier_temp__ = ${attr.value}`, {
parser: prettierParserBabel.parsers['babel-ts'],
})
function* ancestors<N, V>(
path: import('ast-types/lib/node-path').NodePath<N, V>,
) {
yield path
while (path.parentPath) {
path = path.parentPath
yield path
}
}
let didChange = false
astTypes.visit(ast, {
visitLiteral(path) {
let entries = Array.from(ancestors(path))
let concat = entries.find((entry) => {
return (
entry.parent &&
entry.parent.value &&
entry.parent.value.type === 'BinaryExpression' &&
entry.parent.value.operator === '+'
)
})
if (isStringLiteral(path.node)) {
let sorted = sortStringLiteral(path.node, {
env,
collapseWhitespace: {
start: concat?.name !== 'right',
end: concat?.name !== 'left',
},
})
if (sorted) {
didChange = true
// https://github.com/benjamn/recast/issues/171#issuecomment-224996336
// @ts-ignore
let quote = path.node.extra.raw[0]
let value = jsesc(path.node.value, {
quotes: quote === "'" ? 'single' : 'double',
})
// @ts-ignore
path.node.value = new String(quote + value + quote)
}
}
this.traverse(path)
},
visitTemplateLiteral(path) {
let entries = Array.from(ancestors(path))
let concat = entries.find((entry) => {
return (
entry.parent &&
entry.parent.value &&
entry.parent.value.type === 'BinaryExpression' &&
entry.parent.value.operator === '+'
)
})
let sorted = sortTemplateLiteral(path.node, {
env,
collapseWhitespace: {
start: concat?.name !== 'right',
end: concat?.name !== 'left',
},
})
if (sorted) {
didChange = true
}
this.traverse(path)
},
visitTaggedTemplateExpression(path) {
let entries = Array.from(ancestors(path))
let concat = entries.find((entry) => {
return (
entry.parent &&
entry.parent.value &&
entry.parent.value.type === 'BinaryExpression' &&
entry.parent.value.operator === '+'
)
})
if (isSortableTemplateExpression(path.node, functions)) {
let sorted = sortTemplateLiteral(path.node.quasi, {
env,
collapseWhitespace: {
start: concat?.name !== 'right',
end: concat?.name !== 'left',
},
})
if (sorted) {
didChange = true
}
}
this.traverse(path)
},
})
if (didChange) {
attr.value = recast.print(ast.program.body[0].declarations[0].init).code
}
}
function transformHtml(ast: any, { env, changes }: TransformerContext) {
let { staticAttrs, dynamicAttrs } = env.customizations
let { parser } = env.options
for (let attr of ast.attrs ?? []) {
if (staticAttrs.has(attr.name)) {
attr.value = sortClasses(attr.value, { env })
} else if (dynamicAttrs.has(attr.name)) {
if (!/[`'"]/.test(attr.value)) {
continue
}
if (parser === 'angular') {
transformDynamicAngularAttribute(attr, env)
} else {
transformDynamicJsAttribute(attr, env)
}
}
}
for (let child of ast.children ?? []) {
transformHtml(child, { env, changes })
}
}
function transformGlimmer(ast: any, { env }: TransformerContext) {
let { staticAttrs } = env.customizations
visit(ast, {
AttrNode(attr, _path, meta) {
if (staticAttrs.has(attr.name) && attr.value) {
meta.sortTextNodes = true
}
},
TextNode(node, path, meta) {
if (!meta.sortTextNodes) {
return
}
let concat = path.find((entry) => {
return entry.parent && entry.parent.type === 'ConcatStatement'
})
let siblings = {
prev: concat?.parent.parts[concat.index! - 1],
next: concat?.parent.parts[concat.index! + 1],
}
node.chars = sortClasses(node.chars, {
env,
ignoreFirst: siblings.prev && !/^\s/.test(node.chars),
ignoreLast: siblings.next && !/\s$/.test(node.chars),
collapseWhitespace: {
start: !siblings.prev,
end: !siblings.next,
},
})
},
StringLiteral(node, path, meta) {
if (!meta.sortTextNodes) {
return
}
let concat = path.find((entry) => {
return (
entry.parent &&
entry.parent.type === 'SubExpression' &&
entry.parent.path.original === 'concat'
)
})
node.value = sortClasses(node.value, {
env,
ignoreLast: Boolean(concat) && !/[^\S\r\n]$/.test(node.value),
collapseWhitespace: {
start: false,
end: !concat,
},
})
},
})
}
function transformLiquid(ast: any, { env }: TransformerContext) {
let { staticAttrs } = env.customizations
function isClassAttr(node: {
name: string | { type: string; value: string }[]
}) {
return Array.isArray(node.name)
? node.name.every(
(n) => n.type === 'TextNode' && staticAttrs.has(n.value),
)
: staticAttrs.has(node.name)
}
function hasSurroundingQuotes(str: string) {
let start = str[0]
let end = str[str.length - 1]
return start === end && (start === '"' || start === "'" || start === '`')
}
let sources: { type: string; source: string }[] = []
let changes: StringChange[] = []
function sortAttribute(attr: AttrSingleQuoted | AttrDoubleQuoted) {
for (let i = 0; i < attr.value.length; i++) {
let node = attr.value[i]
if (node.type === 'TextNode') {
let after = sortClasses(node.value, {
env,
ignoreFirst: i > 0 && !/^\s/.test(node.value),
ignoreLast: i < attr.value.length - 1 && !/\s$/.test(node.value),
removeDuplicates: false,
collapseWhitespace: false,
})
changes.push({
start: node.position.start,
end: node.position.end,
before: node.value,
after,
})
} else if (
// @ts-ignore: `LiquidDrop` is for older versions of the liquid plugin (1.2.x)
(node.type === 'LiquidDrop' || node.type === 'LiquidVariableOutput') &&
typeof node.markup === 'object' &&
node.markup.type === 'LiquidVariable'
) {
visit(node.markup.expression, {
String(node: any) {
let pos = { ...node.position }
// We have to offset the position ONLY when quotes are part of the String node
// This is because `value` does NOT include quotes
if (hasSurroundingQuotes(node.source.slice(pos.start, pos.end))) {
pos.start += 1
pos.end -= 1
}
let after = sortClasses(node.value, { env })
changes.push({
start: pos.start,
end: pos.end,
before: node.value,
after,
})
},
})
}
}
}
visit(ast, {
LiquidTag(node: any) {
sources.push(node)
},
HtmlElement(node: any) {
sources.push(node)
},
AttrSingleQuoted(node: any) {
if (isClassAttr(node)) {
sources.push(node)
sortAttribute(node)
}
},
AttrDoubleQuoted(node: any) {
if (isClassAttr(node)) {
sources.push(node)
sortAttribute(node)
}
},
})
for (let node of sources) {
node.source = spliceChangesIntoString(node.source, changes)
}
}
function sortStringLiteral(
node: any,
{
env,
collapseWhitespace = { start: true, end: true },
}: {
env: TransformerEnv
removeDuplicates?: false
collapseWhitespace?: false | { start: boolean; end: boolean }
},
) {
let result = sortClasses(node.value, {
env,
collapseWhitespace,
})
let didChange = result !== node.value
node.value = result
// A string literal was escaped if:
// - There are backslashes in the raw value; AND
// - The raw value is not the same as the value (excluding the surrounding quotes)
let wasEscaped = false
if (node.extra) {
// JavaScript (StringLiteral)
wasEscaped =
node.extra?.rawValue.includes('\\') &&
node.extra?.raw.slice(1, -1) !== node.value
} else {
// TypeScript (Literal)
wasEscaped =
node.value.includes('\\') && node.raw.slice(1, -1) !== node.value
}
let escaped = wasEscaped ? result.replace(/\\/g, '\\\\') : result
if (node.extra) {
// JavaScript (StringLiteral)
let raw = node.extra.raw
node.extra = {
...node.extra,
rawValue: result,
raw: raw[0] + escaped + raw.slice(-1),
}
} else {
// TypeScript (Literal)
let raw = node.raw
node.raw = raw[0] + escaped + raw.slice(-1)
}
return didChange
}
function isStringLiteral(node: any) {
return (
node.type === 'StringLiteral' ||
(node.type === 'Literal' && typeof node.value === 'string')
)
}
function sortTemplateLiteral(
node: any,
{
env,
collapseWhitespace = { start: true, end: true },
}: {
env: TransformerEnv
removeDuplicates?: false
collapseWhitespace?: false | { start: boolean; end: boolean }
},
) {
let didChange = false
for (let i = 0; i < node.quasis.length; i++) {
let quasi = node.quasis[i]
let same = quasi.value.raw === quasi.value.cooked
let originalRaw = quasi.value.raw
let originalCooked = quasi.value.cooked
quasi.value.raw = sortClasses(quasi.value.raw, {
env,
// Is not the first "item" and does not start with a space
ignoreFirst: i > 0 && !/^\s/.test(quasi.value.raw),
// Is between two expressions
// And does not end with a space
ignoreLast: i < node.expressions.length && !/\s$/.test(quasi.value.raw),
collapseWhitespace: {
start: collapseWhitespace && collapseWhitespace.start && i === 0,
end:
collapseWhitespace &&
collapseWhitespace.end &&
i >= node.expressions.length,
},
})
quasi.value.cooked = same
? quasi.value.raw
: sortClasses(quasi.value.cooked, {
env,
ignoreFirst: i > 0 && !/^\s/.test(quasi.value.cooked),
ignoreLast:
i < node.expressions.length && !/\s$/.test(quasi.value.cooked),
collapseWhitespace: {
start: collapseWhitespace && collapseWhitespace.start && i === 0,
end:
collapseWhitespace &&
collapseWhitespace.end &&
i >= node.expressions.length,
},
})
if (
quasi.value.raw !== originalRaw ||
quasi.value.cooked !== originalCooked
) {
didChange = true
}
}
return didChange
}
function isSortableTemplateExpression(
node:
| import('@babel/types').TaggedTemplateExpression
| import('ast-types').namedTypes.TaggedTemplateExpression,
functions: Set<string>,
): boolean {
if (node.tag.type === 'Identifier') {
return functions.has(node.tag.name)
}
if (node.tag.type === 'MemberExpression') {
let expr = node.tag.object
// If the tag is a MemberExpression we should traverse all MemberExpression's until we find the leading Identifier
while (expr.type === 'MemberExpression') {
expr = expr.object
}
if (expr.type === 'Identifier') {
return functions.has(expr.name)
}
}
return false
}
function isSortableCallExpression(
node:
| import('@babel/types').CallExpression
| import('ast-types').namedTypes.CallExpression,
functions: Set<string>,
): boolean {
if (!node.arguments?.length) {
return false
}
if (node.callee.type === 'Identifier') {
return functions.has(node.callee.name)
}
if (node.callee.type === 'MemberExpression') {
let expr = node.callee.object
// If the tag is a MemberExpression we should traverse all MemberExpression's until we find the leading Identifier
while (expr.type === 'MemberExpression') {
expr = expr.object
}
if (expr.type === 'Identifier') {
return functions.has(expr.name)
}
}
return false
}
function transformJavaScript(
ast: import('@babel/types').Node,
{ env }: TransformerContext,
) {
let { staticAttrs, functions } = env.customizations
function sortInside(ast: import('@babel/types').Node) {
visit(ast, (node, path) => {
let concat = path.find((entry) => {
return (
entry.parent &&
entry.parent.type === 'BinaryExpression' &&
entry.parent.operator === '+'
)
})
if (isStringLiteral(node)) {
sortStringLiteral(node, {
env,
collapseWhitespace: {
start: concat?.key !== 'right',
end: concat?.key !== 'left',
},
})
} else if (node.type === 'TemplateLiteral') {
sortTemplateLiteral(node, {
env,
collapseWhitespace: {
start: concat?.key !== 'right',
end: concat?.key !== 'left',
},
})
} else if (node.type === 'TaggedTemplateExpression') {
if (isSortableTemplateExpression(node, functions)) {
sortTemplateLiteral(node.quasi, {
env,
collapseWhitespace: {
start: concat?.key !== 'right',
end: concat?.key !== 'left',
},
})
}
}
})
}
visit(ast, {
JSXAttribute(node) {
node = node as import('@babel/types').JSXAttribute
if (!node.value) {
return
}
// We don't want to support namespaced attributes (e.g. `somens:class`)
// React doesn't support them and most tools don't either
if (typeof node.name.name !== 'string') {
return
}
if (!staticAttrs.has(node.name.name)) {
return
}
if (isStringLiteral(node.value)) {
sortStringLiteral(node.value, { env })
} else if (node.value.type === 'JSXExpressionContainer') {
sortInside(node.value)
}
},
CallExpression(node) {
node = node as import('@babel/types').CallExpression
if (!isSortableCallExpression(node, functions)) {
return
}
node.arguments.forEach((arg) => sortInside(arg))
},
TaggedTemplateExpression(node, path) {
node = node as import('@babel/types').TaggedTemplateExpression
if (!isSortableTemplateExpression(node, functions)) {
return
}
let concat = path.find((entry) => {
return (
entry.parent &&
entry.parent.type === 'BinaryExpression' &&
entry.parent.operator === '+'
)
})
sortTemplateLiteral(node.quasi, {
env,
collapseWhitespace: {
start: concat?.key !== 'right',
end: concat?.key !== 'left',
},
})
},
})
}
function transformCss(ast: any, { env }: TransformerContext) {
ast.walk((node: any) => {
if (node.type === 'css-atrule' && node.name === 'apply') {
let isImportant = /\s+(?:!important|#{(['"]*)!important\1})\s*$/.test(
node.params,
)
node.params = sortClasses(node.params, {
env,
ignoreLast: isImportant,
collapseWhitespace: {
start: false,
end: !isImportant,
},
})
}
})
}
function transformAstro(ast: any, { env, changes }: TransformerContext) {
let { staticAttrs, dynamicAttrs } = env.customizations
if (
ast.type === 'element' ||
ast.type === 'custom-element' ||
ast.type === 'component'
) {
for (let attr of ast.attributes ?? []) {
if (
staticAttrs.has(attr.name) &&
attr.type === 'attribute' &&
attr.kind === 'quoted'
) {
attr.value = sortClasses(attr.value, {
env,
})
} else if (
dynamicAttrs.has(attr.name) &&
attr.type === 'attribute' &&
attr.kind === 'expression' &&
typeof attr.value === 'string'
) {
transformDynamicJsAttribute(attr, env)
}
}
}
for (let child of ast.children ?? []) {
transformAstro(child, { env, changes })
}
}
function transformMarko(ast: any, { env }: TransformerContext) {
let { staticAttrs } = env.customizations
const nodesToVisit = [ast]
while (nodesToVisit.length > 0) {
const currentNode = nodesToVisit.pop()
switch (currentNode.type) {
case 'File':
nodesToVisit.push(currentNode.program)
break
case 'Program':
nodesToVisit.push(...currentNode.body)
break
case 'MarkoTag':
nodesToVisit.push(...currentNode.attributes)
nodesToVisit.push(currentNode.body)
break
case 'MarkoTagBody':
nodesToVisit.push(...currentNode.body)
break
case 'MarkoAttribute':
if (!staticAttrs.has(currentNode.name)) break
switch (currentNode.value.type) {
case 'ArrayExpression':
const classList = currentNode.value.elements
for (const node of classList) {
if (node.type === 'StringLiteral') {
node.value = sortClasses(node.value, { env })
}
}
break
case 'StringLiteral':
currentNode.value.value = sortClasses(currentNode.value.value, {
env,
})
break
}
break
}
}
}
function transformMelody(ast: any, { env, changes }: TransformerContext) {
let { staticAttrs } = env.customizations
for (let child of ast.expressions ?? []) {
transformMelody(child, { env, changes })
}
visit(ast, {
Attribute(node, _path, meta) {
if (!staticAttrs.has(node.name.name)) return
meta.sortTextNodes = true
},
StringLiteral(node, path, meta) {
if (!meta.sortTextNodes) {
return
}
const concat = path.find((entry) => {
return (
entry.parent &&
(entry.parent.type === 'BinaryConcatExpression' ||
entry.parent.type === 'BinaryAddExpression')
)
})
node.value = sortClasses(node.value, {
env,
ignoreFirst: concat?.key === 'right' && !/^[^\S\r\n]/.test(node.value),
ignoreLast: concat?.key === 'left' && !/[^\S\r\n]$/.test(node.value),
collapseWhitespace: {
start: concat?.key !== 'right',
end: concat?.key !== 'left',
},
})
},
})
}
function transformPug(ast: any, { env }: TransformerContext) {
let { staticAttrs } = env.customizations
// This isn't optimal
// We should merge the classes together across class attributes and class tokens
// And then we sort them
// But this is good enough for now
// First sort the classes in attributes
for (const token of ast.tokens) {
if (token.type === 'attribute' && staticAttrs.has(token.name)) {
token.val = [
token.val.slice(0, 1),
sortClasses(token.val.slice(1, -1), { env }),
token.val.slice(-1),
].join('')
}
}
// Collect lists of consecutive class tokens
let startIdx = -1
let endIdx = -1
let ranges: [number, number][] = []
for (let i = 0; i < ast.tokens.length; i++) {
const token = ast.tokens[i]
if (token.type === 'class') {
startIdx = startIdx === -1 ? i : startIdx
endIdx = i
} else if (startIdx !== -1) {
ranges.push([startIdx, endIdx])
startIdx = -1
endIdx = -1
}
}
if (startIdx !== -1) {
ranges.push([startIdx, endIdx])
startIdx = -1
endIdx = -1
}
// Sort the lists of class tokens
for (const [startIdx, endIdx] of ranges) {
const classes = ast.tokens
.slice(startIdx, endIdx + 1)
.map((token: any) => token.val)
const { classList } = sortClassList(classes, {
env,
removeDuplicates: false,
})
for (let i = startIdx; i <= endIdx; i++) {
ast.tokens[i].val = classList[i - startIdx]
}
}
}
function transformSvelte(ast: any, { env, changes }: TransformerContext) {
let { staticAttrs } = env.customizations
for (let attr of ast.attributes ?? []) {
if (!staticAttrs.has(attr.name) || attr.type !== 'Attribute') {
continue
}
for (let i = 0; i < attr.value.length; i++) {
let value = attr.value[i]
if (value.type === 'Text') {
let same = value.raw === value.data
value.raw = sortClasses(value.raw, {
env,
ignoreFirst: i > 0 && !/^\s/.test(value.raw),
ignoreLast: i < attr.value.length - 1 && !/\s$/.test(value.raw),
removeDuplicates: false,
collapseWhitespace: false,
})
value.data = same
? value.raw
: sortClasses(value.data, {
env,
ignoreFirst: i > 0 && !/^\s/.test(value.data),
ignoreLast: i < attr.value.length - 1 && !/\s$/.test(value.data),
removeDuplicates: false,
collapseWhitespace: false,
})
} else if (value.type === 'MustacheTag') {
visit(value.expression, {
Literal(node) {
if (isStringLiteral(node)) {
let before = node.raw
let sorted = sortStringLiteral(node, {
env,
removeDuplicates: false,
collapseWhitespace: false,
})
if (sorted) {
changes.push({
before,
after: node.raw,
start: node.loc.start,
end: node.loc.end,
})
}
}
},
TemplateLiteral(node) {
let before = node.quasis.map((quasi: any) => quasi.value.raw)
let sorted = sortTemplateLiteral(node, {
env,
removeDuplicates: false,
collapseWhitespace: false,
})
if (sorted) {
for (let [idx, quasi] of node.quasis.entries()) {
changes.push({
before: before[idx],
after: quasi.value.raw,
start: quasi.loc.start,
end: quasi.loc.end,
})
}
}
},