Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/application/awareness/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Editor } from 'slate';
import { Awareness } from 'y-protocols/awareness';

import { getUserIconUrl } from '@/application/user-metadata';
import { Log } from '@/utils/log';
import { useCurrentUser, useService } from '@/components/main/app.hooks';

import { AwarenessMetadata, AwarenessState } from './types';
Expand Down Expand Up @@ -49,7 +50,7 @@ export function useDispatchUserAwareness(awareness?: Awareness) {
awareness.setLocalState(awarenessState);

// Log successful user awareness dispatch
console.debug('📡 User awareness dispatched:', awarenessState);
Log.debug('📡 User awareness dispatched:', awarenessState);
},
[awareness]
);
Expand Down Expand Up @@ -100,7 +101,7 @@ export function useDispatchCursorAwareness(awareness?: Awareness) {
awareness.setLocalState(awarenessState);

// Log successful cursor awareness sync
console.debug('🎯 Cursor awareness synced:', awarenessState);
Log.debug('🎯 Cursor awareness synced:', awarenessState);
} catch (error) {
// Log conversion errors for debugging
console.warn('⚠️ Cursor awareness sync failed:', error);
Expand Down Expand Up @@ -149,7 +150,7 @@ export function useDispatchClearAwareness(awareness?: Awareness) {
});

// Log awareness clear
console.debug('🚫 Awareness cleared for current user');
Log.debug('🚫 Awareness cleared for current user');
}, [awareness, service, currentUser]);

const clearCursor = useCallback((workspaceAvatar?: string | null) => {
Expand All @@ -171,7 +172,7 @@ export function useDispatchClearAwareness(awareness?: Awareness) {
}),
});

console.debug('🚫 Cursor awareness cleared for current user');
Log.debug('🚫 Cursor awareness cleared for current user');
}, [awareness, service, currentUser]);

return { clearAwareness, clearCursor };
Expand Down
5 changes: 3 additions & 2 deletions src/application/awareness/selector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useSlate } from 'slate-react';
import { Awareness } from 'y-protocols/awareness';

import { useService } from '@/components/main/app.hooks';
import { Log } from '@/utils/log';

import { AwarenessMetadata, AwarenessState, AwarenessUser, Cursor } from './types';
import { convertAwarenessSelection } from './utils';
Expand Down Expand Up @@ -92,7 +93,7 @@ export function useRemoteSelectionsSelector(awareness?: Awareness) {
timestamp: state.timestamp,
});
} else {
console.debug(`🎯 No selection found for client ${clientId}`);
Log.debug(`🎯 No selection found for client ${clientId}`);
}
});

Expand Down Expand Up @@ -120,7 +121,7 @@ export function useRemoteSelectionsSelector(awareness?: Awareness) {
};
});

console.debug('🎯 Final cursors array:', result);
Log.debug('🎯 Final cursors array:', result);
return result;
}, [cursors, editor]);

Expand Down
5 changes: 3 additions & 2 deletions src/application/database-yjs/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useCallback, useMemo } from 'react';
import { v4 as uuidv4 } from 'uuid';
import * as Y from 'yjs';

import { Log } from '@/utils/log';
import { parseYDatabaseDateTimeCellToCell } from '@/application/database-yjs/cell.parse';
import {
useCreateRow,
Expand Down Expand Up @@ -2002,7 +2003,7 @@ function updateDateCell(
}

if (payload.includeTime !== undefined) {
console.debug('includeTime', payload.includeTime);
Log.debug('includeTime', payload.includeTime);
cell.set(YjsDatabaseKey.include_time, payload.includeTime);
}

Expand Down Expand Up @@ -3737,7 +3738,7 @@ export function useUpdateFileMediaTypeOption(fieldId: string) {
);
typeOptionMap.set(String(FieldType.FileMedia), newTypeOption);
} else {
console.debug('Updating file media type option', typeOption.toJSON());
Log.debug('Updating file media type option', typeOption.toJSON());
typeOption.set(
YjsDatabaseKey.content,
JSON.stringify({
Expand Down
3 changes: 2 additions & 1 deletion src/application/db/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { IndexeddbPersistence } from 'y-indexeddb';
import * as Y from 'yjs';

import { databasePrefix } from '@/application/constants';
import { Log } from '@/utils/log';
import { rowSchema, rowTable } from '@/application/db/tables/rows';
import { userSchema, UserTable } from '@/application/db/tables/users';
import { viewMetasSchema, ViewMetasTable } from '@/application/db/tables/view_metas';
Expand Down Expand Up @@ -106,7 +107,7 @@ export async function clearData() {
const deleteRequest = indexedDB.deleteDatabase(dbName);

deleteRequest.onsuccess = () => {
console.debug(`Database ${dbName} deleted successfully`);
Log.debug(`Database ${dbName} deleted successfully`);
resolve(true);
};

Expand Down
3 changes: 2 additions & 1 deletion src/application/services/js-services/cache/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getRowKey } from '@/application/database-yjs/row_meta';
import { closeCollabDB, db, openCollabDB } from '@/application/db';
import { Fetcher, StrategyType } from '@/application/services/js-services/cache/types';
import { Log } from '@/utils/log';
import {
DatabaseId,
PublishViewMetaData,
Expand Down Expand Up @@ -390,7 +391,7 @@ export async function deleteViewMeta(name: string) {
}

export async function deleteView(name: string) {
console.debug('deleteView', name);
Log.debug('deleteView', name);
await deleteViewMeta(name);
await closeCollabDB(name);

Expand Down
11 changes: 6 additions & 5 deletions src/application/services/js-services/http/http_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { omit } from 'lodash-es';
import { nanoid } from 'nanoid';

import { GlobalComment, Reaction } from '@/application/comment.type';
import { Log } from '@/utils/log';
import { ERROR_CODE } from '@/application/constants';
import { initGrantService, refreshToken } from '@/application/services/js-services/http/gotrue';
import { parseGoTrueErrorFromUrl } from '@/application/services/js-services/http/gotrue-error';
Expand Down Expand Up @@ -155,7 +156,7 @@ async function executeAPIRequest<TResponseData = unknown>(

const method = response.config?.method?.toUpperCase() || 'UNKNOWN';

console.debug('[executeAPIRequest]', { method, url: requestUrl });
Log.debug('[executeAPIRequest]', { method, url: requestUrl });

if (!response.data) {
console.error('[executeAPIRequest] No response data received', response);
Expand Down Expand Up @@ -238,7 +239,7 @@ export function initAPIService(config: AFCloudConfig) {
const token = getTokenParsed();

if (!token) {
console.debug('[initAPIService][request] no token found, sending request without auth header', {
Log.debug('[initAPIService][request] no token found, sending request without auth header', {
url: config.url,
});
return config;
Expand Down Expand Up @@ -359,7 +360,7 @@ export async function signInWithUrl(url: string) {
const hadOldToken = !!localStorage.getItem('token');

if (hadOldToken) {
console.debug('[signInWithUrl] Clearing old token before processing OAuth callback to prevent race condition');
Log.debug('[signInWithUrl] Clearing old token before processing OAuth callback to prevent race condition');
localStorage.removeItem('token');
}

Expand Down Expand Up @@ -1400,7 +1401,7 @@ export async function uploadImportFile(presignedUrl: string, file: File, onProgr
onUploadProgress: (progressEvent) => {
const { progress = 0 } = progressEvent;

console.debug(`Upload progress: ${progress * 100}%`);
Log.debug(`Upload progress: ${progress * 100}%`);
onProgress(progress);
},
headers: {
Expand All @@ -1425,7 +1426,7 @@ export async function createDatabaseView(
) {
const url = `/api/workspace/${workspaceId}/page-view/${viewId}/database-view`;

console.debug('[createDatabaseView]', { url, workspaceId, viewId, payload });
Log.debug('[createDatabaseView]', { url, workspaceId, viewId, payload });

return executeAPIRequest<CreateDatabaseViewResponse>(() =>
axiosInstance?.post<APIResponse<CreateDatabaseViewResponse>>(url, {
Expand Down
9 changes: 5 additions & 4 deletions src/application/services/js-services/sync-protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as awarenessProtocol from 'y-protocols/awareness';
import * as Y from 'yjs';

import { Types } from '@/application/types';
import { Log } from '@/utils/log';
import { collab, messages } from '@/proto/messages';

/**
Expand Down Expand Up @@ -61,7 +62,7 @@ const handleAccessChanged = (ctx: SyncContext, message: collab.IAccessChanged):

const handleAwarenessUpdate = (ctx: SyncContext, message: collab.IAwarenessUpdate): void => {
if (!ctx.awareness) {
console.debug(`No awareness instance found in SyncContext for objectId ${ctx.doc.guid}`);
Log.debug(`No awareness instance found in SyncContext for objectId ${ctx.doc.guid}`);
} else {
awarenessProtocol.applyAwarenessUpdate(ctx.awareness, message.payload!, 'remote');
}
Expand All @@ -81,12 +82,12 @@ const handleUpdate = (ctx: SyncContext, message: collab.IUpdate): void => {
throw new Error(`Unknown update flags: ${message.flags} at ${message.messageId?.timestamp}`);
}

console.debug(`applied update to doc ${doc.guid}`);
Log.debug(`applied update to doc ${doc.guid}`);
ctx.lastMessageId = message.messageId || ctx.lastMessageId;

// check if there are any missing update data
if (doc.store.pendingStructs || doc.store.pendingDs) {
console.debug(`Doc ${doc.guid} has missing dependencies. Sending sync request...`);
Log.debug(`Doc ${doc.guid} has missing dependencies. Sending sync request...`);
emit({
collabMessage: {
objectId: doc.guid,
Expand Down Expand Up @@ -117,7 +118,7 @@ export const initSync = (ctx: SyncContext) => {
throw new Error('SyncContext must have a Y.Doc instance.');
}

console.debug(`Initializing sync for objectId ${doc.guid} with collabType ${collabType}`);
Log.debug(`Initializing sync for objectId ${doc.guid} with collabType ${collabType}`);

let onAwarenessChange;
const updates: Uint8Array[] = [];
Expand Down
13 changes: 7 additions & 6 deletions src/application/slate-yjs/utils/applyTextToSlate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Editor, Element, Operation, Path, Text } from 'slate';
import * as Y from 'yjs';

import { YjsEditor } from '@/application/slate-yjs';
import { Log } from '@/utils/log';

interface Delta {
retain?: number;
Expand Down Expand Up @@ -30,7 +31,7 @@ function applyTextYEvent(editor: YjsEditor, textId: string, event: Y.YTextEvent)
const [targetElement, textPath] = entry as [Element, number[]];
const delta = event.delta as Delta[];

console.debug('📝 Applying YText event', {
Log.debug('📝 Applying YText event', {
textId,
delta,
targetPath: textPath,
Expand All @@ -39,10 +40,10 @@ function applyTextYEvent(editor: YjsEditor, textId: string, event: Y.YTextEvent)
Editor.withoutNormalizing(editor, () => {
const operations = applyDelta(targetElement, textPath, delta);

console.debug(`🔄 Generated ${operations.length} operations from delta:`, operations);
Log.debug(`🔄 Generated ${operations.length} operations from delta:`, operations);

operations.forEach((op, index) => {
console.debug(`Applying operation ${index + 1}/${operations.length}:`, op);
Log.debug(`Applying operation ${index + 1}/${operations.length}:`, op);
editor.apply(op);
});
});
Expand Down Expand Up @@ -121,7 +122,7 @@ function handleAttributeChange(
): Operation[] {
const ops: Operation[] = [];

console.debug(`🎨 Applying attributes from offset ${startOffset} to ${endOffset}:`, attributes);
Log.debug(`🎨 Applying attributes from offset ${startOffset} to ${endOffset}:`, attributes);

// Convert Y offsets to Slate path/text offsets
const [startPathOffset, startTextOffset] = yOffsetToSlateOffsets(node, startOffset);
Expand Down Expand Up @@ -210,7 +211,7 @@ function handleAttributeChange(
function handleDelete(node: Element, slatePath: Path, startOffset: number, endOffset: number): Operation[] {
const ops: Operation[] = [];

console.debug(`➖ Deleting from offset ${startOffset} to ${endOffset}`);
Log.debug(`➖ Deleting from offset ${startOffset} to ${endOffset}`);

const [startPathOffset, startTextOffset] = yOffsetToSlateOffsets(node, startOffset);
const [endPathOffset, endTextOffset] = yOffsetToSlateOffsets(node, endOffset, { assoc: -1 });
Expand Down Expand Up @@ -282,7 +283,7 @@ function handleInsert(
): Operation[] {
const ops: Operation[] = [];

console.debug(`➕ Inserting at offset ${offset}:`, insert, attributes);
Log.debug(`➕ Inserting at offset ${offset}:`, insert, attributes);

const [pathOffset, textOffset] = yOffsetToSlateOffsets(node, offset, { insert: true });

Expand Down
16 changes: 8 additions & 8 deletions src/application/slate-yjs/utils/applyToSlate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,42 +27,42 @@ interface YBlockChange {
* @param events - Array of Yjs events to process
*/
export function translateYEvents(editor: YjsEditor, events: Array<YEvent>) {
console.debug('=== Translating Yjs events to Slate operations ===', {
Log.debug('=== Translating Yjs events to Slate operations ===', {
eventCount: events.length,
eventTypes: events.map((e) => e.path.join('.')),
timestamp: new Date().toISOString(),
});

events.forEach((event, index) => {
console.debug(`Processing event ${index + 1}/${events.length}:`, {
Log.debug(`Processing event ${index + 1}/${events.length}:`, {
path: event.path,
type: event.constructor.name,
});

// Handle block-level changes (document.blocks)
if (isEqual(event.path, ['document', 'blocks'])) {
console.debug('→ Applying block map changes');
Log.debug('→ Applying block map changes');
applyBlocksYEvent(editor, event as BlockMapEvent);
}

// Handle individual block updates (document.blocks[blockId])
if (isEqual(event.path, ['document', 'blocks', event.path[2]])) {
const blockId = event.path[2] as string;

console.debug(`→ Applying block update for blockId: ${blockId}`);
Log.debug(`→ Applying block update for blockId: ${blockId}`);
applyUpdateBlockYEvent(editor, blockId, event as YMapEvent<unknown>);
}

// Handle text content changes (document.meta.text_map[textId])
if (isEqual(event.path, ['document', 'meta', 'text_map', event.path[3]])) {
const textId = event.path[3] as string;

console.debug(`→ Applying text content changes for textId: ${textId}`);
Log.debug(`→ Applying text content changes for textId: ${textId}`);
applyTextYEvent(editor, textId, event as YTextEvent);
}
});

console.debug('=== Yjs events translation completed ===');
Log.debug('=== Yjs events translation completed ===');
}

/**
Expand Down Expand Up @@ -91,7 +91,7 @@ function applyUpdateBlockYEvent(editor: YjsEditor, blockId: string, event: YMapE
const [node, path] = entry;
const oldData = node.data as Record<string, unknown>;

console.debug(`✅ Updating block data for blockId: ${blockId}`, {
Log.debug(`✅ Updating block data for blockId: ${blockId}`, {
path,
oldDataKeys: Object.keys(oldData),
newDataKeys: Object.keys(newData),
Expand Down Expand Up @@ -121,7 +121,7 @@ function applyBlocksYEvent(editor: YjsEditor, event: BlockMapEvent) {
const { changes, keysChanged } = event;
const { keys } = changes;

console.debug('🔄 Processing block map changes:', {
Log.debug('🔄 Processing block map changes:', {
keysChangedCount: keysChanged?.size ?? 0,
keysChanged: Array.from(keysChanged ?? []),
changes: Array.from(keys.entries()).map(([key, value]) => ({
Expand Down
7 changes: 4 additions & 3 deletions src/application/slate-yjs/utils/applyToYjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
} from 'slate';
import * as Y from 'yjs';

import { Log } from '@/utils/log';
import { EditorMarkFormat } from '@/application/slate-yjs/types';
import { getNodeAtPath } from '@/application/slate-yjs/utils/editor';
import { calculateOffsetRelativeToParent } from '@/application/slate-yjs/utils/positions';
Expand Down Expand Up @@ -102,7 +103,7 @@ function insertText(
yText.insert(relativeOffset, text, attributes);
}

console.debug('insertText', attributes, yText.toDelta());
Log.debug('insertText', attributes, yText.toDelta());
}

function applyInsertText(ydoc: Y.Doc, editor: Editor, op: InsertTextOperation, slateContent: Descendant[]) {
Expand Down Expand Up @@ -158,7 +159,7 @@ function applyRemoveText(ydoc: Y.Doc, editor: Editor, op: RemoveTextOperation, s

yText.delete(relativeOffset, text.length);

console.debug('applyRemoveText', op, yText.toDelta());
Log.debug('applyRemoveText', op, yText.toDelta());
}

function applySetNode(ydoc: Y.Doc, editor: Editor, op: SetNodeOperation, slateContent: Descendant[]) {
Expand All @@ -171,7 +172,7 @@ function applySetNode(ydoc: Y.Doc, editor: Editor, op: SetNodeOperation, slateCo
const isData = Object.keys(newProperties).some((prop: string) => prop === 'data');
const sharedRoot = ydoc.getMap(YjsEditorKey.data_section) as YSharedRoot;

console.debug('applySetNode isLeaf', isLeaf, op);
Log.debug('applySetNode isLeaf', isLeaf, op);
if (isLeaf) {
const node = getNodeAtPath(slateContent, path.slice(0, -1)) as Element;
const textId = node.textId;
Expand Down
Loading
Loading