-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrenderer.js
More file actions
6149 lines (5881 loc) · 253 KB
/
Copy pathrenderer.js
File metadata and controls
6149 lines (5881 loc) · 253 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
window.copyCode = function copyCode(btn) {
const block = btn && btn.closest && btn.closest('.code-block');
const pre = block && block.querySelector('pre');
const code = pre && (pre.querySelector('code') || pre);
const text = code ? code.textContent : '';
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text).then(() => {
const t = btn.textContent;
btn.textContent = '已复制';
setTimeout(() => { btn.textContent = t; }, 1200);
});
}
};
window.addEventListener('DOMContentLoaded', async () => {
const settingsBody = document.getElementById('settings-body');
if (settingsBody) {
try {
const res = await fetch('/settings-modal.html');
if (res.ok) settingsBody.innerHTML = await res.text();
} catch (_) {}
}
// 身份页状态必须在任何使用它们的函数之前声明(避免 let TDZ / 闭包读到未初始化变量)
let currentSettingsTab = 'sync';
let identityHasExisting = false;
let lastDerivedEsec = '';
let identityLoginMode = 'paste'; // 'paste' | 'new'
let identityPrefillNonce = 0;
/** 服务器 profile 中的头像 URL,保存时原样写回(本页不再提供头像 URL 输入) */
let profileServerAvatarUrl = '';
/** 用户信息是否在本次会话中被用户修改过;若已修改则不自动用服务器数据覆盖 */
let profileDirtyInSession = false;
/** 仅当「新用户(邮箱)」模式点击过“生成新用户密钥”后为 true,用于决定是否需要向服务器注册 create_user */
let identityGeneratedThisSession = false;
/** 「用户信息」页密钥展示:编码(epub / ESEC)或裸 hex */
let profileKeyDisplayMode = 'encoded';
const identityKeyHexCache = { pubkeyHex: '', privkeyHex: '' };
const composeState = {
mode: null,
draft: null,
tags: [],
/** 书籍联合作者:{ email, pubkey },与 eventstoreUI create_book.coAuthors 一致(发布时传 pubkey 数组) */
coAuthors: [],
draftFileId: null,
remoteId: '',
assetMap: {},
/** 书籍:各章节正文(内存);当前编辑章节见 bookActiveChapterId */
bookChapterContents: {},
bookActiveChapterId: null,
/** 本机新建书籍会话盐,用于首次保存时生成与「远程下载」同规则的草稿目录 id */
bookNewLocalSalt: null,
};
/** 书籍上传:Monaco setValue 程序化换章时不应记为「待上传」 */
let bookPendingSuppress = 0;
let bookUploadPendingTimer = null;
let activeComposeUploadRequestId = null;
let composeGenerateStatusTimer = null;
function refreshIdentityKeyHexCacheFromIdentity(id) {
if (!id || typeof id !== 'object') return;
if (typeof id.pubkeyHex === 'string' && id.pubkeyHex.trim()) identityKeyHexCache.pubkeyHex = id.pubkeyHex.trim();
if (typeof id.privkeyHex === 'string' && id.privkeyHex.trim()) identityKeyHexCache.privkeyHex = id.privkeyHex.trim();
}
function updateProfileKeyFormatUi() {
const encBtn = document.getElementById('settings-profile-key-format-encoded');
const hexBtn = document.getElementById('settings-profile-key-format-hex');
const pubLabel = document.getElementById('settings-profile-pubkey-label-text');
const privLabel = document.getElementById('settings-profile-privkey-label-text');
const isHex = profileKeyDisplayMode === 'hex';
if (encBtn) encBtn.classList.toggle('profile-form-key-format-btn--active', !isHex);
if (hexBtn) hexBtn.classList.toggle('profile-form-key-format-btn--active', isHex);
if (pubLabel) pubLabel.textContent = isHex ? '公钥(hex)' : '公钥(epub)';
if (privLabel) privLabel.textContent = isHex ? '私钥(hex)' : '私钥(ESEC)';
}
function updateProfileHeroNameDisplay(name) {
const heroNameEl = document.getElementById('settings-profile-hero-name');
if (!heroNameEl) return;
const v = typeof name === 'string' ? name.trim() : '';
heroNameEl.textContent = v || '未设置昵称';
}
function renderProfileAvatarPreview(url) {
const previewEl = document.getElementById('settings-profile-avatar-preview');
if (!previewEl) return;
previewEl.innerHTML = '';
const raw = typeof url === 'string' ? url.trim() : '';
const src = raw ? resolveAvatarUrlForDisplay(raw) : '';
if (!src) {
const icon = document.createElement('i');
icon.className = 'bi bi-person-fill profile-form-avatar-empty-icon';
icon.setAttribute('aria-hidden', 'true');
previewEl.appendChild(icon);
return;
}
const img = document.createElement('img');
img.src = src;
img.alt = '';
img.onerror = () => {
previewEl.innerHTML = '';
const icon = document.createElement('i');
icon.className = 'bi bi-person-fill profile-form-avatar-empty-icon';
icon.setAttribute('aria-hidden', 'true');
previewEl.appendChild(icon);
};
previewEl.appendChild(img);
}
function fileToDataUrl(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : '');
reader.onerror = () => reject(new Error('读取图片失败'));
reader.readAsDataURL(file);
});
}
/** 居中裁成正方形,用于封面上传 */
function cropImageFileToSquareBlob(file) {
return new Promise((resolve, reject) => {
const img = new Image();
const url = URL.createObjectURL(file);
img.onload = () => {
try {
const w = img.naturalWidth;
const h = img.naturalHeight;
const side = Math.min(w, h);
const sx = (w - side) / 2;
const sy = (h - side) / 2;
const canvas = document.createElement('canvas');
canvas.width = side;
canvas.height = side;
const ctx = canvas.getContext('2d');
if (!ctx) {
URL.revokeObjectURL(url);
reject(new Error('canvas'));
return;
}
ctx.drawImage(img, sx, sy, side, side, 0, 0, side, side);
URL.revokeObjectURL(url);
canvas.toBlob(
(blob) => {
if (!blob) reject(new Error('crop failed'));
else resolve(blob);
},
'image/png',
0.92,
);
} catch (e) {
URL.revokeObjectURL(url);
reject(e);
}
};
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error('load image failed'));
};
img.src = url;
});
}
function normalizeComposeTag(s) {
return String(s || '')
.trim()
.replace(/^#/, '')
.replace(/\s+/g, ' ');
}
function renderComposeTags() {
const container = document.getElementById('content-compose-tags-list');
const hidden = document.getElementById('content-compose-tags');
if (!container) return;
container.innerHTML = '';
composeState.tags.forEach((tag, i) => {
const chip = document.createElement('span');
chip.className = 'content-compose-tag-chip';
const text = document.createElement('span');
text.className = 'content-compose-tag-text';
text.textContent = tag;
chip.appendChild(text);
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'content-compose-tag-remove';
btn.setAttribute('aria-label', '删除标签');
btn.innerHTML = '<i class="bi bi-x-lg"></i>';
btn.addEventListener('click', () => {
composeState.tags.splice(i, 1);
renderComposeTags();
if (composeState.mode === 'book' && composeState.draftFileId) {
scheduleMarkBookUploadPending({ meta: true });
}
});
chip.appendChild(btn);
container.appendChild(chip);
});
if (hidden) hidden.value = composeState.tags.join(', ');
}
function toggleComposeCoAuthorInput(show) {
const row = document.getElementById('content-compose-coauthors-input-row');
const btn = document.getElementById('content-compose-coauthor-show');
if (row) row.style.display = show ? 'flex' : 'none';
if (btn) btn.style.display = show ? 'none' : 'inline-flex';
if (show) {
const inp = document.getElementById('content-compose-coauthor-input');
if (inp) setTimeout(() => inp.focus(), 50);
}
}
async function tryAddComposeCoAuthor() {
const input = document.getElementById('content-compose-coauthor-input');
const v = input && String(input.value || '').trim();
if (!v) return;
const api = window.markwrite && window.markwrite.api;
if (!api || typeof api.eventstoreLookupUser !== 'function') {
showAppAlert('联合作者查询需要桌面版并已配置 Sync 服务器');
return;
}
let res;
try {
res = await api.eventstoreLookupUser({ value: v });
} catch (e) {
showAppAlert(`查询失败:${e && e.message ? e.message : String(e)}`);
return;
}
if (!res || !res.ok) {
showAppAlert((res && res.message) || '未找到用户');
return;
}
const pk = res.pubkey ? String(res.pubkey).trim() : '';
if (!pk) {
showAppAlert('未返回公钥');
return;
}
if (composeState.coAuthors.some((a) => a.pubkey === pk)) {
showAppAlert('该联合作者已存在');
if (input) input.value = '';
return;
}
composeState.coAuthors.push({
email: res.email ? String(res.email).trim() : '',
pubkey: pk,
});
if (input) input.value = '';
renderComposeCoAuthors();
toggleComposeCoAuthorInput(false);
if (composeState.mode === 'book' && composeState.draftFileId) {
scheduleMarkBookUploadPending({ meta: true });
}
}
function composeCoAuthorRowDisplay(co) {
const em = co && co.email != null ? String(co.email).trim() : '';
if (em) return em;
const pk = co && co.pubkey ? String(co.pubkey) : '';
if (pk.length > 20) return `${pk.slice(0, 8)}…${pk.slice(-6)}`;
return pk || '';
}
async function hydrateComposeCoAuthorEmails() {
const api = window.markwrite && window.markwrite.api;
if (!api || typeof api.eventstoreLookupUser !== 'function') return;
const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
let changed = false;
for (let i = 0; i < composeState.coAuthors.length; i++) {
const co = composeState.coAuthors[i];
if (!co || !co.pubkey) continue;
const em = String(co.email || '').trim();
if (em && emailRe.test(em)) continue;
try {
const res = await api.eventstoreLookupUser({ value: co.pubkey });
if (res && res.ok && res.email && String(res.email).trim()) {
composeState.coAuthors[i] = {
...co,
email: String(res.email).trim(),
};
changed = true;
}
} catch (_) {}
}
if (changed) renderComposeCoAuthors();
}
function renderComposeCoAuthors() {
const list = document.getElementById('content-compose-coauthors-list');
if (!list) return;
list.innerHTML = '';
composeState.coAuthors.forEach((co, i) => {
const row = document.createElement('div');
row.className = 'content-compose-coauthor-row';
const label = document.createElement('span');
label.className = 'content-compose-coauthor-label';
const display = composeCoAuthorRowDisplay(co);
label.textContent = display;
label.title = (co && co.pubkey) ? String(co.pubkey) : '';
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'content-compose-coauthor-remove';
btn.setAttribute('aria-label', '移除联合作者');
btn.innerHTML = '<i class="bi bi-x-lg"></i>';
btn.addEventListener('click', () => {
composeState.coAuthors = composeState.coAuthors.filter((_, j) => j !== i);
renderComposeCoAuthors();
if (composeState.mode === 'book' && composeState.draftFileId) {
scheduleMarkBookUploadPending({ meta: true });
}
});
row.appendChild(label);
row.appendChild(btn);
list.appendChild(row);
});
}
function addComposeTagFromInput() {
const input = document.getElementById('content-compose-tag-input');
const v = normalizeComposeTag(input && input.value);
if (!v) return;
if (composeState.tags.includes(v)) {
if (input) input.value = '';
return;
}
composeState.tags.push(v);
if (input) input.value = '';
renderComposeTags();
if (composeState.mode === 'book' && composeState.draftFileId) {
scheduleMarkBookUploadPending({ meta: true });
}
}
function setComposeUploadProgress(text, kind) {
if (!contentComposeUploadProgress) return;
const msg = String(text || '').trim();
if (!msg) {
contentComposeUploadProgress.textContent = '';
contentComposeUploadProgress.style.display = 'none';
contentComposeUploadProgress.classList.remove('is-error');
return;
}
contentComposeUploadProgress.style.display = 'block';
contentComposeUploadProgress.textContent = msg;
contentComposeUploadProgress.classList.toggle('is-error', kind === 'error');
}
function setComposeGenerateStatus(text, kind) {
if (!contentComposeGenerateStatus) return;
const msg = String(text || '').trim();
if (composeGenerateStatusTimer) {
clearTimeout(composeGenerateStatusTimer);
composeGenerateStatusTimer = null;
}
if (!msg) {
contentComposeGenerateStatus.textContent = '';
contentComposeGenerateStatus.style.display = 'none';
contentComposeGenerateStatus.classList.remove('is-loading', 'is-success');
return;
}
contentComposeGenerateStatus.style.display = 'inline-flex';
contentComposeGenerateStatus.textContent = msg;
contentComposeGenerateStatus.classList.toggle('is-loading', kind === 'loading');
contentComposeGenerateStatus.classList.toggle('is-success', kind === 'success');
if (kind === 'success') {
composeGenerateStatusTimer = setTimeout(() => setComposeGenerateStatus(''), 1800);
}
}
/** 书籍大纲由树同步到隐藏 textarea;始终用 document 取当前节点,避免模板切换后缓存引用失效。 */
function getLiveBookOutlineTextFromDom() {
const el = document.getElementById('content-compose-outline');
return el && typeof el.value === 'string' ? el.value.trim() : '';
}
function isBookOutlineDirtyComparedToBaseline() {
if (composeState.mode !== 'book') return false;
return getLiveBookOutlineTextFromDom() !== getOutlineFromSerializedState(composeBaselineSerialized);
}
function readComposeDraftFromUi() {
const titleEl = document.getElementById('content-compose-main-title');
const coverEl = document.getElementById('content-compose-cover');
const extraEl = document.getElementById('content-compose-extra');
const authorEl = document.getElementById('content-compose-author');
const outline = getLiveBookOutlineTextFromDom();
let content = editor ? editor.getValue() : '';
if (composeState.mode === 'book') {
const map = { ...composeState.bookChapterContents };
const aid = composeState.bookActiveChapterId;
if (aid != null && editor) map[aid] = editor.getValue();
const ids = collectBookChapterIdsFromOutlineStr(outline);
content = mergeBookChaptersPlain(ids, map);
}
const isBook = composeState.mode === 'book';
return {
title: (titleEl && titleEl.value.trim()) || '',
tags: composeState.tags.length ? composeState.tags.join(', ') : '',
cover: (coverEl && coverEl.value.trim()) || '',
extra: isBook ? '' : ((extraEl && extraEl.value.trim()) || ''),
/** 博客:作者由发布端/身份自动生成,不采集联合作者 */
author: isBook && authorEl ? authorEl.value.trim() : '',
coAuthors: isBook && Array.isArray(composeState.coAuthors)
? composeState.coAuthors.map((x) => ({
email: typeof x.email === 'string' ? x.email : '',
pubkey: typeof x.pubkey === 'string' ? x.pubkey : '',
}))
: [],
outline,
content,
};
}
/** 与主进程书籍草稿一致:编辑器用 <!-- mw-chapter:id --> 分章;发布/上传前去掉标记 */
function stripMwChapterMarkers(md) {
return String(md || '').replace(/<!--\s*mw-chapter:\d+\s*-->\s*/g, '');
}
function collectBookChapterIdsFromOutlineStr(outlineStr) {
try {
const j = JSON.parse(String(outlineStr || '').trim() || '[]');
const ids = [];
function walk(items) {
if (!Array.isArray(items)) return;
items.forEach((it) => {
if (!it || typeof it !== 'object') return;
if (it.type === 'chapter' && typeof it.id === 'number') ids.push(it.id);
if (Array.isArray(it.children)) walk(it.children);
});
}
walk(Array.isArray(j) ? j : []);
return ids;
} catch (_) {
return [];
}
}
function splitEditorIntoBookChapterMap(content, outlineStr) {
const s = String(content || '');
const re = /<!--\s*mw-chapter:(\d+)\s*-->/g;
const matches = [];
let m;
while ((m = re.exec(s)) !== null) {
matches.push({ id: Number(m[1]), start: m.index, endAfter: m.index + m[0].length });
}
const ids = collectBookChapterIdsFromOutlineStr(outlineStr);
const map = {};
if (matches.length === 0) {
if (ids.length) map[ids[0]] = s;
ids.slice(1).forEach((id) => { map[id] = ''; });
return map;
}
for (let i = 0; i < matches.length; i++) {
const cur = matches[i];
const next = matches[i + 1];
let body = s.slice(cur.endAfter, next ? next.start : s.length);
if (body.startsWith('\n')) body = body.slice(1);
map[cur.id] = body;
}
ids.forEach((id) => {
if (map[id] === undefined) map[id] = '';
});
return map;
}
function mergeBookChaptersPlain(ids, map) {
return ids.map((id) => String(map[id] != null ? map[id] : '')).join('\n\n');
}
function buildBookChapterContentsPayload() {
const map = { ...composeState.bookChapterContents };
const aid = composeState.bookActiveChapterId;
if (aid != null && editor) map[aid] = editor.getValue();
return map;
}
function walkOutlineChapterIdsForPrune(items, out) {
if (!Array.isArray(items)) return;
items.forEach((it) => {
if (!it || typeof it !== 'object') return;
if (it.type === 'chapter' && typeof it.id === 'number') out.push(it.id);
if (Array.isArray(it.children)) walkOutlineChapterIdsForPrune(it.children, out);
});
}
function pruneBookChapterContentsToOutlineItems(items) {
const ids = [];
walkOutlineChapterIdsForPrune(Array.isArray(items) ? items : [], ids);
const set = new Set(ids);
Object.keys(composeState.bookChapterContents).forEach((k) => {
const n = Number(k);
if (!set.has(n)) delete composeState.bookChapterContents[k];
});
if (composeState.bookActiveChapterId != null && !set.has(composeState.bookActiveChapterId)) {
const first = ids[0];
composeState.bookActiveChapterId = first != null ? first : null;
if (editor) {
runWithBookPendingSuppressed(() => {
editor.setValue(first != null ? String(composeState.bookChapterContents[first] ?? '') : '');
});
}
if (bookOutlinePaneInstance && first != null) {
bookOutlinePaneInstance.setSelectedChapterId(first);
}
}
}
let bookChapterSwitchResolver = null;
function openBookChapterSwitchConfirm() {
return new Promise((resolve) => {
bookChapterSwitchResolver = resolve;
const el = document.getElementById('book-chapter-switch-modal');
if (el) {
el.style.display = 'flex';
el.setAttribute('aria-hidden', 'false');
} else {
resolve('cancel');
}
});
}
function closeBookChapterSwitchModal(choice) {
const el = document.getElementById('book-chapter-switch-modal');
if (el) {
el.style.display = 'none';
el.setAttribute('aria-hidden', 'true');
}
if (bookChapterSwitchResolver) {
bookChapterSwitchResolver(choice);
bookChapterSwitchResolver = null;
}
}
async function onBeforeBookChapterSelect(nextId, prevId) {
if (composeState.mode !== 'book' || !editor) return true;
if (prevId == null || prevId === nextId) {
composeState.bookActiveChapterId = nextId;
runWithBookPendingSuppressed(() => {
editor.setValue(String(composeState.bookChapterContents[nextId] ?? ''));
});
return true;
}
const cur = editor.getValue();
const committed = String(composeState.bookChapterContents[prevId] ?? '');
if (cur === committed) {
composeState.bookActiveChapterId = nextId;
runWithBookPendingSuppressed(() => {
editor.setValue(String(composeState.bookChapterContents[nextId] ?? ''));
});
return true;
}
const choice = await openBookChapterSwitchConfirm();
if (choice === 'cancel') return false;
if (choice === 'save') {
composeState.bookChapterContents[prevId] = cur;
const r = await saveComposeDraftToDisk();
if (!r.ok) {
showAppAlert(r.error || '保存失败');
return false;
}
markComposeBaselineFromCurrent();
}
composeState.bookActiveChapterId = nextId;
runWithBookPendingSuppressed(() => {
editor.setValue(String(composeState.bookChapterContents[nextId] ?? ''));
});
return true;
}
function onBookOutlineSynced(items) {
if (composeState.mode !== 'book') return;
pruneBookChapterContentsToOutlineItems(items);
updateBookOutlineSaveButtonState();
}
function wireBookOutlinePaneIPC() {
if (!bookOutlinePaneInstance) return;
bookOutlinePaneInstance.onBeforeChapterSelect = onBeforeBookChapterSelect;
bookOutlinePaneInstance.onOutlineSynced = onBookOutlineSynced;
}
function initEmptyBookChapterMapFromOutlineStr(outlineStr) {
const ids = collectBookChapterIdsFromOutlineStr(outlineStr);
const m = {};
ids.forEach((id) => { m[id] = ''; });
composeState.bookChapterContents = m;
}
/**
* 将当前创作页(文章信息 + 大纲 + 正文)写入本地草稿文件,生成/固定 draftFileId。
* 发布到服务器前应先调用,否则没有本地索引,远端 ID 难以可靠写回。
* @param {{ bookSaveChapterOnly?: boolean }} [opts] `bookSaveChapterOnly`:仅写入当前章节的 `chapters/{id}.md`,不覆盖其它章节文件。
*/
async function saveComposeDraftToDisk(opts) {
const o = opts && typeof opts === 'object' ? opts : {};
const api = window.markwrite && window.markwrite.api;
if (!api || typeof api.composeDraftsSave !== 'function') {
return { ok: false, error: '草稿保存不可用(请使用桌面版)' };
}
if (!composeState.mode) {
return { ok: false, error: '请先通过「新建 Blog / 新建书籍」进入创作页' };
}
const ui = readComposeDraftFromUi();
if (composeState.mode === 'book' && !String(ui.author || '').trim()) {
return { ok: false, error: '请先填写作者' };
}
if (composeState.mode === 'book' && o.bookSaveChapterOnly) {
if (!composeState.draftFileId) {
return { ok: false, error: '请先完整保存一次书籍草稿后再仅保存本章' };
}
commitActiveBookChapterFromEditor();
const aid = composeState.bookActiveChapterId;
if (aid == null) return { ok: false, error: '未选中章节' };
const body = String(composeState.bookChapterContents[aid] ?? '');
const payloadChapter = {
id: composeState.draftFileId,
mode: 'book',
title: ui.title,
tags: composeState.tags.slice(),
cover: ui.cover,
extra: ui.extra,
author: ui.author || '',
coAuthors: Array.isArray(ui.coAuthors) ? ui.coAuthors : [],
outline: getLiveBookOutlineTextFromDom() || ui.outline || '',
content: '',
remoteId: composeState.remoteId || '',
assetMap: composeState.assetMap || {},
bookSaveChapterOnly: aid,
chapterContents: { [String(aid)]: body },
};
const resCh = await api.composeDraftsSave(payloadChapter);
if (resCh && resCh.ok && resCh.id) {
return { ok: true, id: resCh.id };
}
return { ok: false, error: (resCh && resCh.error) || '保存章节失败' };
}
const payload = {
id: composeState.draftFileId || undefined,
mode: composeState.mode || 'blog',
title: ui.title,
tags: composeState.tags.slice(),
cover: ui.cover,
extra: ui.extra,
author: ui.author || '',
coAuthors: Array.isArray(ui.coAuthors) ? ui.coAuthors : [],
outline: ui.outline || '',
content: ui.content,
remoteId: composeState.remoteId || '',
assetMap: composeState.assetMap || {},
};
if (composeState.mode === 'book') {
const cc = buildBookChapterContentsPayload();
const ids = collectBookChapterIdsFromOutlineStr(ui.outline || '');
ids.forEach((id) => {
if (cc[id] === undefined) cc[id] = '';
});
payload.chapterContents = cc;
payload.content = mergeBookChaptersPlain(ids, cc);
}
if (composeState.mode === 'book' && !composeState.draftFileId && composeState.bookNewLocalSalt) {
let myPk = '';
if (typeof api.identityGet === 'function') {
try {
const idRes = await api.identityGet({ serverId: getActiveSyncServerIdForIdentity() });
myPk = (idRes && idRes.pubkeyHex) ? String(idRes.pubkeyHex).trim() : '';
} catch (_) {}
}
if (!myPk && identityKeyHexCache.pubkeyHex) myPk = identityKeyHexCache.pubkeyHex;
const stableId = buildRemoteImportDraftId({
mode: 'book',
title: ui.title,
remoteId: composeState.bookNewLocalSalt,
authorPubkeyHex: myPk,
});
const go = await confirmOverwriteIfLocalDraftExists(api, stableId);
if (!go) return { ok: false, error: '已取消保存' };
payload.id = stableId;
}
let outlineWasDirtyBeforeFullSave = false;
if (composeState.mode === 'book') {
const liveOutline = getLiveBookOutlineTextFromDom();
payload.outline = liveOutline;
const cc = buildBookChapterContentsPayload();
const ids = collectBookChapterIdsFromOutlineStr(liveOutline);
ids.forEach((id) => {
if (cc[id] === undefined) cc[id] = '';
});
payload.chapterContents = cc;
payload.content = mergeBookChaptersPlain(ids, cc);
outlineWasDirtyBeforeFullSave = isBookOutlineDirtyComparedToBaseline();
}
const res = await api.composeDraftsSave(payload);
if (res && res.ok && res.id) {
composeState.draftFileId = res.id;
composeState.bookNewLocalSalt = null;
if (composeState.mode === 'book') {
commitActiveBookChapterFromEditor();
if (
outlineWasDirtyBeforeFullSave
&& typeof api.composeBookUploadMarkPending === 'function'
) {
try {
await api.composeBookUploadMarkPending({ draftId: res.id, outline: true });
} catch (_) {}
}
}
return { ok: true, id: res.id };
}
return { ok: false, error: (res && res.error) || '保存草稿失败' };
}
function serializeComposeDraftState() {
const ui = readComposeDraftFromUi();
const am = composeState.assetMap && typeof composeState.assetMap === 'object' ? composeState.assetMap : {};
const isBook = composeState.mode === 'book';
return JSON.stringify({
mode: composeState.mode || '',
title: ui.title,
cover: ui.cover,
extra: ui.extra,
author: isBook ? (ui.author || '') : '',
coAuthors: isBook && Array.isArray(composeState.coAuthors) ? composeState.coAuthors.slice() : [],
outline: ui.outline || '',
content: ui.content,
tags: composeState.tags.slice(),
draftFileId: composeState.draftFileId || null,
remoteId: composeState.remoteId || '',
assetMap: am,
});
}
function markEditorBaselineFromCurrent() {
if (!editor) return;
editorBaseline = {
path: currentFilePath,
content: editor.getValue(),
};
}
/** 书籍:把当前章 Monaco 正文写回 bookChapterContents。切换章节时用 map 与编辑器比较「是否未保存」,保存后必须同步,否则会误判。 */
function commitActiveBookChapterFromEditor() {
if (composeState.mode !== 'book' || !editor) return;
const aid = composeState.bookActiveChapterId;
if (aid == null) return;
composeState.bookChapterContents[aid] = editor.getValue();
}
/** 书籍:显式「待上传」标记(见 book-upload-sync.json pending),不用 SHA */
function scheduleMarkBookUploadPending(patch) {
if (composeState.mode !== 'book' || !composeState.draftFileId) return;
if (bookPendingSuppress > 0) return;
if (bookUploadPendingTimer) clearTimeout(bookUploadPendingTimer);
bookUploadPendingTimer = setTimeout(() => {
bookUploadPendingTimer = null;
if (bookPendingSuppress > 0) return;
const api = window.markwrite && window.markwrite.api;
if (!api || typeof api.composeBookUploadMarkPending !== 'function') return;
void api.composeBookUploadMarkPending({ draftId: composeState.draftFileId, ...patch });
}, 400);
}
function runWithBookPendingSuppressed(fn) {
bookPendingSuppress++;
try {
fn();
} finally {
bookPendingSuppress--;
}
}
function markComposeBaselineFromCurrent() {
commitActiveBookChapterFromEditor();
composeBaselineSerialized = serializeComposeDraftState();
updateBookOutlineSaveButtonState();
}
function getOutlineFromSerializedState(s) {
if (!s) return '';
try {
const j = JSON.parse(String(s));
return (j && typeof j.outline === 'string') ? j.outline.trim() : '';
} catch (_) {
return '';
}
}
function updateBookOutlineSaveButtonState() {
const btn = document.getElementById('book-outline-save-draft');
if (!btn) return;
if (composeState.mode !== 'book') {
btn.classList.remove('is-dirty');
return;
}
const currentOutline = getLiveBookOutlineTextFromDom();
const baselineOutline = getOutlineFromSerializedState(composeBaselineSerialized);
btn.classList.toggle('is-dirty', currentOutline !== baselineOutline);
}
function isContentDirty() {
if (composeState.mode) {
return serializeComposeDraftState() !== composeBaselineSerialized;
}
if (!editor) return false;
const p = currentFilePath || null;
const bp = editorBaseline.path || null;
return editor.getValue() !== editorBaseline.content || p !== bp;
}
/**
* 将服务端返回的相对路径拼成可访问 URL(与 main.js compose 上传里 mkPublicUrl 一致)。
* uploadpath 已以 /uploads 结尾时不再重复加 uploads/;否则为纯文件名等补上 uploads/。
*/
function toPublicUploadUrl(webPath) {
const rel = (webPath || '').trim();
if (!rel) return '';
if (/^https?:\/\//i.test(rel) || /^data:/i.test(rel) || /^blob:/i.test(rel)) return rel;
if (/^\/\//.test(rel)) {
try {
return `${window.location.protocol}${rel}`;
} catch (_) {
return `https:${rel}`;
}
}
const active = getActiveSyncServer();
const uploadBase = active && typeof active.uploadpath === 'string' ? active.uploadpath.trim() : '';
if (!uploadBase) return rel;
let p = rel.replace(/^\//, '');
try {
const base = uploadBase.endsWith('/') ? uploadBase : `${uploadBase}/`;
const baseUrl = new URL(base);
const basePath = (baseUrl.pathname || '').replace(/\/+$/, '');
if (/\/uploads$/i.test(basePath)) {
if (/^uploads\//i.test(p)) p = p.replace(/^uploads\//i, '');
return String(new URL(p, base).href).replace(/\/uploads\/uploads\//gi, '/uploads/');
}
if (!/^uploads\//i.test(p)) p = `uploads/${p}`;
return String(new URL(p, base).href).replace(/\/uploads\/uploads\//gi, '/uploads/');
} catch (_) {
const b = uploadBase.replace(/\/+$/, '');
if (/\/uploads$/i.test(b)) {
if (/^uploads\//i.test(p)) p = p.replace(/^uploads\//i, '');
return `${b}/${p}`.replace(/\/uploads\/uploads\//gi, '/uploads/');
}
if (!/^uploads\//i.test(p)) p = `uploads/${p}`;
return `${b}/${p}`.replace(/\/uploads\/uploads\//gi, '/uploads/');
}
}
/** 封面图:绝对 URL、协议相对、本地 uploads/*、其余走 Sync 的 uploadpath */
function resolveCoverImgSrc(v) {
const raw = String(v || '').trim();
if (!raw) return '';
if (/^https?:\/\//i.test(raw) || /^data:/i.test(raw) || /^blob:/i.test(raw)) return raw;
if (/^\/\//.test(raw)) {
try {
return `${window.location.protocol}${raw}`;
} catch (_) {
return `https:${raw}`;
}
}
if (/^\/?uploads\//i.test(raw)) return `/${raw.replace(/^\//, '')}`;
return toPublicUploadUrl(raw);
}
function normalizeLocalUploadsWebPath(v) {
const raw = String(v || '').trim();
if (!raw) return '';
if (/^\/?uploads\//i.test(raw)) return raw.replace(/^\//, '');
return raw;
}
function resolveComposeCoverPreviewSrc(v) {
return resolveCoverImgSrc(v);
}
function renderComposeCoverPreview(url) {
if (!contentComposeCoverPreview) return;
contentComposeCoverPreview.innerHTML = '';
const src = resolveComposeCoverPreviewSrc(url);
if (!src) {
const icon = document.createElement('i');
icon.className = 'bi bi-image';
contentComposeCoverPreview.appendChild(icon);
return;
}
const img = document.createElement('img');
img.src = src;
img.alt = '';
img.onerror = () => {
contentComposeCoverPreview.innerHTML = '<i class="bi bi-image"></i>';
};
contentComposeCoverPreview.appendChild(img);
}
async function applyProfileAvatarFile(file) {
if (!file) return false;
if (!file.type || !file.type.startsWith('image/')) {
showAppAlert('请选择图片文件(png/jpg/webp/gif)');
return false;
}
if (file.size > 3 * 1024 * 1024) {
showAppAlert('图片过大,请选择 3MB 以内的头像');
return false;
}
try {
const dataUrl = await fileToDataUrl(file);
if (!dataUrl) throw new Error('图片数据为空');
profileServerAvatarUrl = dataUrl;
profileDirtyInSession = true;
renderProfileAvatarPreview(profileServerAvatarUrl);
return true;
} catch (e) {
showAppAlert(`头像上传失败:${e && e.message ? e.message : String(e)}`);
return false;
}
}
function normalizeRemoteProfile(raw) {
const p = raw && typeof raw === 'object' ? raw : {};
const displayName = String(
p.displayName || p.display_name || p.name || p.nickname || p.nick || '',
).trim();
const title = String(
p.title || p.jobTitle || p.job_title || p.role || '',
).trim();
const bio = String(
p.bio || p.about || p.description || p.intro || '',
).trim();
const avatarUrl = String(
p.avatarUrl || p.avatar_url || p.avatar || p.picture || p.image || '',
).trim();
return { displayName, title, bio, avatarUrl };
}
const PREVIEW_THEME_CSS = [
'base.css',
'vars.css',
'fonts.css',
'icons.css',
'utils.css',
'components/custom-block.css',
'components/vp-code.css',
'components/vp-doc.css',
'components/vp-code-group.css',
'components/vp-sponsor.css',
];
const base = '/preview-theme/';
PREVIEW_THEME_CSS.forEach((name) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = base + name;
document.head.appendChild(link);
});
const container = document.getElementById('monaco-container');
const editorFilename = document.getElementById('editor-filename');
const syncConnStatus = document.getElementById('sync-conn-status');
const syncConnText = document.getElementById('sync-conn-text');
const syncConnReconnectBtn = document.getElementById('sync-conn-reconnect');
// 旧的文件操作按钮(已在 UI 隐藏,仍可复用其逻辑)
const btnOpen = document.getElementById('btn-open');
const btnToggleExplorer = document.getElementById('btn-toggle-explorer');
const btnExpandExplorer = document.getElementById('btn-expand-explorer');
const btnRefreshFiles = document.getElementById("btn-refresh-files");
const btnNew = document.getElementById('btn-new');
const btnSave = document.getElementById('btn-save');
const btnSaveAs = document.getElementById('btn-saveas');
// 顶部自定义菜单项
const menuFileNew = document.getElementById('menu-file-new');
const menuFileOpen = document.getElementById('menu-file-open');
const menuFileSave = document.getElementById('menu-file-save');
const menuFileSaveAs = document.getElementById('menu-file-saveas');
const menuFileOpenWorkspace = document.getElementById('menu-file-open-workspace');
const menuViewToggleExplorer = document.getElementById('menu-view-toggle-explorer');
const menuViewTogglePreview = document.getElementById('menu-view-toggle-preview');
const menuViewToggleDevTools = document.getElementById('menu-view-toggle-devtools');
const menuSettingsOpen = document.getElementById('menu-settings-open');
const menuContentNewBlog = document.getElementById('menu-content-new-blog');
const menuContentNewBook = document.getElementById('menu-content-new-book');
const menuContentDraftsBlog = document.getElementById('menu-content-drafts-blog');
const menuContentDraftsBook = document.getElementById('menu-content-drafts-book');
const menuContentRemoteBlogMine = document.getElementById('menu-content-remote-blog-mine');
const menuContentRemoteBlogAll = document.getElementById('menu-content-remote-blog-all');
const menuContentRemoteBookMine = document.getElementById('menu-content-remote-book-mine');
const menuContentRemoteBookAll = document.getElementById('menu-content-remote-book-all');
const contentComposePanel = document.getElementById('content-compose-panel');
const contentComposeTopHost = document.getElementById('content-compose-top-host');
const contentComposeBottomHost = document.getElementById('content-compose-bottom-host');
let contentComposeTitle = document.getElementById('content-compose-title');
let contentComposeSubtitle = document.getElementById('content-compose-subtitle');
let contentComposeMainTitle = null;
let contentComposeTagInput = null;
let contentComposeTagAdd = null;
let contentComposeCover = null;
let contentComposeAuthor = null;
let contentComposeExtraWrap = null;
let contentComposeExtra = null;
let contentComposeGenerateTags = null;
let contentComposeGenerateSummary = null;
let contentComposeGenerateStatus = null;
let contentComposeCoverUpload = null;
let contentComposeCoverScreenshot = null;
let contentComposeCoverFile = null;