@wkgeo/cli 1.1.0 → 1.1.2
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/CHANGELOG.md +45 -0
- package/README.md +163 -25
- package/SKILL.md +121 -36
- package/lib/args.mjs +2 -2
- package/lib/asset-role.mjs +68 -0
- package/lib/cms.mjs +2 -2
- package/lib/commands/billing.mjs +56 -10
- package/lib/commands/cms.mjs +49 -13
- package/lib/commands/content.mjs +108 -0
- package/lib/commands/crawl.mjs +219 -0
- package/lib/commands/geo.mjs +1673 -0
- package/lib/commands/index.mjs +640 -541
- package/lib/commands/member.mjs +930 -0
- package/lib/commands/seo.mjs +1386 -0
- package/lib/commands/siteops.mjs +3 -3
- package/lib/commands/sites.mjs +21 -125
- package/lib/commands/template.mjs +1222 -6
- package/lib/config.mjs +16 -13
- package/lib/content-apply.mjs +664 -0
- package/lib/content-check.mjs +887 -0
- package/lib/content-contract.mjs +957 -0
- package/lib/errors.mjs +6 -0
- package/lib/format.mjs +5 -1
- package/lib/login.mjs +15 -3
- package/lib/manifest-apply.mjs +1499 -0
- package/lib/manifest-schema.json +476 -0
- package/lib/manifest.mjs +1082 -0
- package/lib/oauth-urls.mjs +1 -1
- package/lib/runtime.mjs +5 -1
- package/lib/site-create.mjs +536 -0
- package/lib/template-anim.mjs +1338 -0
- package/lib/template-animation.mjs +232 -0
- package/lib/template-capture.mjs +700 -0
- package/lib/template-gen.mjs +1204 -0
- package/lib/template-pack.mjs +206 -0
- package/lib/template-publish.mjs +733 -0
- package/lib/template-score.mjs +865 -0
- package/lib/template-validate.mjs +368 -0
- package/lib/template-verify.mjs +434 -0
- package/lib/templates-sync.mjs +616 -0
- package/package.json +2 -2
|
@@ -0,0 +1,1338 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 动画提取 / `_base` 映射 / verify 对账(task-46)。
|
|
3
|
+
*
|
|
4
|
+
* ## 这一层干什么
|
|
5
|
+
* 1. **抽**:从模板包(也就是原站镜像)的 `pages/*.html`(含内联 `<style>`/`<script>`/属性)、
|
|
6
|
+
* `assets/` 下的 `.css` 与 `.js` 里抽四类东西:
|
|
7
|
+
* `@keyframes` 名与帧;`animation` / `transition` 声明与长写;滚动入场
|
|
8
|
+
* (`data-reveal` / IntersectionObserver / class 切换);`transform` 的位移/缩放/旋转与延迟时长。
|
|
9
|
+
* 2. **映射**:每条动画尽量落到 `templates/_base` **已有**的类名/属性/变量上
|
|
10
|
+
* (`[data-reveal]` + `data-delay` / `.anim-float` / `.anim-pulse` / `.anim-gradient` /
|
|
11
|
+
* `.anim-shine` / `[data-kenburns]` / `.marquee` / `[data-parallax]`),**不新造体系**;
|
|
12
|
+
* 落不下去的标 `unmapped` 并写清原因。
|
|
13
|
+
* 3. **对账**:`verify` 把清单(期望)与 `-t0` vs `-t1500` 两帧的像素差区域(实测)比对,
|
|
14
|
+
* 给出命中 / 缺失 / 多余;缺失与多余都影响退出码。
|
|
15
|
+
*
|
|
16
|
+
* ## 为什么清单要单独一个文件
|
|
17
|
+
* `templates/_base` 本轮**只读**,`template.json` 的 v2 字段表也不能随便加键,
|
|
18
|
+
* 所以清单落在 `design/animations.json`(随模板包一起分发),几何证据落在
|
|
19
|
+
* `design/animations.geom.json`(Chrome 实测的元素矩形,用来把像素区域归因到具体动画)。
|
|
20
|
+
*
|
|
21
|
+
* ## 口径(写死,别处别再改一套)
|
|
22
|
+
* * 首屏窗口 = load 后 **120ms ~ 1500ms**(与 `-t0/-t1500` 两帧同口径);
|
|
23
|
+
* * 只有 **load 触发** 的动画才算「期望在首屏窗口内动」;滚动/hover 是交互触发,
|
|
24
|
+
* 首屏可能看不到(`mayFireAtLoad` 只作信息,不算缺失);
|
|
25
|
+
* * 一个动画可能点亮多个像素区域(聚类会拆开),所以**不做数量相等**:
|
|
26
|
+
* 期望动画只要有一个像素区域与它的元素矩形相交就算命中。
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import fs from 'node:fs';
|
|
30
|
+
import fsp from 'node:fs/promises';
|
|
31
|
+
import path from 'node:path';
|
|
32
|
+
|
|
33
|
+
export const ANIM_FORMAT = 'wkgeo-anim@1';
|
|
34
|
+
export const ANIM_GEOM_FORMAT = 'wkgeo-anim-geom@1';
|
|
35
|
+
export const ANIM_MANIFEST_FILE = 'animations.json';
|
|
36
|
+
export const ANIM_GEOM_FILE = 'animations.geom.json';
|
|
37
|
+
/** 首屏动画窗口(ms,相对 load):与 design/<视口>-t0.png / -t1500.png 完全一致 */
|
|
38
|
+
export const FRAME_WINDOW_MS = [120, 1500];
|
|
39
|
+
|
|
40
|
+
const STATE_CLASS_RE = /^(is-visible|is-shown|is-inview|is-in-view|is-active|is-open|is-loaded|visible|show|shown|in-view|revealed|active|loaded|in|on)$/i;
|
|
41
|
+
|
|
42
|
+
// ---------------------------------------------------------------- CSS 词法
|
|
43
|
+
|
|
44
|
+
export function stripComments(css) {
|
|
45
|
+
return String(css || '').replace(/\/\*[\s\S]*?\*\//g, '');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 从 `open`(指向 `{`)找配对的 `}`;跳过字符串 */
|
|
49
|
+
function findBlockEnd(src, open) {
|
|
50
|
+
let depth = 0;
|
|
51
|
+
for (let i = open; i < src.length; i++) {
|
|
52
|
+
const ch = src[i];
|
|
53
|
+
if (ch === '"' || ch === "'") {
|
|
54
|
+
const q = ch;
|
|
55
|
+
i++;
|
|
56
|
+
while (i < src.length && src[i] !== q) {
|
|
57
|
+
if (src[i] === '\\') i++;
|
|
58
|
+
i++;
|
|
59
|
+
}
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (ch === '{') depth++;
|
|
63
|
+
else if (ch === '}') {
|
|
64
|
+
depth--;
|
|
65
|
+
if (depth === 0) return i;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return -1;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 按顶层分隔符切(逗号/空白),尊重 `()` 与引号 */
|
|
72
|
+
export function splitTopLevel(value, sep = ',') {
|
|
73
|
+
const out = [];
|
|
74
|
+
let depth = 0;
|
|
75
|
+
let quote = null;
|
|
76
|
+
let cur = '';
|
|
77
|
+
for (const ch of String(value || '')) {
|
|
78
|
+
if (quote) {
|
|
79
|
+
cur += ch;
|
|
80
|
+
if (ch === quote) quote = null;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (ch === '"' || ch === "'") {
|
|
84
|
+
quote = ch;
|
|
85
|
+
cur += ch;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (ch === '(') depth++;
|
|
89
|
+
if (ch === ')') depth = Math.max(0, depth - 1);
|
|
90
|
+
if (!depth && (sep === ' ' ? /\s/.test(ch) : ch === sep)) {
|
|
91
|
+
if (cur.trim()) out.push(cur.trim());
|
|
92
|
+
cur = '';
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
cur += ch;
|
|
96
|
+
}
|
|
97
|
+
if (cur.trim()) out.push(cur.trim());
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function splitTokens(value) {
|
|
102
|
+
return splitTopLevel(value, ' ');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** `600ms` / `0.62s` / `.3s` → ms;不是时间返回 null */
|
|
106
|
+
export function parseDurationMs(v) {
|
|
107
|
+
const m = String(v || '')
|
|
108
|
+
.trim()
|
|
109
|
+
.toLowerCase()
|
|
110
|
+
.match(/^(-?[\d.]+)(ms|s)$/);
|
|
111
|
+
if (!m) return null;
|
|
112
|
+
const n = Number(m[1]);
|
|
113
|
+
if (!Number.isFinite(n)) return null;
|
|
114
|
+
return Math.round(m[2] === 's' ? n * 1000 : n);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function isEasing(tok) {
|
|
118
|
+
return /^(linear|ease|ease-in|ease-out|ease-in-out|step-start|step-end|steps|cubic-bezier|linear\(|spring|cubic-bezier\()/i.test(tok);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function parseDeclarations(body) {
|
|
122
|
+
const decls = {};
|
|
123
|
+
for (const part of splitTopLevel(body, ';')) {
|
|
124
|
+
const at = part.indexOf(':');
|
|
125
|
+
if (at < 0) continue;
|
|
126
|
+
const prop = part.slice(0, at).trim().toLowerCase();
|
|
127
|
+
const value = part.slice(at + 1).trim();
|
|
128
|
+
if (prop) decls[prop] = value;
|
|
129
|
+
}
|
|
130
|
+
return decls;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function lineAt(text, index) {
|
|
134
|
+
return String(text).slice(0, Math.max(0, index)).split('\n').length;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function parseAnimationLayers(value) {
|
|
138
|
+
return splitTopLevel(value, ',')
|
|
139
|
+
.filter(Boolean)
|
|
140
|
+
.map((layer) => {
|
|
141
|
+
const l = { name: null, durationMs: 0, delayMs: 0, iteration: '1', easing: 'ease', direction: 'normal', fill: 'none', playState: 'running' };
|
|
142
|
+
let times = 0;
|
|
143
|
+
for (const tok of splitTokens(layer)) {
|
|
144
|
+
const low = tok.toLowerCase();
|
|
145
|
+
const ms = parseDurationMs(low);
|
|
146
|
+
if (ms !== null) {
|
|
147
|
+
if (times === 0) l.durationMs = ms;
|
|
148
|
+
else l.delayMs = ms;
|
|
149
|
+
times++;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (low === 'infinite') {
|
|
153
|
+
l.iteration = 'infinite';
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if (/^[\d.]+$/.test(low)) {
|
|
157
|
+
l.iteration = low;
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (isEasing(low)) {
|
|
161
|
+
l.easing = low;
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
if (/^(normal|reverse|alternate|alternate-reverse)$/.test(low)) {
|
|
165
|
+
l.direction = low;
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
if (/^(forwards|backwards|both)$/.test(low)) {
|
|
169
|
+
l.fill = low;
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (/^(running|paused)$/.test(low)) {
|
|
173
|
+
l.playState = low;
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
if (!l.name && low !== 'none') l.name = tok;
|
|
177
|
+
}
|
|
178
|
+
return l;
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function parseTransitionLayers(value) {
|
|
183
|
+
return splitTopLevel(value, ',')
|
|
184
|
+
.filter(Boolean)
|
|
185
|
+
.map((layer) => {
|
|
186
|
+
const l = { property: 'all', durationMs: 0, delayMs: 0, easing: 'ease' };
|
|
187
|
+
let times = 0;
|
|
188
|
+
for (const tok of splitTokens(layer)) {
|
|
189
|
+
const low = tok.toLowerCase();
|
|
190
|
+
const ms = parseDurationMs(low);
|
|
191
|
+
if (ms !== null) {
|
|
192
|
+
if (times === 0) l.durationMs = ms;
|
|
193
|
+
else l.delayMs = ms;
|
|
194
|
+
times++;
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
if (isEasing(low)) {
|
|
198
|
+
l.easing = low;
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
l.property = low;
|
|
202
|
+
}
|
|
203
|
+
return l;
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const KEYFRAMES_AT = new Set(['@keyframes', '@-webkit-keyframes']);
|
|
208
|
+
const NESTED_AT = /^@(media|supports|layer|container|scope|document)\b/i;
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* 把一段 CSS 拆成 `{keyframes, rules}`。
|
|
212
|
+
* * `@keyframes` → 名字 + 帧(`0%` / `from` / `to` 与其声明);
|
|
213
|
+
* * 普通规则 → `{selector, media, decls, line}`(`@media` 里的规则会带上 media 前缀,照样收)。
|
|
214
|
+
*/
|
|
215
|
+
export function parseCss(cssText, { file = null } = {}) {
|
|
216
|
+
const css = stripComments(cssText);
|
|
217
|
+
const keyframes = [];
|
|
218
|
+
const rules = [];
|
|
219
|
+
const warnings = [];
|
|
220
|
+
|
|
221
|
+
const visit = (text, media, baseOffset) => {
|
|
222
|
+
let i = 0;
|
|
223
|
+
while (i < text.length) {
|
|
224
|
+
const open = text.indexOf('{', i);
|
|
225
|
+
if (open < 0) break;
|
|
226
|
+
const prelude = text.slice(i, open).trim();
|
|
227
|
+
const close = findBlockEnd(text, open);
|
|
228
|
+
if (close < 0) {
|
|
229
|
+
warnings.push(`CSS 大括号不配对(${file || '内联'} 第 ${lineAt(text, i)} 行附近)`);
|
|
230
|
+
break;
|
|
231
|
+
}
|
|
232
|
+
const body = text.slice(open + 1, close);
|
|
233
|
+
const line = lineAt(text, baseOffset + i);
|
|
234
|
+
if (prelude.startsWith('@')) {
|
|
235
|
+
const at = (prelude.match(/^@[a-z-]+/i) || [''])[0].toLowerCase();
|
|
236
|
+
if (KEYFRAMES_AT.has(at)) {
|
|
237
|
+
const name = prelude.slice(at.length).trim().split(/\s+/)[0];
|
|
238
|
+
const frames = [];
|
|
239
|
+
let j = 0;
|
|
240
|
+
while (j < body.length) {
|
|
241
|
+
const fo = body.indexOf('{', j);
|
|
242
|
+
if (fo < 0) break;
|
|
243
|
+
const sel = body.slice(j, fo).trim();
|
|
244
|
+
const fc = findBlockEnd(body, fo);
|
|
245
|
+
if (fc < 0) break;
|
|
246
|
+
frames.push({
|
|
247
|
+
at: sel.replace(/\s+/g, ' '),
|
|
248
|
+
decls: parseDeclarations(body.slice(fo + 1, fc)),
|
|
249
|
+
});
|
|
250
|
+
j = fc + 1;
|
|
251
|
+
}
|
|
252
|
+
keyframes.push({ name, frames, line, file, media: media.join(' ') });
|
|
253
|
+
} else if (NESTED_AT.test(prelude)) {
|
|
254
|
+
visit(body, [...media, prelude.replace(/\s+/g, ' ')], baseOffset + open + 1);
|
|
255
|
+
}
|
|
256
|
+
// 其它 at 规则(@font-face / @import / @page…)与动画无关,跳过
|
|
257
|
+
} else {
|
|
258
|
+
rules.push({
|
|
259
|
+
selector: prelude.replace(/\s+/g, ' ').trim(),
|
|
260
|
+
media: media.join(' '),
|
|
261
|
+
decls: parseDeclarations(body),
|
|
262
|
+
line,
|
|
263
|
+
file,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
i = close + 1;
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
visit(css, [], 0);
|
|
271
|
+
return { keyframes, rules, warnings };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ---------------------------------------------------------------- transform / motion
|
|
275
|
+
|
|
276
|
+
function num(v) {
|
|
277
|
+
const m = String(v || '').match(/-?[\d.]+/);
|
|
278
|
+
return m ? Number(m[0]) : null;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export function parseTranslate(value) {
|
|
282
|
+
const s = String(value || '');
|
|
283
|
+
const fn = s.match(/(translate3d|translateX|translateY|translate)\(([^)]*)\)/i);
|
|
284
|
+
if (!fn) return null;
|
|
285
|
+
const args = splitTopLevel(fn[2], ',').map((a) => a.trim());
|
|
286
|
+
if (/translate3d/i.test(fn[1])) return { x: num(args[0]), y: num(args[1]) };
|
|
287
|
+
if (/translateX/i.test(fn[1])) return { x: num(args[0]), y: 0 };
|
|
288
|
+
if (/translateY/i.test(fn[1])) return { x: 0, y: num(args[0]) };
|
|
289
|
+
return { x: num(args[0]), y: args.length > 1 ? num(args[1]) : 0 };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export function parseScale(value) {
|
|
293
|
+
const m = String(value || '').match(/scale(?:3d|X|Y)?\(([^)]*)\)/i);
|
|
294
|
+
if (!m) return null;
|
|
295
|
+
const args = splitTopLevel(m[1], ',').map((a) => num(a));
|
|
296
|
+
const vals = args.filter((v) => v !== null);
|
|
297
|
+
return vals.length ? Math.min(...vals) : null;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export function parseRotate(value) {
|
|
301
|
+
const m = String(value || '').match(/rotate(?:3d|X|Y|Z)?\(([^)]*)\)/i);
|
|
302
|
+
if (!m) return null;
|
|
303
|
+
const deg = String(m[1]).match(/(-?[\d.]+)deg/);
|
|
304
|
+
if (deg) return Math.abs(Number(deg[1]));
|
|
305
|
+
const rad = String(m[1]).match(/(-?[\d.]+)rad/);
|
|
306
|
+
if (rad) return Math.abs((Number(rad[1]) * 180) / Math.PI);
|
|
307
|
+
const turns = String(m[1]).match(/(-?[\d.]+)turn/);
|
|
308
|
+
if (turns) return Math.abs(Number(turns[1]) * 360);
|
|
309
|
+
return null;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** 从 keyframes 汇总「到底动了什么」——用来判断等价动效,也用来判断有没有位移 */
|
|
313
|
+
export function motionOfFrames(frames = []) {
|
|
314
|
+
const out = { properties: [], translate: [], scale: [], rotate: [], opacity: [], backgroundPosition: [], filter: [], transform: [] };
|
|
315
|
+
const props = new Set();
|
|
316
|
+
for (const f of frames) {
|
|
317
|
+
for (const [prop, value] of Object.entries(f.decls || {})) {
|
|
318
|
+
props.add(prop);
|
|
319
|
+
if (prop === 'transform') {
|
|
320
|
+
out.transform.push(value);
|
|
321
|
+
const t = parseTranslate(value);
|
|
322
|
+
if (t && (t.x || t.y)) out.translate.push(t);
|
|
323
|
+
const s = parseScale(value);
|
|
324
|
+
if (s !== null) out.scale.push(s);
|
|
325
|
+
const r = parseRotate(value);
|
|
326
|
+
if (r !== null) out.rotate.push(r);
|
|
327
|
+
} else if (prop === 'opacity') {
|
|
328
|
+
const n = num(value);
|
|
329
|
+
if (n !== null) out.opacity.push(n);
|
|
330
|
+
} else if (prop === 'background-position' || prop === 'background') {
|
|
331
|
+
out.backgroundPosition.push(value);
|
|
332
|
+
} else if (prop === 'filter') {
|
|
333
|
+
out.filter.push(value);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
out.properties = [...props].sort();
|
|
338
|
+
return out;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// ---------------------------------------------------------------- 映射到 _base
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* `templates/_base` 已有的动效(只读,不新造):
|
|
345
|
+
* `.anim-float` / `.anim-pulse` / `.anim-gradient` / `.anim-shine` / `[data-kenburns]` /
|
|
346
|
+
* `.marquee` + `.marquee__track` / `[data-reveal]` + `data-delay` / `[data-parallax]`。
|
|
347
|
+
*/
|
|
348
|
+
export const BASE_MAP = {
|
|
349
|
+
float: { klass: 'anim-float', keyframes: 'float', timing: { durationMs: 6000, easing: 'ease-in-out', iteration: 'infinite' } },
|
|
350
|
+
pulse: { klass: 'anim-pulse', keyframes: 'pulse', timing: { durationMs: 2400, easing: 'ease-in-out', iteration: 'infinite' } },
|
|
351
|
+
gradient: {
|
|
352
|
+
klass: 'anim-gradient',
|
|
353
|
+
keyframes: 'gradient-shift',
|
|
354
|
+
timing: { durationMs: 9000, easing: 'ease', iteration: 'infinite' },
|
|
355
|
+
css: 'background-size: 220% 220%',
|
|
356
|
+
},
|
|
357
|
+
shine: { klass: 'anim-shine', keyframes: 'shine', timing: { durationMs: 3200, easing: 'var(--wkg-ease)', iteration: 'infinite' } },
|
|
358
|
+
kenburns: { attrs: { 'data-kenburns': '' }, keyframes: 'kenburns', timing: { durationMs: 22000, iteration: 'infinite', direction: 'alternate' } },
|
|
359
|
+
marquee: {
|
|
360
|
+
klass: 'marquee',
|
|
361
|
+
keyframes: 'marquee',
|
|
362
|
+
timing: { durationMs: 30000, easing: 'linear', iteration: 'infinite' },
|
|
363
|
+
requiresMarkup: true,
|
|
364
|
+
vars: { '--marquee-dur': '30s' },
|
|
365
|
+
},
|
|
366
|
+
reveal: { attrs: { 'data-reveal': 'fade-up' }, vars: { '--reveal-dur': '620ms', '--reveal-offset': '28px' } },
|
|
367
|
+
parallax: { attrs: { 'data-parallax': '' } },
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
function fmtMs(ms) {
|
|
371
|
+
return ms % 1000 === 0 ? `${ms / 1000}s` : `${ms}ms`;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function delayBucket(ms) {
|
|
375
|
+
const buckets = [100, 150, 200, 250, 300, 400, 500, 600, 800];
|
|
376
|
+
if (!ms || ms <= 0) return null;
|
|
377
|
+
let best = buckets[0];
|
|
378
|
+
for (const b of buckets) if (Math.abs(b - ms) < Math.abs(best - ms)) best = b;
|
|
379
|
+
return best;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** 初始位移/缩放 → `_base` 的 `data-reveal` 变体 */
|
|
383
|
+
export function revealVariantOf({ translate = null, scale = null, opacity = null } = {}) {
|
|
384
|
+
const t = translate || { x: 0, y: 0 };
|
|
385
|
+
if (t.y && t.y > 0) return 'fade-up';
|
|
386
|
+
if (t.y && t.y < 0) return 'fade-down';
|
|
387
|
+
if (t.x && t.x > 0) return 'fade-right';
|
|
388
|
+
if (t.x && t.x < 0) return 'fade-left';
|
|
389
|
+
if (scale !== null && scale !== undefined && scale < 1) return 'zoom';
|
|
390
|
+
if (opacity !== null && opacity !== undefined && opacity < 1) return 'fade';
|
|
391
|
+
return 'fade-up';
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* 把一条抽出来的动画映射到 `_base`。
|
|
396
|
+
* @returns {{status:'exact'|'alias'|'unmapped'|'na', base?:object, deltas?:string[], reason?:string}}
|
|
397
|
+
*/
|
|
398
|
+
export function mapToBase(entry) {
|
|
399
|
+
const kind = entry.kind;
|
|
400
|
+
if (kind === 'hover') {
|
|
401
|
+
return {
|
|
402
|
+
status: 'na',
|
|
403
|
+
reason: 'hover/focus 交互过渡:不进首屏清单;`_base` 的 `.btn` / `.card` 自带同款 transition',
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
if (kind === 'reveal') {
|
|
407
|
+
const variant = entry.reveal.variant;
|
|
408
|
+
const dur = entry.timing.durationMs || 620;
|
|
409
|
+
const offset = Math.abs((entry.motion.translate[0] && entry.motion.translate[0].y) || (entry.motion.translate[0] && entry.motion.translate[0].x) || 28);
|
|
410
|
+
const deltas = [];
|
|
411
|
+
if (Math.abs(dur - 620) > 80) deltas.push(`时长 ${fmtMs(dur)} ≠ 基础库 --reveal-dur 620ms(用变量覆盖,不改类名)`);
|
|
412
|
+
if (offset > 0 && Math.abs(offset - 28) > 6) deltas.push(`位移 ${offset}px ≠ 基础库 --reveal-offset 28px(用变量覆盖)`);
|
|
413
|
+
const base = {
|
|
414
|
+
attrs: { 'data-reveal': variant },
|
|
415
|
+
vars: { '--reveal-dur': fmtMs(dur), '--reveal-offset': `${Math.round(offset)}px` },
|
|
416
|
+
};
|
|
417
|
+
const bucket = delayBucket(entry.timing.delayMs);
|
|
418
|
+
if (bucket) base.attrs['data-delay'] = String(bucket);
|
|
419
|
+
if (entry.entryFrom === 'js') base.js = '由 `_base/assets/base.js` 的 IntersectionObserver 加 `.is-visible`,不需要模板自带 JS';
|
|
420
|
+
return { status: deltas.length ? 'alias' : 'exact', base, deltas };
|
|
421
|
+
}
|
|
422
|
+
if (kind === 'parallax') {
|
|
423
|
+
return { status: 'exact', base: { attrs: { 'data-parallax': '' } } };
|
|
424
|
+
}
|
|
425
|
+
const target = BASE_MAP[kind];
|
|
426
|
+
if (!target) return { status: 'unmapped', reason: unmappedReason(entry) };
|
|
427
|
+
const deltas = [];
|
|
428
|
+
const kfName = (entry.keyframesName || '').toLowerCase();
|
|
429
|
+
const sameName = kfName === target.keyframes.toLowerCase();
|
|
430
|
+
const baseDur = target.timing.durationMs;
|
|
431
|
+
const dur = entry.timing.durationMs || 0;
|
|
432
|
+
const loop = entry.timing.iteration === 'infinite';
|
|
433
|
+
if (!sameName) deltas.push(`原站 keyframes 叫 \`${entry.keyframesName}\`,基础库叫 \`${target.keyframes}\`(复用基础库那份)`);
|
|
434
|
+
if (loop && Math.abs(dur - baseDur) > baseDur * 0.2) deltas.push(`时长 ${fmtMs(dur)} ≠ 基础库 ${fmtMs(baseDur)}`);
|
|
435
|
+
if (!loop && target.timing.iteration === 'infinite') deltas.push(`原站只播 ${entry.timing.iteration} 次,基础库是 infinite`);
|
|
436
|
+
if (kind === 'float') {
|
|
437
|
+
const amp = Math.abs((entry.motion.translate[0] && entry.motion.translate[0].y) || 0);
|
|
438
|
+
if (amp > 20) deltas.push(`位移 ${amp}px ≠ 基础库 float 的 10px(按需在模板 CSS 覆盖 keyframes)`);
|
|
439
|
+
if (amp > 40) return { status: 'alias', base: baseOf(target), deltas };
|
|
440
|
+
}
|
|
441
|
+
if (kind === 'marquee') {
|
|
442
|
+
deltas.push('需要 `.marquee > .marquee__track > .marquee__group` 三层结构,内容复制两份');
|
|
443
|
+
}
|
|
444
|
+
return { status: deltas.length ? 'alias' : 'exact', base: baseOf(target), deltas };
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function baseOf(target) {
|
|
448
|
+
const base = {};
|
|
449
|
+
if (target.klass) base.class = target.klass;
|
|
450
|
+
if (target.attrs) base.attrs = { ...target.attrs };
|
|
451
|
+
if (target.vars) base.vars = { ...target.vars };
|
|
452
|
+
if (target.keyframes) base.keyframes = target.keyframes;
|
|
453
|
+
if (target.css) base.css = target.css;
|
|
454
|
+
if (target.requiresMarkup) base.requiresMarkup = true;
|
|
455
|
+
return base;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function unmappedReason(entry) {
|
|
459
|
+
const k = entry.kind;
|
|
460
|
+
if (k === 'spin') return '基础库没有「旋转循环」动效(`@keyframes` 里只有 float/pulse/shine/gradient-shift/kenburns/marquee),需要模板自带 CSS';
|
|
461
|
+
if (k === 'fade') return '只有 opacity 变化的循环/闪烁:基础库 `.anim-pulse` 会额外缩放,不等价,需要模板自带 CSS';
|
|
462
|
+
if (k === 'zoom' || k === 'slide') return '一次性位移/缩放(非入场 reveal):基础库没有对应 keyframes,建议改成 `[data-reveal]` 或用 `--reveal-dur` 表达';
|
|
463
|
+
return `基础库没有与 \`${entry.keyframesName || entry.kind}\` 等价的动效(keyframes/时长/位移都对不上),保留模板自带 CSS`;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// ---------------------------------------------------------------- HTML / JS 证据
|
|
467
|
+
|
|
468
|
+
export function scanHtml(html) {
|
|
469
|
+
const ev = { reveal: [], parallax: 0, kenburns: 0, animClasses: [], animEls: [], inlineAnim: [] };
|
|
470
|
+
const s = String(html || '');
|
|
471
|
+
for (const m of s.matchAll(/<([a-z][a-z0-9-]*)\b((?:"[^"]*"|'[^']*'|[^>"'])*)>/gi)) {
|
|
472
|
+
const tag = m[1].toLowerCase();
|
|
473
|
+
const attrs = m[2] || '';
|
|
474
|
+
const attr = (name) => {
|
|
475
|
+
const mm = attrs.match(new RegExp(`\\s${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, 'i'));
|
|
476
|
+
return mm ? (mm[2] !== undefined ? mm[2] : mm[3]) : null;
|
|
477
|
+
};
|
|
478
|
+
const has = (name) => new RegExp(`\\s${name}(\\s|=|$)`, 'i').test(attrs);
|
|
479
|
+
const cls = attr('class') || '';
|
|
480
|
+
if (has('data-reveal')) {
|
|
481
|
+
ev.reveal.push({
|
|
482
|
+
tag,
|
|
483
|
+
variant: (attr('data-reveal') || '').trim() || null,
|
|
484
|
+
delay: (attr('data-delay') || '').trim() || null,
|
|
485
|
+
class: cls,
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
if (has('data-parallax')) ev.parallax++;
|
|
489
|
+
if (has('data-kenburns')) ev.kenburns++;
|
|
490
|
+
const anim = [];
|
|
491
|
+
for (const c of cls.split(/\s+/)) {
|
|
492
|
+
if (!c) continue;
|
|
493
|
+
if (/^(anim-|reveal|marquee|carousel|fade|float)/.test(c)) ev.animClasses.push(c);
|
|
494
|
+
if (/^(anim-(float|pulse|gradient|shine)|marquee)$/.test(c)) anim.push(c);
|
|
495
|
+
}
|
|
496
|
+
if (anim.length) ev.animEls.push({ tag, class: cls, anim });
|
|
497
|
+
const style = attr('style');
|
|
498
|
+
if (style && /animation|transition/.test(style)) ev.inlineAnim.push({ tag, class: cls, style });
|
|
499
|
+
}
|
|
500
|
+
return ev;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
export function scanJs(jsText) {
|
|
504
|
+
const s = String(jsText || '');
|
|
505
|
+
const classes = new Set();
|
|
506
|
+
for (const m of s.matchAll(/(?:classList\.(?:add|toggle|remove|replace)|classList\s*=\s*[^;]*?)\(?[^;'"\n]{0,40}?['"]([a-zA-Z][\w-]*)['"]/g)) classes.add(m[1]);
|
|
507
|
+
for (const m of s.matchAll(/className\s*\+?=\s*[^;]*?['"]([a-zA-Z][\w-]*)['"]/g)) classes.add(m[1]);
|
|
508
|
+
return {
|
|
509
|
+
intersectionObserver: (s.match(/new\s+IntersectionObserver/g) || []).length,
|
|
510
|
+
scrollListener: (s.match(/addEventListener\s*\(\s*['"]scroll['"]/g) || []).length,
|
|
511
|
+
animateCalls: (s.match(/\.animate\s*\(/g) || []).length,
|
|
512
|
+
requestAnimationFrame: (s.match(/requestAnimationFrame\s*\(/g) || []).length,
|
|
513
|
+
scrollLibraries: /gsap|ScrollTrigger|AOS|locomotive-scroll|lenis|swiper/i.test(s),
|
|
514
|
+
toggledClasses: [...classes].filter((c) => c.length > 1).slice(0, 40),
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// ---------------------------------------------------------------- 抽取主流程
|
|
519
|
+
|
|
520
|
+
function selectorList(selector) {
|
|
521
|
+
return splitTopLevel(selector, ',').map((s) => s.trim()).filter(Boolean);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** 选择器 → 探测用的锚点:去伪类/伪元素/状态类,保留结构 */
|
|
525
|
+
export function anchorOf(selector) {
|
|
526
|
+
let s = String(selector || '').trim();
|
|
527
|
+
s = s.replace(/::[a-z-]+(\([^)]*\))?/gi, '');
|
|
528
|
+
s = s.replace(/:(hover|focus|focus-within|focus-visible|active|visited|target|before|after|link|any-link)\b/gi, '');
|
|
529
|
+
s = s.replace(/\.([\w-]+)/g, (m, name) => (STATE_CLASS_RE.test(name) ? '' : m));
|
|
530
|
+
s = s.replace(/\s*>\s*/g, ' > ').replace(/\s+/g, ' ').trim();
|
|
531
|
+
if (!s) s = String(selector || '').trim();
|
|
532
|
+
return s;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function isStateSelector(selector) {
|
|
536
|
+
return selectorList(selector).some((part) => {
|
|
537
|
+
const classes = part.match(/\.([\w-]+)/g) || [];
|
|
538
|
+
return classes.some((c) => STATE_CLASS_RE.test(c.slice(1)));
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
function keyframesNameOf(rule) {
|
|
543
|
+
const name = rule.decls['animation-name'];
|
|
544
|
+
if (name) return String(name).split(',')[0].trim();
|
|
545
|
+
const shorthand = rule.decls.animation;
|
|
546
|
+
if (!shorthand) return null;
|
|
547
|
+
const layers = parseAnimationLayers(shorthand);
|
|
548
|
+
const withName = layers.find((l) => l.name);
|
|
549
|
+
return withName ? withName.name : null;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function triggerOfRule(rule, { stateSelectors = new Set() } = {}) {
|
|
553
|
+
const sel = rule.selector || '';
|
|
554
|
+
if (/:(hover|focus|active|focus-within|focus-visible)\b/i.test(sel)) return 'hover';
|
|
555
|
+
for (const part of selectorList(sel)) {
|
|
556
|
+
const classes = part.match(/\.([\w-]+)/g) || [];
|
|
557
|
+
if (classes.some((c) => stateSelectors.has(c.slice(1)))) return 'scroll';
|
|
558
|
+
}
|
|
559
|
+
if (/\[data-reveal\]/i.test(sel)) return 'scroll';
|
|
560
|
+
return 'load';
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
function kfById(keyframes, name, media) {
|
|
564
|
+
if (!name) return null;
|
|
565
|
+
const lower = String(name).toLowerCase();
|
|
566
|
+
return (
|
|
567
|
+
keyframes.find((k) => k.name.toLowerCase() === lower && (!media || k.media === media)) ||
|
|
568
|
+
keyframes.find((k) => k.name.toLowerCase() === lower) ||
|
|
569
|
+
null
|
|
570
|
+
);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* 先看名字(原站作者起的名字往往就是动效意图),再看**运动签名**:
|
|
575
|
+
* 循环 + 只有 Y 位移 → float;循环 + 只有 X 位移 → marquee;循环 + 旋转 → spin;
|
|
576
|
+
* 循环 + 缩放&透明度 → pulse;循环 + 只有透明度 → fade;一次性 → slide/zoom/fade。
|
|
577
|
+
*/
|
|
578
|
+
function kindOfKeyframes(name, motion, loop = false) {
|
|
579
|
+
const n = String(name || '').toLowerCase();
|
|
580
|
+
if (/float|bob|drift/.test(n)) return 'float';
|
|
581
|
+
if (/pulse|breath|beat|heart/.test(n)) return 'pulse';
|
|
582
|
+
if (/gradient/.test(n)) return 'gradient';
|
|
583
|
+
if (/marquee|ticker|trail|scroll-?text/.test(n)) return 'marquee';
|
|
584
|
+
if (/ken.?burns/.test(n)) return 'kenburns';
|
|
585
|
+
if (/shine|sheen|sweep|shimmer|glint/.test(n)) return 'shine';
|
|
586
|
+
if (/spin|rotat|turn/.test(n)) return 'spin';
|
|
587
|
+
const onlyRotate = motion.rotate.length && !motion.translate.length && !motion.scale.length;
|
|
588
|
+
if (onlyRotate) return 'spin';
|
|
589
|
+
const onlyY = motion.translate.length && motion.translate.every((t) => !t.x && t.y);
|
|
590
|
+
const onlyX = motion.translate.length && motion.translate.every((t) => t.x && !t.y);
|
|
591
|
+
if (!motion.translate.length && !motion.scale.length && motion.opacity.length) return loop ? 'fade' : 'fade';
|
|
592
|
+
if (loop) {
|
|
593
|
+
if (onlyY) return 'float';
|
|
594
|
+
if (onlyX) return 'marquee';
|
|
595
|
+
if (motion.scale.length && motion.opacity.length) return 'pulse';
|
|
596
|
+
if (motion.translate.length) return 'slide';
|
|
597
|
+
return 'custom';
|
|
598
|
+
}
|
|
599
|
+
if (motion.translate.length) return 'slide';
|
|
600
|
+
if (motion.scale.length) return 'zoom';
|
|
601
|
+
if (motion.opacity.length) return 'fade';
|
|
602
|
+
return 'custom';
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
function transitionKindsOf(rule) {
|
|
606
|
+
const props = new Set();
|
|
607
|
+
if (rule.decls.transition) for (const l of parseTransitionLayers(rule.decls.transition)) props.add(l.property);
|
|
608
|
+
if (rule.decls['transition-property']) for (const p of splitTopLevel(rule.decls['transition-property'], ',')) props.add(p.trim().toLowerCase());
|
|
609
|
+
return [...props];
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
function transitionTimingOf(rule) {
|
|
613
|
+
if (rule.decls.transition) {
|
|
614
|
+
const layers = parseTransitionLayers(rule.decls.transition);
|
|
615
|
+
const first = layers[0] || {};
|
|
616
|
+
return { durationMs: first.durationMs || 0, delayMs: first.delayMs || 0, easing: first.easing || 'ease' };
|
|
617
|
+
}
|
|
618
|
+
return {
|
|
619
|
+
durationMs: parseDurationMs(rule.decls['transition-duration']) || 0,
|
|
620
|
+
delayMs: parseDurationMs(rule.decls['transition-delay']) || 0,
|
|
621
|
+
easing: rule.decls['transition-timing-function'] || 'ease',
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* 从一组源码抽动画清单。
|
|
627
|
+
* @param {{key?:string, page?:string, css?:Array<{file:string,text:string}>, js?:Array<{file:string,text:string}>, html?:Array<{file:string,text:string}>}} input
|
|
628
|
+
*/
|
|
629
|
+
export function extractAnimations({ key = null, page = '/pages/index.html', css = [], js = [], html = [] } = {}) {
|
|
630
|
+
const warnings = [];
|
|
631
|
+
const parsed = [];
|
|
632
|
+
for (const c of css) {
|
|
633
|
+
try {
|
|
634
|
+
const r = parseCss(c.text, { file: c.file });
|
|
635
|
+
parsed.push({ file: c.file, ...r });
|
|
636
|
+
warnings.push(...r.warnings);
|
|
637
|
+
} catch (e) {
|
|
638
|
+
warnings.push(`CSS 解析失败 ${c.file}:${e.message}`);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
const keyframes = parsed.flatMap((p) => p.keyframes);
|
|
642
|
+
const rules = parsed.flatMap((p) => p.rules);
|
|
643
|
+
|
|
644
|
+
const htmlScan = html.map((h) => ({ file: h.file, ...scanHtml(h.text) }));
|
|
645
|
+
const jsScan = js.map((j) => ({ file: j.file, ...scanJs(j.text) }));
|
|
646
|
+
const toggled = new Set(jsScan.flatMap((j) => j.toggledClasses));
|
|
647
|
+
|
|
648
|
+
const entries = [];
|
|
649
|
+
const seen = new Set();
|
|
650
|
+
const push = (entry) => {
|
|
651
|
+
const id = `${entry.kind}|${entry.anchor}|${entry.keyframesName || ''}|${entry.selector}`;
|
|
652
|
+
if (seen.has(id)) return;
|
|
653
|
+
seen.add(id);
|
|
654
|
+
entries.push(entry);
|
|
655
|
+
};
|
|
656
|
+
|
|
657
|
+
// ---- 1) keyframes 动画(`animation:` 声明) ----
|
|
658
|
+
for (const rule of rules) {
|
|
659
|
+
if (!rule.decls.animation && !rule.decls['animation-name']) continue;
|
|
660
|
+
const layers = rule.decls.animation
|
|
661
|
+
? parseAnimationLayers(rule.decls.animation)
|
|
662
|
+
: splitTopLevel(rule.decls['animation-name'], ',').map((name) => ({
|
|
663
|
+
name: name.trim(),
|
|
664
|
+
durationMs: parseDurationMs(rule.decls['animation-duration']) || 0,
|
|
665
|
+
delayMs: parseDurationMs(rule.decls['animation-delay']) || 0,
|
|
666
|
+
iteration: rule.decls['animation-iteration-count'] || '1',
|
|
667
|
+
easing: rule.decls['animation-timing-function'] || 'ease',
|
|
668
|
+
direction: rule.decls['animation-direction'] || 'normal',
|
|
669
|
+
fill: rule.decls['animation-fill-mode'] || 'none',
|
|
670
|
+
playState: rule.decls['animation-play-state'] || 'running',
|
|
671
|
+
}));
|
|
672
|
+
for (const layer of layers) {
|
|
673
|
+
const kf = kfById(keyframes, layer.name, rule.media);
|
|
674
|
+
if (!kf) {
|
|
675
|
+
warnings.push(`\`${rule.selector}\` 用了 \`animation: ${layer.name}\`,但没找到同名 @keyframes`);
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
const motion = motionOfFrames(kf.frames);
|
|
679
|
+
const loop = layer.iteration === 'infinite';
|
|
680
|
+
const kind = kindOfKeyframes(layer.name, motion, loop);
|
|
681
|
+
const trigger = triggerOfRule(rule, { stateSelectors: toggled });
|
|
682
|
+
for (const sel of selectorList(rule.selector)) {
|
|
683
|
+
push({
|
|
684
|
+
kind,
|
|
685
|
+
selector: sel,
|
|
686
|
+
anchor: anchorOf(sel),
|
|
687
|
+
keyframesName: kf.name,
|
|
688
|
+
keyframes: kf.frames,
|
|
689
|
+
media: rule.media || '',
|
|
690
|
+
trigger: layer.playState === 'paused' ? 'paused' : trigger,
|
|
691
|
+
loop: layer.iteration === 'infinite',
|
|
692
|
+
timing: {
|
|
693
|
+
durationMs: layer.durationMs,
|
|
694
|
+
delayMs: layer.delayMs,
|
|
695
|
+
iteration: layer.iteration,
|
|
696
|
+
easing: layer.easing,
|
|
697
|
+
direction: layer.direction,
|
|
698
|
+
fill: layer.fill,
|
|
699
|
+
},
|
|
700
|
+
motion,
|
|
701
|
+
source: { file: rule.file, line: rule.line },
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
// ---- 2) transition:分组找「初始态 + 状态类」→ reveal;带 :hover → hover ----
|
|
708
|
+
const transGroups = new Map();
|
|
709
|
+
for (const rule of rules) {
|
|
710
|
+
if (!rule.decls.transition && !rule.decls['transition-property']) continue;
|
|
711
|
+
const kinds = transitionKindsOf(rule);
|
|
712
|
+
if (!kinds.length) continue;
|
|
713
|
+
const timing = transitionTimingOf(rule);
|
|
714
|
+
for (const sel of selectorList(rule.selector)) {
|
|
715
|
+
const anchor = anchorOf(sel);
|
|
716
|
+
const key = anchor;
|
|
717
|
+
const g = transGroups.get(key) || { anchor, initial: null, state: null, hover: null, kinds: new Set() };
|
|
718
|
+
kinds.forEach((k) => g.kinds.add(k));
|
|
719
|
+
if (/:(hover|focus|active|focus-within)\b/i.test(sel)) {
|
|
720
|
+
g.hover = g.hover || { rule, sel, timing };
|
|
721
|
+
} else if (isStateSelector(sel) || (sel.match(/\.([\w-]+)/g) || []).some((c) => toggled.has(c.slice(1)))) {
|
|
722
|
+
g.state = g.state || { rule, sel, timing };
|
|
723
|
+
} else {
|
|
724
|
+
g.initial = g.initial || { rule, sel, timing };
|
|
725
|
+
}
|
|
726
|
+
transGroups.set(key, g);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
// 补充:真实站点常把 `transition` 写在基础态,只在 `:hover` 里改属性 ——
|
|
730
|
+
// 只按带 transition 的规则分组会漏掉这类 hover,所以再扫一遍「没有 transition 但有 :hover」的规则,
|
|
731
|
+
// 挂到同锚点的组上(组必须已存在,即基础态确实声明了 transition)。
|
|
732
|
+
for (const rule of rules) {
|
|
733
|
+
if (rule.decls.transition || rule.decls['transition-property']) continue;
|
|
734
|
+
if (!/:(hover|focus|active|focus-within)\b/i.test(rule.selector || '')) continue;
|
|
735
|
+
for (const sel of selectorList(rule.selector)) {
|
|
736
|
+
const anchor = anchorOf(sel);
|
|
737
|
+
const g = transGroups.get(anchor);
|
|
738
|
+
if (!g) continue;
|
|
739
|
+
if (!g.hover) g.hover = { rule, sel, timing: g.initial ? g.initial.timing : transitionTimingOf(rule) };
|
|
740
|
+
transGroups.set(anchor, g);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
for (const g of transGroups.values()) {
|
|
745
|
+
const kinds = [...g.kinds];
|
|
746
|
+
const transformish = kinds.some((k) => /transform|all/.test(k));
|
|
747
|
+
const opacityish = kinds.some((k) => /opacity|all/.test(k));
|
|
748
|
+
if (g.hover && !g.state) {
|
|
749
|
+
push({
|
|
750
|
+
kind: 'hover',
|
|
751
|
+
selector: g.hover.sel,
|
|
752
|
+
anchor: g.anchor,
|
|
753
|
+
trigger: 'hover',
|
|
754
|
+
loop: false,
|
|
755
|
+
timing: g.hover.timing,
|
|
756
|
+
motion: { properties: kinds, translate: [], scale: [], rotate: [], opacity: [], backgroundPosition: [], filter: [], transform: [] },
|
|
757
|
+
source: { file: g.hover.rule.file, line: g.hover.rule.line },
|
|
758
|
+
});
|
|
759
|
+
continue;
|
|
760
|
+
}
|
|
761
|
+
if (g.state && (transformish || opacityish)) {
|
|
762
|
+
const init = g.initial ? g.initial.rule.decls : g.state.rule.decls;
|
|
763
|
+
const translate = parseTranslate(init.transform || '');
|
|
764
|
+
const scale = parseScale(init.transform || '');
|
|
765
|
+
const opacity = init.opacity !== undefined ? num(init.opacity) : null;
|
|
766
|
+
const timing = g.initial && g.initial.timing.durationMs ? g.initial.timing : g.state.timing;
|
|
767
|
+
push({
|
|
768
|
+
kind: 'reveal',
|
|
769
|
+
selector: g.state.sel,
|
|
770
|
+
anchor: g.anchor,
|
|
771
|
+
trigger: 'scroll',
|
|
772
|
+
entryFrom: 'css',
|
|
773
|
+
loop: false,
|
|
774
|
+
timing: { ...timing, iteration: '1' },
|
|
775
|
+
reveal: { variant: revealVariantOf({ translate, scale, opacity }), stateClass: (g.state.sel.match(/\.([\w-]+)/g) || []).pop() },
|
|
776
|
+
motion: {
|
|
777
|
+
properties: [...new Set([...kinds, 'opacity', 'transform'])],
|
|
778
|
+
translate: translate ? [translate] : [],
|
|
779
|
+
scale: scale !== null ? [scale] : [],
|
|
780
|
+
rotate: [],
|
|
781
|
+
opacity: opacity !== null ? [opacity] : [],
|
|
782
|
+
backgroundPosition: [],
|
|
783
|
+
filter: [],
|
|
784
|
+
transform: [],
|
|
785
|
+
},
|
|
786
|
+
source: { file: g.state.rule.file, line: g.state.rule.line },
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// ---- 3) HTML 里的声明式入场(data-reveal / data-parallax / data-kenburns / 内联 style) ----
|
|
792
|
+
for (const h of htmlScan) {
|
|
793
|
+
for (const r of h.reveal) {
|
|
794
|
+
const cls = (r.class || '').split(/\s+/).find(Boolean);
|
|
795
|
+
const anchor = cls ? `.${cls}` : '[data-reveal]';
|
|
796
|
+
const exists = entries.some((e) => e.kind === 'reveal' && (e.anchor === anchor || e.anchor === '[data-reveal]'));
|
|
797
|
+
if (exists) {
|
|
798
|
+
const hit = entries.find((e) => e.kind === 'reveal' && (e.anchor === anchor || e.anchor === '[data-reveal]'));
|
|
799
|
+
hit.entryFrom = 'markup';
|
|
800
|
+
hit.markup = { tag: r.tag, variant: r.variant, delay: r.delay };
|
|
801
|
+
if (r.variant) hit.reveal = { ...(hit.reveal || {}), variant: r.variant };
|
|
802
|
+
if (r.delay && parseDurationMs(r.delay) === null && /^\d+$/.test(r.delay)) hit.timing.delayMs = Number(r.delay);
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
push({
|
|
806
|
+
kind: 'reveal',
|
|
807
|
+
selector: anchor,
|
|
808
|
+
anchor,
|
|
809
|
+
trigger: 'scroll',
|
|
810
|
+
entryFrom: 'markup',
|
|
811
|
+
loop: false,
|
|
812
|
+
timing: { durationMs: 620, delayMs: r.delay && /^\d+$/.test(r.delay) ? Number(r.delay) : 0, iteration: '1', easing: 'ease' },
|
|
813
|
+
reveal: { variant: r.variant || 'fade-up' },
|
|
814
|
+
markup: { tag: r.tag, variant: r.variant, delay: r.delay },
|
|
815
|
+
motion: { properties: ['opacity', 'transform'], translate: [{ x: 0, y: 28 }], scale: [], rotate: [], opacity: [0], backgroundPosition: [], filter: [], transform: [] },
|
|
816
|
+
source: { file: h.file, line: null },
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
if (h.parallax) {
|
|
820
|
+
push({
|
|
821
|
+
kind: 'parallax',
|
|
822
|
+
selector: '[data-parallax]',
|
|
823
|
+
anchor: '[data-parallax]',
|
|
824
|
+
trigger: 'scroll',
|
|
825
|
+
entryFrom: 'markup',
|
|
826
|
+
loop: false,
|
|
827
|
+
timing: { durationMs: 0, delayMs: 0, iteration: '1', easing: 'linear' },
|
|
828
|
+
motion: { properties: ['transform'], translate: [], scale: [], rotate: [], opacity: [], backgroundPosition: [], filter: [], transform: [] },
|
|
829
|
+
source: { file: h.file, line: null },
|
|
830
|
+
});
|
|
831
|
+
}
|
|
832
|
+
if (h.kenburns) {
|
|
833
|
+
const kf = kfById(keyframes, 'kenburns', '');
|
|
834
|
+
push({
|
|
835
|
+
kind: 'kenburns',
|
|
836
|
+
selector: '[data-kenburns]',
|
|
837
|
+
anchor: '[data-kenburns]',
|
|
838
|
+
keyframesName: 'kenburns',
|
|
839
|
+
keyframes: kf ? kf.frames : [],
|
|
840
|
+
trigger: 'load',
|
|
841
|
+
entryFrom: 'markup',
|
|
842
|
+
loop: true,
|
|
843
|
+
timing: { durationMs: 22000, delayMs: 0, iteration: 'infinite', easing: 'ease-in-out', direction: 'alternate' },
|
|
844
|
+
motion: kf ? motionOfFrames(kf.frames) : { properties: ['transform'], translate: [], scale: [1, 1.12], rotate: [], opacity: [], backgroundPosition: [], filter: [], transform: [] },
|
|
845
|
+
source: { file: h.file, line: null },
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
// ---- 3.5) HTML 直接用了 _base 动效类(模板最常见:`class="hero__orbit anim-float"`) ----
|
|
851
|
+
// 这类动画的 @keyframes 在 `assets/base/base.css` 里(已被排除,不重复计),但**元素确实在动**,
|
|
852
|
+
// 所以按类名反向补一条清单:字段全部对齐 BASE_MAP,map.status = exact。
|
|
853
|
+
const BASE_CLASS_KIND = {
|
|
854
|
+
'anim-float': 'float',
|
|
855
|
+
'anim-pulse': 'pulse',
|
|
856
|
+
'anim-gradient': 'gradient',
|
|
857
|
+
'anim-shine': 'shine',
|
|
858
|
+
marquee: 'marquee',
|
|
859
|
+
};
|
|
860
|
+
for (const h of htmlScan) {
|
|
861
|
+
for (const el of h.animEls || []) {
|
|
862
|
+
for (const c of el.anim) {
|
|
863
|
+
const kind = BASE_CLASS_KIND[c];
|
|
864
|
+
if (!kind) continue;
|
|
865
|
+
const own = (el.class || '')
|
|
866
|
+
.split(/\s+/)
|
|
867
|
+
.filter(Boolean)
|
|
868
|
+
.filter((x) => !BASE_CLASS_KIND[x] && !/^marquee/.test(x));
|
|
869
|
+
const anchor = own.length ? `.${own[0]}` : `.${c}`;
|
|
870
|
+
if (entries.some((e) => e.anchor === anchor && e.kind === kind)) continue;
|
|
871
|
+
const target = BASE_MAP[kind] || {};
|
|
872
|
+
const kfName = target.keyframes || null;
|
|
873
|
+
const kf = kfById(keyframes, kfName, '');
|
|
874
|
+
push({
|
|
875
|
+
kind,
|
|
876
|
+
selector: `.${c}`,
|
|
877
|
+
anchor,
|
|
878
|
+
keyframesName: kfName,
|
|
879
|
+
keyframes: kf ? kf.frames : [],
|
|
880
|
+
trigger: 'load',
|
|
881
|
+
entryFrom: 'base-class',
|
|
882
|
+
loop: true,
|
|
883
|
+
timing: {
|
|
884
|
+
durationMs: (target.timing || {}).durationMs || 0,
|
|
885
|
+
delayMs: 0,
|
|
886
|
+
iteration: (target.timing || {}).iteration || 'infinite',
|
|
887
|
+
easing: (target.timing || {}).easing || 'ease-in-out',
|
|
888
|
+
...((target.timing || {}).direction ? { direction: target.timing.direction } : {}),
|
|
889
|
+
},
|
|
890
|
+
motion: kf
|
|
891
|
+
? motionOfFrames(kf.frames)
|
|
892
|
+
: { properties: ['animation'], translate: [], scale: [], rotate: [], opacity: [], backgroundPosition: [], filter: [], transform: [] },
|
|
893
|
+
source: { file: h.file, line: null },
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
// ---- 4) 期望窗口 + 映射 ----
|
|
900
|
+
const animations = entries.map((e, i) => {
|
|
901
|
+
const delay = Number(e.timing.delayMs || 0);
|
|
902
|
+
const dur = Number(e.timing.durationMs || 0);
|
|
903
|
+
let expect;
|
|
904
|
+
if (e.trigger === 'load') {
|
|
905
|
+
const startsInWindow = delay < FRAME_WINDOW_MS[1];
|
|
906
|
+
const endsBeforeWindow = !e.loop && delay + dur <= FRAME_WINDOW_MS[0];
|
|
907
|
+
expect = {
|
|
908
|
+
motionInFirstWindow: startsInWindow && !endsBeforeWindow,
|
|
909
|
+
mayFireAtLoad: startsInWindow && !endsBeforeWindow,
|
|
910
|
+
windowMs: FRAME_WINDOW_MS,
|
|
911
|
+
why: !startsInWindow
|
|
912
|
+
? `animation-delay ${fmtMs(delay)} ≥ ${FRAME_WINDOW_MS[1]}ms,首屏窗口内还没开始`
|
|
913
|
+
: endsBeforeWindow
|
|
914
|
+
? `延迟+时长 ${fmtMs(delay + dur)} ≤ ${FRAME_WINDOW_MS[0]}ms,t0 之前就播完了`
|
|
915
|
+
: 'load 后立即开始,落在 120–1500ms 窗口内',
|
|
916
|
+
};
|
|
917
|
+
} else if (e.trigger === 'scroll') {
|
|
918
|
+
expect = { motionInFirstWindow: false, mayFireAtLoad: true, windowMs: FRAME_WINDOW_MS, why: '滚动/入场触发:首屏元素可能在 load 时就已进入视口并播放,也可能要滚动才播' };
|
|
919
|
+
} else {
|
|
920
|
+
expect = { motionInFirstWindow: false, mayFireAtLoad: false, windowMs: FRAME_WINDOW_MS, why: e.trigger === 'hover' ? 'hover/focus 交互触发,首屏两帧看不到' : `触发方式 ${e.trigger},首屏两帧看不到` };
|
|
921
|
+
}
|
|
922
|
+
const mapping = mapToBase({ ...e, kind: e.kind });
|
|
923
|
+
return {
|
|
924
|
+
id: `a${i + 1}`,
|
|
925
|
+
kind: e.kind,
|
|
926
|
+
selector: e.selector,
|
|
927
|
+
anchor: e.anchor,
|
|
928
|
+
media: e.media || '',
|
|
929
|
+
trigger: e.trigger,
|
|
930
|
+
loop: !!e.loop,
|
|
931
|
+
keyframesName: e.keyframesName || null,
|
|
932
|
+
timing: e.timing,
|
|
933
|
+
motion: summarizeMotion(e.motion),
|
|
934
|
+
keyframes: (e.keyframes || []).map((f) => ({ at: f.at, decls: f.decls })),
|
|
935
|
+
reveal: e.reveal || null,
|
|
936
|
+
expect,
|
|
937
|
+
base: mapping.base || null,
|
|
938
|
+
map: { status: mapping.status, deltas: mapping.deltas || [], reason: mapping.reason || null },
|
|
939
|
+
source: e.source,
|
|
940
|
+
};
|
|
941
|
+
});
|
|
942
|
+
|
|
943
|
+
const counts = {
|
|
944
|
+
total: animations.length,
|
|
945
|
+
load: animations.filter((a) => a.trigger === 'load').length,
|
|
946
|
+
scroll: animations.filter((a) => a.trigger === 'scroll').length,
|
|
947
|
+
hover: animations.filter((a) => a.trigger === 'hover').length,
|
|
948
|
+
expectInWindow: animations.filter((a) => a.expect.motionInFirstWindow).length,
|
|
949
|
+
mapped: animations.filter((a) => a.map.status === 'exact' || a.map.status === 'alias').length,
|
|
950
|
+
exact: animations.filter((a) => a.map.status === 'exact').length,
|
|
951
|
+
alias: animations.filter((a) => a.map.status === 'alias').length,
|
|
952
|
+
unmapped: animations.filter((a) => a.map.status === 'unmapped').length,
|
|
953
|
+
na: animations.filter((a) => a.map.status === 'na').length,
|
|
954
|
+
keyframes: [...new Set(keyframes.map((k) => k.name))].length,
|
|
955
|
+
};
|
|
956
|
+
|
|
957
|
+
const signals = jsScan.reduce(
|
|
958
|
+
(acc, j) => ({
|
|
959
|
+
files: acc.files + 1,
|
|
960
|
+
intersectionObserver: acc.intersectionObserver + j.intersectionObserver,
|
|
961
|
+
scrollListener: acc.scrollListener + j.scrollListener,
|
|
962
|
+
animateCalls: acc.animateCalls + j.animateCalls,
|
|
963
|
+
requestAnimationFrame: acc.requestAnimationFrame + j.requestAnimationFrame,
|
|
964
|
+
scrollLibraries: acc.scrollLibraries || j.scrollLibraries,
|
|
965
|
+
toggledClasses: [...new Set([...acc.toggledClasses, ...j.toggledClasses])].slice(0, 40),
|
|
966
|
+
}),
|
|
967
|
+
{ files: 0, intersectionObserver: 0, scrollListener: 0, animateCalls: 0, requestAnimationFrame: 0, scrollLibraries: false, toggledClasses: [] }
|
|
968
|
+
);
|
|
969
|
+
|
|
970
|
+
return {
|
|
971
|
+
_format: ANIM_FORMAT,
|
|
972
|
+
key,
|
|
973
|
+
page,
|
|
974
|
+
generatedAt: new Date().toISOString(),
|
|
975
|
+
source: { css: css.map((c) => c.file), js: js.map((j) => j.file), html: html.map((h) => h.file) },
|
|
976
|
+
base: { library: 'templates/_base', vocabulary: Object.keys(BASE_MAP) },
|
|
977
|
+
signals,
|
|
978
|
+
counts,
|
|
979
|
+
animations,
|
|
980
|
+
warnings,
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
function summarizeMotion(motion) {
|
|
985
|
+
const t = motion.translate || [];
|
|
986
|
+
const tx = t.map((v) => v.x).filter((v) => v !== null && v !== undefined);
|
|
987
|
+
const ty = t.map((v) => v.y).filter((v) => v !== null && v !== undefined);
|
|
988
|
+
const span = (arr) => (arr.length ? { min: Math.min(...arr), max: Math.max(...arr) } : null);
|
|
989
|
+
return {
|
|
990
|
+
properties: motion.properties || [],
|
|
991
|
+
translateX: span(tx),
|
|
992
|
+
translateY: span(ty),
|
|
993
|
+
scale: span((motion.scale || []).filter((v) => v !== null)),
|
|
994
|
+
rotate: span((motion.rotate || []).filter((v) => v !== null)),
|
|
995
|
+
opacity: span((motion.opacity || []).filter((v) => v !== null)),
|
|
996
|
+
backgroundPosition: (motion.backgroundPosition || []).slice(0, 4),
|
|
997
|
+
filter: (motion.filter || []).slice(0, 4),
|
|
998
|
+
transform: (motion.transform || []).slice(0, 6),
|
|
999
|
+
};
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
// ---------------------------------------------------------------- 读目录 / 落盘
|
|
1003
|
+
|
|
1004
|
+
async function walkFiles(root, { exts = ['.css'], skip = ['node_modules', '.git'], skipPrefixes = [] } = {}) {
|
|
1005
|
+
const out = [];
|
|
1006
|
+
const walk = async (dir) => {
|
|
1007
|
+
let entries;
|
|
1008
|
+
try {
|
|
1009
|
+
entries = await fsp.readdir(dir, { withFileTypes: true });
|
|
1010
|
+
} catch {
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
for (const e of entries) {
|
|
1014
|
+
if (skip.includes(e.name)) continue;
|
|
1015
|
+
const full = path.join(dir, e.name);
|
|
1016
|
+
const rel = path.relative(root, full).replace(/\\/g, '/');
|
|
1017
|
+
if (skipPrefixes.some((p) => rel === p || rel.startsWith(`${p}/`))) continue;
|
|
1018
|
+
if (e.isDirectory()) await walk(full);
|
|
1019
|
+
else if (e.isFile() && exts.includes(path.extname(e.name).toLowerCase())) out.push(full);
|
|
1020
|
+
}
|
|
1021
|
+
};
|
|
1022
|
+
await walk(root);
|
|
1023
|
+
return out.sort();
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
/**
|
|
1027
|
+
* 从一个模板目录(= 原站镜像)抽清单。
|
|
1028
|
+
* **排除 `assets/base/**`**:那是我们自己的基础库,里面的 keyframes 不属于原站。
|
|
1029
|
+
*/
|
|
1030
|
+
export async function extractAnimationsFromDir({ dir, page = '/pages/index.html' } = {}) {
|
|
1031
|
+
const root = path.resolve(dir);
|
|
1032
|
+
const htmlFiles = await walkFiles(path.join(root, 'pages'), { exts: ['.html', '.htm'] });
|
|
1033
|
+
const pageFile = path.join(root, page.replace(/^\//, ''));
|
|
1034
|
+
const cssFiles = await walkFiles(path.join(root, 'assets'), { exts: ['.css'], skipPrefixes: ['base'] });
|
|
1035
|
+
const jsFiles = await walkFiles(path.join(root, 'assets'), { exts: ['.js'], skipPrefixes: ['base'] });
|
|
1036
|
+
const read = async (files) => {
|
|
1037
|
+
const out = [];
|
|
1038
|
+
for (const f of files) {
|
|
1039
|
+
try {
|
|
1040
|
+
out.push({ file: path.relative(root, f).replace(/\\/g, '/'), text: await fsp.readFile(f, 'utf8') });
|
|
1041
|
+
} catch {
|
|
1042
|
+
/* 读不了就跳过 */
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
return out;
|
|
1046
|
+
};
|
|
1047
|
+
const css = await read(cssFiles);
|
|
1048
|
+
const js = await read(jsFiles);
|
|
1049
|
+
const html = await read(htmlFiles.length ? htmlFiles : [pageFile]);
|
|
1050
|
+
|
|
1051
|
+
// 内联 <style> / <script> 也当源码(file 标到页面,便于溯源)
|
|
1052
|
+
for (const h of html) {
|
|
1053
|
+
for (const m of h.text.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)) {
|
|
1054
|
+
css.push({ file: `${h.file}#inline-${css.length + 1}`, text: m[1] });
|
|
1055
|
+
}
|
|
1056
|
+
for (const m of h.text.matchAll(/<script\b(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi)) {
|
|
1057
|
+
if (m[1].trim()) js.push({ file: `${h.file}#inline-${js.length + 1}`, text: m[1] });
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
const key = (() => {
|
|
1062
|
+
try {
|
|
1063
|
+
return JSON.parse(fs.readFileSync(path.join(root, 'template.json'), 'utf8')).key || null;
|
|
1064
|
+
} catch {
|
|
1065
|
+
return null;
|
|
1066
|
+
}
|
|
1067
|
+
})();
|
|
1068
|
+
|
|
1069
|
+
const manifest = extractAnimations({ key, page, css, js, html });
|
|
1070
|
+
return { manifest, files: { css: css.map((c) => c.file), js: js.map((j) => j.file), html: html.map((h) => h.file) } };
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
export async function writeAnimationManifest(designDir, manifest) {
|
|
1074
|
+
const dir = path.resolve(designDir);
|
|
1075
|
+
await fsp.mkdir(dir, { recursive: true });
|
|
1076
|
+
const file = path.join(dir, ANIM_MANIFEST_FILE);
|
|
1077
|
+
await fsp.writeFile(file, JSON.stringify(manifest, null, 2) + '\n', 'utf8');
|
|
1078
|
+
return file;
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
/** 清单可能放在 design/(默认)也可能被人拷到模板根,两个位置都认 */
|
|
1082
|
+
export function readAnimationManifest(dir) {
|
|
1083
|
+
for (const cand of [path.join(dir, ANIM_MANIFEST_FILE), path.join(dir, 'design', ANIM_MANIFEST_FILE)]) {
|
|
1084
|
+
try {
|
|
1085
|
+
const j = JSON.parse(fs.readFileSync(cand, 'utf8'));
|
|
1086
|
+
if (j && Array.isArray(j.animations)) return { ...j, file: cand };
|
|
1087
|
+
} catch {
|
|
1088
|
+
/* 继续找 */
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
return null;
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
export function readAnimationGeom(dir) {
|
|
1095
|
+
const file = path.join(dir, ANIM_GEOM_FILE);
|
|
1096
|
+
try {
|
|
1097
|
+
const j = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
1098
|
+
return j && j.viewports ? { ...j, file } : null;
|
|
1099
|
+
} catch {
|
|
1100
|
+
return null;
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
export async function writeAnimationGeom(designDir, geom) {
|
|
1105
|
+
const dir = path.resolve(designDir);
|
|
1106
|
+
await fsp.mkdir(dir, { recursive: true });
|
|
1107
|
+
const file = path.join(dir, ANIM_GEOM_FILE);
|
|
1108
|
+
await fsp.writeFile(file, JSON.stringify(geom, null, 2) + '\n', 'utf8');
|
|
1109
|
+
return file;
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
/** 需要在 Chrome 里量矩形的锚点:load 窗口内的 + 可能被首屏触发的滚动入场 */
|
|
1113
|
+
export function anchorsOf(manifest) {
|
|
1114
|
+
if (!manifest) return [];
|
|
1115
|
+
const out = new Set();
|
|
1116
|
+
for (const a of manifest.animations || []) {
|
|
1117
|
+
if (!a.anchor) continue;
|
|
1118
|
+
if (a.expect && (a.expect.motionInFirstWindow || a.expect.mayFireAtLoad)) out.add(a.anchor);
|
|
1119
|
+
}
|
|
1120
|
+
return [...out].slice(0, 40);
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
/** capture 用:抽清单并写进 design/animations.json(已存在且 refresh=false 就复用) */
|
|
1124
|
+
export async function ensureAnimationManifest({ templateDir, designDir, refresh = true } = {}) {
|
|
1125
|
+
if (!templateDir) return null;
|
|
1126
|
+
const target = path.join(designDir, ANIM_MANIFEST_FILE);
|
|
1127
|
+
if (!refresh && fs.existsSync(target)) return readAnimationManifest(designDir);
|
|
1128
|
+
const { manifest } = await extractAnimationsFromDir({ dir: templateDir });
|
|
1129
|
+
await writeAnimationManifest(designDir, manifest);
|
|
1130
|
+
return manifest;
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
// ---------------------------------------------------------------- 对账
|
|
1134
|
+
|
|
1135
|
+
function rectsOf(items, anchor) {
|
|
1136
|
+
const hit = (items || []).find((i) => i && i.anchor === anchor);
|
|
1137
|
+
if (!hit || !hit.count) return null;
|
|
1138
|
+
const rects = [...(hit.t0 || []), ...(hit.t1500 || [])].filter((r) => r && Number.isFinite(r.x) && Number.isFinite(r.y));
|
|
1139
|
+
if (!rects.length) return null;
|
|
1140
|
+
const x = Math.min(...rects.map((r) => r.x));
|
|
1141
|
+
const y = Math.min(...rects.map((r) => r.y));
|
|
1142
|
+
const right = Math.max(...rects.map((r) => r.x + Math.max(0, r.w || 0)));
|
|
1143
|
+
const bottom = Math.max(...rects.map((r) => r.y + Math.max(0, r.h || 0)));
|
|
1144
|
+
return { x, y, w: right - x, h: bottom - y };
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
function overlap(a, b, slack = 2) {
|
|
1148
|
+
const ax2 = a.x + a.w + slack;
|
|
1149
|
+
const ay2 = a.y + a.h + slack;
|
|
1150
|
+
const bx2 = b.x + b.w + slack;
|
|
1151
|
+
const by2 = b.y + b.h + slack;
|
|
1152
|
+
const w = Math.min(ax2, bx2) - Math.max(a.x, b.x) + slack;
|
|
1153
|
+
const h = Math.min(ay2, by2) - Math.max(a.y, b.y) + slack;
|
|
1154
|
+
if (w <= 0 || h <= 0) return 0;
|
|
1155
|
+
return w * h;
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
/**
|
|
1159
|
+
* 期望(清单)vs 实测(t0/t1500 像素差区域)对账。
|
|
1160
|
+
*
|
|
1161
|
+
* * **命中**:load 型期望动画,在任一视口里有一个像素区域与它的元素矩形相交;
|
|
1162
|
+
* * **缺失**:load 型期望动画在所有视口都没有区域(元素被 `display:none` 的视口不算失败);
|
|
1163
|
+
* * **多余**:像素区域与**任何**声明锚点(含滚动/hover)都不相交 —— 也就是清单解释不了的运动;
|
|
1164
|
+
* * 没有几何证据(旧包/没跑 capture)时退化成按数量比:`min(期望, 实测)` 记命中,差额分别记缺失/多余,
|
|
1165
|
+
* 并在 `attribution` 里写明退化原因。
|
|
1166
|
+
*
|
|
1167
|
+
* @returns {{ok:boolean,attribution:'geom'|'count'|'none',expected:number,observed:number,matched:number,missing:Array,extra:Array,byViewport:Array,unmapped:Array,note:string}}
|
|
1168
|
+
*/
|
|
1169
|
+
export function reconcileAnimations({ manifest, geom = null, animations = [], slack = 2 } = {}) {
|
|
1170
|
+
if (!manifest) {
|
|
1171
|
+
return {
|
|
1172
|
+
ok: true,
|
|
1173
|
+
attribution: 'none',
|
|
1174
|
+
expected: 0,
|
|
1175
|
+
observed: 0,
|
|
1176
|
+
matched: 0,
|
|
1177
|
+
missing: [],
|
|
1178
|
+
extra: [],
|
|
1179
|
+
byViewport: [],
|
|
1180
|
+
unmapped: [],
|
|
1181
|
+
note: '没有 design/animations.json(先跑 `wkgeo template anim --dir <模板目录>` 或重新 init)——跳过动画对账',
|
|
1182
|
+
};
|
|
1183
|
+
}
|
|
1184
|
+
const entries = (manifest.animations || []).filter((a) => a.anchor);
|
|
1185
|
+
const expectedLoad = entries.filter((a) => a.expect && a.expect.motionInFirstWindow);
|
|
1186
|
+
const allAnchors = [...new Set(entries.map((a) => a.anchor))];
|
|
1187
|
+
const unmapped = entries.filter((a) => a.map && a.map.status === 'unmapped').map((a) => ({ id: a.id, selector: a.selector, anchor: a.anchor, reason: a.map.reason }));
|
|
1188
|
+
const vps = animations.map((a) => a.viewport);
|
|
1189
|
+
const geomVp = geom && geom.viewports ? geom.viewports : null;
|
|
1190
|
+
const observed = animations.reduce((n, a) => n + (a.regions || []).length, 0);
|
|
1191
|
+
|
|
1192
|
+
const attribution = geomVp && vps.some((v) => geomVp[v]) ? 'geom' : 'count';
|
|
1193
|
+
const missing = [];
|
|
1194
|
+
const extra = [];
|
|
1195
|
+
const matchedDetail = [];
|
|
1196
|
+
const byViewport = [];
|
|
1197
|
+
let matched = 0;
|
|
1198
|
+
|
|
1199
|
+
const expectHits = new Map(); // id → {viewport, regions}
|
|
1200
|
+
|
|
1201
|
+
for (const vp of vps) {
|
|
1202
|
+
const regions = ((animations.find((a) => a.viewport === vp) || {}).regions || []).slice();
|
|
1203
|
+
const items = geomVp && geomVp[vp] ? geomVp[vp].items : null;
|
|
1204
|
+
const vpRow = { viewport: vp, expected: expectedLoad.length, observed: regions.length, matched: 0, missing: 0, extra: 0, attribution };
|
|
1205
|
+
const claimed = new Set();
|
|
1206
|
+
if (items) {
|
|
1207
|
+
for (const e of expectedLoad) {
|
|
1208
|
+
const rect = rectsOf(items, e.anchor);
|
|
1209
|
+
if (!rect) continue; // 该视口里没有这个元素(例如移动端隐藏)
|
|
1210
|
+
const hits = [];
|
|
1211
|
+
regions.forEach((r, idx) => {
|
|
1212
|
+
if (overlap(rect, r, slack) > 0) {
|
|
1213
|
+
hits.push(r);
|
|
1214
|
+
claimed.add(idx);
|
|
1215
|
+
}
|
|
1216
|
+
});
|
|
1217
|
+
if (hits.length) {
|
|
1218
|
+
const cur = expectHits.get(e.id) || { id: e.id, kind: e.kind, selector: e.selector, base: e.base, viewports: [] };
|
|
1219
|
+
cur.viewports.push({ viewport: vp, regions: hits.map((r) => r.label), anchorRect: rect });
|
|
1220
|
+
expectHits.set(e.id, cur);
|
|
1221
|
+
vpRow.matched++;
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
// 多余:与**任何**声明锚点都不相交的区域
|
|
1225
|
+
const allRects = allAnchors.map((a) => ({ anchor: a, rect: rectsOf(items, a) })).filter((x) => x.rect);
|
|
1226
|
+
regions.forEach((r, idx) => {
|
|
1227
|
+
const owner = allRects.find((x) => overlap(x.rect, r, slack) > 0);
|
|
1228
|
+
if (!owner) {
|
|
1229
|
+
extra.push({ viewport: vp, region: r.label, box: { x: r.x, y: r.y, w: r.w, h: r.h } });
|
|
1230
|
+
vpRow.extra++;
|
|
1231
|
+
} else claimed.add(idx);
|
|
1232
|
+
});
|
|
1233
|
+
} else {
|
|
1234
|
+
// 没有几何证据:按数量比(先只记数,extra 稍后按视口统一算)
|
|
1235
|
+
const m = Math.min(expectedLoad.length, regions.length);
|
|
1236
|
+
vpRow.matched = m;
|
|
1237
|
+
vpRow.countMode = true;
|
|
1238
|
+
}
|
|
1239
|
+
byViewport.push(vpRow);
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
for (const e of expectedLoad) {
|
|
1243
|
+
if (expectHits.has(e.id)) continue;
|
|
1244
|
+
if (attribution === 'count') {
|
|
1245
|
+
// 退化模式:数量对得上就算命中,超出的按顺序记缺失
|
|
1246
|
+
const m = Math.min(expectedLoad.length, Math.max(0, ...animations.map((a) => (a.regions || []).length)));
|
|
1247
|
+
if (expectedLoad.indexOf(e) < m) {
|
|
1248
|
+
expectHits.set(e.id, { id: e.id, kind: e.kind, selector: e.selector, base: e.base, viewports: [] });
|
|
1249
|
+
continue;
|
|
1250
|
+
}
|
|
1251
|
+
missing.push({
|
|
1252
|
+
id: e.id,
|
|
1253
|
+
kind: e.kind,
|
|
1254
|
+
selector: e.selector,
|
|
1255
|
+
anchor: e.anchor,
|
|
1256
|
+
base: e.base,
|
|
1257
|
+
reason: '没有几何证据(旧包 / 没跑过 capture),按数量比判定缺失',
|
|
1258
|
+
viewports: [],
|
|
1259
|
+
});
|
|
1260
|
+
continue;
|
|
1261
|
+
}
|
|
1262
|
+
// 在任一视口里量到过元素、却哪都没动 → 才算缺失
|
|
1263
|
+
const seen = geomVp ? vps.filter((vp) => rectsOf((geomVp[vp] || {}).items, e.anchor)) : vps;
|
|
1264
|
+
if (!seen.length) {
|
|
1265
|
+
missing.push({
|
|
1266
|
+
id: e.id,
|
|
1267
|
+
kind: e.kind,
|
|
1268
|
+
selector: e.selector,
|
|
1269
|
+
anchor: e.anchor,
|
|
1270
|
+
base: e.base,
|
|
1271
|
+
reason: '清单里有这个元素,但所有视口都没量到它(选择器不可见/被删除)',
|
|
1272
|
+
viewports: [],
|
|
1273
|
+
});
|
|
1274
|
+
continue;
|
|
1275
|
+
}
|
|
1276
|
+
missing.push({
|
|
1277
|
+
id: e.id,
|
|
1278
|
+
kind: e.kind,
|
|
1279
|
+
selector: e.selector,
|
|
1280
|
+
anchor: e.anchor,
|
|
1281
|
+
base: e.base,
|
|
1282
|
+
reason: attribution === 'geom' ? `元素在 ${seen.join('/')} 都量到了,但两个视口的像素差区域都不覆盖它:动画没生效(CSS 被删/被覆盖/被 prefers-reduced-motion 关掉)` : '没有几何证据,按数量比判定缺失',
|
|
1283
|
+
viewports: seen,
|
|
1284
|
+
});
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
if (attribution === 'count') {
|
|
1288
|
+
const m = Math.min(expectedLoad.length, Math.max(0, ...animations.map((a) => (a.regions || []).length)));
|
|
1289
|
+
for (const a of animations) {
|
|
1290
|
+
(a.regions || []).slice(m).forEach((r) => extra.push({ viewport: a.viewport, region: r.label || `区域 ${r.x},${r.y} ${r.w}×${r.h}`, box: { x: r.x, y: r.y, w: r.w, h: r.h } }));
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
matched = expectHits.size;
|
|
1295
|
+
// 按视口把「缺失」也数出来(顶层 missing 是并集,单看 byViewport 会全是 0,容易误读)
|
|
1296
|
+
for (const row of byViewport) {
|
|
1297
|
+
if (row.countMode) continue;
|
|
1298
|
+
const items = geomVp && geomVp[row.viewport] ? geomVp[row.viewport].items : null;
|
|
1299
|
+
if (!items) continue;
|
|
1300
|
+
let miss = 0;
|
|
1301
|
+
for (const e of expectedLoad) {
|
|
1302
|
+
if (!rectsOf(items, e.anchor)) continue; // 该视口看不到这个元素:不算缺失
|
|
1303
|
+
const hits = (expectHits.get(e.id) || {}).viewports || [];
|
|
1304
|
+
if (!hits.some((v) => v.viewport === row.viewport)) miss++;
|
|
1305
|
+
}
|
|
1306
|
+
row.missing = miss;
|
|
1307
|
+
}
|
|
1308
|
+
for (const d of expectHits.values()) matchedDetail.push(d);
|
|
1309
|
+
const ok = missing.length === 0 && extra.length === 0 && (attribution === 'count' ? true : true);
|
|
1310
|
+
|
|
1311
|
+
const loadCount = manifest.counts ? manifest.counts.load : expectedLoad.length;
|
|
1312
|
+
let note;
|
|
1313
|
+
if (!loadCount && !observed) {
|
|
1314
|
+
note = '此站无动画:清单里 0 处时间型动画(load 触发),t0 与 t1500 两帧也 0 处差异';
|
|
1315
|
+
} else if (ok) {
|
|
1316
|
+
note = `对账一致:期望 ${expectedLoad.length} 处 / 命中 ${matched} 处 / 缺失 0 / 多余 0(实测区域 ${observed} 处,几何归因)`;
|
|
1317
|
+
} else {
|
|
1318
|
+
note = `对账不一致:缺失 ${missing.length} 处 / 多余 ${extra.length} 处(期望 ${expectedLoad.length} 处,实测区域 ${observed} 处)`;
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
return {
|
|
1322
|
+
ok,
|
|
1323
|
+
attribution,
|
|
1324
|
+
expected: expectedLoad.length,
|
|
1325
|
+
observed,
|
|
1326
|
+
matched,
|
|
1327
|
+
missing,
|
|
1328
|
+
extra,
|
|
1329
|
+
byViewport,
|
|
1330
|
+
unmapped,
|
|
1331
|
+
detail: matchedDetail,
|
|
1332
|
+
manifest: manifest.file || null,
|
|
1333
|
+
geom: geom ? geom.file || null : null,
|
|
1334
|
+
note,
|
|
1335
|
+
};
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
export { STATE_CLASS_RE };
|