1 | 'use strict';
|
---|
2 |
|
---|
3 | exports.type = 'visitor';
|
---|
4 | exports.name = 'sortDefsChildren';
|
---|
5 | exports.active = true;
|
---|
6 | exports.description = 'Sorts children of <defs> to improve compression';
|
---|
7 |
|
---|
8 | /**
|
---|
9 | * Sorts children of defs in order to improve compression.
|
---|
10 | * Sorted first by frequency then by element name length then by element name (to ensure grouping).
|
---|
11 | *
|
---|
12 | * @author David Leston
|
---|
13 | *
|
---|
14 | * @type {import('../lib/types').Plugin<void>}
|
---|
15 | */
|
---|
16 | exports.fn = () => {
|
---|
17 | return {
|
---|
18 | element: {
|
---|
19 | enter: (node) => {
|
---|
20 | if (node.name === 'defs') {
|
---|
21 | /**
|
---|
22 | * @type {Map<string, number>}
|
---|
23 | */
|
---|
24 | const frequencies = new Map();
|
---|
25 | for (const child of node.children) {
|
---|
26 | if (child.type === 'element') {
|
---|
27 | const frequency = frequencies.get(child.name);
|
---|
28 | if (frequency == null) {
|
---|
29 | frequencies.set(child.name, 1);
|
---|
30 | } else {
|
---|
31 | frequencies.set(child.name, frequency + 1);
|
---|
32 | }
|
---|
33 | }
|
---|
34 | }
|
---|
35 | node.children.sort((a, b) => {
|
---|
36 | if (a.type !== 'element' || b.type !== 'element') {
|
---|
37 | return 0;
|
---|
38 | }
|
---|
39 | const aFrequency = frequencies.get(a.name);
|
---|
40 | const bFrequency = frequencies.get(b.name);
|
---|
41 | if (aFrequency != null && bFrequency != null) {
|
---|
42 | const frequencyComparison = bFrequency - aFrequency;
|
---|
43 | if (frequencyComparison !== 0) {
|
---|
44 | return frequencyComparison;
|
---|
45 | }
|
---|
46 | }
|
---|
47 | const lengthComparison = b.name.length - a.name.length;
|
---|
48 | if (lengthComparison !== 0) {
|
---|
49 | return lengthComparison;
|
---|
50 | }
|
---|
51 | if (a.name !== b.name) {
|
---|
52 | return a.name > b.name ? -1 : 1;
|
---|
53 | }
|
---|
54 | return 0;
|
---|
55 | });
|
---|
56 | }
|
---|
57 | },
|
---|
58 | },
|
---|
59 | };
|
---|
60 | };
|
---|