Compare commits

...

8 Commits

Author SHA1 Message Date
johnnyfish
8874cb552d fix for schemas 2025-07-31 21:27:06 +03:00
johnnyfish
32b2c2fa7a fix: preserve group expanded state when toggling table visibility in canvas filter 2025-07-31 21:05:35 +03:00
johnnyfish
63e8c82b24 fix: resolve table visibility toggle not working in schema grouping mode 2025-07-31 21:01:33 +03:00
johnnyfish
06cb0b5161 feat: add toggle to group tables by area or schema in sidebar 2025-07-31 19:30:41 +03:00
Guy Ben-Aharon
8ffde62c1a fix(readonly): fix zoom out on readonly (#818) 2025-07-31 15:27:38 +03:00
Guy Ben-Aharon
39247b77a2 feat: enhance primary key and unique field handling logic (#817) 2025-07-31 11:38:33 +03:00
Guy Ben-Aharon
984b2aeee2 fix(ui): reduce spacing between primary key icon and short field types (#816) 2025-07-31 11:04:48 +03:00
Guy Ben-Aharon
eed104be5b fix(dbml): fix dbml output format (#815) 2025-07-30 14:31:56 +03:00
15 changed files with 721 additions and 187 deletions

View File

@@ -44,6 +44,7 @@ export interface CodeSnippetProps {
editorProps?: React.ComponentProps<EditorType>;
actions?: CodeSnippetAction[];
actionsTooltipSide?: 'top' | 'right' | 'bottom' | 'left';
allowCopy?: boolean;
}
export const CodeSnippet: React.FC<CodeSnippetProps> = React.memo(
@@ -58,6 +59,7 @@ export const CodeSnippet: React.FC<CodeSnippetProps> = React.memo(
editorProps,
actions,
actionsTooltipSide,
allowCopy = true,
}) => {
const { t } = useTranslation();
const monaco = useMonaco();
@@ -131,33 +133,37 @@ export const CodeSnippet: React.FC<CodeSnippetProps> = React.memo(
<Suspense fallback={<Spinner />}>
{isComplete ? (
<div className="absolute right-1 top-1 z-10 flex flex-col gap-1">
<Tooltip
onOpenChange={setTooltipOpen}
open={isCopied || tooltipOpen}
>
<TooltipTrigger asChild>
<span>
<Button
className="h-fit p-1.5"
variant="outline"
onClick={copyToClipboard}
>
{isCopied ? (
<CopyCheck size={16} />
) : (
<Copy size={16} />
)}
</Button>
</span>
</TooltipTrigger>
<TooltipContent side={actionsTooltipSide}>
{t(
isCopied
? 'copied'
: 'copy_to_clipboard'
)}
</TooltipContent>
</Tooltip>
{allowCopy ? (
<Tooltip
onOpenChange={setTooltipOpen}
open={isCopied || tooltipOpen}
>
<TooltipTrigger asChild>
<span>
<Button
className="h-fit p-1.5"
variant="outline"
onClick={copyToClipboard}
>
{isCopied ? (
<CopyCheck size={16} />
) : (
<Copy size={16} />
)}
</Button>
</span>
</TooltipTrigger>
<TooltipContent
side={actionsTooltipSide}
>
{t(
isCopied
? 'copied'
: 'copy_to_clipboard'
)}
</TooltipContent>
</Tooltip>
) : null}
{actions &&
actions.length > 0 &&

View File

@@ -127,6 +127,10 @@ export const en = {
no_results: 'No tables found matching your 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 +266,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

@@ -362,9 +362,10 @@ export const exportBaseSQL = ({
.join(', ');
if (fieldNames) {
const indexName = table.schema
? `${table.schema}_${index.name}`
: index.name;
const indexName =
table.schema && !isDBMLFlow
? `${table.schema}_${index.name}`
: index.name;
sqlScript += `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${indexName} ON ${tableName} (${fieldNames});\n`;
}
});

View File

@@ -937,26 +937,24 @@ describe('DBML Export - Issue Fixes', () => {
// Check that indexes are properly formatted with names
// Note: When a table has a schema, index names are prefixed with the schema
expect(result.standardDbml).toContain(
'email [unique, name: "public_idx_email"]'
'email [unique, name: "idx_email"]'
);
expect(result.standardDbml).toContain(
'created_at [name: "public_idx_created_at"]'
'created_at [name: "idx_created_at"]'
);
expect(result.standardDbml).toContain(
'(email, created_at) [name: "public_idx_email_created"]'
'(email, created_at) [name: "idx_email_created"]'
);
// Verify proper index syntax in the table
const indexSection = result.standardDbml.match(/Indexes \{[\s\S]*?\}/);
expect(indexSection).toBeTruthy();
expect(indexSection![0]).toContain('email [unique, name: "idx_email"]');
expect(indexSection![0]).toContain(
'email [unique, name: "public_idx_email"]'
'created_at [name: "idx_created_at"]'
);
expect(indexSection![0]).toContain(
'created_at [name: "public_idx_created_at"]'
);
expect(indexSection![0]).toContain(
'(email, created_at) [name: "public_idx_email_created"]'
'(email, created_at) [name: "idx_email_created"]'
);
});
});

View File

@@ -350,7 +350,10 @@ const convertToInlineRefs = (dbml: string): string => {
// Combine all attributes into a single bracket
const combinedAttributes = allAttributes.join(', ');
return `${fieldPart.trim()} [${combinedAttributes}]${commentPart || ''}`;
// Preserve original spacing from fieldPart
const leadingSpaces = fieldPart.match(/^(\s*)/)?.[1] || '';
const fieldDefWithoutSpaces = fieldPart.trim();
return `${leadingSpaces}${fieldDefWithoutSpaces} [${combinedAttributes}]${commentPart || ''}`;
}
);
@@ -388,7 +391,10 @@ const convertToInlineRefs = (dbml: string): string => {
.filter((line) => !line.trim().startsWith('Ref '));
const finalDbml = finalLines.join('\n').trim();
return finalDbml;
// Clean up excessive empty lines - replace multiple consecutive empty lines with just one
const cleanedDbml = finalDbml.replace(/\n\s*\n\s*\n/g, '\n\n');
return cleanedDbml;
};
// Function to check for SQL keywords (add more if needed)
@@ -804,9 +810,15 @@ export function generateDBMLFromDiagram(diagram: Diagram): DBMLExportResult {
standard = restoreTableSchemas(standard, diagram);
// Prepend Enum DBML to the standard output
standard = enumsDBML + '\n' + standard;
if (enumsDBML) {
standard = enumsDBML + '\n\n' + standard;
}
inline = normalizeCharTypeFormat(convertToInlineRefs(standard));
// Clean up excessive empty lines in both outputs
standard = standard.replace(/\n\s*\n\s*\n/g, '\n\n');
inline = inline.replace(/\n\s*\n\s*\n/g, '\n\n');
} catch (error: unknown) {
console.error(
'Error during DBML generation process:',
@@ -822,11 +834,11 @@ export function generateDBMLFromDiagram(diagram: Diagram): DBMLExportResult {
// If an error occurred, still prepend enums if they exist, or they'll be lost.
// The error message will then follow.
if (standard.startsWith('// Error generating DBML:')) {
standard = enumsDBML + standard;
if (standard.startsWith('// Error generating DBML:') && enumsDBML) {
standard = enumsDBML + '\n\n' + standard;
}
if (inline.startsWith('// Error generating DBML:')) {
inline = enumsDBML + inline;
if (inline.startsWith('// Error generating DBML:') && enumsDBML) {
inline = enumsDBML + '\n\n' + inline;
}
}

View File

@@ -1,6 +1,9 @@
import type { DBTable } from '@/lib/domain/db-table';
import type { Area } from '@/lib/domain/area';
import { calcTableHeight } from '@/lib/domain/db-table';
import {
calcTableHeight,
shouldShowTablesBySchemaFilter,
} from '@/lib/domain/db-table';
/**
* Check if a table is inside an area based on their positions and dimensions
@@ -53,9 +56,31 @@ const findContainingArea = (table: DBTable, areas: Area[]): Area | null => {
*/
export const updateTablesParentAreas = (
tables: DBTable[],
areas: Area[]
areas: Area[],
hiddenTableIds?: string[],
filteredSchemas?: string[]
): DBTable[] => {
return tables.map((table) => {
// Check if table is hidden by direct hiding or schema filter
const isHiddenDirectly = hiddenTableIds?.includes(table.id) ?? false;
const isHiddenBySchema = !shouldShowTablesBySchemaFilter(
table,
filteredSchemas
);
const isHidden = isHiddenDirectly || isHiddenBySchema;
// If table is hidden, remove it from any area
if (isHidden) {
if (table.parentAreaId !== null) {
return {
...table,
parentAreaId: null,
};
}
return table;
}
// For visible tables, find containing area as before
const containingArea = findContainingArea(table, areas);
const newParentAreaId = containingArea?.id || null;

View File

@@ -82,13 +82,15 @@ export const CanvasContextMenu: React.FC<React.PropsWithChildren> = ({
openCreateRelationshipDialog();
}, [openCreateRelationshipDialog]);
if (!isDesktop || readonly) {
if (!isDesktop) {
return <>{children}</>;
}
return (
<ContextMenu>
<ContextMenuTrigger>{children}</ContextMenuTrigger>
<ContextMenuTrigger disabled={readonly}>
{children}
</ContextMenuTrigger>
<ContextMenuContent>
<ContextMenuItem
onClick={createTableHandler}

View File

@@ -5,26 +5,40 @@ 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 {
schemaNameToSchemaId,
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 +46,7 @@ type TableContext = {
type NodeContext = {
schema: SchemaContext;
area: AreaContext;
table: TableContext;
};
@@ -51,12 +66,19 @@ export const CanvasFilter: React.FC<CanvasFilterProps> = ({ onClose }) => {
removeHiddenTableId,
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 +93,137 @@ 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]>
);
relevantTableData.forEach((table) => {
const tableData = tables.find((t) => t.id === table.id);
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) => {
const areaTables = tablesByArea.get(area.id) || [];
const areaNode: TreeNode<NodeType, NodeContext> = {
id: `area-${area.id}`,
name: `${area.name} (${areaTables.length})`,
type: 'area',
isFolder: true,
icon: Layers,
context: { id: area.id, name: area.name },
children: areaTables.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,
type: 'table',
isFolder: false,
icon: Table,
context: {
tableSchema: table.schema,
hidden: tableHidden,
},
className: hidden ? 'opacity-50' : '',
};
}
),
};
nodes.push(areaNode);
});
// Add "No Area" group if there are tables without areas
if (tablesWithoutArea.length > 0) {
const noAreaNode: TreeNode<NodeType, NodeContext> = {
id: 'area-no-area',
name: `${t('canvas_filter.no_area')} (${tablesWithoutArea.length})`,
type: 'area',
isFolder: true,
icon: Layers,
context: {
id: 'no-area',
name: t('canvas_filter.no_area'),
},
className: 'opacity-75',
children: tablesWithoutArea.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,
type: 'table',
isFolder: false,
icon: Table,
context: {
tableSchema: table.schema,
hidden: tableHidden,
},
className: hidden ? 'opacity-50' : '',
};
}
),
};
nodes.push(noAreaNode);
}
return nodes;
}
// Default schema grouping
// Group tables by schema
const tablesBySchema = new Map<string, RelevantTableData[]>();
@@ -134,16 +287,36 @@ export const CanvasFilter: React.FC<CanvasFilterProps> = ({ onClose }) => {
});
return nodes;
}, [relevantTableData, databaseType, hiddenTableIds, filteredSchemas]);
}, [
relevantTableData,
databaseType,
hiddenTableIds,
filteredSchemas,
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 with all schemas expanded only when grouping changes
useEffect(() => {
setExpanded((prevExpanded) => {
const newExpanded: Record<string, boolean> = {};
// Preserve existing expanded states for nodes that still exist
treeData.forEach((node) => {
if (node.id in prevExpanded) {
newExpanded[node.id] = prevExpanded[node.id];
} else {
// Default new nodes to expanded
newExpanded[node.id] = true;
}
});
return newExpanded;
});
setExpanded(initialExpanded);
}, [treeData]);
}, [groupBy, treeData]);
// Filter tree data based on search query
const filteredTreeData: TreeNode<NodeType, NodeContext>[] = useMemo(() => {
@@ -219,6 +392,45 @@ 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 === 'area') {
return (
<Button
variant="ghost"
size="sm"
className="size-7 h-fit p-0"
disabled={!node.children || node.children.length === 0}
onClick={(e) => {
e.stopPropagation();
// Toggle all tables in this area
const allHidden =
(node.children?.length > 0 &&
node.children?.every((child) =>
hiddenTableIds?.includes(child.id)
)) ||
false;
node.children?.forEach((child) => {
if (child.type === 'table') {
if (allHidden) {
removeHiddenTableId(child.id);
} else {
addHiddenTableId(child.id);
}
}
});
}}
>
{node.children?.every((child) =>
hiddenTableIds?.includes(child.id)
) ? (
<EyeOff className="size-3.5 text-muted-foreground" />
) : (
<Eye className="size-3.5" />
)}
</Button>
);
}
if (node.type === 'schema') {
const schemaContext = node.context as SchemaContext;
const schemaId = schemaNameToSchemaId(schemaContext.name);
@@ -283,35 +495,12 @@ export const CanvasFilter: React.FC<CanvasFilterProps> = ({ onClose }) => {
className="size-7 h-fit p-0"
onClick={(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
toggleTableVisibility(tableId, !hidden);
}}
disabled={!visibleBySchema}
>
{hidden || !visibleBySchema ? (
{hidden ? (
<EyeOff className="size-3.5 text-muted-foreground" />
) : (
<Eye className="size-3.5" />
@@ -326,7 +515,6 @@ export const CanvasFilter: React.FC<CanvasFilterProps> = ({ onClose }) => {
toggleTableVisibility,
filteredSchemas,
filterSchemas,
treeData,
hiddenTableIds,
addHiddenTableId,
removeHiddenTableId,
@@ -403,6 +591,42 @@ 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 */}

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
@@ -465,7 +505,12 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
useEffect(() => {
const checkParentAreas = debounce(() => {
const updatedTables = updateTablesParentAreas(tables, areas);
const updatedTables = updateTablesParentAreas(
tables,
areas,
hiddenTableIds,
filteredSchemas
);
const needsUpdate: Array<{
id: string;
parentAreaId: string | null;
@@ -505,7 +550,14 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
}, 300);
checkParentAreas();
}, [tablePositions, areas, updateTablesState, tables]);
}, [
tablePositions,
areas,
updateTablesState,
tables,
hiddenTableIds,
filteredSchemas,
]);
const onConnectHandler = useCallback(
async (params: AddEdgeParams) => {

View File

@@ -383,7 +383,8 @@ export const TableNodeField: React.FC<TableNodeFieldProps> = React.memo(
<div
className={cn(
'content-center text-right text-xs text-muted-foreground overflow-hidden min-w-[3rem] max-w-[8rem]',
'content-center text-right text-xs text-muted-foreground overflow-hidden max-w-[8rem]',
field.primaryKey ? 'min-w-0' : 'min-w-[3rem]',
!readonly ? 'group-hover:hidden' : '',
isDiffFieldRemoved
? 'text-red-800 dark:text-red-200'

View File

@@ -17,7 +17,7 @@ import { useTranslation } from 'react-i18next';
import { Textarea } from '@/components/textarea/textarea';
import { useDebounce } from '@/hooks/use-debounce';
import equal from 'fast-deep-equal';
import type { DatabaseType } from '@/lib/domain';
import type { DatabaseType, DBTable } from '@/lib/domain';
import {
Select,
@@ -29,6 +29,7 @@ import {
export interface TableFieldPopoverProps {
field: DBField;
table: DBTable;
databaseType: DatabaseType;
updateField: (attrs: Partial<DBField>) => void;
removeField: () => void;
@@ -36,6 +37,7 @@ export interface TableFieldPopoverProps {
export const TableFieldPopover: React.FC<TableFieldPopoverProps> = ({
field,
table,
databaseType,
updateField,
removeField,
@@ -44,6 +46,19 @@ export const TableFieldPopover: React.FC<TableFieldPopoverProps> = ({
const [localField, setLocalField] = React.useState<DBField>(field);
const [isOpen, setIsOpen] = React.useState(false);
// Check if this field is the only primary key in the table
const isOnlyPrimaryKey = React.useMemo(() => {
if (!field.primaryKey) return false;
// Early exit if we find another primary key
for (const f of table.fields) {
if (f.id !== field.id && f.primaryKey) {
return false;
}
}
return true;
}, [table.fields, field.primaryKey, field.id]);
useEffect(() => {
setLocalField(field);
}, [field]);
@@ -113,7 +128,7 @@ export const TableFieldPopover: React.FC<TableFieldPopoverProps> = ({
</Label>
<Checkbox
checked={localField.unique}
disabled={field.primaryKey}
disabled={isOnlyPrimaryKey}
onCheckedChange={(value) =>
setLocalField((current) => ({
...current,

View File

@@ -23,8 +23,10 @@ import type {
} from '@/components/select-box/select-box';
import { SelectBox } from '@/components/select-box/select-box';
import { TableFieldPopover } from './table-field-modal/table-field-modal';
import type { DBTable } from '@/lib/domain';
export interface TableFieldProps {
table: DBTable;
field: DBField;
updateField: (attrs: Partial<DBField>) => void;
removeField: () => void;
@@ -76,6 +78,7 @@ const generateFieldRegexPatterns = (
};
export const TableField: React.FC<TableFieldProps> = ({
table,
field,
updateField,
removeField,
@@ -83,6 +86,13 @@ export const TableField: React.FC<TableFieldProps> = ({
const { databaseType, customTypes } = useChartDB();
const { t } = useTranslation();
// Only calculate primary key fields, not just count
const primaryKeyFields = useMemo(() => {
return table.fields.filter((f) => f.primaryKey);
}, [table.fields]);
const primaryKeyCount = primaryKeyFields.length;
const { attributes, listeners, setNodeRef, transform, transition } =
useSortable({ id: field.id });
@@ -191,6 +201,42 @@ export const TableField: React.FC<TableFieldProps> = ({
transition,
};
const handlePrimaryKeyToggle = useCallback(
(value: boolean) => {
if (value) {
// When setting as primary key
const updates: Partial<DBField> = {
primaryKey: true,
};
// Only auto-set unique if this will be the only primary key
if (primaryKeyCount === 0) {
updates.unique = true;
}
updateField(updates);
} else {
// When removing primary key
updateField({
primaryKey: false,
});
}
},
[primaryKeyCount, updateField]
);
const handleNullableToggle = useCallback(
(value: boolean) => {
updateField({ nullable: value });
},
[updateField]
);
const handleNameChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
updateField({ name: e.target.value });
},
[updateField]
);
return (
<div
className="flex flex-1 touch-none flex-row justify-between gap-2 p-1"
@@ -215,11 +261,7 @@ export const TableField: React.FC<TableFieldProps> = ({
'side_panel.tables_section.table.field_name'
)}
value={field.name}
onChange={(e) =>
updateField({
name: e.target.value,
})
}
onChange={handleNameChange}
/>
</span>
</TooltipTrigger>
@@ -265,11 +307,7 @@ export const TableField: React.FC<TableFieldProps> = ({
<span>
<TableFieldToggle
pressed={field.nullable}
onPressedChange={(value) =>
updateField({
nullable: value,
})
}
onPressedChange={handleNullableToggle}
>
N
</TableFieldToggle>
@@ -284,12 +322,7 @@ export const TableField: React.FC<TableFieldProps> = ({
<span>
<TableFieldToggle
pressed={field.primaryKey}
onPressedChange={(value) =>
updateField({
unique: value,
primaryKey: value,
})
}
onPressedChange={handlePrimaryKeyToggle}
>
<KeyRound className="h-3.5" />
</TableFieldToggle>
@@ -301,6 +334,7 @@ export const TableField: React.FC<TableFieldProps> = ({
</Tooltip>
<TableFieldPopover
field={field}
table={table}
updateField={updateField}
removeField={removeField}
databaseType={databaseType}

View File

@@ -56,6 +56,32 @@ export const TableListItemContent: React.FC<TableListItemContentProps> = ({
>(['fields']);
const sensors = useSensors(useSensor(PointerSensor));
// Create a memoized version of the field updater that handles primary key logic
const handleFieldUpdate = useCallback(
(fieldId: string, attrs: Partial<DBField>) => {
updateField(table.id, fieldId, attrs);
// Handle the case when removing a primary key and only one remains
if (attrs.primaryKey === false) {
const remainingPrimaryKeys = table.fields.filter(
(f) => f.id !== fieldId && f.primaryKey
);
if (remainingPrimaryKeys.length === 1) {
// Set the remaining primary key field as unique
updateField(
table.id,
remainingPrimaryKeys[0].id,
{
unique: true,
},
{ updateHistory: false }
);
}
}
},
[table.id, table.fields, updateField]
);
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
@@ -147,14 +173,9 @@ export const TableListItemContent: React.FC<TableListItemContentProps> = ({
<TableField
key={field.id}
field={field}
updateField={(
attrs: Partial<DBField>
) =>
updateField(
table.id,
field.id,
attrs
)
table={table}
updateField={(attrs) =>
handleFieldUpdate(field.id, attrs)
}
removeField={() =>
removeField(table.id, field.id)

View File

@@ -17,13 +17,22 @@ 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';
export interface TableListProps {
tables: DBTable[];
groupBy?: 'schema' | 'area';
areas?: Area[];
}
export const TableList: React.FC<TableListProps> = ({ tables }) => {
export const TableList: React.FC<TableListProps> = ({
tables,
groupBy = 'schema',
areas = [],
}) => {
const { updateTablesState } = useChartDB();
const { t } = useTranslation();
const { openTableFromSidebar, openedTableInSidebar } = useLayout();
const lastOpenedTable = React.useRef<string | null>(null);
@@ -87,62 +96,134 @@ 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),
},
]
: []),
];
}
// Default - no grouping, just return all tables as one group
return [
{
id: 'all',
name: '',
tables: sortTables(tables),
},
];
}, [tables, groupBy, areas, sortTables, t]);
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, 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,18 +21,32 @@ 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 { 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,
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 supportsSchemas = useMemo(
() => databasesWithSchemas.includes(databaseType),
[databaseType]
);
const filteredTables = useMemo(() => {
const filterTableName: (table: DBTable) => boolean = (table) =>
@@ -162,6 +176,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} />
@@ -193,7 +238,11 @@ export const TablesSection: React.FC<TablesSectionProps> = () => {
</Button>
</div>
) : (
<TableList tables={filteredTables} />
<TableList
tables={filteredTables}
groupBy={groupBy}
areas={areas}
/>
)}
</ScrollArea>
)}