Skip to content

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

chore: move to ee

DarkPhoenix27043f47759c4cf7
diff --git a/packages/nc-gui/components/shared-view/Outline.vue b/packages/nc-gui/components/shared-view/Outline.vue
index a691152ba5..7c3f5c658a 100644
--- a/packages/nc-gui/components/shared-view/Outline.vue
+++ b/packages/nc-gui/components/shared-view/Outline.vue
@@ -1,48 +1,3 @@
-<script lang="ts" setup>
-const { sharedView, meta, nestedFilters } = useSharedView()
-
-const { signedIn } = useGlobal()
-
-const { loadProject } = useBase()
-
-const { isLocked } = useProvideSmartsheetStore(sharedView, meta, true, ref([]), nestedFilters)
-
-useProvideOutlineViewStore(meta, sharedView)
-
-const reloadEventHook = createEventHook()
-
-provide(ReloadViewDataHookInj, reloadEventHook)
-provide(ReadonlyInj, ref(true))
-provide(MetaInj, meta)
-provide(ActiveViewInj, sharedView)
-provide(IsPublicInj, ref(true))
-provide(IsLockedInj, isLocked)
-
-useProvideViewColumns(sharedView, meta, () => reloadEventHook?.trigger(), true)
-
-useProvideSmartsheetLtarHelpers(meta)
-
-useViewRowColorProvider({ shared: true })
-
-if (signedIn.value) {
- try {
- await loadProject()
- } catch (e: any) {
- message.error(await extractSdkResponseErrorMsg(e))
- }
-}
-</script>
-
<template>
- <div class="nc-container flex flex-col h-full">
- <LazySmartsheetToolbar show-full-screen-toggle />
- <SmartsheetOutline />
- </div>
+ <NcSpanHidden />
</template>
-
-<style scoped>
-.nc-container {
- height: 100%;
- flex: 1 1 100%;
-}
-</style>
diff --git a/packages/nc-gui/components/smartsheet/outline/composables/constants.ts b/packages/nc-gui/components/smartsheet/outline/composables/constants.ts
deleted file mode 100644
index f7471ae0fd..0000000000
--- a/packages/nc-gui/components/smartsheet/outline/composables/constants.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-// Row dimensions
-export const OUTLINE_ROW_HEIGHT = 40
-export const OUTLINE_HEADER_HEIGHT = 32
-
-// Sub-header row (column headers shown when expanding into a child level)
-export const SUB_HEADER_HEIGHT = 28
-
-// Add record row at the bottom of each group
-export const ADD_ROW_HEIGHT = 36
-
-// Indentation per depth level
-export const INDENT_PER_DEPTH = 28
-
-// Chevron column (fixed left area for expand/collapse + indent)
-export const CHEVRON_COL_WIDTH = 40
-
-// Chevron / expand-collapse toggle
-export const CHEVRON_SIZE = 16
-export const CHEVRON_MARGIN_RIGHT = 8
-
-// Gaps between depth transitions (rendered in useCanvasRender)
-export const DEPTH_INCREASE_GAP = 8
-export const DEPTH_DECREASE_GAP = 16
-
-// Cell padding
-export const CELL_PADDING = 10
-
-// Column resize
-export const RESIZE_HANDLE_WIDTH = 8
-export const MIN_COLUMN_WIDTH = 80
-
-// Default column width
-export const DEFAULT_COLUMN_WIDTH = 180
-
-// Bottom padding after the last row
-export const BOTTOM_PADDING = 120
diff --git a/packages/nc-gui/components/smartsheet/outline/composables/types.ts b/packages/nc-gui/components/smartsheet/outline/composables/types.ts
deleted file mode 100644
index 35e659ffac..0000000000
--- a/packages/nc-gui/components/smartsheet/outline/composables/types.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * Hit-test element tracked during rendering.
- */
-export interface OutlineCanvasElement {
- type: 'row' | 'chevron' | 'header' | 'addRow' | 'expandRow' | 'cell'
- rowIndex: number
- x: number
- y: number
- width: number
- height: number
- depth: number
- pk?: string | number
- columnId?: string
- parentPk?: string | number
-}
-
-export interface OutlineActiveCell {
- rowIndex: number
- depth: number
- column: CanvasGridColumn
- row: Record<string, any>
- x: number
- y: number
- width: number
- height: number
-}
diff --git a/packages/nc-gui/components/smartsheet/outline/composables/useCanvasOutline.ts b/packages/nc-gui/components/smartsheet/outline/composables/useCanvasOutline.ts
deleted file mode 100644
index addd3c5460..0000000000
--- a/packages/nc-gui/components/smartsheet/outline/composables/useCanvasOutline.ts
+++ /dev/null
@@ -1,889 +0,0 @@
-import type { ColumnType, FormulaType, GridColumnType, LinkToAnotherRecordType, TableType } from 'nocodb-sdk'
-import { PermissionEntity, PermissionKey, UITypes, isLTAR, isSystemColumn, isVirtualCol } from 'nocodb-sdk'
-import { SpriteLoader } from '../../grid/canvas/loaders/SpriteLoader'
-import { getSingleMultiselectColOptions, getUserColOptions, parseCellWidth } from '../../grid/canvas/utils/cell'
-import type { OutlineActiveCell, OutlineCanvasElement } from './types'
-import {
- ADD_ROW_HEIGHT,
- BOTTOM_PADDING,
- CHEVRON_COL_WIDTH,
- DEPTH_DECREASE_GAP,
- DEPTH_INCREASE_GAP,
- INDENT_PER_DEPTH,
- OUTLINE_HEADER_HEIGHT,
- OUTLINE_ROW_HEIGHT,
- SUB_HEADER_HEIGHT,
-} from './constants'
-import { useCanvasRender } from './useCanvasRender'
-import { useColumnResize } from './useColumnResize'
-import { useOutlineDataFetch } from './useDataFetch'
-import { useOutlineCellRenderer } from './useOutlineCellRenderer'
-import { stringifyFilterOrSortArr } from '~/utils/dataUtils'
-import type { OutlineViewRow } from '~/composables/useOutlineViewStore'
-
-export function useCanvasOutline({
- scrollLeft,
- scrollTop,
- width,
- height,
- mousePosition,
-}: {
- scrollLeft: Ref<number>
- scrollTop: Ref<number>
- width: Ref<number>
- height: Ref<number>
- mousePosition: { x: number; y: number }
-}) {
- const { getColor } = useTheme()
- const { $api } = useNuxtApp()
-
- const { levels, displayLevels, isCollapsed, toggleCollapse, depthToLevelId, collapsedParents, isConfigured, selectedLevelId } =
- useOutlineViewStoreOrThrow()
-
- const { meta, view, nestedFilters, sorts } = useSmartsheetStoreOrThrow()
- const {
- fields: viewFields,
- gridViewCols,
- metaColumnById,
- showSystemFields,
- updateGridViewColumn,
- resizingColOldWith,
- } = useViewColumnsOrThrow()
- const { metas, getMeta } = useMetas()
- const { search, getValidSearchQueryForColumn } = useFieldQuery()
-
- const baseStore = useBase()
- const { sqlUis } = storeToRefs(baseStore)
- const { basesUser } = storeToRefs(useBases())
-
- const { isDataReadOnly, isUIAllowed } = useRoles()
- const { isAllowed } = usePermissions()
- const isPublicView = inject(IsPublicInj, ref(false))
- const isDataEditAllowed = computed(() => isUIAllowed('dataEdit') && !isPublicView.value)
- const isAddingEmptyRowAllowed = computed(() => isDataEditAllowed.value && !meta.value?.synced)
-
- const spriteLoader = new SpriteLoader(() => triggerRefreshCanvas())
- const canvasCursorRef = ref<CursorType>('')
- const setCursor: SetCursorType = (cursor) => {
- canvasCursorRef.value = cursor
- }
- const { isRowColouringEnabled, getEvaluatedRowMetaRowColorInfo } = useViewRowColorRender()
-
- const headerRowHeight = computed(() => OUTLINE_HEADER_HEIGHT)
-
- const rowHeight = computed(() => {
- const outlineView = view.value?.view as any
- const rh = outlineView?.row_height
- if (rh !== undefined) {
- const enumVal = [1, 2, 4, 6][rh] ?? 1
- return rowHeightInPx[`${enumVal}`] ?? OUTLINE_ROW_HEIGHT
- }
- return OUTLINE_ROW_HEIGHT
- })
-
- const elementMap = ref<OutlineCanvasElement[]>([])
- const hoverRow = ref<{ rowIndex: number }>({ rowIndex: -1 })
- const activeCell = ref<OutlineActiveCell | null>(null)
- const stickyHeaderDepth = ref(0)
-
- const viewId = computed(() => view.value?.id)
-
- const cachedRows = ref(new Map<number, OutlineViewRow>())
- const chunkStates = ref<Array<'loading' | 'loaded' | undefined>>([])
- const totalRows = ref(0)
- const levelCounts = ref<Record<string, number>>({})
-
- function getMetaForDepth(depth: number): TableType | undefined {
- const level = displayLevels.value[depth]
- if (!level?.fk_model_id) return undefined
- const baseId = meta.value?.base_id
- const metaKey = `${baseId}:${level.fk_model_id}`
- return metas.value?.[metaKey] as TableType | undefined
- }
-
- async function updateOrSaveRow(row: Row, property?: string): Promise<any> {
- if (!property) return
-
- const newVal = row.row[property]
- const oldVal = row.oldRow?.[property]
- if (newVal === oldVal) return
-
- const depth = row.row.__nc_depth ?? 0
- const depthMeta = getMetaForDepth(depth)
- if (!depthMeta) return
-
- const rowId = extractPkFromRow(row.row, depthMeta.columns as ColumnType[])
- if (!rowId) return
-
- try {
- const updatedRowData = await $api.dbTableRow.update(
- NOCO,
- depthMeta.base_id as string,
- depthMeta.id as string,
- encodeURIComponent(rowId),
- { [property]: newVal ?? null },
- )
-
- for (const [idx, cached] of cachedRows.value) {
- if (cached.__nc_pk === row.row.__nc_pk) {
- Object.assign(cached, updatedRowData)
- break
- }
- }
- triggerRefreshCanvas()
- } catch (e: any) {
- message.error(e.message || 'Failed to save')
- }
- }
-
- const { renderCell, handleCellClick, handleCellHover, imageLoader, actionManager } = useOutlineCellRenderer({
- spriteLoader,
- triggerRefreshCanvas: () => triggerRefreshCanvas(),
- setCursor,
- meta: meta as Ref<TableType | undefined>,
- cachedRows: cachedRows as Ref<Map<number, Row>>,
- totalRows,
- chunkStates,
- updateOrSaveRow,
- })
-
- // Collapsed state serialized for API calls
- const collapsedJson = computed(() => {
- const cp = collapsedParents.value
- const hasAny = Object.values(cp).some((arr) => arr.length > 0)
- return hasAny ? JSON.stringify(cp) : ''
- })
-
- const sharedViewPassword = inject(SharedViewPasswordInj, ref(''))
-
- function buildDraftFilterSortParams() {
- // For outline view, filters and sorts must be level-scoped (fk_level_id).
- // If a draft entry lacks fk_level_id, fall back to the currently selected level.
- const fallbackLevelId = selectedLevelId.value
-
- // Build search filter from the toolbar search bar.
- // SearchData.vue uses the selected level's columns for the field picker, so we look up
- // the column from that level's table meta and scope the filter to selectedLevelId.
- const searchFilters: any[] = []
- const searchQuery = search.value.query?.trim()
- if (searchQuery && search.value.field && fallbackLevelId) {
- const selectedLevel = levels.value.find((l) => l.id === fallbackLevelId)
- if (selectedLevel?.fk_model_id) {
- const baseId = (meta.value as any)?.base_id
- const levelMeta = metas.value?.[`${baseId}:${selectedLevel.fk_model_id}`] as any
- const col = levelMeta?.columns?.find((c: ColumnType) => c.id === search.value.field)
- if (col) {
- const result = getValidSearchQueryForColumn(col, searchQuery, levelMeta, { getWhereQueryAs: 'object' })
- if (result && typeof result === 'object' && 'fk_column_id' in result) {
- searchFilters.push({ ...result, fk_level_id: fallbackLevelId })
- }
- }
- }
- }
-
- const filterArrJson = isUIAllowed('filterSync')
- ? searchFilters.length
- ? stringifyFilterOrSortArr(searchFilters)
- : undefined
- : stringifyFilterOrSortArr([
- ...(nestedFilters.value ?? [])
- .filter((f) => !f.id)
- .map((f) => (f.fk_level_id ? f : { ...f, fk_level_id: fallbackLevelId })),
- ...searchFilters,
- ])
-
- const sortArrJson = isUIAllowed('sortSync')
- ? undefined
- : stringifyFilterOrSortArr(
- (sorts.value ?? []).filter((s) => !s.id).map((s) => (s.fk_level_id ? s : { ...s, fk_level_id: fallbackLevelId })),
- )
-
- return { filterArrJson, sortArrJson }
- }
-
- async function loadPage(params: { offset: number; limit: number; collapsed: string }): Promise<OutlineViewRow[]> {
- let response: any
-
- const { filterArrJson, sortArrJson } = buildDraftFilterSortParams()
-
- if (isPublicView.value) {
- const sharedViewUuid = view.value?.uuid
- if (!sharedViewUuid) return []
-
- const query: Record<string, any> = {
- limit: params.limit,
- offset: params.offset,
- }
- if (params.collapsed) query.collapsed = params.collapsed
- if (filterArrJson) query.filterArrJson = filterArrJson
- if (sortArrJson) query.sortArrJson = sortArrJson
-
- response = await $api.public.dataList(sharedViewUuid, query, {
- headers: {
- 'xc-password': sharedViewPassword.value,
- },
- })
- } else {
- const workspaceId = (meta.value as any)?.fk_workspace_id
- const baseId = meta.value?.base_id
- if (!workspaceId || !baseId || !viewId.value) return []
-
- const query: Record<string, any> = {
- operation: 'outlineViewDataList',
- viewId: viewId.value,
- limit: params.limit,
- offset: params.offset,
- }
- if (params.collapsed) query.collapsed = params.collapsed
- if (filterArrJson) query.filterArrJson = filterArrJson
- if (sortArrJson) query.sortArrJson = sortArrJson
-
- response = await $api.internal.getOperation(workspaceId, baseId, query)
- }
-
- const rows = response.list || response?.data?.list || []
-
- if (isRowColouringEnabled.value) {
- for (const row of rows) {
- const colorInfo = getEvaluatedRowMetaRowColorInfo(row)
- row.__nc_color = colorInfo
- }
- }
-
- return rows
- }
-
- async function loadCount(params: { collapsed: string }): Promise<{ totalRows: number; counts: Record<string, number> }> {
- const { filterArrJson, sortArrJson } = buildDraftFilterSortParams()
-
- if (isPublicView.value) {
- const sharedViewUuid = view.value?.uuid
- if (!sharedViewUuid) return { totalRows: 0, counts: {} }
-
- const query: Record<string, any> = {}
- if (params.collapsed) query.collapsed = params.collapsed
- if (filterArrJson) query.filterArrJson = filterArrJson
- if (sortArrJson) query.sortArrJson = sortArrJson
-
- const response = await $api.public.dbViewRowCount(sharedViewUuid, query, {
- headers: {
- 'xc-password': sharedViewPassword.value,
- },
- })
- return {
- totalRows: +(response.totalRows || 0),
- counts: (response as any).counts || {},
- }
- }
-
- const workspaceId = (meta.value as any)?.fk_workspace_id
- const baseId = meta.value?.base_id
- if (!workspaceId || !baseId || !viewId.value) return { totalRows: 0, counts: {} }
-
- const query: Record<string, any> = {
- operation: 'outlineViewDataCount',
- viewId: viewId.value,
- }
- if (params.collapsed) query.collapsed = params.collapsed
- if (filterArrJson) query.filterArrJson = filterArrJson
- if (sortArrJson) query.sortArrJson = sortArrJson
-
- const response = await $api.internal.getOperation(workspaceId, baseId, query)
- return {
- totalRows: +(response.totalRows || 0),
- counts: response.counts || {},
- }
- }
-
- const { fetchCount, updateVisibleRows, resetAndReload } = useOutlineDataFetch({
- viewId,
- cachedRows,
- chunkStates,
- totalRows,
- levelCounts,
- collapsedJson,
- loadPage,
- loadCount,
- triggerRefreshCanvas: () => triggerRefreshCanvas(),
- })
-
- const columnsPerLevel = computed<Record<string, CanvasGridColumn[]>>(() => {
- const result: Record<string, CanvasGridColumn[]> = {}
-
- for (const level of levels.value) {
- if (!level.id || !level.fk_model_id) continue
-
- const baseId = meta.value?.base_id
- const levelMetaKey = `${baseId}:${level.fk_model_id}`
- const levelMeta = metas.value?.[levelMetaKey] as TableType | undefined
-
- const levelFields = (viewFields.value || [])
- .filter((f: any) => {
- if (f.fk_level_id !== level.id || !f.show) return false
- const col = metaColumnById.value?.[f.fk_column_id!]
- if (!col) return false
- // Hide system columns unless showSystemFields is on (keep PV)
- if (!showSystemFields.value && isSystemColumn(col) && !col.pv) return false
- return true
- })
- .sort((a: any, b: any) => (a.order ?? 0) - (b.order ?? 0))
-
- const cols: CanvasGridColumn[] = []
-
- const levelBaseUsers = baseId ? basesUser.value.get(baseId) || [] : []
-
- for (const f of levelFields) {
- const col = metaColumnById.value[f.fk_column_id!] as ColumnType
- if (!col) continue
-
- const viewCol = gridViewCols.value[f.fk_column_id] as GridColumnType | undefined
-
- let relatedColObj: ColumnType | undefined
- let relatedTableMeta: any
-
- if ([UITypes.Lookup, UITypes.Rollup].includes(col.uidt as UITypes)) {
- const lookupMetaKey = `${baseId}:${col.fk_model_id!}`
- relatedColObj = metas.value?.[lookupMetaKey]?.columns?.find(
- (c: ColumnType) => c.id === (col as any)?.colOptions?.fk_relation_column_id,
- ) as ColumnType
-
- if (relatedColObj && (relatedColObj as any).colOptions?.fk_related_model_id) {
- const relatedBaseId = ((relatedColObj as any).colOptions as any)?.fk_related_base_id || baseId
- const relatedMetaKey = `${relatedBaseId}:${(relatedColObj as any).colOptions.fk_related_model_id}`
- relatedTableMeta = metas.value?.[relatedMetaKey]
- }
- } else if (isLTAR(col.uidt as UITypes, (col as any).colOptions)) {
- const colOptions = (col as any).colOptions as LinkToAnotherRecordType
- if (colOptions?.fk_related_model_id) {
- const relatedBaseId = (colOptions as any)?.fk_related_base_id || baseId
- const ltarMetaKey = `${relatedBaseId}:${colOptions.fk_related_model_id}`
- relatedTableMeta = metas.value?.[ltarMetaKey]
- }
- }
-
- col.extra = {}
-
- if ([UITypes.SingleSelect, UITypes.MultiSelect].includes(col.uidt as UITypes)) {
- col.extra = getSingleMultiselectColOptions(col)
- } else if ([UITypes.User, UITypes.CreatedBy, UITypes.LastModifiedBy].includes(col.uidt as UITypes)) {
- col.extra = getUserColOptions(col, levelBaseUsers)
- }
-
- if ([UITypes.LastModifiedTime, UITypes.CreatedTime, UITypes.DateTime].includes(col.uidt as UITypes)) {
- const colMeta = parseProp(col.meta)
- col.extra.timezone = isEeUI ? getTimeZoneFromName(colMeta?.timezone) : undefined
- col.extra.isDisplayTimezone = isEeUI ? colMeta?.isDisplayTimezone : undefined
- }
-
- if ([UITypes.Formula].includes(col.uidt as UITypes)) {
- const referencedColumn = (col.colOptions as FormulaType)?.parsed_tree?.referencedColumn
- const displayType = (col.meta as any)?.display_type ?? referencedColumn?.uidt
- const levelMeta = metas.value?.[`${baseId}:${col.fk_model_id!}`]
- const displayColumnConfig = (col.meta as any)?.display_type
- ? ((col.meta as any)?.display_column_meta as any)
- : referencedColumn
- ? levelMeta?.columns?.find((c: ColumnType) => c.id === referencedColumn.id)
- : undefined
-
- if ([UITypes.DateTime].includes(displayType) && displayColumnConfig?.meta) {
- const displayColumnConfigMeta = displayColumnConfig.meta
- displayColumnConfig.extra = {
- timezone:
- isEeUI && displayColumnConfigMeta.isDisplayTimezone
- ? getTimeZoneFromName(displayColumnConfigMeta.timezone)
- : undefined,
- isDisplayTimezone: isEeUI ? displayColumnConfigMeta.isDisplayTimezone : undefined,
- }
- }
- col.extra.display_type = displayType
- col.extra.display_column_meta = displayColumnConfig
- }
-
- const sqlUi = sqlUis.value[col.source_id!] ?? Object.values(sqlUis.value)[0]
-
- const isCellEditable =
- showReadonlyColumnTooltip(col) ||
- !showEditRestrictedColumnTooltip(col) ||
- isAllowed(PermissionEntity.FIELD, col.id, PermissionKey.RECORD_FIELD_EDIT)
-
- const isSyncedCol = !!(levelMeta?.synced && col.readonly)
-
- const isReadonly =
- col.readonly || isDataReadOnly.value || !isDataEditAllowed.value || isPublicView.value || !isCellEditable || isSyncedCol
-
- cols.push({
- id: col.id!,
- grid_column_id: viewCol?.id ?? col.id!,
- title: col.title!,
- uidt: col.uidt as any,
- width: viewCol?.width ?? '180px',
- fixed: false,
- pv: !!col.pv,
- virtual: isVirtualCol(col),
- readonly: isReadonly,
- isCellEditable,
- isSyncedColumn: isSyncedCol,
- columnObj: col as ColumnType & { extra?: any },
- relatedColObj,
- relatedTableMeta,
- aggregation: '',
- agg_fn: '',
- agg_prefix: '',
- abstractType: sqlUi?.getAbstractType(col) ?? null,
- })
- }
-
- result[level.id] = cols
- }
-
- return result
- })
-
- watch(
- columnsPerLevel,
- async (levels) => {
- const baseId = meta.value?.base_id
- if (!baseId) return
-
- for (const cols of Object.values(levels)) {
- for (const col of cols) {
- const columnObj = col.columnObj
- if (isLTAR(columnObj.uidt as UITypes, (columnObj as any).colOptions)) {
- const colOptions = (columnObj as any).colOptions as LinkToAnotherRecordType
- if (colOptions?.fk_related_model_id) {
- const relatedBaseId = (colOptions as any)?.fk_related_base_id || baseId
- const metaKey = `${relatedBaseId}:${colOptions.fk_related_model_id}`
- if (!metas.value?.[metaKey]) {
- await getMeta(colOptions.fk_related_model_id, false, false, relatedBaseId)
- }
- }
- } else if ([UITypes.Lookup, UITypes.Rollup].includes(columnObj.uidt as UITypes)) {
- const lookupMetaKey = `${baseId}:${columnObj.fk_model_id!}`
- const relatedColObj = metas.value?.[lookupMetaKey]?.columns?.find(
- (c: ColumnType) => c.id === (columnObj as any)?.colOptions?.fk_relation_column_id,
- )
- if (relatedColObj && (relatedColObj as any).colOptions?.fk_related_model_id) {
- const relatedBaseId = ((relatedColObj as any).colOptions as any)?.fk_related_base_id || baseId
- const metaKey = `${relatedBaseId}:${(relatedColObj as any).colOptions.fk_related_model_id}`
- if (!metas.value?.[metaKey]) {
- await getMeta((relatedColObj as any).colOptions.fk_related_model_id, false, false, relatedBaseId)
- }
- }
- }
- }
- }
- },
- { immediate: true },
- )
-
- const rootColumns = computed<CanvasGridColumn[]>(() => {
- const rootLevel = displayLevels.value[0]
- if (!rootLevel?.id) return []
- return columnsPerLevel.value[rootLevel.id] ?? []
- })
-
- function getColumnsForDepth(depth: number): CanvasGridColumn[] {
- const levelId = depthToLevelId.value[depth]
- if (!levelId) return []
- return columnsPerLevel.value[levelId] ?? []
- }
-
- const levelOrder = computed(() => displayLevels.value.map((l) => l.fk_model_id!))
-
- const scrollMetrics = computed(() => {
- const N = displayLevels.value.length
- if (N === 0 || totalRows.value === 0) {
- return { subHeaderCount: 0, rowCount: 0, addRowCount: 0, groups: [] as number[], scrollableHeight: 0 }
- }
-
- const cts = levelCounts.value
- const order = levelOrder.value
-
- const groups = new Array(N).fill(0)
- groups[0] = 1
- for (let d = 1; d < N; d++) {
- groups[d] = cts[order[d - 1]] || 0
- }
-
- const rowCount = totalRows.value
-
- // The render loop draws sub-headers in TWO places:
- // 1. Depth increase (non-first): entering a child group β€” one per non-root group
- // 2. Depth decrease: re-rendering column headers after closing children
- //
- // Add-rows are drawn for each closed level on depth decrease + trailing.
- // The root level (d=0) never gets an add-row (trailing loop uses d >= 1).
- //
- // Count of each transition type:
- const depthIncreaseCount = groups.slice(1).reduce((s: number, g: number) => s + g, 0)
- const depthDecreaseCount = Math.max(0, groups[N - 1] - 1)
-
- // Sub-headers: one per depth-increase + one per depth-decrease
- const subHeaderCount = depthIncreaseCount + depthDecreaseCount
-
- // Add-rows: exclude root group (root never gets an add-row)
- const addRowCount = isAddingEmptyRowAllowed.value ? groups.reduce((s: number, g: number) => s + g, 0) - 1 : 0
-
- // Gaps before sub-headers at depth boundaries
- const transitionGapHeight = depthIncreaseCount * DEPTH_INCREASE_GAP + depthDecreaseCount * DEPTH_DECREASE_GAP
-
- const scrollableHeight =
- subHeaderCount * SUB_HEADER_HEIGHT +
- rowCount * rowHeight.value +
- addRowCount * ADD_ROW_HEIGHT +
- transitionGapHeight +
- BOTTOM_PADDING
-
- return { subHeaderCount, rowCount, addRowCount, groups, scrollableHeight }
- })
-
- const totalHeight = computed(() => {
- if (totalRows.value === 0) return headerRowHeight.value
- return headerRowHeight.value + scrollMetrics.value.scrollableHeight
- })
-
- const slotHeight = computed(() => {
- if (totalRows.value === 0) return rowHeight.value
- return scrollMetrics.value.scrollableHeight / totalRows.value
- })
-
- const totalWidth = computed(() => {
- let maxWidth = width.value
- const maxDepth = displayLevels.value.length
- for (let d = 0; d < maxDepth; d++) {
- const cols = getColumnsForDepth(d)
- const indent = CHEVRON_COL_WIDTH + d * INDENT_PER_DEPTH
- const colsWidth = indent + cols.reduce((sum, c) => sum + parseCellWidth(c.width), 0)
- maxWidth = Math.max(maxWidth, colsWidth)
- }
- return maxWidth
- })
-
- const rowSlice = computed(() => {
- if (totalRows.value === 0) return { start: 0, end: 0 }
-
- const sh = slotHeight.value
- const hh = headerRowHeight.value
- const buffer = 3
-
- const adjustedScroll = Math.max(0, scrollTop.value - hh)
- const start = Math.max(0, Math.floor(adjustedScroll / sh) - buffer)
- const end = Math.min(totalRows.value, Math.ceil((adjustedScroll + height.value) / sh) + buffer)
-
- return { start, end }
- })
-
- const { canvasRef, renderCanvas } = useCanvasRender({
- width,
- height,
- scrollLeft,
- scrollTop,
- headerRowHeight,
- rowHeight,
- cachedRows,
- rowSlice,
- slotHeight,
- totalRows,
- hoverRow,
- mousePosition,
- elementMap,
- isCollapsed,
- displayLevels,
- getColumnsForDepth,
- getColor,
- meta,
- renderCell,
- stickyHeaderDepth,
- isAddingEmptyRowAllowed,
- })
-
- let rafId: number | null = null
- function triggerRefreshCanvas() {
- if (rafId) cancelAnimationFrame(rafId)
- rafId = requestAnimationFrame(() => {
- renderCanvas()
- rafId = null
- })
- }
-
- watch([scrollTop, scrollLeft, width, height, rowHeight, () => totalRows.value, columnsPerLevel], () => triggerRefreshCanvas())
-
- watch(rowSlice, (slice) => updateVisibleRows(slice))
- watch(collapsedJson, () => resetAndReload())
-
- function findElementAt(x: number, y: number, type?: OutlineCanvasElement['type']): OutlineCanvasElement | null {
- for (let i = elementMap.value.length - 1; i >= 0; i--) {
- const el = elementMap.value[i]
- if (type && el.type !== type) continue
- if (x >= el.x && x <= el.x + el.width && y >= el.y && y <= el.y + el.height) {
- return el
- }
- }
- return null
- }
-
- function resolveHeaderAt(x: number, y: number): { columns: CanvasGridColumn[]; startX: number } | null {
- // Sticky header: shows columns for the depth of the first visible row
- if (y >= 0 && y < headerRowHeight.value) {
- const d = stickyHeaderDepth.value
- const cols = getColumnsForDepth(d)
- const indent = CHEVRON_COL_WIDTH + d * INDENT_PER_DEPTH
- return {
- columns: cols,
- startX: indent - scrollLeft.value,
- }
- }
-
- // Sub-headers: check elementMap for 'header' type
- const headerEl = findElementAt(x, y, 'header')
- if (headerEl) {
- const cols = getColumnsForDepth(headerEl.depth)
- const indent = CHEVRON_COL_WIDTH + headerEl.depth * INDENT_PER_DEPTH
- return {
- columns: cols,
- startX: indent - scrollLeft.value,
- }
- }
-
- return null
- }
-
- const {
- isResizing,
- startResize,
- updateCursor: getResizeCursor,
- } = useColumnResize(
- canvasRef,
- triggerRefreshCanvas,
- resolveHeaderAt,
- // onResize: live local update during drag
- (columnId: string, newWidth: number) => {
- const widthStr = `${Math.round(newWidth)}px`
- if (gridViewCols.value[columnId]) {
- gridViewCols.value[columnId].width = widthStr
- }
- triggerRefreshCanvas()
- },
- // onResizeEnd: persist to server
- (columnId: string, newWidth: number) => {
- const widthStr = `${Math.round(newWidth)}px`
- if (gridViewCols.value[columnId]) {
- resizingColOldWith.value = gridViewCols.value[columnId].width || '180px'
- gridViewCols.value[columnId].width = widthStr
- }
- updateGridViewColumn(columnId, { width: widthStr })
- },
- )
-
- function handleCanvasMouseDown(e: MouseEvent) {
- if (startResize(e)) return
- }
-
- const expandRowHook = createEventHook<{ row: OutlineViewRow; depth: number }>()
- const addRowHook = createEventHook<{ depth: number; parentPk?: string | number }>()
-
- async function handleCanvasClick(e: MouseEvent) {
- if (isResizing.value) return
-
- const rect = canvasRef.value?.getBoundingClientRect()
- if (!rect) return
-
- const x = e.clientX - rect.left
- const y = e.clientY - rect.top
-
- const expandEl = findElementAt(x, y, 'expandRow')
- if (expandEl) {
- const row = cachedRows.value.get(expandEl.rowIndex)
- if (row) {
- expandRowHook.trigger({ row, depth: expandEl.depth })
- }
- return
- }
-
- const cellEl = findElementAt(x, y, 'cell')
- if (cellEl && cellEl.columnId) {
- const row = cachedRows.value.get(cellEl.rowIndex)
- if (row) {
- const cols = getColumnsForDepth(cellEl.depth)
- const col = cols.find((c) => c.id === cellEl.columnId)
- if (col) {
- const rowObj: Row = { row: { ...row }, oldRow: { ...row }, rowMeta: { rowIndex: cellEl.rowIndex } }
- const cellPosition = { x: cellEl.x, y: cellEl.y, width: cellEl.width, height: cellEl.height }
- const handled = await handleCellClick({
- event: e,
- row: rowObj,
- column: col,
- value: row[col.title],
- mousePosition: { x, y },
- pk: row.__nc_pk,
- selected: false,
- imageLoader,
- path: [],
- cellPosition,
- })
-
- if (handled) {
- const cached = cachedRows.value.get(cellEl.rowIndex)
- if (cached) {
- Object.assign(cached, rowObj.row)
- }
- triggerRefreshCanvas()
- return
- }
-
- const canvasOnlyTypes = [UITypes.Checkbox, UITypes.Rating, UITypes.Button]
- if (canvasOnlyTypes.includes(col.columnObj.uidt as UITypes)) {
- return
- }
-
- activeCell.value = {
- rowIndex: cellEl.rowIndex,
- depth: cellEl.depth,
- column: col,
- row: { ...row },
- x: cellEl.x,
- y: cellEl.y,
- width: cellEl.width,
- height: cellEl.height,
- }
- return
- }
- }
- }
-
- const addRowEl = findElementAt(x, y, 'addRow')
- if (addRowEl) {
- addRowHook.trigger({ depth: addRowEl.depth, parentPk: addRowEl.parentPk })
- return
- }
-
- activeCell.value = null
-
- const chevron = findElementAt(x, y, 'chevron')
- if (chevron && chevron.pk !== undefined) {
- toggleCollapse(chevron.depth, String(chevron.pk))
- }
- }
-
- function handleCanvasMouseMove(e: MouseEvent) {
- const rect = canvasRef.value?.getBoundingClientRect()
- if (!rect) return
-
- const x = e.clientX - rect.left
- const y = e.clientY - rect.top
-
- mousePosition.x = x
- mousePosition.y = y
-
- canvasCursorRef.value = ''
-
- if (canvasRef.value) {
- const resizeCursor = getResizeCursor(x, y)
- if (resizeCursor) {
- canvasRef.value.style.cursor = resizeCursor
- } else {
- const expandEl = findElementAt(x, y, 'expandRow')
- const chevronEl = findElementAt(x, y, 'chevron')
- const addRowEl = findElementAt(x, y, 'addRow')
-
- if (expandEl || chevronEl || addRowEl) {
- canvasRef.value.style.cursor = 'pointer'
- } else {
- const cellEl = findElementAt(x, y, 'cell')
- if (cellEl?.columnId) {
- const row = cachedRows.value.get(cellEl.rowIndex)
- if (row) {
- const cols = getColumnsForDepth(cellEl.depth)
- const col = cols.find((c) => c.id === cellEl.columnId)
- if (col) {
- handleCellHover({
- event: e,
- row: { row: { ...row }, oldRow: { ...row }, rowMeta: {} },
- column: col,
- value: row[col.title],
- mousePosition: { x, y },
- pk: row.__nc_pk,
- selected: false,
- imageLoader,
- })
- }
- }
- }
- canvasRef.value.style.cursor = canvasCursorRef.value || ''
- }
- }
- }
-
- const rowEl = findElementAt(x, y, 'row')
- const newHoverIndex = rowEl?.rowIndex ?? -1
-
- const inHeader = y < headerRowHeight.value || findElementAt(x, y, 'header')
- if (inHeader) {
- triggerRefreshCanvas()
- } else if (newHoverIndex >= 0) {
- if (hoverRow.value.rowIndex !== newHoverIndex) {
- hoverRow.value = { rowIndex: newHoverIndex }
- }
- triggerRefreshCanvas()
- } else if (hoverRow.value.rowIndex !== newHoverIndex) {
- hoverRow.value = { rowIndex: newHoverIndex }
- triggerRefreshCanvas()
- }
- }
-
- function handleCanvasMouseLeave() {
- mousePosition.x = -1
- mousePosition.y = -1
- if (hoverRow.value.rowIndex !== -1) {
- hoverRow.value = { rowIndex: -1 }
- }
- triggerRefreshCanvas()
- }
-
- async function loadInitialData() {
- if (!isConfigured.value || !viewId.value) return
-
- await fetchCount()
- if (totalRows.value > 0) {
- updateVisibleRows({ start: 0, end: Math.ceil(height.value / rowHeight.value) + 5 })
- }
- nextTick(() => triggerRefreshCanvas())
- }
-
- onMounted(async () => {
- // Wait for levels + viewId to be available (view meta may load async)
- await waitForCondition(() => isConfigured.value && !!viewId.value, 100)
- // Wait a tick for the v-else template branch to render the canvas element
- await nextTick()
- await loadInitialData()
- })
-
- watch(
- () => levels.value.length,
- () => {
- if (isConfigured.value && viewId.value) {
- resetAndReload()
- }
- },
- )
-
- onBeforeUnmount(() => {
- if (rafId) cancelAnimationFrame(rafId)
- })
-
- return {
- canvasRef,
- triggerRefreshCanvas,
- resetAndReload,
- totalHeight,
- totalWidth,
- handleCanvasMouseDown,
- handleCanvasClick,
- handleCanvasMouseMove,
- handleCanvasMouseLeave,
- onExpandRow: expandRowHook.on,
- onAddRow: addRowHook.on,
- activeCell,
- cachedRows,
- }
-}
diff --git a/packages/nc-gui/components/smartsheet/outline/composables/useCanvasRender.ts b/packages/nc-gui/components/smartsheet/outline/composables/useCanvasRender.ts
deleted file mode 100644
index 9cc4bdf24d..0000000000
--- a/packages/nc-gui/components/smartsheet/outline/composables/useCanvasRender.ts
+++ /dev/null
@@ -1,695 +0,0 @@
-import type { ColumnType, OutlineViewLevelType, TableType } from 'nocodb-sdk'
-import { parseCellWidth } from '../../grid/canvas/utils/cell'
-import { getSafe2DContext } from '../../grid/canvas/utils/safeCanvas'
-import type { OutlineCanvasElement } from './types'
-import {
- ADD_ROW_HEIGHT,
- CELL_PADDING,
- CHEVRON_COL_WIDTH,
- CHEVRON_SIZE,
- DEPTH_DECREASE_GAP,
- DEPTH_INCREASE_GAP,
- INDENT_PER_DEPTH,
- SUB_HEADER_HEIGHT,
-} from './constants'
-import type { OutlineViewRow } from '~/composables/useOutlineViewStore'
-
-type GetColorFn = (cssVar: string, darkCssVar?: string, opacity?: number) => string
-
-type RenderCellFn = (
- ctx: CanvasRenderingContext2D,
- column: ColumnType,
- options: {
- value: any
- row?: Record<string, any>
- x: number
- y: number
- width: number
- height: number
- pv?: boolean
- padding?: number
- pk?: any
- mousePosition?: { x: number; y: number }
- meta?: any
- isRowHovered?: boolean
- relatedColObj?: any
- relatedTableMeta?: any
- readonly?: boolean
- },
-) => void
-
-export function useCanvasRender({
- width,
- height,
- scrollLeft,
- scrollTop,
- headerRowHeight,
- rowHeight,
- cachedRows,
- rowSlice,
- slotHeight,
- totalRows,
- hoverRow,
- mousePosition,
- elementMap,
- isCollapsed,
- displayLevels,
- getColumnsForDepth,
- getColor,
- meta,
- renderCell,
- stickyHeaderDepth,
- isAddingEmptyRowAllowed,
-}: {
- width: Ref<number>
- height: Ref<number>
- scrollLeft: Ref<number>
- scrollTop: Ref<number>
- headerRowHeight: ComputedRef<number>
- rowHeight: ComputedRef<number>
- cachedRows: Ref<Map<number, OutlineViewRow>>
- rowSlice: ComputedRef<{ start: number; end: number }>
- slotHeight: ComputedRef<number>
- totalRows: Ref<number>
- hoverRow: Ref<{ rowIndex: number }>
- mousePosition: { x: number; y: number }
- elementMap: Ref<OutlineCanvasElement[]>
- isCollapsed: (depth: number, pk: string) => boolean
- displayLevels: ComputedRef<OutlineViewLevelType[]>
- getColumnsForDepth: (depth: number) => CanvasGridColumn[]
- getColor: GetColorFn
- meta: Ref<TableType | undefined>
- renderCell: RenderCellFn
- stickyHeaderDepth: Ref<number>
- isAddingEmptyRowAllowed: ComputedRef<boolean>
-}) {
- const canvasRef = ref<HTMLCanvasElement>()
-
- function getColors() {
- return {
- bg: getColor(themeV4Colors.base.white),
- rowBg: getColor(themeV4Colors.base.white),
- rowHoverBg: getColor(themeV4Colors.gray['50']),
- borderColor: getColor(themeV4Colors.gray['200']),
- borderLight: getColor(themeV4Colors.gray['100']),
- chevronColor: getColor(themeV4Colors.gray['500']),
- headerBg: getColor(themeV4Colors.base.white),
- headerText: getColor(themeV4Colors.gray['500']),
- subHeaderBg: getColor(themeV4Colors.base.white),
- subHeaderText: getColor(themeV4Colors.gray['500']),
- addRowBg: getColor(themeV4Colors.base.white),
- addRowText: getColor(themeV4Colors.gray['400']),
- }
- }
-
- function renderCanvas() {
- const canvas = canvasRef.value
- if (!canvas) return
-
- const ctx = getSafe2DContext(canvas)
- if (!ctx) return
-
- const dpr = window.devicePixelRatio || 1
- canvas.width = width.value * dpr
- canvas.height = height.value * dpr
- canvas.style.width = `${width.value}px`
- ctx.scale(dpr, dpr)
-
- const colors = getColors()
-
- ctx.clearRect(0, 0, width.value, canvas.height)
- ctx.fillStyle = colors.bg
- ctx.fillRect(0, 0, width.value, canvas.height)
-
- elementMap.value = []
-
- const { start, end } = rowSlice.value
- const rows = cachedRows.value
- const sh = slotHeight.value
-
- const hh = headerRowHeight.value
-
- // Content starts after the sticky header
- let y = hh + start * sh // estimated start Y in content coords
-
- // Track the depth shown by the most recent sub-header that's
- // at or above the viewport top, so we can render a sticky header.
- let stickyDepth = 0
- let stickyFound = false
-
- // Track last parent PK per depth (for addRow context)
- const lastPkAtDepth: Record<number, string | number> = {}
-
- for (let i = start; i < end && i < totalRows.value; i++) {
- const row = rows.get(i)
- if (!row) {
- y += rowHeight.value
- continue
- }
-
- const depth = row.__nc_depth ?? 0
-
- // Check previous row for depth transitions
- const prevRow = i > 0 ? rows.get(i - 1) : undefined
- const prevDepth = prevRow ? prevRow.__nc_depth ?? 0 : i === 0 ? -1 : undefined
-
- if (prevDepth !== undefined) {
- if (depth > prevDepth) {
- // The very first group's header is covered by the sticky header β€” skip it
- const isFirstGroup = prevDepth === -1
-
- if (!isFirstGroup) {
- // Add gap before sub-header
- if (prevDepth >= 0) {
- y += DEPTH_INCREASE_GAP
- }
- // Entering a new group: draw sub-header
- const subHeaderScreenY = y - scrollTop.value
- if (subHeaderScreenY + SUB_HEADER_HEIGHT > hh && subHeaderScreenY < height.value) {
- renderSubHeader(ctx, depth, subHeaderScreenY, colors)
- }
- // Track for sticky: if this sub-header is at or above the header bottom
- if (subHeaderScreenY <= hh) {
- stickyDepth = depth
- stickyFound = true
- } else if (!stickyFound) {
- stickyDepth = depth
- stickyFound = true
- }
- y += SUB_HEADER_HEIGHT
- } else {
- // First group: sticky header covers it, just track depth
- stickyDepth = depth
- stickyFound = true
- }
- } else if (depth < prevDepth) {
- // Closing groups: draw add-row for each closed depth
- if (isAddingEmptyRowAllowed.value) {
- for (let d = prevDepth; d > depth; d--) {
- const addRowScreenY = y - scrollTop.value
- if (addRowScreenY + ADD_ROW_HEIGHT > hh && addRowScreenY < height.value) {
- renderAddRow(ctx, d, addRowScreenY, colors, lastPkAtDepth[d - 1])
- }
- y += ADD_ROW_HEIGHT
- }
- }
-
- // Re-render sub-header for the current depth
- // so column names are visible again after expanded children
- y += DEPTH_DECREASE_GAP
- const subHeaderScreenY = y - scrollTop.value
- if (subHeaderScreenY + SUB_HEADER_HEIGHT > hh && subHeaderScreenY < height.value) {
- renderSubHeader(ctx, depth, subHeaderScreenY, colors)
- }
- if (subHeaderScreenY <= hh) {
- stickyDepth = depth
- stickyFound = true
- }
- y += SUB_HEADER_HEIGHT
- }
- }
-
- // Render the data row
- const screenY = y - scrollTop.value
- if (screenY + rowHeight.value > hh && screenY < height.value) {
- renderRow(ctx, row, i, screenY, depth, colors)
- }
-
- // Track PK at this depth for addRow parent context
- lastPkAtDepth[depth] = row.__nc_pk
-
- // If no sub-header found yet, use this row's depth for the sticky
- if (!stickyFound) {
- stickyDepth = depth
- stickyFound = true
- }
-
- y += rowHeight.value
- }
-
- // After the last rendered row, insert trailing add-rows for open depths
- const lastRow = rows.get(end - 1)
- if (lastRow && end >= totalRows.value && isAddingEmptyRowAllowed.value) {
- const lastDepth = lastRow.__nc_depth ?? 0
- for (let d = lastDepth; d >= 1; d--) {
- const addRowScreenY = y - scrollTop.value
- if (addRowScreenY + ADD_ROW_HEIGHT > hh && addRowScreenY < height.value) {
- renderAddRow(ctx, d, addRowScreenY, colors, lastPkAtDepth[d - 1])
- }
- y += ADD_ROW_HEIGHT
- }
- }
-
- // Sticky header (drawn last to overlay β€” shows columns for the depth
- // of the sub-header that has scrolled past the viewport top)
- stickyHeaderDepth.value = stickyDepth
- renderHeader(ctx, stickyDepth, colors)
- }
-
- function renderHeader(ctx: CanvasRenderingContext2D, depth: number, colors: ReturnType<typeof getColors>) {
- const hh = headerRowHeight.value
- const cols = getColumnsForDepth(depth)
- const indent = CHEVRON_COL_WIDTH + depth * INDENT_PER_DEPTH
-
- // Background β€” shadow only when scrolled
- if (scrollTop.value > 0) {
- ctx.save()
- ctx.shadowColor = 'rgba(0, 0, 0, 0.12)'
- ctx.shadowBlur = 8
- ctx.shadowOffsetX = 0
- ctx.shadowOffsetY = 4
- ctx.fillStyle = colors.headerBg
- ctx.fillRect(0, -2, width.value, hh + 2)
- ctx.restore()
- } else {
- ctx.fillStyle = colors.headerBg
- ctx.fillRect(0, 0, width.value, hh)
- }
-
- if (cols.length === 0) return
-
- let x = indent - scrollLeft.value
- const isHeaderHovered = mousePosition.y >= 0 && mousePosition.y < hh
-
- ctx.font = '700 11px Inter'
- ctx.textBaseline = 'middle'
-
- for (let ci = 0; ci < cols.length; ci++) {
- const col = cols[ci]
- const w = parseCellWidth(col.width)
-
- ctx.fillStyle = colors.headerText
- const text = truncateText(ctx, col.title, w - CELL_PADDING * 2)
- ctx.fillText(text, x + CELL_PADDING, hh / 2)
-
- // Pill divider between columns (including after the last)
- if (isHeaderHovered) {
- const pillX = x + w
- renderHeaderPill(ctx, pillX, 0, hh)
- }
-
- x += w
- }
- }
-
- function renderSubHeader(ctx: CanvasRenderingContext2D, depth: number, screenY: number, colors: ReturnType<typeof getColors>) {
- const cols = getColumnsForDepth(depth)
- if (cols.length === 0) return
-
- const indent = CHEVRON_COL_WIDTH + depth * INDENT_PER_DEPTH
-
- // Track sub-header in element map for hit-testing (resize, etc.)
- elementMap.value.push({
- type: 'header',
- rowIndex: -1,
- x: 0,
- y: screenY,
- width: width.value,
- height: SUB_HEADER_HEIGHT,
- depth,
- })
-
- ctx.fillStyle = colors.subHeaderBg
- ctx.fillRect(0, screenY, width.value, SUB_HEADER_HEIGHT)
-
- const borderStartX = indent - scrollLeft.value
-
- ctx.strokeStyle = colors.borderLight
- ctx.lineWidth = 0.5
- ctx.beginPath()
- ctx.moveTo(borderStartX, screenY + SUB_HEADER_HEIGHT - 0.5)
- ctx.lineTo(width.value, screenY + SUB_HEADER_HEIGHT - 0.5)
- ctx.stroke()
-
- let x = borderStartX
- const isSubHeaderHovered = mousePosition.y >= screenY && mousePosition.y < screenY + SUB_HEADER_HEIGHT
-
- ctx.font = '700 10px Inter'
- ctx.textBaseline = 'middle'
-
- for (let ci = 0; ci < cols.length; ci++) {
- const col = cols[ci]
- const w = parseCellWidth(col.width)
-
- ctx.fillStyle = colors.subHeaderText
- const text = truncateText(ctx, col.title, w - CELL_PADDING * 2)
- ctx.fillText(text, x + CELL_PADDING, screenY + SUB_HEADER_HEIGHT / 2)
-
- // Pill divider between columns (including after the last)
- if (isSubHeaderHovered) {
- const pillX = x + w
- renderHeaderPill(ctx, pillX, screenY, SUB_HEADER_HEIGHT)
- }
-
- x += w
- }
- }
-
- function renderAddRow(
- ctx: CanvasRenderingContext2D,
- depth: number,
- screenY: number,
- colors: ReturnType<typeof getColors>,
- parentPk?: string | number,
- ) {
- const rh = ADD_ROW_HEIGHT
- const indent = CHEVRON_COL_WIDTH + depth * INDENT_PER_DEPTH
-
- const isAddRowHovered = mousePosition.y >= screenY && mousePosition.y < screenY + rh
-
- ctx.fillStyle = isAddRowHovered ? getColor(themeV4Colors.gray['50']) : colors.addRowBg
- ctx.fillRect(0, screenY, width.value, rh)
-
- const borderStartX = indent - scrollLeft.value
- ctx.strokeStyle = colors.borderLight
- ctx.lineWidth = 0.5
- ctx.beginPath()
- ctx.moveTo(borderStartX, screenY + rh - 0.5)
- ctx.lineTo(width.value, screenY + rh - 0.5)
- ctx.stroke()
-
- const x = borderStartX + CELL_PADDING
- ctx.font = '400 12px Inter'
- ctx.textBaseline = 'middle'
- ctx.fillStyle = isAddRowHovered ? getColor(themeV4Colors.gray['600']) : colors.addRowText
- ctx.fillText('+ New record', x, screenY + rh / 2)
-
- elementMap.value.push({
- type: 'addRow',
- rowIndex: -1,
- x: 0,
- y: screenY,
- width: width.value,
- height: rh,
- depth,
- parentPk,
- })
- }
-
- function renderRow(
- ctx: CanvasRenderingContext2D,
- row: OutlineViewRow,
- rowIndex: number,
- screenY: number,
- depth: number,
- colors: ReturnType<typeof getColors>,
- ) {
- const rh = rowHeight.value
- const isHovered = hoverRow.value.rowIndex === rowIndex
- const maxDepth = displayLevels.value.length - 1
- const isParent = depth < maxDepth
- const collapsed = isCollapsed(depth, String(row.__nc_pk))
- const indent = CHEVRON_COL_WIDTH + depth * INDENT_PER_DEPTH
-
- // Row coloring
- const colorInfo = row.__nc_color as
- | {
- rowBgColor?: string
- rowHoverColor?: string
- rowLeftBorderColor?: string
- rowBorderColor?: string
- is_set_as_background?: boolean
- }
- | undefined
-
- const rowColor = colorInfo
- ? colorInfo.is_set_as_background && isHovered
- ? colorInfo.rowHoverColor
- : colorInfo.rowBgColor
- : null
-
- // Row background
- ctx.fillStyle = rowColor || (isHovered ? colors.rowHoverBg : colors.rowBg)
- ctx.fillRect(0, screenY, width.value, rh)
-
- // Row bottom border (starts from indent)
- const borderStartX = indent - scrollLeft.value
- ctx.strokeStyle = rowColor ? colorInfo?.rowBorderColor || colors.borderColor : colors.borderColor
- ctx.lineWidth = 0.5
- ctx.beginPath()
- ctx.moveTo(borderStartX, screenY + rh - 0.5)
- ctx.lineTo(width.value, screenY + rh - 0.5)
- ctx.stroke()
-
- // Left border color indicator
- if (colorInfo?.rowLeftBorderColor) {
- const indicatorW = 4
- const indicatorH = rh - 8
- const indicatorX = borderStartX
- const indicatorY = screenY + (rh - indicatorH) / 2
-
- ctx.fillStyle = colorInfo.rowLeftBorderColor
- ctx.beginPath()
- ctx.roundRect(indicatorX, indicatorY, indicatorW, indicatorH, 8)
- ctx.fill()
- }
-
- // Element map: row
- elementMap.value.push({
- type: 'row',
- rowIndex,
- x: 0,
- y: screenY,
- width: width.value,
- height: rh,
- depth,
- pk: row.__nc_pk,
- })
-
- // Chevron
- if (isParent) {
- const chevronX = depth * INDENT_PER_DEPTH + (CHEVRON_COL_WIDTH - CHEVRON_SIZE) / 2 - scrollLeft.value
- const chevronY = screenY + 8
-
- renderChevron(ctx, chevronX, chevronY, collapsed, colors.chevronColor)
-
- // Hit area: full chevron column width for easier clicking
- const hitX = depth * INDENT_PER_DEPTH - scrollLeft.value
- elementMap.value.push({
- type: 'chevron',
- rowIndex,
- x: hitX,
- y: screenY,
- width: CHEVRON_COL_WIDTH,
- height: rh,
- depth,
- pk: row.__nc_pk,
- })
- }
-
- // Cell values per column
- const cols = getColumnsForDepth(depth)
- let x = indent - scrollLeft.value
-
- for (const col of cols) {
- const w = parseCellWidth(col.width)
- const value = row[col.title]
- const isEditable = !col.readonly
-
- // Editable cell: border + shadow
- if (isEditable && isHovered) {
- const cellX = x + 1
- const cellY = screenY + 2
- const cellW = w - 2
- const cellH = rh - 4
-
- // Shadow layers (approximate multi-layer CSS box-shadow)
- ctx.save()
- ctx.shadowColor = 'rgba(0, 0, 0, 0.12)'
- ctx.shadowBlur = 4
- ctx.shadowOffsetX = 0
- ctx.shadowOffsetY = 1
- ctx.fillStyle = colors.rowBg
- ctx.beginPath()
- ctx.roundRect(cellX, cellY, cellW, cellH, 4)
- ctx.fill()
- ctx.restore()
-
- // Border
- ctx.strokeStyle = getColor(themeV4Colors.gray['300'])
- ctx.lineWidth = 0.5
- ctx.beginPath()
- ctx.roundRect(cellX, cellY, cellW, cellH, 4)
- ctx.stroke()
- }
-
- // Clip and render cell via the type-aware renderer
- ctx.save()
- ctx.beginPath()
- ctx.rect(x, screenY, w, rh)
- ctx.clip()
-
- renderCell(ctx, col.columnObj, {
- value,
- row,
- x,
- y: screenY,
- width: w,
- height: rh,
- pv: col.pv,
- padding: CELL_PADDING,
- pk: row.__nc_pk,
- mousePosition,
- meta: meta.value,
- isRowHovered: isHovered,
- relatedColObj: col.relatedColObj,
- relatedTableMeta: col.relatedTableMeta,
- readonly: col.readonly,
- })
-
- ctx.restore()
-
- // Register editable cell hit region
- if (isEditable) {
- elementMap.value.push({
- type: 'cell',
- rowIndex,
- x,
- y: screenY,
- width: w,
- height: rh,
- depth,
- pk: row.__nc_pk,
- columnId: col.id,
- })
- }
-
- x += w
- }
-
- // "Open >" expand button on hover β€” positioned at the right of the first cell
- if (isHovered && cols.length > 0) {
- const firstColW = parseCellWidth(cols[0].width)
- const firstCellX = indent - scrollLeft.value
-
- const label = 'Open'
- ctx.font = '500 11px Inter'
- const labelW = ctx.measureText(label).width
- const chevronW = 5
- const btnPadH = 6
- const btnGap = 3
- const btnW = btnPadH + labelW + btnGap + chevronW + btnPadH
- const btnH = 20
- const btnX = firstCellX + firstColW - btnW - CELL_PADDING
- const btnY = screenY + (rh - btnH) / 2
-
- // Only render if button fits inside first cell
- if (btnX > firstCellX + CELL_PADDING) {
- // Background pill
- ctx.fillStyle = getColor(themeV4Colors.gray['100'])
- ctx.beginPath()
- ctx.roundRect(btnX, btnY, btnW, btnH, 4)
- ctx.fill()
-
- // Check hover over expand button
- const isBtnHovered =
- mousePosition.x >= btnX && mousePosition.x <= btnX + btnW && mousePosition.y >= btnY && mousePosition.y <= btnY + btnH
-
- if (isBtnHovered) {
- ctx.fillStyle = getColor(themeV4Colors.gray['200'])
- ctx.beginPath()
- ctx.roundRect(btnX, btnY, btnW, btnH, 4)
- ctx.fill()
- }
-
- // Label text
- ctx.fillStyle = getColor(themeV4Colors.gray['600'])
- ctx.font = '500 11px Inter'
- ctx.textBaseline = 'middle'
- ctx.fillText(label, btnX + btnPadH, btnY + btnH / 2)
-
- // Right chevron ">"
- const chevronX = btnX + btnPadH + labelW + btnGap
- const chevronCY = btnY + btnH / 2
- const cs = 3
- ctx.beginPath()
- ctx.moveTo(chevronX, chevronCY - cs)
- ctx.lineTo(chevronX + cs, chevronCY)
- ctx.lineTo(chevronX, chevronCY + cs)
- ctx.strokeStyle = getColor(themeV4Colors.gray['600'])
- ctx.lineWidth = 1.5
- ctx.stroke()
-
- // Element map for click
- elementMap.value.push({
- type: 'expandRow',
- rowIndex,
- x: btnX,
- y: btnY,
- width: btnW,
- height: btnH,
- depth,
- pk: row.__nc_pk,
- })
- }
- }
- }
-
- function renderHeaderPill(ctx: CanvasRenderingContext2D, pillX: number, headerY: number, headerH: number) {
- const pillW = 3
- const pillH = 14
- const pillR = 1.5
- const px = pillX - pillW / 2
- const py = headerY + (headerH - pillH) / 2
-
- // Check if mouse is directly over the pill (generous hit area)
- const hitPadX = 8
- const hitPadY = 4
- const isHovered =
- mousePosition.x >= px - hitPadX &&
- mousePosition.x <= px + pillW + hitPadX &&
- mousePosition.y >= py - hitPadY &&
- mousePosition.y <= py + pillH + hitPadY
-
- ctx.fillStyle = isHovered ? getColor(themeV4Colors.brand['500']) : getColor(themeV4Colors.gray['300'])
-
- ctx.beginPath()
- ctx.roundRect(px, py, pillW, pillH, pillR)
- ctx.fill()
- }
-
- function renderChevron(ctx: CanvasRenderingContext2D, x: number, y: number, collapsed: boolean, color: string) {
- ctx.save()
- ctx.fillStyle = color
- ctx.beginPath()
-
- const cx = x + CHEVRON_SIZE / 2
- const cy = y + CHEVRON_SIZE / 2
- const s = 4
-
- if (collapsed) {
- ctx.moveTo(cx - s / 2 + 1, cy - s)
- ctx.lineTo(cx + s / 2 + 1, cy)
- ctx.lineTo(cx - s / 2 + 1, cy + s)
- } else {
- ctx.moveTo(cx - s, cy - s / 2 + 1)
- ctx.lineTo(cx, cy + s / 2 + 1)
- ctx.lineTo(cx + s, cy - s / 2 + 1)
- }
-
- ctx.closePath()
- ctx.fill()
- ctx.restore()
- }
-
- function truncateText(ctx: CanvasRenderingContext2D, text: string, maxWidth: number): string {
- if (maxWidth <= 0) return ''
- if (ctx.measureText(text).width <= maxWidth) return text
-
- const ellipsis = '...'
- const ew = ctx.measureText(ellipsis).width
- let lo = 0
- let hi = text.length
- while (lo < hi) {
- const mid = Math.ceil((lo + hi) / 2)
- if (ctx.measureText(text.slice(0, mid)).width + ew <= maxWidth) lo = mid
- else hi = mid - 1
- }
- return text.slice(0, lo) + ellipsis
- }
-
- return {
- canvasRef,
- renderCanvas,
- }
-}
diff --git a/packages/nc-gui/components/smartsheet/outline/composables/useColumnResize.ts b/packages/nc-gui/components/smartsheet/outline/composables/useColumnResize.ts
deleted file mode 100644
index cc7130d3d1..0000000000
--- a/packages/nc-gui/components/smartsheet/outline/composables/useColumnResize.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { parseCellWidth } from '../../grid/canvas/utils/cell'
-import { MIN_COLUMN_WIDTH, RESIZE_HANDLE_WIDTH } from './constants'
-
-export interface HeaderContext {
- columns: CanvasGridColumn[]
- startX: number // left edge of first column (already adjusted for scroll)
-}
-
-/**
- * Column resize for the outline view canvas.
- * Works on both root header and sub-headers via `resolveHeader`.
- */
-export function useColumnResize(
- canvasRef: Ref<HTMLCanvasElement | undefined>,
- drawCanvas: () => void,
- /** Given canvas-local (x, y), return the columns + startX for that header, or null */
- resolveHeader: (x: number, y: number) => HeaderContext | null,
- onResize: (columnId: string, width: number) => void,
- onResizeEnd: (columnId: string, width: number) => void,
-) {
- const isResizing = ref(false)
- const resizingColumn = ref<{
- id: string
- initialWidth: number
- startX: number
- currentWidth: number
- } | null>(null)
-
- const isLocked = inject(IsLockedInj, ref(false))
-
- /** Find a resizeable column border near x in the given header context */
- function findResizeTarget(x: number, y: number): { id: string; width: number } | null {
- const ctx = resolveHeader(x, y)
- if (!ctx) return null
-
- let currentX = ctx.startX
- for (const column of ctx.columns) {
- const w = parseCellWidth(column.width)
- const borderX = currentX + w
-
- if (Math.abs(x - borderX) <= RESIZE_HANDLE_WIDTH / 2) {
- return { id: column.id, width: w }
- }
- currentX += w
- }
- return null
- }
-
- function handleDrag(e: MouseEvent) {
- if (!isResizing.value || !resizingColumn.value) return
-
- const rect = canvasRef.value?.getBoundingClientRect()
- if (!rect) return
-
- const x = e.clientX - rect.left
- const delta = x - resizingColumn.value.startX
- const newWidth = Math.max(MIN_COLUMN_WIDTH, resizingColumn.value.initialWidth + delta)
- resizingColumn.value.currentWidth = newWidth
-
- onResize(resizingColumn.value.id, newWidth)
- }
-
- function handleMouseUp() {
- if (isResizing.value && resizingColumn.value) {
- onResizeEnd(resizingColumn.value.id, resizingColumn.value.currentWidth)
- }
- cleanup()
- }
-
- function cleanup() {
- isResizing.value = false
- resizingColumn.value = null
- window.removeEventListener('mousemove', handleDrag)
- window.removeEventListener('mouseup', handleMouseUp)
- }
-
- /** Call from canvas mousedown β€” returns true if resize started */
- function startResize(e: MouseEvent): boolean {
- const rect = canvasRef.value?.getBoundingClientRect()
- if (!rect || isLocked.value) return false
-
- const x = e.clientX - rect.left
- const y = e.clientY - rect.top
- const target = findResizeTarget(x, y)
- if (!target) return false
-
- isResizing.value = true
- resizingColumn.value = {
- id: target.id,
- initialWidth: target.width,
- startX: x,
- currentWidth: target.width,
- }
-
- window.addEventListener('mousemove', handleDrag)
- window.addEventListener('mouseup', handleMouseUp)
- return true
- }
-
- /** Call from canvas mousemove to get cursor */
- function updateCursor(x: number, y: number): string | null {
- if (isResizing.value) return 'col-resize'
- const target = findResizeTarget(x, y)
- return target ? 'col-resize' : null
- }
-
- onBeforeUnmount(cleanup)
-
- return {
- isResizing,
- resizingColumn,
- startResize,
- updateCursor,
- }
-}
diff --git a/packages/nc-gui/components/smartsheet/outline/composables/useDataFetch.ts b/packages/nc-gui/components/smartsheet/outline/composables/useDataFetch.ts
deleted file mode 100644
index 4069d8cd02..0000000000
--- a/packages/nc-gui/components/smartsheet/outline/composables/useDataFetch.ts
+++ /dev/null
@@ -1,278 +0,0 @@
-/**
- * useOutlineDataFetch β€” Chunked data loading for the outline view canvas.
- *
- * The outline view API (`outlineViewDataList`) supports offset/limit pagination.
- * The count API (`outlineViewDataCount`) returns totalRows + per-model counts.
- *
- * Both endpoints accept a `collapsed` param (JSON) so the server
- * only returns expanded rows β€” collapsed subtrees are skipped server-side.
- *
- * This composable adapts the grid canvas's useDataFetch pattern:
- * - Chunked loading with prefetch
- * - Scroll-direction-aware prefetching
- * - Throttled API calls
- */
-
-import type { OutlineViewRow } from '~/composables/useOutlineViewStore'
-
-const CHUNK_SIZE = 50
-const INITIAL_LOAD_SIZE = 100
-const BUFFER_SIZE = 100
-const PREFETCH_THRESHOLD = 25
-const API_THROTTLE = 500
-
-export function useOutlineDataFetch({
- viewId,
- cachedRows,
- chunkStates,
- totalRows,
- levelCounts,
- collapsedJson,
- loadPage,
- loadCount,
- triggerRefreshCanvas,
-}: {
- /** Current view ID */
- viewId: ComputedRef<string | undefined>
- /** Row cache: index β†’ row data */
- cachedRows: Ref<Map<number, OutlineViewRow>>
- /** Chunk state tracking */
- chunkStates: Ref<Array<'loading' | 'loaded' | undefined>>
- /** Total visible row count (from count endpoint) */
- totalRows: Ref<number>
- /** Per-model counts from count endpoint: { modelId: count } */
- levelCounts: Ref<Record<string, number>>
- /** Serialized collapsed state for API calls */
- collapsedJson: ComputedRef<string>
- /** Fetch a page of data */
- loadPage: (params: { offset: number; limit: number; collapsed: string }) => Promise<OutlineViewRow[]>
- /** Fetch total count */
- loadCount: (params: { collapsed: string }) => Promise<{ totalRows: number; counts: Record<string, number> }>
- /** Trigger canvas re-render */
- triggerRefreshCanvas: () => void
-}) {
- const previousRowSlice = ref({ start: 0, end: 0 })
-
- // -------------------------------------------------------------------
- // Fetch count
- // -------------------------------------------------------------------
- async function fetchCount() {
- if (!viewId.value) return
-
- try {
- const result = await loadCount({ collapsed: collapsedJson.value })
- totalRows.value = result.totalRows
- levelCounts.value = result.counts
- } catch (e) {
- // silently ignore β€” count will remain at previous value
- }
- }
-
- // -------------------------------------------------------------------
- // Fetch a single chunk
- // -------------------------------------------------------------------
- async function fetchChunk(chunkId: number, isInitialLoad = false) {
- if (chunkStates.value[chunkId]) return
-
- const offset = chunkId * CHUNK_SIZE
- const limit = isInitialLoad ? INITIAL_LOAD_SIZE : CHUNK_SIZE
-
- if (offset >= totalRows.value) return
-
- chunkStates.value[chunkId] = 'loading'
- if (isInitialLoad) {
- chunkStates.value[chunkId + 1] = 'loading'
- }
-
- try {
- const rows = await loadPage({
- offset,
- limit,
- collapsed: collapsedJson.value,
- })
-
- rows.forEach((row, idx) => {
- cachedRows.value.set(offset + idx, row)
- })
-
- chunkStates.value[chunkId] = 'loaded'
- if (isInitialLoad) {
- chunkStates.value[chunkId + 1] = 'loaded'
- }
- } catch (e) {
- // reset chunk state so it can be retried
- chunkStates.value[chunkId] = undefined
- if (isInitialLoad) {
- chunkStates.value[chunkId + 1] = undefined
- }
- }
- }
-
- // -------------------------------------------------------------------
- // Fetch contiguous chunk group in one API call
- // -------------------------------------------------------------------
- async function fetchChunkGroup(group: number[]) {
- if (group.length === 0) return
-
- const startChunk = group[0]!
- const endChunk = group[group.length - 1]!
- const offset = startChunk * CHUNK_SIZE
- const limit = (endChunk + 1) * CHUNK_SIZE - offset
-
- if (offset >= totalRows.value) return
-
- group.forEach((id) => (chunkStates.value[id] = 'loading'))
-
- try {
- const rows = await loadPage({
- offset,
- limit,
- collapsed: collapsedJson.value,
- })
-
- rows.forEach((row, idx) => {
- cachedRows.value.set(offset + idx, row)
- })
-
- group.forEach((id) => (chunkStates.value[id] = 'loaded'))
- } catch (e) {
- // reset chunk states so they can be retried
- group.forEach((id) => (chunkStates.value[id] = undefined))
- }
- }
-
- // -------------------------------------------------------------------
- // Throttled batch fetcher
- // -------------------------------------------------------------------
- const debouncedFetchChunks = useThrottleFn(
- async (chunksToFetch: Set<number>, firstChunkId: number) => {
- if (chunksToFetch.size === 0) return
-
- const chunks = Array.from(chunksToFetch).sort((a, b) => a - b)
-
- // Group contiguous chunks
- const groups: number[][] = []
- let currentGroup: number[] = [chunks[0]!]
-
- for (let i = 1; i < chunks.length; i++) {
- if (chunks[i] === chunks[i - 1]! + 1) {
- currentGroup.push(chunks[i]!)
- } else {
- groups.push(currentGroup)
- currentGroup = [chunks[i]!]
- }
- }
- groups.push(currentGroup)
-
- const maxGroupSize = Math.floor(200 / CHUNK_SIZE) // API max limit is 200
-
- for (const group of groups) {
- if (group[0] === 0 && firstChunkId === 0 && !chunkStates.value[0]) {
- await fetchChunk(0, true)
- const remaining = group.filter((id) => id > 1)
- if (remaining.length) {
- for (let i = 0; i < remaining.length; i += maxGroupSize) {
- await fetchChunkGroup(remaining.slice(i, i + maxGroupSize))
- }
- }
- } else if (group.length > maxGroupSize) {
- for (let i = 0; i < group.length; i += maxGroupSize) {
- await fetchChunkGroup(group.slice(i, i + maxGroupSize))
- }
- } else {
- await fetchChunkGroup(group)
- }
- }
-
- nextTick(triggerRefreshCanvas)
- },
- API_THROTTLE,
- true,
- )
-
- // -------------------------------------------------------------------
- // Update visible rows β€” called on scroll
- // -------------------------------------------------------------------
- function updateVisibleRows(rowSlice: { start: number; end: number }) {
- const { start, end } = rowSlice
- const firstChunkId = Math.floor(start / CHUNK_SIZE)
- const lastChunkId = Math.floor(Math.max(0, end - 1) / CHUNK_SIZE)
-
- // Scroll direction
- let scrollDirection: 'down' | 'up' | 'none' = 'none'
- if (start > previousRowSlice.value.start) scrollDirection = 'down'
- else if (start < previousRowSlice.value.start) scrollDirection = 'up'
- previousRowSlice.value = { start, end }
-
- const chunksToFetch = new Set<number>()
-
- // Visible chunks
- for (let chunkId = firstChunkId; chunkId <= lastChunkId; chunkId++) {
- if (!chunkStates.value[chunkId]) {
- chunksToFetch.add(chunkId)
- }
- }
-
- // Prefetch based on scroll direction
- if (scrollDirection === 'down' || scrollDirection === 'none') {
- const nextChunkId = lastChunkId + 1
- if (end % CHUNK_SIZE > CHUNK_SIZE - PREFETCH_THRESHOLD && !chunkStates.value[nextChunkId]) {
- chunksToFetch.add(nextChunkId)
- }
- } else if (scrollDirection === 'up') {
- const prevChunkId = firstChunkId - 1
- if (prevChunkId >= 0 && start % CHUNK_SIZE < PREFETCH_THRESHOLD && !chunkStates.value[prevChunkId]) {
- chunksToFetch.add(prevChunkId)
- }
- }
-
- // Evict out-of-buffer rows
- clearCache(Math.max(0, start - BUFFER_SIZE), Math.min(totalRows.value, end + BUFFER_SIZE))
-
- debouncedFetchChunks(chunksToFetch, firstChunkId)
- }
-
- // -------------------------------------------------------------------
- // Clear rows outside the buffer window
- // -------------------------------------------------------------------
- function clearCache(keepStart: number, keepEnd: number) {
- const affectedChunks = new Set<number>()
-
- for (const [idx] of cachedRows.value) {
- if (idx < keepStart || idx >= keepEnd) {
- cachedRows.value.delete(idx)
- affectedChunks.add(Math.floor(idx / CHUNK_SIZE))
- }
- }
-
- // Reset chunkStates for evicted chunks so they get re-fetched when scrolled back
- for (const chunkId of affectedChunks) {
- chunkStates.value[chunkId] = undefined
- }
- }
-
- // -------------------------------------------------------------------
- // Reset β€” call when collapsed state changes (server re-query needed)
- // Does NOT clear old cache β€” stale rows are naturally evicted by
- // updateVisibleRows and overwritten by new fetches, avoiding flicker.
- // -------------------------------------------------------------------
- async function resetAndReload() {
- chunkStates.value = []
-
- await fetchCount()
-
- if (totalRows.value > 0) {
- await fetchChunk(0, true)
- }
-
- nextTick(triggerRefreshCanvas)
- }
-
- return {
- fetchCount,
- fetchChunk,
- updateVisibleRows,
- resetAndReload,
- clearCache,
- }
-}
diff --git a/packages/nc-gui/components/smartsheet/outline/composables/useOutlineCellRenderer.ts b/packages/nc-gui/components/smartsheet/outline/composables/useOutlineCellRenderer.ts
deleted file mode 100644
index 69f658fcfb..0000000000
--- a/packages/nc-gui/components/smartsheet/outline/composables/useOutlineCellRenderer.ts
+++ /dev/null
@@ -1,370 +0,0 @@
-import { type ColumnType, type TableType, UITypes } from 'nocodb-sdk'
-import { renderSingleLineText } from '../../grid/canvas/utils/canvas'
-import type { SpriteLoader } from '../../grid/canvas/loaders/SpriteLoader'
-import { ImageWindowLoader } from '../../grid/canvas/loaders/ImageLoader'
-import { MarkdownLoader } from '../../grid/canvas/loaders/markdownLoader'
-import { EmailCellRenderer } from '../../grid/canvas/cells/Email'
-import { SingleLineTextCellRenderer } from '../../grid/canvas/cells/SingleLineText'
-import { LongTextCellRenderer } from '../../grid/canvas/cells/LongText'
-import { FloatCellRenderer } from '../../grid/canvas/cells/Number'
-import { DecimalCellRenderer } from '../../grid/canvas/cells/Decimal'
-import { AttachmentCellRenderer } from '../../grid/canvas/cells/Attachment'
-import { CheckboxCellRenderer } from '../../grid/canvas/cells/Checkbox'
-import { DateCellRenderer } from '../../grid/canvas/cells/Date'
-import { DateTimeCellRenderer } from '../../grid/canvas/cells/DateTime'
-import { YearCellRenderer } from '../../grid/canvas/cells/Year'
-import { TimeCellRenderer } from '../../grid/canvas/cells/Time'
-import { CurrencyRenderer } from '../../grid/canvas/cells/Currency'
-import { PercentCellRenderer } from '../../grid/canvas/cells/Percent'
-import { UrlCellRenderer } from '../../grid/canvas/cells/Url'
-import { GeoDataCellRenderer } from '../../grid/canvas/cells/GeoData'
-import { PhoneNumberCellRenderer } from '../../grid/canvas/cells/PhoneNumber'
-import { DurationCellRenderer } from '../../grid/canvas/cells/Duration'
-import { JsonCellRenderer } from '../../grid/canvas/cells/Json'
-import { BarcodeCellRenderer } from '../../grid/canvas/cells/Barcode'
-import { QRCodeCellRenderer } from '../../grid/canvas/cells/QRCode'
-import { RatingCellRenderer } from '../../grid/canvas/cells/Rating'
-import { ColourCellRenderer } from '../../grid/canvas/cells/Colour'
-import { UserFieldCellRenderer } from '../../grid/canvas/cells/User'
-import { SingleSelectCellRenderer } from '../../grid/canvas/cells/SingleSelect'
-import { MultiSelectCellRenderer } from '../../grid/canvas/cells/MultiSelect'
-import { RollupCellRenderer } from '../../grid/canvas/cells/Rollup'
-import { LinksCellRenderer } from '../../grid/canvas/cells/Links'
-import { LookupCellRenderer } from '../../grid/canvas/cells/Lookup'
-import { ButtonCellRenderer } from '../../grid/canvas/cells/Button'
-import { LtarCellRenderer } from '../../grid/canvas/cells/LTAR'
-import { FormulaCellRenderer } from '../../grid/canvas/cells/Formula'
-import { UUIDCellRenderer } from '../../grid/canvas/cells/UUID'
-import { GenericReadOnlyRenderer } from '../../grid/canvas/cells/GenericReadonlyRenderer'
-import { NullCellRenderer } from '../../grid/canvas/cells/Null'
-import { PlainCellRenderer } from '../../grid/canvas/cells/Plain'
-import { ActionManager } from '../../grid/canvas/loaders/ActionManager'
-
-const CLEANUP_INTERVAL = 1000
-
-export function useOutlineCellRenderer(params: {
- spriteLoader: SpriteLoader
- triggerRefreshCanvas: () => void
- setCursor: SetCursorType
- meta: Ref<TableType | undefined>
- cachedRows: Ref<Map<number, Row>>
- totalRows: Ref<number>
- chunkStates: Ref<Array<'loading' | 'loaded' | undefined>>
- updateOrSaveRow: (row: Row, property?: string) => Promise<any>
-}) {
- const { spriteLoader, triggerRefreshCanvas, setCursor } = params
-
- const { getColor, isDark } = useTheme()
- const { metas } = useMetas()
- const { showNull, appInfo, user } = useGlobal()
- const { t } = useI18n()
- const { $api } = useNuxtApp()
-
- const isPublic = inject(IsPublicInj, ref(false))
-
- const baseStore = useBase()
- const { isMysql, isXcdbBase, isPg } = baseStore
- const { sqlUis } = storeToRefs(baseStore)
-
- const { basesUser } = storeToRefs(useBases())
-
- const imageLoader = new ImageWindowLoader(() => triggerRefreshCanvas())
- const markdownLoader = new MarkdownLoader(() => triggerRefreshCanvas())
-
- const { generateRows: _generateRows } = useNocoAi()
- const { eventBus: scriptEventBus } = useScriptExecutor()
- const { loadScript } = useScriptStore()
- const { currentUser } = useUserSync()
-
- function generateRows(columnId: string, rowIds: string[]) {
- return _generateRows(params.meta.value?.id, columnId, rowIds)
- }
-
- const emptySelectedRows = computed(() => [] as Array<Row>)
- const emptyIsRowSortRequired = computed(() => [] as Array<Row>)
-
- const getDataCache = () => ({
- cachedRows: params.cachedRows,
- totalRows: params.totalRows,
- chunkStates: params.chunkStates,
- selectedRows: emptySelectedRows,
- isRowSortRequiredRows: emptyIsRowSortRequired,
- })
-
- const actionManager = new ActionManager(
- $api,
- loadScript,
- generateRows,
- params.meta as Ref<TableType>,
- triggerRefreshCanvas,
- getDataCache,
- scriptEventBus,
- currentUser,
- )
-
- if (baseStore.base?.id && baseStore.base?.fk_workspace_id) {
- actionManager.setBaseInfo(baseStore.base.id, baseStore.base.fk_workspace_id)
- }
-
- onUnmounted(() => {
- actionManager.releaseEventListeners()
- })
-
- const cellTypesRegistry = new Map<string, CellRenderer>()
-
- cellTypesRegistry.set(UITypes.Email, EmailCellRenderer)
- cellTypesRegistry.set(UITypes.SingleLineText, SingleLineTextCellRenderer)
- cellTypesRegistry.set(UITypes.LongText, LongTextCellRenderer)
- cellTypesRegistry.set(UITypes.Number, FloatCellRenderer)
- cellTypesRegistry.set(UITypes.Decimal, DecimalCellRenderer)
- cellTypesRegistry.set(UITypes.Attachment, AttachmentCellRenderer)
- cellTypesRegistry.set(UITypes.Checkbox, CheckboxCellRenderer)
- cellTypesRegistry.set(UITypes.Date, DateCellRenderer)
- cellTypesRegistry.set(UITypes.DateTime, DateTimeCellRenderer)
- cellTypesRegistry.set(UITypes.Year, YearCellRenderer)
- cellTypesRegistry.set(UITypes.Time, TimeCellRenderer)
- cellTypesRegistry.set(UITypes.Currency, CurrencyRenderer)
- cellTypesRegistry.set(UITypes.Percent, PercentCellRenderer)
- cellTypesRegistry.set(UITypes.URL, UrlCellRenderer)
- cellTypesRegistry.set(UITypes.GeoData, GeoDataCellRenderer)
- cellTypesRegistry.set(UITypes.PhoneNumber, PhoneNumberCellRenderer)
- cellTypesRegistry.set(UITypes.Duration, DurationCellRenderer)
- cellTypesRegistry.set(UITypes.CreatedTime, DateTimeCellRenderer)
- cellTypesRegistry.set(UITypes.LastModifiedTime, DateTimeCellRenderer)
- cellTypesRegistry.set(UITypes.JSON, JsonCellRenderer)
- cellTypesRegistry.set(UITypes.Barcode, BarcodeCellRenderer)
- cellTypesRegistry.set(UITypes.QrCode, QRCodeCellRenderer)
- cellTypesRegistry.set(UITypes.Rating, RatingCellRenderer)
- cellTypesRegistry.set(UITypes.Colour, ColourCellRenderer)
- cellTypesRegistry.set(UITypes.User, UserFieldCellRenderer)
- cellTypesRegistry.set(UITypes.CreatedBy, UserFieldCellRenderer)
- cellTypesRegistry.set(UITypes.LastModifiedBy, UserFieldCellRenderer)
- cellTypesRegistry.set(UITypes.SingleSelect, SingleSelectCellRenderer)
- cellTypesRegistry.set(UITypes.MultiSelect, MultiSelectCellRenderer)
- cellTypesRegistry.set(UITypes.Rollup, RollupCellRenderer)
- cellTypesRegistry.set(UITypes.Links, LinksCellRenderer)
- cellTypesRegistry.set(UITypes.Lookup, LookupCellRenderer)
- cellTypesRegistry.set(UITypes.Button, ButtonCellRenderer)
- cellTypesRegistry.set(UITypes.LinkToAnotherRecord, LtarCellRenderer)
- cellTypesRegistry.set(UITypes.Formula, FormulaCellRenderer)
- cellTypesRegistry.set(UITypes.Geometry, SingleLineTextCellRenderer)
- cellTypesRegistry.set(UITypes.SpecificDBType, SingleLineTextCellRenderer)
- cellTypesRegistry.set(UITypes.UUID, UUIDCellRenderer)
- cellTypesRegistry.set(UITypes.ForeignKey, GenericReadOnlyRenderer)
- cellTypesRegistry.set(UITypes.ID, GenericReadOnlyRenderer)
-
- const cellRenderStoreMap = new Map<string, CellRenderStore>()
- const expirationTimes = new Map<string, number>()
-
- const getCellRenderStore = (key: string) => {
- if (!cellRenderStoreMap.has(key)) {
- cellRenderStoreMap.set(key, {})
- }
- expirationTimes.set(key, Date.now() + CLEANUP_INTERVAL)
- return cellRenderStoreMap.get(key)!
- }
-
- let cleanUpInterval: ReturnType<typeof setInterval> | null = null
-
- onMounted(() => {
- cleanUpInterval = setInterval(() => {
- const now = Date.now()
- for (const [key, expiration] of expirationTimes.entries()) {
- if (now >= expiration) {
- cellRenderStoreMap.delete(key)
- expirationTimes.delete(key)
- }
- }
- }, CLEANUP_INTERVAL)
- })
-
- onUnmounted(() => {
- if (cleanUpInterval) {
- clearInterval(cleanUpInterval)
- }
- })
-
- const renderCell = (
- ctx: CanvasRenderingContext2D,
- column: ColumnType,
- {
- value,
- row,
- x,
- y,
- width,
- height,
- pv = false,
- padding = 10,
- pk,
- mousePosition,
- meta,
- isRowHovered = false,
- renderAsPlainCell = false,
- relatedColObj,
- relatedTableMeta,
- textColor,
- fontFamily,
- readonly = false,
- }: Omit<CellRendererOptions, 'metas' | 'isMysql' | 'isXcdbBase' | 'sqlUis' | 'baseUsers' | 'isPg'>,
- ) => {
- const cellType = cellTypesRegistry.get(column.uidt!)
- const cellRenderStore = getCellRenderStore(`${column.id}-${pk}`)
-
- const shouldRenderNull = showNull.value && isShowNullField(column) && (ncIsUndefined(value) || ncIsNull(value))
-
- let cellRenderer: CellRenderFn | undefined
-
- if (renderAsPlainCell) {
- cellRenderer = PlainCellRenderer.render
- } else if (cellType) {
- cellRenderer = shouldRenderNull ? cellType.renderEmpty ?? NullCellRenderer.render : cellType.render
- } else if (shouldRenderNull) {
- cellRenderer = NullCellRenderer.render
- }
-
- ctx.textAlign = 'left'
-
- if (cellRenderer) {
- cellRenderer(ctx, {
- value,
- row,
- column,
- x,
- y,
- width,
- height,
- selected: false,
- pv,
- readonly,
- spriteLoader,
- imageLoader,
- markdownLoader,
- isMysql,
- isPg,
- isXcdbBase,
- t,
- padding,
- renderCell,
- meta,
- metas: metas.value,
- relatedColObj,
- relatedTableMeta,
- tag: {},
- fontSize: 13,
- textAlign: 'center',
- textColor,
- mousePosition,
- pk,
- disabled: false,
- sqlUis: sqlUis.value,
- actionManager,
- setCursor,
- getColor,
- isDark: isDark.value,
- cellRenderStore,
- baseUsers: meta?.base_id ? basesUser.value.get(meta.base_id) || [] : [],
- user: user.value,
- isUnderLookup: false,
- isPublic: isPublic.value,
- path: [],
- fontFamily,
- isRowHovered,
- isRowChecked: false,
- rowMeta: {},
- allowLocalUrl: appInfo.value?.allowLocalUrl,
- })
- } else {
- renderSingleLineText(ctx, {
- x: x + padding,
- y,
- text: value?.toString() ?? '',
- fontFamily: fontFamily ?? `${pv ? 600 : 500} 13px Inter`,
- fillStyle: pv ? getColor(themeV4Colors.brand['500']) : getColor(textColor ?? themeV4Colors.gray['600']),
- height,
- py: padding,
- cellRenderStore,
- })
- }
- }
-
- const handleCellClick = async (ctx: {
- event: MouseEvent
- row: Row
- column: CanvasGridColumn
- value: any
- mousePosition: { x: number; y: number }
- pk: any
- selected: boolean
- imageLoader: ImageWindowLoader
- path: Array<number>
- cellPosition: { x: number; y: number; width: number; height: number }
- }) => {
- if (!ctx.column?.columnObj?.uidt) return false
-
- const cellHandler = cellTypesRegistry.get(ctx.column.columnObj.uidt)
- const cellRenderStore = getCellRenderStore(`${ctx.column.id}-${ctx.pk}`)
-
- if (cellHandler?.handleClick) {
- return await cellHandler.handleClick({
- ...ctx,
- cellRenderStore,
- isDoubleClick: ctx.event.detail === 2,
- readonly: ctx.column.readonly,
- getCellPosition: () => ctx.cellPosition,
- updateOrSaveRow: params.updateOrSaveRow,
- actionManager,
- makeCellEditable: () => {},
- markdownLoader,
- isPublic: isPublic.value,
- openDetachedExpandedForm: () => {},
- openDetachedLongText: () => {},
- allowLocalUrl: appInfo.value?.allowLocalUrl,
- t,
- getColor,
- baseRoles: {},
- })
- }
- return false
- }
-
- const handleCellHover = async (ctx: {
- event: MouseEvent
- row: Row
- column: CanvasGridColumn
- value: any
- mousePosition: { x: number; y: number }
- pk: any
- selected: boolean
- imageLoader: ImageWindowLoader
- }) => {
- if (!ctx.column?.columnObj?.uidt) return
-
- const cellHandler = cellTypesRegistry.get(ctx.column.columnObj.uidt)
- const cellRenderStore = getCellRenderStore(`${ctx.column.id}-${ctx.pk}`)
-
- if (cellHandler?.handleHover) {
- return await cellHandler.handleHover({
- ...ctx,
- cellRenderStore,
- setCursor,
- markdownLoader,
- path: [],
- baseUsers: ctx.row?.row?.base_id ? basesUser.value.get(ctx.row.row.base_id) || [] : [],
- t,
- getCellPosition: () => ({ x: 0, y: 0, width: 0, height: 0 }),
- updateOrSaveRow: params.updateOrSaveRow,
- actionManager,
- makeCellEditable: () => {},
- })
- }
- }
-
- return {
- renderCell,
- handleCellClick,
- handleCellHover,
- imageLoader,
- actionManager,
- }
-}
diff --git a/packages/nc-gui/components/smartsheet/outline/index.vue b/packages/nc-gui/components/smartsheet/outline/index.vue
index 9bb5a4ffca..7c3f5c658a 100644
--- a/packages/nc-gui/components/smartsheet/outline/index.vue
+++ b/packages/nc-gui/components/smartsheet/outline/index.vue
@@ -1,471 +1,3 @@
-<script setup lang="ts">
-import {
- type ColumnType,
- type LinkToAnotherRecordType,
- RelationTypes,
- type TableType,
- isLinksOrLTAR,
- isVirtualCol,
-} from 'nocodb-sdk'
-import { flip, offset, shift, useFloating } from '@floating-ui/vue'
-import Scroller from '../grid/canvas/components/Scroller.vue'
-import Tooltip from '../grid/canvas/components/Tooltip.vue'
-import { useCanvasOutline } from './composables/useCanvasOutline'
-
-const { meta, view } = useSmartsheetStoreOrThrow()
-const { metas, getMeta } = useMetas()
-const { $api } = useNuxtApp()
-
-const route = useRoute()
-const router = useRouter()
-
-const rowHeightEnum = computed(() => {
- const outlineView = view.value?.view as OutlineType | undefined
- if (outlineView?.row_height !== undefined) {
- switch (outlineView.row_height) {
- case 0:
- return 1
- case 1:
- return 2
- case 2:
- return 4
- case 3:
- return 6
- default:
- return 1
- }
- }
- return 1
-})
-
-provide(IsCanvasInjectionInj, true)
-provide(IsFormInj, ref(false))
-provide(IsGalleryInj, ref(false))
-provide(IsGridInj, ref(false))
-provide(IsCalendarInj, ref(false))
-provide(IsListInj, ref(true))
-provide(RowHeightInj, rowHeightEnum)
-
-const scrollTop = ref(0)
-const scrollLeft = ref(0)
-const wrapperRef = ref()
-const activeCellRow = ref<Row | null>(null)
-
-const mousePosition = reactive({ x: 0, y: 0 })
-const clientMousePosition = reactive(clientMousePositionDefaultValue)
-const scroller = ref()
-provide(ClientMousePositionInj, clientMousePosition)
-
-const isContextMenuOpen = ref(false)
-
-const reloadViewDataHook = inject(ReloadViewDataHookInj, createEventHook())
-const isPublicView = inject(IsPublicInj, ref(false))
-
-const { height, width } = useElementSize(wrapperRef)
-const tooltipStore = useTooltipStore()
-const { targetReference, placement } = storeToRefs(tooltipStore)
-const tooltipRef = ref()
-const { floatingStyles } = useFloating(targetReference, tooltipRef, {
- placement,
- middleware: [offset(8), flip(), shift({ padding: 5 })],
-})
-
-const { isConfigured } = useOutlineViewStoreOrThrow()
-
-const {
- canvasRef,
- triggerRefreshCanvas,
- resetAndReload,
- totalHeight,
- totalWidth,
- handleCanvasMouseDown,
- handleCanvasClick,
- handleCanvasMouseMove,
- handleCanvasMouseLeave,
- onExpandRow,
- onAddRow,
- activeCell,
- cachedRows,
-} = useCanvasOutline({
- scrollLeft,
- scrollTop,
- width,
- height,
- mousePosition,
-})
-
-function handleScroll({ left, top }: { left: number; top: number }) {
- scrollLeft.value = left
- scrollTop.value = top
- if (activeCell.value) {
- activeCell.value = null
- }
-}
-
-reloadViewDataHook.on(() => {
- resetAndReload()
-})
-
-const { displayLevels } = useOutlineViewStoreOrThrow()
-
-const expandedFormDlg = ref(false)
-const expandedFormRow = ref<Row>()
-const expandedFormRowState = ref<Record<string, any>>()
-const expandedFormMeta = ref<TableType>()
-
-function getMetaForDepth(depth: number): TableType | undefined {
- const level = displayLevels.value[depth]
- if (!level?.fk_model_id) return undefined
- const baseId = meta.value?.base_id
- const metaKey = `${baseId}:${level.fk_model_id}`
- return metas.value?.[metaKey] as TableType | undefined
-}
-
-const expandedFormOnRowIdDlg = computed({
- get() {
- return !!route.query.rowId
- },
- set(val) {
- if (!val) {
- expandedFormMeta.value = undefined
- router.push({
- query: {
- ...route.query,
- rowId: undefined,
- },
- })
- }
- },
-})
-
-function expandForm(row: Row, state?: Record<string, any>) {
- const rowMeta = expandedFormMeta.value || meta.value
- const rowId = extractPkFromRow(row.row, rowMeta!.columns as ColumnType[])
- expandedFormRowState.value = state
-
- if (rowId && !isPublicView.value) {
- expandedFormRow.value = undefined
- router.push({
- query: {
- ...route.query,
- rowId,
- },
- })
- } else {
- expandedFormRow.value = row
- expandedFormDlg.value = true
- }
-}
-
-onExpandRow(async ({ row, depth }) => {
- let depthMeta = getMetaForDepth(depth)
- if (!depthMeta) {
- const level = displayLevels.value[depth]
- if (level?.fk_model_id) {
- const baseId = meta.value?.base_id
- depthMeta = (await getMeta(level.fk_model_id, false, false, baseId)) as TableType | undefined
- }
- }
- expandedFormMeta.value = depthMeta
-
- const rowObj: Row = {
- row: { ...row },
- oldRow: { ...row },
- rowMeta: {},
- }
- expandForm(rowObj)
-})
-
-onAddRow(async ({ depth, parentPk }) => {
- let depthMeta = getMetaForDepth(depth)
- if (!depthMeta) {
- const level = displayLevels.value[depth]
- if (level?.fk_model_id) {
- const baseId = meta.value?.base_id
- depthMeta = (await getMeta(level.fk_model_id, false, false, baseId)) as TableType | undefined
- }
- }
- if (!depthMeta) return
-
- expandedFormMeta.value = depthMeta
-
- const newRow: Row = {
- row: {},
- oldRow: {},
- rowMeta: { new: true },
- }
-
- if (parentPk !== undefined && depth > 0) {
- const parentLevel = displayLevels.value[depth - 1]
- let parentDepthMeta = getMetaForDepth(depth - 1)
- if (!parentDepthMeta && parentLevel?.fk_model_id) {
- parentDepthMeta = (await getMeta(parentLevel.fk_model_id, false, false, meta.value?.base_id)) as TableType | undefined
- }
-
- if (parentLevel?.fk_link_column_id && parentDepthMeta) {
- const hmCol = parentDepthMeta.columns?.find((c: ColumnType) => c.id === parentLevel.fk_link_column_id)
- if (hmCol) {
- const hmColOpt = hmCol.colOptions as LinkToAnotherRecordType
-
- const btCol = depthMeta.columns?.find((c: ColumnType) => {
- if (!isLinksOrLTAR(c)) return false
- const colOpt = c.colOptions as LinkToAnotherRecordType
- if (!colOpt) return false
- return (
- colOpt.fk_related_model_id === parentDepthMeta!.id &&
- (colOpt.type === RelationTypes.BELONGS_TO || colOpt.type === 'bt') &&
- colOpt.fk_child_column_id === hmColOpt.fk_child_column_id
- )
- })
-
- if (btCol?.title) {
- const parentPkCols = parentDepthMeta.columns?.filter((c: ColumnType) => c.pk) ?? []
- const parentPvCol = parentDepthMeta.columns?.find((c: ColumnType) => c.pv)
- const pkValues = parentPk.toString().split('___')
- const parentRowRef: Record<string, any> = {}
- parentPkCols.forEach((col: ColumnType, i: number) => {
- parentRowRef[col.title!] = pkValues[i] ?? parentPk
- })
- if (parentPvCol?.title && !(parentPvCol.title in parentRowRef)) {
- parentRowRef[parentPvCol.title] = parentPk
- }
-
- newRow.row[btCol.title] = parentRowRef
- expandedFormRowState.value = { [btCol.title]: parentRowRef }
- expandedFormRow.value = newRow
- expandedFormDlg.value = true
- return
- }
- }
- }
- }
-
- expandedFormRow.value = newRow
- expandedFormRowState.value = undefined
- expandedFormDlg.value = true
-})
-
-const activeCellStyle = computed(() => {
- if (!activeCell.value) return {}
- return {
- position: 'absolute' as const,
- top: `${activeCell.value.y}px`,
- left: `${activeCell.value.x}px`,
- width: `${activeCell.value.width}px`,
- height: `${activeCell.value.height}px`,
- zIndex: 10,
- }
-})
-
-function onCellValueUpdate(val: any) {
- if (!activeCell.value || !activeCellRow.value) return
- activeCellRow.value.row[activeCell.value.column.title] = val
-}
-
-let pendingSave: {
- cell: typeof activeCell.value
- row: Row
-} | null = null
-
-watch(activeCell, (newVal, oldVal) => {
- if (oldVal && activeCellRow.value) {
- pendingSave = {
- cell: { ...oldVal },
- row: JSON.parse(JSON.stringify(activeCellRow.value)),
- }
- savePendingCell()
- }
-
- if (newVal) {
- activeCellRow.value = {
- row: { ...newVal.row },
- oldRow: { ...newVal.row },
- rowMeta: {},
- }
- } else {
- activeCellRow.value = null
- }
-})
-
-async function onVirtualCellSave(rowObj: Row, property: string) {
- if (!activeCell.value) return
- await saveRowProperty(activeCell.value, rowObj, property)
-}
-
-async function onCellSave() {
- if (!activeCell.value || !activeCellRow.value) return
- await saveRowProperty(activeCell.value, activeCellRow.value, activeCell.value.column.title)
-}
-
-async function saveRowProperty(cell: NonNullable<typeof activeCell.value>, rowObj: Row, property: string) {
- const newVal = rowObj.row[property]
- const oldVal = rowObj.oldRow[property]
-
- if (newVal === oldVal) return
-
- const depthMeta = getMetaForDepth(cell.depth)
- if (!depthMeta) return
-
- const rowId = extractPkFromRow(rowObj.row, depthMeta.columns as ColumnType[])
- if (!rowId) return
-
- try {
- const updatedRowData = await $api.dbTableRow.update(
- NOCO,
- depthMeta.base_id as string,
- depthMeta.id as string,
- encodeURIComponent(rowId),
- {
- [property]: newVal ?? null,
- },
- )
-
- const cached = cachedRows.value.get(cell.rowIndex)
- if (cached) {
- Object.assign(cached, updatedRowData)
- triggerRefreshCanvas()
- }
- } catch (e: any) {
- message.error(await extractSdkResponseErrorMsg(e))
- }
-}
-
-async function savePendingCell() {
- const save = pendingSave
- pendingSave = null
- if (!save?.cell || !save?.row) return
-
- await saveRowProperty(save.cell!, save.row, save.cell!.column.title)
-}
-</script>
-
<template>
- <div ref="wrapperRef" class="flex flex-col w-full h-full nc-outline-view-wrapper bg-nc-bg-gray-extralight">
- <div v-if="!isConfigured" class="flex flex-col items-center justify-center h-full gap-6 p-8">
- <GeneralIcon class="text-nc-content-orange-dark w-16 h-16" icon="alertTriangleSolid" />
- <div class="text-xl font-semibold text-nc-content-gray">Hierarchy Not Configured</div>
- <div class="text-sm text-nc-content-gray-muted">
- Use <span class="font-medium text-nc-content-gray">Set Levels</span> in the toolbar to configure your outline view
- hierarchy.
- </div>
- </div>
-
- <template v-else>
- <Scroller
- ref="scroller"
- class="relative flex-1"
- :scroll-height="totalHeight"
- :scroll-width="totalWidth"
- :height="height"
- :width="width"
- :inset="50"
- @scroll="handleScroll"
- >
- <div
- class="sticky top-0 left-0"
- :style="{
- height: `${totalHeight}px`,
- width: `${totalWidth}px`,
- }"
- >
- <Teleport to="body">
- <Transition name="tooltip">
- <Tooltip v-if="tooltipStore.tooltipText" ref="tooltipRef" :tooltip-style="floatingStyles" />
- </Transition>
- </Teleport>
- <NcDropdown
- v-model:visible="isContextMenuOpen"
- :trigger="['contextmenu']"
- overlay-class-name="nc-dropdown-grid-context-menu"
- >
- <canvas
- ref="canvasRef"
- class="sticky top-0 left-0"
- :height="`${height}px`"
- :width="`${width}px`"
- oncontextmenu="return false"
- @mousedown="handleCanvasMouseDown"
- @click="handleCanvasClick"
- @mousemove="handleCanvasMouseMove"
- @mouseleave="handleCanvasMouseLeave"
- />
- <template #overlay>
- <NcMenu>
- <NcMenuItem> This is context menu </NcMenuItem>
- </NcMenu>
- </template>
- </NcDropdown>
-
- <div
- v-if="activeCell && activeCellRow"
- :style="activeCellStyle"
- class="nc-outline-active-cell pointer-events-auto rounded bg-nc-bg-default"
- >
- <SmartsheetRow :row="activeCellRow">
- <template #default>
- <SmartsheetVirtualCell
- v-if="isVirtualCol(activeCell.column.columnObj)"
- v-model="activeCellRow.row[activeCell.column.title]"
- :column="activeCell.column.columnObj"
- :row="activeCellRow"
- active
- @save="onVirtualCellSave"
- />
- <SmartsheetCell
- v-else
- :model-value="activeCellRow.row[activeCell.column.title]"
- :column="activeCell.column.columnObj"
- active
- edit-enabled
- @update:model-value="onCellValueUpdate"
- @save="onCellSave"
- />
- </template>
- </SmartsheetRow>
- </div>
- </div>
- </Scroller>
- </template>
- </div>
-
- <Suspense>
- <LazySmartsheetExpandedForm
- v-if="expandedFormRow && expandedFormDlg"
- v-model="expandedFormDlg"
- :row="expandedFormRow"
- :load-row="!isPublicView"
- :state="expandedFormRowState"
- :meta="expandedFormMeta || meta"
- use-meta-fields
- />
- </Suspense>
- <Suspense>
- <LazySmartsheetExpandedForm
- v-if="expandedFormOnRowIdDlg && (expandedFormMeta?.id || meta?.id)"
- v-model="expandedFormOnRowIdDlg"
- :row="expandedFormRow ?? { row: {}, oldRow: {}, rowMeta: {} }"
- :meta="expandedFormMeta || meta"
- :load-row="!isPublicView"
- :row-id="route.query.rowId"
- :expand-form="expandForm"
- use-meta-fields
- />
- </Suspense>
+ <NcSpanHidden />
</template>
-
-<style scoped lang="scss">
-:deep(.custom-scrollbar-track.vertical) {
- bottom: 4px;
-}
-:deep(.custom-scrollbar-track.horizontal) {
- bottom: 4px;
-}
-.nc-outline-active-cell {
- box-shadow: 0px 0px 1px rgba(0, 0, 0, 0.32), 0px 0px 3px rgba(0, 0, 0, 0.11), 0px 1px 4px rgba(0, 0, 0, 0.12);
- border: 1px solid var(--nc-border-gray-medium);
- display: flex;
- align-items: center;
- padding: 0 8px;
- overflow: hidden;
-}
-</style>
diff --git a/packages/nc-gui/components/smartsheet/toolbar/Outline/LevelSelector.vue b/packages/nc-gui/components/smartsheet/toolbar/Outline/LevelSelector.vue
index f3992318ce..7c3f5c658a 100644
--- a/packages/nc-gui/components/smartsheet/toolbar/Outline/LevelSelector.vue
+++ b/packages/nc-gui/components/smartsheet/toolbar/Outline/LevelSelector.vue
@@ -1,35 +1,3 @@
-<script setup lang="ts">
-const { levels, selectedLevelId, setSelectedLevel } = useOutlineViewStoreOrThrow()
-
-const meta = inject(MetaInj, ref())
-const { getMetaByKey } = useMetas()
-
-function getTableTitle(tableId?: string) {
- if (!tableId) return 'Unknown'
- const baseId = meta.value?.base_id
- const tableMeta = getMetaByKey(baseId, tableId)
- return tableMeta?.title || 'Unknown'
-}
-</script>
-
<template>
- <div v-if="levels.length > 0" class="flex items-center gap-1">
- <div
- v-for="(level, index) in levels"
- :key="level.id || index"
- class="flex items-center gap-1 px-2 selector-level py-1 overflow-hidden rounded-md text-xs font-medium cursor-pointer transition-colors"
- :class="{
- 'bg-nc-bg-brand text-nc-content-brand': selectedLevelId === level.id,
- 'bg-nc-bg-gray-light text-nc-content-gray-muted hover:bg-nc-bg-gray-medium': selectedLevelId !== level.id,
- 'level-two': levels.length === 2,
- 'level-three': levels.length === 3,
- }"
- @click="setSelectedLevel(level.id ?? null)"
- >
- <NcTooltip show-on-truncate-only class="truncate">
- Level {{ index + 1 }} - {{ getTableTitle(level.fk_model_id) }}
- <template #title> Level {{ index + 1 }} - {{ getTableTitle(level.fk_model_id) }} </template>
- </NcTooltip>
- </div>
- </div>
+ <NcSpanHidden />
</template>
diff --git a/packages/nc-gui/components/smartsheet/toolbar/Outline/SetLevels.vue b/packages/nc-gui/components/smartsheet/toolbar/Outline/SetLevels.vue
index 714d958486..7c3f5c658a 100644
--- a/packages/nc-gui/components/smartsheet/toolbar/Outline/SetLevels.vue
+++ b/packages/nc-gui/components/smartsheet/toolbar/Outline/SetLevels.vue
@@ -1,331 +1,3 @@
-<script setup lang="ts">
-import type { ColumnType, LinkToAnotherRecordType, OutlineViewLevelType, TableType } from 'nocodb-sdk'
-import { RelationTypes, isLinksOrLTAR } from 'nocodb-sdk'
-
-const meta = inject(MetaInj, ref())
-
-const isPublic = inject(IsPublicInj, ref(false))
-
-const isLocked = inject(IsLockedInj, ref(false))
-
-const isToolbarIconMode = inject(
- IsToolbarIconMode,
- computed(() => false),
-)
-
-const { eventBus } = useSmartsheetStoreOrThrow()
-
-const { levels, saveLevelConfiguration, showEmptyParents, updateViewMeta, isLoading } = useOutlineViewStoreOrThrow()
-
-const open = ref(false)
-
-useMenuCloseOnEsc(open)
-
-const localLevels = ref<Partial<OutlineViewLevelType>[]>([])
-
-watch(open, (val) => {
- if (val) {
- if (levels.value.length > 0) {
- localLevels.value = levels.value.map((l) => ({ ...l }))
- } else {
- localLevels.value = [{ level: 0, fk_model_id: meta.value?.id }]
- }
- }
-})
-
-const displayOrder = computed(() => {
- return localLevels.value.map((_, i) => i).reverse()
-})
-
-const canAddLevel = computed(() => {
- if (localLevels.value.length >= 3) return false
- if (localLevels.value.length === 0) return true
-
- return localLevels.value.every((level, idx) => {
- if (!level.fk_model_id) return false
- return !(idx > 0 && !level.fk_link_column_id)
- })
-})
-
-function filterTableForLevel(arrayIndex: number): (table: TableType) => boolean {
- return (table: TableType) => {
- const sourceId = meta.value?.source_id
- if (sourceId && table.source_id !== sourceId) return false
-
- const usedTableIds = new Set(
- localLevels.value
- .filter((_, i) => i !== arrayIndex)
- .map((l) => l.fk_model_id)
- .filter(Boolean),
- )
- return !usedTableIds.has(table.id!)
- }
-}
-
-// Filter: only HM link columns pointing to the target table (level below)
-function filterLinkColumnForLevel(targetTableId: string | undefined) {
- return (c: ColumnType) => {
- if (!isLinksOrLTAR(c) || c.system) return false
- const colOptions = c.colOptions as LinkToAnotherRecordType | undefined
- if (!colOptions) return false
- if (colOptions.type !== RelationTypes.HAS_MANY) return false
- if (targetTableId && colOptions.fk_related_model_id !== targetTableId) return false
- return true
- }
-}
-
-function onTableSelect(arrayIndex: number, tableId: string | null | undefined) {
- if (!tableId) return
- localLevels.value[arrayIndex].fk_model_id = tableId
- localLevels.value[arrayIndex].fk_link_column_id = undefined
-}
-
-function addLevel() {
- if (!canAddLevel.value) return
- localLevels.value.push({ level: localLevels.value.length })
-}
-
-function removeLevel(arrayIndex: number) {
- if (arrayIndex === 0) return
- localLevels.value.splice(arrayIndex, 1)
- localLevels.value.forEach((l, i) => {
- l.level = i
- })
-}
-
-async function save() {
- if (isLocked.value) return
-
- try {
- const cleanedLevels = localLevels.value.map((l) => {
- const clean: Partial<OutlineViewLevelType> = {
- level: l.level,
- fk_model_id: l.fk_model_id,
- }
- if (l.fk_link_column_id) clean.fk_link_column_id = l.fk_link_column_id
- if (l.fk_self_link_column_id) clean.fk_self_link_column_id = l.fk_self_link_column_id
- if (l.wrap_headers != null) clean.wrap_headers = l.wrap_headers
- if (l.enable_nested_records != null) clean.enable_nested_records = l.enable_nested_records
- return clean
- })
-
- await saveLevelConfiguration({
- levels: cleanedLevels as OutlineViewLevelType[],
- })
-
- await nextTick()
-
- if (levels.value.length > 0) {
- localLevels.value = levels.value.map((l) => ({ ...l }))
- }
-
- eventBus.emit(SmartsheetStoreEvents.FIELD_RELOAD)
- eventBus.emit(SmartsheetStoreEvents.SORT_RELOAD)
- eventBus.emit(SmartsheetStoreEvents.FILTER_RELOAD)
- } catch (e) {
- message.error(await extractSdkResponseErrorMsg(e))
- }
-}
-
-async function toggleHideEmptySections(val: boolean) {
- if (isLocked.value) return
- await updateViewMeta({ show_empty_parents: !val })
-}
-
-const hideEmptySections = computed({
- get: () => !showEmptyParents.value,
- set: (val: boolean) => {
- toggleHideEmptySections(val)
- },
-})
-
-const isConfigValid = computed(() => {
- if (localLevels.value.length === 0) return false
- return localLevels.value.every((level, idx) => {
- if (!level.fk_model_id) return false
- if (idx > 0 && !level.fk_link_column_id) return false
- return true
- })
-})
-
-const isDirty = computed(() => {
- return JSON.stringify(localLevels.value) !== JSON.stringify(levels.value.map((l) => ({ ...l })))
-})
-</script>
-
<template>
- <NcDropdown
- v-if="!isPublic"
- v-model:visible="open"
- :trigger="['click']"
- overlay-class-name="nc-dropdown-outline-set-levels-menu overflow-hidden"
- class="!xs:hidden"
- >
- <NcTooltip :disabled="!isToolbarIconMode" class="nc-outline-set-levels-btn">
- <template #title>
- {{ $t('title.setLevels') }}
- </template>
-
- <NcButton
- v-e="['c:outline:set-levels']"
- class="nc-outline-set-levels-menu-btn nc-toolbar-btn !border-0 !h-7 group"
- size="small"
- type="secondary"
- :show-as-disabled="isLocked"
- >
- <div class="flex items-center gap-2">
- <GeneralIcon icon="layers" class="h-4 w-4" />
- <div v-if="!isToolbarIconMode" class="flex items-center gap-0.5">
- <span class="text-capitalize !text-[13px] font-medium">
- {{ $t('title.setLevels') }}
- </span>
- <div
- v-if="levels.length > 0"
- class="flex items-center rounded-md transition-colors duration-0.3s bg-nc-bg-gray-light px-1 min-h-5"
- :class="{
- 'group-hover:bg-nc-bg-gray-medium': !isLocked,
- }"
- >
- <span class="!text-[13px] font-medium !leading-5">{{ levels.length }}</span>
- </div>
- </div>
- </div>
- </NcButton>
- </NcTooltip>
-
- <template #overlay>
- <div v-if="open" class="p-4 w-96 bg-nc-bg-default nc-table-toolbar-menu rounded-lg flex flex-col gap-4" @click.stop>
- <div class="flex items-center justify-between">
- <span class="text-sm font-semibold text-nc-content-gray">
- {{ $t('title.levels') }}
- </span>
- <NcButton
- v-if="localLevels.length < 3"
- type="text"
- size="xs"
- class="!text-nc-content-gray-subtle !text-xs"
- :disabled="isLocked"
- @click="addLevel"
- >
- <div
- :class="{
- 'text-nc-content-gray-disabled': isLocked || !canAddLevel,
- }"
- class="flex items-center gap-1"
- >
- <GeneralIcon icon="plus" class="w-3.5 h-3.5" />
- <span>{{ $t('general.addLevelAbove') }}</span>
- </div>
- </NcButton>
- </div>
-
- <div class="border-t border-nc-border-gray-medium" />
- <div class="flex flex-col">
- <template v-for="(arrIdx, displayIdx) in displayOrder" :key="arrIdx">
- <div class="flex flex-col gap-2 p-3 rounded-lg border border-nc-border-gray-medium">
- <div class="flex items-center justify-between">
- <span class="text-[11px] font-semibold text-nc-content-gray-muted uppercase tracking-wide">
- {{ $t('general.levelN', { n: arrIdx + 1 }) }}
- </span>
- <NcTooltip v-if="arrIdx === 0">
- <template #title>
- {{ $t('tooltip.levelOneTable') }}
- </template>
- <GeneralIcon icon="info" class="w-3.5 h-3.5 text-nc-content-gray-muted" />
- </NcTooltip>
- <NcButton
- v-else
- type="text"
- size="xxs"
- class="!text-nc-content-gray-muted hover:!text-nc-content-red-dark"
- :disabled="isLocked"
- @click="removeLevel(arrIdx)"
- >
- <GeneralIcon icon="close" class="w-3.5 h-3.5" />
- </NcButton>
- </div>
-
- <!-- Table selection -->
- <NcListTableSelector
- disable-label
- :value="localLevels[arrIdx].fk_model_id"
- :disabled="isLocked || arrIdx === 0"
- :filter-table="filterTableForLevel(arrIdx)"
- @update:value="(val) => onTableSelect(arrIdx, val)"
- />
- </div>
-
- <!-- Link connector between levels (dashed line + link field selector) -->
- <div v-if="displayIdx < displayOrder.length - 1" class="nc-level-connector flex items-stretch ml-7">
- <div class="w-0 border-l-2 border-dashed border-nc-border-gray-medium" />
- <div class="py-2 pl-4 flex-1">
- <NcListColumnSelector
- disable-label
- :table-id="localLevels[arrIdx]?.fk_model_id"
- :value="localLevels[arrIdx].fk_link_column_id"
- :disabled="isLocked || !localLevels[arrIdx]?.fk_model_id || !localLevels[arrIdx - 1]?.fk_model_id"
- :filter-column="filterLinkColumnForLevel(localLevels[arrIdx - 1]?.fk_model_id)"
- @update:value="
- (val) => {
- localLevels[arrIdx].fk_link_column_id = val
- }
- "
- />
- </div>
- </div>
- </template>
- </div>
-
- <!-- Enable nested records (for root level) -->
- <!--
- <template v-if="localLevels.length > 0">
- <div class="flex items-center gap-1">
- <NcSwitch v-model:checked="enableNestedRecords" size="small" class="nc-switch" :disabled="isLocked">
- <div class="text-sm text-nc-content-gray">
- {{ $t('labels.enableNestedRecords') || 'Enable nested records' }}
- </div>
- </NcSwitch>
- </div>
-
- <div v-if="enableNestedRecords" class="nc-level-connector flex items-stretch ml-7">
- <div class="w-0 border-l-2 border-dashed border-nc-border-gray-medium" />
- <div class="py-2 pl-4 flex-1">
- <NcListColumnSelector
- disable-label
- :table-id="localLevels[0]?.fk_model_id"
- :value="localLevels[0]?.fk_self_link_column_id"
- :disabled="isLocked"
- :filter-column="filterSelfLinkColumn"
- @update:value="(val) => { if (localLevels[0]) localLevels[0].fk_self_link_column_id = val }"
- />
- </div>
- </div>
- </template>
- -->
-
- <!-- Save button (visible when dirty) -->
- <NcButton
- v-if="isDirty"
- type="primary"
- size="small"
- class="w-full"
- :loading="isLoading"
- :disabled="isLocked || !isConfigValid"
- @click="save"
- >
- {{ $t('general.save') || 'Save' }}
- </NcButton>
-
- <!-- <div class="flex items-center gap-1 pt-1">
- <NcSwitch v-model:checked="hideEmptySections" size="small" class="nc-switch" :disabled="isLocked">
- <div class="text-sm text-nc-content-gray">
- {{ $t('labels.hideEmptySections') || 'Hide empty sections' }}
- </div>
- </NcSwitch>
- </div> -->
-
- <GeneralLockedViewFooter v-if="isLocked" class="-mb-4 -mx-4" @on-open="open = false" />
- </div>
- </template>
- </NcDropdown>
+ <NcSpanHidden />
</template>
diff --git a/packages/nc-gui/composables/useOutlineViewStore.ts b/packages/nc-gui/composables/useOutlineViewStore.ts
index b5052e54a3..c5361fab1a 100644
--- a/packages/nc-gui/composables/useOutlineViewStore.ts
+++ b/packages/nc-gui/composables/useOutlineViewStore.ts
@@ -1,5 +1,4 @@
-import type { OutlineType, OutlineViewLevelType, TableType, ViewType } from 'nocodb-sdk'
-import { ViewTypes } from 'nocodb-sdk'
+import type { TableType, ViewType } from 'nocodb-sdk'
export interface OutlineViewRow {
__nc_depth: number
@@ -11,135 +10,23 @@ export interface OutlineViewRow {
}
const [useProvideOutlineViewStore, useOutlineViewStore] = useInjectionState(
- (meta: Ref<TableType | undefined>, viewMeta: Ref<ViewType | undefined>) => {
- const { updateViewMeta: _updateViewMeta } = useViewsStore()
- const selectedLevelId = ref<string | null>(null)
-
- const viewId = computed(() => viewMeta.value?.id)
-
- const outlineMetaData = computed<OutlineType | undefined>(() => {
- return viewMeta.value?.view as OutlineType | undefined
- })
-
- const levels = computed<OutlineViewLevelType[]>(() => {
- return outlineMetaData.value?.levels || []
- })
-
- const isConfigured = computed(() => levels.value.length >= 1)
-
- const showEmptyParents = computed(() => {
- return outlineMetaData.value?.show_empty_parents !== false
- })
-
- const selectedLevel = computed<OutlineViewLevelType | undefined>(() => {
- if (!selectedLevelId.value) return levels.value[0]
- return levels.value.find((l) => l.id === selectedLevelId.value)
- })
-
- // Display levels: reversed so highest level = depth 0
- const displayLevels = computed(() => [...levels.value].reverse())
-
- // Map model ID -> depth index in displayLevels
- const modelIdToDepth = computed<Record<string, number>>(() => {
- const map: Record<string, number> = {}
- displayLevels.value.forEach((level, idx) => {
- if (level.fk_model_id) map[level.fk_model_id] = idx
- })
- return map
- })
-
- // Map depth index -> level ID
- const depthToLevelId = computed<Record<number, string>>(() => {
- const map: Record<number, string> = {}
- displayLevels.value.forEach((level, depth) => {
- if (level.id) map[depth] = level.id
- })
- return map
- })
-
- const collapsedParents = ref<Record<number, string[]>>({})
-
- function setSelectedLevel(levelId: string | null) {
- selectedLevelId.value = levelId
- }
-
- function toggleCollapse(depth: number, pk: string) {
- const current = { ...collapsedParents.value }
- const arr = current[depth] ? [...current[depth]] : []
- const idx = arr.indexOf(pk)
- if (idx >= 0) {
- arr.splice(idx, 1)
- } else {
- arr.push(pk)
- }
- current[depth] = arr
- collapsedParents.value = current
- }
-
- function isCollapsed(depth: number, pk: string): boolean {
- return collapsedParents.value[depth]?.includes(pk) ?? false
- }
-
- async function saveLevelConfiguration(config: { levels: OutlineViewLevelType[] }) {
- if (!viewId.value) return
-
- try {
- await _updateViewMeta(viewId.value, ViewTypes.OUTLINE, {
- levels: config.levels,
- })
- } catch (e) {
- throw e
- }
- }
-
- /** Update view meta (show_empty_parents, etc.) */
- async function updateViewMeta(updates: Partial<OutlineType>) {
- if (!viewId.value) return
-
- try {
- await _updateViewMeta(viewId.value, ViewTypes.OUTLINE, updates)
- } catch (e) {
- throw e
- }
- }
-
- watch(
- levels,
- (newLevels) => {
- if (newLevels.length > 0 && !newLevels.find((l) => l.id === selectedLevelId.value)) {
- selectedLevelId.value = newLevels[0]?.id ?? null
- } else if (newLevels.length === 0) {
- selectedLevelId.value = null
- }
- },
- { immediate: true },
- )
-
- onMounted(async () => {
- await waitForCondition(() => levels.value?.length, 100)
- if (levels.value.length > 0 && !levels.value.find((l) => l.id === selectedLevelId.value)) {
- selectedLevelId.value = levels.value[0]?.id ?? null
- } else if (levels.value.length === 0) {
- selectedLevelId.value = null
- }
- })
-
+ (_meta: Ref<TableType | undefined>, _viewMeta: Ref<ViewType | undefined>) => {
return {
- levels,
- isConfigured,
- showEmptyParents,
- selectedLevelId,
- selectedLevel,
- setSelectedLevel,
- outlineMetaData,
- displayLevels,
- modelIdToDepth,
- depthToLevelId,
- collapsedParents,
- toggleCollapse,
- isCollapsed,
- saveLevelConfiguration,
- updateViewMeta,
+ levels: computed(() => []),
+ isConfigured: computed(() => false),
+ showEmptyParents: computed(() => false),
+ selectedLevelId: ref<string | null>(null),
+ selectedLevel: computed(() => undefined),
+ setSelectedLevel: (_levelId: string | null) => {},
+ outlineMetaData: computed(() => undefined),
+ displayLevels: computed(() => []),
+ modelIdToDepth: computed(() => ({})),
+ depthToLevelId: computed(() => ({})),
+ collapsedParents: ref<Record<number, string[]>>({}),
+ toggleCollapse: (_depth: number, _pk: string) => {},
+ isCollapsed: (_depth: number, _pk: string) => false,
+ saveLevelConfiguration: async (_config: { levels: any[] }) => {},
+ updateViewMeta: async (_updates: Record<string, any>) => {},
}
},
'outlineView',