openprototype 0.2.1 → 1.0.1

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.
@@ -285,6 +285,29 @@ body.is-resizing-sidebar .preview-frame {
285
285
  .folder.collapsed > .folder-head .folder-arrow { transform: rotate(-90deg); }
286
286
  .folder-icon { color: #f5a400; flex-shrink: 0; }
287
287
  .folder-icon svg { width: 13px; height: 13px; fill: currentColor; display: block; }
288
+ .folder-name {
289
+ flex: 1;
290
+ min-width: 0;
291
+ overflow: hidden;
292
+ text-overflow: ellipsis;
293
+ white-space: nowrap;
294
+ }
295
+ .tree-add-btn {
296
+ flex-shrink: 0;
297
+ height: 17px;
298
+ padding: 0 4px;
299
+ border: 1px solid #d8dfe9;
300
+ border-radius: 3px;
301
+ background: #fff;
302
+ color: #8a94a6;
303
+ font-size: 10px;
304
+ font-weight: 400;
305
+ line-height: 15px;
306
+ cursor: pointer;
307
+ visibility: hidden;
308
+ }
309
+ .folder-head:hover .tree-add-btn { visibility: visible; }
310
+ .tree-add-btn:hover { border-color: #1677ff; color: #1677ff; background: #f0f5ff; }
288
311
 
289
312
  /* ── File row ── */
290
313
  .file-row {
@@ -403,6 +426,43 @@ body.is-resizing-sidebar .preview-frame {
403
426
  }
404
427
  .toast.show { opacity: 1; }
405
428
 
429
+ /* ── Create modal ── */
430
+ .create-modal-mask {
431
+ position: fixed;
432
+ inset: 0;
433
+ background: rgba(15, 23, 42, 0.35);
434
+ display: none;
435
+ align-items: center;
436
+ justify-content: center;
437
+ z-index: 10000;
438
+ }
439
+ .create-modal-mask.show { display: flex; }
440
+ .create-modal {
441
+ width: 320px;
442
+ background: #fff;
443
+ border-radius: 10px;
444
+ box-shadow: 0 12px 40px rgba(15, 23, 42, 0.18);
445
+ padding: 16px;
446
+ }
447
+ .create-modal-title { font-size: 14px; font-weight: 600; margin-bottom: 4px; }
448
+ .create-modal-location { font-size: 11px; color: #7b8495; margin-bottom: 12px; word-break: break-all; }
449
+ .create-modal-field { margin-bottom: 10px; }
450
+ .create-modal-field label { display: block; font-size: 11px; color: #4f5665; margin-bottom: 4px; }
451
+ .create-modal-field input {
452
+ width: 100%;
453
+ border: 1px solid #dfe5ee;
454
+ border-radius: 4px;
455
+ padding: 5px 8px;
456
+ font-size: 12px;
457
+ color: #20242d;
458
+ outline: none;
459
+ }
460
+ .create-modal-field input:focus { border-color: #1677ff; }
461
+ .create-modal-error { font-size: 11px; color: #d91f2f; min-height: 15px; margin-bottom: 6px; }
462
+ .create-modal-actions { display: flex; justify-content: flex-end; gap: 8px; }
463
+ .create-modal-actions .btn { padding: 4px 14px; font-size: 12px; }
464
+ .create-modal-actions .btn-primary { margin-left: 0; }
465
+
406
466
  /* ── Version badge ── */
407
467
  .version-badge {
408
468
  flex-shrink: 0;
@@ -482,6 +542,8 @@ body.is-resizing-sidebar .preview-frame {
482
542
  </label>
483
543
  <button class="btn" id="expandAllBtn">全部展开</button>
484
544
  <button class="btn" id="collapseAllBtn">全部折叠</button>
545
+ <button class="btn" id="newFolderBtn">新建文件夹</button>
546
+ <button class="btn" id="newPageBtn">新建页面</button>
485
547
  </div>
486
548
  </div>
487
549
 
@@ -502,6 +564,27 @@ body.is-resizing-sidebar .preview-frame {
502
564
  <iframe class="preview-frame" id="previewFrame" style="display:none"></iframe>
503
565
  </div>
504
566
 
567
+ <!-- ═══ CREATE MODAL ═══ -->
568
+ <div class="create-modal-mask" id="createModalMask">
569
+ <div class="create-modal" role="dialog" aria-modal="true" aria-labelledby="createModalTitle">
570
+ <div class="create-modal-title" id="createModalTitle">新建页面</div>
571
+ <div class="create-modal-location" id="createModalLocation"></div>
572
+ <div class="create-modal-field">
573
+ <label for="createNameInput">名称(作为文件 / 目录名,支持中文、字母、数字、_ 和 -)</label>
574
+ <input id="createNameInput" type="text" placeholder="如 order_list" autocomplete="off">
575
+ </div>
576
+ <div class="create-modal-field" id="createTitleField">
577
+ <label for="createTitleInput">页面标题(可选,用于页面 &lt;title&gt; 与 PRD)</label>
578
+ <input id="createTitleInput" type="text" placeholder="如 订单列表" autocomplete="off">
579
+ </div>
580
+ <div class="create-modal-error" id="createModalError"></div>
581
+ <div class="create-modal-actions">
582
+ <button class="btn" id="createCancelBtn" type="button">取消</button>
583
+ <button class="btn btn-primary" id="createConfirmBtn" type="button">创建</button>
584
+ </div>
585
+ </div>
586
+ </div>
587
+
505
588
  <div class="toast" id="toast"></div>
506
589
 
507
590
  <script>
@@ -918,7 +1001,7 @@ function applyTitleSearch() {
918
1001
  // ─────────────────────────────────────────────
919
1002
  let totalCount = 0;
920
1003
 
921
- function renderNodes(nodes, depth) {
1004
+ function renderNodes(nodes, depth, trail) {
922
1005
  const wrap = document.createElement('div');
923
1006
  wrap.style.paddingLeft = depth === 0 ? '0' : '14px';
924
1007
 
@@ -953,17 +1036,25 @@ function renderNodes(nodes, depth) {
953
1036
 
954
1037
  wrap.appendChild(row);
955
1038
  } else {
1039
+ const folderKey = trail ? trail + '/' + node.name : node.name;
956
1040
  const folder = document.createElement('div');
957
1041
  folder.className = 'folder';
958
1042
  folder.dataset.searchText = node.name;
1043
+ folder.dataset.pathKey = folderKey;
959
1044
 
960
1045
  const head = document.createElement('div');
961
1046
  head.className = 'folder-head';
962
- head.innerHTML = `<span class="folder-arrow">${I_ARROW}</span><span class="folder-icon">${I_FOLDER}</span><span>${node.name}</span>`;
1047
+ head.innerHTML = `<span class="folder-arrow">${I_ARROW}</span><span class="folder-icon">${I_FOLDER}</span><span class="folder-name">${node.name}</span><button type="button" class="tree-add-btn" data-create="page" title="在此文件夹新建页面">+页</button><button type="button" class="tree-add-btn" data-create="folder" title="在此文件夹新建子文件夹">+夹</button>`;
963
1048
  head.addEventListener('click', () => folder.classList.toggle('collapsed'));
1049
+ head.querySelectorAll('.tree-add-btn').forEach(btn => {
1050
+ btn.addEventListener('click', e => {
1051
+ e.stopPropagation();
1052
+ openCreateModal(btn.dataset.create, folderKey);
1053
+ });
1054
+ });
964
1055
 
965
1056
  folder.appendChild(head);
966
- folder.appendChild(renderNodes(node.children || [], depth + 1));
1057
+ folder.appendChild(renderNodes(node.children || [], depth + 1, folderKey));
967
1058
  folder.classList.add('folder-children-wrap');
968
1059
 
969
1060
  // wrap children into .folder-children div for collapse
@@ -977,6 +1068,100 @@ function renderNodes(nodes, depth) {
977
1068
  return wrap;
978
1069
  }
979
1070
 
1071
+ // 重建整棵树;重渲染时保留折叠状态与当前选中页
1072
+ function renderTree() {
1073
+ const treeWrap = document.getElementById('sidebarTree');
1074
+ const collapsedKeys = new Set(
1075
+ Array.from(treeWrap.querySelectorAll('.folder.collapsed')).map(f => f.dataset.pathKey)
1076
+ );
1077
+ const activePath = activeRow ? activeRow.dataset.path : '';
1078
+ totalCount = 0;
1079
+ Object.keys(breadcrumbMap).forEach(key => delete breadcrumbMap[key]);
1080
+ buildBreadcrumbs(TREE, '');
1081
+ treeWrap.replaceChildren(renderNodes(TREE, 0, ''));
1082
+ treeWrap.querySelectorAll('.folder').forEach(f => {
1083
+ if (collapsedKeys.has(f.dataset.pathKey)) f.classList.add('collapsed');
1084
+ });
1085
+ activeRow = null;
1086
+ if (activePath) {
1087
+ const row = treeWrap.querySelector(`.file-row[data-path="${CSS.escape(activePath)}"]`);
1088
+ if (row) { row.classList.add('active'); activeRow = row; }
1089
+ }
1090
+ document.getElementById('totalCount').textContent = totalCount;
1091
+ applyTitleSearch();
1092
+ updateStats();
1093
+ }
1094
+
1095
+ // ─────────────────────────────────────────────
1096
+ // Create folder / page
1097
+ // ─────────────────────────────────────────────
1098
+ const PAGE_BASE = decodeURIComponent(new URL('.', window.location.href).pathname).replace(/\/$/, '');
1099
+ let createModalState = null;
1100
+
1101
+ function openCreateModal(type, parentPath) {
1102
+ createModalState = { type, parentPath: parentPath || '' };
1103
+ document.getElementById('createModalTitle').textContent = type === 'folder' ? '新建文件夹' : '新建页面';
1104
+ document.getElementById('createModalLocation').textContent = '位置:' + (parentPath ? parentPath + '/' : '根目录');
1105
+ document.getElementById('createTitleField').style.display = type === 'page' ? '' : 'none';
1106
+ document.getElementById('createNameInput').value = '';
1107
+ document.getElementById('createTitleInput').value = '';
1108
+ document.getElementById('createModalError').textContent = '';
1109
+ document.getElementById('createModalMask').classList.add('show');
1110
+ document.getElementById('createNameInput').focus();
1111
+ }
1112
+
1113
+ function closeCreateModal() {
1114
+ createModalState = null;
1115
+ document.getElementById('createModalMask').classList.remove('show');
1116
+ }
1117
+
1118
+ function expandFolderTrail(key) {
1119
+ document.querySelectorAll('.folder').forEach(f => {
1120
+ const k = f.dataset.pathKey || '';
1121
+ if (k === key || key.startsWith(k + '/')) f.classList.remove('collapsed');
1122
+ });
1123
+ }
1124
+
1125
+ async function submitCreateModal() {
1126
+ if (!createModalState) return;
1127
+ const { type, parentPath } = createModalState;
1128
+ const errorEl = document.getElementById('createModalError');
1129
+ const name = document.getElementById('createNameInput').value.trim();
1130
+ if (!name) { errorEl.textContent = '请输入名称'; return; }
1131
+ if (!/^[\w一-龥-]+$/.test(name)) {
1132
+ errorEl.textContent = '名称只能包含中文、字母、数字、下划线或短横线';
1133
+ return;
1134
+ }
1135
+ const confirmBtn = document.getElementById('createConfirmBtn');
1136
+ confirmBtn.disabled = true;
1137
+ errorEl.textContent = '';
1138
+ try {
1139
+ const payload = { base: PAGE_BASE, parent: parentPath, name };
1140
+ if (type === 'page') payload.title = document.getElementById('createTitleInput').value.trim();
1141
+ const res = await fetch(type === 'folder' ? '/api/create-folder' : '/api/create-page', {
1142
+ method: 'POST',
1143
+ headers: { 'Content-Type': 'application/json' },
1144
+ body: JSON.stringify(payload)
1145
+ });
1146
+ const data = await res.json().catch(() => ({}));
1147
+ if (!res.ok || !data.ok) throw new Error(data.error || '创建失败:' + res.status);
1148
+ closeCreateModal();
1149
+ await loadTree();
1150
+ renderTree();
1151
+ if (parentPath) expandFolderTrail(parentPath);
1152
+ showToast((type === 'folder' ? '文件夹已创建:' : '页面已创建:') + data.path);
1153
+ if (type === 'page') {
1154
+ const row = document.querySelector(`.file-row[data-path="${CSS.escape(data.path)}"]`);
1155
+ if (row) loadPreview(data.path, row);
1156
+ }
1157
+ fetchAllVersions();
1158
+ } catch (err) {
1159
+ errorEl.textContent = err.message;
1160
+ } finally {
1161
+ confirmBtn.disabled = false;
1162
+ }
1163
+ }
1164
+
980
1165
  // ─────────────────────────────────────────────
981
1166
  // Stats
982
1167
  // ─────────────────────────────────────────────
@@ -1017,8 +1202,6 @@ window.addEventListener('DOMContentLoaded', async () => {
1017
1202
  document.getElementById('sidebarTree').textContent = '页面树加载失败:' + e.message;
1018
1203
  return;
1019
1204
  }
1020
- buildBreadcrumbs(TREE, '');
1021
-
1022
1205
  const savedVer = navStorage.getItem(VERSION_KEY);
1023
1206
  if (savedVer) document.getElementById('versionInput').value = savedVer;
1024
1207
  const versionInput = document.getElementById('versionInput');
@@ -1038,9 +1221,7 @@ window.addEventListener('DOMContentLoaded', async () => {
1038
1221
  document.getElementById('navSearchInput').addEventListener('input', applyTitleSearch);
1039
1222
 
1040
1223
  const treeWrap = document.getElementById('sidebarTree');
1041
- treeWrap.appendChild(renderNodes(TREE, 0));
1042
- document.getElementById('totalCount').textContent = totalCount;
1043
- updateStats();
1224
+ renderTree();
1044
1225
 
1045
1226
  // version filter: re-evaluate all badges on input change
1046
1227
  document.getElementById('versionInput').addEventListener('input', () => {
@@ -1071,6 +1252,21 @@ window.addEventListener('DOMContentLoaded', async () => {
1071
1252
  copyText(window.location.href, '本页地址已复制到剪贴板');
1072
1253
  });
1073
1254
 
1255
+ // 新建文件夹 / 页面
1256
+ document.getElementById('newFolderBtn').addEventListener('click', () => openCreateModal('folder', ''));
1257
+ document.getElementById('newPageBtn').addEventListener('click', () => openCreateModal('page', ''));
1258
+ document.getElementById('createCancelBtn').addEventListener('click', closeCreateModal);
1259
+ document.getElementById('createConfirmBtn').addEventListener('click', submitCreateModal);
1260
+ document.getElementById('createModalMask').addEventListener('click', e => {
1261
+ if (e.target === e.currentTarget) closeCreateModal();
1262
+ });
1263
+ [document.getElementById('createNameInput'), document.getElementById('createTitleInput')].forEach(input => {
1264
+ input.addEventListener('keydown', e => {
1265
+ if (e.key === 'Enter') { e.preventDefault(); submitCreateModal(); }
1266
+ else if (e.key === 'Escape') closeCreateModal();
1267
+ });
1268
+ });
1269
+
1074
1270
  });
1075
1271
  </script>
1076
1272
  <!-- agent-panel:start (本地开发专用;发布时可由 openprototype publish 自动剥离) -->
package/runtime/server.js CHANGED
@@ -146,6 +146,178 @@ function handleSavePrd(req, res) {
146
146
  });
147
147
  }
148
148
 
149
+ // ── 树节点创建(文件夹 / 页面)─────────────────────────
150
+ const NAME_SEGMENT_RE = /^[A-Za-z0-9_\-一-龥]+$/;
151
+
152
+ function assertValidSegment(name, label) {
153
+ if (!NAME_SEGMENT_RE.test(String(name || ''))) {
154
+ throw new Error(`${label}只能包含中文、字母、数字、下划线或短横线`);
155
+ }
156
+ }
157
+
158
+ /** base 必须是已注册产品的入口目录(nav-tree.json 所在目录) */
159
+ function resolveProductRootDir(basePath) {
160
+ const resolved = path.resolve(ROOT_DIR, '.' + String(basePath || '').replace(/\/+$/, ''));
161
+ const root = AGENT_WRITE_ROOTS.find((dir) => dir === resolved);
162
+ if (!root) throw new Error('base 必须是已注册产品的入口目录(见 proto-kit.config.json)');
163
+ return root;
164
+ }
165
+
166
+ function resolveParentDir(rootDir, parent) {
167
+ const relParent = String(parent || '').replace(/^\/+|\/+$/g, '');
168
+ if (!relParent) return { dir: rootDir, rel: '' };
169
+ const segments = relParent.split('/');
170
+ segments.forEach((seg) => assertValidSegment(seg, '父目录名'));
171
+ const dir = path.join(rootDir, ...segments);
172
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new Error('父目录不存在');
173
+ return { dir, rel: segments.join('/') };
174
+ }
175
+
176
+ function compareNavNodes(a, b) {
177
+ const aIsFolder = !!a.children;
178
+ const bIsFolder = !!b.children;
179
+ if (aIsFolder !== bIsFolder) return aIsFolder ? -1 : 1;
180
+ return (a.name || a.file).localeCompare(b.name || b.file, 'zh-Hans-CN');
181
+ }
182
+
183
+ function loadNavTree(rootDir) {
184
+ const file = path.join(rootDir, 'nav-tree.json');
185
+ if (!fs.existsSync(file)) return [];
186
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
187
+ }
188
+
189
+ function saveNavTree(rootDir, tree) {
190
+ fs.writeFileSync(path.join(rootDir, 'nav-tree.json'), JSON.stringify(tree, null, 2) + '\n');
191
+ }
192
+
193
+ /** 沿 relParent 逐级找到(必要时创建)文件夹节点,返回其 children 数组 */
194
+ function ensureNavFolder(tree, relParent) {
195
+ let level = tree;
196
+ if (!relParent) return level;
197
+ for (const name of relParent.split('/')) {
198
+ let node = level.find((n) => n.children && n.name === name);
199
+ if (!node) {
200
+ node = { name, children: [] };
201
+ level.push(node);
202
+ level.sort(compareNavNodes);
203
+ }
204
+ level = node.children;
205
+ }
206
+ return level;
207
+ }
208
+
209
+ function todayString() {
210
+ const now = new Date();
211
+ const pad = (n) => String(n).padStart(2, '0');
212
+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
213
+ }
214
+
215
+ function buildPageStub(title) {
216
+ return `<!DOCTYPE html>
217
+ <html lang="zh-CN">
218
+ <head>
219
+ <meta charset="UTF-8">
220
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
221
+ <title>${title}</title>
222
+ <style>
223
+ *, *::before, *::after { box-sizing: border-box; }
224
+ body {
225
+ margin: 0;
226
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', 'PingFang SC', 'Hiragino Sans GB', sans-serif;
227
+ font-size: 13px; color: #20242d; background: #f3f5f8; padding: 20px;
228
+ }
229
+ .page-title { font-size: 18px; font-weight: 600; margin: 0 0 16px; }
230
+ .panel { background: #fff; border: 1px solid #e6ebf2; border-radius: 8px; padding: 20px; }
231
+ .placeholder { color: #7b8495; margin: 0; }
232
+ </style>
233
+ </head>
234
+ <body>
235
+ <h1 class="page-title">${title}</h1>
236
+ <div class="panel">
237
+ <p class="placeholder">「${title}」原型待完善:可直接编辑本文件,或在导航页选中该页面后通过右侧 Agent 生成内容。</p>
238
+ </div>
239
+ </body>
240
+ </html>
241
+ `;
242
+ }
243
+
244
+ function buildPrdStub(title, fileName) {
245
+ return `# ${title} PRD
246
+
247
+ ## 一、页面信息
248
+
249
+ | 项 | 内容 |
250
+ |----|------|
251
+ | 页面名称 | ${title} |
252
+ | 页面文件 | ${fileName} |
253
+
254
+ ## 二、需求说明
255
+
256
+ (待补充)
257
+
258
+ ## 修订记录
259
+
260
+ | 版本 | 日期 | 修订人 | 说明 |
261
+ |------|------|--------|------|
262
+ | V1.0.0 | ${todayString()} | | 新建页面 |
263
+ `;
264
+ }
265
+
266
+ function handleCreateFolder(req, res) {
267
+ readJsonBody(req, 32 * 1024, (parseErr, data) => {
268
+ try {
269
+ if (parseErr) throw parseErr;
270
+ const rootDir = resolveProductRootDir(data.base);
271
+ const { dir: parentDir, rel: parentRel } = resolveParentDir(rootDir, data.parent);
272
+ const name = String(data.name || '').trim();
273
+ assertValidSegment(name, '文件夹名');
274
+ const dir = path.join(parentDir, name);
275
+ if (fs.existsSync(dir)) throw new Error('同名文件或文件夹已存在');
276
+ fs.mkdirSync(dir);
277
+ const relPath = parentRel ? `${parentRel}/${name}` : name;
278
+ const tree = loadNavTree(rootDir);
279
+ ensureNavFolder(tree, relPath);
280
+ saveNavTree(rootDir, tree);
281
+ console.log(`[200] POST /api/create-folder -> ${dir}`);
282
+ sendJson(res, 200, { ok: true, path: relPath });
283
+ } catch (err) {
284
+ console.log(`[400] POST /api/create-folder -> ${err.message}`);
285
+ sendJson(res, 400, { ok: false, error: err.message });
286
+ }
287
+ });
288
+ }
289
+
290
+ function handleCreatePage(req, res) {
291
+ readJsonBody(req, 64 * 1024, (parseErr, data) => {
292
+ try {
293
+ if (parseErr) throw parseErr;
294
+ const rootDir = resolveProductRootDir(data.base);
295
+ const { dir: parentDir, rel: parentRel } = resolveParentDir(rootDir, data.parent);
296
+ const name = String(data.name || '').trim().replace(/\.html$/i, '');
297
+ assertValidSegment(name, '页面名');
298
+ const title = String(data.title || '').trim() || name;
299
+ const htmlFile = path.join(parentDir, `${name}.html`);
300
+ const mdFile = path.join(parentDir, `${name}.md`);
301
+ if (fs.existsSync(htmlFile)) throw new Error('同名页面已存在');
302
+ fs.writeFileSync(htmlFile, buildPageStub(title));
303
+ if (!fs.existsSync(mdFile)) fs.writeFileSync(mdFile, buildPrdStub(title, `${name}.html`));
304
+ const relPath = (parentRel ? `${parentRel}/` : '') + `${name}.html`;
305
+ const tree = loadNavTree(rootDir);
306
+ const children = ensureNavFolder(tree, parentRel);
307
+ if (!children.some((n) => n.file === `${name}.html`)) {
308
+ children.push({ file: `${name}.html`, path: relPath });
309
+ children.sort(compareNavNodes);
310
+ }
311
+ saveNavTree(rootDir, tree);
312
+ console.log(`[200] POST /api/create-page -> ${htmlFile}`);
313
+ sendJson(res, 200, { ok: true, path: relPath });
314
+ } catch (err) {
315
+ console.log(`[400] POST /api/create-page -> ${err.message}`);
316
+ sendJson(res, 400, { ok: false, error: err.message });
317
+ }
318
+ });
319
+ }
320
+
149
321
  // ── PRD 标红提取 ───────────────────────────────────────
150
322
  function normalizeRedMarkedContent(text) {
151
323
  return String(text || '')
@@ -615,6 +787,8 @@ const server = http.createServer(async (req, res) => {
615
787
  if (await handleAgentApi(req, res, urlPath)) return;
616
788
 
617
789
  if (req.method === 'POST' && urlPath === '/api/save-prd') return requireLoopback(req, res) && handleSavePrd(req, res);
790
+ if (req.method === 'POST' && urlPath === '/api/create-folder') return requireLoopback(req, res) && handleCreateFolder(req, res);
791
+ if (req.method === 'POST' && urlPath === '/api/create-page') return requireLoopback(req, res) && handleCreatePage(req, res);
618
792
  if (req.method === 'POST' && urlPath === '/api/build-update-page-prompt') return requireLoopback(req, res) && handleBuildUpdatePagePrompt(req, res);
619
793
  if (req.method === 'POST' && urlPath === '/api/update-page-from-prd') return requireLoopback(req, res) && handleUpdatePageFromPrd(req, res);
620
794
 
@@ -57,6 +57,12 @@
57
57
  .prd-slide-panel.open {
58
58
  transform: translateX(0);
59
59
  }
60
+ /* 样式注入完成的那一帧,transform 会从 none 变为 translateX(100%)。若此时过渡已生效,
61
+ 面板会先整块出现在右侧再滑出去。prd-panel.js 在首帧挂上该类屏蔽过渡,之后再移除。 */
62
+ .prd-float-btn.prd-panel-no-anim,
63
+ .prd-slide-panel.prd-panel-no-anim {
64
+ transition: none;
65
+ }
60
66
  .prd-panel-resizer {
61
67
  position: absolute;
62
68
  left: -3px;
@@ -18,19 +18,56 @@ var PRD_PANEL_MAX_RATIO = 0.86;
18
18
  // 记录本文件自身的 <script src>,用于定位同目录的 prd-panel.css 并自动注入
19
19
  var PRD_PANEL_SCRIPT_SRC = document.currentScript ? document.currentScript.getAttribute('src') : '';
20
20
 
21
+ var PRD_PANEL_NO_ANIM_CLASS = 'prd-panel-no-anim';
22
+
21
23
  function arePrdPanelStylesReady() {
22
24
  var link = document.getElementById('prdPanelStyles');
23
25
  return !!(link && link.sheet);
24
26
  }
25
27
 
28
+ function getPrdPanelChromeElements() {
29
+ return ['prdFloatBtn', 'prdPanel'].map(function(id) {
30
+ return document.getElementById(id);
31
+ }).filter(Boolean);
32
+ }
33
+
34
+ // 样式就绪前先禁用过渡:注入 prd-panel.css 的那一帧 transform 由 none 变为 translateX(100%),
35
+ // 过渡若已生效,浏览器会把这次变化当成动画播放,面板就会闪现在右侧再滑走。
36
+ function preparePrdPanelChrome(element) {
37
+ if (!element) return;
38
+ element.classList.add(PRD_PANEL_NO_ANIM_CLASS);
39
+ hidePrdPanelUntilStylesReady(element);
40
+ }
41
+
42
+ function restorePrdPanelAnimation() {
43
+ var pending = getPrdPanelChromeElements().filter(function(element) {
44
+ return element.classList.contains(PRD_PANEL_NO_ANIM_CLASS);
45
+ });
46
+ if (!pending.length) return;
47
+
48
+ var restore = function() {
49
+ pending.forEach(function(element) {
50
+ // 先读一次布局,确保初始 transform 在过渡恢复前已落定,否则恢复过渡时仍会补出动画
51
+ element.getBoundingClientRect();
52
+ element.classList.remove(PRD_PANEL_NO_ANIM_CLASS);
53
+ });
54
+ };
55
+
56
+ if (window.requestAnimationFrame) {
57
+ window.requestAnimationFrame(restore);
58
+ } else {
59
+ setTimeout(restore, 0);
60
+ }
61
+ }
62
+
26
63
  function revealPrdPanelDom() {
27
- ['prdFloatBtn', 'prdPanel'].forEach(function(id) {
28
- var element = document.getElementById(id);
29
- if (element && element.dataset.prdPanelPending === 'true') {
64
+ getPrdPanelChromeElements().forEach(function(element) {
65
+ if (element.dataset.prdPanelPending === 'true') {
30
66
  element.style.visibility = '';
31
67
  delete element.dataset.prdPanelPending;
32
68
  }
33
69
  });
70
+ restorePrdPanelAnimation();
34
71
  }
35
72
 
36
73
  function hidePrdPanelUntilStylesReady(element) {
@@ -40,17 +77,23 @@ function hidePrdPanelUntilStylesReady(element) {
40
77
  }
41
78
 
42
79
  function ensurePrdPanelStyles() {
43
- var existingLink = document.getElementById('prdPanelStyles');
44
- if (existingLink) return existingLink;
45
- var href = PRD_PANEL_SCRIPT_SRC
46
- ? PRD_PANEL_SCRIPT_SRC.replace(/prd-panel\.js(?:\?.*)?$/, 'prd-panel.css')
47
- : 'common/prd-panel.css';
48
- var link = document.createElement('link');
49
- link.id = 'prdPanelStyles';
50
- link.rel = 'stylesheet';
51
- link.href = href;
52
- link.addEventListener('load', revealPrdPanelDom);
53
- document.head.appendChild(link);
80
+ var link = document.getElementById('prdPanelStyles');
81
+ if (!link) {
82
+ var href = PRD_PANEL_SCRIPT_SRC
83
+ ? PRD_PANEL_SCRIPT_SRC.replace(/prd-panel\.js(?:\?.*)?$/, 'prd-panel.css')
84
+ : 'common/prd-panel.css';
85
+ link = document.createElement('link');
86
+ link.id = 'prdPanelStyles';
87
+ link.rel = 'stylesheet';
88
+ link.href = href;
89
+ document.head.appendChild(link);
90
+ }
91
+ // 已存在的 link 也要绑定:样式可能由页面自己引入,此时同样需要在加载完成后揭示面板
92
+ if (link.dataset.prdPanelBound !== 'true') {
93
+ link.dataset.prdPanelBound = 'true';
94
+ link.addEventListener('load', revealPrdPanelDom);
95
+ link.addEventListener('error', revealPrdPanelDom);
96
+ }
54
97
  return link;
55
98
  }
56
99
 
@@ -138,18 +181,23 @@ function ensurePrdPanelDom() {
138
181
  prdFloatBtn.id = 'prdFloatBtn';
139
182
  prdFloatBtn.className = 'prd-float-btn';
140
183
  prdFloatBtn.textContent = 'PRD';
141
- hidePrdPanelUntilStylesReady(prdFloatBtn);
184
+ preparePrdPanelChrome(prdFloatBtn);
142
185
  document.body.appendChild(prdFloatBtn);
143
186
  }
144
187
 
145
188
  var prdPanel = document.getElementById('prdPanel');
146
189
  if (!prdPanel) {
147
190
  prdPanel = document.createElement('div');
148
- hidePrdPanelUntilStylesReady(prdPanel);
191
+ preparePrdPanelChrome(prdPanel);
149
192
  document.body.appendChild(prdPanel);
150
193
  }
151
194
 
152
- return ensurePrdPanelStructure(prdPanel);
195
+ var structuredPanel = ensurePrdPanelStructure(prdPanel);
196
+ // 样式已就绪(多为缓存命中)时 link 的 load 不会再触发,这里直接恢复过渡
197
+ if (arePrdPanelStylesReady()) {
198
+ revealPrdPanelDom();
199
+ }
200
+ return structuredPanel;
153
201
  }
154
202
 
155
203
  function initPrdPanel() {
@@ -1265,6 +1313,11 @@ function renderMarkdownToHtml(markdown) {
1265
1313
  return html;
1266
1314
  }
1267
1315
 
1316
+ // 解析到本脚本就开始下载样式,而不是等到 DOMContentLoaded,尽量让样式先于面板建好
1317
+ if (document.head) {
1318
+ ensurePrdPanelStyles();
1319
+ }
1320
+
1268
1321
  if (document.readyState === 'loading') {
1269
1322
  document.addEventListener('DOMContentLoaded', function() {
1270
1323
  if (!prdPanelInitialized) {
@@ -31,19 +31,22 @@ function collectRegisteredPaths(nodes, out) {
31
31
  }
32
32
 
33
33
  function listDiskPaths(dir) {
34
- const out = [];
34
+ const files = [];
35
+ const dirs = [];
35
36
  const walk = (p) => {
36
37
  for (const name of fs.readdirSync(p)) {
38
+ if (name.startsWith('.')) continue; // 隐藏目录 / 文件不进导航树
37
39
  const full = path.join(p, name);
38
40
  if (fs.statSync(full).isDirectory()) {
41
+ dirs.push(path.relative(dir, full).split(path.sep).join('/'));
39
42
  walk(full);
40
43
  } else if (name.endsWith('.html') && full !== path.join(dir, 'index.html')) {
41
- out.push(path.relative(dir, full).split(path.sep).join('/'));
44
+ files.push(path.relative(dir, full).split(path.sep).join('/'));
42
45
  }
43
46
  }
44
47
  };
45
48
  walk(dir);
46
- return out.sort((a, b) => a.localeCompare(b, 'zh-Hans-CN'));
49
+ return { files: files.sort((a, b) => a.localeCompare(b, 'zh-Hans-CN')), dirs };
47
50
  }
48
51
 
49
52
  function ensureFolderChildren(tree, folderNames) {
@@ -72,8 +75,10 @@ function sortTree(nodes) {
72
75
  return nodes;
73
76
  }
74
77
 
75
- function buildTree(paths) {
78
+ function buildTree(paths, dirs) {
76
79
  const tree = [];
80
+ // 先登记磁盘上的所有目录(含空目录,保住导航页刚创建、还没放页面的文件夹)
81
+ for (const relDir of dirs || []) ensureFolderChildren(tree, relDir.split('/'));
77
82
  for (const relPath of paths) {
78
83
  const segments = relPath.split('/');
79
84
  const fileName = segments.pop();
@@ -88,9 +93,9 @@ function syncTarget(target) {
88
93
  ? JSON.parse(fs.readFileSync(target.treePath, 'utf8'))
89
94
  : [];
90
95
  const previous = collectRegisteredPaths(previousTree, new Set());
91
- const diskPaths = listDiskPaths(target.dir);
96
+ const { files: diskPaths, dirs } = listDiskPaths(target.dir);
92
97
  const onDisk = new Set(diskPaths);
93
- const tree = buildTree(diskPaths);
98
+ const tree = buildTree(diskPaths, dirs);
94
99
  const next = collectRegisteredPaths(tree, new Set());
95
100
  const added = [...next].filter((p) => !previous.has(p));
96
101
  const removed = [...previous].filter((p) => !onDisk.has(p));