Skip to content

πŸ”₯ πŸ”₯ πŸ”₯ A Free & Self-hostable Airtable Alternative

feat: realtime grid

mertmit68cf682792bc
diff --git a/packages/nc-gui/composables/useApi/interceptors.ts b/packages/nc-gui/composables/useApi/interceptors.ts
index cb6a38d9fc..a8f4ee093f 100644
--- a/packages/nc-gui/composables/useApi/interceptors.ts
+++ b/packages/nc-gui/composables/useApi/interceptors.ts
@@ -8,11 +8,13 @@ export function addAxiosInterceptors(api: Api<any>) {
const router = useRouter()
const route = router.currentRoute
const optimisedQuery = useState('optimisedQuery', () => true)
+ const { $ncSocket } = useNuxtApp()
const axiosInstance = api.instance
axiosInstance.interceptors.request.use((config) => {
config.headers['xc-gui'] = 'true'
+ config.headers['xc-socket-id'] = $ncSocket?.id() || null
if (state.token.value && !config.headers['xc-short-token']) {
config.headers['xc-auth'] = state.token.value
diff --git a/packages/nc-gui/composables/useInfiniteData.ts b/packages/nc-gui/composables/useInfiniteData.ts
index eabce4a0f3..0503d2913b 100644
--- a/packages/nc-gui/composables/useInfiniteData.ts
+++ b/packages/nc-gui/composables/useInfiniteData.ts
@@ -2,6 +2,7 @@ import type { ComputedRef, Ref } from 'vue'
import {
type Api,
type ColumnType,
+ type DataPayload,
type FilterType,
type LinkToAnotherRecordType,
NcApiVersion,
@@ -83,7 +84,7 @@ export function useInfiniteData(args: {
const NOCO = 'noco'
const { meta, viewMeta, callbacks, where, disableSmartsheet, isPublic, groupByColumns = ref(null) } = args
- const { $api } = useNuxtApp()
+ const { $api, $ncSocket } = useNuxtApp()
const { t } = useI18n()
@@ -2025,6 +2026,136 @@ export function useInfiniteData(args: {
}
})
+ watch(
+ meta,
+ (newMeta, oldMeta) => {
+ console.log('useData meta changed')
+ if (newMeta?.fk_workspace_id && newMeta?.base_id && newMeta?.id) {
+ if (oldMeta?.id && oldMeta.id === newMeta.id) return
+
+ $ncSocket.subscribe(`event-data:${newMeta.fk_workspace_id}:${newMeta.base_id}:${newMeta.id}`)
+
+ $ncSocket.onMessage(`event-data:${newMeta.fk_workspace_id}:${newMeta.base_id}:${newMeta.id}`, (data: DataPayload) => {
+ const { id, action, payload, before } = data
+
+ if (action === 'add') {
+ // Add the new row to the local cache (cachedRows)
+ try {
+ const dataCache = getDataCache()
+
+ // find index to insert the new row
+ if (before) {
+ for (const [rowIndex, cachedRow] of dataCache.cachedRows.value.entries()) {
+ const pk = extractPkFromRow(cachedRow.row, meta.value?.columns as ColumnType[])
+ if (pk && `${pk}` === `${before}`) {
+ // Insert before the found row
+ const newRowIndex = rowIndex
+ dataCache.cachedRows.value.set(newRowIndex, {
+ row: payload,
+ oldRow: {},
+ rowMeta: { new: false, rowIndex: newRowIndex, path: [] },
+ })
+
+ const rows = Array.from(dataCache.cachedRows.value.entries())
+ const rowsToShift = rows.filter(([index]) => index > rowIndex)
+ rowsToShift.sort((a, b) => a[0] - b[0])
+
+ for (const [index, row] of rowsToShift) {
+ const newIndex = index + 1
+ row.rowMeta.rowIndex = newIndex
+ dataCache.cachedRows.value.delete(index)
+ dataCache.cachedRows.value.set(newIndex, row)
+ }
+
+ if (rowsToShift.length) {
+ dataCache.chunkStates.value[getChunkIndex(rowsToShift[rowsToShift.length - 1][0])] = undefined
+ }
+
+ dataCache.totalRows.value++
+ dataCache.actualTotalRows.value = Math.max(dataCache.actualTotalRows.value || 0, dataCache.totalRows.value)
+
+ callbacks?.syncVisibleData?.()
+ return
+ }
+ }
+ }
+
+ // If no order is found, append to the end
+ const newRowIndex = dataCache.cachedRows.value.size
+ dataCache.cachedRows.value.set(newRowIndex, {
+ row: payload,
+ oldRow: {},
+ rowMeta: { new: false, rowIndex: newRowIndex, path: [] },
+ })
+ dataCache.totalRows.value++
+ dataCache.actualTotalRows.value = Math.max(dataCache.actualTotalRows.value || 0, dataCache.totalRows.value)
+
+ callbacks?.syncVisibleData?.()
+ } catch (e) {
+ console.error('Failed to add cached row on socket event', e)
+ }
+ } else if (action === 'update') {
+ // Update the row in the local cache (cachedRows)
+ try {
+ const dataCache = getDataCache()
+ let updated = false
+ for (const cachedRow of dataCache.cachedRows.value.values()) {
+ const pk = extractPkFromRow(cachedRow.row, meta.value?.columns as ColumnType[])
+ if (pk && `${pk}` === `${id}`) {
+ Object.assign(cachedRow.row, payload)
+ Object.assign(cachedRow.oldRow, payload)
+ cachedRow.rowMeta.changed = false
+ updated = true
+ break
+ }
+ }
+ if (updated) {
+ callbacks?.syncVisibleData?.()
+ }
+ } catch (e) {
+ console.error('Failed to update cached row on socket event', e)
+ }
+ } else if (action === 'delete') {
+ // Delete the row from the local cache (cachedRows)
+ try {
+ const dataCache = getDataCache()
+ for (const [rowIndex, cachedRow] of dataCache.cachedRows.value.entries()) {
+ const pk = extractPkFromRow(cachedRow.row, meta.value?.columns as ColumnType[])
+ if (pk && `${pk}` === `${id}`) {
+ dataCache.cachedRows.value.delete(rowIndex)
+
+ const rows = Array.from(dataCache.cachedRows.value.entries())
+ const rowsToShift = rows.filter(([index]) => index > rowIndex)
+ rowsToShift.sort((a, b) => a[0] - b[0])
+
+ for (const [index, row] of rowsToShift) {
+ const newIndex = index - 1
+ row.rowMeta.rowIndex = newIndex
+ dataCache.cachedRows.value.delete(index)
+ dataCache.cachedRows.value.set(newIndex, row)
+ }
+
+ if (rowsToShift.length) {
+ dataCache.chunkStates.value[getChunkIndex(rowsToShift[rowsToShift.length - 1][0])] = undefined
+ }
+
+ dataCache.totalRows.value = (dataCache.totalRows.value || 0) - 1
+ dataCache.actualTotalRows.value = Math.max(0, (dataCache.actualTotalRows.value || 0) - 1)
+
+ callbacks?.syncVisibleData?.()
+ }
+ }
+ callbacks?.syncVisibleData?.()
+ } catch (e) {
+ console.error('Failed to delete cached row on socket event', e)
+ }
+ }
+ })
+ }
+ },
+ { immediate: true },
+ )
+
return {
getDataCache,
insertRow,
diff --git a/packages/nc-gui/nuxt-shim.d.ts b/packages/nc-gui/nuxt-shim.d.ts
index 2c726e682e..d04aebb800 100644
--- a/packages/nc-gui/nuxt-shim.d.ts
+++ b/packages/nc-gui/nuxt-shim.d.ts
@@ -33,6 +33,12 @@ declare module '#app' {
): Promise<void>
unsubscribe(topic: { id: string }): Promise<void>
}
+ $ncSocket: {
+ id: () => string | null
+ subscribe: (event: string) => void
+ onMessage: (evt: string, handler: (...args: any[]) => void) => void
+ offMessage: (evt: string) => void
+ }
}
}
diff --git a/packages/nocodb-sdk/src/lib/index.ts b/packages/nocodb-sdk/src/lib/index.ts
index c02f4ecdcf..414bcbb3b9 100644
--- a/packages/nocodb-sdk/src/lib/index.ts
+++ b/packages/nocodb-sdk/src/lib/index.ts
@@ -10,6 +10,7 @@ export * from '~/lib/formulaHelpers';
export * from '~/lib/regex';
export * from '~/lib/payment';
export * from '~/lib/permission';
+export * from '~/lib/realtime';
export {
default as UITypes,
UITypesName,
diff --git a/packages/nocodb-sdk/src/lib/ncTypes.ts b/packages/nocodb-sdk/src/lib/ncTypes.ts
index e639d11379..db86093d21 100644
--- a/packages/nocodb-sdk/src/lib/ncTypes.ts
+++ b/packages/nocodb-sdk/src/lib/ncTypes.ts
@@ -32,6 +32,7 @@ export interface NcRequest extends Partial<Request> {
clientIp?: string;
query?: Record<string, any>;
skipAudit?: boolean;
+ socketId?: string;
}
export type NcRecord<T = any> = Record<string, T>;
diff --git a/packages/nocodb-sdk/src/lib/realtime/index.ts b/packages/nocodb-sdk/src/lib/realtime/index.ts
new file mode 100644
index 0000000000..1318d69e43
--- /dev/null
+++ b/packages/nocodb-sdk/src/lib/realtime/index.ts
@@ -0,0 +1,57 @@
+import { UserType } from "~/lib/Api";
+
+export enum EventType {
+ CONNECTION_WELCOME = 'connection-welcome',
+ CONNECTION_ERROR = 'connection-error',
+ NOTIFICATION = 'notification',
+ DATA_EVENT = 'event-data',
+}
+
+// Base payload interface for all socket events
+export interface BaseSocketPayload {
+ timestamp: number;
+ socketId?: string;
+}
+
+// Connection event payloads
+export interface ConnectionWelcomePayload extends BaseSocketPayload {
+ message: string;
+ serverInfo: {
+ version: string;
+ environment: string;
+ };
+ user?: UserType;
+}
+
+export interface ConnectionErrorPayload extends BaseSocketPayload {
+ error: {
+ code: string;
+ message: string;
+ details?: any;
+ };
+}
+
+export interface DataPayload extends BaseSocketPayload {
+ id: string
+ action: 'add' | 'update' | 'delete'
+ payload: Record<string, any>
+ before?: string
+}
+
+// Union type for all socket event payloads
+export type SocketEventPayload =
+ | ConnectionWelcomePayload
+ | ConnectionErrorPayload
+ | DataPayload;
+
+// Type mapping for event types to their corresponding payloads
+export type SocketEventPayloadMap = {
+ [EventType.CONNECTION_WELCOME]: ConnectionWelcomePayload;
+ [EventType.CONNECTION_ERROR]: ConnectionErrorPayload;
+ [EventType.DATA_EVENT]: DataPayload;
+ [key: string]: BaseSocketPayload;
+};
+
+// Helper type to get payload type for a specific event
+export type PayloadForEvent<T extends EventType> = SocketEventPayloadMap[T];
+
diff --git a/packages/nocodb/src/interface/config.ts b/packages/nocodb/src/interface/config.ts
index 3d1b9fe2b6..713dd3619f 100644
--- a/packages/nocodb/src/interface/config.ts
+++ b/packages/nocodb/src/interface/config.ts
@@ -1,3 +1,5 @@
+import type { Socket } from 'socket.io';
+import type { Handshake } from 'socket.io/dist/socket-types';
import type { Handler } from 'express';
import type * as e from 'express';
import type { Knex } from 'knex';
@@ -324,4 +326,8 @@ export interface AppConfig {
dashboardPath: string;
}
-export { NcContext, NcRequest };
+interface NcSocket extends Socket {
+ handshake: Handshake & NcRequest;
+}
+
+export { NcContext, NcRequest, NcSocket };