mainPackageStyles.test.mjs
9.53 KB
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
import assert from 'node:assert/strict'
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
import { formatResponsiveFontSize } from '../../utils/responsiveFontSize.js'
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
const STYLE_REFERENCE_EXTENSIONS = new Set([
'.css',
'.js',
'.json',
'.sass',
'.scss',
'.wxml',
'.wxs',
'.wxss'
])
const SCAN_ROOTS = [
'app.sass',
'components',
'integration',
'packageCrowdFunding',
'packageDynamicForm',
'packageEquity',
'packageEquityAI',
'packageStudyCenter',
'packageUsedCar',
'pages',
'styles',
'subvehicleConversion',
'tabDate',
'tabIndex',
'tabMine',
'tabOperating',
'tabRepairOrder',
'tabWorkOrder'
]
/**
* Recursively lists runtime source files in deterministic order.
* Test, documentation, generated-authority and dependency folders are excluded
* because they are not compiled as mini-program runtime consumers.
* @param {string} entryPath Absolute file or directory path.
* @returns {string[]} Absolute runtime source paths.
*/
function listRuntimeSourceFiles(entryPath) {
if (!existsSync(entryPath)) return []
const stats = statSync(entryPath)
if (stats.isFile()) return STYLE_REFERENCE_EXTENSIONS.has(path.extname(entryPath))
? [entryPath]
: []
return readdirSync(entryPath, { withFileTypes: true })
.filter(entry => !['docs', 'test', 'tests'].includes(entry.name))
.sort((left, right) => left.name.localeCompare(right.name))
.flatMap(entry => listRuntimeSourceFiles(path.join(entryPath, entry.name)))
}
/**
* Removes source comments so dormant examples do not force runtime variables.
* @param {string} source Runtime source text.
* @returns {string} Comment-free source used by the dependency assertion.
*/
function stripComments(source) {
return source
.replace(/<!--[\s\S]*?-->/g, '')
.replace(/\/\*[\s\S]*?\*\//g, '')
.replace(/^\s*\/\/.*$/gm, '')
}
/**
* Reads a parenthesized numeric Sass list.
* @param {string} source app.sass source.
* @param {string} variableName Sass variable name without the dollar sign.
* @returns {number[]} Sorted numeric values.
*/
function readSassNumberList(source, variableName) {
const match = new RegExp(`\\$${variableName}:\\s*\\(([\\s\\S]*?)\\);`).exec(source)
assert.ok(match, `$${variableName} must be a parenthesized Sass list`)
return [...match[1].matchAll(/\d+(?:\.\d+)?/g)]
.map(item => Number(item[0]))
.sort((left, right) => left - right)
}
/**
* Resolves every WXSS import declared by a stylesheet.
* @param {string} relativePath Project-relative stylesheet path.
* @returns {string[]} Absolute imported stylesheet paths.
*/
function resolveStyleImports(relativePath) {
const sourcePath = path.join(projectRoot, relativePath)
const source = readFileSync(sourcePath, 'utf8')
return [...source.matchAll(/@import\s+['"]([^'"]+)['"]\s*;/g)]
.map(match => path.resolve(path.dirname(sourcePath), match[1]))
}
/**
* Asserts that a group of stylesheets delegates duplicated rules to one file.
* @param {string[]} consumerPaths Project-relative consumer paths.
* @param {string} sharedPath Project-relative shared stylesheet path.
* @param {string[]} movedSelectors Selectors that must live only in the shared file.
* @returns {void}
*/
function assertSharedStyle(consumerPaths, sharedPath, movedSelectors) {
const absoluteSharedPath = path.join(projectRoot, sharedPath)
assert.ok(existsSync(absoluteSharedPath), `${sharedPath} must exist`)
const sharedSource = stripComments(readFileSync(absoluteSharedPath, 'utf8'))
for (const relativePath of consumerPaths) {
const imports = resolveStyleImports(relativePath)
assert.ok(
imports.includes(absoluteSharedPath),
`${relativePath} must import ${sharedPath}`
)
const consumerSource = stripComments(readFileSync(path.join(projectRoot, relativePath), 'utf8'))
for (const selector of movedSelectors) {
const selectorPattern = new RegExp(`${selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*\\{`)
assert.match(sharedSource, selectorPattern, `${selector} must be declared by ${sharedPath}`)
assert.doesNotMatch(
consumerSource,
selectorPattern,
`${selector} must not be duplicated in ${relativePath}`
)
}
}
}
/**
* Asserts that selectors with identical declarations use one grouped rule.
* @param {string} relativePath Project-relative stylesheet path.
* @param {string[][]} selectorGroups Ordered selector groups.
* @returns {void}
*/
function assertGroupedSelectors(relativePath, selectorGroups) {
const source = stripComments(readFileSync(path.join(projectRoot, relativePath), 'utf8'))
for (const selectors of selectorGroups) {
const escapedSelectors = selectors.map(selector =>
selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
const groupedRulePattern = new RegExp(`${escapedSelectors.join('\\s*,\\s*')}\\s*\\{`)
assert.match(
source,
groupedRulePattern,
`${relativePath} must group ${selectors.join(', ')}`
)
}
}
/**
* Collects numeric custom-property references from runtime source.
* @returns {{ base: number[], content: number[], dynamicPaths: string[] }} References.
*/
function collectFontSizeReferences() {
const base = new Set()
const content = new Set()
const dynamicPaths = []
for (const file of SCAN_ROOTS.flatMap(root =>
listRuntimeSourceFiles(path.join(projectRoot, root)))) {
const source = stripComments(readFileSync(file, 'utf8'))
for (const match of source.matchAll(/var\(--fontSize(Content)?(\d+)\)/g)) {
;(match[1] ? content : base).add(Number(match[2]))
}
if (source.includes('--fontSize${')) {
dynamicPaths.push(path.relative(projectRoot, file).replaceAll('\\', '/'))
}
}
return {
base: [...base].sort((left, right) => left - right),
content: [...content].sort((left, right) => left - right),
dynamicPaths
}
}
test('responsive font-size formatter preserves phone and large-screen scaling', () => {
assert.equal(formatResponsiveFontSize(28, 767), 'calc(28vmin / 7.5)')
assert.equal(formatResponsiveFontSize(28, 768), 'calc(28vmin / 8.5)')
assert.equal(formatResponsiveFontSize(1114, 375), 'calc(1114vmin / 7.5)')
assert.throws(() => formatResponsiveFontSize(Number.NaN, 375), /finite number/)
assert.throws(() => formatResponsiveFontSize(28, Number.POSITIVE_INFINITY), /finite number/)
})
test('app Sass emits exactly the statically referenced font-size variables', () => {
const appSass = readFileSync(path.join(projectRoot, 'app.sass'), 'utf8')
const references = collectFontSizeReferences()
const declaredBase = readSassNumberList(appSass, 'font-size-values')
const declaredContent = readSassNumberList(appSass, 'font-size-content-values')
assert.deepEqual(declaredBase, references.base)
assert.deepEqual(declaredContent, references.content)
assert.deepEqual(
references.dynamicPaths,
[],
`runtime CSS variable names must not be assembled dynamically:\n${references.dynamicPaths.join('\n')}`
)
assert.ok(declaredBase.length < 400, 'font-size declarations must stay usage-driven')
assert.ok(declaredContent.length < 50, 'content font-size declarations must stay usage-driven')
})
test('main-package page clones share scoped WXSS rules', () => {
assertSharedStyle(
[
'pages/tabWorkOrder/pages/index/index.sass',
'pages/tabDateIndex/pages/tabDateIndex.sass'
],
'styles/main-list-common.wxss',
['page', '.to-box', '.search-box', '.search-box .search-input', '.input-placeholder']
)
assertSharedStyle(
['pages/sceneIndex/sceneIndex.wxss', 'pages/changeScene/changeScene.wxss'],
'styles/scene-selection-common.wxss',
['page', '.user-box', '.scene-item .left', '.change-btn', '.logout']
)
})
test('main-package component clones share scoped WXSS rules', () => {
assertSharedStyle(
[
'pages/tabWorkOrder/components/OrderScreen/OrderScreen.wxss',
'pages/tabDateIndex/components/DateScreen/DateScreen.wxss'
],
'styles/screen-panel-common.wxss',
['.confirm-box', '.box .title', '.box .list-box .item', '.btn-box', '.text-hide']
)
assertSharedStyle(
['components/DatePicker/DatePicker.wxss', 'components/RemarkPopup/RemarkPopup.wxss'],
'styles/fixed-picker-common.wxss',
['.fixed-box', '.fixed-content', '.fixed-content .fixed-footer', '.text-center']
)
assertSharedStyle(
['pages/components/authSetting/authSetting.wxss', 'pages/components/authNoLogin/authNoLogin.wxss'],
'styles/auth-tips-common.wxss',
['.tips .icon', '.tips .icon .check-img', '.tips .choose-box']
)
})
test('identical declarations in main-package styles use grouped selectors', () => {
assertGroupedSelectors('components/navigationBar/navigationBar.wxss', [
['.back-box', '.menu-box']
])
assertGroupedSelectors('pages/tabDateIndex/pages/tabDateIndex.sass', [
['.date-icon', '.phone-icon']
])
assertGroupedSelectors('pages/accountItems/accountItems.wxss', [
['.items .right .midle_4', '.items .right .midle_5']
])
assertGroupedSelectors('pages/merchantList/merchantList.wxss', [
[
'.custom_items .text_box .status_text_0',
'.custom_items .text_box .status_text_3'
]
])
assertGroupedSelectors('components/SideSelectPopup/SideSelectPopup.wxss', [
[
'.search-box .select_box .option_box::after',
'.search-box .select_box .option_box::before'
],
[
'.wrapper .custom_element .text_box .status_text_0',
'.wrapper .custom_element .text_box .status_text_3'
]
])
})