Skip to content

Free, simple, and intuitive online database diagram editor and SQL generator.

Update Open Modal design (#1061)

1ilite680c5b9592b
diff --git a/src/components/EditorHeader/Modal/Open.jsx b/src/components/EditorHeader/Modal/Open.jsx
deleted file mode 100644
index 3dbfa389..00000000
--- a/src/components/EditorHeader/Modal/Open.jsx
+++ /dev/null
@@ -1,250 +0,0 @@
-import { useEffect, useState } from "react";
-import { Banner, Spin, Tag } from "@douyinfe/semi-ui";
-import { useLiveQuery } from "dexie-react-hooks";
-import { useTranslation } from "react-i18next";
-import { db } from "../../../data/db";
-import { databases } from "../../../data/databases";
-import { useExtensions } from "../../../context/ExtensionsContext";
-
-function formatSize(bytes) {
- if (bytes == null) return "";
- if (bytes >= 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(1) + "MB";
- if (bytes >= 1024) return (bytes / 1024).toFixed(1) + "KB";
- return bytes + "B";
-}
-
-function useDiagramList() {
- const extensions = useExtensions();
- const cloudList = extensions?.cloudList;
- const cloudEnabled = typeof cloudList === "function";
- const cloudCurrentUserId = extensions?.cloudCurrentUserId ?? null;
-
- const localDiagrams = useLiveQuery(() => db.diagrams.toArray(), []);
-
- const [cloudState, setCloudState] = useState(() => ({
- loading: cloudEnabled,
- error: null,
- items: null,
- }));
-
- useEffect(() => {
- if (!cloudEnabled) {
- setCloudState({ loading: false, error: null, items: [] });
- return undefined;
- }
- let cancelled = false;
- setCloudState({ loading: true, error: null, items: null });
- cloudList()
- .then((items) => {
- if (cancelled) return;
- setCloudState({ loading: false, error: null, items });
- })
- .catch((err) => {
- if (cancelled) return;
- setCloudState({
- loading: false,
- error: err?.response?.data?.error || err?.message || "Failed to load",
- items: null,
- });
- });
- return () => {
- cancelled = true;
- };
- }, [cloudEnabled, cloudList]);
-
- return {
- loading: cloudState.loading || localDiagrams === undefined,
- error: cloudState.error,
- cloud: cloudState.items ?? [],
- local: localDiagrams ?? [],
- cloudEnabled,
- currentUserId: cloudCurrentUserId,
- };
-}
-
-function ownerLabel(d, currentUserId) {
- if (!d?.owner) return null;
- if (currentUserId && String(d.owner.id) === String(currentUserId)) {
- return "You";
- }
- return d.owner.username || d.owner.email || `User ${d.owner.id}`;
-}
-
-function DiagramTable({
- items,
- isCloud,
- currentUserId,
- selectedDiagramId,
- setSelectedDiagramId,
- cloudRowActions,
-}) {
- const { t } = useTranslation();
- const showOwner =
- isCloud &&
- items.some((d) => d.owner && String(d.owner.id) !== String(currentUserId));
- const showRowActions = isCloud && typeof cloudRowActions === "function";
-
- return (
- <table className="w-full text-left border-separate border-spacing-x-0">
- <thead>
- <tr>
- <th>{t("name")}</th>
- {showOwner && <th>Owner</th>}
- <th>{t("last_modified")}</th>
- <th>{t("size")}</th>
- <th>{t("type")}</th>
- {showRowActions && <th />}
- </tr>
- </thead>
- <tbody>
- {items.map((d) => {
- const lastModified =
- d.lastModified instanceof Date
- ? d.lastModified
- : d.lastModified
- ? new Date(d.lastModified)
- : null;
- const size = isCloud
- ? formatSize(d.sizeBytes)
- : formatSize(JSON.stringify(d).length);
- const dbInfo = databases[d.database];
- const owner = ownerLabel(d, currentUserId);
- return (
- <tr
- key={d.diagramId}
- className={`cursor-pointer ${
- selectedDiagramId === d.diagramId
- ? "bg-blue-300/30"
- : "hover-1"
- }`}
- onClick={() => setSelectedDiagramId(d.diagramId)}
- >
- <td className="py-1">
- <i className="bi bi-file-earmark-text text-[16px] me-1 opacity-60" />
- {d.name}
- </td>
- {showOwner && (
- <td className="py-1">
- {owner === "You" ? (
- <Tag size="small" color="blue">
- You
- </Tag>
- ) : (
- <span className="text-sm">{owner}</span>
- )}
- </td>
- )}
- <td className="py-1">
- {lastModified
- ? lastModified.toLocaleDateString() +
- " " +
- lastModified.toLocaleTimeString()
- : ""}
- </td>
- <td className="py-1">{size}</td>
- <td className="py-1">{dbInfo?.name ?? "Generic"}</td>
- {showRowActions && (
- <td
- className="py-1 text-right"
- onClick={(e) => e.stopPropagation()}
- >
- {cloudRowActions(d)}
- </td>
- )}
- </tr>
- );
- })}
- </tbody>
- </table>
- );
-}
-
-function SectionHeader({ children }) {
- return (
- <h4 className="text-xs uppercase tracking-wider text-zinc-500 dark:text-zinc-400 mb-1 mt-2 first:mt-0">
- {children}
- </h4>
- );
-}
-
-export default function Open({ selectedDiagramId, setSelectedDiagramId }) {
- const { t } = useTranslation();
- const { loading, error, cloud, local, cloudEnabled, currentUserId } =
- useDiagramList();
- const extensions = useExtensions();
- const cloudRowActions = extensions?.cloudRowActions;
-
- if (loading) {
- return (
- <div className="flex justify-center py-10">
- <Spin />
- </div>
- );
- }
-
- if (error) {
- return (
- <Banner
- fullMode={false}
- type="danger"
- bordered
- icon={null}
- closeIcon={null}
- description={<div>{error}</div>}
- />
- );
- }
-
- const hasCloud = cloud.length > 0;
- const hasLocal = local.length > 0;
-
- if (!hasCloud && !hasLocal) {
- return (
- <Banner
- fullMode={false}
- type="info"
- bordered
- icon={null}
- closeIcon={null}
- description={<div>{t("no_saved_diagrams")}</div>}
- />
- );
- }
-
- return (
- <div className="max-h-[360px] overflow-auto space-y-3">
- {cloudEnabled && (
- <section>
- <SectionHeader>Cloud diagrams</SectionHeader>
- {hasCloud ? (
- <DiagramTable
- items={cloud}
- isCloud
- currentUserId={currentUserId}
- selectedDiagramId={selectedDiagramId}
- setSelectedDiagramId={setSelectedDiagramId}
- cloudRowActions={cloudRowActions}
- />
- ) : (
- <div className="text-sm text-zinc-500 dark:text-zinc-400 px-1 py-2">
- No cloud diagrams yet.
- </div>
- )}
- </section>
- )}
- {hasLocal && (
- <section>
- {cloudEnabled && <SectionHeader>Local (this browser)</SectionHeader>}
- <DiagramTable
- items={local}
- isCloud={false}
- currentUserId={currentUserId}
- selectedDiagramId={selectedDiagramId}
- setSelectedDiagramId={setSelectedDiagramId}
- cloudRowActions={cloudRowActions}
- />
- </section>
- )}
- </div>
- );
-}
diff --git a/src/components/EditorHeader/Modal/Open/components/DiagramFilters.jsx b/src/components/EditorHeader/Modal/Open/components/DiagramFilters.jsx
new file mode 100644
index 00000000..0087bd7a
--- /dev/null
+++ b/src/components/EditorHeader/Modal/Open/components/DiagramFilters.jsx
@@ -0,0 +1,58 @@
+import { Button, Input, Select } from "@douyinfe/semi-ui";
+import { IconSearch } from "@douyinfe/semi-icons";
+import { useTranslation } from "react-i18next";
+import { ALL } from "../diagram";
+
+const SOURCE_OPTIONS = [
+ { value: ALL, label: "All types" },
+ { value: "cloud", label: "Cloud" },
+ { value: "local", label: "Local" },
+];
+
+export default function DiagramFilters({
+ query,
+ onQueryChange,
+ database,
+ onDatabaseChange,
+ databaseOptions,
+ source,
+ onSourceChange,
+ showSourceFilter,
+ onClear,
+}) {
+ const { t } = useTranslation();
+ const hasActiveFilters =
+ query.trim() !== "" || database !== ALL || source !== ALL;
+
+ return (
+ <div className="flex gap-2 flex-wrap mb-3">
+ <Input
+ prefix={<IconSearch />}
+ placeholder={t("search")}
+ value={query}
+ onChange={onQueryChange}
+ showClear
+ className="flex-1"
+ />
+ <Select
+ value={database}
+ onChange={onDatabaseChange}
+ optionList={databaseOptions}
+ className="min-w-[150px]"
+ />
+ {showSourceFilter && (
+ <Select
+ value={source}
+ onChange={onSourceChange}
+ optionList={SOURCE_OPTIONS}
+ className="min-w-[130px]"
+ />
+ )}
+ {hasActiveFilters && (
+ <Button theme="borderless" onClick={onClear}>
+ {t("clear")}
+ </Button>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/EditorHeader/Modal/Open/components/DiagramTable.jsx b/src/components/EditorHeader/Modal/Open/components/DiagramTable.jsx
new file mode 100644
index 00000000..3b2a6216
--- /dev/null
+++ b/src/components/EditorHeader/Modal/Open/components/DiagramTable.jsx
@@ -0,0 +1,119 @@
+import { Tag } from "@douyinfe/semi-ui";
+import { useTranslation } from "react-i18next";
+import SortableHeader from "./SortableHeader";
+import { SOURCE, databaseName, formatSize, ownerLabel } from "../diagram";
+
+function TypeCell({ entry }) {
+ const isCloud = entry.source === SOURCE.cloud;
+ return (
+ <Tag size="small" color={isCloud ? "cyan" : "grey"}>
+ {isCloud ? "Cloud" : "Local"}
+ </Tag>
+ );
+}
+
+function OwnerCell({ entry, currentUserId }) {
+ const label = ownerLabel(entry, currentUserId);
+ if (label === "You") {
+ return (
+ <Tag size="small" color="blue">
+ You
+ </Tag>
+ );
+ }
+ return <span className="text-sm">{label}</span>;
+}
+
+function formatTimestamp(date) {
+ return date ? `${date.toLocaleDateString()} ${date.toLocaleTimeString()}` : "";
+}
+
+function useColumns({ showType, showOwner, currentUserId }) {
+ const { t } = useTranslation();
+ return [
+ {
+ key: "name",
+ label: t("name"),
+ sortable: true,
+ render: ({ entry }) => entry.name,
+ },
+ showType && { key: "type", label: "Type", render: TypeCell },
+ showOwner && {
+ key: "owner",
+ label: "Owner",
+ render: (props) => <OwnerCell {...props} currentUserId={currentUserId} />,
+ },
+ { key: "database", label: "Database", render: ({ entry }) => databaseName(entry.database) },
+ {
+ key: "lastModified",
+ label: t("last_modified"),
+ sortable: true,
+ render: ({ entry }) => formatTimestamp(entry.lastModified),
+ },
+ {
+ key: "size",
+ label: t("size"),
+ sortable: true,
+ render: ({ entry }) => formatSize(entry.size),
+ },
+ ].filter(Boolean);
+}
+
+export default function DiagramTable({
+ entries,
+ sort,
+ onSort,
+ selectedDiagramId,
+ onSelect,
+ showType,
+ showOwner,
+ currentUserId,
+}) {
+ const columns = useColumns({ showType, showOwner, currentUserId });
+
+ return (
+ <table className="w-full text-left border-separate border-spacing-x-0">
+ <thead>
+ <tr>
+ {columns.map((column) =>
+ column.sortable ? (
+ <SortableHeader
+ key={column.key}
+ label={column.label}
+ sortKey={column.key}
+ sort={sort}
+ onSort={onSort}
+ className="sticky top-0 z-10 py-2 px-3 border-b border-zinc-100 dark:border-zinc-700 sidesheet-theme"
+ />
+ ) : (
+ <th
+ key={column.key}
+ className="sticky top-0 z-10 py-2 px-3 border-b border-zinc-100 dark:border-zinc-700 sidesheet-theme"
+ >
+ {column.label}
+ </th>
+ ),
+ )}
+ </tr>
+ </thead>
+ <tbody>
+ {entries.map((entry) => {
+ const selected = selectedDiagramId === entry.diagramId;
+ return (
+ <tr
+ key={`${entry.source}-${entry.diagramId}`}
+ className={`cursor-pointer ${selected ? "bg-blue-300/30" : "hover-1"}`}
+ onClick={() => onSelect(entry.diagramId)}
+ >
+ {columns.map((column) => (
+ <td key={column.key} className="py-2 px-3">
+ {column.render({ entry })}
+ </td>
+ ))}
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ );
+}
diff --git a/src/components/EditorHeader/Modal/Open/components/SortableHeader.jsx b/src/components/EditorHeader/Modal/Open/components/SortableHeader.jsx
new file mode 100644
index 00000000..78a929ec
--- /dev/null
+++ b/src/components/EditorHeader/Modal/Open/components/SortableHeader.jsx
@@ -0,0 +1,25 @@
+export default function SortableHeader({
+ label,
+ sortKey,
+ sort,
+ onSort,
+ className,
+ style,
+}) {
+ const active = sort.key === sortKey;
+ const icon =
+ active && sort.dir === "asc" ? "bi-caret-up-fill" : "bi-caret-down-fill";
+
+ return (
+ <th className={className} style={style}>
+ <button
+ type="button"
+ onClick={() => onSort(sortKey)}
+ className="inline-flex items-center gap-1 cursor-pointer select-none bg-transparent border-0 p-0 hover:opacity-80"
+ >
+ {label}
+ <i className={`bi text-[12px] ${icon} ${active ? "" : "opacity-30"}`} />
+ </button>
+ </th>
+ );
+}
diff --git a/src/components/EditorHeader/Modal/Open/diagram.js b/src/components/EditorHeader/Modal/Open/diagram.js
new file mode 100644
index 00000000..2d25e81d
--- /dev/null
+++ b/src/components/EditorHeader/Modal/Open/diagram.js
@@ -0,0 +1,96 @@
+import { databases } from "../../../../data/databases";
+
+const KILOBYTE = 1024;
+const MEGABYTE = 1024 * KILOBYTE;
+
+export const SOURCE = { cloud: "cloud", local: "local" };
+export const ALL = "all";
+
+export function formatSize(bytes) {
+ if (bytes == null) return "";
+ if (bytes >= MEGABYTE) return `${(bytes / MEGABYTE).toFixed(1)}MB`;
+ if (bytes >= KILOBYTE) return `${(bytes / KILOBYTE).toFixed(1)}KB`;
+ return `${bytes}B`;
+}
+
+export function databaseName(database) {
+ return databases[database]?.name ?? "Generic";
+}
+
+export function ownerLabel(entry, currentUserId) {
+ const { owner } = entry;
+ if (!owner) return null;
+ if (currentUserId && String(owner.id) === String(currentUserId)) return "You";
+ return owner.username || owner.email || `User ${owner.id}`;
+}
+
+function toDate(value) {
+ if (value instanceof Date) return value;
+ return value ? new Date(value) : null;
+}
+
+function toEntry(raw, source, size) {
+ return {
+ raw,
+ source,
+ diagramId: raw.diagramId,
+ name: raw.name ?? "",
+ database: raw.database || "generic",
+ owner: source === SOURCE.cloud ? (raw.owner ?? null) : null,
+ size,
+ lastModified: toDate(raw.lastModified),
+ };
+}
+
+export function mergeDiagrams(cloud, local) {
+ return [
+ ...cloud.map((d) => toEntry(d, SOURCE.cloud, d.sizeBytes ?? 0)),
+ ...local.map((d) =>
+ toEntry(d, SOURCE.local, JSON.stringify(d).length),
+ ),
+ ];
+}
+
+export function databaseOptions(entries) {
+ const present = [...new Set(entries.map((entry) => entry.database))];
+ return [
+ { value: ALL, label: "All databases" },
+ ...present.map((database) => ({
+ value: database,
+ label: databaseName(database),
+ })),
+ ];
+}
+
+export function filterDiagrams(entries, { query, database, source }) {
+ const needle = query.trim().toLowerCase();
+ return entries.filter((entry) => {
+ if (needle && !entry.name.toLowerCase().includes(needle)) return false;
+ if (database !== ALL && entry.database !== database) return false;
+ if (source !== ALL && entry.source !== source) return false;
+ return true;
+ });
+}
+
+const comparators = {
+ name: (a, b) => a.name.localeCompare(b.name),
+ size: (a, b) => a.size - b.size,
+ lastModified: (a, b) => timeOf(a) - timeOf(b),
+};
+
+function timeOf(entry) {
+ return entry.lastModified ? entry.lastModified.getTime() : 0;
+}
+
+export function sortDiagrams(entries, { key, dir }) {
+ const compare = comparators[key] ?? comparators.lastModified;
+ const factor = dir === "asc" ? 1 : -1;
+ return [...entries].sort((a, b) => factor * compare(a, b));
+}
+
+export function nextSort(current, key) {
+ if (current.key === key) {
+ return { key, dir: current.dir === "asc" ? "desc" : "asc" };
+ }
+ return { key, dir: key === "name" ? "asc" : "desc" };
+}
diff --git a/src/components/EditorHeader/Modal/Open/hooks/useDiagramList.js b/src/components/EditorHeader/Modal/Open/hooks/useDiagramList.js
new file mode 100644
index 00000000..e3002d95
--- /dev/null
+++ b/src/components/EditorHeader/Modal/Open/hooks/useDiagramList.js
@@ -0,0 +1,51 @@
+import { useEffect, useState } from "react";
+import { useLiveQuery } from "dexie-react-hooks";
+import { db } from "../../../../../data/db";
+import { useExtensions } from "../../../../../context/ExtensionsContext";
+
+const DISABLED = { loading: false, error: null, items: [] };
+
+function readError(err) {
+ return err?.response?.data?.error || err?.message || "Failed to load";
+}
+
+export function useDiagramList() {
+ const extensions = useExtensions();
+ const cloudList = extensions?.cloudList;
+ const cloudEnabled = typeof cloudList === "function";
+ const currentUserId = extensions?.cloudCurrentUserId ?? null;
+
+ const local = useLiveQuery(() => db.diagrams.toArray(), []);
+ const [cloud, setCloud] = useState(() =>
+ cloudEnabled ? { loading: true, error: null, items: null } : DISABLED,
+ );
+
+ useEffect(() => {
+ if (!cloudEnabled) {
+ setCloud(DISABLED);
+ return undefined;
+ }
+ let cancelled = false;
+ setCloud({ loading: true, error: null, items: null });
+ cloudList()
+ .then((items) => {
+ if (!cancelled) setCloud({ loading: false, error: null, items });
+ })
+ .catch((err) => {
+ if (!cancelled)
+ setCloud({ loading: false, error: readError(err), items: null });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [cloudEnabled, cloudList]);
+
+ return {
+ loading: cloud.loading || local === undefined,
+ error: cloud.error,
+ cloud: cloud.items ?? [],
+ local: local ?? [],
+ cloudEnabled,
+ currentUserId,
+ };
+}
diff --git a/src/components/EditorHeader/Modal/Open/index.jsx b/src/components/EditorHeader/Modal/Open/index.jsx
new file mode 100644
index 00000000..819d6a92
--- /dev/null
+++ b/src/components/EditorHeader/Modal/Open/index.jsx
@@ -0,0 +1,109 @@
+import { useMemo, useState } from "react";
+import { Banner, Spin } from "@douyinfe/semi-ui";
+import { useTranslation } from "react-i18next";
+import { useDiagramList } from "./hooks/useDiagramList";
+import {
+ ALL,
+ databaseOptions,
+ filterDiagrams,
+ mergeDiagrams,
+ nextSort,
+ sortDiagrams,
+} from "./diagram";
+import DiagramFilters from "./components/DiagramFilters";
+import DiagramTable from "./components/DiagramTable";
+
+const DEFAULT_SORT = { key: "lastModified", dir: "desc" };
+
+function InfoBanner({ type, children }) {
+ return (
+ <Banner
+ fullMode={false}
+ type={type}
+ bordered
+ icon={null}
+ closeIcon={null}
+ description={<div>{children}</div>}
+ />
+ );
+}
+
+export default function Open({ selectedDiagramId, setSelectedDiagramId }) {
+ const { t } = useTranslation();
+ const { loading, error, cloud, local, cloudEnabled, currentUserId } =
+ useDiagramList();
+
+ const [query, setQuery] = useState("");
+ const [database, setDatabase] = useState(ALL);
+ const [source, setSource] = useState(ALL);
+ const [sort, setSort] = useState(DEFAULT_SORT);
+
+ const clearFilters = () => {
+ setQuery("");
+ setDatabase(ALL);
+ setSource(ALL);
+ };
+
+ const diagrams = useMemo(() => mergeDiagrams(cloud, local), [cloud, local]);
+ const dbOptions = useMemo(() => databaseOptions(diagrams), [diagrams]);
+ const visible = useMemo(
+ () =>
+ sortDiagrams(filterDiagrams(diagrams, { query, database, source }), sort),
+ [diagrams, query, database, source, sort],
+ );
+
+ const showOwner =
+ cloudEnabled &&
+ visible.some(
+ (entry) =>
+ entry.owner && String(entry.owner.id) !== String(currentUserId),
+ );
+
+ if (loading) {
+ return (
+ <div className="flex justify-center py-10">
+ <Spin />
+ </div>
+ );
+ }
+
+ if (error) return <InfoBanner type="danger">{error}</InfoBanner>;
+
+ if (diagrams.length === 0) {
+ return <InfoBanner type="info">{t("no_saved_diagrams")}</InfoBanner>;
+ }
+
+ return (
+ <div className="flex flex-col">
+ <DiagramFilters
+ query={query}
+ onQueryChange={setQuery}
+ database={database}
+ onDatabaseChange={setDatabase}
+ databaseOptions={dbOptions}
+ source={source}
+ onSourceChange={setSource}
+ showSourceFilter={cloudEnabled}
+ onClear={clearFilters}
+ />
+ <div className="max-h-[360px] overflow-auto">
+ {visible.length > 0 ? (
+ <DiagramTable
+ entries={visible}
+ sort={sort}
+ onSort={(key) => setSort((current) => nextSort(current, key))}
+ selectedDiagramId={selectedDiagramId}
+ onSelect={setSelectedDiagramId}
+ showType={cloudEnabled}
+ showOwner={showOwner}
+ currentUserId={currentUserId}
+ />
+ ) : (
+ <div className="text-sm text-zinc-500 dark:text-zinc-400 px-1 py-6 text-center">
+ No diagrams match your filters.
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}