Dev #7

Merged
sandrodach merged 33 commits from dev into main 2026-10-27 11:42:12 +01:00
4 changed files with 221 additions and 59 deletions
Showing only changes of commit cedf5aebff - Show all commits

No files matched your search

@@ -196,10 +196,12 @@ export const DocumentEditor: React.FC<DocumentEditorProps> = ({
switch (evt.type) {
case 'doc_state': {
if (evt.title !== undefined) {
const isTitleFocused =
const isTitleActivelyEditing =
titleInputRef.current !== null &&
document.activeElement === titleInputRef.current;
if (!isTitleFocused) {
document.activeElement === titleInputRef.current &&
typeof document !== 'undefined' &&
document.hasFocus();
if (!isTitleActivelyEditing) {
setTitle(evt.title);
}
}
@@ -211,10 +213,12 @@ export const DocumentEditor: React.FC<DocumentEditorProps> = ({
case 'title_updated': {
if (evt.title !== undefined) {
const isTitleFocused =
const isTitleActivelyEditing =
titleInputRef.current !== null &&
document.activeElement === titleInputRef.current;
if (!isTitleFocused) {
document.activeElement === titleInputRef.current &&
typeof document !== 'undefined' &&
document.hasFocus();
if (!isTitleActivelyEditing) {
setTitle(evt.title);
}
if (docRef.current) {
@@ -407,6 +411,27 @@ export const DocumentEditor: React.FC<DocumentEditorProps> = ({
}, 250);
};
const handleTitleBlur = () => {
if (titleDebounceRef.current !== null) {
window.clearTimeout(titleDebounceRef.current);
titleDebounceRef.current = null;
sendTitleUpdated(title);
}
};
// Flush title debouncing on window blur so background window never holds stale pending title
useEffect(() => {
const handleWindowBlur = () => {
if (titleDebounceRef.current !== null) {
window.clearTimeout(titleDebounceRef.current);
titleDebounceRef.current = null;
sendTitleUpdated(title);
}
};
window.addEventListener('blur', handleWindowBlur);
return () => window.removeEventListener('blur', handleWindowBlur);
}, [title, sendTitleUpdated]);
const handleUpdateBlock = useCallback(
(updatedBlock: DocumentBlock) => {
setBlocks((prev) =>
@@ -920,6 +945,7 @@ export const DocumentEditor: React.FC<DocumentEditorProps> = ({
value={title}
readOnly={!canEdit}
onChange={handleTitleChange}
onBlur={handleTitleBlur}
placeholder="Titel der Notiz…"
className="flex-1 min-w-0 text-xl sm:text-2xl font-bold text-main bg-transparent border-0 focus:outline-none focus:ring-0 tracking-tight"
/>
@@ -102,15 +102,87 @@ export const OutlinerBlock: React.FC<OutlinerBlockProps> = ({
const localContentRef = useRef<string>(localContent);
localContentRef.current = localContent;
// Sync incoming remote changes ONLY when this textarea is NOT active
// Callback refs to avoid stale closures in setTimeout, debounce flush, and event listeners
const onUpdateBlockRef = useRef(onUpdateBlock);
onUpdateBlockRef.current = onUpdateBlock;
const onFocusBlockRef = useRef(onFocusBlock);
onFocusBlockRef.current = onFocusBlock;
const onCreateBlockBelowRef = useRef(onCreateBlockBelow);
onCreateBlockBelowRef.current = onCreateBlockBelow;
const onDeleteBlockRef = useRef(onDeleteBlock);
onDeleteBlockRef.current = onDeleteBlock;
const onIndentBlockRef = useRef(onIndentBlock);
onIndentBlockRef.current = onIndentBlock;
const onNavigateFocusRef = useRef(onNavigateFocus);
onNavigateFocusRef.current = onNavigateFocus;
const sendCursorMovedRef = useRef(sendCursorMoved);
sendCursorMovedRef.current = sendCursorMoved;
// Track if this input currently has actual focus in an active browser window
const isFocusedRef = useRef<boolean>(false);
const flushDebounce = useCallback(
(contentToFlush: string, overrides?: Partial<DocumentBlock>) => {
if (debounceTimerRef.current !== null) {
window.clearTimeout(debounceTimerRef.current);
debounceTimerRef.current = null;
}
const nextBlock: DocumentBlock = {
...latestBlockRef.current,
content: contentToFlush,
...overrides,
};
onUpdateBlockRef.current(nextBlock, true);
},
[]
);
// Sync incoming remote changes ONLY when this textarea is NOT actively being edited
// Condition: isFocusedRef.current === true && document.hasFocus()
useEffect(() => {
const isActivelyFocused =
textareaRef.current !== null && document.activeElement === textareaRef.current;
if (!isActivelyFocused && block.content !== localContentRef.current) {
const isActivelyEditing =
isFocusedRef.current === true &&
typeof document !== 'undefined' &&
document.hasFocus() &&
textareaRef.current !== null &&
document.activeElement === textareaRef.current;
if (!isActivelyEditing && block.content !== localContentRef.current) {
setLocalContent(block.content || '');
localContentRef.current = block.content || '';
}
}, [block.content]);
// Handle window blur / focus to instantly flush debounced input and clear zombie focus
useEffect(() => {
const handleWindowBlur = () => {
if (debounceTimerRef.current !== null) {
window.clearTimeout(debounceTimerRef.current);
debounceTimerRef.current = null;
flushDebounce(localContentRef.current);
} else if (localContentRef.current !== latestBlockRef.current.content) {
flushDebounce(localContentRef.current);
}
isFocusedRef.current = false;
sendCursorMovedRef.current?.(null);
};
const handleWindowFocus = () => {
const isThisActive =
textareaRef.current !== null &&
document.activeElement === textareaRef.current &&
document.hasFocus();
isFocusedRef.current = isThisActive;
};
window.addEventListener('blur', handleWindowBlur);
window.addEventListener('focus', handleWindowFocus);
return () => {
window.removeEventListener('blur', handleWindowBlur);
window.removeEventListener('focus', handleWindowFocus);
};
}, [flushDebounce]);
useEffect(() => {
return () => {
if (debounceTimerRef.current !== null) {
@@ -136,22 +208,6 @@ export const OutlinerBlock: React.FC<OutlinerBlockProps> = ({
return () => window.removeEventListener('resize', adjustHeight);
}, [adjustHeight]);
const flushDebounce = useCallback(
(contentToFlush: string, overrides?: Partial<DocumentBlock>) => {
if (debounceTimerRef.current !== null) {
window.clearTimeout(debounceTimerRef.current);
debounceTimerRef.current = null;
}
const nextBlock: DocumentBlock = {
...latestBlockRef.current,
content: contentToFlush,
...overrides,
};
onUpdateBlock(nextBlock, true);
},
[onUpdateBlock]
);
const filteredSlashCommands = useMemo(() => {
if (slashSearch === null) return [];
const q = slashSearch.toLowerCase();
@@ -237,7 +293,7 @@ export const OutlinerBlock: React.FC<OutlinerBlockProps> = ({
debounceTimerRef.current = window.setTimeout(() => {
debounceTimerRef.current = null;
onUpdateBlock({
onUpdateBlockRef.current({
...latestBlockRef.current,
content: val,
});
@@ -245,28 +301,34 @@ export const OutlinerBlock: React.FC<OutlinerBlockProps> = ({
};
const handleFocus = (e: React.FocusEvent<HTMLTextAreaElement>) => {
onFocusBlock(block.id);
sendCursorMoved?.(block.id, e.target.selectionStart, e.target.selectionEnd);
isFocusedRef.current = true;
onFocusBlockRef.current(block.id);
sendCursorMovedRef.current?.(block.id, e.target.selectionStart, e.target.selectionEnd);
};
const handleBlur = () => {
isFocusedRef.current = false;
if (debounceTimerRef.current !== null) {
flushDebounce(localContent);
window.clearTimeout(debounceTimerRef.current);
debounceTimerRef.current = null;
flushDebounce(localContentRef.current);
} else if (localContentRef.current !== latestBlockRef.current.content) {
flushDebounce(localContentRef.current);
}
sendCursorMoved?.(null);
sendCursorMovedRef.current?.(null);
};
const handleClick = (e: React.MouseEvent<HTMLTextAreaElement>) => {
sendCursorMoved?.(block.id, e.currentTarget.selectionStart, e.currentTarget.selectionEnd);
sendCursorMovedRef.current?.(block.id, e.currentTarget.selectionStart, e.currentTarget.selectionEnd);
};
const handleKeyUp = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
sendCursorMoved?.(block.id, e.currentTarget.selectionStart, e.currentTarget.selectionEnd);
sendCursorMovedRef.current?.(block.id, e.currentTarget.selectionStart, e.currentTarget.selectionEnd);
};
const handleSelect = (e: React.SyntheticEvent<HTMLTextAreaElement>) => {
const target = e.currentTarget;
sendCursorMoved?.(block.id, target.selectionStart, target.selectionEnd);
sendCursorMovedRef.current?.(block.id, target.selectionStart, target.selectionEnd);
};
const primaryRemoteCursor = activeRemoteCursors.length > 0 ? activeRemoteCursors[0] : null;
@@ -306,7 +368,7 @@ export const OutlinerBlock: React.FC<OutlinerBlockProps> = ({
e.preventDefault();
e.stopPropagation();
flushDebounce(localContent);
onIndentBlock(block.id, e.shiftKey ? -1 : 1);
onIndentBlockRef.current(block.id, e.shiftKey ? -1 : 1);
return;
}
@@ -316,7 +378,7 @@ export const OutlinerBlock: React.FC<OutlinerBlockProps> = ({
e.stopPropagation();
setSlashSearch(null);
flushDebounce(localContent);
onCreateBlockBelow(block.id, localContent);
onCreateBlockBelowRef.current(block.id, localContent);
return;
}
@@ -330,7 +392,7 @@ export const OutlinerBlock: React.FC<OutlinerBlockProps> = ({
window.clearTimeout(debounceTimerRef.current);
debounceTimerRef.current = null;
}
onDeleteBlock(block.id);
onDeleteBlockRef.current(block.id);
return;
}
@@ -340,7 +402,7 @@ export const OutlinerBlock: React.FC<OutlinerBlockProps> = ({
if (el && el.selectionStart === 0 && el.selectionEnd === 0) {
e.preventDefault();
flushDebounce(localContent);
onNavigateFocus(block.id, 'up');
onNavigateFocusRef.current(block.id, 'up');
}
return;
}
@@ -350,7 +412,7 @@ export const OutlinerBlock: React.FC<OutlinerBlockProps> = ({
if (el && el.selectionStart === localContent.length && el.selectionEnd === localContent.length) {
e.preventDefault();
flushDebounce(localContent);
onNavigateFocus(block.id, 'down');
onNavigateFocusRef.current(block.id, 'down');
}
return;
}
@@ -742,7 +804,7 @@ export const OutlinerBlock: React.FC<OutlinerBlockProps> = ({
{canEdit && (
<button
type="button"
onClick={() => onDeleteBlock(block.id)}
onClick={() => onDeleteBlockRef.current(block.id)}
className="opacity-0 group-hover:opacity-100 focus:opacity-100 p-0.5 text-faint hover:text-status-err rounded-btn transition-opacity shrink-0"
title="Block löschen"
>
+70 -19
View File
@@ -84,6 +84,13 @@ export function useDocumentSync(
const onRemoteEventRef = useRef(onRemoteEvent);
onRemoteEventRef.current = onRemoteEvent;
const docIdRef = useRef(docId);
docIdRef.current = docId;
const canEditRef = useRef(canEdit);
canEditRef.current = canEdit;
const currentUserRef = useRef(currentUser);
currentUserRef.current = currentUser;
const reconnectTimerRef = useRef<number | null>(null);
const fallbackTimerRef = useRef<number | null>(null);
@@ -93,6 +100,12 @@ export function useDocumentSync(
() => getUserColor(currentUser?.id || clientIdRef.current),
[currentUser?.id]
);
const localUserNameRef = useRef(localUserName);
localUserNameRef.current = localUserName;
const localUserColorRef = useRef(localUserColor);
localUserColorRef.current = localUserColor;
const pendingMessagesQueueRef = useRef<string[]>([]);
const lastCursorSendRef = useRef<number>(0);
const pendingCursorTimerRef = useRef<number | null>(null);
@@ -126,9 +139,11 @@ export function useDocumentSync(
if (!docId) {
setStatus('offline');
setRemoteCursors({});
pendingMessagesQueueRef.current = [];
return;
}
pendingMessagesQueueRef.current = [];
let isDisposed = false;
let retryCount = 0;
const currentClientId = `cli_${Math.random().toString(36).slice(2, 10)}_${Date.now().toString(36)}`;
@@ -171,6 +186,19 @@ export function useDocumentSync(
}
retryCount = 0;
setStatus('connected');
// Flush any queued messages buffered while connecting or reconnecting
if (pendingMessagesQueueRef.current.length > 0) {
const queue = [...pendingMessagesQueueRef.current];
pendingMessagesQueueRef.current = [];
for (const msg of queue) {
try {
ws.send(msg);
} catch (err) {
console.warn('[DocSync] Failed to flush queued message:', err);
}
}
}
};
ws.onmessage = (event) => {
@@ -281,27 +309,32 @@ export function useDocumentSync(
const executeSendCursor = useCallback(
(blockId: string | null, selectionStart?: number, selectionEnd?: number) => {
const ws = wsRef.current;
if (!docId || !ws || ws.readyState !== WebSocket.OPEN) return;
const activeDocId = docIdRef.current;
if (!activeDocId || !ws || ws.readyState !== WebSocket.OPEN) return;
const payload: DocSyncEvent = {
type: 'cursor_moved',
docId,
docId: activeDocId,
clientId: clientIdRef.current,
userId: currentUser?.id,
userName: localUserName,
userColor: localUserColor,
userId: currentUserRef.current?.id,
userName: localUserNameRef.current,
userColor: localUserColorRef.current,
blockId: blockId || undefined,
selectionStart,
selectionEnd,
};
ws.send(JSON.stringify(payload));
try {
ws.send(JSON.stringify(payload));
} catch {
// Ephemeral cursor, ignore send failure
}
lastCursorSendRef.current = Date.now();
},
[docId, currentUser?.id, localUserName, localUserColor]
[]
);
const sendCursorMoved = useCallback(
(blockId: string | null, selectionStart?: number, selectionEnd?: number) => {
if (!docId) return;
if (!docIdRef.current) return;
const now = Date.now();
const elapsed = now - lastCursorSendRef.current;
@@ -340,30 +373,48 @@ export function useDocumentSync(
}
}
},
[docId, executeSendCursor]
[executeSendCursor]
);
const sendRawEvent = useCallback(
(evt: DocSyncEvent, fallbackFn?: () => void) => {
if (!docId || !canEdit) return;
const activeDocId = docIdRef.current;
const activeCanEdit = canEditRef.current;
if (!activeDocId || !activeCanEdit) return;
const ws = wsRef.current;
const payload: DocSyncEvent = {
...evt,
docId,
docId: activeDocId,
clientId: clientIdRef.current,
};
const jsonStr = JSON.stringify(payload);
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(payload));
} else if (fallbackFn) {
if (fallbackTimerRef.current !== null) {
window.clearTimeout(fallbackTimerRef.current);
try {
ws.send(jsonStr);
} catch (err) {
console.warn('[DocSync] Failed to send WebSocket message, buffering:', err);
pendingMessagesQueueRef.current.push(jsonStr);
}
} else {
console.warn(
`[DocSync] WebSocket not OPEN (state=${ws ? ws.readyState : 'null'}). Buffering event:`,
evt.type
);
pendingMessagesQueueRef.current.push(jsonStr);
if (fallbackFn) {
if (fallbackTimerRef.current !== null) {
window.clearTimeout(fallbackTimerRef.current);
}
fallbackTimerRef.current = window.setTimeout(() => {
fallbackFn();
}, 600);
}
fallbackTimerRef.current = window.setTimeout(() => {
fallbackFn();
}, 600);
}
},
[docId, canEdit]
[]
);
const sendBlockCreated = useCallback(
+23
View File
@@ -320,8 +320,10 @@ func (r *DocRoom) HandleEvent(evt DocSyncEvent, sender *DocWSClient) {
targetID = evt.Block.ID
}
if targetID != "" {
found := false
for i := range r.blocks {
if r.blocks[i].ID == targetID {
found = true
if evt.Block != nil {
r.blocks[i].Content = evt.Block.Content
r.blocks[i].Level = evt.Block.Level
@@ -359,6 +361,22 @@ func (r *DocRoom) HandleEvent(evt DocSyncEvent, sender *DocWSClient) {
break
}
}
if !found && evt.Block != nil {
newBlock := *evt.Block
newBlock.DocumentID = r.docID
if newBlock.Type == "" {
newBlock.Type = "text"
}
if newBlock.Level < 0 {
newBlock.Level = 0
}
r.blocks = append(r.blocks, newBlock)
r.blocks = normalizeRoomBlocks(r.docID, r.blocks)
bCopy := newBlock
evt.Block = &bCopy
evt.BlockID = targetID
mutated = true
}
}
case "block_deleted":
@@ -441,6 +459,11 @@ func (r *DocRoom) HandleEvent(evt DocSyncEvent, sender *DocWSClient) {
select {
case client.send <- msgBytes:
default:
slog.Warn("Doc room WS client send buffer full, dropping message",
"doc_id", r.docID,
"client_id", client.clientID,
"user_id", client.userID,
)
}
}
}