Free, simple, and intuitive online database diagram editor and SQL generator.
JavaScript databasedatabase-designdatabase-diagramdatabase-schemadbmldiagram-editoreditorer-diagramerderdiagramindexeddbmariadbmcporacle-databaseoracle-dbpostgresqlschema-designsqlsql-serversqlite
Allow configuring custom types (#953)
1ilit8bb2ea2a02ce
diff --git a/src/components/EditorCanvas/Table.jsx b/src/components/EditorCanvas/Table.jsxindex 3791bc89..b10e9eb7 100644--- a/src/components/EditorCanvas/Table.jsx+++ b/src/components/EditorCanvas/Table.jsx@@ -19,7 +19,7 @@ import { Popover, Tag, Button, SideSheet } from "@douyinfe/semi-ui";import { useLayout, useSettings, useDiagram, useSelect } from "../../hooks";import TableInfo from "../EditorSidePanel/TablesTab/TableInfo";import { useTranslation } from "react-i18next";-import { dbToTypes } from "../../data/datatypes";+import { resolveType } from "../../utils/customTypes";import { isRtl } from "../../i18n/utils/rtl";import i18n from "../../i18n/i18n";import { getCommentHeight, getTableHeight } from "../../utils/utils";@@ -280,6 +280,7 @@ export default function Table({</div>{tableData.fields.map((e, i) => {+ const resolved = resolveType(database, e.type);return settings.showFieldSummary ? (<Popoverkey={i}@@ -292,12 +293,15 @@ export default function Table({<p className="me-4 font-bold">{e.name}</p><pclassName={- "ms-4 font-mono " + dbToTypes[database][e.type].color+ "ms-4 font-mono " ++ (resolved.isCustom ? "" : resolved.color)+ }+ style={+ resolved.isCustom ? { color: resolved.color } : {}}>{e.type +- ((dbToTypes[database][e.type].isSized ||- dbToTypes[database][e.type].hasPrecision) &&+ ((resolved.isSized || resolved.hasPrecision) &&e.size &&e.size !== ""? "(" + e.size + ")"@@ -376,6 +380,7 @@ export default function Table({);function field(fieldData, index) {+ const fieldResolved = resolveType(database, fieldData.type);return (<divclassName={`${@@ -474,12 +479,17 @@ export default function Table({{!fieldData.notNull && <span className="font-mono">?</span>}<spanclassName={- "font-mono " + dbToTypes[database][fieldData.type].color+ "font-mono " ++ (fieldResolved.isCustom ? "" : fieldResolved.color)+ }+ style={+ fieldResolved.isCustom+ ? { color: fieldResolved.color }+ : {}}>{fieldData.type +- ((dbToTypes[database][fieldData.type].isSized ||- dbToTypes[database][fieldData.type].hasPrecision) &&+ ((fieldResolved.isSized || fieldResolved.hasPrecision) &&fieldData.size &&fieldData.size !== ""? `(${fieldData.size})`diff --git a/src/components/EditorHeader/ConfigureCustomTypes/components/TypeRow.jsx b/src/components/EditorHeader/ConfigureCustomTypes/components/TypeRow.jsxnew file mode 100644index 00000000..8f9f4326--- /dev/null+++ b/src/components/EditorHeader/ConfigureCustomTypes/components/TypeRow.jsx@@ -0,0 +1,49 @@+import { Button, Input, Select } from "@douyinfe/semi-ui";+import { IconDeleteStroked } from "@douyinfe/semi-icons";+import ColorPicker from "../../../EditorSidePanel/ColorPicker";+import { DB } from "../../../../data/constants";+import { databases } from "../../../../data/databases";++const dbOptions = Object.values(DB)+ .filter((value) => value !== DB.GENERIC)+ .map((value) => ({+ label: databases[value].name,+ value,+ }));++export default function TypeRow({ type, index, onChange, onDelete }) {+ return (+ <tr className="configure-custom-types-row border-b border-[var(--semi-color-border)] last:border-b-0">+ <td className="py-2 pr-3 align-middle">+ <Input+ value={type.type}+ placeholder="VARCHAR"+ onChange={(v) => onChange(index, "type", v)}+ />+ </td>+ <td className="py-2 pr-3 align-middle w-[1%] whitespace-nowrap">+ <ColorPicker+ usePopover={true}+ value={type.color}+ onColorPick={(color) => onChange(index, "color", color)}+ />+ </td>+ <td className="py-2 pr-3 align-middle w-[1%] whitespace-nowrap">+ <Select+ value={type.database}+ className="w-36"+ optionList={dbOptions}+ onChange={(v) => onChange(index, "database", v)}+ />+ </td>+ <td className="py-2 align-middle w-[1%] whitespace-nowrap">+ <Button+ icon={<IconDeleteStroked />}+ type="danger"+ size="large"+ onClick={() => onDelete(index)}+ />+ </td>+ </tr>+ );+}diff --git a/src/components/EditorHeader/ConfigureCustomTypes/index.jsx b/src/components/EditorHeader/ConfigureCustomTypes/index.jsxnew file mode 100644index 00000000..fe19b05b--- /dev/null+++ b/src/components/EditorHeader/ConfigureCustomTypes/index.jsx@@ -0,0 +1,240 @@+import { Button, Modal, Select, Toast } from "@douyinfe/semi-ui";+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import Empty from "../../EditorSidePanel/Empty";+import TypeRow from "./components/TypeRow";+import { DB } from "../../../data/constants";+import { databases } from "../../../data/databases";+import {+ getCustomTypes,+ saveCustomTypes,+ resolveType,+} from "../../../utils/customTypes";+import { useDiagram } from "../../../hooks";++const dbFilterOptions = [+ { label: "All", value: "" },+ ...Object.values(DB)+ .filter((value) => value !== DB.GENERIC)+ .map((value) => ({+ label: databases[value].name,+ value,+ })),+];++function storedToArray(stored) {+ const arr = [];+ for (const [db, types] of Object.entries(stored)) {+ for (const [name, entry] of Object.entries(types)) {+ arr.push({+ type: name,+ color: entry.color,+ database: db,+ _originalName: name,+ });+ }+ }+ return arr;+}++function arrayToStored(arr) {+ const result = {};+ for (const item of arr) {+ const db = item.database;+ const name = item.type.toUpperCase();+ if (!result[db]) result[db] = {};+ result[db][name] = { type: name, color: item.color };+ }+ return result;+}++export default function ConfigureCustomTypes({ open, onClose }) {+ const { t } = useTranslation();+ const { setTables, database } = useDiagram();+ const [customTypes, setCustomTypes] = useState([]);+ const [filterDb, setFilterDb] = useState("");+ const savedTypesRef = useRef([]);++ const addType = () => {+ setCustomTypes((prev) => [+ {+ type: "",+ color: "#ccc",+ database: filterDb || database || DB.MYSQL,+ },+ ...prev,+ ]);+ };++ const handleChange = (index, field, value) => {+ setCustomTypes((prev) =>+ prev.map((item, i) => (i === index ? { ...item, [field]: value } : item)),+ );+ };++ const handleDelete = (index) => {+ setCustomTypes((prev) => prev.filter((_, i) => i !== index));+ };++ const handleSave = () => {+ const invalid = customTypes.find((ct) => !ct.type.trim());+ if (invalid) {+ Toast.warning(t("type_name_required"));+ return;+ }++ const renames = [];+ for (const ct of customTypes) {+ if (ct._originalName && ct._originalName !== ct.type.toUpperCase()) {+ renames.push({+ oldName: ct._originalName,+ newName: ct.type.toUpperCase(),+ });+ }+ }++ const newStored = arrayToStored(customTypes);+ const oldStored = getCustomTypes();+ const deleted = new Set();+ for (const [db, types] of Object.entries(oldStored)) {+ for (const name of Object.keys(types)) {+ const wasRenamed = renames.some((r) => r.oldName === name);+ if (!wasRenamed && (!newStored[db] || !newStored[db][name])) {+ deleted.add(name);+ }+ }+ }++ saveCustomTypes(newStored);++ setTables((prev) =>+ prev.map((table) => ({+ ...table,+ fields: table.fields.map((field) => {+ const upper = field.type.toUpperCase();+ const rename = renames.find((r) => r.oldName === upper);+ if (rename) return { ...field, type: rename.newName };+ if (deleted.has(upper)) {+ const fallback = resolveType(database, upper);+ return { ...field, type: fallback.type };+ }+ return { ...field };+ }),+ })),+ );++ Toast.success(t("saved"));+ onClose();+ };++ const handleClose = () => {+ setCustomTypes([]);+ setFilterDb("");+ onClose();+ };++ useEffect(() => {+ if (!open) return;+ const loaded = storedToArray(getCustomTypes());+ setCustomTypes(loaded);+ savedTypesRef.current = loaded;+ }, [open]);++ const filteredTypes = filterDb+ ? customTypes+ .map((ct, i) => ({ ...ct, _index: i }))+ .filter((ct) => ct.database === filterDb)+ : customTypes.map((ct, i) => ({ ...ct, _index: i }));++ return (+ <Modal+ title={t("configure_custom_types")}+ centered+ size="medium"+ visible={open}+ onCancel={handleClose}+ footer={+ <div+ className={`flex items-center ${customTypes.length === 0 ? "justify-end" : "justify-between"}`}+ >+ {customTypes.length > 0 && (+ <Button onClick={addType} className="m-0!">+ {t("add_custom_type")}+ </Button>+ )}+ <div>+ <Button onClick={handleClose} type="tertiary">+ {t("close")}+ </Button>+ <Button theme="solid" onClick={handleSave}>+ {t("save")}+ </Button>+ </div>+ </div>+ }+ >+ <p className="opacity-80 mb-5">{t("custom_types_description")}</p>++ {customTypes.length > 0 && (+ <div className="mb-3">+ <Select+ value={filterDb}+ optionList={dbFilterOptions}+ onChange={setFilterDb}+ prefix={t("database") + ":"}+ className="w-48"+ />+ </div>+ )}++ {filteredTypes.length > 0 && (+ <div className="max-h-96 overflow-y-auto">+ <table className="configure-custom-types-table w-full border-collapse text-sm">+ <thead>+ <tr className="text-left text-[var(--semi-color-text-2)]">+ <th className="font-medium align-bottom">{t("name")}</th>+ <th className="font-medium align-bottom whitespace-nowrap">+ {t("type_color")}+ </th>+ <th+ className="font-medium align-bottom"+ aria-label={t("database")}+ >+ {t("database")}+ </th>+ <th aria-label={t("delete")} />+ </tr>+ </thead>+ <tbody>+ {filteredTypes.map((type) => (+ <TypeRow+ key={type._index}+ type={type}+ index={type._index}+ onChange={handleChange}+ onDelete={handleDelete}+ />+ ))}+ </tbody>+ </table>+ </div>+ )}++ {customTypes.length === 0 && (+ <div className="text-center">+ <Empty />+ <div className="text-md font-semibold">{t("no_custom_types")}</div>+ <Button theme="solid" className="mt-5" onClick={addType}>+ {t("add_custom_type")}+ </Button>+ </div>+ )}++ {customTypes.length > 0 && filteredTypes.length === 0 && (+ <div className="text-center py-8 opacity-60">+ {t("no_custom_types")}+ </div>+ )}+ </Modal>+ );+}diff --git a/src/components/EditorHeader/ControlPanel.jsx b/src/components/EditorHeader/ControlPanel.jsxindex 685669c6..ab0f7733 100644--- a/src/components/EditorHeader/ControlPanel.jsx+++ b/src/components/EditorHeader/ControlPanel.jsx@@ -85,6 +85,7 @@ import { getTableHeight } from "../../utils/utils";import { deleteFromCache, STORAGE_KEY } from "../../utils/cache";import { useLiveQuery } from "dexie-react-hooks";import { DateTime } from "luxon";+import ConfigureCustomTypes from "./ConfigureCustomTypes";export default function ControlPanel({ title, setTitle, lastSaved }) {const { id: diagramId } = useParams();@@ -1482,6 +1483,10 @@ export default function ControlPanel({ title, setTitle, lastSaved }) {function: () => setModal(MODAL.TABLE_WIDTH),disabled: layout.readOnly,},+ configure_custom_types: {+ function: () => setModal(MODAL.CONFIG_CUSTOM_TYPES),+ disabled: layout.readOnly,+ },language: {function: () => setModal(MODAL.LANGUAGE),},@@ -1601,6 +1606,10 @@ export default function ControlPanel({ title, setTitle, lastSaved }) {setTitle={setTitle}onClose={() => setSidesheet(SIDESHEET.NONE)}/>+ <ConfigureCustomTypes+ open={modal === MODAL.CONFIG_CUSTOM_TYPES}+ onClose={() => setModal(MODAL.NONE)}+ /></>);diff --git a/src/components/EditorHeader/Modal/Modal.jsx b/src/components/EditorHeader/Modal/Modal.jsxindex 0d833e8e..fb7ff8f0 100644--- a/src/components/EditorHeader/Modal/Modal.jsx+++ b/src/components/EditorHeader/Modal/Modal.jsx@@ -33,6 +33,7 @@ import Rename from "./Rename";import SetTableWidth from "./SetTableWidth";import Share from "./Share";import { useNavigate } from "react-router-dom";+import { mergeCustomTypes } from "../../../utils/customTypes";const extensionToLanguage = {md: "markdown",@@ -93,6 +94,9 @@ export default function Modal({if (databases[database].hasTypes && importData.types) {setTypes(importData.types);}+ if (importData.customTypes) {+ mergeCustomTypes(importData.customTypes);+ }};const parseSQLAndLoadDiagram = () => {@@ -326,7 +330,7 @@ export default function Modal({<SemiUIModalstyle={isRtl(i18n.language) ? { direction: "rtl" } : {}}title={getModalTitle(modal)}- visible={modal !== MODAL.NONE}+ visible={modal !== MODAL.NONE && modal !== MODAL.CONFIG_CUSTOM_TYPES}onOk={getModalOnOk}afterClose={() => {setExportData(() => ({diff --git a/src/components/EditorHeader/Modal/Share.jsx b/src/components/EditorHeader/Modal/Share.jsxindex b632f473..3e6460d1 100644--- a/src/components/EditorHeader/Modal/Share.jsx+++ b/src/components/EditorHeader/Modal/Share.jsx@@ -14,6 +14,7 @@ import {import { databases } from "../../../data/databases";import { MODAL } from "../../../data/constants";import { create, patch, SHARE_FILENAME } from "../../../api/gists";+import { getCustomTypes } from "../../../utils/customTypes";export default function Share({ title, setModal }) {const { t } = useTranslation();@@ -29,6 +30,21 @@ export default function Share({ title, setModal }) {const url = window.location.origin + "/editor?shareId=" + gistId;const diagramToString = useCallback(() => {+ const allCustomTypes = getCustomTypes();+ const usedFieldTypes = new Set(+ tables.flatMap((t) => t.fields.map((f) => f.type.toUpperCase())),+ );+ const usedCustomTypes = {};+ for (const [db, types] of Object.entries(allCustomTypes)) {+ for (const [name, entry] of Object.entries(types)) {+ if (usedFieldTypes.has(name)) {+ if (!usedCustomTypes[db]) usedCustomTypes[db] = {};+ usedCustomTypes[db][name] = entry;+ }+ }+ }+ const hasCustomTypes = Object.keys(usedCustomTypes).length > 0;+return JSON.stringify({title,tables: tables,@@ -38,6 +54,7 @@ export default function Share({ title, setModal }) {database: database,...(databases[database].hasTypes && { types: types }),...(databases[database].hasEnums && { enums: enums }),+ ...(hasCustomTypes && { customTypes: usedCustomTypes }),transform: transform,});}, [diff --git a/src/components/EditorSidePanel/TablesTab/FieldDetails.jsx b/src/components/EditorSidePanel/TablesTab/FieldDetails.jsxindex 93b2c333..0f4a91df 100644--- a/src/components/EditorSidePanel/TablesTab/FieldDetails.jsx+++ b/src/components/EditorSidePanel/TablesTab/FieldDetails.jsx@@ -11,13 +11,14 @@ import { Action, ObjectType } from "../../../data/constants";import { IconDeleteStroked } from "@douyinfe/semi-icons";import { useDiagram, useLayout, useUndoRedo } from "../../../hooks";import { useTranslation } from "react-i18next";-import { dbToTypes } from "../../../data/datatypes";import { databases } from "../../../data/databases";+import { resolveType } from "../../../utils/customTypes";export default function FieldDetails({ data, tid }) {const { t } = useTranslation();const { layout } = useLayout();const { tables, database } = useDiagram();+ const resolved = resolveType(database, data.type);const { setUndoStack, setRedoStack } = useUndoRedo();const { updateField, deleteField } = useDiagram();const [editField, setEditField] = useState({});@@ -31,7 +32,7 @@ export default function FieldDetails({ data, tid }) {placeholder={t("default_value")}value={data.default}readonly={layout.readOnly}- disabled={dbToTypes[database][data.type].noDefault || data.increment}+ disabled={resolved.noDefault || data.increment}onChange={(value) => updateField(tid, data.id, { default: value })}onFocus={(e) => setEditField({ default: e.target.value })}onBlur={(e) => {@@ -100,7 +101,7 @@ export default function FieldDetails({ data, tid }) {/></>)}- {dbToTypes[database][data.type].isSized && (+ {resolved.isSized && (<><div className="font-semibold">{t("size")}</div><InputNumber@@ -133,7 +134,7 @@ export default function FieldDetails({ data, tid }) {/></>)}- {dbToTypes[database][data.type].hasPrecision && (+ {resolved.hasPrecision && (<><div className="font-semibold">{t("precision")}</div><Input@@ -171,7 +172,7 @@ export default function FieldDetails({ data, tid }) {/></>)}- {dbToTypes[database][data.type].hasCheck && (+ {resolved.hasCheck && (<><div className="font-semibold">{t("check")}</div><Input@@ -242,7 +243,7 @@ export default function FieldDetails({ data, tid }) {value="increment"checked={data.increment}disabled={- !dbToTypes[database][data.type].canIncrement || data.isArray || layout.readOnly+ !resolved.canIncrement || data.isArray || layout.readOnly}onChange={(checkedValues) => {setUndoStack((prev) => [@@ -311,7 +312,7 @@ export default function FieldDetails({ data, tid }) {</div>)}{databases[database].hasUnsignedTypes &&- dbToTypes[database][data.type].signed && (+ resolved.signed && (<div className="flex justify-between items-center my-3"><div className="font-medium">{t("Unsigned")}</div><Checkboxdiff --git a/src/components/EditorSidePanel/TablesTab/TableField.jsx b/src/components/EditorSidePanel/TablesTab/TableField.jsxindex b9495c77..bdad924a 100644--- a/src/components/EditorSidePanel/TablesTab/TableField.jsx+++ b/src/components/EditorSidePanel/TablesTab/TableField.jsx@@ -13,6 +13,7 @@ import { useTranslation } from "react-i18next";import { dbToTypes } from "../../../data/datatypes";import { DragHandle } from "../../SortableList/DragHandle";import FieldDetails from "./FieldDetails";+import { getCustomTypesForDb, resolveType } from "../../../utils/customTypes";export default function TableField({ data, tid, index, inherited }) {const { updateField } = useDiagram();@@ -71,6 +72,10 @@ export default function TableField({ data, tid, index, inherited }) {label: value,value,})),+ ...Object.keys(getCustomTypesForDb(database)).map((value) => ({+ label: value,+ value,+ })),...types.map((type) => ({label: type.name.toUpperCase(),value: type.name.toUpperCase(),@@ -105,8 +110,8 @@ export default function TableField({ data, tid, index, inherited }) {},]);setRedoStack([]);- const incr =- data.increment && !!dbToTypes[database][value].canIncrement;+ const typeInfo = resolveType(database, value);+ const incr = data.increment && !!typeInfo.canIncrement;if (value === "ENUM" || value === "SET") {updateField(tid, data.id, {@@ -115,16 +120,13 @@ export default function TableField({ data, tid, index, inherited }) {values: data.values ? [...data.values] : [],increment: incr,});- } else if (- dbToTypes[database][value].isSized ||- dbToTypes[database][value].hasPrecision- ) {+ } else if (typeInfo.isSized || typeInfo.hasPrecision) {updateField(tid, data.id, {type: value,- size: dbToTypes[database][value].defaultSize,+ size: typeInfo.defaultSize,increment: incr,});- } else if (!dbToTypes[database][value].hasDefault || incr) {+ } else if (!typeInfo.hasDefault || incr) {updateField(tid, data.id, {type: value,increment: incr,@@ -132,7 +134,7 @@ export default function TableField({ data, tid, index, inherited }) {size: "",values: [],});- } else if (dbToTypes[database][value].hasCheck) {+ } else if (typeInfo.hasCheck) {updateField(tid, data.id, {type: value,check: "",diff --git a/src/components/EditorSidePanel/TypesTab/TypeField.jsx b/src/components/EditorSidePanel/TypesTab/TypeField.jsxindex 588dab80..e902c744 100644--- a/src/components/EditorSidePanel/TypesTab/TypeField.jsx+++ b/src/components/EditorSidePanel/TypesTab/TypeField.jsx@@ -20,6 +20,7 @@ import {} from "../../../hooks";import { useTranslation } from "react-i18next";import { dbToTypes } from "../../../data/datatypes";+import { getCustomTypesForDb, resolveType } from "../../../utils/customTypes";export default function TypeField({ data, tid, fid }) {const { types, updateType } = useTypes();@@ -76,6 +77,10 @@ export default function TypeField({ data, tid, fid }) {label: value,value: value,})),+ ...Object.keys(getCustomTypesForDb(database)).map((value) => ({+ label: value,+ value,+ })),...types.filter((type) => type.name.toLowerCase() !== types[tid].name.toLowerCase(),@@ -126,8 +131,8 @@ export default function TypeField({ data, tid, fid }) {),});} else if (- dbToTypes[database][value].isSized ||- dbToTypes[database][value].hasPrecision+ resolveType(database, value).isSized ||+ resolveType(database, value).hasPrecision) {updateType(tid, {fields: types[tid].fields.map((e, id) =>@@ -135,7 +140,7 @@ export default function TypeField({ data, tid, fid }) {? {...data,type: value,- size: dbToTypes[database][value].defaultSize,+ size: resolveType(database, value).defaultSize,}: e,),@@ -205,7 +210,7 @@ export default function TypeField({ data, tid, fid }) {/></>)}- {dbToTypes[database][data.type].isSized && (+ {resolveType(database, data.type).isSized && (<><div className="font-semibold">{t("size")}</div><InputNumber@@ -244,7 +249,7 @@ export default function TypeField({ data, tid, fid }) {/></>)}- {dbToTypes[database][data.type].hasPrecision && (+ {resolveType(database, data.type).hasPrecision && (<><div className="font-semibold">{t("precision")}</div><Inputdiff --git a/src/components/Workspace.jsx b/src/components/Workspace.jsxindex fa0f1ebd..2b39b19d 100644--- a/src/components/Workspace.jsx+++ b/src/components/Workspace.jsx@@ -31,6 +31,7 @@ import {} from "react-router-dom";import { get, SHARE_FILENAME } from "../api/gists";import { nanoid } from "nanoid";+import { mergeCustomTypes } from "../utils/customTypes";export const IdContext = createContext({gistId: "",@@ -359,6 +360,9 @@ export default function WorkSpace() {) ?? [],);}+ if (parsedDiagram.customTypes) {+ mergeCustomTypes(parsedDiagram.customTypes);+ }if (diagramId) {navigate(`/editor/diagrams/${diagramId}`, {replace: true,diff --git a/src/data/constants.js b/src/data/constants.jsindex 35b5976b..c56a68f6 100644--- a/src/data/constants.js+++ b/src/data/constants.js@@ -87,6 +87,7 @@ export const MODAL = {TABLE_WIDTH: 9,LANGUAGE: 10,SHARE: 11,+ CONFIG_CUSTOM_TYPES: 12,};export const STATUS = {diff --git a/src/data/schemas.js b/src/data/schemas.jsindex 79476fa3..a82d41ad 100644--- a/src/data/schemas.js+++ b/src/data/schemas.js@@ -131,6 +131,15 @@ export const enumSchema = {},};+export const customTypeEntrySchema = {+ type: "object",+ properties: {+ type: { type: "string", minLength: 1 },+ color: { type: "string" },+ },+ required: ["type", "color"],+};+export const jsonSchema = {type: "object",properties: {diff --git a/src/i18n/locales/en.js b/src/i18n/locales/en.jsindex 81d5679b..ccbf1f87 100644--- a/src/i18n/locales/en.js+++ b/src/i18n/locales/en.js@@ -279,6 +279,17 @@ const en = {insert_sql: "Insert SQL",upload_file: "Upload file",show_comments: "Show comments",+ configure_custom_types: "Configure custom types",+ type_color: "Color",+ custom_types_description:+ "Define custom data types that are not supported by default. These types will be available when creating or editing columns.",+ type_data_corrupted: "Configured types are corrupted.",+ no_custom_types: "You do not have any types configured",+ close: "Close",+ add_custom_type: "Add custom type",+ type_name_required: "Type name is required",+ database: "Database",+ saved: "Saved",},};diff --git a/src/utils/customTypes.js b/src/utils/customTypes.jsnew file mode 100644index 00000000..fa44374f--- /dev/null+++ b/src/utils/customTypes.js@@ -0,0 +1,114 @@+import { Validator } from "jsonschema";+import { DB } from "../data/constants";+import { customTypeEntrySchema } from "../data/schemas";+import { dbToTypes } from "../data/datatypes";++const STORAGE_KEY = "custom_types";+const validator = new Validator();+const validDatabases = new Set(Object.values(DB));++function isValidEntry(entry) {+ return validator.validate(entry, customTypeEntrySchema).valid;+}++function migrateIfNeeded(parsed) {+ if (Array.isArray(parsed)) {+ const result = {};+ for (const item of parsed) {+ if (!item.type || !item.database) continue;+ const db = item.database;+ const name = item.type.toUpperCase();+ if (!validDatabases.has(db)) continue;+ if (!result[db]) result[db] = {};+ result[db][name] = { type: name, color: item.color || "#ccc" };+ }+ return result;+ }+ return parsed;+}++export function getCustomTypes() {+ try {+ const raw = localStorage.getItem(STORAGE_KEY);+ if (!raw) return {};+ const parsed = migrateIfNeeded(JSON.parse(raw));+ if (typeof parsed !== "object" || parsed === null) return {};+ const result = {};+ for (const [db, types] of Object.entries(parsed)) {+ if (!validDatabases.has(db)) continue;+ if (typeof types !== "object" || types === null) continue;+ for (const [name, entry] of Object.entries(types)) {+ if (!isValidEntry(entry)) continue;+ if (!result[db]) result[db] = {};+ result[db][name] = { type: entry.type, color: entry.color };+ }+ }+ return result;+ } catch {+ return {};+ }+}++export function getCustomTypesForDb(database) {+ const all = getCustomTypes();+ const dbTypes = all[database];+ if (!dbTypes) return {};+ const result = {};+ for (const [name, entry] of Object.entries(dbTypes)) {+ result[name] = {+ type: entry.type,+ color: entry.color,+ checkDefault: () => true,+ hasCheck: false,+ isSized: false,+ hasPrecision: false,+ canIncrement: false,+ noDefault: false,+ isCustom: true,+ };+ }+ return result;+}++export function saveCustomTypes(types) {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(types));+}++const BLOB_FALLBACK = {+ type: "BLOB",+ color: "",+ checkDefault: () => true,+ hasCheck: false,+ isSized: false,+ hasPrecision: false,+ canIncrement: false,+ noDefault: true,+ isCustom: false,+};++export function resolveType(database, typeName) {+ const builtIn = dbToTypes[database][typeName];+ if (builtIn) return builtIn;++ const customDb = getCustomTypesForDb(database);+ if (customDb[typeName]) return customDb[typeName];++ return dbToTypes[database]["BLOB"] || BLOB_FALLBACK;+}++export function mergeCustomTypes(incoming) {+ if (typeof incoming !== "object" || incoming === null) return;+ const existing = getCustomTypes();+ for (const [db, types] of Object.entries(incoming)) {+ if (!validDatabases.has(db)) continue;+ if (typeof types !== "object" || types === null) continue;+ if (!existing[db]) existing[db] = {};+ for (const [name, entry] of Object.entries(types)) {+ if (!isValidEntry(entry)) continue;+ if (!existing[db][name]) {+ existing[db][name] = { type: entry.type, color: entry.color };+ }+ }+ }+ saveCustomTypes(existing);+}