@eightshift/frontend-libs-tailwind 3.3.0 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/CODEOWNERS +1 -1
- package/CHANGELOG.md +27 -1
- package/README.md +45 -0
- package/bin/tw-sweep.mjs +281 -0
- package/bun.lock +163 -152
- package/linters/oxlint.config.mjs +65 -0
- package/linters/tw-ignore.mjs +45 -0
- package/linters/tw-sweep-extract.mjs +545 -0
- package/package.json +24 -16
- package/scripts/editor/tailwindcss.js +60 -220
- package/test/fixtures/theme/src/Blocks/custom/card/card.php +23 -0
- package/test/fixtures/theme/src/Blocks/custom/card/manifest.json +13 -0
- package/test/fixtures/theme/src/Plugins/Forms.php +15 -0
- package/test/fixtures/theme/src/card.js +2 -0
- package/test/fixtures/theme/tailwind.css +6 -0
- package/test/fixtures/theme/tw-ignore.json +1 -0
- package/test/tw-sweep.test.mjs +119 -0
- package/.claude/settings.local.json +0 -7
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import { getDefaultSelectors } from 'eslint-plugin-better-tailwindcss/defaults';
|
|
3
|
+
import { loadTwIgnore, TW_IGNORE_FILE } from './tw-ignore.mjs';
|
|
4
|
+
|
|
5
|
+
// Resolved here, not by name, so projects that depend only on this package
|
|
6
|
+
// load the plugin under isolated linkers (pnpm, bun --linker isolated).
|
|
7
|
+
const tailwindPlugin = fileURLToPath(import.meta.resolve('eslint-plugin-better-tailwindcss'));
|
|
8
|
+
|
|
9
|
+
const defaultIgnorePatterns = ['public/**', 'node_modules/**', 'vendor/**', 'vendor-prefixed/**', 'eightshift/**', 'coverage/**'];
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Eightshift oxlint config with Tailwind class checks.
|
|
13
|
+
*
|
|
14
|
+
* Usage in a project's `oxlint.config.ts`:
|
|
15
|
+
*
|
|
16
|
+
* import { defineConfig } from 'oxlint';
|
|
17
|
+
* import { createOxlintConfig } from '@eightshift/frontend-libs-tailwind/linters/oxlint.config.mjs';
|
|
18
|
+
*
|
|
19
|
+
* export default defineConfig(createOxlintConfig({ entryPoint: 'tailwind.css' }));
|
|
20
|
+
*
|
|
21
|
+
* Unknown-class exceptions live in `tw-ignore.json` (shared with `tw-sweep`).
|
|
22
|
+
*
|
|
23
|
+
* @param {object} options
|
|
24
|
+
* @param {string} options.entryPoint Tailwind CSS entry, relative to the config.
|
|
25
|
+
* @param {string} [options.ignoreFile] Unknown-class ignore list (JSON array of regex strings).
|
|
26
|
+
* @param {string[]} [options.ignorePatterns] Extra paths to skip.
|
|
27
|
+
* @param {object} [options.rules] Rule overrides, merged last.
|
|
28
|
+
* @returns {object} oxlint config.
|
|
29
|
+
*/
|
|
30
|
+
export function createOxlintConfig({ entryPoint, ignoreFile = TW_IGNORE_FILE, ignorePatterns = [], rules = {} }) {
|
|
31
|
+
if (!entryPoint) {
|
|
32
|
+
throw new Error('createOxlintConfig: `entryPoint` is required');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
plugins: ['eslint', 'unicorn', 'oxc', 'react'],
|
|
37
|
+
jsPlugins: [tailwindPlugin],
|
|
38
|
+
settings: {
|
|
39
|
+
'better-tailwindcss': {
|
|
40
|
+
entryPoint,
|
|
41
|
+
selectors: [...getDefaultSelectors(), { kind: 'attribute', name: '^.+ClassName$', match: [{ type: 'strings' }] }],
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
ignorePatterns: [...defaultIgnorePatterns, ...ignorePatterns],
|
|
45
|
+
rules: {
|
|
46
|
+
'no-array-constructor': 'error',
|
|
47
|
+
'no-constant-binary-expression': 'error',
|
|
48
|
+
'no-implicit-coercion': 'error',
|
|
49
|
+
'no-nested-ternary': 'error',
|
|
50
|
+
'no-unused-expressions': 'error',
|
|
51
|
+
'no-void': 'error',
|
|
52
|
+
'no-param-reassign': 'warn',
|
|
53
|
+
'react/rules-of-hooks': 'error',
|
|
54
|
+
'react/exhaustive-deps': 'error',
|
|
55
|
+
'react/react-in-jsx-scope': 'off',
|
|
56
|
+
'react/self-closing-comp': 'warn',
|
|
57
|
+
'better-tailwindcss/no-duplicate-classes': 'error',
|
|
58
|
+
'better-tailwindcss/no-deprecated-classes': 'error',
|
|
59
|
+
'better-tailwindcss/enforce-canonical-classes': 'error',
|
|
60
|
+
'better-tailwindcss/no-unknown-classes': ['error', { ignore: loadTwIgnore(ignoreFile) }],
|
|
61
|
+
'better-tailwindcss/no-conflicting-classes': 'error',
|
|
62
|
+
...rules,
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
|
|
4
|
+
export const TW_IGNORE_FILE = 'tw-ignore.json';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Loads the project's Tailwind unknown-class ignore list: a JSON array of regex
|
|
8
|
+
* source strings, shared by oxlint (`no-unknown-classes`) and `tw-sweep`.
|
|
9
|
+
*
|
|
10
|
+
* A missing file means "ignore nothing". An invalid file or pattern throws,
|
|
11
|
+
* naming the offending entry, so a typo never silently disables the check.
|
|
12
|
+
*
|
|
13
|
+
* @param {string} [file] Path to the JSON file, relative to `cwd`.
|
|
14
|
+
* @param {string} [cwd] Base directory.
|
|
15
|
+
* @returns {string[]} Regex source strings.
|
|
16
|
+
*/
|
|
17
|
+
export function loadTwIgnore(file = TW_IGNORE_FILE, cwd = process.cwd()) {
|
|
18
|
+
const path = resolve(cwd, file);
|
|
19
|
+
|
|
20
|
+
if (!existsSync(path)) {
|
|
21
|
+
return [];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
let patterns;
|
|
25
|
+
|
|
26
|
+
try {
|
|
27
|
+
patterns = JSON.parse(readFileSync(path, 'utf8'));
|
|
28
|
+
} catch (error) {
|
|
29
|
+
throw new Error(`${path}: invalid JSON (${error.message})`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (!Array.isArray(patterns) || patterns.some((pattern) => typeof pattern !== 'string')) {
|
|
33
|
+
throw new Error(`${path}: expected a JSON array of regex strings`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
for (const pattern of patterns) {
|
|
37
|
+
try {
|
|
38
|
+
new RegExp(pattern);
|
|
39
|
+
} catch (error) {
|
|
40
|
+
throw new Error(`${path}: invalid pattern ${JSON.stringify(pattern)} (${error.message})`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return patterns;
|
|
45
|
+
}
|
|
@@ -0,0 +1,545 @@
|
|
|
1
|
+
// Class extraction for tw-sweep.
|
|
2
|
+
//
|
|
3
|
+
// Extraction yields GROUPS. A group is one class "source" (one manifest
|
|
4
|
+
// string, one PHP string literal, one class attribute) holding
|
|
5
|
+
// {className, start, end} tokens with absolute file offsets.
|
|
6
|
+
|
|
7
|
+
export const REGION_START = 'tw-sweep-classes-start';
|
|
8
|
+
export const REGION_END = 'tw-sweep-classes-end';
|
|
9
|
+
|
|
10
|
+
// Only tokens that look like utilities. Bare words (`group`, `tab`, `flex`)
|
|
11
|
+
// are skipped: they are mostly hooks, and the known ones are always canonical.
|
|
12
|
+
export function splitToTokens(value, valueAbsStart) {
|
|
13
|
+
const tokens = [];
|
|
14
|
+
|
|
15
|
+
for (const match of value.matchAll(/\S+/g)) {
|
|
16
|
+
const className = match[0];
|
|
17
|
+
|
|
18
|
+
if (!/[-:]/.test(className)) {
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
tokens.push({ className, start: valueAbsStart + match.index, end: valueAbsStart + match.index + className.length });
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
return tokens;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function pushGroup(groups, kind, value, valueAbsStart) {
|
|
29
|
+
const tokens = splitToTokens(value, valueAbsStart);
|
|
30
|
+
|
|
31
|
+
if (tokens.length) {
|
|
32
|
+
groups.push({ kind, tokens });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// If a comment starts at `i`, returns the index of its last character;
|
|
37
|
+
// otherwise -1. Used outside strings so an apostrophe in a comment never
|
|
38
|
+
// opens one. `#[` is a PHP attribute, not a comment.
|
|
39
|
+
function commentEnd(content, i) {
|
|
40
|
+
const two = content.slice(i, i + 2);
|
|
41
|
+
|
|
42
|
+
if (two === '//' || (content[i] === '#' && content[i + 1] !== '[')) {
|
|
43
|
+
const newline = content.indexOf('\n', i);
|
|
44
|
+
|
|
45
|
+
return newline === -1 ? content.length - 1 : newline - 1;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (two === '/*') {
|
|
49
|
+
const close = content.indexOf('*/', i + 2);
|
|
50
|
+
|
|
51
|
+
return close === -1 ? content.length - 1 : close + 1;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return -1;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function findClose(content, open) {
|
|
58
|
+
const pairs = { '[': ']', '{': '}', '(': ')' };
|
|
59
|
+
const stack = [pairs[content[open]]];
|
|
60
|
+
let quote = null;
|
|
61
|
+
|
|
62
|
+
for (let i = open + 1; i < content.length; i++) {
|
|
63
|
+
const char = content[i];
|
|
64
|
+
|
|
65
|
+
if (quote) {
|
|
66
|
+
if (char === '\\') {
|
|
67
|
+
i++;
|
|
68
|
+
} else if (char === quote) {
|
|
69
|
+
quote = null;
|
|
70
|
+
}
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const skipTo = commentEnd(content, i);
|
|
75
|
+
|
|
76
|
+
if (skipTo !== -1) {
|
|
77
|
+
i = skipTo;
|
|
78
|
+
} else if (char === '"' || char === "'") {
|
|
79
|
+
quote = char;
|
|
80
|
+
} else if (pairs[char]) {
|
|
81
|
+
stack.push(pairs[char]);
|
|
82
|
+
} else if (char === stack[stack.length - 1]) {
|
|
83
|
+
stack.pop();
|
|
84
|
+
|
|
85
|
+
if (!stack.length) {
|
|
86
|
+
return i;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return content.length;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ---- manifest.json -------------------------------------------------------
|
|
95
|
+
|
|
96
|
+
function jsonStrings(content, from, to) {
|
|
97
|
+
const out = [];
|
|
98
|
+
const re = /"((?:[^"\\]|\\.)*)"(\s*:)?/g;
|
|
99
|
+
|
|
100
|
+
re.lastIndex = from;
|
|
101
|
+
|
|
102
|
+
for (let m; (m = re.exec(content)) && m.index < to;) {
|
|
103
|
+
if (!m[2]) {
|
|
104
|
+
out.push({ value: m[1], start: m.index + 1 });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// String literal syntaxes. `decode(raw, i)` reads one character or escape at
|
|
112
|
+
// `i` of a raw literal body and returns [decoded, sourceLength]; `encode(text)`
|
|
113
|
+
// writes a class back so it decodes to `text`. PHP keeps unknown escapes as
|
|
114
|
+
// written (`'\_'` and `"\_"` are a backslash and `_`), so its encoders escape a
|
|
115
|
+
// backslash only where PHP would otherwise read an escape.
|
|
116
|
+
const JSON_STRING = {
|
|
117
|
+
decode: (raw, i) => {
|
|
118
|
+
if (raw[i] !== '\\') {
|
|
119
|
+
return [raw[i], 1];
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const length = raw[i + 1] === 'u' ? 6 : 2;
|
|
123
|
+
|
|
124
|
+
return [JSON.parse(`"${raw.slice(i, i + length)}"`), length];
|
|
125
|
+
},
|
|
126
|
+
encode: (text) => JSON.stringify(text).slice(1, -1),
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
const PHP_SINGLE = {
|
|
130
|
+
decode: (raw, i) => (raw[i] === '\\' && (raw[i + 1] === '\\' || raw[i + 1] === "'") ? [raw[i + 1], 2] : [raw[i], 1]),
|
|
131
|
+
encode: (text) => text.replace(/'|\\(?=[\\']|$)/g, '\\$&'),
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const PHP_DOUBLE_ESCAPES = { n: '\n', t: '\t', r: '\r', v: '\v', f: '\f', e: '\x1b', '\\': '\\', $: '$', '"': '"' };
|
|
135
|
+
|
|
136
|
+
const PHP_DOUBLE = {
|
|
137
|
+
decode: (raw, i) => (raw[i] === '\\' && Object.hasOwn(PHP_DOUBLE_ESCAPES, raw[i + 1] ?? '') ? [PHP_DOUBLE_ESCAPES[raw[i + 1]], 2] : [raw[i], 1]),
|
|
138
|
+
encode: (text) => text.replace(/["$]|\\(?=[nrtvfe\\$"0-7xu]|$)/g, '\\$&'),
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const JS_ESCAPES = { n: '\n', t: '\t', r: '\r', v: '\v', f: '\f', b: '\b', 0: '\0', '\n': '' };
|
|
142
|
+
|
|
143
|
+
// JS drops the backslash of unknown escapes (`'\_'` is `_`).
|
|
144
|
+
const jsString = (quote) => ({
|
|
145
|
+
decode: (raw, i) => {
|
|
146
|
+
if (raw[i] !== '\\') {
|
|
147
|
+
return [raw[i], 1];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const next = raw[i + 1];
|
|
151
|
+
|
|
152
|
+
if (next === 'x') {
|
|
153
|
+
return [String.fromCharCode(parseInt(raw.slice(i + 2, i + 4), 16)), 4];
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (next === 'u') {
|
|
157
|
+
const braced = raw[i + 2] === '{';
|
|
158
|
+
const end = braced ? raw.indexOf('}', i) + 1 : i + 6;
|
|
159
|
+
|
|
160
|
+
return [String.fromCodePoint(parseInt(raw.slice(i + (braced ? 3 : 2), braced ? end - 1 : end), 16)), end - i];
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
return [JS_ESCAPES[next] ?? next, 2];
|
|
164
|
+
},
|
|
165
|
+
encode: (text) => text.replace(new RegExp(`[\\\\${quote}]`, 'g'), '\\$&'),
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
// Splits a raw literal body (escapes intact) into tokens. Class names are
|
|
169
|
+
// decoded, so an escaped newline separates classes; offsets stay on the raw
|
|
170
|
+
// source, and `encode` lets `--write` re-escape the replacement.
|
|
171
|
+
function pushEscapedGroup(groups, kind, raw, rawStart, syntax) {
|
|
172
|
+
const tokens = [];
|
|
173
|
+
let current = null;
|
|
174
|
+
|
|
175
|
+
const finish = () => {
|
|
176
|
+
if (current && /[-:]/.test(current.className)) {
|
|
177
|
+
tokens.push(current);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
current = null;
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
for (let i = 0; i < raw.length;) {
|
|
184
|
+
const [char, length] = syntax.decode(raw, i);
|
|
185
|
+
|
|
186
|
+
if (/\s/.test(char)) {
|
|
187
|
+
finish();
|
|
188
|
+
} else {
|
|
189
|
+
current ??= { className: '', start: rawStart + i, encode: syntax.encode };
|
|
190
|
+
current.className += char;
|
|
191
|
+
current.end = rawStart + i + length;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
i += length;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
finish();
|
|
198
|
+
|
|
199
|
+
if (tokens.length) {
|
|
200
|
+
groups.push({ kind, tokens });
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function extractManifest(content, groups) {
|
|
205
|
+
// "twClasses": "a b", "twClassesEditor": "a b", ...
|
|
206
|
+
for (const m of content.matchAll(/"(twClasses\w*)"\s*:\s*"((?:[^"\\]|\\.)*)"/g)) {
|
|
207
|
+
pushEscapedGroup(groups, 'manifest', m[2], m.index + m[0].length - m[2].length - 1, JSON_STRING);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// "twClasses": { "variant": ["a", "b"] } and "twClasses*": ["a", "b"]
|
|
211
|
+
for (const m of content.matchAll(/"(twClasses\w*)"\s*:\s*([[{])/g)) {
|
|
212
|
+
const open = m.index + m[0].length - 1;
|
|
213
|
+
const close = findClose(content, open);
|
|
214
|
+
|
|
215
|
+
for (const literal of jsonStrings(content, open + 1, close)) {
|
|
216
|
+
pushEscapedGroup(groups, 'manifest', literal.value, literal.start, JSON_STRING);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ---- PHP -------------------------------------------------------------------
|
|
222
|
+
|
|
223
|
+
// A literal alone in brackets that follow an expression is an index
|
|
224
|
+
// (`$map['key']`, `get()['key']`). After `(`, `,`, `=` or a keyword such as
|
|
225
|
+
// `return`, the brackets open an array value (`['w-[16px]']`).
|
|
226
|
+
function isArrayIndex(content, literalStart, literalEnd) {
|
|
227
|
+
if (!/^\s*\]/.test(content.slice(literalEnd, literalEnd + 4))) {
|
|
228
|
+
return false;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const before = content.slice(Math.max(0, literalStart - 64), literalStart).match(/(?:(\w+)|[\])}])\s*\[\s*$/);
|
|
232
|
+
|
|
233
|
+
return Boolean(before) && !/^(return|yield|echo|print|case|and|or|xor|else)$/i.test(before[1] ?? '');
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Comment spans [start, end) in a PHP file. Outside `<?php … ?>` only HTML
|
|
237
|
+
// comments count. Inside, PHP comments outside strings count, and a `//` or `#`
|
|
238
|
+
// comment ends at the newline or at `?>`, as in PHP.
|
|
239
|
+
function phpCommentRanges(content) {
|
|
240
|
+
const ranges = [];
|
|
241
|
+
let inPhp = false;
|
|
242
|
+
let quote = null;
|
|
243
|
+
|
|
244
|
+
for (let i = 0; i < content.length; i++) {
|
|
245
|
+
const char = content[i];
|
|
246
|
+
|
|
247
|
+
if (!inPhp) {
|
|
248
|
+
if (content.startsWith('<?', i)) {
|
|
249
|
+
inPhp = true;
|
|
250
|
+
i++;
|
|
251
|
+
} else if (content.startsWith('<!--', i)) {
|
|
252
|
+
const close = content.indexOf('-->', i + 4);
|
|
253
|
+
const end = close === -1 ? content.length : close + 3;
|
|
254
|
+
|
|
255
|
+
ranges.push([i, end]);
|
|
256
|
+
i = end - 1;
|
|
257
|
+
}
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
if (quote) {
|
|
262
|
+
if (char === '\\') {
|
|
263
|
+
i++;
|
|
264
|
+
} else if (char === quote) {
|
|
265
|
+
quote = null;
|
|
266
|
+
}
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
if (content.startsWith('?>', i)) {
|
|
271
|
+
inPhp = false;
|
|
272
|
+
i++;
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (char === '"' || char === "'") {
|
|
277
|
+
quote = char;
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const skipTo = commentEnd(content, i);
|
|
282
|
+
|
|
283
|
+
if (skipTo === -1) {
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
let end = skipTo + 1;
|
|
288
|
+
|
|
289
|
+
if (!content.startsWith('/*', i)) {
|
|
290
|
+
const tagClose = content.indexOf('?>', i);
|
|
291
|
+
|
|
292
|
+
if (tagClose !== -1 && tagClose < end) {
|
|
293
|
+
end = tagClose;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
ranges.push([i, end]);
|
|
298
|
+
i = end - 1;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
return ranges;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function htmlCommentRanges(content) {
|
|
305
|
+
return [...content.matchAll(/<!--[\s\S]*?(?:-->|$)/g)].map((m) => [m.index, m.index + m[0].length]);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const inRanges = (ranges, offset) => ranges.some(([start, end]) => offset >= start && offset < end);
|
|
309
|
+
|
|
310
|
+
// PHP string literals in [from, to). Comments are skipped, because an
|
|
311
|
+
// apostrophe in one would otherwise open a string. Double-quoted strings with
|
|
312
|
+
// `$` are interpolated, so they are not static classes. With `skipKeys`,
|
|
313
|
+
// literals used as array keys or indexes are skipped.
|
|
314
|
+
function phpStrings(content, from, to, { skipKeys }) {
|
|
315
|
+
const out = [];
|
|
316
|
+
const re = /\/\/[^\n]*|#(?!\[)[^\n]*|\/\*[\s\S]*?\*\/|'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)"/g;
|
|
317
|
+
|
|
318
|
+
re.lastIndex = from;
|
|
319
|
+
|
|
320
|
+
for (let m; (m = re.exec(content)) && m.index < to;) {
|
|
321
|
+
if (m[1] === undefined && m[2] === undefined) {
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const value = m[1] ?? m[2];
|
|
326
|
+
|
|
327
|
+
if (m[2] !== undefined && value.includes('$')) {
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
if (skipKeys && (/^\s*=>/.test(content.slice(re.lastIndex, re.lastIndex + 4)) || isArrayIndex(content, m.index, re.lastIndex))) {
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Comparison operands (`$type === 'layout-grid'`) are values, not classes.
|
|
336
|
+
if (/(===|!==|==|!=|<>)\s*$/.test(content.slice(Math.max(0, m.index - 8), m.index)) || /^\s*(===|!==|==|!=|<>)/.test(content.slice(re.lastIndex, re.lastIndex + 8))) {
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
out.push({ value, start: m.index + 1, syntax: m[1] === undefined ? PHP_DOUBLE : PHP_SINGLE });
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
return out;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// Splits call arguments at top-level commas: [{start, end}] (end exclusive).
|
|
347
|
+
function callArgs(content, open, close) {
|
|
348
|
+
const args = [];
|
|
349
|
+
let start = open + 1;
|
|
350
|
+
let quote = null;
|
|
351
|
+
let depth = 0;
|
|
352
|
+
|
|
353
|
+
for (let i = open + 1; i < close; i++) {
|
|
354
|
+
const char = content[i];
|
|
355
|
+
|
|
356
|
+
if (quote) {
|
|
357
|
+
if (char === '\\') {
|
|
358
|
+
i++;
|
|
359
|
+
} else if (char === quote) {
|
|
360
|
+
quote = null;
|
|
361
|
+
}
|
|
362
|
+
continue;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const skipTo = commentEnd(content, i);
|
|
366
|
+
|
|
367
|
+
if (skipTo !== -1) {
|
|
368
|
+
i = skipTo;
|
|
369
|
+
} else if (char === '"' || char === "'") {
|
|
370
|
+
quote = char;
|
|
371
|
+
} else if ('([{'.includes(char)) {
|
|
372
|
+
depth++;
|
|
373
|
+
} else if (')]}'.includes(char)) {
|
|
374
|
+
depth--;
|
|
375
|
+
} else if (char === ',' && depth === 0) {
|
|
376
|
+
args.push({ start, end: i });
|
|
377
|
+
start = i + 1;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
args.push({ start, end: close });
|
|
382
|
+
|
|
383
|
+
return args;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// Parenthesised spans inside [from, to): nested calls and groupings. Their
|
|
387
|
+
// literals belong to another function (`Helpers::selector($c, '', 'is-on')`),
|
|
388
|
+
// not to the helper being scanned.
|
|
389
|
+
function nestedParenRanges(content, from, to) {
|
|
390
|
+
const ranges = [];
|
|
391
|
+
let quote = null;
|
|
392
|
+
|
|
393
|
+
for (let i = from; i < to; i++) {
|
|
394
|
+
const char = content[i];
|
|
395
|
+
|
|
396
|
+
if (quote) {
|
|
397
|
+
if (char === '\\') {
|
|
398
|
+
i++;
|
|
399
|
+
} else if (char === quote) {
|
|
400
|
+
quote = null;
|
|
401
|
+
}
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const skipTo = commentEnd(content, i);
|
|
406
|
+
|
|
407
|
+
if (skipTo !== -1) {
|
|
408
|
+
i = skipTo;
|
|
409
|
+
} else if (char === '"' || char === "'") {
|
|
410
|
+
quote = char;
|
|
411
|
+
} else if (char === '(') {
|
|
412
|
+
const close = findClose(content, i);
|
|
413
|
+
|
|
414
|
+
ranges.push([i, close]);
|
|
415
|
+
i = close;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
return ranges;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// helper name → number of leading arguments that are not classes.
|
|
423
|
+
const PHP_HELPERS = {
|
|
424
|
+
tailwindClasses: 1, // (part, attributes, manifest, ...custom)
|
|
425
|
+
getTwPart: 1, // (part, manifest, ...custom)
|
|
426
|
+
getTwClasses: 0, // (attributes, manifest, ...custom)
|
|
427
|
+
clsx: 0, // ([classes or 'class' => condition])
|
|
428
|
+
classnames: 0,
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
// Static class attributes outside comments. Values containing PHP or format
|
|
432
|
+
// placeholders are built at runtime and skipped.
|
|
433
|
+
function extractClassAttributes(content, groups, comments) {
|
|
434
|
+
for (const m of content.matchAll(/\bclass\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) {
|
|
435
|
+
if (inRanges(comments, m.index)) {
|
|
436
|
+
continue;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
const value = m[1] ?? m[2];
|
|
440
|
+
|
|
441
|
+
if (/<\?|\$|%|\{/.test(value)) {
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
pushGroup(groups, 'class-attr', value, m.index + m[0].length - value.length - 1);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function extractPhp(content, groups) {
|
|
450
|
+
const comments = phpCommentRanges(content);
|
|
451
|
+
// Only the Eightshift helpers: `Helpers::name(` or an unqualified `name(`.
|
|
452
|
+
// Same-named methods on other classes (`FormsHelper::getTwPart`) differ.
|
|
453
|
+
const helperRe = new RegExp(`(?:\\bHelpers::|(?<![\\w$>:]))(${Object.keys(PHP_HELPERS).join('|')})\\s*\\(`, 'g');
|
|
454
|
+
|
|
455
|
+
for (const m of content.matchAll(helperRe)) {
|
|
456
|
+
if (inRanges(comments, m.index)) {
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
const open = m.index + m[0].length - 1;
|
|
461
|
+
const close = findClose(content, open);
|
|
462
|
+
const args = callArgs(content, open, close).slice(PHP_HELPERS[m[1]]);
|
|
463
|
+
// clsx keys are classes (`'is-open' => $open`); elsewhere keys are not.
|
|
464
|
+
const skipKeys = m[1] !== 'clsx' && m[1] !== 'classnames';
|
|
465
|
+
|
|
466
|
+
for (const arg of args) {
|
|
467
|
+
const nested = nestedParenRanges(content, arg.start, arg.end);
|
|
468
|
+
|
|
469
|
+
for (const literal of phpStrings(content, arg.start, arg.end, { skipKeys })) {
|
|
470
|
+
if (nested.some(([open, close]) => literal.start > open && literal.start < close)) {
|
|
471
|
+
continue;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
pushEscapedGroup(groups, 'php-call', literal.value, literal.start, literal.syntax);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
extractClassAttributes(content, groups, comments);
|
|
480
|
+
|
|
481
|
+
// Opt-in regions: every string literal that is not an array key is a class
|
|
482
|
+
// source. For class maps no helper call wraps, e.g. Eightshift Forms
|
|
483
|
+
// selectors returned from a filter.
|
|
484
|
+
for (let from = content.indexOf(REGION_START); from !== -1;) {
|
|
485
|
+
const endMarker = content.indexOf(REGION_END, from);
|
|
486
|
+
const end = endMarker === -1 ? content.length : endMarker;
|
|
487
|
+
const bodyStart = Math.min(content.indexOf('\n', from) + 1 || end, end);
|
|
488
|
+
|
|
489
|
+
for (const literal of phpStrings(content, bodyStart, end, { skipKeys: true })) {
|
|
490
|
+
pushEscapedGroup(groups, 'php-region', literal.value, literal.start, literal.syntax);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
from = content.indexOf(REGION_START, end);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// ---- JS (files passed explicitly, e.g. by lint-staged) --------------------
|
|
498
|
+
|
|
499
|
+
function extractJs(content, groups) {
|
|
500
|
+
for (const m of content.matchAll(/\b\w*[cC]lassName\s*[:=]\s*(["'])((?:(?!\1)[^\\]|\\.)*)\1/g)) {
|
|
501
|
+
pushEscapedGroup(groups, 'js-attr', m[2], m.index + m[0].length - m[2].length - 1, jsString(m[1]));
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// A literal can match more than one source, e.g. a helper call inside a marked
|
|
506
|
+
// region. The first source to claim a character range keeps it, so each class
|
|
507
|
+
// is reported once and `--write` edits it once.
|
|
508
|
+
function dropOverlappingTokens(groups, contentLength) {
|
|
509
|
+
const claimed = new Uint8Array(contentLength);
|
|
510
|
+
const kept = [];
|
|
511
|
+
|
|
512
|
+
for (const group of groups) {
|
|
513
|
+
const tokens = group.tokens.filter(({ start, end }) => {
|
|
514
|
+
if (claimed.subarray(start, end).includes(1)) {
|
|
515
|
+
return false;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
claimed.fill(1, start, end);
|
|
519
|
+
|
|
520
|
+
return true;
|
|
521
|
+
});
|
|
522
|
+
|
|
523
|
+
if (tokens.length) {
|
|
524
|
+
kept.push({ ...group, tokens });
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
return kept;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
export function extractGroups(content, file) {
|
|
532
|
+
const groups = [];
|
|
533
|
+
|
|
534
|
+
if (file.endsWith('.json')) {
|
|
535
|
+
extractManifest(content, groups);
|
|
536
|
+
} else if (file.endsWith('.php')) {
|
|
537
|
+
extractPhp(content, groups);
|
|
538
|
+
} else if (file.endsWith('.html')) {
|
|
539
|
+
extractClassAttributes(content, groups, htmlCommentRanges(content));
|
|
540
|
+
} else if (/\.(m?js|jsx|tsx?)$/.test(file)) {
|
|
541
|
+
extractJs(content, groups);
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
return dropOverlappingTokens(groups, content.length);
|
|
545
|
+
}
|