Compare commits

...

2 Commits

Author SHA1 Message Date
johnnyfish
d30a735abb feat: add toggle to group tables by area or schema in sidebar 2025-08-01 14:49:39 +03:00
johnnyfish
901b1ccd4a refactor: consolidate table filtering to canvas filter with improved UX 2025-08-01 12:19:06 +03:00
40 changed files with 899 additions and 390 deletions

View File

@@ -1,4 +1,11 @@
import React, { type ReactNode, useCallback, useState } from 'react';
import React, {
type ReactNode,
useCallback,
useState,
useMemo,
useEffect,
useRef,
} from 'react';
import { canvasContext } from './canvas-context';
import { useChartDB } from '@/hooks/use-chartdb';
import {
@@ -15,13 +22,49 @@ interface CanvasProviderProps {
}
export const CanvasProvider = ({ children }: CanvasProviderProps) => {
const { tables, relationships, updateTablesState, filteredSchemas } =
useChartDB();
const {
tables,
relationships,
updateTablesState,
filteredSchemas,
hiddenTableIds,
schemas,
} = useChartDB();
const { fitView } = useReactFlow();
const [overlapGraph, setOverlapGraph] =
useState<Graph<string>>(createGraph());
// Check if there are any filtered items to determine initial showFilter state
const hasFilteredItems = useMemo(() => {
const hasHiddenTables = (hiddenTableIds ?? []).length > 0;
const hasSchemasFilter =
filteredSchemas &&
schemas.length > 0 &&
filteredSchemas.length < schemas.length;
return hasHiddenTables || hasSchemasFilter;
}, [filteredSchemas, hiddenTableIds, schemas]);
const [showFilter, setShowFilter] = useState(false);
const hasInitialized = useRef(false);
// Only auto-show filter on initial load if there are filtered items
// Wait for data to be defined (not just empty arrays) before initializing
useEffect(() => {
const dataLoaded =
filteredSchemas !== undefined && hiddenTableIds !== undefined;
if (!hasInitialized.current && dataLoaded) {
// Add 2 seconds delay to ensure all data is fully loaded
const timer = setTimeout(() => {
if (hasFilteredItems) {
setShowFilter(true);
}
hasInitialized.current = true;
}, 2000);
return () => clearTimeout(timer);
}
}, [hasFilteredItems, filteredSchemas, hiddenTableIds]);
const reorderTables = useCallback(
(

View File

@@ -285,6 +285,8 @@ export interface ChartDBContext {
hiddenTableIds?: string[];
addHiddenTableId: (tableId: string) => Promise<void>;
removeHiddenTableId: (tableId: string) => Promise<void>;
addHiddenTableIds: (tableIds: string[]) => Promise<void>;
removeHiddenTableIds: (tableIds: string[]) => Promise<void>;
}
export const chartDBContext = createContext<ChartDBContext>({
@@ -386,4 +388,6 @@ export const chartDBContext = createContext<ChartDBContext>({
hiddenTableIds: [],
addHiddenTableId: emptyFn,
removeHiddenTableId: emptyFn,
addHiddenTableIds: emptyFn,
removeHiddenTableIds: emptyFn,
});

View File

@@ -155,18 +155,16 @@ export const ChartDBProvider: React.FC<
return undefined;
}
const schemasFilterFromCache =
(schemasFilter[diagramId] ?? []).length === 0
? undefined // in case of empty filter, skip cache
: schemasFilter[diagramId];
const schemasFilterFromCache = schemasFilter[diagramId];
return (
schemasFilterFromCache ?? [
schemas.find((s) => s.name === defaultSchemaName)?.id ??
schemas[0]?.id,
]
);
}, [schemasFilter, diagramId, schemas, defaultSchemaName]);
// If there's an explicit filter set (even if empty), use it
if (schemasFilterFromCache !== undefined) {
return schemasFilterFromCache;
}
// Default to showing all schemas if no filter has been set
return schemas.map((s) => s.id);
}, [schemasFilter, diagramId, schemas]);
const currentDiagram: Diagram = useMemo(
() => ({
@@ -1750,25 +1748,81 @@ export const ChartDBProvider: React.FC<
const addHiddenTableId: ChartDBContext['addHiddenTableId'] = useCallback(
async (tableId: string) => {
if (!hiddenTableIds.includes(tableId)) {
setHiddenTableIds((prev) => [...prev, tableId]);
await hideTableForDiagram(diagramId, tableId);
}
setHiddenTableIds((prev) => {
if (!prev.includes(tableId)) {
hideTableForDiagram(diagramId, tableId);
return [...prev, tableId];
}
return prev;
});
},
[hiddenTableIds, diagramId, hideTableForDiagram]
[diagramId, hideTableForDiagram]
);
const removeHiddenTableId: ChartDBContext['removeHiddenTableId'] =
useCallback(
async (tableId: string) => {
if (hiddenTableIds.includes(tableId)) {
setHiddenTableIds((prev) =>
prev.filter((id) => id !== tableId)
setHiddenTableIds((prev) => {
if (prev.includes(tableId)) {
unhideTableForDiagram(diagramId, tableId);
return prev.filter((id) => id !== tableId);
}
return prev;
});
},
[diagramId, unhideTableForDiagram]
);
const addHiddenTableIds: ChartDBContext['addHiddenTableIds'] = useCallback(
async (tableIds: string[]) => {
if (tableIds.length === 0) return;
const newIds: string[] = [];
setHiddenTableIds((prev) => {
const toAdd = tableIds.filter((id) => !prev.includes(id));
newIds.push(...toAdd);
if (toAdd.length === 0) return prev;
return [...prev, ...toAdd];
});
// Batch update config for all tables after state update
if (newIds.length > 0) {
await Promise.all(
newIds.map((id) => hideTableForDiagram(diagramId, id))
);
}
},
[diagramId, hideTableForDiagram]
);
const removeHiddenTableIds: ChartDBContext['removeHiddenTableIds'] =
useCallback(
async (tableIds: string[]) => {
if (tableIds.length === 0) return;
const idsToRemove: string[] = [];
setHiddenTableIds((prev) => {
const toRemove = new Set(tableIds);
const filtered = prev.filter((id) => !toRemove.has(id));
if (filtered.length === prev.length) return prev;
// Collect IDs that need to be removed
idsToRemove.push(
...tableIds.filter((id) => prev.includes(id))
);
return filtered;
});
// Batch update config for all tables after state update
if (idsToRemove.length > 0) {
await Promise.all(
idsToRemove.map((id) =>
unhideTableForDiagram(diagramId, id)
)
);
await unhideTableForDiagram(diagramId, tableId);
}
},
[hiddenTableIds, diagramId, unhideTableForDiagram]
[diagramId, unhideTableForDiagram]
);
return (
@@ -1846,6 +1900,8 @@ export const ChartDBProvider: React.FC<
hiddenTableIds,
addHiddenTableId,
removeHiddenTableId,
addHiddenTableIds,
removeHiddenTableIds,
highlightCustomTypeId,
highlightedCustomType,
}}

View File

@@ -36,10 +36,6 @@ export interface LayoutContext {
hideSidePanel: () => void;
showSidePanel: () => void;
toggleSidePanel: () => void;
isSelectSchemaOpen: boolean;
openSelectSchema: () => void;
closeSelectSchema: () => void;
}
export const layoutContext = createContext<LayoutContext>({
@@ -70,8 +66,4 @@ export const layoutContext = createContext<LayoutContext>({
hideSidePanel: emptyFn,
showSidePanel: emptyFn,
toggleSidePanel: emptyFn,
isSelectSchemaOpen: false,
openSelectSchema: emptyFn,
closeSelectSchema: emptyFn,
});

View File

@@ -23,8 +23,6 @@ export const LayoutProvider: React.FC<React.PropsWithChildren> = ({
React.useState<SidebarSection>('tables');
const [isSidePanelShowed, setIsSidePanelShowed] =
React.useState<boolean>(isDesktop);
const [isSelectSchemaOpen, setIsSelectSchemaOpen] =
React.useState<boolean>(false);
const closeAllTablesInSidebar: LayoutContext['closeAllTablesInSidebar'] =
() => setOpenedTableInSidebar('');
@@ -88,11 +86,6 @@ export const LayoutProvider: React.FC<React.PropsWithChildren> = ({
setOpenedTableInSidebar(customTypeId);
};
const openSelectSchema: LayoutContext['openSelectSchema'] = () =>
setIsSelectSchemaOpen(true);
const closeSelectSchema: LayoutContext['closeSelectSchema'] = () =>
setIsSelectSchemaOpen(false);
return (
<layoutContext.Provider
value={{
@@ -108,9 +101,6 @@ export const LayoutProvider: React.FC<React.PropsWithChildren> = ({
hideSidePanel,
showSidePanel,
toggleSidePanel,
isSelectSchemaOpen,
openSelectSchema,
closeSelectSchema,
openedDependencyInSidebar,
openDependencyFromSidebar,
closeAllDependenciesInSidebar,

View File

@@ -22,11 +22,6 @@ export interface LocalConfigContext {
showFieldAttributes: boolean;
setShowFieldAttributes: (showFieldAttributes: boolean) => void;
hideMultiSchemaNotification: boolean;
setHideMultiSchemaNotification: (
hideMultiSchemaNotification: boolean
) => void;
githubRepoOpened: boolean;
setGithubRepoOpened: (githubRepoOpened: boolean) => void;
@@ -56,9 +51,6 @@ export const LocalConfigContext = createContext<LocalConfigContext>({
showFieldAttributes: true,
setShowFieldAttributes: emptyFn,
hideMultiSchemaNotification: false,
setHideMultiSchemaNotification: emptyFn,
githubRepoOpened: false,
setGithubRepoOpened: emptyFn,

View File

@@ -8,7 +8,6 @@ const scrollActionKey = 'scroll_action';
const schemasFilterKey = 'schemas_filter';
const showCardinalityKey = 'show_cardinality';
const showFieldAttributesKey = 'show_field_attributes';
const hideMultiSchemaNotificationKey = 'hide_multi_schema_notification';
const githubRepoOpenedKey = 'github_repo_opened';
const starUsDialogLastOpenKey = 'star_us_dialog_last_open';
const showDependenciesOnCanvasKey = 'show_dependencies_on_canvas';
@@ -40,12 +39,6 @@ export const LocalConfigProvider: React.FC<React.PropsWithChildren> = ({
(localStorage.getItem(showFieldAttributesKey) || 'true') === 'true'
);
const [hideMultiSchemaNotification, setHideMultiSchemaNotification] =
React.useState<boolean>(
(localStorage.getItem(hideMultiSchemaNotificationKey) ||
'false') === 'true'
);
const [githubRepoOpened, setGithubRepoOpened] = React.useState<boolean>(
(localStorage.getItem(githubRepoOpenedKey) || 'false') === 'true'
);
@@ -77,13 +70,6 @@ export const LocalConfigProvider: React.FC<React.PropsWithChildren> = ({
localStorage.setItem(githubRepoOpenedKey, githubRepoOpened.toString());
}, [githubRepoOpened]);
useEffect(() => {
localStorage.setItem(
hideMultiSchemaNotificationKey,
hideMultiSchemaNotification.toString()
);
}, [hideMultiSchemaNotification]);
useEffect(() => {
localStorage.setItem(themeKey, theme);
}, [theme]);
@@ -127,8 +113,6 @@ export const LocalConfigProvider: React.FC<React.PropsWithChildren> = ({
setShowCardinality,
showFieldAttributes,
setShowFieldAttributes,
hideMultiSchemaNotification,
setHideMultiSchemaNotification,
setGithubRepoOpened,
githubRepoOpened,
starUsDialogLastOpen,

View File

@@ -128,6 +128,8 @@ export const ar: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -129,6 +129,8 @@ export const bn: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -130,6 +130,8 @@ export const de: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -125,8 +125,14 @@ export const en = {
collapse: 'Collapse All',
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',
default_grouping: 'Default View',
group_by_schema: 'Group by Schema',
group_by_area: 'Group by Area',
no_area: 'No Area',
table: {
fields: 'Fields',
@@ -262,6 +268,15 @@ export const en = {
},
},
canvas_filter: {
title: 'Filter Tables',
search_placeholder: 'Search tables...',
default_grouping: 'Default View',
group_by_schema: 'Group by Schema',
group_by_area: 'Group by Area',
no_area: 'No Area',
},
toolbar: {
zoom_in: 'Zoom In',
zoom_out: 'Zoom Out',

View File

@@ -119,6 +119,8 @@ export const es: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -118,6 +118,8 @@ export const fr: LanguageTranslation = {
clear: 'Effacer le Filtre',
no_results:
'Aucune table trouvée correspondant à votre filtre.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
show_list: 'Afficher la Liste des Tableaux',
show_dbml: "Afficher l'éditeur DBML",

View File

@@ -129,6 +129,8 @@ export const gu: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -129,6 +129,8 @@ export const hi: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -126,6 +126,8 @@ export const hr: LanguageTranslation = {
clear: 'Očisti filter',
no_results:
'Nema pronađenih tablica koje odgovaraju vašem filteru.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
show_list: 'Prikaži popis tablica',
show_dbml: 'Prikaži DBML uređivač',

View File

@@ -128,6 +128,8 @@ export const id_ID: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -132,6 +132,8 @@ export const ja: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -128,6 +128,8 @@ export const ko_KR: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -131,6 +131,8 @@ export const mr: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -130,6 +130,9 @@ export const ne: LanguageTranslation = {
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
// TODO: Translate
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -129,6 +129,8 @@ export const pt_BR: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -127,6 +127,8 @@ export const ru: LanguageTranslation = {
no_results:
'Таблицы не найдены, соответствующие вашему фильтру.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
show_list: 'Переключиться на список таблиц',
show_dbml: 'Переключиться на редактор DBML',

View File

@@ -129,6 +129,8 @@ export const te: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -128,6 +128,8 @@ export const tr: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -127,6 +127,8 @@ export const uk: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -128,6 +128,8 @@ export const vi: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -125,6 +125,8 @@ export const zh_CN: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -125,6 +125,8 @@ export const zh_TW: LanguageTranslation = {
// TODO: Translate
clear: 'Clear Filter',
no_results: 'No tables found matching your filter.',
all_tables_filtered: 'All tables are filtered.',
open_filter: 'Open Filter',
// TODO: Translate
show_list: 'Show Table List',
show_dbml: 'Show DBML Editor',

View File

@@ -56,6 +56,7 @@ export const updateTablesParentAreas = (
areas: Area[]
): DBTable[] => {
return tables.map((table) => {
// Find containing area based on position
const containingArea = findContainingArea(table, areas);
const newParentAreaId = containingArea?.id || null;

View File

@@ -5,26 +5,37 @@ import React, {
useEffect,
useRef,
} from 'react';
import { X, Search, Eye, EyeOff, Database, Table, Funnel } from 'lucide-react';
import {
X,
Search,
Eye,
EyeOff,
Database,
Table,
Funnel,
Layers,
} from 'lucide-react';
import { useChartDB } from '@/hooks/use-chartdb';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/button/button';
import { Input } from '@/components/input/input';
import { shouldShowTableSchemaBySchemaFilter } from '@/lib/domain/db-table';
import { schemaNameToSchemaId } from '@/lib/domain/db-schema';
import { databasesWithSchemas } from '@/lib/domain/db-schema';
import { defaultSchemas } from '@/lib/data/default-schemas';
import { useReactFlow } from '@xyflow/react';
import { TreeView } from '@/components/tree-view/tree-view';
import type { TreeNode } from '@/components/tree-view/tree';
import { ScrollArea } from '@/components/scroll-area/scroll-area';
import { ToggleGroup, ToggleGroupItem } from '@/components/toggle/toggle-group';
export interface CanvasFilterProps {
onClose: () => void;
}
type NodeType = 'schema' | 'table';
type NodeType = 'schema' | 'table' | 'area';
type SchemaContext = { name: string };
type AreaContext = { id: string; name: string };
type TableContext = {
tableSchema?: string | null;
hidden: boolean;
@@ -32,6 +43,7 @@ type TableContext = {
type NodeContext = {
schema: SchemaContext;
area: AreaContext;
table: TableContext;
};
@@ -49,14 +61,22 @@ export const CanvasFilter: React.FC<CanvasFilterProps> = ({ onClose }) => {
hiddenTableIds,
addHiddenTableId,
removeHiddenTableId,
addHiddenTableIds,
removeHiddenTableIds,
filteredSchemas,
filterSchemas,
areas,
} = useChartDB();
const { fitView, setNodes } = useReactFlow();
const [searchQuery, setSearchQuery] = useState('');
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
const [isFilterVisible, setIsFilterVisible] = useState(false);
const [groupBy, setGroupBy] = useState<'schema' | 'area'>('schema');
const searchInputRef = useRef<HTMLInputElement>(null);
const supportsSchemas = useMemo(
() => databasesWithSchemas.includes(databaseType),
[databaseType]
);
const hasAreas = useMemo(() => areas.length > 0, [areas]);
// Extract only the properties needed for tree data
const relevantTableData = useMemo<RelevantTableData[]>(
@@ -71,6 +91,179 @@ export const CanvasFilter: React.FC<CanvasFilterProps> = ({ onClose }) => {
// Convert tables to tree nodes
const treeData = useMemo(() => {
if (groupBy === 'area' && hasAreas) {
// Group tables by area
const tablesByArea = new Map<string, RelevantTableData[]>();
const tablesWithoutArea: RelevantTableData[] = [];
// Create a map of area id to area
const areaMap = areas.reduce(
(acc, area) => {
acc[area.id] = area;
return acc;
},
{} as Record<string, (typeof areas)[0]>
);
// Create table lookup map for O(1) access
const tableMap = new Map(tables.map((t) => [t.id, t]));
// Include ALL tables, not just visible ones
relevantTableData.forEach((table) => {
const tableData = tableMap.get(table.id);
// Tables should stay in their areas regardless of visibility
if (
tableData?.parentAreaId &&
areaMap[tableData.parentAreaId]
) {
const areaId = tableData.parentAreaId;
if (!tablesByArea.has(areaId)) {
tablesByArea.set(areaId, []);
}
tablesByArea.get(areaId)!.push(table);
} else {
tablesWithoutArea.push(table);
}
});
// Sort tables within each area
tablesByArea.forEach((tables) => {
tables.sort((a, b) => a.name.localeCompare(b.name));
});
tablesWithoutArea.sort((a, b) => a.name.localeCompare(b.name));
// Convert to tree nodes
const nodes: TreeNode<NodeType, NodeContext>[] = [];
// Sort all areas by order or name (including empty ones)
const sortedAreas = areas.sort((a, b) => {
if (a.order !== undefined && b.order !== undefined) {
return a.order - b.order;
}
return a.name.localeCompare(b.name);
});
sortedAreas.forEach((area) => {
// Get all tables for this area from our mapping
const areaTables = tablesByArea.get(area.id) || [];
// Count all tables that belong to this area (including hidden ones)
const totalTablesInArea = tables.filter(
(t) => t.parentAreaId === area.id
).length;
// Always show the area if it has any tables
if (totalTablesInArea > 0 || areaTables.length > 0) {
// Get ALL tables that belong to this area (not just the visible ones)
const allTablesInThisArea = tables.filter(
(t) => t.parentAreaId === area.id
);
// Check if all tables in this area are hidden
const allTablesInAreaHidden =
allTablesInThisArea.length > 0 &&
allTablesInThisArea.every((table) =>
hiddenTableIds?.includes(table.id)
);
const areaNode: TreeNode<NodeType, NodeContext> = {
id: `area-${area.id}`,
name: `${area.name} (${totalTablesInArea})`,
type: 'area',
isFolder: true,
icon: Layers,
context: { id: area.id, name: area.name },
className: allTablesInAreaHidden ? 'text-gray-400' : '',
children: areaTables.map(
(table): TreeNode<NodeType, NodeContext> => {
const tableHidden =
hiddenTableIds?.includes(table.id) ?? false;
// If the parent area is hidden (all tables hidden), this table should appear gray too
const shouldAppearGray =
tableHidden || allTablesInAreaHidden;
return {
id: table.id,
name: table.name,
type: 'table',
isFolder: false,
icon: Table,
context: {
tableSchema: table.schema,
hidden: tableHidden,
},
className: shouldAppearGray
? 'text-gray-400'
: '',
};
}
),
};
nodes.push(areaNode);
}
});
// Add "No Area" group if there are tables without areas
// Count all tables that don't belong to any area (including hidden ones)
const totalTablesWithoutArea = tables.filter(
(t) => !t.parentAreaId
).length;
if (totalTablesWithoutArea > 0) {
// Get ALL tables without area (not just the visible ones)
const allTablesWithoutAreaList = tables.filter(
(t) => !t.parentAreaId
);
// Check if all tables without area are hidden
const allTablesWithoutAreaHidden =
allTablesWithoutAreaList.length > 0 &&
allTablesWithoutAreaList.every((table) =>
hiddenTableIds?.includes(table.id)
);
const noAreaNode: TreeNode<NodeType, NodeContext> = {
id: 'area-no-area',
name: `${t('canvas_filter.no_area')} (${totalTablesWithoutArea})`,
type: 'area',
isFolder: true,
icon: Layers,
context: {
id: 'no-area',
name: t('canvas_filter.no_area'),
},
className: allTablesWithoutAreaHidden
? 'text-gray-400'
: '',
children: tablesWithoutArea.map(
(table): TreeNode<NodeType, NodeContext> => {
const tableHidden =
hiddenTableIds?.includes(table.id) ?? false;
// If the parent area is hidden (all tables hidden), this table should appear gray too
const shouldAppearGray =
tableHidden || allTablesWithoutAreaHidden;
return {
id: table.id,
name: table.name,
type: 'table',
isFolder: false,
icon: Table,
context: {
tableSchema: table.schema,
hidden: tableHidden,
},
className: shouldAppearGray
? 'text-gray-400'
: '',
};
}
),
};
nodes.push(noAreaNode);
}
return nodes;
}
// Default schema grouping
// Group tables by schema
const tablesBySchema = new Map<string, RelevantTableData[]>();
@@ -92,10 +285,11 @@ export const CanvasFilter: React.FC<CanvasFilterProps> = ({ onClose }) => {
const nodes: TreeNode<NodeType, NodeContext>[] = [];
tablesBySchema.forEach((schemaTables, schemaName) => {
const schemaId = schemaNameToSchemaId(schemaName);
const schemaHidden = filteredSchemas
? !filteredSchemas.includes(schemaId)
: false;
// Pre-calculate if all tables in this schema are hidden
const allTablesHidden = schemaTables.every(
(table) => hiddenTableIds?.includes(table.id) ?? false
);
const schemaNode: TreeNode<NodeType, NodeContext> = {
id: `schema-${schemaName}`,
name: `${schemaName} (${schemaTables.length})`,
@@ -103,18 +297,11 @@ export const CanvasFilter: React.FC<CanvasFilterProps> = ({ onClose }) => {
isFolder: true,
icon: Database,
context: { name: schemaName },
className: schemaHidden ? 'opacity-50' : '',
className: allTablesHidden ? 'text-gray-400' : '',
children: schemaTables.map(
(table): TreeNode<NodeType, NodeContext> => {
const tableHidden =
hiddenTableIds?.includes(table.id) ?? false;
const visibleBySchema =
shouldShowTableSchemaBySchemaFilter({
tableSchema: table.schema,
filteredSchemas,
});
const hidden = tableHidden || !visibleBySchema;
return {
id: table.id,
name: table.name,
@@ -125,7 +312,7 @@ export const CanvasFilter: React.FC<CanvasFilterProps> = ({ onClose }) => {
tableSchema: table.schema,
hidden: tableHidden,
},
className: hidden ? 'opacity-50' : '',
className: tableHidden ? 'opacity-50' : '',
};
}
),
@@ -134,16 +321,36 @@ export const CanvasFilter: React.FC<CanvasFilterProps> = ({ onClose }) => {
});
return nodes;
}, [relevantTableData, databaseType, hiddenTableIds, filteredSchemas]);
}, [
relevantTableData,
databaseType,
hiddenTableIds,
groupBy,
hasAreas,
areas,
tables,
t,
]);
// Initialize expanded state with all schemas expanded
useMemo(() => {
const initialExpanded: Record<string, boolean> = {};
treeData.forEach((node) => {
initialExpanded[node.id] = true;
// Initialize expanded state - collapse if multiple schemas, expand if single schema (when grouping changes)
useEffect(() => {
setExpanded((prevExpanded) => {
const hasMultipleSchemas = treeData.length > 1;
const newExpanded: Record<string, boolean> = {};
treeData.forEach((node) => {
// Preserve existing expanded state if it exists, otherwise set based on schema count
if (node.id in prevExpanded) {
newExpanded[node.id] = prevExpanded[node.id];
} else {
// If there are multiple schemas, start collapsed; otherwise expanded
newExpanded[node.id] = !hasMultipleSchemas;
}
});
return newExpanded;
});
setExpanded(initialExpanded);
}, [treeData]);
}, [groupBy, treeData]);
// Filter tree data based on search query
const filteredTreeData: TreeNode<NodeType, NodeContext>[] = useMemo(() => {
@@ -219,44 +426,82 @@ export const CanvasFilter: React.FC<CanvasFilterProps> = ({ onClose }) => {
// Render component that's always visible (eye indicator)
const renderActions = useCallback(
(node: TreeNode<NodeType, NodeContext>) => {
if (node.type === 'schema') {
const schemaContext = node.context as SchemaContext;
const schemaId = schemaNameToSchemaId(schemaContext.name);
const schemaHidden = filteredSchemas
? !filteredSchemas.includes(schemaId)
: false;
if (node.type === 'area') {
const areaContext = node.context as AreaContext;
const areaId = areaContext.id;
// Find all tables that belong to this area (not just the visible ones)
const allTablesInArea =
areaId === 'no-area'
? tables.filter((table) => !table.parentAreaId)
: tables.filter(
(table) => table.parentAreaId === areaId
);
// Check if all tables in this area are hidden - use current state
const allHidden =
allTablesInArea.length > 0 &&
allTablesInArea.every((table) =>
hiddenTableIds?.includes(table.id)
);
return (
<Button
variant="ghost"
size="sm"
className="size-7 h-fit p-0"
onClick={(e) => {
disabled={allTablesInArea.length === 0}
onClick={async (e) => {
e.stopPropagation();
// unhide all tables in this schema
node.children?.forEach((child) => {
if (
child.type === 'table' &&
hiddenTableIds?.includes(child.id)
) {
removeHiddenTableId(child.id);
}
});
if (schemaHidden) {
filterSchemas([
...(filteredSchemas ?? []),
schemaId,
]);
// Toggle all tables in this area using bulk operations
const tableIds = allTablesInArea.map(
(table) => table.id
);
if (allHidden) {
await removeHiddenTableIds(tableIds);
} else {
filterSchemas(
filteredSchemas?.filter(
(s) => s !== schemaId
) ?? []
);
await addHiddenTableIds(tableIds);
}
}}
>
{schemaHidden ? (
{allHidden ? (
<EyeOff className="size-3.5 text-muted-foreground" />
) : (
<Eye className="size-3.5" />
)}
</Button>
);
}
if (node.type === 'schema') {
// Get all table IDs in this schema
const schemaTableIds =
node.children?.map((child) => child.id) || [];
// Check if all tables in this schema are hidden
const allTablesHidden =
schemaTableIds.length > 0 &&
schemaTableIds.every((id) => hiddenTableIds?.includes(id));
return (
<Button
variant="ghost"
size="sm"
className="size-7 h-fit p-0"
disabled={schemaTableIds.length === 0}
onClick={async (e) => {
e.stopPropagation();
if (allTablesHidden) {
// Show all tables in this schema
await removeHiddenTableIds(schemaTableIds);
} else {
// Hide all tables in this schema
await addHiddenTableIds(schemaTableIds);
}
}}
>
{allTablesHidden ? (
<EyeOff className="size-3.5 text-muted-foreground" />
) : (
<Eye className="size-3.5" />
@@ -268,9 +513,12 @@ export const CanvasFilter: React.FC<CanvasFilterProps> = ({ onClose }) => {
if (node.type === 'table') {
const tableId = node.id;
const tableContext = node.context as TableContext;
const hidden = tableContext.hidden;
const tableSchema = tableContext.tableSchema;
// Always use the current state directly
const isCurrentlyHidden =
hiddenTableIds?.includes(tableId) ?? false;
const visibleBySchema = shouldShowTableSchemaBySchemaFilter({
tableSchema,
filteredSchemas,
@@ -281,37 +529,17 @@ export const CanvasFilter: React.FC<CanvasFilterProps> = ({ onClose }) => {
variant="ghost"
size="sm"
className="size-7 h-fit p-0"
onClick={(e) => {
onClick={async (e) => {
e.stopPropagation();
if (!visibleBySchema && tableSchema) {
// Unhide schema and hide all other tables
const schemaId =
schemaNameToSchemaId(tableSchema);
filterSchemas([
...(filteredSchemas ?? []),
schemaId,
]);
const schemaNode = treeData.find(
(s) =>
(s.context as SchemaContext).name ===
tableSchema
);
if (schemaNode) {
schemaNode.children?.forEach((child) => {
if (
child.id !== tableId &&
!hiddenTableIds?.includes(child.id)
) {
addHiddenTableId(child.id);
}
});
}
} else {
toggleTableVisibility(tableId, !hidden);
}
// Simply toggle the table visibility using current state
await toggleTableVisibility(
tableId,
!isCurrentlyHidden
);
}}
disabled={groupBy === 'schema' && !visibleBySchema}
>
{hidden || !visibleBySchema ? (
{isCurrentlyHidden ? (
<EyeOff className="size-3.5 text-muted-foreground" />
) : (
<Eye className="size-3.5" />
@@ -325,18 +553,24 @@ export const CanvasFilter: React.FC<CanvasFilterProps> = ({ onClose }) => {
[
toggleTableVisibility,
filteredSchemas,
filterSchemas,
treeData,
hiddenTableIds,
addHiddenTableId,
removeHiddenTableId,
addHiddenTableIds,
removeHiddenTableIds,
tables,
groupBy,
]
);
// Handle node click
const handleNodeClick = useCallback(
(node: TreeNode<NodeType, NodeContext>) => {
if (node.type === 'table') {
if (node.type === 'schema' || node.type === 'area') {
// Toggle schema/area expansion on single click
setExpanded((prev) => ({
...prev,
[node.id]: !prev[node.id],
}));
} else if (node.type === 'table') {
const tableContext = node.context as TableContext;
const tableSchema = tableContext.tableSchema;
const visibleBySchema = shouldShowTableSchemaBySchemaFilter({
@@ -403,11 +637,48 @@ export const CanvasFilter: React.FC<CanvasFilterProps> = ({ onClose }) => {
className="h-full pl-9"
/>
</div>
{hasAreas && (
<div className="mt-2">
<ToggleGroup
type="single"
value={groupBy}
onValueChange={(value) => {
if (value)
setGroupBy(value as 'schema' | 'area');
}}
className="w-full justify-start"
>
<ToggleGroupItem
value="schema"
aria-label={
supportsSchemas
? 'Group by schema'
: 'Default'
}
className="h-8 flex-1 gap-1.5 text-xs"
>
<Database className="size-3.5" />
{supportsSchemas
? t('canvas_filter.group_by_schema')
: t('canvas_filter.default_grouping')}
</ToggleGroupItem>
<ToggleGroupItem
value="area"
aria-label="Group by area"
className="h-8 flex-1 gap-1.5 text-xs"
>
<Layers className="size-3.5" />
{t('canvas_filter.group_by_area')}
</ToggleGroupItem>
</ToggleGroup>
</div>
)}
</div>
{/* Table Tree */}
<ScrollArea className="flex-1 rounded-b-lg" type="auto">
<TreeView
key={`tree-${groupBy}-${JSON.stringify(hiddenTableIds?.sort() || [])}`}
data={filteredTreeData}
onNodeClick={handleNodeClick}
renderActionsComponent={renderActions}

View File

@@ -144,15 +144,48 @@ const tableToTableNode = (
};
};
const areaToAreaNode = (area: Area): AreaNodeType => ({
id: area.id,
type: 'area',
position: { x: area.x, y: area.y },
data: { area },
width: area.width,
height: area.height,
zIndex: -10,
});
const areaToAreaNode = (
area: Area,
tables: DBTable[],
hiddenTableIds?: string[],
filteredSchemas?: string[]
): AreaNodeType => {
// Check if all tables in this area are hidden
const tablesInArea = tables.filter(
(table) => table.parentAreaId === area.id
);
// Don't hide area if it has no tables (empty area)
if (tablesInArea.length === 0) {
return {
id: area.id,
type: 'area',
position: { x: area.x, y: area.y },
data: { area },
width: area.width,
height: area.height,
zIndex: -10,
hidden: false,
};
}
const allTablesHidden = tablesInArea.every(
(table) =>
hiddenTableIds?.includes(table.id) ||
!shouldShowTablesBySchemaFilter(table, filteredSchemas)
);
return {
id: area.id,
type: 'area',
position: { x: area.x, y: area.y },
data: { area },
width: area.width,
height: area.height,
zIndex: -10,
hidden: allTablesHidden,
};
};
export interface CanvasProps {
initialTables: DBTable[];
@@ -415,7 +448,14 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
},
};
}),
...areas.map(areaToAreaNode),
...areas.map((area) =>
areaToAreaNode(
area,
tables,
hiddenTableIds,
filteredSchemas
)
),
];
// Check if nodes actually changed

View File

@@ -1,4 +1,4 @@
import React, { useCallback, useState } from 'react';
import React, { useCallback, useState, useMemo } from 'react';
import { Card, CardContent } from '@/components/card/card';
import { ZoomIn, ZoomOut, Funnel, Redo, Undo, Scan } from 'lucide-react';
import { Separator } from '@/components/separator/separator';
@@ -30,12 +30,26 @@ export const Toolbar: React.FC<ToolbarProps> = () => {
const { getZoom, zoomIn, zoomOut, fitView } = useReactFlow();
const [zoom, setZoom] = useState<string>(convertToPercentage(getZoom()));
const { setShowFilter } = useCanvas();
const { hiddenTableIds } = useChartDB();
const { hiddenTableIds, filteredSchemas, schemas } = useChartDB();
const toggleFilter = useCallback(() => {
setShowFilter((prev) => !prev);
}, [setShowFilter]);
// Check if any filtering is active
const hasActiveFilter = useMemo(() => {
// Check if any tables are hidden
const hasHiddenTables = (hiddenTableIds ?? []).length > 0;
// Check if schemas are being filtered
const hasSchemasFilter =
filteredSchemas &&
schemas.length > 0 &&
filteredSchemas.length < schemas.length;
return hasHiddenTables || hasSchemasFilter;
}, [hiddenTableIds, filteredSchemas, schemas]);
useOnViewportChange({
onChange: ({ zoom }) => {
setZoom(convertToPercentage(zoom));
@@ -80,8 +94,7 @@ export const Toolbar: React.FC<ToolbarProps> = () => {
'transition-all duration-200',
{
'bg-pink-500 text-white hover:bg-pink-600 hover:text-white':
(hiddenTableIds ?? []).length >
0,
hasActiveFilter,
}
)}
>

View File

@@ -1,14 +1,9 @@
import React, { Suspense, useCallback, useEffect, useRef } from 'react';
import { useParams } from 'react-router-dom';
import React, { Suspense, useEffect } from 'react';
import { useChartDB } from '@/hooks/use-chartdb';
import { useDialog } from '@/hooks/use-dialog';
import { Toaster } from '@/components/toast/toaster';
import { useBreakpoint } from '@/hooks/use-breakpoint';
import { useLayout } from '@/hooks/use-layout';
import { useToast } from '@/components/toast/use-toast';
import { ToastAction } from '@/components/toast/toast';
import { useLocalConfig } from '@/hooks/use-local-config';
import { useTranslation } from 'react-i18next';
import { FullScreenLoaderProvider } from '@/context/full-screen-spinner-context/full-screen-spinner-provider';
import { LayoutProvider } from '@/context/layout-context/layout-provider';
import { LocalConfigProvider } from '@/context/local-config-context/local-config-provider';
@@ -43,21 +38,11 @@ export const EditorMobileLayoutLazy = React.lazy(
);
const EditorPageComponent: React.FC = () => {
const { diagramName, currentDiagram, schemas, filteredSchemas } =
useChartDB();
const { openSelectSchema, showSidePanel } = useLayout();
const { diagramName, currentDiagram } = useChartDB();
const { openStarUsDialog } = useDialog();
const { diagramId } = useParams<{ diagramId: string }>();
const { isMd: isDesktop } = useBreakpoint('md');
const {
hideMultiSchemaNotification,
setHideMultiSchemaNotification,
starUsDialogLastOpen,
setStarUsDialogLastOpen,
githubRepoOpened,
} = useLocalConfig();
const { toast } = useToast();
const { t } = useTranslation();
const { starUsDialogLastOpen, setStarUsDialogLastOpen, githubRepoOpened } =
useLocalConfig();
const { initialDiagram } = useDiagramLoader();
useEffect(() => {
@@ -85,73 +70,6 @@ const EditorPageComponent: React.FC = () => {
starUsDialogLastOpen,
]);
const lastDiagramId = useRef<string>('');
const handleChangeSchema = useCallback(async () => {
showSidePanel();
if (!isDesktop) {
await new Promise((resolve) => setTimeout(resolve, 500));
}
openSelectSchema();
}, [openSelectSchema, showSidePanel, isDesktop]);
useEffect(() => {
if (lastDiagramId.current === currentDiagram.id) {
return;
}
lastDiagramId.current = currentDiagram.id;
if (schemas.length > 1 && !hideMultiSchemaNotification) {
const formattedSchemas = !filteredSchemas
? t('multiple_schemas_alert.none')
: filteredSchemas
.map((filteredSchema) =>
schemas.find((schema) => schema.id === filteredSchema)
)
.map((schema) => `'${schema?.name}'`)
.join(', ');
toast({
duration: Infinity,
title: t('multiple_schemas_alert.title'),
description: t('multiple_schemas_alert.description', {
schemasCount: schemas.length,
formattedSchemas,
}),
variant: 'default',
layout: 'column',
hideCloseButton: true,
className:
'top-0 right-0 flex fixed md:max-w-[420px] md:top-4 md:right-4',
action: (
<div className="flex justify-between gap-1">
<div />
<ToastAction
onClick={() => {
handleChangeSchema();
setHideMultiSchemaNotification(true);
}}
altText="Show me the schemas"
className="border border-pink-600 bg-pink-600 text-white hover:bg-pink-500"
>
{t('multiple_schemas_alert.show_me')}
</ToastAction>
</div>
),
});
}
}, [
schemas,
filteredSchemas,
toast,
currentDiagram.id,
diagramId,
openSelectSchema,
t,
handleChangeSchema,
hideMultiSchemaNotification,
setHideMultiSchemaNotification,
]);
return (
<>
<Helmet>

View File

@@ -19,7 +19,8 @@ import { useLayout } from '@/hooks/use-layout';
export interface DependenciesSectionProps {}
export const DependenciesSection: React.FC<DependenciesSectionProps> = () => {
const { dependencies, filteredSchemas, getTable } = useChartDB();
const { dependencies, filteredSchemas, hiddenTableIds, getTable } =
useChartDB();
const [filterText, setFilterText] = React.useState('');
const { closeAllDependenciesInSidebar } = useLayout();
const { t } = useTranslation();
@@ -44,12 +45,15 @@ export const DependenciesSection: React.FC<DependenciesSectionProps> = () => {
);
};
const filterSchema: (dependency: DBDependency) => boolean = (
const filterVisible: (dependency: DBDependency) => boolean = (
dependency
) => shouldShowDependencyBySchemaFilter(dependency, filteredSchemas);
) =>
shouldShowDependencyBySchemaFilter(dependency, filteredSchemas) &&
!hiddenTableIds?.includes(dependency.tableId) &&
!hiddenTableIds?.includes(dependency.dependentTableId);
return dependencies
.filter(filterSchema)
.filter(filterVisible)
.filter(filterName)
.sort((a, b) => {
const dependentTableA = getTable(a.dependentTableId);
@@ -60,7 +64,7 @@ export const DependenciesSection: React.FC<DependenciesSectionProps> = () => {
`${dependentTableB?.name}${tableB?.name}`
);
});
}, [dependencies, filterText, filteredSchemas, getTable]);
}, [dependencies, filterText, filteredSchemas, hiddenTableIds, getTable]);
return (
<section className="flex flex-1 flex-col overflow-hidden px-2">

View File

@@ -20,7 +20,7 @@ import { useDialog } from '@/hooks/use-dialog';
export interface RelationshipsSectionProps {}
export const RelationshipsSection: React.FC<RelationshipsSectionProps> = () => {
const { relationships, filteredSchemas } = useChartDB();
const { relationships, filteredSchemas, hiddenTableIds } = useChartDB();
const [filterText, setFilterText] = React.useState('');
const { closeAllRelationshipsInSidebar } = useLayout();
const { t } = useTranslation();
@@ -34,13 +34,18 @@ export const RelationshipsSection: React.FC<RelationshipsSectionProps> = () => {
!filterText?.trim?.() ||
relationship.name.toLowerCase().includes(filterText.toLowerCase());
const filterSchema: (relationship: DBRelationship) => boolean = (
const filterVisible: (relationship: DBRelationship) => boolean = (
relationship
) =>
shouldShowRelationshipBySchemaFilter(relationship, filteredSchemas);
shouldShowRelationshipBySchemaFilter(
relationship,
filteredSchemas
) &&
!hiddenTableIds?.includes(relationship.sourceTableId) &&
!hiddenTableIds?.includes(relationship.targetTableId);
return relationships.filter(filterSchema).filter(filterName);
}, [relationships, filterText, filteredSchemas]);
return relationships.filter(filterVisible).filter(filterName);
}, [relationships, filterText, filteredSchemas, hiddenTableIds]);
const handleCreateRelationship = useCallback(async () => {
setFilterText('');

View File

@@ -1,4 +1,4 @@
import React, { useCallback, useMemo } from 'react';
import React from 'react';
import {
Select,
SelectContent,
@@ -12,8 +12,6 @@ import { RelationshipsSection } from './relationships-section/relationships-sect
import { useLayout } from '@/hooks/use-layout';
import type { SidebarSection } from '@/context/layout-context/layout-context';
import { useTranslation } from 'react-i18next';
import type { SelectBoxOption } from '@/components/select-box/select-box';
import { SelectBox } from '@/components/select-box/select-box';
import { useChartDB } from '@/hooks/use-chartdb';
import { DependenciesSection } from './dependencies-section/dependencies-section';
import { useBreakpoint } from '@/hooks/use-breakpoint';
@@ -25,69 +23,12 @@ export interface SidePanelProps {}
export const SidePanel: React.FC<SidePanelProps> = () => {
const { t } = useTranslation();
const { schemas, filterSchemas, filteredSchemas, databaseType } =
useChartDB();
const {
selectSidebarSection,
selectedSidebarSection,
isSelectSchemaOpen,
openSelectSchema,
closeSelectSchema,
} = useLayout();
const { databaseType } = useChartDB();
const { selectSidebarSection, selectedSidebarSection } = useLayout();
const { isMd: isDesktop } = useBreakpoint('md');
const schemasOptions: SelectBoxOption[] = useMemo(
() =>
schemas.map(
(schema): SelectBoxOption => ({
label: schema.name,
value: schema.id,
description: `(${schema.tableCount} tables)`,
})
),
[schemas]
);
const setIsSelectSchemaOpen = useCallback(
(open: boolean) => {
if (open) {
openSelectSchema();
} else {
closeSelectSchema();
}
},
[openSelectSchema, closeSelectSchema]
);
return (
<aside className="flex h-full flex-col overflow-hidden">
{schemasOptions.length > 0 ? (
<div className="flex items-center justify-center border-b pl-3 pt-0.5">
<div className="shrink-0 text-sm font-semibold">
{t('side_panel.schema')}
</div>
<div className="flex min-w-0 flex-1">
<SelectBox
oneLine
className="w-full rounded-none border-none"
selectAll
deselectAll
options={schemasOptions}
value={filteredSchemas ?? []}
onChange={(values) => {
filterSchemas(values as string[]);
}}
placeholder={t('side_panel.filter_by_schema')}
inputPlaceholder={t('side_panel.search_schema')}
emptyPlaceholder={t('side_panel.no_schemas_found')}
multiple
open={isSelectSchemaOpen}
onOpenChange={setIsSelectSchemaOpen}
/>
</div>
</div>
) : null}
{!isDesktop ? (
<div className="flex justify-center border-b pt-0.5">
<Select

View File

@@ -55,7 +55,6 @@ export const TableListItemHeader: React.FC<TableListItemHeaderProps> = ({
createField,
createTable,
schemas,
filteredSchemas,
databaseType,
} = useChartDB();
const { openTableSchemaDialog } = useDialog();
@@ -267,7 +266,7 @@ export const TableListItemHeader: React.FC<TableListItemHeaderProps> = ({
let schemaToDisplay;
if (schemas.length > 1 && !!filteredSchemas && filteredSchemas.length > 1) {
if (schemas.length > 1) {
schemaToDisplay = table.schema;
}

View File

@@ -17,13 +17,24 @@ import {
verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { useChartDB } from '@/hooks/use-chartdb.ts';
import type { Area } from '@/lib/domain/area';
import { useTranslation } from 'react-i18next';
import { defaultSchemas } from '@/lib/data/default-schemas';
import { databasesWithSchemas } from '@/lib/domain/db-schema';
export interface TableListProps {
tables: DBTable[];
groupBy?: 'schema' | 'area';
areas?: Area[];
}
export const TableList: React.FC<TableListProps> = ({ tables }) => {
const { updateTablesState } = useChartDB();
export const TableList: React.FC<TableListProps> = ({
tables,
groupBy = 'schema',
areas = [],
}) => {
const { updateTablesState, databaseType } = useChartDB();
const { t } = useTranslation();
const { openTableFromSidebar, openedTableInSidebar } = useLayout();
const lastOpenedTable = React.useRef<string | null>(null);
@@ -87,62 +98,162 @@ export const TableList: React.FC<TableListProps> = ({ tables }) => {
}
}, [scrollToTable, openedTableInSidebar]);
const sortTables = useCallback((tablesToSort: DBTable[]) => {
return tablesToSort.sort((table1: DBTable, table2: DBTable) => {
// if one table has order and the other doesn't, the one with order should come first
if (table1.order && table2.order === undefined) {
return -1;
}
if (table1.order === undefined && table2.order) {
return 1;
}
// if both tables have order, sort by order
if (table1.order !== undefined && table2.order !== undefined) {
return (table1.order ?? 0) - (table2.order ?? 0);
}
// if both tables don't have order, sort by name
if (table1.isView === table2.isView) {
// Both are either tables or views, so sort alphabetically by name
return table1.name.localeCompare(table2.name);
}
// If one is a view and the other is not, put tables first
return table1.isView ? 1 : -1;
});
}, []);
const groupedTables = useMemo(() => {
if (groupBy === 'area') {
// Group tables by area
const tablesWithArea: Record<string, DBTable[]> = {};
const tablesWithoutArea: DBTable[] = [];
// Create a map of area id to area name
const areaMap = areas.reduce(
(acc, area) => {
acc[area.id] = area.name;
return acc;
},
{} as Record<string, string>
);
tables.forEach((table) => {
if (table.parentAreaId && areaMap[table.parentAreaId]) {
if (!tablesWithArea[table.parentAreaId]) {
tablesWithArea[table.parentAreaId] = [];
}
tablesWithArea[table.parentAreaId].push(table);
} else {
tablesWithoutArea.push(table);
}
});
// Sort areas by their order or name
const sortedAreas = areas
.filter((area) => tablesWithArea[area.id])
.sort((a, b) => {
if (a.order !== undefined && b.order !== undefined) {
return a.order - b.order;
}
return a.name.localeCompare(b.name);
});
return [
...sortedAreas.map((area) => ({
id: area.id,
name: area.name,
tables: sortTables(tablesWithArea[area.id]),
})),
...(tablesWithoutArea.length > 0
? [
{
id: 'no-area',
name: t('side_panel.tables_section.no_area'),
tables: sortTables(tablesWithoutArea),
},
]
: []),
];
}
// Group by schema
const supportsSchemas = databasesWithSchemas.includes(databaseType);
if (supportsSchemas) {
// Group tables by schema
const tablesBySchema: Record<string, DBTable[]> = {};
tables.forEach((table) => {
const schema =
table.schema ?? defaultSchemas[databaseType] ?? 'default';
if (!tablesBySchema[schema]) {
tablesBySchema[schema] = [];
}
tablesBySchema[schema].push(table);
});
// Sort schemas alphabetically
const sortedSchemas = Object.keys(tablesBySchema).sort((a, b) =>
a.localeCompare(b)
);
return sortedSchemas.map((schema) => ({
id: `schema-${schema}`,
name: schema,
tables: sortTables(tablesBySchema[schema]),
}));
}
// For databases that don't support schemas, return all tables as one group
return [
{
id: 'all',
name: '',
tables: sortTables(tables),
},
];
}, [tables, groupBy, areas, sortTables, t, databaseType]);
return (
<Accordion
type="single"
collapsible
className="flex w-full flex-col gap-1"
value={openedTableInSidebar}
onValueChange={openTableFromSidebar}
onAnimationEnd={handleScrollToTable}
>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext
items={tables}
strategy={verticalListSortingStrategy}
>
{tables
.sort((table1: DBTable, table2: DBTable) => {
// if one table has order and the other doesn't, the one with order should come first
if (table1.order && table2.order === undefined) {
return -1;
}
if (table1.order === undefined && table2.order) {
return 1;
}
// if both tables have order, sort by order
if (
table1.order !== undefined &&
table2.order !== undefined
) {
return (
(table1.order ?? 0) - (table2.order ?? 0)
);
}
// if both tables don't have order, sort by name
if (table1.isView === table2.isView) {
// Both are either tables or views, so sort alphabetically by name
return table1.name.localeCompare(table2.name);
}
// If one is a view and the other is not, put tables first
return table1.isView ? 1 : -1;
})
.map((table) => (
<TableListItem
key={table.id}
table={table}
ref={refs[table.id]}
/>
))}
</SortableContext>
</DndContext>
</Accordion>
<div className="flex flex-col gap-3">
{groupedTables.map((group) => (
<div key={group.id}>
{group.name && (
<div className="mb-2 px-2 text-xs font-medium text-muted-foreground">
{group.name}
</div>
)}
<Accordion
type="single"
collapsible
className="flex w-full flex-col gap-1"
value={openedTableInSidebar}
onValueChange={openTableFromSidebar}
onAnimationEnd={handleScrollToTable}
>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext
items={group.tables}
strategy={verticalListSortingStrategy}
>
{group.tables.map((table) => (
<TableListItem
key={table.id}
table={table}
ref={refs[table.id]}
/>
))}
</SortableContext>
</DndContext>
</Accordion>
</div>
))}
</div>
);
};

View File

@@ -1,7 +1,7 @@
import React, { useCallback, useMemo, useState } from 'react';
import { TableList } from './table-list/table-list';
import { Button } from '@/components/button/button';
import { Table, List, X, Code } from 'lucide-react';
import { Table, List, X, Code, Funnel, Layers, Database } from 'lucide-react';
import { Input } from '@/components/input/input';
import type { DBTable } from '@/lib/domain/db-table';
import { shouldShowTablesBySchemaFilter } from '@/lib/domain/db-table';
@@ -21,29 +21,60 @@ import { TableDBML } from './table-dbml/table-dbml';
import { useHotkeys } from 'react-hotkeys-hook';
import { getOperatingSystem } from '@/lib/utils';
import type { DBSchema } from '@/lib/domain';
import { useCanvas } from '@/hooks/use-canvas';
import { ToggleGroup, ToggleGroupItem } from '@/components/toggle/toggle-group';
import { databasesWithSchemas } from '@/lib/domain/db-schema';
export interface TablesSectionProps {}
export const TablesSection: React.FC<TablesSectionProps> = () => {
const { createTable, tables, filteredSchemas, schemas } = useChartDB();
const {
createTable,
tables,
hiddenTableIds,
filteredSchemas,
schemas,
areas,
databaseType,
} = useChartDB();
const { openTableSchemaDialog } = useDialog();
const viewport = useViewport();
const { t } = useTranslation();
const { openTableFromSidebar } = useLayout();
const [filterText, setFilterText] = React.useState('');
const [showDBML, setShowDBML] = useState(false);
const [groupBy, setGroupBy] = useState<'schema' | 'area'>('schema');
const filterInputRef = React.useRef<HTMLInputElement>(null);
const { setShowFilter } = useCanvas();
const supportsSchemas = useMemo(
() => databasesWithSchemas.includes(databaseType),
[databaseType]
);
const filteredTables = useMemo(() => {
const filterTableName: (table: DBTable) => boolean = (table) =>
!filterText?.trim?.() ||
table.name.toLowerCase().includes(filterText.toLowerCase());
const filterSchema: (table: DBTable) => boolean = (table) =>
// Show only tables that are visible on the canvas
const filterVisible: (table: DBTable) => boolean = (table) =>
!hiddenTableIds?.includes(table.id) &&
shouldShowTablesBySchemaFilter(table, filteredSchemas);
return tables.filter(filterSchema).filter(filterTableName);
}, [tables, filterText, filteredSchemas]);
return tables.filter(filterVisible).filter(filterTableName);
}, [tables, filterText, hiddenTableIds, filteredSchemas]);
// Check if all tables are filtered out by canvas filters (not text filter)
const allTablesFilteredByCanvas = useMemo(() => {
return (
tables.length > 0 &&
tables.every(
(table) =>
hiddenTableIds?.includes(table.id) ||
!shouldShowTablesBySchemaFilter(table, filteredSchemas)
)
);
}, [tables, hiddenTableIds, filteredSchemas]);
const createTableWithLocation = useCallback(
async ({ schema }: { schema?: DBSchema }) => {
@@ -97,6 +128,10 @@ export const TablesSection: React.FC<TablesSectionProps> = () => {
setFilterText('');
}, []);
const handleOpenCanvasFilter = useCallback(() => {
setShowFilter(true);
}, [setShowFilter]);
const operatingSystem = useMemo(() => getOperatingSystem(), []);
useHotkeys(
@@ -162,6 +197,37 @@ export const TablesSection: React.FC<TablesSectionProps> = () => {
{t('side_panel.tables_section.add_table')}
</Button>
</div>
<div className="mb-2">
<ToggleGroup
type="single"
value={groupBy}
onValueChange={(value) => {
if (value) setGroupBy(value as 'schema' | 'area');
}}
className="w-full justify-start"
>
<ToggleGroupItem
value="schema"
aria-label={
supportsSchemas ? 'Group by schema' : 'Default'
}
className="h-8 flex-1 gap-1.5 text-xs"
>
<Database className="size-3.5" />
{supportsSchemas
? t('side_panel.tables_section.group_by_schema')
: t('side_panel.tables_section.default_grouping')}
</ToggleGroupItem>
<ToggleGroupItem
value="area"
aria-label="Group by area"
className="h-8 flex-1 gap-1.5 text-xs"
>
<Layers className="size-3.5" />
{t('side_panel.tables_section.group_by_area')}
</ToggleGroupItem>
</ToggleGroup>
</div>
<div className="flex flex-1 flex-col overflow-hidden">
{showDBML ? (
<TableDBML filteredTables={filteredTables} />
@@ -177,6 +243,23 @@ export const TablesSection: React.FC<TablesSectionProps> = () => {
)}
className="mt-20"
/>
) : allTablesFilteredByCanvas ? (
<div className="mt-10 flex flex-col items-center gap-2">
<div className="text-sm text-muted-foreground">
{t(
'side_panel.tables_section.all_tables_filtered'
)}
</div>
<Button
variant="outline"
size="sm"
onClick={handleOpenCanvasFilter}
className="gap-1"
>
<Funnel className="size-3.5" />
{t('side_panel.tables_section.open_filter')}
</Button>
</div>
) : filterText && filteredTables.length === 0 ? (
<div className="mt-10 flex flex-col items-center gap-2">
<div className="text-sm text-muted-foreground">
@@ -193,7 +276,11 @@ export const TablesSection: React.FC<TablesSectionProps> = () => {
</Button>
</div>
) : (
<TableList tables={filteredTables} />
<TableList
tables={filteredTables}
groupBy={groupBy}
areas={areas}
/>
)}
</ScrollArea>
)}