mirror of
https://github.com/open-webui/open-webui.git
synced 2026-11-16 09:41:23 +00:00
refac
This commit is contained in:
parent
b34885efc6
commit
e3ad014fb2
7 changed files with 391 additions and 70 deletions
|
|
@ -274,6 +274,46 @@ async def publish_chat_presence(chat_id: str):
|
|||
log.exception('Failed to publish presence for chat %s', chat_id)
|
||||
|
||||
|
||||
async def publish_note_presence(note_id: str):
|
||||
lock = (
|
||||
REDIS.lock(
|
||||
f'{REDIS_KEY_PREFIX}:note:{note_id}:presence:lock',
|
||||
timeout=WEBSOCKET_REDIS_LOCK_TIMEOUT,
|
||||
blocking_timeout=WEBSOCKET_REDIS_LOCK_TIMEOUT,
|
||||
)
|
||||
if REDIS is not None
|
||||
else SOCKET_EVENT_LOCKS.setdefault(('note', note_id), asyncio.Lock())
|
||||
)
|
||||
async with lock, asyncio.timeout(WEBSOCKET_REDIS_LOCK_TIMEOUT / 2):
|
||||
now = time.time()
|
||||
people = {}
|
||||
for batch in get_session_pool_batches():
|
||||
for _, session in batch:
|
||||
if (
|
||||
not session
|
||||
or note_id not in session.get('note_ids', [])
|
||||
or now - session.get('last_seen_at', 0) > SESSION_POOL_TIMEOUT
|
||||
):
|
||||
continue
|
||||
location = session.get('note_locations', {}).get(note_id, {})
|
||||
previous = people.get(session['id'])
|
||||
if previous is None or location.get('updated_at', 0) > previous.get('updated_at', 0):
|
||||
people[session['id']] = {**location, 'id': session['id'], 'name': session.get('name', '')}
|
||||
if REDIS is not None and not await lock.owned():
|
||||
return
|
||||
await sio.emit(
|
||||
'note:presence',
|
||||
{'note_id': note_id, 'users': sorted(people.values(), key=lambda person: person['id'])},
|
||||
room=f'note:{note_id}',
|
||||
)
|
||||
|
||||
|
||||
async def remove_document_session(sid: str):
|
||||
for document_id in await YDOC_MANAGER.remove_user_from_all_documents(sid):
|
||||
async with YDOC_MANAGER.lock(document_id):
|
||||
await sio.leave_room(sid, f'doc_{document_id}')
|
||||
|
||||
|
||||
async def periodic_session_pool_cleanup():
|
||||
"""Reap orphaned SESSION_POOL entries that missed heartbeats (e.g. crashed instance)."""
|
||||
retry_delay = random.uniform(WEBSOCKET_REDIS_LOCK_TIMEOUT / 2, WEBSOCKET_REDIS_LOCK_TIMEOUT)
|
||||
|
|
@ -306,6 +346,12 @@ async def periodic_session_pool_cleanup():
|
|||
if sid in expired
|
||||
for chat_id in entry.get('chat_ids', [])
|
||||
}
|
||||
note_ids = {
|
||||
note_id
|
||||
for sid, entry in batch
|
||||
if sid in expired
|
||||
for note_id in entry.get('note_ids', [])
|
||||
}
|
||||
if WEBSOCKET_MANAGER == 'redis':
|
||||
SESSION_POOL.delete_many(*expired)
|
||||
else:
|
||||
|
|
@ -315,8 +361,13 @@ async def periodic_session_pool_cleanup():
|
|||
if sid in expired:
|
||||
for chat_id in entry.get('chat_ids', []):
|
||||
await sio.leave_room(sid, f'chat:{chat_id}')
|
||||
for note_id in entry.get('note_ids', []):
|
||||
await sio.leave_room(sid, f'note:{note_id}')
|
||||
await remove_document_session(sid)
|
||||
for chat_id in chat_ids:
|
||||
await publish_chat_presence(chat_id)
|
||||
for note_id in note_ids:
|
||||
await publish_note_presence(note_id)
|
||||
await asyncio.sleep(0) # don't hold the loop for the whole sweep
|
||||
|
||||
next_cleanup_at = time.monotonic() + SESSION_POOL_TIMEOUT
|
||||
|
|
@ -500,7 +551,15 @@ async def leave_room_for_users(room: str, user_ids: list[str]):
|
|||
"""Make all sessions of each user leave a room, including sessions on other workers."""
|
||||
for sid in get_session_ids_by_user_ids(user_ids):
|
||||
try:
|
||||
await sio.leave_room(sid, room)
|
||||
if room.startswith('doc_'):
|
||||
document_id = room.removeprefix('doc_')
|
||||
async with YDOC_MANAGER.lock(document_id):
|
||||
await sio.leave_room(sid, room)
|
||||
await YDOC_MANAGER.remove_user(document_id, sid)
|
||||
elif room.startswith('note:'):
|
||||
await leave_note(sid, {'note_id': room.removeprefix('note:')})
|
||||
else:
|
||||
await sio.leave_room(sid, room)
|
||||
except Exception as e:
|
||||
log.debug('Failed to make session %s leave room %s: %s', sid, room, e)
|
||||
|
||||
|
|
@ -603,7 +662,7 @@ async def user_join(sid, data):
|
|||
'last_seen_at': int(time.time()),
|
||||
}
|
||||
|
||||
SESSION_POOL[sid] = {**socket_user, 'chat_ids': (SESSION_POOL.get(sid) or {}).get('chat_ids', [])}
|
||||
SESSION_POOL[sid] = {**(SESSION_POOL.get(sid) or {}), **socket_user}
|
||||
await sio.save_session(sid, {'user': socket_user, 'token': auth['token']})
|
||||
LOCAL_AUTHENTICATED_SIDS.add(sid)
|
||||
await sio.enter_room(sid, f'user:{user.id}')
|
||||
|
|
@ -666,8 +725,8 @@ async def heartbeat(sid, data):
|
|||
user = await get_socket_session_user(sid)
|
||||
if user:
|
||||
SESSION_POOL[sid] = {
|
||||
**(SESSION_POOL.get(sid) or {}),
|
||||
**user,
|
||||
'chat_ids': (SESSION_POOL.get(sid) or {}).get('chat_ids', []),
|
||||
'last_seen_at': int(time.time()),
|
||||
}
|
||||
await Users.update_last_active_by_id(user['id'])
|
||||
|
|
@ -734,6 +793,10 @@ async def join_note(sid, data):
|
|||
|
||||
log.debug('Joining note %s for user %s', note.id, user.id)
|
||||
await sio.enter_room(sid, f'note:{note.id}')
|
||||
session = SESSION_POOL.get(sid)
|
||||
if session:
|
||||
SESSION_POOL[sid] = {**session, 'note_ids': list(set(session.get('note_ids', [])) | {note.id})}
|
||||
await publish_note_presence(note.id)
|
||||
|
||||
|
||||
@sio.on('note:leave')
|
||||
|
|
@ -741,6 +804,16 @@ async def leave_note(sid, data):
|
|||
note_id = data.get('note_id')
|
||||
if isinstance(note_id, str):
|
||||
await sio.leave_room(sid, f'note:{note_id}')
|
||||
session = SESSION_POOL.get(sid)
|
||||
if session:
|
||||
locations = dict(session.get('note_locations', {}))
|
||||
locations.pop(note_id, None)
|
||||
SESSION_POOL[sid] = {
|
||||
**session,
|
||||
'note_ids': [id for id in session.get('note_ids', []) if id != note_id],
|
||||
'note_locations': locations,
|
||||
}
|
||||
await publish_note_presence(note_id)
|
||||
|
||||
|
||||
@sio.on('events:channel')
|
||||
|
|
@ -959,8 +1032,8 @@ async def ydoc_document_join(sid, data):
|
|||
log.error(f'User {user.get("id")} does not have access to note {note_id}')
|
||||
return
|
||||
|
||||
user_id = data.get('user_id', sid)
|
||||
user_name = data.get('user_name', 'Anonymous')
|
||||
user_id = user['id']
|
||||
user_name = user.get('name', '')
|
||||
user_color = data.get('user_color', '#000000')
|
||||
|
||||
if (
|
||||
|
|
@ -975,6 +1048,17 @@ async def ydoc_document_join(sid, data):
|
|||
|
||||
# Join Socket.IO room
|
||||
await sio.enter_room(sid, f'doc_{document_id}')
|
||||
if document_id.startswith('note:'):
|
||||
session = SESSION_POOL.get(sid)
|
||||
if session:
|
||||
SESSION_POOL[sid] = {
|
||||
**session,
|
||||
'note_locations': {
|
||||
**session.get('note_locations', {}),
|
||||
note_id: {'page_id': page['id'], 'document_id': document_id, 'updated_at': time.time()},
|
||||
},
|
||||
}
|
||||
await publish_note_presence(note_id)
|
||||
|
||||
# Get the Yjs document state
|
||||
ydoc = Y.Doc()
|
||||
|
|
@ -1151,7 +1235,9 @@ async def yjs_document_update(sid, data):
|
|||
snapshot = data.get('data')
|
||||
if isinstance(snapshot, dict) and 'content' in snapshot:
|
||||
editor = await Users.get_user_by_id(user['id'])
|
||||
if not editor or not await has_access_to_note_files(note, get_content_files(snapshot['content']), editor):
|
||||
if not editor or not await has_access_to_note_files(
|
||||
note, get_content_files(snapshot['content']), editor
|
||||
):
|
||||
await sio.emit('error', {'message': 'Cannot attach files you cannot access'}, room=sid)
|
||||
return
|
||||
|
||||
|
|
@ -1270,6 +1356,29 @@ async def yjs_awareness_update(sid, data):
|
|||
if room not in sio.rooms(sid): # must have joined the document first
|
||||
return
|
||||
update = data['update']
|
||||
if document_id.startswith('note:'):
|
||||
note_id = document_id.split(':')[1]
|
||||
session = SESSION_POOL.get(sid)
|
||||
location = (session or {}).get('note_locations', {}).get(note_id)
|
||||
cursor = data.get('cursor')
|
||||
position = data.get('cursor_position')
|
||||
if (
|
||||
location
|
||||
and location.get('document_id') == document_id
|
||||
and isinstance(cursor, dict)
|
||||
and isinstance(cursor.get('head'), dict)
|
||||
and len(dumps_bytes(cursor)) <= 1024
|
||||
and isinstance(position, int)
|
||||
and 0 <= position <= 100_000_000
|
||||
):
|
||||
SESSION_POOL[sid] = {
|
||||
**session,
|
||||
'note_locations': {
|
||||
**session.get('note_locations', {}),
|
||||
note_id: {**location, 'cursor': cursor, 'cursor_position': position, 'updated_at': time.time()},
|
||||
},
|
||||
}
|
||||
await publish_note_presence(note_id)
|
||||
|
||||
# Broadcast to the room; user_id is the authenticated identity, not client-supplied
|
||||
await sio.emit(
|
||||
|
|
@ -1289,7 +1398,11 @@ async def disconnect(sid, reason=None):
|
|||
LOCAL_AUTHENTICATED_SIDS.discard(sid)
|
||||
if sid in SESSION_POOL:
|
||||
chat_ids = (SESSION_POOL.get(sid) or {}).get('chat_ids', [])
|
||||
note_ids = (SESSION_POOL.get(sid) or {}).get('note_ids', [])
|
||||
del SESSION_POOL[sid]
|
||||
for note_id in note_ids:
|
||||
await sio.leave_room(sid, f'note:{note_id}')
|
||||
await publish_note_presence(note_id)
|
||||
for chat_id in chat_ids:
|
||||
await sio.leave_room(sid, f'chat:{chat_id}')
|
||||
await publish_chat_presence(chat_id)
|
||||
|
|
@ -1303,10 +1416,7 @@ async def disconnect(sid, reason=None):
|
|||
else:
|
||||
USAGE_POOL[model_id] = connections
|
||||
|
||||
await YDOC_MANAGER.remove_user_from_all_documents(sid)
|
||||
else:
|
||||
pass
|
||||
# print(f"Unknown session ID {sid} disconnected")
|
||||
await remove_document_session(sid)
|
||||
|
||||
|
||||
async def redis_event_listener() -> None:
|
||||
|
|
|
|||
|
|
@ -393,7 +393,7 @@ class YdocManager:
|
|||
if not self._users[document_id]:
|
||||
del self._users[document_id]
|
||||
|
||||
async def remove_user_from_all_documents(self, user_id: str):
|
||||
async def remove_user_from_all_documents(self, user_id: str) -> list[str]:
|
||||
if self._redis:
|
||||
session_key = f'{self._redis_key_prefix}:session:{user_id}:documents'
|
||||
document_ids = await self._redis.smembers(session_key)
|
||||
|
|
@ -405,6 +405,7 @@ class YdocManager:
|
|||
await self.remove_user(document_id, user_id)
|
||||
if not await self.get_users(document_id) and not await has_active_tasks(self._redis, document_id):
|
||||
await self.clear_document(document_id)
|
||||
return list(document_ids)
|
||||
|
||||
async def clear_document(self, document_id: str):
|
||||
if self._redis:
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@
|
|||
export let activeProfileId: string | null = null;
|
||||
export let overflowOpen = false;
|
||||
export let mode: 'contributors' | 'presence' = 'contributors';
|
||||
export let onSelect: ((person: ChatParticipant) => void) | null = null;
|
||||
|
||||
// Preserve the base overflow label alongside its generated plural forms.
|
||||
// $i18n.t('Show all {{count}} contributors');
|
||||
|
|
@ -54,25 +55,40 @@
|
|||
: '-space-x-1'} rtl:space-x-reverse"
|
||||
>
|
||||
{#each people.slice(0, 3) as person (person.id)}
|
||||
<div class="relative rounded-full hover:z-10 focus-within:z-10">
|
||||
<ProfilePreview
|
||||
side={mode === 'presence' ? 'bottom' : 'right'}
|
||||
align={mode === 'presence' ? 'end' : 'center'}
|
||||
user={{ id: person.id, name: person.name || $i18n.t('Unknown User') }}
|
||||
bind:openPreview={
|
||||
() => !overflowOpen && activeProfileId === person.id,
|
||||
(open) => setProfileOpen(person.id, open)
|
||||
}
|
||||
>
|
||||
{@render avatar(
|
||||
person,
|
||||
`${avatarClass} bg-white dark:bg-gray-900 ${
|
||||
mode === 'presence'
|
||||
? `ring-2 ${['ring-red-400', 'ring-sky-400', 'ring-lime-500', 'ring-amber-400', 'ring-violet-400'][person.id.charCodeAt(0) % 5]}`
|
||||
: 'ring-1 ring-white dark:ring-gray-900'
|
||||
}`
|
||||
)}
|
||||
</ProfilePreview>
|
||||
<div class="relative flex items-center rounded-full hover:z-10 focus-within:z-10">
|
||||
{#if onSelect}
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center justify-center rounded-full focus-visible:outline"
|
||||
aria-label={person.name || $i18n.t('Unknown User')}
|
||||
title={person.name || $i18n.t('Unknown User')}
|
||||
onclick={() => onSelect(person)}
|
||||
>
|
||||
{@render avatar(
|
||||
person,
|
||||
`${avatarClass} bg-white dark:bg-gray-900 ring-2 ${['ring-red-400', 'ring-sky-400', 'ring-lime-500', 'ring-amber-400', 'ring-violet-400'][person.id.charCodeAt(0) % 5]}`
|
||||
)}
|
||||
</button>
|
||||
{:else}
|
||||
<ProfilePreview
|
||||
side={mode === 'presence' ? 'bottom' : 'right'}
|
||||
align={mode === 'presence' ? 'end' : 'center'}
|
||||
user={{ id: person.id, name: person.name || $i18n.t('Unknown User') }}
|
||||
bind:openPreview={
|
||||
() => !overflowOpen && activeProfileId === person.id,
|
||||
(open) => setProfileOpen(person.id, open)
|
||||
}
|
||||
>
|
||||
{@render avatar(
|
||||
person,
|
||||
`${avatarClass} bg-white dark:bg-gray-900 ${
|
||||
mode === 'presence'
|
||||
? `ring-2 ${['ring-red-400', 'ring-sky-400', 'ring-lime-500', 'ring-amber-400', 'ring-violet-400'][person.id.charCodeAt(0) % 5]}`
|
||||
: 'ring-1 ring-white dark:ring-gray-900'
|
||||
}`
|
||||
)}
|
||||
</ProfilePreview>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
|
@ -80,9 +96,10 @@
|
|||
{#if people.length > 3}
|
||||
<Popover.Root bind:open={overflowOpen} onOpenChange={() => (activeProfileId = null)}>
|
||||
<Popover.Trigger
|
||||
class="shrink-0 rounded px-0.5 {mode === 'presence'
|
||||
class="inline-flex shrink-0 items-center justify-center rounded bg-transparent px-0.5 leading-none {mode ===
|
||||
'presence'
|
||||
? 'h-6 text-xs'
|
||||
: 'text-[0.625rem]'} text-gray-500 hover:bg-gray-100 focus-visible:outline dark:text-gray-400 dark:hover:bg-gray-800"
|
||||
: 'text-[0.625rem]'} text-gray-500 hover:text-gray-900 focus-visible:outline dark:text-gray-400 dark:hover:text-gray-100"
|
||||
aria-label={mode === 'presence'
|
||||
? $i18n.t('Collaborators')
|
||||
: $i18n.t('Show all {{count}} contributors', { count: people.length })}
|
||||
|
|
@ -109,20 +126,36 @@
|
|||
<li
|
||||
class="rounded-lg p-1 hover:bg-gray-50 dark:hover:bg-gray-800 [&>button]:max-w-full"
|
||||
>
|
||||
<ProfilePreview
|
||||
side={mode === 'presence' ? 'bottom' : 'right'}
|
||||
align={mode === 'presence' ? 'end' : 'center'}
|
||||
user={{ id: person.id, name: person.name || $i18n.t('Unknown User') }}
|
||||
bind:openPreview={
|
||||
() => overflowOpen && activeProfileId === person.id,
|
||||
(open) => setProfileOpen(person.id, open)
|
||||
}
|
||||
>
|
||||
{@render avatar(person, 'size-6')}
|
||||
<span class="ms-2 min-w-0 truncate text-sm">
|
||||
{person.name || $i18n.t('Unknown User')}
|
||||
</span>
|
||||
</ProfilePreview>
|
||||
{#if onSelect}
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center rounded-lg text-left"
|
||||
onclick={() => {
|
||||
overflowOpen = false;
|
||||
onSelect(person);
|
||||
}}
|
||||
>
|
||||
{@render avatar(person, 'size-6')}
|
||||
<span class="ms-2 min-w-0 truncate text-sm"
|
||||
>{person.name || $i18n.t('Unknown User')}</span
|
||||
>
|
||||
</button>
|
||||
{:else}
|
||||
<ProfilePreview
|
||||
side={mode === 'presence' ? 'bottom' : 'right'}
|
||||
align={mode === 'presence' ? 'end' : 'center'}
|
||||
user={{ id: person.id, name: person.name || $i18n.t('Unknown User') }}
|
||||
bind:openPreview={
|
||||
() => overflowOpen && activeProfileId === person.id,
|
||||
(open) => setProfileOpen(person.id, open)
|
||||
}
|
||||
>
|
||||
{@render avatar(person, 'size-6')}
|
||||
<span class="ms-2 min-w-0 truncate text-sm">
|
||||
{person.name || $i18n.t('Unknown User')}
|
||||
</span>
|
||||
</ProfilePreview>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
|
|
|||
|
|
@ -423,6 +423,14 @@
|
|||
$: serializeContent(richText);
|
||||
|
||||
let provider: SocketIOCollaborationProvider | null = null;
|
||||
export let cursorTarget = null;
|
||||
$: if (cursorTarget && editor) {
|
||||
const target = cursorTarget;
|
||||
cursorTarget = null;
|
||||
if (provider) provider.revealCursor(target);
|
||||
else
|
||||
editor.commands.focus(Math.min(target.cursor_position ?? 0, editor.state.doc.content.size));
|
||||
}
|
||||
export const flush = async () => {
|
||||
await tick();
|
||||
await provider?.flush();
|
||||
|
|
@ -838,6 +846,23 @@
|
|||
}
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
// Read-only viewers join for presence without starting the editing provider.
|
||||
if (!collaboration || editable || !documentId || !socket || !user) return;
|
||||
const presenceSocket = socket;
|
||||
const presenceDocumentId = documentId;
|
||||
const join = () =>
|
||||
presenceSocket.emit('ydoc:document:join', { document_id: presenceDocumentId });
|
||||
presenceSocket.on('connect', join);
|
||||
if (presenceSocket.connected) join();
|
||||
return () => {
|
||||
presenceSocket.off('connect', join);
|
||||
if (presenceSocket.connected) {
|
||||
presenceSocket.emit('ydoc:document:leave', { document_id: presenceDocumentId });
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
onMount(async () => {
|
||||
content = value;
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,8 @@ import {
|
|||
yUndoPlugin,
|
||||
undo,
|
||||
redo,
|
||||
prosemirrorJSONToYDoc
|
||||
prosemirrorJSONToYDoc,
|
||||
relativePositionToAbsolutePosition
|
||||
} from 'y-prosemirror';
|
||||
import type { Socket } from 'socket.io-client';
|
||||
import type { SessionUser } from '$lib/stores';
|
||||
|
|
@ -48,6 +49,38 @@ export class SocketIOCollaborationProvider {
|
|||
private editorContentGetter: EditorContentGetter | null = null;
|
||||
private listeners: Array<[string, (...args: any[]) => void]> = [];
|
||||
private contentSnapshotTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private cursorTarget: any = null;
|
||||
|
||||
public revealCursor(target: any) {
|
||||
this.cursorTarget = target;
|
||||
this.revealPendingCursor();
|
||||
}
|
||||
|
||||
private revealPendingCursor() {
|
||||
if (!this.synced || !this.editor || !this.cursorTarget) return;
|
||||
const target = this.cursorTarget;
|
||||
this.cursorTarget = null;
|
||||
const editor = this.editor;
|
||||
let position = target.cursor_position ?? 0;
|
||||
try {
|
||||
const state = ySyncPluginKey.getState(editor.state);
|
||||
if (target.cursor?.head && state?.binding) {
|
||||
position =
|
||||
relativePositionToAbsolutePosition(
|
||||
this.doc,
|
||||
state.type,
|
||||
Y.createRelativePositionFromJSON(target.cursor.head),
|
||||
state.binding.mapping
|
||||
) ?? position;
|
||||
}
|
||||
} catch {
|
||||
// A replaced document can no longer resolve the old relative cursor.
|
||||
}
|
||||
queueMicrotask(() => {
|
||||
if (!editor.isDestroyed)
|
||||
editor.commands.focus(Math.min(position, editor.state.doc.content.size));
|
||||
});
|
||||
}
|
||||
|
||||
constructor(
|
||||
private readonly documentId: string,
|
||||
|
|
@ -131,6 +164,7 @@ export class SocketIOCollaborationProvider {
|
|||
if (!state || !this.editor) return;
|
||||
Y.applyUpdate(this.doc, new Uint8Array(state), 'server');
|
||||
this.synced = true;
|
||||
this.revealPendingCursor();
|
||||
if (!this.contentSnapshotTimer) this.sendContentSnapshot();
|
||||
}
|
||||
);
|
||||
|
|
@ -252,6 +286,7 @@ export class SocketIOCollaborationProvider {
|
|||
}
|
||||
}
|
||||
this.synced = true;
|
||||
this.revealPendingCursor();
|
||||
} catch (error) {
|
||||
console.error('Error applying Yjs state:', error);
|
||||
|
||||
|
|
@ -318,7 +353,9 @@ export class SocketIOCollaborationProvider {
|
|||
this.socket.emit('ydoc:awareness:update', {
|
||||
document_id: this.documentId,
|
||||
user_id: this.socket.id,
|
||||
update: Array.from(awarenessUpdate)
|
||||
update: Array.from(awarenessUpdate),
|
||||
cursor: this.awareness.getLocalState()?.cursor,
|
||||
cursor_position: this.editor?.state.selection.head
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,17 @@
|
|||
import { Node } from '@tiptap/core';
|
||||
import { Plugin, PluginKey } from '@tiptap/pm/state';
|
||||
import { Decoration, DecorationSet } from '@tiptap/pm/view';
|
||||
import { createClassComponent } from 'svelte/legacy';
|
||||
import FileItem from '../FileItem.svelte';
|
||||
|
||||
export const fileUploadsKey = new PluginKey<DecorationSet>('fileUploads');
|
||||
|
||||
const fileItemStyle = {
|
||||
small: true,
|
||||
className: 'w-56 max-w-full',
|
||||
colorClassName: 'bg-gray-50/60 dark:bg-white/[0.03] border border-gray-100/80 dark:border-white/5'
|
||||
};
|
||||
|
||||
export default Node.create<{ context: Map<any, any> }>({
|
||||
name: 'fileAttachment',
|
||||
group: 'block',
|
||||
|
|
@ -49,6 +59,58 @@ export default Node.create<{ context: Map<any, any> }>({
|
|||
renderText({ node }) {
|
||||
return node.attrs.name;
|
||||
},
|
||||
addProseMirrorPlugins() {
|
||||
return [
|
||||
new Plugin({
|
||||
key: fileUploadsKey,
|
||||
state: {
|
||||
init: () => DecorationSet.empty,
|
||||
apply: (transaction, decorations) => {
|
||||
decorations = decorations.map(transaction.mapping, transaction.doc);
|
||||
const action = transaction.getMeta(fileUploadsKey);
|
||||
if (action?.add) {
|
||||
const { id, pos, file } = action.add;
|
||||
let component;
|
||||
const placeholder = Decoration.widget(
|
||||
pos,
|
||||
(view) => {
|
||||
const dom = document.createElement('div');
|
||||
dom.className = 'not-prose my-2 w-fit max-w-full';
|
||||
dom.setAttribute('aria-busy', 'true');
|
||||
component = createClassComponent({
|
||||
component: FileItem,
|
||||
target: dom,
|
||||
context: this.options.context,
|
||||
props: {
|
||||
...fileItemStyle,
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
type: 'file',
|
||||
loading: true,
|
||||
dismissible: true
|
||||
}
|
||||
});
|
||||
component.$on('dismiss', () => {
|
||||
view.dispatch(view.state.tr.setMeta(fileUploadsKey, { remove: id }));
|
||||
});
|
||||
return dom;
|
||||
},
|
||||
{ id, side: -1, stopEvent: () => true, destroy: () => component?.$destroy() }
|
||||
);
|
||||
decorations = decorations.add(transaction.doc, [placeholder]);
|
||||
}
|
||||
if (action?.remove) {
|
||||
decorations = decorations.remove(
|
||||
decorations.find(undefined, undefined, (spec) => spec.id === action.remove)
|
||||
);
|
||||
}
|
||||
return decorations;
|
||||
}
|
||||
},
|
||||
props: { decorations: (state) => fileUploadsKey.getState(state) }
|
||||
})
|
||||
];
|
||||
},
|
||||
addNodeView() {
|
||||
return ({ node, editor, getPos }) => {
|
||||
const dom = document.createElement('div');
|
||||
|
|
@ -60,6 +122,7 @@ export default Node.create<{ context: Map<any, any> }>({
|
|||
target: dom,
|
||||
context: this.options.context,
|
||||
props: {
|
||||
...fileItemStyle,
|
||||
item: { ...node.attrs, type: 'file' },
|
||||
name: node.attrs.name,
|
||||
type: 'file',
|
||||
|
|
@ -67,11 +130,7 @@ export default Node.create<{ context: Map<any, any> }>({
|
|||
url: node.attrs.id,
|
||||
dismissible: editor.isEditable,
|
||||
edit: editor.isEditable,
|
||||
small: true,
|
||||
modal: true,
|
||||
className: 'w-56 max-w-full',
|
||||
colorClassName:
|
||||
'bg-gray-50/60 dark:bg-white/[0.03] border border-gray-100/80 dark:border-white/5'
|
||||
modal: true
|
||||
}
|
||||
});
|
||||
component.$on('dismiss', () => {
|
||||
|
|
|
|||
|
|
@ -70,12 +70,14 @@
|
|||
import { deleteChatById } from '$lib/apis/chats';
|
||||
|
||||
import RichTextInput from '../common/RichTextInput.svelte';
|
||||
import { fileUploadsKey } from '../common/RichTextInput/FileAttachment';
|
||||
import Spinner from '../common/Spinner.svelte';
|
||||
import Mic from '../icons/Mic.svelte';
|
||||
import VoiceRecording from '../chat/MessageInput/VoiceRecording.svelte';
|
||||
import DeleteConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
|
||||
|
||||
import AccessButton from '../common/AccessButton.svelte';
|
||||
import ChatParticipants from '../common/ChatParticipants.svelte';
|
||||
|
||||
import FilesOverlay from '../chat/MessageInput/FilesOverlay.svelte';
|
||||
import RecordMenu from './RecordMenu.svelte';
|
||||
|
|
@ -129,6 +131,39 @@
|
|||
let loadGeneration = 0;
|
||||
let pageScroll: Record<string, number> = {};
|
||||
$: activePage = note?.data?.pages?.find((p) => p.id === activePageId);
|
||||
$: activeDocumentId = activePage
|
||||
? `note:${note.id}:page:${activePage.id}:${activePage.generation}`
|
||||
: '';
|
||||
let presenceNoteId = '';
|
||||
let cursorTarget = null;
|
||||
let liveParticipants: {
|
||||
id: string;
|
||||
name: string;
|
||||
page_id?: string;
|
||||
document_id?: string;
|
||||
cursor?: any;
|
||||
cursor_position?: number;
|
||||
}[] = [];
|
||||
const clearPresence = () => (liveParticipants = []);
|
||||
$: if (presenceNoteId !== note?.id) {
|
||||
presenceNoteId = note?.id;
|
||||
clearPresence();
|
||||
}
|
||||
const presenceEventHandler = (event: { note_id: string; users: typeof liveParticipants }) => {
|
||||
if (!$socket?.connected || event.note_id !== note?.id) return;
|
||||
liveParticipants = event.users.filter((person) => person.id !== $user?.id);
|
||||
};
|
||||
const joinNote = () => {
|
||||
if (note?.id)
|
||||
$socket?.emit('note:join', { note_id: note.id, auth: { token: localStorage.token } });
|
||||
};
|
||||
const goToParticipant = async (person) => {
|
||||
const target = liveParticipants.find((participant) => participant.id === person.id);
|
||||
if (!target?.page_id || pageBusy) return;
|
||||
await selectPage(target.page_id);
|
||||
await tick();
|
||||
if (activePageId === target.page_id) cursorTarget = { ...target };
|
||||
};
|
||||
$: if (
|
||||
note?.id === id &&
|
||||
$page.url.searchParams.get('page') &&
|
||||
|
|
@ -142,6 +177,7 @@
|
|||
if (!target || target.id === activePageId) return;
|
||||
const body = document.getElementById('note-content-container');
|
||||
if (body && activePageId) pageScroll[activePageId] = body.scrollTop;
|
||||
cursorTarget = null;
|
||||
activePageId = target.id;
|
||||
selectedContent = null;
|
||||
versionIdx = null;
|
||||
|
|
@ -360,14 +396,15 @@
|
|||
note.access_grants = [];
|
||||
}
|
||||
|
||||
$socket?.emit('note:join', {
|
||||
note_id: id,
|
||||
auth: {
|
||||
token: localStorage.token
|
||||
}
|
||||
});
|
||||
$socket?.off('events:note', noteEventHandler);
|
||||
$socket?.on('events:note', noteEventHandler);
|
||||
$socket?.off('note:presence', presenceEventHandler);
|
||||
$socket?.on('note:presence', presenceEventHandler);
|
||||
$socket?.off('disconnect', clearPresence);
|
||||
$socket?.on('disconnect', clearPresence);
|
||||
$socket?.off('connect', joinNote);
|
||||
$socket?.on('connect', joinNote);
|
||||
joinNote();
|
||||
} else {
|
||||
goto('/');
|
||||
return;
|
||||
|
|
@ -606,21 +643,24 @@ ${content}
|
|||
pos = uploadEditor?.state.selection.from
|
||||
) => {
|
||||
if (!uploadEditor || uploadEditor.isDestroyed || !file) return Promise.resolve(null);
|
||||
// Keep the insertion point attached to the document while the upload is in flight.
|
||||
let position = pos;
|
||||
const trackPosition = ({ transaction }) => {
|
||||
position = transaction.mapping.map(position);
|
||||
};
|
||||
uploadEditor.on('transaction', trackPosition);
|
||||
const id = uuidv4();
|
||||
// Keep upload UI local so unfinished files never enter saved or shared content.
|
||||
uploadEditor.view.dispatch(
|
||||
uploadEditor.state.tr.setMeta(fileUploadsKey, { add: { id, pos, file } })
|
||||
);
|
||||
const pending = (async () => {
|
||||
const uploading = toast.loading($i18n.t('Uploading...'));
|
||||
try {
|
||||
const item = await processInputFile(file);
|
||||
if (!item || uploadEditor.isDestroyed) return null;
|
||||
const placeholder = fileUploadsKey
|
||||
.getState(uploadEditor.state)
|
||||
?.find(undefined, undefined, (spec) => spec.id === id)[0];
|
||||
if (!placeholder) return null;
|
||||
uploadEditor
|
||||
.chain()
|
||||
.setMeta(fileUploadsKey, { remove: id })
|
||||
.insertContentAt(
|
||||
position,
|
||||
placeholder.from,
|
||||
item.type === 'image'
|
||||
? { type: 'image', attrs: { src: item.url } }
|
||||
: { type: 'fileAttachment', attrs: { id: item.id, name: item.name, size: item.size } }
|
||||
|
|
@ -632,8 +672,9 @@ ${content}
|
|||
toast.error(String(error));
|
||||
return null;
|
||||
} finally {
|
||||
toast.dismiss(uploading);
|
||||
uploadEditor.off('transaction', trackPosition);
|
||||
if (!uploadEditor.isDestroyed) {
|
||||
uploadEditor.view.dispatch(uploadEditor.state.tr.setMeta(fileUploadsKey, { remove: id }));
|
||||
}
|
||||
}
|
||||
})();
|
||||
pendingFileUploads.add(pending);
|
||||
|
|
@ -957,6 +998,9 @@ ${content}
|
|||
$socket?.emit('note:leave', { note_id: note?.id });
|
||||
if (debounceTimeout) clearTimeout(debounceTimeout);
|
||||
$socket?.off('events:note', noteEventHandler);
|
||||
$socket?.off('note:presence', presenceEventHandler);
|
||||
$socket?.off('disconnect', clearPresence);
|
||||
$socket?.off('connect', joinNote);
|
||||
|
||||
const dropzoneElement = document.getElementById('note-editor');
|
||||
|
||||
|
|
@ -1263,6 +1307,17 @@ ${content}
|
|||
</button>
|
||||
</NoteMenu>
|
||||
|
||||
{#if liveParticipants.length > 0}
|
||||
<div class="ms-1 me-0.5">
|
||||
<ChatParticipants
|
||||
participants={liveParticipants}
|
||||
onSelect={goToParticipant}
|
||||
mode="presence"
|
||||
avatarClass="size-5"
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if note?.write_access}
|
||||
{#if $user?.permissions?.sharing?.notes || $user?.role === 'admin'}
|
||||
<div class="ml-1.5">
|
||||
|
|
@ -1442,7 +1497,8 @@ ${content}
|
|||
json={true}
|
||||
bind:value={renderedPage.content.json}
|
||||
html={editorHtml}
|
||||
documentId={`note:${note.id}:page:${renderedPage.id}:${renderedPage.generation}`}
|
||||
documentId={activeDocumentId}
|
||||
bind:cursorTarget
|
||||
collaboration={true}
|
||||
socket={$socket}
|
||||
user={$user}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue