Database diagrams editor that allows you to visualize and design your DB with a single query.
TypeScript databasedbdb-migrationeditorerdmariadbmssqlmysqlpostgresqlreactreact-flowschema-migrationssqlsqlitetypescriptvisualizationxyflow
validate same field types when connecting
Guy Ben-Aharon90c5d589704a
diff --git a/package-lock.json b/package-lock.jsonindex 04a79d51..88bf0616 100644--- a/package-lock.json+++ b/package-lock.json@@ -21,6 +21,7 @@"@radix-ui/react-select": "^2.1.1","@radix-ui/react-separator": "^1.1.0","@radix-ui/react-slot": "^1.1.0",+ "@radix-ui/react-toast": "^1.2.1","@radix-ui/react-toggle": "^1.1.0","@radix-ui/react-toggle-group": "^1.1.0","@radix-ui/react-tooltip": "^1.1.2",@@ -1915,6 +1916,40 @@}}},+ "node_modules/@radix-ui/react-toast": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-toast/-/react-toast-1.2.1.tgz",+ "integrity": "sha512-5trl7piMXcZiCq7MW6r8YYmu0bK5qDpTWz+FdEPdKyft2UixkspheYbjbrLXVN5NGKHFbOP7lm8eD0biiSqZqg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.0",+ "@radix-ui/react-collection": "1.1.0",+ "@radix-ui/react-compose-refs": "1.1.0",+ "@radix-ui/react-context": "1.1.0",+ "@radix-ui/react-dismissable-layer": "1.1.0",+ "@radix-ui/react-portal": "1.1.1",+ "@radix-ui/react-presence": "1.1.0",+ "@radix-ui/react-primitive": "2.0.0",+ "@radix-ui/react-use-callback-ref": "1.1.0",+ "@radix-ui/react-use-controllable-state": "1.1.0",+ "@radix-ui/react-use-layout-effect": "1.1.0",+ "@radix-ui/react-visually-hidden": "1.1.0"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },"node_modules/@radix-ui/react-toggle": {"version": "1.1.0","resolved": "https://registry.npmjs.org/@radix-ui/react-toggle/-/react-toggle-1.1.0.tgz",diff --git a/package.json b/package.jsonindex 3db65def..5c5ca1ab 100644--- a/package.json+++ b/package.json@@ -24,6 +24,7 @@"@radix-ui/react-select": "^2.1.1","@radix-ui/react-separator": "^1.1.0","@radix-ui/react-slot": "^1.1.0",+ "@radix-ui/react-toast": "^1.2.1","@radix-ui/react-toggle": "^1.1.0","@radix-ui/react-toggle-group": "^1.1.0","@radix-ui/react-tooltip": "^1.1.2",diff --git a/src/components/toast/toast.tsx b/src/components/toast/toast.tsxnew file mode 100644index 00000000..c1ea5f44--- /dev/null+++ b/src/components/toast/toast.tsx@@ -0,0 +1,127 @@+import React from 'react';+import { Cross2Icon } from '@radix-ui/react-icons';+import * as ToastPrimitives from '@radix-ui/react-toast';+import { cva, type VariantProps } from 'class-variance-authority';++import { cn } from '@/lib/utils';++const ToastProvider = ToastPrimitives.Provider;++const ToastViewport = React.forwardRef<+ React.ElementRef<typeof ToastPrimitives.Viewport>,+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>+>(({ className, ...props }, ref) => (+ <ToastPrimitives.Viewport+ ref={ref}+ className={cn(+ 'fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]',+ className+ )}+ {...props}+ />+));+ToastViewport.displayName = ToastPrimitives.Viewport.displayName;++const toastVariants = cva(+ 'group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full',+ {+ variants: {+ variant: {+ default: 'border bg-background text-foreground',+ destructive:+ 'destructive group border-destructive bg-destructive text-destructive-foreground',+ },+ },+ defaultVariants: {+ variant: 'default',+ },+ }+);++const Toast = React.forwardRef<+ React.ElementRef<typeof ToastPrimitives.Root>,+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &+ VariantProps<typeof toastVariants>+>(({ className, variant, ...props }, ref) => {+ return (+ <ToastPrimitives.Root+ ref={ref}+ className={cn(toastVariants({ variant }), className)}+ {...props}+ />+ );+});+Toast.displayName = ToastPrimitives.Root.displayName;++const ToastAction = React.forwardRef<+ React.ElementRef<typeof ToastPrimitives.Action>,+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>+>(({ className, ...props }, ref) => (+ <ToastPrimitives.Action+ ref={ref}+ className={cn(+ 'inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive',+ className+ )}+ {...props}+ />+));+ToastAction.displayName = ToastPrimitives.Action.displayName;++const ToastClose = React.forwardRef<+ React.ElementRef<typeof ToastPrimitives.Close>,+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>+>(({ className, ...props }, ref) => (+ <ToastPrimitives.Close+ ref={ref}+ className={cn(+ 'absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600',+ className+ )}+ toast-close=""+ {...props}+ >+ <Cross2Icon className="h-4 w-4" />+ </ToastPrimitives.Close>+));+ToastClose.displayName = ToastPrimitives.Close.displayName;++const ToastTitle = React.forwardRef<+ React.ElementRef<typeof ToastPrimitives.Title>,+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>+>(({ className, ...props }, ref) => (+ <ToastPrimitives.Title+ ref={ref}+ className={cn('text-sm font-semibold [&+div]:text-xs', className)}+ {...props}+ />+));+ToastTitle.displayName = ToastPrimitives.Title.displayName;++const ToastDescription = React.forwardRef<+ React.ElementRef<typeof ToastPrimitives.Description>,+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>+>(({ className, ...props }, ref) => (+ <ToastPrimitives.Description+ ref={ref}+ className={cn('text-sm opacity-90', className)}+ {...props}+ />+));+ToastDescription.displayName = ToastPrimitives.Description.displayName;++type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>;++type ToastActionElement = React.ReactElement<typeof ToastAction>;++export {+ type ToastProps,+ type ToastActionElement,+ ToastProvider,+ ToastViewport,+ Toast,+ ToastTitle,+ ToastDescription,+ ToastClose,+ ToastAction,+};diff --git a/src/components/toast/toaster.tsx b/src/components/toast/toaster.tsxnew file mode 100644index 00000000..db9ef9b4--- /dev/null+++ b/src/components/toast/toaster.tsx@@ -0,0 +1,42 @@+import React from 'react';+import {+ Toast,+ ToastClose,+ ToastDescription,+ ToastProvider,+ ToastTitle,+ ToastViewport,+} from '@/components/toast/toast';+import { useToast } from '@/components/toast/use-toast';++export function Toaster() {+ const { toasts } = useToast();++ return (+ <ToastProvider>+ {toasts.map(function ({+ id,+ title,+ description,+ action,+ ...props+ }) {+ return (+ <Toast key={id} {...props}>+ <div className="grid gap-1">+ {title && <ToastTitle>{title}</ToastTitle>}+ {description && (+ <ToastDescription>+ {description}+ </ToastDescription>+ )}+ </div>+ {action}+ <ToastClose />+ </Toast>+ );+ })}+ <ToastViewport />+ </ToastProvider>+ );+}diff --git a/src/components/toast/use-toast.ts b/src/components/toast/use-toast.tsnew file mode 100644index 00000000..1d600967--- /dev/null+++ b/src/components/toast/use-toast.ts@@ -0,0 +1,190 @@+// Inspired by react-hot-toast library+import React from 'react';++import type { ToastActionElement, ToastProps } from '@/components/toast/toast';++const TOAST_LIMIT = 1;+const TOAST_REMOVE_DELAY = 1000000;++type ToasterToast = ToastProps & {+ id: string;+ title?: React.ReactNode;+ description?: React.ReactNode;+ action?: ToastActionElement;+};++const actionTypes = {+ ADD_TOAST: 'ADD_TOAST',+ UPDATE_TOAST: 'UPDATE_TOAST',+ DISMISS_TOAST: 'DISMISS_TOAST',+ REMOVE_TOAST: 'REMOVE_TOAST',+} as const;++let count = 0;++function genId() {+ count = (count + 1) % Number.MAX_SAFE_INTEGER;+ return count.toString();+}++type ActionType = typeof actionTypes;++type Action =+ | {+ type: ActionType['ADD_TOAST'];+ toast: ToasterToast;+ }+ | {+ type: ActionType['UPDATE_TOAST'];+ toast: Partial<ToasterToast>;+ }+ | {+ type: ActionType['DISMISS_TOAST'];+ toastId?: ToasterToast['id'];+ }+ | {+ type: ActionType['REMOVE_TOAST'];+ toastId?: ToasterToast['id'];+ };++interface State {+ toasts: ToasterToast[];+}++const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>();++const addToRemoveQueue = (toastId: string) => {+ if (toastTimeouts.has(toastId)) {+ return;+ }++ const timeout = setTimeout(() => {+ toastTimeouts.delete(toastId);+ dispatch({+ type: 'REMOVE_TOAST',+ toastId: toastId,+ });+ }, TOAST_REMOVE_DELAY);++ toastTimeouts.set(toastId, timeout);+};++export const reducer = (state: State, action: Action): State => {+ switch (action.type) {+ case 'ADD_TOAST':+ return {+ ...state,+ toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),+ };++ case 'UPDATE_TOAST':+ return {+ ...state,+ toasts: state.toasts.map((t) =>+ t.id === action.toast.id ? { ...t, ...action.toast } : t+ ),+ };++ case 'DISMISS_TOAST': {+ const { toastId } = action;++ // ! Side effects ! - This could be extracted into a dismissToast() action,+ // but I'll keep it here for simplicity+ if (toastId) {+ addToRemoveQueue(toastId);+ } else {+ state.toasts.forEach((toast) => {+ addToRemoveQueue(toast.id);+ });+ }++ return {+ ...state,+ toasts: state.toasts.map((t) =>+ t.id === toastId || toastId === undefined+ ? {+ ...t,+ open: false,+ }+ : t+ ),+ };+ }+ case 'REMOVE_TOAST':+ if (action.toastId === undefined) {+ return {+ ...state,+ toasts: [],+ };+ }+ return {+ ...state,+ toasts: state.toasts.filter((t) => t.id !== action.toastId),+ };+ }+};++const listeners: Array<(state: State) => void> = [];++let memoryState: State = { toasts: [] };++function dispatch(action: Action) {+ memoryState = reducer(memoryState, action);+ listeners.forEach((listener) => {+ listener(memoryState);+ });+}++type Toast = Omit<ToasterToast, 'id'>;++function toast({ ...props }: Toast) {+ const id = genId();++ const update = (props: ToasterToast) =>+ dispatch({+ type: 'UPDATE_TOAST',+ toast: { ...props, id },+ });+ const dismiss = () => dispatch({ type: 'DISMISS_TOAST', toastId: id });++ dispatch({+ type: 'ADD_TOAST',+ toast: {+ ...props,+ id,+ open: true,+ onOpenChange: (open) => {+ if (!open) dismiss();+ },+ },+ });++ return {+ id: id,+ dismiss,+ update,+ };+}++function useToast() {+ const [state, setState] = React.useState<State>(memoryState);++ React.useEffect(() => {+ listeners.push(setState);+ return () => {+ const index = listeners.indexOf(setState);+ if (index > -1) {+ listeners.splice(index, 1);+ }+ };+ }, [state]);++ return {+ ...state,+ toast,+ dismiss: (toastId?: string) =>+ dispatch({ type: 'DISMISS_TOAST', toastId }),+ };+}++export { useToast, toast };diff --git a/src/context/chartdb-context/chartdb-provider.tsx b/src/context/chartdb-context/chartdb-provider.tsxindex f491daae..cd12c4ae 100644--- a/src/context/chartdb-context/chartdb-provider.tsx+++ b/src/context/chartdb-context/chartdb-provider.tsx@@ -140,7 +140,10 @@ export const ChartDBProvider: React.FC<React.PropsWithChildren> = ({{id: generateId(),name: 'id',- type: 'bigint',+ type:+ databaseType === DatabaseType.SQLITE+ ? 'integer'+ : 'bigint',unique: true,nullable: false,primaryKey: true,@@ -155,7 +158,7 @@ export const ChartDBProvider: React.FC<React.PropsWithChildren> = ({await addTable(table);return table;- }, [addTable, tables]);+ }, [addTable, tables, databaseType]);const getTable: ChartDBContext['getTable'] = useCallback((id: string) => tables.find((table) => table.id === id) ?? null,diff --git a/src/pages/editor-page/canvas/canvas.tsx b/src/pages/editor-page/canvas/canvas.tsxindex a8081312..9a1e44c3 100644--- a/src/pages/editor-page/canvas/canvas.tsx+++ b/src/pages/editor-page/canvas/canvas.tsx@@ -21,6 +21,7 @@ import { TableEdge, TableEdgeType } from './table-edge';import { useChartDB } from '@/hooks/use-chartdb';import { LEFT_HANDLE_ID_PREFIX, TARGET_ID_PREFIX } from './table-node-field';import { Toolbar } from './toolbar/toolbar';+import { useToast } from '@/components/toast/use-toast';type AddEdgeParams = Parameters<typeof addEdge<TableEdgeType>>[0];@@ -31,12 +32,14 @@ export interface CanvasProps {}export const Canvas: React.FC<CanvasProps> = () => {const { getEdge } = useReactFlow();+ const { toast } = useToast();const {tables,relationships,createRelationship,updateTablesState,removeRelationships,+ getField,} = useChartDB();const nodeTypes = useMemo(() => ({ table: TableNode }), []);const edgeTypes = useMemo(() => ({ 'table-edge': TableEdge }), []);@@ -85,11 +88,32 @@ export const Canvas: React.FC<CanvasProps> = () => {const onConnectHandler = useCallback(async (params: AddEdgeParams) => {+ const sourceTableId = params.source;+ const targetTableId = params.target;+ const sourceFieldId = params.sourceHandle?.split('_')?.pop() ?? '';+ const targetFieldId = params.targetHandle?.split('_')?.pop() ?? '';+ const sourceField = getField(sourceTableId, sourceFieldId);+ const targetField = getField(targetTableId, targetFieldId);++ if (!sourceField || !targetField) {+ return;+ }++ if (sourceField.type !== targetField.type) {+ toast({+ title: 'Field types do not match',+ variant: 'destructive',+ description:+ 'Relationships can only be created between fields of the same type',+ });+ return;+ }+const relationship = await createRelationship({- sourceTableId: params.source,- targetTableId: params.target,- sourceFieldId: params.sourceHandle?.split('_')?.pop() ?? '',- targetFieldId: params.targetHandle?.split('_')?.pop() ?? '',+ sourceTableId,+ targetTableId,+ sourceFieldId,+ targetFieldId,});return setEdges((edges) =>addEdge<TableEdgeType>(@@ -98,7 +122,7 @@ export const Canvas: React.FC<CanvasProps> = () => {));},- [setEdges, createRelationship]+ [setEdges, createRelationship, getField, toast]);const onEdgesChangeHandler: OnEdgesChange<TableEdgeType> = useCallback(diff --git a/src/pages/editor-page/editor-page.tsx b/src/pages/editor-page/editor-page.tsxindex 4d783b63..008ed2f1 100644--- a/src/pages/editor-page/editor-page.tsx+++ b/src/pages/editor-page/editor-page.tsx@@ -12,6 +12,7 @@ import { useConfig } from '@/hooks/use-config';import { useChartDB } from '@/hooks/use-chartdb';import { useDialog } from '@/hooks/use-dialog';import { useRedoUndoStack } from '@/hooks/use-redo-undo-stack';+import { Toaster } from '@/components/toast/toaster';export const EditorPage: React.FC = () => {const { loadDiagram } = useChartDB();@@ -52,17 +53,20 @@ export const EditorPage: React.FC = () => {]);return (- <section className="bg-background h-screen w-screen flex flex-col">- <TopNavbar />- <ResizablePanelGroup direction="horizontal">- <ResizablePanel defaultSize={25} minSize={25} maxSize={99}>- <SidePanel />- </ResizablePanel>- <ResizableHandle />- <ResizablePanel defaultSize={75}>- <Canvas />- </ResizablePanel>- </ResizablePanelGroup>- </section>+ <>+ <section className="bg-background h-screen w-screen flex flex-col">+ <TopNavbar />+ <ResizablePanelGroup direction="horizontal">+ <ResizablePanel defaultSize={25} minSize={25} maxSize={99}>+ <SidePanel />+ </ResizablePanel>+ <ResizableHandle />+ <ResizablePanel defaultSize={75}>+ <Canvas />+ </ResizablePanel>+ </ResizablePanelGroup>+ </section>+ <Toaster />+ </>);};