openprototype 1.0.2 → 1.2.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.
@@ -0,0 +1,422 @@
1
+ /**
2
+ * 新手引导 — 首次打开工作台时,用分步气泡把主要功能走一遍。
3
+ *
4
+ * 设计约束(改这个文件前先看一眼):
5
+ * 1. 外壳 HTML 是脚手架时复制的、之后不会自动升级,所以引导逻辑必须留在 /_kit/ 下,
6
+ * 外壳里只有一对 <!-- onboarding:start/end --> 引用标签。
7
+ * 2. runtime/shell/ 不在 static-check 的 NON_PAGE_DIRS 白名单里,会被当页面文件扫描,
8
+ * 所以存储访问沿用 agent-panel.js 的 window['localStorage'] 写法绕开 FORBIDDEN_STORAGE 红线。
9
+ * 3. 不改动外壳内联脚本和 agent-panel.js:锚点就绪靠 rAF 轮询等,重放按钮靠运行时注入。
10
+ *
11
+ * 调试:window.ProtoTour.reset() 清除"已看过"标记;URL 加 ?tour=off 可整体关闭。
12
+ */
13
+ (function() {
14
+ const KIT = window.PROTO_KIT || {};
15
+ const NS = (KIT.productId || 'proto') + '-navigator';
16
+ const SEEN_KEY = NS + '-onboarding-seen';
17
+ const TOUR_VERSION = '1'; // 引导改版时 +1,可让老用户重新看一次
18
+ const tourStorage = window['localStorage']; // 见文件头约束 2,勿改成点号访问
19
+
20
+ const GAP = 12; // 气泡与高亮框的间距
21
+ const MARGIN = 12; // 气泡与视口边缘的最小留白
22
+ const PAD = 4; // 高亮框相对目标元素的外扩
23
+ const READY_TIMEOUT = 8000;
24
+ const VISIBLE_TIMEOUT = 20000; // 标签页迟迟不可见时的兜底,见 waitVisible
25
+
26
+ // ── 步骤配置 ──────────────────────────────────────────
27
+ // selector 支持字符串或数组(数组取并集包围盒,一次框住相邻的几个元素);
28
+ // fallback 在主锚点不可见时兜底(例如 Agent 栏处于折叠态)。
29
+ const STEPS = [
30
+ {
31
+ selector: ['#newFolderBtn', '#newPageBtn'],
32
+ placement: 'bottom',
33
+ title: '第一步 · 先把页面建起来',
34
+ body: '点 <b>新建文件夹</b> 分模块,点 <b>新建页面</b> 建一个原型页。建完会自动写进左侧导航树,不用手动改配置。'
35
+ },
36
+ {
37
+ selector: ['#navSearchInput', '#sidebarTree'],
38
+ placement: 'right',
39
+ title: '第二步 · 在这儿找页面',
40
+ body: '左侧是全部原型页面,按目录分组。页面多了就在 <b>搜索</b> 框里输标题关键字,支持模糊匹配;拖动条目还能直接调整顺序。'
41
+ },
42
+ {
43
+ selector: '#previewPlaceholder',
44
+ fallback: '#previewFrame',
45
+ placement: 'left',
46
+ title: '第三步 · 点开就能预览',
47
+ body: '点左侧任意页面,这里直接渲染出来,右上角 <b>在新标签打开 ↗</b> 可以全屏看。页面右下角还有个 <b>PRD</b> 悬浮按钮,随时能看和改这一页的需求说明。'
48
+ },
49
+ {
50
+ selector: '#agentInput',
51
+ fallback: '#agentPanel',
52
+ placement: 'left',
53
+ title: '第四步 · 用大白话改页面',
54
+ body: '选中页面后,在这里描述你要改什么,比如「表格加一列负责人」。Agent 会直接改代码,中间的预览会自动刷新。'
55
+ },
56
+ {
57
+ selector: '#agentPrdUpdateBtn',
58
+ fallback: '#agentPanel',
59
+ placement: 'left',
60
+ title: '第五步 · 按 PRD 标红一键更新',
61
+ body: '在 PRD 里把要改的地方标红,回到这里点这个按钮,Agent 就会按标红内容改页面。<b>需要先选中一个页面,按钮才可点。</b>'
62
+ }
63
+ ];
64
+
65
+ // ── 运行状态 ──────────────────────────────────────────
66
+ const state = {
67
+ active: false,
68
+ steps: [], // 本次要走的步骤(已过滤掉这版外壳里不存在的锚点)
69
+ index: 0,
70
+ shown: 0, // 实际展示过的步数,用来判断结束时该不该记"已看过"
71
+ lastFocus: null,
72
+ reposition: null
73
+ };
74
+
75
+ let els = {};
76
+
77
+ // ── 工具 ──────────────────────────────────────────────
78
+ // offsetParent 为 null 就说明自身或某个祖先 display:none —— 正是"Agent 栏折叠了"这种要走
79
+ // fallback 的情况(本引导的锚点都不是 position:fixed,不会误判)。
80
+ // 刻意不量 getBoundingClientRect 的宽高:布局还没排完时(刚导航完、标签页在后台)
81
+ // 量出来会是 0,把本该展示的步骤误判成不可见而跳过。
82
+ function isVisible(el) {
83
+ return !!el && el.offsetParent !== null;
84
+ }
85
+
86
+ const selectorList = sel => (Array.isArray(sel) ? sel : [sel]);
87
+
88
+ /** 解析一个步骤的锚点:主 selector 全不可见时退回 fallback,都不行返回 [] */
89
+ function resolveTargets(step) {
90
+ const pick = sel => selectorList(sel).map(s => document.querySelector(s)).filter(isVisible);
91
+ const main = pick(step.selector);
92
+ if (main.length) return main;
93
+ return step.fallback ? pick(step.fallback) : [];
94
+ }
95
+
96
+ /**
97
+ * 这一步在当前这版外壳里存不存在(只看 DOM 里有没有,不量尺寸)。
98
+ * 步骤清单按"存在"过滤而不是按"可见"过滤:布局偶尔会有一瞬间量不到尺寸
99
+ * (刚导航完还没排版、标签页在后台等),按可见过滤会把步骤永久少算一条。
100
+ * 真正的可见性判断留到 go() 展示那一刻做。
101
+ */
102
+ function stepExists(step) {
103
+ const has = sel => selectorList(sel).some(s => document.querySelector(s));
104
+ return has(step.selector) || (step.fallback ? has(step.fallback) : false);
105
+ }
106
+
107
+ /** 多个元素的并集包围盒 */
108
+ function unionRect(targets) {
109
+ let top = Infinity, left = Infinity, right = -Infinity, bottom = -Infinity;
110
+ targets.forEach(el => {
111
+ const r = el.getBoundingClientRect();
112
+ top = Math.min(top, r.top);
113
+ left = Math.min(left, r.left);
114
+ right = Math.max(right, r.right);
115
+ bottom = Math.max(bottom, r.bottom);
116
+ });
117
+ return { top, left, right, bottom, width: right - left, height: bottom - top };
118
+ }
119
+
120
+ function clamp(value, min, max) {
121
+ return Math.max(min, Math.min(max, value));
122
+ }
123
+
124
+ // ── DOM ───────────────────────────────────────────────
125
+ function buildDom() {
126
+ const blocker = document.createElement('div');
127
+ blocker.className = 'tour-blocker';
128
+
129
+ const spotlight = document.createElement('div');
130
+ spotlight.className = 'tour-spotlight';
131
+
132
+ const bubble = document.createElement('div');
133
+ bubble.className = 'tour-bubble';
134
+ bubble.setAttribute('role', 'dialog');
135
+ bubble.setAttribute('aria-modal', 'true');
136
+ bubble.setAttribute('aria-labelledby', 'tourTitle');
137
+ bubble.innerHTML = [
138
+ '<div class="tour-bubble-arrow"></div>',
139
+ '<div class="tour-step-index" id="tourStepIndex"></div>',
140
+ '<div class="tour-title" id="tourTitle"></div>',
141
+ '<div class="tour-body" id="tourBody"></div>',
142
+ '<div class="tour-actions">',
143
+ ' <button class="tour-skip" id="tourSkipBtn" type="button">跳过引导</button>',
144
+ ' <span class="tour-actions-spacer"></span>',
145
+ ' <button class="tour-btn" id="tourPrevBtn" type="button">上一步</button>',
146
+ ' <button class="tour-btn tour-btn-primary" id="tourNextBtn" type="button">下一步</button>',
147
+ '</div>'
148
+ ].join('');
149
+
150
+ document.body.appendChild(blocker);
151
+ document.body.appendChild(spotlight);
152
+ document.body.appendChild(bubble);
153
+
154
+ els = {
155
+ blocker,
156
+ spotlight,
157
+ bubble,
158
+ arrow: bubble.querySelector('.tour-bubble-arrow'),
159
+ stepIndex: bubble.querySelector('#tourStepIndex'),
160
+ title: bubble.querySelector('#tourTitle'),
161
+ body: bubble.querySelector('#tourBody'),
162
+ skip: bubble.querySelector('#tourSkipBtn'),
163
+ prev: bubble.querySelector('#tourPrevBtn'),
164
+ next: bubble.querySelector('#tourNextBtn')
165
+ };
166
+
167
+ els.skip.addEventListener('click', () => stop(true));
168
+ els.prev.addEventListener('click', () => go(state.index - 1));
169
+ els.next.addEventListener('click', () => go(state.index + 1));
170
+ }
171
+
172
+ function teardownDom() {
173
+ [els.blocker, els.spotlight, els.bubble].forEach(el => { if (el) el.remove(); });
174
+ els = {};
175
+ }
176
+
177
+ // ── 定位 ──────────────────────────────────────────────
178
+ /**
179
+ * 把气泡贴到高亮矩形旁边:首选方向放不下就翻到对侧;两侧都放不下且目标本身足够大
180
+ * (典型如"整个中间预览区"),就直接居中盖在目标上,比硬挤到边上压住目标边缘好看;
181
+ * 目标很小则退回 clamp 回视口,免得气泡把目标整个遮住。
182
+ * 箭头指向目标中心;目标中心落在气泡范围外时直接藏掉,免得指错地方。
183
+ */
184
+ function place(rect, placement) {
185
+ const vw = window.innerWidth;
186
+ const vh = window.innerHeight;
187
+ const bw = els.bubble.offsetWidth;
188
+ const bh = els.bubble.offsetHeight;
189
+
190
+ const horizontal = placement === 'left' || placement === 'right';
191
+ const fitsBefore = horizontal ? rect.left - GAP - bw >= MARGIN : rect.top - GAP - bh >= MARGIN;
192
+ const fitsAfter = horizontal
193
+ ? rect.right + GAP + bw <= vw - MARGIN
194
+ : rect.bottom + GAP + bh <= vh - MARGIN;
195
+ const roomInside = horizontal ? rect.width > bw + 40 : rect.height > bh + 40;
196
+
197
+ if (!fitsBefore && !fitsAfter && roomInside) {
198
+ const left = clamp(rect.left + rect.width / 2 - bw / 2, MARGIN, Math.max(MARGIN, vw - bw - MARGIN));
199
+ const top = clamp(rect.top + rect.height / 2 - bh / 2, MARGIN, Math.max(MARGIN, vh - bh - MARGIN));
200
+ els.bubble.style.left = left + 'px';
201
+ els.bubble.style.top = top + 'px';
202
+ els.arrow.className = 'tour-bubble-arrow is-hidden';
203
+ return;
204
+ }
205
+
206
+ let dir = placement;
207
+ if (dir === 'bottom' && !fitsAfter && fitsBefore) dir = 'top';
208
+ else if (dir === 'top' && !fitsBefore && fitsAfter) dir = 'bottom';
209
+ else if (dir === 'right' && !fitsAfter && fitsBefore) dir = 'left';
210
+ else if (dir === 'left' && !fitsBefore && fitsAfter) dir = 'right';
211
+
212
+ let left, top;
213
+ if (dir === 'bottom' || dir === 'top') {
214
+ left = rect.left + rect.width / 2 - bw / 2;
215
+ top = dir === 'bottom' ? rect.bottom + GAP : rect.top - GAP - bh;
216
+ } else {
217
+ left = dir === 'right' ? rect.right + GAP : rect.left - GAP - bw;
218
+ top = rect.top + rect.height / 2 - bh / 2;
219
+ }
220
+
221
+ left = clamp(left, MARGIN, Math.max(MARGIN, vw - bw - MARGIN));
222
+ top = clamp(top, MARGIN, Math.max(MARGIN, vh - bh - MARGIN));
223
+
224
+ els.bubble.style.left = left + 'px';
225
+ els.bubble.style.top = top + 'px';
226
+
227
+ // 箭头
228
+ els.arrow.className = 'tour-bubble-arrow is-' + dir;
229
+ if (dir === 'bottom' || dir === 'top') {
230
+ const centerX = rect.left + rect.width / 2;
231
+ if (centerX < left + 16 || centerX > left + bw - 16) els.arrow.classList.add('is-hidden');
232
+ else { els.arrow.style.left = (centerX - left - 8) + 'px'; els.arrow.style.top = ''; }
233
+ } else {
234
+ const centerY = rect.top + rect.height / 2;
235
+ if (centerY < top + 16 || centerY > top + bh - 16) els.arrow.classList.add('is-hidden');
236
+ else { els.arrow.style.top = (centerY - top - 8) + 'px'; els.arrow.style.left = ''; }
237
+ }
238
+ }
239
+
240
+ /** 重新量一遍当前步的锚点并摆好高亮框和气泡(resize / scroll 时也走这里) */
241
+ function reposition() {
242
+ const step = state.steps[state.index];
243
+ if (!step) return;
244
+ const targets = resolveTargets(step);
245
+ if (!targets.length) return;
246
+
247
+ const rect = unionRect(targets);
248
+ els.spotlight.style.left = (rect.left - PAD) + 'px';
249
+ els.spotlight.style.top = (rect.top - PAD) + 'px';
250
+ els.spotlight.style.width = (rect.width + PAD * 2) + 'px';
251
+ els.spotlight.style.height = (rect.height + PAD * 2) + 'px';
252
+
253
+ place({
254
+ left: rect.left - PAD,
255
+ top: rect.top - PAD,
256
+ right: rect.right + PAD,
257
+ bottom: rect.bottom + PAD,
258
+ width: rect.width + PAD * 2,
259
+ height: rect.height + PAD * 2
260
+ }, step.placement);
261
+ }
262
+
263
+ // ── 步骤切换 ──────────────────────────────────────────
264
+ function go(index) {
265
+ if (index < 0) return;
266
+ // 一条都没真正展示过就走到头,说明是异常情况(锚点全都量不到),
267
+ // 别把"已看过"记下来,否则用户会白白错过这次引导
268
+ if (index >= state.steps.length) return stop(state.shown > 0);
269
+
270
+ state.index = index;
271
+ const step = state.steps[index];
272
+ const targets = resolveTargets(step);
273
+
274
+ // 走到这一步时锚点没了(比如中途切了页面),跳过它继续往下
275
+ if (!targets.length) return go(index + 1);
276
+ state.shown++;
277
+
278
+ targets[0].scrollIntoView({ block: 'nearest', inline: 'nearest' });
279
+
280
+ els.stepIndex.textContent = `第 ${index + 1} 步 / 共 ${state.steps.length} 步`;
281
+ els.title.textContent = step.title;
282
+ els.body.innerHTML = step.body;
283
+ els.prev.hidden = index === 0;
284
+ els.next.textContent = index === state.steps.length - 1 ? '开始使用' : '下一步';
285
+
286
+ reposition();
287
+ els.next.focus();
288
+ }
289
+
290
+ function onKeyDown(e) {
291
+ if (!state.active) return;
292
+ if (e.key === 'Escape') { e.preventDefault(); stop(true); }
293
+ else if (e.key === 'ArrowRight') { e.preventDefault(); go(state.index + 1); }
294
+ else if (e.key === 'ArrowLeft') { e.preventDefault(); if (state.index > 0) go(state.index - 1); }
295
+ else if (e.key === 'Tab') {
296
+ // 焦点锁在气泡内,别让 Tab 跑到被遮住的界面上
297
+ const focusable = Array.from(els.bubble.querySelectorAll('button')).filter(b => !b.hidden);
298
+ if (!focusable.length) return;
299
+ const first = focusable[0];
300
+ const last = focusable[focusable.length - 1];
301
+ if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
302
+ else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
303
+ }
304
+ }
305
+
306
+ // ── 启停 ──────────────────────────────────────────────
307
+ function start() {
308
+ if (state.active) return;
309
+
310
+ const steps = STEPS.filter(stepExists);
311
+ if (!steps.length) return; // 界面还没就绪到能引导的程度,安静退出
312
+
313
+ state.active = true;
314
+ state.steps = steps;
315
+ state.index = 0;
316
+ state.shown = 0;
317
+ state.lastFocus = document.activeElement;
318
+
319
+ buildDom();
320
+ document.addEventListener('keydown', onKeyDown, true);
321
+ state.reposition = () => { if (state.active) reposition(); };
322
+ window.addEventListener('resize', state.reposition);
323
+ window.addEventListener('scroll', state.reposition, true); // capture:侧栏树自己也会滚
324
+
325
+ go(0);
326
+ }
327
+
328
+ /** persist=true 表示这是用户主动看完/跳过,记下来下次不再自动弹 */
329
+ function stop(persist) {
330
+ if (!state.active) return;
331
+ state.active = false;
332
+
333
+ document.removeEventListener('keydown', onKeyDown, true);
334
+ window.removeEventListener('resize', state.reposition);
335
+ window.removeEventListener('scroll', state.reposition, true);
336
+ state.reposition = null;
337
+
338
+ teardownDom();
339
+
340
+ if (persist) {
341
+ try { tourStorage.setItem(SEEN_KEY, TOUR_VERSION); } catch (err) { /* 隐私模式下写不进去,忽略 */ }
342
+ }
343
+ if (state.lastFocus && state.lastFocus.focus) state.lastFocus.focus();
344
+ state.lastFocus = null;
345
+ }
346
+
347
+ function reset() {
348
+ try { tourStorage.removeItem(SEEN_KEY); } catch (err) { /* 同上 */ }
349
+ }
350
+
351
+ // ── 就绪等待 ──────────────────────────────────────────
352
+ // 导航树要等 nav-tree.json 拉完才有内容,Agent 面板要等 agent-panel.js 建完 DOM。
353
+ // 用轮询而不是去改那两处现有代码派发事件,保持零侵入;超时也照常开场(步骤会自动过滤)。
354
+ // 这里刻意用 setTimeout 而不是 requestAnimationFrame:后台标签页里 rAF 会被完全冻结,
355
+ // 连超时都不会推进,工作台在后台标签打开时引导就永远不会出现。
356
+ // 标签页在后台时不开场:一来用户根本没在看,白白消耗掉唯一一次首开引导;
357
+ // 二来后台标签的布局可能量到 0 宽高,会把步骤误判成"锚点不可见"而跳过。
358
+ // 加超时兜底:个别嵌入式浏览器会一直报 hidden,不能让引导永远卡在这儿等。
359
+ // 超时后照常开场也是安全的 —— 步骤清单按"存在"过滤,且一条都没展示成功时不会记"已看过"。
360
+ function waitVisible() {
361
+ if (document.visibilityState !== 'hidden') return Promise.resolve();
362
+ return new Promise(resolve => {
363
+ const timer = setTimeout(finish, VISIBLE_TIMEOUT);
364
+ function finish() {
365
+ clearTimeout(timer);
366
+ document.removeEventListener('visibilitychange', onChange);
367
+ resolve();
368
+ }
369
+ function onChange() { if (document.visibilityState !== 'hidden') finish(); }
370
+ document.addEventListener('visibilitychange', onChange);
371
+ });
372
+ }
373
+
374
+ function waitReady() {
375
+ return new Promise(resolve => {
376
+ const t0 = Date.now();
377
+ (function tick() {
378
+ const treeReady = !!document.querySelector('#sidebarTree .file-row, #sidebarTree .folder');
379
+ const agentReady = !!document.getElementById('agentInput');
380
+ if ((treeReady && agentReady) || Date.now() - t0 > READY_TIMEOUT) return resolve();
381
+ setTimeout(tick, 100);
382
+ })();
383
+ });
384
+ }
385
+
386
+ // ── 重放入口 ──────────────────────────────────────────
387
+ // 外壳 HTML 是冻结的,所以这个按钮在运行时注入到侧栏标题行(.copy-address-btn 旁边)。
388
+ function injectReplayButton() {
389
+ const row = document.querySelector('.sidebar-title-row');
390
+ if (!row || row.querySelector('.tour-replay-btn')) return;
391
+ const btn = document.createElement('button');
392
+ btn.className = 'tour-replay-btn';
393
+ btn.type = 'button';
394
+ btn.textContent = '?';
395
+ btn.title = '重新看一遍新手引导';
396
+ btn.setAttribute('aria-label', '重新看一遍新手引导');
397
+ btn.addEventListener('click', start);
398
+ row.appendChild(btn);
399
+ }
400
+
401
+ // ── 入口 ──────────────────────────────────────────────
402
+ async function init() {
403
+ injectReplayButton();
404
+
405
+ if (new URLSearchParams(window.location.search).get('tour') === 'off') return;
406
+ let seen = null;
407
+ try { seen = tourStorage.getItem(SEEN_KEY); } catch (err) { return; }
408
+ if (seen === TOUR_VERSION) return;
409
+
410
+ await waitVisible();
411
+ await waitReady();
412
+ start();
413
+ }
414
+
415
+ window.ProtoTour = { start, stop: () => stop(false), reset };
416
+
417
+ if (document.readyState === 'loading') {
418
+ document.addEventListener('DOMContentLoaded', init);
419
+ } else {
420
+ init();
421
+ }
422
+ })();
@@ -88,6 +88,7 @@ function preserveTreeOrder(nodes, previousNodes) {
88
88
  (previousNodes || []).forEach((previousNode) => {
89
89
  const node = currentByKey.get(nodeKey(previousNode));
90
90
  if (!node) return;
91
+ if (node.file && previousNode.title) node.title = previousNode.title;
91
92
  ordered.push(node);
92
93
  currentByKey.delete(nodeKey(previousNode));
93
94
  });