-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathp2p.js
More file actions
3706 lines (3369 loc) · 118 KB
/
p2p.js
File metadata and controls
3706 lines (3369 loc) · 118 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
import {
markdownInput,
markdownPreview,
slidesPreview,
viewSlidesButton,
fullPreviewButton,
createRoomButton,
joinForm,
joinRoomKey,
privateMode,
udpMode,
localHostInput,
localPortInput,
setupPage,
editorPage,
roomStatus,
roomKeyLabel,
roomRoleBadge,
copyRoomKey,
peersCount,
peersLink,
localUrlLabel,
exportMenu,
exportHtmlButton,
exportPdfButton,
exportSlidesButton,
disconnectButton,
protocolSelect,
titleInput,
publishButton,
clearDraftButton,
publishList,
fetchCidInput,
fetchButton,
} from "./common.js";
import { initMarkdown, renderPreview, scheduleRender, showSpinner, renderMarkdown } from "./noteEditor.js";
import { initToolbar } from "./toolbar.js";
import { initCursorOverlay, updateCursorOverlay, destroyCursorOverlay,
setLocalColor, updateLineAuthors } from "./cursorOverlay.js";
let sendTimer = null;
let saveTimer = null;
let eventSource = null;
let lastSentContent = "";
let lastSavedContent = "";
let currentRoomUrl = null;
let currentRoomKey = null;
let hyperdriveUrl = null;
let draftDriveUrl = null;
let lastDraftPayload = null;
let justCreatedRoom = false;
let ydoc = null;
let ytext = null;
let pendingUpdate = null;
let sendUpdateTimer = null;
let flushRetryTimer = null;
let flushRetryCount = 0;
const MAX_FLUSH_RETRIES = 10;
let prevText = "";
let isApplyingRemote = false;
let savedYjsState = null; // Save Yjs CRDT state (not just text) for proper merge on reconnect
let currentRole = null;
let reconnectTimer = null;
let isRecoveringYjsState = false;
const MAX_PENDING_UPDATE_BYTES = 2 * 1024 * 1024;
const Y_ORIGIN_REMOTE = "remote-sse";
const ROOM_STATE_PREFIX = "p2pmd-room-";
const ROOM_CONTENT_PREFIX = "p2pmd-room-content-";
const ROOM_LINE_ATTR_PREFIX = "p2pmd-room-line-attributions-";
const ROOM_LOCAL_LINE_ATTR_PREFIX = "p2pmd-room-local-line-attributions-";
const PEER_STATUS_PREFIX = "p2pmd-peer-status-";
const PEER_ACTIVITY_PREFIX = "p2pmd-peer-activity-";
const ACTIVE_ROOM_STATUS_KEY = "p2pmd-active-room";
const LAST_ROOM_KEY = "p2pmd-last-room";
const LAST_ROOM_STATE = "p2pmd-last-room-state";
const DISPLAY_NAME_KEY = "p2pmd-display-name";
const USER_COLOR_KEY = "p2pmd-user-color";
const CLIENT_ID_KEY = "p2pmd-client-id";
const DRAFT_DRIVE_NAME = "p2pmd-drafts";
const MAX_ACTIVITY_ITEMS = 150;
const PRESENCE_THROTTLE_MS = 220;
const TYPING_IDLE_MS = 1200;
const PEER_FALLBACK_NAME_LEN = 8;
const saveDelay = 2000;
let hyperSaveInFlight = false;
let draftSaveInFlight = false;
const draftSnapshotCache = new Map();
let currentPeerList = [];
let peerActivityLog = [];
let presenceSendTimer = null;
let typingResetTimer = null;
let lineAttributionPersistTimer = null;
let isLocalTyping = false;
let lastPresencePayload = "";
const onboardingPage = document.getElementById("onboarding-page");
const onboardingNameInput = document.getElementById("onboarding-name");
const onboardingSubmitButton = document.getElementById("onboard-submit");
const publishCSS = `
@font-face {
font-family: 'FontWithASyntaxHighlighter';
src: url('browser://theme/fonts/FontWithASyntaxHighlighter-Regular.woff2') format('woff2');
}
:root {
color-scheme: light;
}
html,
body {
margin: 0;
padding: 0;
background: #ffffff;
color: #111111;
}
body {
font-family: system-ui, -apple-system, sans-serif;
line-height: 1.6;
padding: 2rem;
}
pre, code {
background: #2d2d2d;
color: #f8f8f2;
font-weight: 1000;
padding: 0.15rem 0.35rem;
border-radius: 6px;
font-family: 'FontWithASyntaxHighlighter', monospace;
}
pre code {
display: block;
padding: 1rem;
overflow: auto;
}
blockquote {
border-left: 3px solid #d1d5db;
padding-left: 1rem;
color: #374151;
}
footer.p2pmd-footer {
margin-top: 2rem;
font-size: 0.9rem;
color: #4b5563;
}
footer.p2pmd-footer a {
color: inherit;
}
`;
function fetchWithTimeout(url, options = {}, timeoutMs = 2000) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeoutMs);
const merged = { ...options, signal: controller.signal };
return fetch(url, merged).finally(() => clearTimeout(id));
}
async function pingServerStatus(localUrl, attempts = 5) {
let retries = attempts;
while (retries > 0) {
try {
const res = await fetchWithTimeout(`${localUrl}/status`, {}, 1500);
if (res.ok) return true;
} catch {}
retries--;
await new Promise(resolve => setTimeout(resolve, 200));
}
return false;
}
function safeLocalStorageGet(key) {
try {
return localStorage.getItem(key);
} catch {
return null;
}
}
function safeLocalStorageSet(key, value) {
try {
localStorage.setItem(key, value);
} catch {}
}
function safeLocalStorageRemove(key) {
try {
localStorage.removeItem(key);
} catch {}
}
function getRoomLineAttributionStorageKey(roomKey) {
return `${ROOM_LINE_ATTR_PREFIX}${roomKey}`;
}
function getLocalLineAttributionStorageKey(roomKey) {
return `${ROOM_LOCAL_LINE_ATTR_PREFIX}${roomKey}`;
}
function readRoomLineAttributions(roomKey) {
const candidates = getRoomKeyCandidates(roomKey);
if (candidates.length === 0) return {};
for (const candidate of candidates) {
const raw = safeLocalStorageGet(getRoomLineAttributionStorageKey(candidate));
if (!raw) continue;
try {
const parsed = JSON.parse(raw);
const normalized = normalizeLineAttributions(parsed?.lineAttributions || parsed);
if (normalized) return normalized;
} catch {}
}
return {};
}
function clearLocalLineAttributions(roomKey) {
const candidates = getRoomKeyCandidates(roomKey);
if (candidates.length === 0) return;
for (const candidate of candidates) {
safeLocalStorageRemove(getLocalLineAttributionStorageKey(candidate));
}
}
function persistRoomLineAttributionsNow() {
if (!currentRoomKey) return;
const normalizedRoom = normalizeLineAttributions(_roomLineAttributions);
const normalizedLocal = normalizeLineAttributions(_localLineAttributions);
const candidates = getRoomKeyCandidates(currentRoomKey);
for (const candidate of candidates) {
const roomStorageKey = getRoomLineAttributionStorageKey(candidate);
if (!normalizedRoom) {
safeLocalStorageRemove(roomStorageKey);
} else {
safeLocalStorageSet(roomStorageKey, JSON.stringify({
roomKey: currentRoomKey,
lineAttributions: normalizedRoom,
updatedAt: Date.now()
}));
}
const localStorageKey = getLocalLineAttributionStorageKey(candidate);
if (!normalizedLocal) {
safeLocalStorageRemove(localStorageKey);
continue;
}
safeLocalStorageSet(localStorageKey, JSON.stringify({
roomKey: currentRoomKey,
lineAttributions: normalizedLocal,
updatedAt: Date.now()
}));
}
}
function scheduleRoomLineAttributionsPersist() {
if (lineAttributionPersistTimer) clearTimeout(lineAttributionPersistTimer);
lineAttributionPersistTimer = setTimeout(() => {
lineAttributionPersistTimer = null;
persistRoomLineAttributionsNow();
}, 250);
}
function buildRandomClientId() {
try {
if (window.crypto?.randomUUID) {
return window.crypto.randomUUID();
}
} catch {}
return `client-${Math.random().toString(36).slice(2, 10)}-${Date.now().toString(36)}`;
}
function getOrCreateClientId() {
const existing = safeLocalStorageGet(CLIENT_ID_KEY);
if (existing && typeof existing === "string") return existing;
const next = buildRandomClientId();
safeLocalStorageSet(CLIENT_ID_KEY, next);
return next;
}
function normalizeDisplayName(value) {
if (typeof value !== "string") return "";
return value.trim().replace(/\s+/g, " ").slice(0, 32);
}
function getDisplayName() {
return normalizeDisplayName(safeLocalStorageGet(DISPLAY_NAME_KEY) || "");
}
function saveDisplayName(value) {
const next = normalizeDisplayName(value);
if (!next) {
safeLocalStorageRemove(DISPLAY_NAME_KEY);
return "";
}
safeLocalStorageSet(DISPLAY_NAME_KEY, next);
getOrCreateLocalPeerColor();
return next;
}
function hasDisplayName() {
return !!getDisplayName();
}
function normalizeHexColor(value) {
if (typeof value !== "string") return "";
const trimmed = value.trim();
return /^#[0-9a-fA-F]{6}$/.test(trimmed) ? trimmed.toUpperCase() : "";
}
function hslToHex(h, s, l) {
const hue = ((Number(h) % 360) + 360) % 360;
const sat = Math.max(0, Math.min(100, Number(s))) / 100;
const lig = Math.max(0, Math.min(100, Number(l))) / 100;
const c = (1 - Math.abs(2 * lig - 1)) * sat;
const x = c * (1 - Math.abs((hue / 60) % 2 - 1));
const m = lig - c / 2;
let r = 0;
let g = 0;
let b = 0;
if (hue < 60) [r, g, b] = [c, x, 0];
else if (hue < 120) [r, g, b] = [x, c, 0];
else if (hue < 180) [r, g, b] = [0, c, x];
else if (hue < 240) [r, g, b] = [0, x, c];
else if (hue < 300) [r, g, b] = [x, 0, c];
else [r, g, b] = [c, 0, x];
const toHex = (v) => Math.round((v + m) * 255).toString(16).padStart(2, "0").toUpperCase();
return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
function createReadablePeerColor() {
let hue = Math.floor(Math.random() * 360);
try {
if (window.crypto?.getRandomValues) {
const bytes = new Uint8Array(1);
window.crypto.getRandomValues(bytes);
hue = bytes[0] / 255 * 360;
}
} catch {}
return hslToHex(hue, 72, 44);
}
function getOrCreateLocalPeerColor() {
const existing = normalizeHexColor(safeLocalStorageGet(USER_COLOR_KEY) || "");
if (existing) return existing;
const next = createReadablePeerColor();
safeLocalStorageSet(USER_COLOR_KEY, next);
return next;
}
function getLocalPeerColor() {
return normalizeHexColor(safeLocalStorageGet(USER_COLOR_KEY) || "") || getOrCreateLocalPeerColor();
}
function showSetupBootScreen() {
showSpinner(true);
}
function hideSetupBootScreen() {
showSpinner(false);
}
function syncOnboardingInput() {
if (!onboardingNameInput) return;
onboardingNameInput.value = getDisplayName();
}
function ensureProfileBeforeRoomAction() {
if (hasDisplayName()) return true;
setView("onboarding");
syncOnboardingInput();
if (onboardingNameInput) onboardingNameInput.focus();
return false;
}
function truncateIdentifier(value, size = 10) {
if (!value || typeof value !== "string") return "";
const trimmed = value.trim();
if (trimmed.length <= size) return trimmed;
return `${trimmed.slice(0, size)}...`;
}
function getCursorDetails(text, offset) {
const safeText = typeof text === "string" ? text : "";
const safeOffset = Number.isFinite(offset) ? Math.max(0, Math.min(offset, safeText.length)) : 0;
const prefix = safeText.slice(0, safeOffset);
const lines = prefix.split("\n");
return {
offset: safeOffset,
line: lines.length,
column: (lines[lines.length - 1] || "").length + 1
};
}
const localClientId = getOrCreateClientId();
const urlParams = new URLSearchParams(window.location.search);
const paramProtocol = urlParams.get("protocol");
const storedProtocol = safeLocalStorageGet("lastProtocol");
const initialProtocol = paramProtocol || storedProtocol || "hyper";
if (protocolSelect) {
protocolSelect.value = initialProtocol;
}
getOrCreateLocalPeerColor();
function hasMeaningfulContent(value) {
return typeof value === "string" && value.trim().length > 0;
}
function saveRoomDraft(roomKey, content) {
if (!roomKey) return;
const payload = typeof content === "string" ? content : "";
safeLocalStorageSet(`${ROOM_CONTENT_PREFIX}${roomKey}`, payload);
}
function loadRoomDraft(roomKey) {
if (!roomKey) return "";
return safeLocalStorageGet(`${ROOM_CONTENT_PREFIX}${roomKey}`) || "";
}
function getDraftFileName(roomKey) {
if (!roomKey) return null;
const safeKey = roomKey.replace(/[^a-z0-9]+/gi, "_");
return `${safeKey}.json`;
}
async function getDraftDriveUrl() {
if (!draftDriveUrl) {
const cached = safeLocalStorageGet("p2pmd:draftDriveUrl");
if (cached) {
draftDriveUrl = cached;
return draftDriveUrl;
}
const response = await fetchWithTimeout(
`hyper://localhost/?key=${encodeURIComponent(DRAFT_DRIVE_NAME)}`,
{ method: "POST" },
2000
);
if (!response.ok) {
throw new Error(`Failed to generate Hyperdrive key: ${response.statusText}`);
}
draftDriveUrl = await response.text();
safeLocalStorageSet("p2pmd:draftDriveUrl", draftDriveUrl);
}
return draftDriveUrl;
}
function buildDraftPayload(content) {
const payload = {
content: typeof content === "string" ? content : "",
updatedAt: Date.now(),
roomKey: currentRoomKey || null
};
if (ydoc && window.Y) {
try {
payload.yjsState = bytesToBase64(window.Y.encodeStateAsUpdate(ydoc));
} catch {}
}
if (titleInput) payload.title = titleInput.value;
if (protocolSelect) payload.protocol = protocolSelect.value;
return payload;
}
async function writeDraft(payload, roomKey) {
const driveUrl = await getDraftDriveUrl();
const fileName = getDraftFileName(roomKey);
if (!driveUrl || !fileName) return;
const url = `${driveUrl}${fileName}`;
const response = await fetchWithTimeout(
url,
{
method: "PUT",
body: JSON.stringify(payload),
headers: { "Content-Type": "application/json" }
},
2000
);
if (!response.ok) {
throw new Error(`Failed to save draft: ${response.statusText}`);
}
}
async function saveDraft({ force = false } = {}) {
if (!currentRoomKey) return;
if (draftSaveInFlight && !force) return;
try {
const payload = buildDraftPayload(markdownInput.value || "");
const serialized = JSON.stringify(payload);
if (!force && serialized === lastDraftPayload) {
return;
}
draftSaveInFlight = true;
lastDraftPayload = serialized;
await writeDraft(payload, currentRoomKey);
} catch (error) {
console.error("[saveDraft] Error saving draft:", error);
} finally {
draftSaveInFlight = false;
}
}
async function loadDraftFromHyperdrive(roomKey) {
let retries = 3;
while (retries > 0) {
try {
const driveUrl = await getDraftDriveUrl();
const fileName = getDraftFileName(roomKey);
if (!driveUrl || !fileName) return "";
const url = `${driveUrl}${fileName}`;
const response = await fetchWithTimeout(url, {}, 3000);
if (!response.ok) {
if (response.status === 404) {
draftSnapshotCache.delete(roomKey);
return "";
}
retries--;
if (retries > 0) {
await new Promise(resolve => setTimeout(resolve, 1000));
continue;
}
return "";
}
const data = await response.json();
if (!data || data.isCleared) {
draftSnapshotCache.delete(roomKey);
return "";
}
if (typeof data.title === "string" && titleInput) {
titleInput.value = data.title;
}
if (typeof data.protocol === "string" && protocolSelect && !paramProtocol) {
protocolSelect.value = data.protocol;
safeLocalStorageSet("lastProtocol", data.protocol);
toggleTitleInput();
updateSelectorURL();
}
if (typeof data.content === "string") {
draftSnapshotCache.set(roomKey, {
content: data.content,
updatedAt: Number.isFinite(Number(data.updatedAt)) ? Number(data.updatedAt) : 0,
yjsState: typeof data.yjsState === "string" ? data.yjsState : null
});
lastDraftPayload = JSON.stringify(data);
return data.content;
}
draftSnapshotCache.delete(roomKey);
return "";
} catch (error) {
console.error("[loadDraft] Error loading draft:", error);
retries--;
if (retries > 0) {
await new Promise(resolve => setTimeout(resolve, 1000));
} else {
return "";
}
}
}
return "";
}
async function clearDraft() {
if (!currentRoomKey) return;
const fileName = getDraftFileName(currentRoomKey);
try {
const driveUrl = await getDraftDriveUrl();
const url = `${driveUrl}${fileName}`;
const response = await fetchWithTimeout(url, { method: "DELETE" }, 2000);
if (response.ok || response.status === 404) {
return;
}
} catch (error) {
console.error("[clearDraft] Error deleting draft:", error);
}
try {
const payload = { isCleared: true, clearedAt: Date.now(), roomKey: currentRoomKey };
lastDraftPayload = JSON.stringify(payload);
await writeDraft(payload, currentRoomKey);
} catch (error) {
console.error("[clearDraft] Error saving cleared draft:", error);
}
}
function normalizeHost(value) {
if (!value || typeof value !== "string") return "";
const trimmed = value.trim();
if (!trimmed) return "";
try {
if (trimmed.includes("://")) {
const parsed = new URL(trimmed);
return parsed.hostname || "";
}
} catch {}
if (trimmed.includes("/")) {
return trimmed.split("/")[0] || "";
}
if (trimmed.includes(":")) {
return trimmed.split(":")[0] || "";
}
return trimmed;
}
function normalizePort(value, fallback) {
const num = Number(value);
return Number.isFinite(num) && num > 0 ? num : fallback;
}
function extractPort(value) {
if (!value || typeof value !== "string") return null;
const trimmed = value.trim();
if (!trimmed) return null;
try {
if (trimmed.includes("://")) {
const parsed = new URL(trimmed);
if (parsed.port) return Number(parsed.port);
}
} catch {}
if (trimmed.includes(":")) {
const parts = trimmed.split(":");
const port = Number(parts[1]);
return Number.isFinite(port) ? port : null;
}
return null;
}
function parseLocalUrl(value) {
if (!value || typeof value !== "string") return { host: null, port: null };
const trimmed = value.trim();
if (!trimmed) return { host: null, port: null };
try {
const parsed = new URL(trimmed);
return {
host: parsed.hostname || null,
port: normalizePort(parsed.port, null)
};
} catch {}
if (trimmed.includes(":")) {
const [host, port] = trimmed.split(":");
return { host: host || null, port: normalizePort(port, null) };
}
return { host: trimmed, port: null };
}
function normalizeRoomKey(key) {
if (!key || typeof key !== "string") return "";
return key.trim();
}
function getRoomKeyValue(key) {
const trimmed = normalizeRoomKey(key);
if (!trimmed) return "";
return trimmed.startsWith("hs://") ? trimmed.slice(5) : trimmed;
}
function validateRoomKey(key) {
const baseKey = getRoomKeyValue(key);
if (baseKey.length < 32) {
alert("Error: ID must be at least 32-bytes long");
return false;
}
return true;
}
function getRoomKeyCandidates(key) {
const trimmed = normalizeRoomKey(key);
if (!trimmed) return [];
const candidates = new Set([trimmed]);
if (trimmed.startsWith("hs://")) {
candidates.add(trimmed.slice(5));
} else {
candidates.add(`hs://${trimmed}`);
}
return Array.from(candidates).filter(Boolean);
}
function isSameRoomKey(a, b) {
if (!a || !b) return false;
const setA = new Set(getRoomKeyCandidates(a));
for (const candidate of getRoomKeyCandidates(b)) {
if (setA.has(candidate)) return true;
}
return false;
}
function updateRoomUrl(state) {
const params = new URLSearchParams(window.location.search);
if (state?.key) {
params.set("roomKey", normalizeRoomKey(state.key));
if (state.localUrl) params.set("localUrl", state.localUrl);
if (typeof state.secure === "boolean") params.set("secure", String(state.secure));
if (typeof state.udp === "boolean") params.set("udp", String(state.udp));
if (state.host) params.set("host", state.host);
if (state.port) params.set("port", String(state.port));
} else {
params.delete("roomKey");
params.delete("localUrl");
params.delete("secure");
params.delete("udp");
params.delete("host");
params.delete("port");
}
const base = window.location.pathname + window.location.hash;
const query = params.toString();
const nextUrl = query ? `${base}?${query}` : base;
history.replaceState(null, "", nextUrl);
}
function readRoomStateFromUrl() {
const params = new URLSearchParams(window.location.search);
const key = normalizeRoomKey(params.get("roomKey") || "");
if (!key) return null;
return {
key,
localUrl: params.get("localUrl") || "",
secure: params.get("secure") === "true",
udp: params.get("udp") === "true",
host: params.get("host") || "",
port: normalizePort(params.get("port"), null)
};
}
function readRoomStateFromStorage(key) {
const candidates = getRoomKeyCandidates(key);
if (candidates.length === 0) return null;
for (const candidate of candidates) {
const raw = safeLocalStorageGet(`${ROOM_STATE_PREFIX}${candidate}`);
if (!raw) continue;
try {
return JSON.parse(raw);
} catch {
continue;
}
}
return null;
}
function readLastRoomState() {
const raw = safeLocalStorageGet(LAST_ROOM_STATE);
if (!raw) return null;
try {
return JSON.parse(raw);
} catch {
return null;
}
}
function normalizeRoomState(state) {
if (!state || typeof state !== "object") return null;
const normalized = { ...state };
if (normalized.hosted === undefined && typeof normalized.isHosted === "boolean") {
normalized.hosted = normalized.isHosted;
}
if (normalized.creator === undefined && normalized.hosted === true) {
normalized.creator = true;
}
return normalized;
}
function resolveRoomState(key) {
const stored = normalizeRoomState(readRoomStateFromStorage(key));
if (stored) return stored;
const last = normalizeRoomState(readLastRoomState());
if (last?.key && isSameRoomKey(last.key, key)) return last;
return null;
}
function persistRoomState(state) {
if (!state?.key) return;
const normalized = normalizeRoomState(state);
if (!normalized) return;
if (!normalized.savedAt) normalized.savedAt = Date.now();
const payload = JSON.stringify(normalized);
const candidates = getRoomKeyCandidates(normalized.key);
for (const candidate of candidates) {
safeLocalStorageSet(`${ROOM_STATE_PREFIX}${candidate}`, payload);
}
}
export function scheduleSend() {
if (!currentRoomUrl) return;
if (!ydoc || !ytext) {
if (sendTimer) clearTimeout(sendTimer);
sendTimer = setTimeout(async () => {
const content = markdownInput.value;
if (content === lastSentContent) return;
_attributeCurrentLine();
updateLineAuthors(_roomLineAttributions);
lastSentContent = content;
try {
await fetch(`${currentRoomUrl}/doc`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
content,
clientId: localClientId,
role: currentRole || "client",
name: getDisplayName(),
...getCurrentCursorPayload(),
lineAttributions: getLineAttributionsPayload()
})
});
schedulePresenceSend();
} catch {
updatePeers(0);
} finally {
scheduleDraftSave();
}
}, 200);
return;
}
if (sendTimer) {
clearTimeout(sendTimer);
sendTimer = null;
}
const newText = markdownInput.value;
const oldText = ytext ? ytext.toString() : prevText;
if (newText === oldText) {
prevText = oldText;
return;
}
_attributeCurrentLine();
updateLineAuthors(_roomLineAttributions);
applyTextDiff(ytext, oldText, newText);
prevText = newText;
}
function _attributeCurrentLine() {
try {
const text = markdownInput.value || "";
const offset = markdownInput.selectionStart ?? 0;
const before = text.slice(0, Math.min(offset, text.length));
let line = 1;
for (const ch of before) if (ch === "\n") line++;
const name = getDisplayName() || truncateIdentifier(localClientId, PEER_FALLBACK_NAME_LEN);
const color = currentPeerList.find((p) => p.clientId === localClientId)?.color || _localFallbackColor();
if (!color) return;
_localLineAttributions[String(line)] = { name, color };
_roomLineAttributions[String(line)] = { name, color };
scheduleRoomLineAttributionsPersist();
} catch {}
}
// Local peer's accumulated line attributions, sent via /presence.
let _localLineAttributions = {};
// Room-level accumulated line attributions, preserved even after peers disconnect.
let _roomLineAttributions = {};
function _localFallbackColor() {
return getLocalPeerColor();
}
function attributeLocalLineRange(startLine, endLine, { reset = false } = {}) {
const start = Math.max(1, Number(startLine) || 1);
const end = Math.max(start, Number(endLine) || start);
const name = getDisplayName() || truncateIdentifier(localClientId, PEER_FALLBACK_NAME_LEN);
const color = currentPeerList.find((p) => p.clientId === localClientId)?.color || _localFallbackColor();
if (!color) return;
if (reset) {
_localLineAttributions = {};
_roomLineAttributions = {};
}
for (let line = start; line <= end; line += 1) {
const lineKey = String(line);
const entry = { name, color };
_localLineAttributions[lineKey] = entry;
_roomLineAttributions[lineKey] = entry;
}
updateLineAuthors(_roomLineAttributions);
scheduleRoomLineAttributionsPersist();
}
function mergeLineAttributionsIntoRoom(value) {
if (!value || typeof value !== "object") return;
let changed = false;
for (const [line, info] of Object.entries(value)) {
const lineNum = Number(line);
if (!Number.isFinite(lineNum) || lineNum < 1) continue;
if (!info || typeof info !== "object" || typeof info.color !== "string") continue;
const lineKey = String(Math.floor(lineNum));
const prevValue = _roomLineAttributions[lineKey];
const incomingName = typeof info.name === "string" ? info.name.trim() : "";
const colorMatchedPeer = currentPeerList.find((peer) => peer?.color === info.color && peer?.name);
const resolvedName = incomingName || colorMatchedPeer?.name || prevValue?.name || "";
const nextValue = {
name: resolvedName,
color: info.color
};
if (!prevValue || prevValue.name !== nextValue.name || prevValue.color !== nextValue.color) {
_roomLineAttributions[lineKey] = nextValue;
changed = true;
}
}
if (changed) scheduleRoomLineAttributionsPersist();
}
function refreshRoomAttributionNamesFromPeerList() {
if (!_roomLineAttributions || typeof _roomLineAttributions !== "object") return;
const colorToNames = new Map();
for (const peer of currentPeerList || []) {
if (!peer || typeof peer.color !== "string") continue;
const name = typeof peer.name === "string" ? peer.name.trim() : "";
if (!name) continue;
if (!colorToNames.has(peer.color)) colorToNames.set(peer.color, new Set());
colorToNames.get(peer.color).add(name);
}
let changed = false;
for (const [lineKey, info] of Object.entries(_roomLineAttributions)) {
if (!info || typeof info !== "object" || typeof info.color !== "string") continue;
const names = colorToNames.get(info.color);
if (!names || names.size !== 1) continue;
const [resolvedName] = Array.from(names);
if (resolvedName && info.name !== resolvedName) {
_roomLineAttributions[lineKey] = {
name: resolvedName,
color: info.color
};
changed = true;
}
}
if (changed) {
updateLineAuthors(_roomLineAttributions);
scheduleRoomLineAttributionsPersist();
}
}
function refreshLocalLineAttribution() {
updateLineAuthors(_roomLineAttributions);
}
function syncLocalLineAttributionNames() {
const currentName = getDisplayName() || truncateIdentifier(localClientId, PEER_FALLBACK_NAME_LEN);
if (!currentName) return;
let changed = false;
for (const lineKey of Object.keys(_localLineAttributions || {})) {
const localInfo = _localLineAttributions[lineKey];
if (localInfo && localInfo.name !== currentName) {
_localLineAttributions[lineKey] = {
...localInfo,
name: currentName
};
changed = true;
}
const roomInfo = _roomLineAttributions[lineKey];
if (roomInfo && roomInfo.name !== currentName) {
_roomLineAttributions[lineKey] = {
...roomInfo,
name: currentName
};
changed = true;
}
}
if (changed) {
updateLineAuthors(_roomLineAttributions);
scheduleRoomLineAttributionsPersist();
}
}
function bytesToBase64(bytes) {
let binary = "";
for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
return btoa(binary);
}
function base64ToBytes(b64) {
const binary = atob(b64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes;
}
function applyTextDiff(ytextRef, oldText, newText, origin = null) {
if (!ytextRef || oldText === newText) return;
// Trim unchanged edges so we emit one minimal delete/insert change.
let prefixLen = 0;
const minLen = Math.min(oldText.length, newText.length);
while (prefixLen < minLen && oldText[prefixLen] === newText[prefixLen]) prefixLen++;
let oldSuffix = oldText.length;
let newSuffix = newText.length;
while (oldSuffix > prefixLen && newSuffix > prefixLen &&
oldText[oldSuffix - 1] === newText[newSuffix - 1]) {
oldSuffix--;
newSuffix--;
}
const deleteLen = oldSuffix - prefixLen;
const insertStr = newText.slice(prefixLen, newSuffix);
ytextRef.doc.transact(() => {
if (deleteLen > 0) ytextRef.delete(prefixLen, deleteLen);
if (insertStr) ytextRef.insert(prefixLen, insertStr);
}, origin);
}
function getCurrentCursorPayload() {
const start = Number.isFinite(markdownInput.selectionStart) ? markdownInput.selectionStart : 0;
const end = Number.isFinite(markdownInput.selectionEnd) ? markdownInput.selectionEnd : start;