source: frontend/node_modules/postcss-merge-longhand/src/lib/decl/borders.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 13 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 21.2 KB
Line 
1'use strict';
2const { list } = require('postcss');
3const stylehacks = require('stylehacks');
4const insertCloned = require('../insertCloned.js');
5const parseTrbl = require('../parseTrbl.js');
6const hasAllProps = require('../hasAllProps.js');
7const getDecls = require('../getDecls.js');
8const getRules = require('../getRules.js');
9const getValue = require('../getValue.js');
10const mergeRules = require('../mergeRules.js');
11const minifyTrbl = require('../minifyTrbl.js');
12const minifyWsc = require('../minifyWsc.js');
13const canMerge = require('../canMerge.js');
14const trbl = require('../trbl.js');
15const isCustomProp = require('../isCustomProp.js');
16const canExplode = require('../canExplode.js');
17const getLastNode = require('../getLastNode.js');
18const parseWsc = require('../parseWsc.js');
19const { isValidWsc } = require('../validateWsc.js');
20
21const wsc = ['width', 'style', 'color'];
22const defaults = ['medium', 'none', 'currentcolor'];
23const colorMightRequireFallback =
24 /(hsla|rgba|color|hwb|lab|lch|oklab|oklch)\(/i;
25
26/**
27 * @param {...string} parts
28 * @return {string}
29 */
30function borderProperty(...parts) {
31 return `border-${parts.join('-')}`;
32}
33/**
34 * @param {string} value
35 * @return {string}
36 */
37function mapBorderProperty(value) {
38 return borderProperty(value);
39}
40
41const directions = trbl.map(mapBorderProperty);
42const properties = wsc.map(mapBorderProperty);
43/** @type {string[]} */
44const directionalProperties = directions.reduce(
45 (prev, curr) => prev.concat(wsc.map((prop) => `${curr}-${prop}`)),
46 /** @type {string[]} */ ([])
47);
48
49const precedence = [
50 ['border'],
51 directions.concat(properties),
52 directionalProperties,
53];
54
55const allProperties = precedence.reduce((a, b) => a.concat(b));
56
57/**
58 * @param {string} prop
59 * @return {number | undefined}
60 */
61function getLevel(prop) {
62 for (let i = 0; i < precedence.length; i++) {
63 if (precedence[i].includes(prop.toLowerCase())) {
64 return i;
65 }
66 }
67}
68
69/** @type {(value: string) => boolean} */
70const isValueCustomProp = (value) =>
71 value !== undefined && value.search(/var\s*\(\s*--/i) !== -1;
72
73/**
74 * @param {string[]} values
75 * @return {boolean}
76 */
77function canMergeValues(values) {
78 return !values.some(isValueCustomProp);
79}
80
81/**
82 * @param {import('postcss').Declaration} decl
83 * @return {string}
84 */
85function getColorValue(decl) {
86 if (decl.prop.substr(-5) === 'color') {
87 return decl.value;
88 }
89
90 return parseWsc(decl.value)[2] || defaults[2];
91}
92
93/**
94 * @param {[string, string, string]} values
95 * @param {[string, string, string]} nextValues
96 * @return {string[]}
97 */
98function diffingProps(values, nextValues) {
99 return wsc.reduce((prev, curr, i) => {
100 if (values[i] === nextValues[i]) {
101 return prev;
102 }
103
104 return [...prev, curr];
105 }, /** @type {string[]} */ ([]));
106}
107
108/**
109 * @param {{values: [string, string, string], nextValues: [string, string, string], decl: import('postcss').Declaration, nextDecl: import('postcss').Declaration, index: number}} arg
110 * @return {void}
111 */
112function mergeRedundant({ values, nextValues, decl, nextDecl, index }) {
113 if (!canMerge([decl, nextDecl])) {
114 return;
115 }
116
117 if (stylehacks.detect(decl) || stylehacks.detect(nextDecl)) {
118 return;
119 }
120
121 const diff = diffingProps(values, nextValues);
122
123 if (diff.length !== 1) {
124 return;
125 }
126
127 const prop = /** @type {string} */ (diff.pop());
128 const position = wsc.indexOf(prop);
129
130 const prop1 = `${nextDecl.prop}-${prop}`;
131 const prop2 = `border-${prop}`;
132
133 let props = parseTrbl(values[position]);
134
135 props[index] = nextValues[position];
136
137 const borderValue2 = values.filter((e, i) => i !== position).join(' ');
138 const propValue2 = minifyTrbl(props);
139
140 const origLength = (minifyWsc(decl.value) + nextDecl.prop + nextDecl.value)
141 .length;
142 const newLength1 =
143 decl.value.length + prop1.length + minifyWsc(nextValues[position]).length;
144 const newLength2 = borderValue2.length + prop2.length + propValue2.length;
145
146 if (newLength1 < newLength2 && newLength1 < origLength) {
147 nextDecl.prop = prop1;
148 nextDecl.value = nextValues[position];
149 }
150
151 if (newLength2 < newLength1 && newLength2 < origLength) {
152 decl.value = borderValue2;
153 nextDecl.prop = prop2;
154 nextDecl.value = propValue2;
155 }
156}
157
158/**
159 * @param {string | string[]} mapped
160 * @return {boolean}
161 */
162function isCloseEnough(mapped) {
163 return (
164 (mapped[0] === mapped[1] && mapped[1] === mapped[2]) ||
165 (mapped[1] === mapped[2] && mapped[2] === mapped[3]) ||
166 (mapped[2] === mapped[3] && mapped[3] === mapped[0]) ||
167 (mapped[3] === mapped[0] && mapped[0] === mapped[1])
168 );
169}
170
171/**
172 * @param {string[]} mapped
173 * @return {string[]}
174 */
175function getDistinctShorthands(mapped) {
176 return [...new Set(mapped)];
177}
178/**
179 * @param {import('postcss').Rule} rule
180 * @return {void}
181 */
182function explode(rule) {
183 rule.walkDecls(/^border/i, (decl) => {
184 if (!canExplode(decl, false)) {
185 return;
186 }
187
188 if (stylehacks.detect(decl)) {
189 return;
190 }
191
192 const prop = decl.prop.toLowerCase();
193
194 // border -> border-trbl
195 if (prop === 'border') {
196 if (isValidWsc(parseWsc(decl.value))) {
197 directions.forEach((direction) => {
198 insertCloned(
199 /** @type {import('postcss').Rule} */ (decl.parent),
200 decl,
201 { prop: direction }
202 );
203 });
204
205 decl.remove();
206 }
207 }
208
209 // border-trbl -> border-trbl-wsc
210 if (directions.some((direction) => prop === direction)) {
211 let values = parseWsc(decl.value);
212
213 if (isValidWsc(values)) {
214 wsc.forEach((d, i) => {
215 insertCloned(
216 /** @type {import('postcss').Rule} */ (decl.parent),
217 decl,
218 {
219 prop: `${prop}-${d}`,
220 value: values[i] || defaults[i],
221 }
222 );
223 });
224
225 decl.remove();
226 }
227 }
228
229 // border-wsc -> border-trbl-wsc
230 wsc.some((style) => {
231 if (prop !== borderProperty(style)) {
232 return false;
233 }
234
235 if (isCustomProp(decl)) {
236 decl.prop = decl.prop.toLowerCase();
237 return false;
238 }
239 parseTrbl(decl.value).forEach((value, i) => {
240 insertCloned(
241 /** @type {import('postcss').Rule} */ (decl.parent),
242 decl,
243 {
244 prop: borderProperty(trbl[i], style),
245 value,
246 }
247 );
248 });
249
250 return decl.remove();
251 });
252 });
253}
254
255/**
256 * @param {import('postcss').Rule} rule
257 * @return {void}
258 */
259function merge(rule) {
260 // border-trbl-wsc -> border-trbl
261 trbl.forEach((direction) => {
262 const prop = borderProperty(direction);
263
264 mergeRules(
265 rule,
266 wsc.map((style) => borderProperty(direction, style)),
267 (rules, lastNode) => {
268 if (canMerge(rules, false) && !rules.some(stylehacks.detect)) {
269 insertCloned(
270 /** @type {import('postcss').Rule} */ (lastNode.parent),
271 lastNode,
272 {
273 prop,
274 value: rules.map(getValue).join(' '),
275 }
276 );
277 for (const node of rules) {
278 node.remove();
279 }
280
281 return true;
282 }
283 return false;
284 }
285 );
286 });
287
288 // border-trbl-wsc -> border-wsc
289 wsc.forEach((style) => {
290 const prop = borderProperty(style);
291
292 mergeRules(
293 rule,
294 trbl.map((direction) => borderProperty(direction, style)),
295 (rules, lastNode) => {
296 if (canMerge(rules) && !rules.some(stylehacks.detect)) {
297 insertCloned(
298 /** @type {import('postcss').Rule} */ (lastNode.parent),
299 lastNode,
300 {
301 prop,
302 value: minifyTrbl(rules.map(getValue).join(' ')),
303 }
304 );
305
306 for (const node of rules) {
307 node.remove();
308 }
309
310 return true;
311 }
312 return false;
313 }
314 );
315 });
316
317 // border-trbl -> border-wsc
318 mergeRules(rule, directions, (rules, lastNode) => {
319 if (rules.some(stylehacks.detect)) {
320 return false;
321 }
322
323 const values = rules.map(({ value }) => value);
324
325 if (!canMergeValues(values)) {
326 return false;
327 }
328
329 const parsed = values.map((value) => parseWsc(value));
330
331 if (!parsed.every(isValidWsc)) {
332 return false;
333 }
334
335 wsc.forEach((d, i) => {
336 const value = parsed.map((v) => v[i] || defaults[i]);
337
338 if (canMergeValues(value)) {
339 insertCloned(
340 /** @type {import('postcss').Rule} */ (lastNode.parent),
341 lastNode,
342 {
343 prop: borderProperty(d),
344 value: minifyTrbl(
345 /** @type {[string, string, string, string]} */ (value)
346 ),
347 }
348 );
349 } else {
350 insertCloned(
351 /** @type {import('postcss').Rule} */ (lastNode.parent),
352 lastNode
353 );
354 }
355 });
356
357 for (const node of rules) {
358 node.remove();
359 }
360
361 return true;
362 });
363
364 // border-wsc -> border
365 // border-wsc -> border + border-color
366 // border-wsc -> border + border-dir
367 mergeRules(rule, properties, (rules, lastNode) => {
368 if (rules.some(stylehacks.detect)) {
369 return false;
370 }
371
372 const values = rules.map((node) => parseTrbl(node.value));
373 const mapped = [0, 1, 2, 3].map((i) =>
374 [values[0][i], values[1][i], values[2][i]].join(' ')
375 );
376
377 if (!canMergeValues(mapped)) {
378 return false;
379 }
380
381 const [width, style, color] = rules;
382 const reduced = getDistinctShorthands(mapped);
383
384 if (isCloseEnough(mapped) && canMerge(rules, false)) {
385 const first =
386 mapped.indexOf(reduced[0]) !== mapped.lastIndexOf(reduced[0]);
387
388 const border = insertCloned(
389 /** @type {import('postcss').Rule} */ (lastNode.parent),
390 lastNode,
391 {
392 prop: 'border',
393 value: first ? reduced[0] : reduced[1],
394 }
395 );
396
397 if (reduced[1]) {
398 const value = first ? reduced[1] : reduced[0];
399 const prop = borderProperty(trbl[mapped.indexOf(value)]);
400
401 rule.insertAfter(
402 border,
403 Object.assign(lastNode.clone(), {
404 prop,
405 value,
406 })
407 );
408 }
409 for (const node of rules) {
410 node.remove();
411 }
412
413 return true;
414 } else if (reduced.length === 1) {
415 rule.insertBefore(
416 color,
417 Object.assign(lastNode.clone(), {
418 prop: 'border',
419 value: [width, style].map(getValue).join(' '),
420 })
421 );
422 rules
423 .filter((node) => node.prop.toLowerCase() !== properties[2])
424 .forEach((node) => node.remove());
425
426 return true;
427 }
428 return false;
429 });
430
431 // border-wsc -> border + border-trbl
432 mergeRules(rule, properties, (rules, lastNode) => {
433 if (rules.some(stylehacks.detect)) {
434 return false;
435 }
436
437 const values = rules.map((node) => parseTrbl(node.value));
438 const mapped = [0, 1, 2, 3].map((i) =>
439 [values[0][i], values[1][i], values[2][i]].join(' ')
440 );
441 const reduced = getDistinctShorthands(mapped);
442 const none = 'medium none currentcolor';
443
444 if (reduced.length > 1 && reduced.length < 4 && reduced.includes(none)) {
445 const filtered = mapped.filter((p) => p !== none);
446 const mostCommon = reduced.sort(
447 (a, b) =>
448 mapped.filter((v) => v === b).length -
449 mapped.filter((v) => v === a).length
450 )[0];
451 const borderValue = reduced.length === 2 ? filtered[0] : mostCommon;
452
453 rule.insertBefore(
454 lastNode,
455 Object.assign(lastNode.clone(), {
456 prop: 'border',
457 value: borderValue,
458 })
459 );
460
461 directions.forEach((dir, i) => {
462 if (mapped[i] !== borderValue) {
463 rule.insertBefore(
464 lastNode,
465 Object.assign(lastNode.clone(), {
466 prop: dir,
467 value: mapped[i],
468 })
469 );
470 }
471 });
472
473 for (const node of rules) {
474 node.remove();
475 }
476
477 return true;
478 }
479 return false;
480 });
481
482 // border-trbl -> border
483 // border-trbl -> border + border-trbl
484 mergeRules(rule, directions, (rules, lastNode) => {
485 if (rules.some(stylehacks.detect)) {
486 return false;
487 }
488
489 const values = rules.map((node) => {
490 const wscValue = parseWsc(node.value);
491
492 if (!isValidWsc(wscValue)) {
493 return node.value;
494 }
495
496 return wscValue.map((value, i) => value || defaults[i]).join(' ');
497 });
498
499 const reduced = getDistinctShorthands(values);
500
501 if (isCloseEnough(values)) {
502 const first =
503 values.indexOf(reduced[0]) !== values.lastIndexOf(reduced[0]);
504
505 rule.insertBefore(
506 lastNode,
507 Object.assign(lastNode.clone(), {
508 prop: 'border',
509 value: minifyWsc(first ? values[0] : values[1]),
510 })
511 );
512
513 if (reduced[1]) {
514 const value = first ? reduced[1] : reduced[0];
515 const prop = directions[values.indexOf(value)];
516 rule.insertBefore(
517 lastNode,
518 Object.assign(lastNode.clone(), {
519 prop: prop,
520 value: minifyWsc(value),
521 })
522 );
523 }
524
525 for (const node of rules) {
526 node.remove();
527 }
528
529 return true;
530 }
531 return false;
532 });
533
534 // border-trbl-wsc + border-trbl (custom prop) -> border-trbl + border-trbl-wsc (custom prop)
535 directions.forEach((direction) => {
536 wsc.forEach((style, i) => {
537 const prop = `${direction}-${style}`;
538
539 mergeRules(rule, [direction, prop], (rules, lastNode) => {
540 if (lastNode.prop !== direction) {
541 return false;
542 }
543
544 const values = parseWsc(lastNode.value);
545
546 if (!isValidWsc(values)) {
547 return false;
548 }
549
550 const wscProp = rules.filter((r) => r !== lastNode)[0];
551
552 if (!isValueCustomProp(values[i]) || isCustomProp(wscProp)) {
553 return false;
554 }
555
556 const wscValue = values[i];
557
558 values[i] = wscProp.value;
559
560 if (canMerge(rules, false) && !rules.some(stylehacks.detect)) {
561 insertCloned(
562 /** @type {import('postcss').Rule} */ (lastNode.parent),
563 lastNode,
564 {
565 prop,
566 value: wscValue,
567 }
568 );
569 lastNode.value = minifyWsc(/** @type {any} */ (values));
570
571 wscProp.remove();
572
573 return true;
574 }
575 return false;
576 });
577 });
578 });
579
580 // border-wsc + border (custom prop) -> border + border-wsc (custom prop)
581 wsc.forEach((style, i) => {
582 const prop = borderProperty(style);
583 mergeRules(rule, ['border', prop], (rules, lastNode) => {
584 if (lastNode.prop !== 'border') {
585 return false;
586 }
587
588 const values = parseWsc(lastNode.value);
589
590 if (!isValidWsc(values)) {
591 return false;
592 }
593
594 const wscProp = rules.filter((r) => r !== lastNode)[0];
595
596 if (!isValueCustomProp(values[i]) || isCustomProp(wscProp)) {
597 return false;
598 }
599
600 const wscValue = values[i];
601
602 values[i] = wscProp.value;
603
604 if (canMerge(rules, false) && !rules.some(stylehacks.detect)) {
605 insertCloned(
606 /** @type {import('postcss').Rule} */ (lastNode.parent),
607 lastNode,
608 {
609 prop,
610 value: wscValue,
611 }
612 );
613 lastNode.value = minifyWsc(/** @type {any} */ (values));
614 wscProp.remove();
615
616 return true;
617 }
618 return false;
619 });
620 });
621
622 // optimize border-trbl
623 let decls = getDecls(rule, directions);
624
625 while (decls.length) {
626 const lastNode = decls[decls.length - 1];
627
628 wsc.forEach((d, i) => {
629 const names = directions
630 .filter((name) => name !== lastNode.prop)
631 .map((name) => `${name}-${d}`);
632
633 let nodes = rule.nodes.slice(0, rule.nodes.indexOf(lastNode));
634
635 const border = getLastNode(nodes, 'border');
636
637 if (border) {
638 nodes = nodes.slice(nodes.indexOf(border));
639 }
640
641 const props = nodes.filter(
642 (node) =>
643 node.type === 'decl' &&
644 names.includes(node.prop) &&
645 node.important === lastNode.important
646 );
647 const rules = getRules(
648 /** @type {import('postcss').Declaration[]} */ (props),
649 names
650 );
651
652 if (hasAllProps(rules, ...names) && !rules.some(stylehacks.detect)) {
653 const values = rules.map((node) => (node ? node.value : null));
654 const filteredValues = values.filter(Boolean);
655 const lastNodeValue = list.space(lastNode.value)[i];
656
657 values[directions.indexOf(lastNode.prop)] = lastNodeValue;
658
659 let value = minifyTrbl(values.join(' '));
660
661 if (
662 filteredValues[0] === filteredValues[1] &&
663 filteredValues[1] === filteredValues[2]
664 ) {
665 value = /** @type {string} */ (filteredValues[0]);
666 }
667
668 let refNode = props[props.length - 1];
669
670 if (value === lastNodeValue) {
671 refNode = lastNode;
672 let valueArray = list.space(lastNode.value);
673 valueArray.splice(i, 1);
674 lastNode.value = valueArray.join(' ');
675 }
676
677 insertCloned(
678 /** @type {import('postcss').Rule} */ (refNode.parent),
679 /** @type {import('postcss').Declaration} */ (refNode),
680 {
681 prop: borderProperty(d),
682 value,
683 }
684 );
685
686 decls = decls.filter((node) => !rules.includes(node));
687 for (const node of rules) {
688 node.remove();
689 }
690 }
691 });
692
693 decls = decls.filter((node) => node !== lastNode);
694 }
695
696 rule.walkDecls('border', (decl) => {
697 const nextDecl = decl.next();
698
699 if (!nextDecl || nextDecl.type !== 'decl') {
700 return false;
701 }
702
703 const index = directions.indexOf(nextDecl.prop);
704
705 if (index === -1) {
706 return;
707 }
708
709 const values = parseWsc(decl.value);
710 const nextValues = parseWsc(nextDecl.value);
711
712 if (!isValidWsc(values) || !isValidWsc(nextValues)) {
713 return;
714 }
715
716 const config = {
717 values,
718 nextValues,
719 decl,
720 nextDecl,
721 index,
722 };
723
724 return mergeRedundant(config);
725 });
726
727 rule.walkDecls(/^border($|-(top|right|bottom|left)$)/i, (decl) => {
728 let values = parseWsc(decl.value);
729
730 if (!isValidWsc(values)) {
731 return;
732 }
733
734 const position = directions.indexOf(decl.prop);
735 let dirs = [...directions];
736
737 dirs.splice(position, 1);
738 wsc.forEach((d, i) => {
739 const props = dirs.map((dir) => `${dir}-${d}`);
740
741 mergeRules(rule, [decl.prop, ...props], (rules) => {
742 if (!rules.includes(decl)) {
743 return false;
744 }
745
746 const longhands = rules.filter((p) => p !== decl);
747
748 if (
749 longhands[0].value.toLowerCase() ===
750 longhands[1].value.toLowerCase() &&
751 longhands[1].value.toLowerCase() ===
752 longhands[2].value.toLowerCase() &&
753 values[i] !== undefined &&
754 longhands[0].value.toLowerCase() === values[i].toLowerCase()
755 ) {
756 for (const node of longhands) {
757 node.remove();
758 }
759
760 insertCloned(
761 /** @type {import('postcss').Rule} */ (decl.parent),
762 decl,
763 {
764 prop: borderProperty(d),
765 value: values[i],
766 }
767 );
768
769 /** @type {string|null} */ (values[i]) = null;
770 }
771 return false;
772 });
773
774 const newValue = values.join(' ');
775
776 if (newValue) {
777 decl.value = newValue;
778 } else {
779 decl.remove();
780 }
781 });
782 });
783
784 // clean-up values
785 rule.walkDecls(/^border($|-(top|right|bottom|left)$)/i, (decl) => {
786 decl.value = minifyWsc(decl.value);
787 });
788
789 // border-spacing-hv -> border-spacing
790 rule.walkDecls(/^border-spacing$/i, (decl) => {
791 const value = list.space(decl.value);
792
793 // merge vertical and horizontal dups
794 if (value.length > 1 && value[0] === value[1]) {
795 decl.value = value.slice(1).join(' ');
796 }
797 });
798
799 // clean-up rules
800 decls = getDecls(rule, allProperties);
801
802 while (decls.length) {
803 const lastNode = decls[decls.length - 1];
804 const lastPart = lastNode.prop.split('-').pop();
805
806 // remove properties of lower precedence
807 const lesser = decls.filter(
808 (node) =>
809 !stylehacks.detect(lastNode) &&
810 !stylehacks.detect(node) &&
811 !isCustomProp(lastNode) &&
812 node !== lastNode &&
813 node.important === lastNode.important &&
814 /** @type {number} */ (getLevel(node.prop)) >
815 /** @type {number} */ (getLevel(lastNode.prop)) &&
816 (node.prop.toLowerCase().includes(lastNode.prop) ||
817 node.prop.toLowerCase().endsWith(/** @type {string} */ (lastPart)))
818 );
819
820 for (const node of lesser) {
821 node.remove();
822 }
823 decls = decls.filter((node) => !lesser.includes(node));
824
825 // get duplicate properties
826 let duplicates = decls.filter(
827 (node) =>
828 !stylehacks.detect(lastNode) &&
829 !stylehacks.detect(node) &&
830 node !== lastNode &&
831 node.important === lastNode.important &&
832 node.prop === lastNode.prop &&
833 !(!isCustomProp(node) && isCustomProp(lastNode))
834 );
835
836 if (duplicates.length) {
837 if (colorMightRequireFallback.test(getColorValue(lastNode))) {
838 const preserve = duplicates
839 .filter(
840 (node) => !colorMightRequireFallback.test(getColorValue(node))
841 )
842 .pop();
843
844 duplicates = duplicates.filter((node) => node !== preserve);
845 }
846 for (const node of duplicates) {
847 node.remove();
848 }
849 }
850
851 decls = decls.filter(
852 (node) => node !== lastNode && !duplicates.includes(node)
853 );
854 }
855}
856
857module.exports = {
858 explode,
859 merge,
860};
Note: See TracBrowser for help on using the repository browser.