openprototype 0.1.0 → 0.2.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.
Files changed (57) hide show
  1. package/AGENTS.md +58 -0
  2. package/CONVENTIONS.md +54 -0
  3. package/LICENSE +21 -0
  4. package/README.md +234 -3
  5. package/bin/cli.js +297 -0
  6. package/lib/config.js +162 -0
  7. package/package.json +32 -10
  8. package/product/demo/pc/customer/customer_form.html +137 -0
  9. package/product/demo/pc/customer/customer_form.md +33 -0
  10. package/product/demo/pc/customer/customer_list.html +132 -0
  11. package/product/demo/pc/customer/customer_list.md +35 -0
  12. package/product/demo/pc/demo-data.js +23 -0
  13. package/product/demo/pc/index.html +1082 -0
  14. package/product/demo/pc/nav-tree.json +15 -0
  15. package/proto-kit.config.json +13 -0
  16. package/runtime/server.js +664 -0
  17. package/runtime/shared/ai-polish.js +159 -0
  18. package/runtime/shared/base-manager.js +168 -0
  19. package/runtime/shared/common/component-renderer.js +917 -0
  20. package/runtime/shared/common/copy-manager.js +134 -0
  21. package/runtime/shared/common/data-bridge.js +45 -0
  22. package/runtime/shared/common/form-renderer.js +211 -0
  23. package/runtime/shared/common/form.js +357 -0
  24. package/runtime/shared/common/formatter.js +78 -0
  25. package/runtime/shared/common/index.js +37 -0
  26. package/runtime/shared/common/line-chart.js +357 -0
  27. package/runtime/shared/common/modal-manager.js +82 -0
  28. package/runtime/shared/common/prd-panel.css +395 -0
  29. package/runtime/shared/common/prd-panel.js +1280 -0
  30. package/runtime/shared/common/prd-popup.js +168 -0
  31. package/runtime/shared/common/search-renderer.js +95 -0
  32. package/runtime/shared/common/table-renderer.js +177 -0
  33. package/runtime/shared/common/table.js +160 -0
  34. package/runtime/shared/common/toast.js +99 -0
  35. package/runtime/shared/common/ui-preference-manager.js +74 -0
  36. package/runtime/shared/common/view-mode.js +30 -0
  37. package/runtime/shared/common.js +43 -0
  38. package/runtime/shared/constants/icons.js +28 -0
  39. package/runtime/shared/constants/status.js +67 -0
  40. package/runtime/shared/libs/marked.min.js +69 -0
  41. package/runtime/shared/prd-content.js +9 -0
  42. package/runtime/shared/styles.css +7673 -0
  43. package/runtime/shared/utils.js +110 -0
  44. package/runtime/shared/view-controls.js +148 -0
  45. package/runtime/shell/agent-panel.css +429 -0
  46. package/runtime/shell/agent-panel.js +629 -0
  47. package/scripts/check/run-checks.js +58 -0
  48. package/scripts/check/smoke-test.js +244 -0
  49. package/scripts/check/static-check.js +248 -0
  50. package/scripts/check/sync-nav-tree.js +139 -0
  51. package/templates/AGENTS.md +58 -0
  52. package/templates/CONVENTIONS.md +54 -0
  53. package/templates/gitignore +12 -0
  54. package/templates/product-shell/index.html +1082 -0
  55. package/templates/skills/auto-test/SKILL.md +62 -0
  56. package/templates/skills/xiaojia/SKILL.md +299 -0
  57. package/cli.js +0 -4
@@ -0,0 +1,1280 @@
1
+ /**
2
+ * PRD 面板模块
3
+ * 管理 PRD 文档的加载、渲染和交互
4
+ */
5
+
6
+ // 页面可在引入本模块前声明这些全局以覆盖默认行为;未声明时使用默认值。
7
+ // PRD_OVERVIEW_VERSION 启用“当前版本”虚拟页签,PRD_WORKSPACE_MAP 配置多文档工作区。
8
+ var PRD_BASE_PATH = typeof PRD_BASE_PATH !== 'undefined' ? PRD_BASE_PATH : './';
9
+ var PRD_FILE_MAP = typeof PRD_FILE_MAP !== 'undefined' ? PRD_FILE_MAP : {};
10
+ var PRD_CACHE = typeof PRD_CACHE !== 'undefined' ? PRD_CACHE : {};
11
+
12
+ var prdPanelInitialized = false;
13
+ var prdPanelWidth = null;
14
+ var PRD_PANEL_DEFAULT_WIDTH = 680;
15
+ var PRD_PANEL_MIN_WIDTH = 360;
16
+ var PRD_PANEL_MAX_RATIO = 0.86;
17
+
18
+ // 记录本文件自身的 <script src>,用于定位同目录的 prd-panel.css 并自动注入
19
+ var PRD_PANEL_SCRIPT_SRC = document.currentScript ? document.currentScript.getAttribute('src') : '';
20
+
21
+ function arePrdPanelStylesReady() {
22
+ var link = document.getElementById('prdPanelStyles');
23
+ return !!(link && link.sheet);
24
+ }
25
+
26
+ function revealPrdPanelDom() {
27
+ ['prdFloatBtn', 'prdPanel'].forEach(function(id) {
28
+ var element = document.getElementById(id);
29
+ if (element && element.dataset.prdPanelPending === 'true') {
30
+ element.style.visibility = '';
31
+ delete element.dataset.prdPanelPending;
32
+ }
33
+ });
34
+ }
35
+
36
+ function hidePrdPanelUntilStylesReady(element) {
37
+ if (!element || arePrdPanelStylesReady()) return;
38
+ element.dataset.prdPanelPending = 'true';
39
+ element.style.visibility = 'hidden';
40
+ }
41
+
42
+ 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);
54
+ return link;
55
+ }
56
+
57
+ function getPrdPanelMaxWidth() {
58
+ return Math.floor(window.innerWidth * PRD_PANEL_MAX_RATIO);
59
+ }
60
+
61
+ function clampPrdPanelWidth(width) {
62
+ width = parseInt(width, 10);
63
+ if (!isFinite(width)) {
64
+ width = PRD_PANEL_DEFAULT_WIDTH;
65
+ }
66
+ return Math.max(PRD_PANEL_MIN_WIDTH, Math.min(getPrdPanelMaxWidth(), width));
67
+ }
68
+
69
+ function applyPrdPanelWidth(prdPanel, width) {
70
+ prdPanelWidth = clampPrdPanelWidth(width);
71
+ prdPanel.style.width = prdPanelWidth + 'px';
72
+ prdPanel.style.minWidth = prdPanelWidth + 'px';
73
+ prdPanel.style.maxWidth = 'none';
74
+ }
75
+
76
+ function ensurePrdPanelStructure(prdPanel) {
77
+ if (!prdPanel) return null;
78
+
79
+ prdPanel.id = 'prdPanel';
80
+ if (!prdPanel.classList.contains('prd-slide-panel')) {
81
+ prdPanel.classList.add('prd-slide-panel');
82
+ }
83
+
84
+ if (!prdPanel.querySelector('.prd-panel-resizer') ||
85
+ !prdPanel.querySelector('#prdPanelTitle') ||
86
+ !prdPanel.querySelector('#prdPanelFileName') ||
87
+ !prdPanel.querySelector('#prdPanelCopyBtn') ||
88
+ !prdPanel.querySelector('#prdPanelEditBtn') ||
89
+ !prdPanel.querySelector('#prdPanelCloseBtn') ||
90
+ !prdPanel.querySelector('#prdPanelTabs') ||
91
+ !prdPanel.querySelector('#prdPanelContent') ||
92
+ !prdPanel.querySelector('#prdPanelEditorWrap')) {
93
+ prdPanel.innerHTML = [
94
+ '<div class="prd-panel-resizer"></div>',
95
+ '<div class="prd-panel-header">',
96
+ ' <div class="prd-panel-header-left">',
97
+ ' <h3 id="prdPanelTitle">PRD文档</h3>',
98
+ ' <span class="prd-panel-file-name" id="prdPanelFileName"></span>',
99
+ ' <button class="prd-panel-copy-btn" id="prdPanelCopyBtn" title="复制 MD 原文">',
100
+ ' <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">',
101
+ ' <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>',
102
+ ' <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>',
103
+ ' </svg>',
104
+ ' </button>',
105
+ ' <button class="prd-panel-edit-btn" id="prdPanelEditBtn" title="编辑 PRD">✎ 编辑</button>',
106
+ ' <span class="prd-panel-toast" id="prdPanelToast"></span>',
107
+ ' </div>',
108
+ ' <button class="prd-panel-close" id="prdPanelCloseBtn">×</button>',
109
+ '</div>',
110
+ '<div class="prd-panel-tabs" id="prdPanelTabs"></div>',
111
+ '<div class="prd-panel-content" id="prdPanelContent"></div>',
112
+ '<div class="prd-panel-editor-wrap" id="prdPanelEditorWrap" style="display:none;">',
113
+ ' <div class="prd-panel-editor-toolbar">',
114
+ ' <button type="button" class="prd-panel-editor-btn" id="prdPanelRedBtn">标红</button>',
115
+ ' <button type="button" class="prd-panel-editor-btn" id="prdPanelUnredBtn">取消标红</button>',
116
+ ' <button type="button" class="prd-panel-editor-btn" id="prdPanelUnredAllBtn">全部取消标红</button>',
117
+ ' <span class="prd-panel-editor-msg" id="prdPanelEditorMsg"></span>',
118
+ ' <span class="prd-panel-editor-spacer"></span>',
119
+ ' <button type="button" class="prd-panel-editor-btn prd-panel-editor-cancel" id="prdPanelCancelBtn">取消</button>',
120
+ ' <button type="button" class="prd-panel-editor-btn prd-panel-editor-save" id="prdPanelSaveBtn">保存</button>',
121
+ ' </div>',
122
+ ' <textarea class="prd-panel-editor-textarea" id="prdPanelEditorTextarea" spellcheck="false"></textarea>',
123
+ '</div>'
124
+ ].join('');
125
+ }
126
+
127
+ return prdPanel;
128
+ }
129
+
130
+ function ensurePrdPanelDom() {
131
+ if (!document.body) return null;
132
+
133
+ ensurePrdPanelStyles();
134
+
135
+ var prdFloatBtn = document.getElementById('prdFloatBtn');
136
+ if (!prdFloatBtn) {
137
+ prdFloatBtn = document.createElement('div');
138
+ prdFloatBtn.id = 'prdFloatBtn';
139
+ prdFloatBtn.className = 'prd-float-btn';
140
+ prdFloatBtn.textContent = 'PRD';
141
+ hidePrdPanelUntilStylesReady(prdFloatBtn);
142
+ document.body.appendChild(prdFloatBtn);
143
+ }
144
+
145
+ var prdPanel = document.getElementById('prdPanel');
146
+ if (!prdPanel) {
147
+ prdPanel = document.createElement('div');
148
+ hidePrdPanelUntilStylesReady(prdPanel);
149
+ document.body.appendChild(prdPanel);
150
+ }
151
+
152
+ return ensurePrdPanelStructure(prdPanel);
153
+ }
154
+
155
+ function initPrdPanel() {
156
+ if (prdPanelInitialized) return;
157
+ // 弹窗页面(prd-popup.js 已接管)跳过,避免覆盖其面板结构
158
+ if (window.__prdPopupReady) return;
159
+
160
+ var prdPanel = ensurePrdPanelDom();
161
+ if (!prdPanel) return;
162
+
163
+ prdPanelInitialized = true;
164
+
165
+ var prdFloatBtn = document.getElementById('prdFloatBtn');
166
+ if (prdFloatBtn) {
167
+ prdFloatBtn.addEventListener('click', togglePrdPanel);
168
+ }
169
+
170
+ var prdPanelCloseBtn = document.getElementById('prdPanelCloseBtn');
171
+ if (prdPanelCloseBtn) {
172
+ prdPanelCloseBtn.addEventListener('click', function() {
173
+ prdPanel.classList.remove('open');
174
+ });
175
+ }
176
+
177
+ var prdPanelCopyBtn = document.getElementById('prdPanelCopyBtn');
178
+ if (prdPanelCopyBtn) {
179
+ prdPanelCopyBtn.addEventListener('click', copyPrdRawContent);
180
+ }
181
+
182
+ var prdPanelEditBtn = document.getElementById('prdPanelEditBtn');
183
+ if (prdPanelEditBtn) {
184
+ prdPanelEditBtn.addEventListener('click', enterPrdEditMode);
185
+ }
186
+
187
+ var prdPanelRedBtn = document.getElementById('prdPanelRedBtn');
188
+ if (prdPanelRedBtn) {
189
+ prdPanelRedBtn.addEventListener('click', applyPrdRedColor);
190
+ }
191
+
192
+ var prdPanelUnredBtn = document.getElementById('prdPanelUnredBtn');
193
+ if (prdPanelUnredBtn) {
194
+ prdPanelUnredBtn.addEventListener('click', removePrdRedColor);
195
+ }
196
+
197
+ var prdPanelUnredAllBtn = document.getElementById('prdPanelUnredAllBtn');
198
+ if (prdPanelUnredAllBtn) {
199
+ prdPanelUnredAllBtn.addEventListener('click', removeAllPrdRedColor);
200
+ }
201
+
202
+ var prdPanelCancelBtn = document.getElementById('prdPanelCancelBtn');
203
+ if (prdPanelCancelBtn) {
204
+ prdPanelCancelBtn.addEventListener('click', exitPrdEditMode);
205
+ }
206
+
207
+ var prdPanelSaveBtn = document.getElementById('prdPanelSaveBtn');
208
+ if (prdPanelSaveBtn) {
209
+ prdPanelSaveBtn.addEventListener('click', savePrdEdits);
210
+ }
211
+
212
+ var savedWidth = localStorage.getItem('prdPanelWidth');
213
+ if (savedWidth) {
214
+ applyPrdPanelWidth(prdPanel, parseInt(savedWidth, 10));
215
+ }
216
+
217
+ var resizeHandle = prdPanel.querySelector('.prd-panel-resizer');
218
+ if (resizeHandle) {
219
+ var isResizing = false;
220
+ resizeHandle.addEventListener('mousedown', function(e) {
221
+ isResizing = true;
222
+ resizeHandle.classList.add('resizing');
223
+ document.body.style.cursor = 'ew-resize';
224
+ document.body.style.userSelect = 'none';
225
+ e.preventDefault();
226
+ });
227
+ document.addEventListener('mousemove', function(e) {
228
+ if (!isResizing) return;
229
+ var newWidth = window.innerWidth - e.clientX;
230
+ applyPrdPanelWidth(prdPanel, newWidth);
231
+ });
232
+ document.addEventListener('mouseup', function() {
233
+ if (isResizing) {
234
+ isResizing = false;
235
+ resizeHandle.classList.remove('resizing');
236
+ document.body.style.cursor = '';
237
+ document.body.style.userSelect = '';
238
+ if (prdPanelWidth) {
239
+ localStorage.setItem('prdPanelWidth', prdPanelWidth);
240
+ }
241
+ }
242
+ });
243
+ }
244
+
245
+ document.addEventListener('click', function(e) {
246
+ if (!prdPanel.classList.contains('open')) return;
247
+ if (prdEditMode) return;
248
+
249
+ var target = e.target;
250
+ var eventPath = typeof e.composedPath === 'function' ? e.composedPath() : [];
251
+ var isInsidePanel = eventPath.indexOf(prdPanel) !== -1 || target.closest('#prdPanel');
252
+ var isFloatBtn = eventPath.indexOf(prdFloatBtn) !== -1 || target.closest('.prd-float-btn');
253
+
254
+ if (!isInsidePanel && !isFloatBtn) {
255
+ prdPanel.classList.remove('open');
256
+ }
257
+ });
258
+
259
+ updatePrdContent();
260
+ }
261
+
262
+ function togglePrdPanel() {
263
+ var prdPanel = document.getElementById('prdPanel');
264
+ if (!prdPanel) return;
265
+
266
+ if (prdPanel.classList.contains('open')) {
267
+ prdPanel.classList.remove('open');
268
+ } else {
269
+ if (prdPanelWidth) {
270
+ applyPrdPanelWidth(prdPanel, prdPanelWidth);
271
+ } else {
272
+ applyPrdPanelWidth(prdPanel, PRD_PANEL_DEFAULT_WIDTH);
273
+ }
274
+ prdPanel.classList.add('open');
275
+ updatePrdContent();
276
+ }
277
+ }
278
+
279
+ var prdCurrentFileName = '';
280
+ var prdCurrentPath = '';
281
+ var prdCurrentRawContent = '';
282
+ var prdWorkspaceTabs = [];
283
+ var prdEditMode = false;
284
+ var prdWorkspaceRootPath = '';
285
+ var prdOverviewMarkdown = '';
286
+ var prdOverviewBuildToken = 0;
287
+ var PRD_OVERVIEW_PATH = './__openprototype_current_version__.md';
288
+
289
+ function notifyNavigatorPrdContext() {
290
+ if (window.parent === window) return;
291
+ var targetOrigin = window.location.origin === 'null' ? '*' : window.location.origin;
292
+ var prdPath = '';
293
+ var contextPath = isPrdOverviewPath(prdCurrentPath) ? prdWorkspaceRootPath : prdCurrentPath;
294
+ if (contextPath) {
295
+ prdPath = decodeURIComponent(new URL(contextPath, window.location.href).pathname);
296
+ }
297
+ window.parent.postMessage({
298
+ type: 'pak-prd-context',
299
+ htmlPath: decodeURIComponent(window.location.pathname || ''),
300
+ prdPath: prdPath,
301
+ title: prdCurrentFileName || ''
302
+ }, targetOrigin);
303
+ }
304
+
305
+ function getDefaultPrdFileName(currentPage) {
306
+ return currentPage.replace(/\.html$/i, '.md');
307
+ }
308
+
309
+ function getPrdFileCandidates(currentPage, mode) {
310
+ var mappedFileName = PRD_FILE_MAP[currentPage];
311
+ var defaultFileName = getDefaultPrdFileName(currentPage);
312
+ var candidates = [];
313
+
314
+ if (mode === 'view' || mode === 'approval') {
315
+ var viewModeMap = {
316
+ 'annual_budget_form.html': 'annual_budget_approval.md',
317
+ 'quarterly_budget_form.html': 'quarterly_budget_approval.md',
318
+ 'monthly_budget_form.html': 'monthly_budget_approval.md',
319
+ 'resource_price_form.html': 'resource_price_approval.md',
320
+ 'kol_form.html': 'kol_list.md'
321
+ };
322
+ if (viewModeMap[currentPage]) {
323
+ mappedFileName = viewModeMap[currentPage];
324
+ }
325
+ }
326
+
327
+ [mappedFileName, defaultFileName].forEach(function(fileName) {
328
+ if (fileName && candidates.indexOf(fileName) === -1) {
329
+ candidates.push(fileName);
330
+ }
331
+ });
332
+
333
+ return candidates;
334
+ }
335
+
336
+ function loadPrdCandidates(fileNames) {
337
+ var paths = [];
338
+ fileNames.forEach(function(fileName) {
339
+ var localPath = './' + fileName;
340
+ var configuredPath = PRD_BASE_PATH + fileName;
341
+ if (paths.indexOf(localPath) === -1) {
342
+ paths.push(localPath);
343
+ }
344
+ if (paths.indexOf(configuredPath) === -1) {
345
+ paths.push(configuredPath);
346
+ }
347
+ });
348
+
349
+ function loadNext(index) {
350
+ if (index >= paths.length) {
351
+ return Promise.resolve(null);
352
+ }
353
+ return loadMarkdownFile(paths[index]).then(function(content) {
354
+ if (content) {
355
+ return {
356
+ path: paths[index],
357
+ fileName: paths[index].split('/').pop(),
358
+ content: content
359
+ };
360
+ }
361
+ return loadNext(index + 1);
362
+ });
363
+ }
364
+
365
+ return loadNext(0);
366
+ }
367
+
368
+ function getPrdWorkspaceConfig(currentPage) {
369
+ if (typeof PRD_WORKSPACE_MAP === 'undefined') {
370
+ return null;
371
+ }
372
+ return PRD_WORKSPACE_MAP[currentPage] || null;
373
+ }
374
+
375
+ function getPrdDisplayName(filePath) {
376
+ return (filePath || '').split('/').pop().replace(/\.md(?:#.*)?$/i, '').replace(/_/g, ' ');
377
+ }
378
+
379
+ function getPrdOverviewVersion() {
380
+ if (typeof PRD_OVERVIEW_VERSION === 'undefined') return '';
381
+ return String(PRD_OVERVIEW_VERSION || '').trim();
382
+ }
383
+
384
+ function isPrdOverviewPath(filePath) {
385
+ return normalizePrdPath(filePath) === normalizePrdPath(PRD_OVERVIEW_PATH);
386
+ }
387
+
388
+ function escapePrdRegExp(text) {
389
+ return String(text || '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
390
+ }
391
+
392
+ function containsPrdVersion(text, version) {
393
+ var normalizedVersion = String(version || '').replace(/^v/i, '');
394
+ if (!normalizedVersion) return false;
395
+ var pattern = '(^|[^0-9.])v?' + escapePrdRegExp(normalizedVersion) + '(?=$|[^0-9.])';
396
+ return new RegExp(pattern, 'i').test(String(text || ''));
397
+ }
398
+
399
+ function getPrdHeadingBefore(lines, index) {
400
+ for (var lineIndex = index - 1; lineIndex >= 0; lineIndex -= 1) {
401
+ var match = String(lines[lineIndex] || '').match(/^#{1,6}\s+(.+)$/);
402
+ if (match) return match[1].replace(/<[^>]+>/g, '').trim();
403
+ }
404
+ return '';
405
+ }
406
+
407
+ function isPrdTableDivider(line) {
408
+ return /^\s*\|(?:\s*:?-{3,}:?\s*\|)+\s*$/.test(String(line || ''));
409
+ }
410
+
411
+ function collectPrdVersionSections(content, version) {
412
+ var lines = String(content || '').split(/\r?\n/);
413
+ var sections = [];
414
+
415
+ for (var index = 0; index < lines.length; index += 1) {
416
+ var line = lines[index];
417
+ if (/^\s*\|.*\|\s*$/.test(line)) {
418
+ var tableStart = index;
419
+ var tableLines = [];
420
+ while (index < lines.length && /^\s*\|.*\|\s*$/.test(lines[index])) {
421
+ tableLines.push(lines[index]);
422
+ index += 1;
423
+ }
424
+ index -= 1;
425
+
426
+ if (tableLines.length >= 3 && isPrdTableDivider(tableLines[1])) {
427
+ var matchedRows = tableLines.slice(2).filter(function(row) {
428
+ return containsPrdVersion(row, version);
429
+ });
430
+ if (matchedRows.length) {
431
+ sections.push({
432
+ heading: getPrdHeadingBefore(lines, tableStart),
433
+ markdown: [tableLines[0], tableLines[1]].concat(matchedRows).join('\n')
434
+ });
435
+ }
436
+ }
437
+ continue;
438
+ }
439
+
440
+ var headingMatch = line.match(/^(#{1,6})\s+(.+)$/);
441
+ if (headingMatch && containsPrdVersion(line, version)) {
442
+ var headingLevel = headingMatch[1].length;
443
+ var sectionLines = [line];
444
+ var nextIndex = index + 1;
445
+ while (nextIndex < lines.length) {
446
+ var nextHeading = lines[nextIndex].match(/^(#{1,6})\s+/);
447
+ if (nextHeading && nextHeading[1].length <= headingLevel) break;
448
+ sectionLines.push(lines[nextIndex]);
449
+ nextIndex += 1;
450
+ }
451
+ sections.push({ heading: '', markdown: sectionLines.join('\n').trim() });
452
+ index = nextIndex - 1;
453
+ continue;
454
+ }
455
+
456
+ if (containsPrdVersion(line, version)) {
457
+ sections.push({
458
+ heading: getPrdHeadingBefore(lines, index),
459
+ markdown: line
460
+ });
461
+ }
462
+ }
463
+
464
+ return sections;
465
+ }
466
+
467
+ function buildPrdOverviewMarkdown(tabs, contents, version) {
468
+ var documentSections = [];
469
+
470
+ tabs.forEach(function(tab, index) {
471
+ var sections = collectPrdVersionSections(contents[index], version);
472
+ if (sections.length) documentSections.push({ tab: tab, sections: sections });
473
+ });
474
+
475
+ if (!documentSections.length) return '';
476
+
477
+ var markdown = [
478
+ '# ' + version + ' 更新总览',
479
+ '',
480
+ '> 自动汇总当前页面工作区内各 PRD 中标注为 ' + version + ' 的修订说明与详细规则。',
481
+ ''
482
+ ];
483
+
484
+ documentSections.forEach(function(documentItem) {
485
+ var tab = documentItem.tab;
486
+ var documentTitle = tab.title === '主文档' ? getPrdDisplayName(tab.path) : tab.title;
487
+ markdown.push('## ' + documentTitle, '', '来源:`' + tab.path.split('/').pop() + '`', '');
488
+
489
+ documentItem.sections.forEach(function(section) {
490
+ if (section.heading) markdown.push('### ' + section.heading, '');
491
+ markdown.push(section.markdown, '');
492
+ });
493
+ });
494
+
495
+ return markdown.join('\n').trim();
496
+ }
497
+
498
+ function renderPrdOverview() {
499
+ var version = getPrdOverviewVersion();
500
+ var contentEl = document.getElementById('prdPanelContent');
501
+ var titleEl = document.getElementById('prdPanelTitle');
502
+ var fileNameEl = document.getElementById('prdPanelFileName');
503
+ var editBtn = document.getElementById('prdPanelEditBtn');
504
+ if (!contentEl || !prdOverviewMarkdown) return;
505
+
506
+ prdCurrentFileName = version + ' 当前版本';
507
+ prdCurrentPath = PRD_OVERVIEW_PATH;
508
+ prdCurrentRawContent = prdOverviewMarkdown;
509
+ if (titleEl) titleEl.textContent = version + ' 更新总览 - PRD';
510
+ if (fileNameEl) fileNameEl.textContent = '';
511
+ if (editBtn) editBtn.style.display = 'none';
512
+
513
+ contentEl.innerHTML = renderMarkdownToHtml(prdOverviewMarkdown);
514
+ wrapPrdTables(contentEl);
515
+ renderPrdTabs(PRD_OVERVIEW_PATH);
516
+ bindPrdTabs();
517
+ notifyNavigatorPrdContext();
518
+ }
519
+
520
+ function preparePrdOverview(rootPath, options) {
521
+ options = options || {};
522
+ var version = getPrdOverviewVersion();
523
+ var realTabs = prdWorkspaceTabs.filter(function(tab) {
524
+ return !isPrdOverviewPath(tab.path);
525
+ });
526
+ var contentOverrides = options.contentOverrides || {};
527
+ var buildToken = ++prdOverviewBuildToken;
528
+ var normalizedRootPath = normalizePrdPath(rootPath);
529
+
530
+ if (!version || !realTabs.length) {
531
+ prdOverviewMarkdown = '';
532
+ prdWorkspaceTabs = realTabs;
533
+ return Promise.resolve('');
534
+ }
535
+
536
+ return Promise.all(realTabs.map(function(tab) {
537
+ var normalizedPath = normalizePrdPath(tab.path);
538
+ if (Object.prototype.hasOwnProperty.call(contentOverrides, normalizedPath)) {
539
+ return Promise.resolve(contentOverrides[normalizedPath]);
540
+ }
541
+ return loadMarkdownFile(tab.path);
542
+ })).then(function(contents) {
543
+ if (buildToken !== prdOverviewBuildToken) return '';
544
+
545
+ prdOverviewMarkdown = buildPrdOverviewMarkdown(realTabs, contents, version);
546
+ prdWorkspaceTabs = prdOverviewMarkdown ? [{
547
+ title: '当前版本',
548
+ path: PRD_OVERVIEW_PATH
549
+ }].concat(realTabs) : realTabs;
550
+
551
+ if (prdOverviewMarkdown && options.activateWhenReady && normalizePrdPath(prdCurrentPath) === normalizedRootPath) {
552
+ renderPrdOverview();
553
+ } else {
554
+ renderPrdTabs(prdCurrentPath);
555
+ bindPrdTabs();
556
+ }
557
+ return prdOverviewMarkdown;
558
+ });
559
+ }
560
+
561
+ function normalizePrdPath(filePath) {
562
+ var path = decodeURIComponent(String(filePath || '')).split('#')[0].split('?')[0];
563
+ var hasDotPrefix = path.indexOf('./') === 0;
564
+ path = path.replace(/\\/g, '/').replace(/^\.\/+/, '');
565
+ var parts = [];
566
+ path.split('/').forEach(function(part) {
567
+ if (!part || part === '.') return;
568
+ if (part === '..') {
569
+ parts.pop();
570
+ } else {
571
+ parts.push(part);
572
+ }
573
+ });
574
+ return (hasDotPrefix ? './' : './') + parts.join('/');
575
+ }
576
+
577
+ function resolvePrdPath(href, basePath) {
578
+ var cleanHref = String(href || '').split('#')[0].split('?')[0];
579
+ if (!cleanHref || /^[a-z]+:/i.test(cleanHref) || cleanHref.charAt(0) === '#') {
580
+ return '';
581
+ }
582
+ if (cleanHref.indexOf('/') === 0) {
583
+ return normalizePrdPath(cleanHref);
584
+ }
585
+ var base = normalizePrdPath(basePath || prdCurrentPath || './');
586
+ var baseDir = base.substring(0, base.lastIndexOf('/') + 1);
587
+ return normalizePrdPath(baseDir + cleanHref);
588
+ }
589
+
590
+ function isInternalPrdHref(href) {
591
+ var cleanHref = String(href || '').split('#')[0].split('?')[0];
592
+ return /\.md$/i.test(cleanHref) && !/^[a-z]+:/i.test(cleanHref);
593
+ }
594
+
595
+ function dedupePrdTabs(tabs) {
596
+ var seen = {};
597
+ return tabs.filter(function(tab) {
598
+ var key = normalizePrdPath(tab.path);
599
+ if (seen[key]) return false;
600
+ seen[key] = true;
601
+ tab.path = key;
602
+ return true;
603
+ });
604
+ }
605
+
606
+ function buildWorkspaceTabsFromConfig(config, rootPath) {
607
+ if (!config || !Array.isArray(config.tabs)) {
608
+ return [];
609
+ }
610
+ return dedupePrdTabs(config.tabs.map(function(tab) {
611
+ return {
612
+ title: tab.title || getPrdDisplayName(tab.file || tab.path),
613
+ path: resolvePrdPath(tab.file || tab.path, rootPath)
614
+ };
615
+ }));
616
+ }
617
+
618
+ function buildWorkspaceTabsFromContent(contentEl, rootPath) {
619
+ var tabs = [{
620
+ title: '主文档',
621
+ path: rootPath
622
+ }];
623
+ if (!contentEl) {
624
+ return tabs;
625
+ }
626
+ contentEl.querySelectorAll('a[href]').forEach(function(link) {
627
+ var href = link.getAttribute('href');
628
+ if (!isInternalPrdHref(href)) return;
629
+ tabs.push({
630
+ title: link.textContent.trim() || getPrdDisplayName(href),
631
+ path: resolvePrdPath(href, rootPath)
632
+ });
633
+ });
634
+ return dedupePrdTabs(tabs);
635
+ }
636
+
637
+ function renderPrdTabs(activePath) {
638
+ var tabsEl = document.getElementById('prdPanelTabs');
639
+ if (!tabsEl) return;
640
+
641
+ if (!prdWorkspaceTabs || prdWorkspaceTabs.length <= 1) {
642
+ tabsEl.innerHTML = '';
643
+ tabsEl.style.display = 'none';
644
+ return;
645
+ }
646
+
647
+ tabsEl.style.display = '';
648
+ tabsEl.innerHTML = prdWorkspaceTabs.map(function(tab) {
649
+ var isActive = normalizePrdPath(tab.path) === normalizePrdPath(activePath);
650
+ return '<button type="button" class="prd-panel-tab' + (isActive ? ' active' : '') + '" data-prd-path="' + escapeHtmlAttr(tab.path) + '">' + escapeHtml(tab.title) + '</button>';
651
+ }).join('');
652
+ }
653
+
654
+ function wrapPrdTables(contentEl) {
655
+ if (!contentEl) return;
656
+ var tables = contentEl.querySelectorAll('table');
657
+ tables.forEach(function(table) {
658
+ if (!table.parentElement.classList.contains('table-wrapper')) {
659
+ var wrapper = document.createElement('div');
660
+ wrapper.className = 'table-wrapper';
661
+ table.parentNode.insertBefore(wrapper, table);
662
+ wrapper.appendChild(table);
663
+ }
664
+ });
665
+ }
666
+
667
+ function bindPrdContentLinks(contentEl) {
668
+ if (!contentEl) return;
669
+ contentEl.querySelectorAll('a[href]').forEach(function(link) {
670
+ var href = link.getAttribute('href');
671
+ if (!isInternalPrdHref(href)) return;
672
+ link.classList.add('prd-doc-link');
673
+ link.addEventListener('click', function(e) {
674
+ e.preventDefault();
675
+ var targetPath = resolvePrdPath(href, prdCurrentPath);
676
+ openPrdPath(targetPath, { title: link.textContent.trim() });
677
+ });
678
+ });
679
+ }
680
+
681
+ function bindPrdTabs() {
682
+ var tabsEl = document.getElementById('prdPanelTabs');
683
+ if (!tabsEl) return;
684
+ tabsEl.querySelectorAll('.prd-panel-tab').forEach(function(tabEl) {
685
+ tabEl.addEventListener('click', function() {
686
+ openPrdPath(tabEl.getAttribute('data-prd-path'), {
687
+ title: tabEl.textContent.trim()
688
+ });
689
+ });
690
+ });
691
+ }
692
+
693
+ function setPrdHeader(filePath, title) {
694
+ var prdTitleEl = document.getElementById('prdPanelTitle');
695
+ var prdFileNameEl = document.getElementById('prdPanelFileName');
696
+ var fileName = (filePath || '').split('/').pop();
697
+
698
+ prdCurrentFileName = fileName;
699
+ prdCurrentPath = normalizePrdPath(filePath || fileName);
700
+
701
+ if (prdTitleEl) {
702
+ prdTitleEl.textContent = (title || getPrdDisplayName(fileName)) + ' - PRD';
703
+ }
704
+ if (prdFileNameEl) {
705
+ prdFileNameEl.textContent = '';
706
+ }
707
+ }
708
+
709
+ function renderLoadedPrd(result, options) {
710
+ var prdContentEl = document.getElementById('prdPanelContent');
711
+ if (!prdContentEl || !result || !result.content) return;
712
+
713
+ var currentPath = normalizePrdPath(result.path || result.fileName);
714
+ setPrdHeader(currentPath, options && options.title);
715
+ prdCurrentRawContent = result.content;
716
+ var editBtn = document.getElementById('prdPanelEditBtn');
717
+ if (editBtn && !prdEditMode) editBtn.style.display = '';
718
+ prdContentEl.innerHTML = renderMarkdownToHtml(result.content);
719
+ wrapPrdTables(prdContentEl);
720
+
721
+ if (options && options.resetWorkspace) {
722
+ var configuredTabs = buildWorkspaceTabsFromConfig(options.workspaceConfig, currentPath);
723
+ prdWorkspaceTabs = configuredTabs.length ? configuredTabs : buildWorkspaceTabsFromContent(prdContentEl, currentPath);
724
+ prdWorkspaceRootPath = currentPath;
725
+ prdOverviewMarkdown = '';
726
+ var contentOverrides = {};
727
+ contentOverrides[currentPath] = result.content;
728
+ preparePrdOverview(currentPath, {
729
+ activateWhenReady: true,
730
+ contentOverrides: contentOverrides
731
+ });
732
+ } else if (options && options.title) {
733
+ var targetPath = normalizePrdPath(currentPath);
734
+ var exists = prdWorkspaceTabs.some(function(tab) {
735
+ return normalizePrdPath(tab.path) === targetPath;
736
+ });
737
+ if (!exists) {
738
+ prdWorkspaceTabs.push({
739
+ title: options.title,
740
+ path: targetPath
741
+ });
742
+ }
743
+ }
744
+
745
+ renderPrdTabs(currentPath);
746
+ bindPrdTabs();
747
+ bindPrdContentLinks(prdContentEl);
748
+ notifyNavigatorPrdContext();
749
+ }
750
+
751
+ function openPrdPath(filePath, options) {
752
+ var prdContentEl = document.getElementById('prdPanelContent');
753
+ var normalizedPath = normalizePrdPath(filePath);
754
+ if (!prdContentEl || !normalizedPath) return Promise.resolve(null);
755
+
756
+ if (isPrdOverviewPath(normalizedPath)) {
757
+ renderPrdOverview();
758
+ return Promise.resolve({ path: PRD_OVERVIEW_PATH, content: prdOverviewMarkdown });
759
+ }
760
+
761
+ prdContentEl.innerHTML = '<div style="padding:20px;text-align:center;color:var(--text-secondary);">加载中...</div>';
762
+
763
+ return loadMarkdownFile(normalizedPath).then(function(content) {
764
+ if (content) {
765
+ var result = {
766
+ path: normalizedPath,
767
+ fileName: normalizedPath.split('/').pop(),
768
+ content: content
769
+ };
770
+ renderLoadedPrd(result, options || {});
771
+ return result;
772
+ }
773
+ prdContentEl.innerHTML = '<div class="error" style="padding:20px;color:var(--danger);">PRD文档加载失败,请检查文件路径:' + normalizedPath + '</div>';
774
+ return null;
775
+ }).catch(function(err) {
776
+ prdContentEl.innerHTML = '<div class="error" style="padding:20px;color:var(--danger);">PRD文档加载失败:' + err.message + '</div>';
777
+ return null;
778
+ });
779
+ }
780
+
781
+ function updatePrdContent() {
782
+ var prdContentEl = document.getElementById('prdPanelContent');
783
+ var prdTitleEl = document.getElementById('prdPanelTitle');
784
+ var prdFileNameEl = document.getElementById('prdPanelFileName');
785
+ if (!prdContentEl) return;
786
+
787
+ var currentPage = decodeURIComponent(window.location.pathname.split('/').pop()) || 'index.html';
788
+ var urlParams = new URLSearchParams(window.location.search);
789
+ var mode = urlParams.get('mode');
790
+
791
+ var prdFileCandidates = getPrdFileCandidates(currentPage, mode);
792
+ var prdFileName = prdFileCandidates[0];
793
+ var workspaceConfig = getPrdWorkspaceConfig(currentPage);
794
+ prdOverviewBuildToken += 1;
795
+ prdWorkspaceRootPath = '';
796
+ prdOverviewMarkdown = '';
797
+
798
+ if (!prdFileName) {
799
+ prdContentEl.innerHTML = '<div class="error" style="padding:20px;color:var(--text-secondary);">当前页面暂无对应的PRD文档</div>';
800
+ prdCurrentPath = '';
801
+ notifyNavigatorPrdContext();
802
+ return;
803
+ }
804
+
805
+ prdCurrentFileName = prdFileName;
806
+ var displayName = prdFileName.replace(/\.md$/, '').replace(/_/g, ' ');
807
+
808
+ if (prdTitleEl) {
809
+ prdTitleEl.textContent = displayName + ' - PRD';
810
+ }
811
+
812
+ if (prdFileNameEl) {
813
+ prdFileNameEl.textContent = '';
814
+ }
815
+
816
+ prdContentEl.innerHTML = '<div style="padding:20px;text-align:center;color:var(--text-secondary);">加载中...</div>';
817
+
818
+ loadPrdCandidates(prdFileCandidates).then(function(result) {
819
+ if (result && result.content) {
820
+ renderLoadedPrd(result, {
821
+ resetWorkspace: true,
822
+ workspaceConfig: workspaceConfig
823
+ });
824
+ } else {
825
+ prdContentEl.innerHTML = '<div class="error" style="padding:20px;color:var(--danger);">PRD文档加载失败,请检查文件路径:' + prdFileCandidates.join(' / ') + '</div>';
826
+ prdCurrentPath = '';
827
+ notifyNavigatorPrdContext();
828
+ }
829
+ }).catch(function(err) {
830
+ prdContentEl.innerHTML = '<div class="error" style="padding:20px;color:var(--danger);">PRD文档加载失败:' + err.message + '</div>';
831
+ prdCurrentPath = '';
832
+ notifyNavigatorPrdContext();
833
+ });
834
+ }
835
+
836
+ function showPrdMessage(elId, text, isError) {
837
+ var msgEl = document.getElementById(elId);
838
+ if (!msgEl) return;
839
+ msgEl.textContent = text || '';
840
+ msgEl.classList.toggle('is-error', !!isError);
841
+ if (text) {
842
+ setTimeout(function() {
843
+ if (msgEl.textContent === text) {
844
+ msgEl.textContent = '';
845
+ msgEl.classList.remove('is-error');
846
+ }
847
+ }, 2000);
848
+ }
849
+ }
850
+
851
+ function showPrdToast(text, isError) {
852
+ showPrdMessage('prdPanelToast', text, isError);
853
+ }
854
+
855
+ function showPrdEditorMsg(text, isError) {
856
+ showPrdMessage('prdPanelEditorMsg', text, isError);
857
+ }
858
+
859
+ function enterPrdEditMode() {
860
+ if (isPrdOverviewPath(prdCurrentPath)) {
861
+ showPrdToast('“当前版本”由关联 PRD 自动汇总,请在原文页签中编辑', true);
862
+ return;
863
+ }
864
+ if (isLocalFileProtocol()) {
865
+ showPrdToast('请通过本地服务器(npm run serve)打开原型后再编辑', true);
866
+ return;
867
+ }
868
+
869
+ var contentEl = document.getElementById('prdPanelContent');
870
+ var editorWrap = document.getElementById('prdPanelEditorWrap');
871
+ var tabsEl = document.getElementById('prdPanelTabs');
872
+ var textarea = document.getElementById('prdPanelEditorTextarea');
873
+ var editBtn = document.getElementById('prdPanelEditBtn');
874
+ if (!contentEl || !editorWrap || !textarea) return;
875
+
876
+ prdEditMode = true;
877
+ textarea.value = prdCurrentRawContent;
878
+ contentEl.style.display = 'none';
879
+ if (tabsEl) tabsEl.style.display = 'none';
880
+ if (editBtn) editBtn.style.display = 'none';
881
+ editorWrap.style.display = '';
882
+ textarea.focus();
883
+ }
884
+
885
+ function exitPrdEditMode() {
886
+ var contentEl = document.getElementById('prdPanelContent');
887
+ var editorWrap = document.getElementById('prdPanelEditorWrap');
888
+ var editBtn = document.getElementById('prdPanelEditBtn');
889
+
890
+ prdEditMode = false;
891
+ if (editorWrap) editorWrap.style.display = 'none';
892
+ if (contentEl) contentEl.style.display = '';
893
+ if (editBtn) editBtn.style.display = '';
894
+ renderPrdTabs(prdCurrentPath);
895
+ bindPrdTabs();
896
+ }
897
+
898
+ function applyPrdRedColor() {
899
+ var textarea = document.getElementById('prdPanelEditorTextarea');
900
+ if (!textarea) return;
901
+
902
+ var start = textarea.selectionStart;
903
+ var end = textarea.selectionEnd;
904
+ if (start === end) {
905
+ showPrdEditorMsg('请先选中要标红的文字', true);
906
+ return;
907
+ }
908
+
909
+ var value = textarea.value;
910
+ var selected = value.slice(start, end);
911
+ var wrapped = wrapPrdSelectionWithRed(selected);
912
+ var scrollTop = textarea.scrollTop;
913
+ textarea.value = value.slice(0, start) + wrapped + value.slice(end);
914
+ textarea.focus();
915
+ textarea.setSelectionRange(start, start + wrapped.length);
916
+ restorePrdEditorScroll(textarea, scrollTop);
917
+ }
918
+
919
+ function wrapPrdSelectionWithRed(text) {
920
+ if (!isPrdMarkdownTableSelection(text)) {
921
+ return '<span style="color:red">' + text + '</span>';
922
+ }
923
+
924
+ return text.split('\n').map(function(line) {
925
+ if (!isPrdMarkdownTableRow(line) || isPrdMarkdownTableDivider(line)) {
926
+ return line;
927
+ }
928
+ return wrapPrdMarkdownTableRowCells(line);
929
+ }).join('\n');
930
+ }
931
+
932
+ function isPrdMarkdownTableSelection(text) {
933
+ return text.split('\n').some(function(line) {
934
+ return isPrdMarkdownTableRow(line) && !isPrdMarkdownTableDivider(line);
935
+ });
936
+ }
937
+
938
+ function isPrdMarkdownTableRow(line) {
939
+ return /^\s*\|.*\|\s*$/.test(line);
940
+ }
941
+
942
+ function isPrdMarkdownTableDivider(line) {
943
+ return /^\s*\|[\s:|-]+\|\s*$/.test(line);
944
+ }
945
+
946
+ function wrapPrdMarkdownTableRowCells(line) {
947
+ var leading = line.match(/^\s*/)[0];
948
+ var trailing = line.match(/\s*$/)[0];
949
+ var body = line.trim();
950
+ var cells = body.slice(1, -1).split('|');
951
+
952
+ return leading + '|' + cells.map(function(cell) {
953
+ var left = cell.match(/^\s*/)[0];
954
+ var right = cell.match(/\s*$/)[0];
955
+ var content = cell.trim();
956
+ if (!content || /<span\b[^>]*\bstyle\s*=\s*["'][^"']*\bcolor\s*:\s*(?:#e53935|red)\b[^"']*["'][^>]*>[\s\S]*<\/span>/i.test(content)) {
957
+ return cell;
958
+ }
959
+ return left + '<span style="color:red">' + content + '</span>' + right;
960
+ }).join('|') + '|' + trailing;
961
+ }
962
+
963
+ function removePrdRedColor() {
964
+ var textarea = document.getElementById('prdPanelEditorTextarea');
965
+ if (!textarea) return;
966
+
967
+ var start = textarea.selectionStart;
968
+ var end = textarea.selectionEnd;
969
+ var value = textarea.value;
970
+ var spanRegex = /<span\b[^>]*\bstyle\s*=\s*["'][^"']*\bcolor\s*:\s*(?:#e53935|red)\b[^"']*["'][^>]*>([\s\S]*?)<\/span>/gi;
971
+ var match;
972
+ var matches = [];
973
+
974
+ while ((match = spanRegex.exec(value)) !== null) {
975
+ var spanStart = match.index;
976
+ var spanEnd = match.index + match[0].length;
977
+ if (start <= spanEnd && end >= spanStart) {
978
+ matches.push({
979
+ start: spanStart,
980
+ end: spanEnd,
981
+ full: match[0],
982
+ inner: match[1]
983
+ });
984
+ }
985
+ }
986
+
987
+ if (!matches.length) {
988
+ showPrdEditorMsg('请先选中或将光标放在已标红的文字上', true);
989
+ return;
990
+ }
991
+
992
+ var nextValue = value;
993
+ var scrollTop = textarea.scrollTop;
994
+ var nextCaret = matches[0].start;
995
+ matches.reverse().forEach(function(item) {
996
+ nextValue = nextValue.slice(0, item.start) + item.inner + nextValue.slice(item.end);
997
+ });
998
+ textarea.value = nextValue;
999
+ textarea.focus();
1000
+ textarea.setSelectionRange(nextCaret, nextCaret);
1001
+ restorePrdEditorScroll(textarea, scrollTop);
1002
+ }
1003
+
1004
+ function removeAllPrdRedColor() {
1005
+ var textarea = document.getElementById('prdPanelEditorTextarea');
1006
+ if (!textarea) return;
1007
+
1008
+ var value = textarea.value;
1009
+ var nextValue = removePrdRedSpans(value);
1010
+ if (nextValue === value) {
1011
+ showPrdEditorMsg('当前文档没有标红内容', true);
1012
+ return;
1013
+ }
1014
+
1015
+ var scrollTop = textarea.scrollTop;
1016
+ var caret = textarea.selectionStart;
1017
+ textarea.value = nextValue;
1018
+ textarea.focus();
1019
+ textarea.setSelectionRange(Math.min(caret, nextValue.length), Math.min(caret, nextValue.length));
1020
+ restorePrdEditorScroll(textarea, scrollTop);
1021
+ }
1022
+
1023
+ function removePrdRedSpans(text) {
1024
+ return text.replace(/<span\b[^>]*\bstyle\s*=\s*["'][^"']*\bcolor\s*:\s*(?:#e53935|red)\b[^"']*["'][^>]*>([\s\S]*?)<\/span>/gi, '$1');
1025
+ }
1026
+
1027
+ function restorePrdEditorScroll(textarea, scrollTop) {
1028
+ textarea.scrollTop = scrollTop;
1029
+ var restore = function() {
1030
+ textarea.scrollTop = scrollTop;
1031
+ };
1032
+ if (window.requestAnimationFrame) {
1033
+ window.requestAnimationFrame(restore);
1034
+ } else {
1035
+ setTimeout(restore, 0);
1036
+ }
1037
+ }
1038
+
1039
+ function savePrdEdits() {
1040
+ var textarea = document.getElementById('prdPanelEditorTextarea');
1041
+ var contentEl = document.getElementById('prdPanelContent');
1042
+ if (!textarea || !contentEl || !prdCurrentPath) {
1043
+ return Promise.reject(new Error('当前没有可保存的 PRD'));
1044
+ }
1045
+
1046
+ var newContent = textarea.value;
1047
+ var absolutePath = decodeURIComponent(new URL(prdCurrentPath, window.location.href).pathname);
1048
+
1049
+ return fetch('/api/save-prd', {
1050
+ method: 'POST',
1051
+ headers: { 'Content-Type': 'application/json' },
1052
+ body: JSON.stringify({ path: absolutePath, content: newContent })
1053
+ }).then(function(response) {
1054
+ return response.text().then(function(text) {
1055
+ var data;
1056
+ try {
1057
+ data = JSON.parse(text);
1058
+ } catch (e) {
1059
+ throw new Error('当前地址不支持保存,请通过本地服务器(npm run serve,默认 http://127.0.0.1:8082)打开原型后再编辑');
1060
+ }
1061
+ if (!response.ok || !data.ok) {
1062
+ throw new Error(data.error || ('保存失败: ' + response.status));
1063
+ }
1064
+ return data;
1065
+ });
1066
+ }).then(function() {
1067
+ PRD_CACHE[prdCurrentPath] = newContent;
1068
+ prdCurrentRawContent = newContent;
1069
+ contentEl.innerHTML = renderMarkdownToHtml(newContent);
1070
+ wrapPrdTables(contentEl);
1071
+ bindPrdContentLinks(contentEl);
1072
+ exitPrdEditMode();
1073
+ var contentOverrides = {};
1074
+ contentOverrides[normalizePrdPath(prdCurrentPath)] = newContent;
1075
+ return preparePrdOverview(prdWorkspaceRootPath || prdCurrentPath, {
1076
+ activateWhenReady: false,
1077
+ contentOverrides: contentOverrides
1078
+ }).then(function() {
1079
+ showPrdToast('已保存', false);
1080
+ return true;
1081
+ });
1082
+ }).catch(function(err) {
1083
+ showPrdEditorMsg('保存失败:' + err.message, true);
1084
+ throw err;
1085
+ });
1086
+ }
1087
+
1088
+ function copyPrdRawContent() {
1089
+ var editorTextarea = document.getElementById('prdPanelEditorTextarea');
1090
+ var copyText = prdEditMode && editorTextarea ? editorTextarea.value : prdCurrentRawContent;
1091
+ if (!copyText && prdCurrentPath) {
1092
+ loadMarkdownFile(prdCurrentPath).then(function(content) {
1093
+ copyTextToClipboard(content || '');
1094
+ });
1095
+ return;
1096
+ }
1097
+
1098
+ copyTextToClipboard(copyText || '');
1099
+ }
1100
+
1101
+ function copyTextToClipboard(text) {
1102
+ if (navigator.clipboard && navigator.clipboard.writeText) {
1103
+ navigator.clipboard.writeText(text).then(function() {
1104
+ showCopySuccess();
1105
+ }).catch(function(err) {
1106
+ fallbackCopy(text);
1107
+ });
1108
+ } else {
1109
+ fallbackCopy(text);
1110
+ }
1111
+ }
1112
+
1113
+ function fallbackCopy(text) {
1114
+ var textarea = document.createElement('textarea');
1115
+ textarea.value = text;
1116
+ textarea.style.position = 'fixed';
1117
+ textarea.style.opacity = '0';
1118
+ document.body.appendChild(textarea);
1119
+ textarea.select();
1120
+ try {
1121
+ document.execCommand('copy');
1122
+ showCopySuccess();
1123
+ } catch (err) {
1124
+ console.error('复制失败:', err);
1125
+ }
1126
+ document.body.removeChild(textarea);
1127
+ }
1128
+
1129
+ function escapeHtml(str) {
1130
+ return String(str || '').replace(/[&<>"']/g, function(ch) {
1131
+ var map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
1132
+ return map[ch] || ch;
1133
+ });
1134
+ }
1135
+
1136
+ function escapeHtmlAttr(str) {
1137
+ return escapeHtml(str).replace(/`/g, '&#96;');
1138
+ }
1139
+
1140
+ function showCopySuccess() {
1141
+ var copyBtn = document.getElementById('prdPanelCopyBtn');
1142
+ if (!copyBtn) return;
1143
+
1144
+ var originalHTML = copyBtn.innerHTML;
1145
+ copyBtn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>';
1146
+ copyBtn.style.color = '#52c41a';
1147
+
1148
+ setTimeout(function() {
1149
+ copyBtn.innerHTML = originalHTML;
1150
+ copyBtn.style.color = '';
1151
+ }, 2000);
1152
+ }
1153
+
1154
+ function isLocalFileProtocol() {
1155
+ return window.location.protocol === 'file:';
1156
+ }
1157
+
1158
+ function loadMarkdownFile(filePath) {
1159
+ var inlineKey = filePath.replace(PRD_BASE_PATH, '').replace(/^\.\//, '');
1160
+ if (typeof INLINE_PRD_CONTENT !== 'undefined' && INLINE_PRD_CONTENT[inlineKey]) {
1161
+ var content = INLINE_PRD_CONTENT[inlineKey];
1162
+ PRD_CACHE[filePath] = content;
1163
+ return Promise.resolve(content);
1164
+ }
1165
+
1166
+ return new Promise(function(resolve, reject) {
1167
+ if (isLocalFileProtocol()) {
1168
+ var xhr = new XMLHttpRequest();
1169
+ xhr.open('GET', filePath, true);
1170
+ xhr.onload = function() {
1171
+ if (xhr.status === 200 || xhr.status === 0) {
1172
+ PRD_CACHE[filePath] = xhr.responseText;
1173
+ resolve(xhr.responseText);
1174
+ } else {
1175
+ resolve(null);
1176
+ }
1177
+ };
1178
+ xhr.onerror = function() {
1179
+ console.error('XHR加载失败:', filePath);
1180
+ resolve(null);
1181
+ };
1182
+ xhr.send();
1183
+ } else {
1184
+ fetch(filePath, { cache: 'no-store' })
1185
+ .then(function(response) {
1186
+ if (!response.ok) {
1187
+ throw new Error('文件加载失败: ' + response.status);
1188
+ }
1189
+ return response.text();
1190
+ })
1191
+ .then(function(text) {
1192
+ PRD_CACHE[filePath] = text;
1193
+ resolve(text);
1194
+ })
1195
+ .catch(function(error) {
1196
+ console.error('加载 Markdown 文件失败:', error);
1197
+ resolve(null);
1198
+ });
1199
+ }
1200
+ });
1201
+ }
1202
+
1203
+ function renderMarkdownToHtml(markdown) {
1204
+ if (typeof marked !== 'undefined') {
1205
+ marked.setOptions({
1206
+ breaks: true,
1207
+ gfm: true,
1208
+ tables: true
1209
+ });
1210
+ var html = marked.parse(markdown);
1211
+
1212
+ if (html.indexOf('<div class="table-wrapper">') === -1) {
1213
+ html = html.replace(/<table>/g, '<div class="table-wrapper"><table>');
1214
+ html = html.replace(/<\/table>/g, '</table></div>');
1215
+ }
1216
+
1217
+ return html;
1218
+ }
1219
+
1220
+ var html = markdown;
1221
+
1222
+ html = html.replace(/^###### (.*$)/gim, '<h6>$1</h6>');
1223
+ html = html.replace(/^##### (.*$)/gim, '<h5>$1</h5>');
1224
+ html = html.replace(/^#### (.*$)/gim, '<h4>$1</h4>');
1225
+ html = html.replace(/^### (.*$)/gim, '<h3>$1</h3>');
1226
+ html = html.replace(/^## (.*$)/gim, '<h2>$1</h2>');
1227
+ html = html.replace(/^# (.*$)/gim, '<h1>$1</h1>');
1228
+
1229
+ html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
1230
+ html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');
1231
+ html = html.replace(/`(.*?)`/g, '<code>$1</code>');
1232
+
1233
+ var tableRegex = /\|(.+)\|\n\|[-| :]+\|\n((?:\|.+\|\n?)+)/g;
1234
+ html = html.replace(tableRegex, function(match, header, body) {
1235
+ var headers = header.split('|').slice(1, -1);
1236
+ var rows = body.trim().split('\n');
1237
+
1238
+ var tableHtml = '<div class="table-wrapper"><table><thead><tr>';
1239
+ headers.forEach(function(h) {
1240
+ tableHtml += '<th>' + h.trim() + '</th>';
1241
+ });
1242
+ tableHtml += '</tr></thead><tbody>';
1243
+
1244
+ rows.forEach(function(row) {
1245
+ var cells = row.split('|').slice(1, -1);
1246
+ tableHtml += '<tr>';
1247
+ cells.forEach(function(c) {
1248
+ tableHtml += '<td>' + c.trim() + '</td>';
1249
+ });
1250
+ tableHtml += '</tr>';
1251
+ });
1252
+ tableHtml += '</tbody></table></div>';
1253
+ return tableHtml;
1254
+ });
1255
+
1256
+ html = html.replace(/^- (.*$)/gim, '<li>$1</li>');
1257
+ html = html.replace(/(<li>.*<\/li>\n?)+/g, '<ul>$&</ul>');
1258
+
1259
+ html = html.replace(/^> (.*$)/gim, '<blockquote>$1</blockquote>');
1260
+
1261
+ html = html.replace(/---/g, '<hr>');
1262
+
1263
+ html = html.replace(/\n/g, '<br>');
1264
+
1265
+ return html;
1266
+ }
1267
+
1268
+ if (document.readyState === 'loading') {
1269
+ document.addEventListener('DOMContentLoaded', function() {
1270
+ if (!prdPanelInitialized) {
1271
+ initPrdPanel();
1272
+ }
1273
+ });
1274
+ } else {
1275
+ setTimeout(function() {
1276
+ if (!prdPanelInitialized) {
1277
+ initPrdPanel();
1278
+ }
1279
+ }, 0);
1280
+ }