π₯ π₯ π₯ A Free & Self-hostable Airtable Alternative
TypeScript airtableairtable-alternativeautomatic-apihacktoberfestlow-codeno-codeno-code-databaseno-code-platformpostgresqlrest-apirestful-apispreadsheetsqliteswagger
feat: calendar realtime
DarkPhoenix27042f4f23a342f7
diff --git a/packages/nc-gui/composables/useCalendarViewStore.ts b/packages/nc-gui/composables/useCalendarViewStore.tsindex 0455a30b6c..3c5b346c30 100644--- a/packages/nc-gui/composables/useCalendarViewStore.ts+++ b/packages/nc-gui/composables/useCalendarViewStore.ts@@ -1,17 +1,15 @@import type { ComputedRef, Ref } from 'vue'-import {+import { EventType, FormulaDataTypes, UITypes, isSystemColumn, isVirtualCol, workerWithTimezone } from 'nocodb-sdk'+import type {type Api,type CalendarRangeType,type CalendarType,type ColumnType,- FormulaDataTypes,+ CommentPayload,+ DataPayload,type PaginatedType,type TableType,- UITypes,type ViewType,- isSystemColumn,- isVirtualCol,- workerWithTimezone,} from 'nocodb-sdk'import dayjs from 'dayjs'@@ -150,7 +148,7 @@ const [useProvideCalendarViewStore, useCalendarViewStore] = useInjectionState(const { base } = storeToRefs(useBase())- const { $api, $e } = useNuxtApp()+ const { $api, $e, $ncSocket } = useNuxtApp()const { t } = useI18n()@@ -1020,6 +1018,235 @@ const [useProvideCalendarViewStore, useCalendarViewStore] = useInjectionState(})})+ const updateActiveDatesForNewRecord = (rowData: Record<string, any>): void => {+ if (!calendarRange.value?.length) return++ for (const range of calendarRange.value) {+ const fromCol = range.fk_from_col+ const toCol = range.fk_to_col++ const fromDate = fromCol ? rowData[fromCol.title!] : null+ const toDate = toCol ? rowData[toCol.title!] : null++ if (fromDate) {+ const date = timezoneDayjs.timezonize(fromDate)+ if (!activeDates.value.some((activeDate) => activeDate.isSame(date, 'day'))) {+ activeDates.value.push(date)+ }+ }++ if (toDate && toDate !== fromDate) {+ const date = timezoneDayjs.timezonize(toDate)+ if (!activeDates.value.some((activeDate) => activeDate.isSame(date, 'day'))) {+ activeDates.value.push(date)+ }+ }+ }++ // Sort active dates+ activeDates.value.sort((a, b) => a.valueOf() - b.valueOf())+ }++ const activeDataChannel = ref<string | null>(null)++ watch(+ meta,+ (newMeta: any, oldMeta: any) => {+ if (newMeta?.fk_workspace_id && newMeta?.base_id && newMeta?.id) {+ if (oldMeta?.id && oldMeta.id === newMeta.id) return++ if (activeDataChannel.value) {+ $ncSocket.offMessage(activeDataChannel.value)+ }++ activeDataChannel.value = `${EventType.DATA_EVENT}:${newMeta.fk_workspace_id}:${newMeta.base_id}:${newMeta.id}`++ $ncSocket.subscribe(activeDataChannel.value)++ $ncSocket.onMessage(activeDataChannel.value, (data: DataPayload) => {+ const { id, action, payload } = data++ if (action === 'add') {+ try {+ // Add to main calendar data if it matches current view's date range+ const newRow = {+ row: payload,+ oldRow: { ...payload },+ rowMeta: {+ new: false,+ ...getEvaluatedRowMetaRowColorInfo(payload),+ },+ }++ // Check if the new row falls within current calendar view date range+ const shouldAddToCalendar = isRowInCurrentDateRange(+ payload,+ calendarRange.value,+ activeCalendarView.value!,+ selectedDate.value,+ selectedDateRange.value,+ selectedMonth.value,+ timezoneDayjs,+ )+ if (shouldAddToCalendar) {+ formattedData.value.push(newRow)+ }++ // Always check if it should be in sidebar based on current sidebar filter+ const shouldAddToSidebar = isRowMatchingSidebarFilter(+ payload,+ sideBarFilterOption.value,+ calendarRange.value,+ selectedDate.value,+ selectedDateRange.value,+ selectedMonth.value,+ selectedTime.value,+ timezoneDayjs,+ )+ if (shouldAddToSidebar) {+ // Avoid duplicates in sidebar+ const existingIndex = formattedSideBarData.value.findIndex(+ (row: Row) => extractPkFromRow(row.row, meta.value?.columns as ColumnType[]) === id,+ )++ if (existingIndex === -1) {+ formattedSideBarData.value.unshift(newRow)+ }+ }++ // Update active dates if the new record contains a date+ updateActiveDatesForNewRecord(payload)+ } catch (e) {+ console.error('Failed to add calendar row on socket event', e)+ }+ } else if (action === 'update') {+ try {+ let updated = false++ let updatedRow = null++ // Update in main calendar data+ formattedData.value = formattedData.value.map((row) => {+ const pk = extractPkFromRow(row.row, meta.value?.columns as ColumnType[])+ if (pk && `${pk}` === `${id}`) {+ Object.assign(row.row, payload)+ Object.assign(row.oldRow, payload)+ Object.assign(row.rowMeta, getEvaluatedRowMetaRowColorInfo(row.row))+ row.rowMeta.changed = false+ updated = true+ updatedRow = row.row+ }+ return row+ })++ // Update in sidebar data+ formattedSideBarData.value = formattedSideBarData.value.map((row) => {+ const pk = extractPkFromRow(row.row, meta.value?.columns as ColumnType[])+ if (pk && `${pk}` === `${id}`) {+ Object.assign(row.row, payload)+ Object.assign(row.oldRow, payload)+ Object.assign(row.rowMeta, getEvaluatedRowMetaRowColorInfo(row.row))+ row.rowMeta.changed = false+ updated = true+ }+ return row+ })++ // Check if updated row should still be visible in current view/filters+ if (updated) {+ // Remove from calendar view if no longer in date range+ const rowInDateRange = isRowInCurrentDateRange(+ updatedRow!,+ calendarRange.value,+ activeCalendarView.value!,+ selectedDate.value,+ selectedDateRange.value,+ selectedMonth.value,+ timezoneDayjs,+ )+ if (!rowInDateRange) {+ formattedData.value = formattedData.value.filter((row) => {+ const pk = extractPkFromRow(row.row, meta.value?.columns as ColumnType[])+ return !(pk && `${pk}` === `${id}`)+ })+ }++ const matchesSidebarFilter = isRowMatchingSidebarFilter(+ updatedRow!,+ sideBarFilterOption.value,+ calendarRange.value,+ selectedDate.value,+ selectedDateRange.value,+ selectedMonth.value,+ selectedTime.value,+ timezoneDayjs,+ )++ const existingInSidebar = formattedSideBarData.value.findIndex((row) => {+ const pk = extractPkFromRow(row.row, meta.value?.columns as ColumnType[])+ return pk && `${pk}` === `${id}`+ })++ if (matchesSidebarFilter) {+ // If it matches the filter but is not in sidebar, add it+ if (existingInSidebar === -1) {+ const newSidebarRow = {+ row: updatedRow,+ oldRow: { ...(updatedRow ?? {}) },+ rowMeta: {+ new: false,+ changed: false,+ ...getEvaluatedRowMetaRowColorInfo(updatedRow),+ },+ }+ formattedSideBarData.value.unshift(newSidebarRow)+ }+ } else {+ // If it doesn't match the filter and exists in sidebar, remove it+ if (existingInSidebar !== -1) {+ formattedSideBarData.value.splice(existingInSidebar, 1)+ }+ }++ // Update active dates+ fetchActiveDates()+ }+ } catch (e) {+ console.error('Failed to update calendar row on socket event', e)+ }+ } else if (action === 'delete') {+ try {+ // Remove from main calendar data+ const calendarIndex = formattedData.value.findIndex((row) => {+ const pk = extractPkFromRow(row.row, meta.value?.columns as ColumnType[])+ return pk && `${pk}` === `${id}`+ })++ if (calendarIndex !== -1) {+ formattedData.value.splice(calendarIndex, 1)+ }++ // Remove from sidebar data+ const sidebarIndex = formattedSideBarData.value.findIndex((row) => {+ const pk = extractPkFromRow(row.row, meta.value?.columns as ColumnType[])+ return pk && `${pk}` === `${id}`+ })++ if (sidebarIndex !== -1) {+ formattedSideBarData.value.splice(sidebarIndex, 1)+ }++ fetchActiveDates()+ } catch (e) {+ console.error('Failed to delete calendar row on socket event', e)+ }+ }+ })+ }+ },+ { immediate: true },+ )+return {fetchActiveDates,formattedSideBarData,diff --git a/packages/nc-gui/utils/calendarUtils.ts b/packages/nc-gui/utils/calendarUtils.tsnew file mode 100644index 0000000000..43ff581642--- /dev/null+++ b/packages/nc-gui/utils/calendarUtils.ts@@ -0,0 +1,180 @@+import type dayjs from 'dayjs'+import type { ColumnType } from 'nocodb-sdk'++const isRowInDateRange = (+ rowData: Record<string, any>,+ rangeStart: dayjs.Dayjs,+ rangeEnd: dayjs.Dayjs,+ calendarRange: Array<{+ fk_from_col: ColumnType+ fk_to_col?: ColumnType | null+ id: string+ is_readonly: boolean+ }>,+ timezoneDayjs: { timezonize: (date: any) => dayjs.Dayjs },+): boolean => {+ if (!calendarRange?.length) return false++ for (const range of calendarRange) {+ const fromCol = range.fk_from_col+ const toCol = range.fk_to_col++ if (!fromCol) continue++ const fromDate = rowData[fromCol.title!]+ const toDate = toCol ? rowData[toCol.title!] : null++ if (!fromDate) continue++ const rowStartDate = timezoneDayjs.timezonize(fromDate)+ const rowEndDate = toDate ? timezoneDayjs.timezonize(toDate) : rowStartDate++ // Check if row's date range intersects with given range+ if (rowStartDate.isBefore(rangeEnd) && rowEndDate.isAfter(rangeStart)) {+ return true+ }+ }++ return false+}++const isRowInCurrentDateRange = (+ rowData: Record<string, any>,+ calendarRange: Array<{+ fk_from_col: ColumnType+ fk_to_col?: ColumnType | null+ id: string+ is_readonly: boolean+ }>,+ activeCalendarView: 'month' | 'year' | 'day' | 'week',+ selectedDate: dayjs.Dayjs,+ selectedDateRange: { start: dayjs.Dayjs; end: dayjs.Dayjs },+ selectedMonth: dayjs.Dayjs,+ timezoneDayjs: { timezonize: (date: any) => dayjs.Dayjs },+): boolean => {+ if (!calendarRange?.length) return false++ for (const range of calendarRange) {+ const fromCol = range.fk_from_col+ const toCol = range.fk_to_col++ if (!fromCol) continue++ const fromDate = rowData[fromCol.title!]+ const toDate = toCol ? rowData[toCol.title!] : null++ if (!fromDate) continue++ // Check if row's date range intersects with current calendar view+ const rowStartDate = timezoneDayjs.timezonize(fromDate)+ const rowEndDate = toDate ? timezoneDayjs.timezonize(toDate) : rowStartDate++ let viewStartDate: dayjs.Dayjs+ let viewEndDate: dayjs.Dayjs++ switch (activeCalendarView) {+ case 'day':+ viewStartDate = selectedDate.startOf('day')+ viewEndDate = selectedDate.endOf('day')+ break+ case 'week':+ viewStartDate = selectedDateRange.start.startOf('week')+ viewEndDate = selectedDateRange.end.endOf('week')+ break+ case 'month': {+ const startOfMonth = timezoneDayjs.timezonize(selectedMonth.startOf('month'))+ viewStartDate = timezoneDayjs.timezonize(startOfMonth.startOf('week'))+ viewEndDate = timezoneDayjs.timezonize(selectedMonth.endOf('month')).endOf('week')+ break+ }+ case 'year':+ viewStartDate = selectedDate.startOf('year')+ viewEndDate = selectedDate.endOf('year')+ break+ default:+ return false+ }++ // Check if date ranges overlap+ if (rowStartDate.isBefore(viewEndDate) && rowEndDate.isAfter(viewStartDate)) {+ return true+ }+ }++ return false+}++const isRowMatchingSidebarFilter = (+ rowData: Record<string, any>,+ sideBarFilterOption: string,+ calendarRange: Array<{+ fk_from_col: ColumnType+ fk_to_col?: ColumnType | null+ id: string+ is_readonly: boolean+ }>,+ selectedDate: dayjs.Dayjs,+ selectedDateRange: { start: dayjs.Dayjs; end: dayjs.Dayjs },+ selectedMonth: dayjs.Dayjs,+ selectedTime: dayjs.Dayjs,+ timezoneDayjs: {+ timezonize: (date: any) => dayjs.Dayjs+ dayjsTz: () => dayjs.Dayjs+ },+): boolean => {+ if (!calendarRange?.length) return false++ // Apply the same logic as sideBarFilter computed property+ switch (sideBarFilterOption) {+ case 'allRecords':+ return true++ case 'withoutDates':+ // Check if row has no dates in any calendar range+ for (const range of calendarRange) {+ const fromCol = range.fk_from_col+ const toCol = range.fk_to_col++ const fromDate = fromCol ? rowData[fromCol.title!] : null+ const toDate = toCol ? rowData[toCol.title!] : null++ if (!fromDate && !toDate) {+ return true+ }+ }+ return false++ case 'day':+ case 'selectedDate':+ return isRowInDateRange(rowData, selectedDate.startOf('day'), selectedDate.endOf('day'), calendarRange, timezoneDayjs)++ case 'week':+ return isRowInDateRange(+ rowData,+ selectedDateRange.start.startOf('week'),+ selectedDateRange.end.endOf('week'),+ calendarRange,+ timezoneDayjs,+ )++ case 'month': {+ const startOfMonth = timezoneDayjs.timezonize(selectedMonth.startOf('month'))+ const firstDayToDisplay = timezoneDayjs.timezonize(startOfMonth.startOf('week'))+ const endOfMonth = timezoneDayjs.timezonize(selectedMonth.endOf('month')).endOf('week')+ return isRowInDateRange(rowData, firstDayToDisplay, endOfMonth, calendarRange, timezoneDayjs)+ }+ case 'year':+ return isRowInDateRange(rowData, selectedDate.startOf('year'), selectedDate.endOf('year'), calendarRange, timezoneDayjs)++ case 'selectedHours': {+ const hourStart = timezoneDayjs.timezonize((selectedTime ?? timezoneDayjs.dayjsTz()).startOf('hour'))+ const hourEnd = timezoneDayjs.timezonize((selectedTime ?? timezoneDayjs.dayjsTz()).endOf('hour'))+ return isRowInDateRange(rowData, hourStart, hourEnd, calendarRange, timezoneDayjs)+ }++ default:+ return false+ }+}++export { isRowInDateRange, isRowInCurrentDateRange, isRowMatchingSidebarFilter }