diff --git a/.github/workflows/check.yaml b/.github/workflows/check.yaml new file mode 100644 index 00000000..88f2fdda --- /dev/null +++ b/.github/workflows/check.yaml @@ -0,0 +1,56 @@ +name: Check + +on: + push: + branches: + - develop + pull_request: + workflow_dispatch: + +jobs: + quality-check: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup pnpm + uses: pnpm/action-setup@v2 + with: + version: 8.13.1 + run_install: false + + - uses: actions/setup-node@v3 + with: + node-version: 20 + cache: pnpm + + - name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + + - name: Cache pnpm + uses: actions/cache@v4 + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + + - name: Cache turbo tasks + uses: actions/cache@v4 + with: + path: .turbo + key: ${{ runner.os }}-turbo-${{ github.sha }} + restore-keys: | + ${{ runner.os }}-turbo- + + - name: Install dependencies + run: pnpm install + + - name: Run Check + run: pnpm run staged + + - name: Log success + run: echo "✅ Success!" diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml deleted file mode 100644 index 0ec007cb..00000000 --- a/.github/workflows/check.yml +++ /dev/null @@ -1,22 +0,0 @@ -name: Check -on: - push: - branches: - - develop - pull_request: -jobs: - check: - name: Check - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - with: - fetch-depth: 0 - - name: Install dependencies - run: npm install - - name: Check type - run: npm run tsc - - name: Check Lint - run: npm run lint - - name: Check Test - run: npm run test diff --git a/.gitignore b/.gitignore index 00bba9bb..49deb113 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ # dependencies /node_modules +**/node_modules /.pnp .pnp.js .yarn/install-state.gz @@ -10,13 +11,16 @@ /coverage # next.js +**/.next /.next/ /out/ # production /build +**/dist # misc +**/.DS_Store .DS_Store *.pem @@ -32,6 +36,11 @@ yarn-error.log* # vercel .vercel +# turbo +**/.turbo +.turbo + # typescript +**/*.tsbuildinfo *.tsbuildinfo next-env.d.ts diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..34a0489e --- /dev/null +++ b/.prettierignore @@ -0,0 +1,11 @@ +package-lock.json +.next +dist +drizzle/* +**/*/drizzle +.prettierignore +.gitignore + +.changeset/ + + diff --git a/.vscode/settings.json b/.vscode/settings.json index 0399a78b..5d3253ee 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,4 @@ { - "editor.formatOnSave": true + "editor.formatOnSave": true, + "typescript.tsdk": "node_modules\\typescript\\lib" } \ No newline at end of file diff --git a/config/eslint/base.js b/config/eslint/base.js new file mode 100644 index 00000000..53c2525a --- /dev/null +++ b/config/eslint/base.js @@ -0,0 +1,63 @@ +/** @type {import('eslint').Linter.Config} */ +const config = { + ignorePatterns: ["node_modules", "dist", ".next"], + env: { + es2022: true, + node: true, + }, + extends: ["plugin:eslint-comments/recommended", "prettier"], + overrides: [ + { + files: [ + "**/*.ts", + "**/*.tsx", + "**/*.js", + "**/*.jsx", + "**/*.mjs", + "**/*.cjs", + ], + parser: "@typescript-eslint/parser", + parserOptions: { + project: true, + }, + plugins: ["@typescript-eslint"], + extends: [ + "plugin:@typescript-eslint/strict-type-checked", + "plugin:@typescript-eslint/stylistic-type-checked", + ], + rules: { + "@typescript-eslint/no-empty-interface": "off", + "@typescript-eslint/prefer-nullish-coalescing": "off", + "@typescript-eslint/restrict-template-expressions": "off", + "@typescript-eslint/consistent-type-definitions": "off", + "@typescript-eslint/array-type": [ + "error", + { + default: "array-simple", + readonly: "array-simple", + }, + ], + "@typescript-eslint/consistent-type-imports": [ + "warn", + { + prefer: "type-imports", + fixStyle: "inline-type-imports", + }, + ], + "@typescript-eslint/no-unused-vars": [ + "warn", + { argsIgnorePattern: "^_" }, + ], + "@typescript-eslint/require-await": "error", + "@typescript-eslint/no-misused-promises": [ + "error", + { + checksVoidReturn: { attributes: false }, + }, + ], + }, + }, + ], +}; + +module.exports = config; diff --git a/config/eslint/next.js b/config/eslint/next.js new file mode 100644 index 00000000..7587867f --- /dev/null +++ b/config/eslint/next.js @@ -0,0 +1,6 @@ +/** @type {import('eslint').Linter.Config} */ +const config = { + extends: ["plugin:@next/next/recommended"], +}; + +module.exports = config; diff --git a/config/eslint/package.json b/config/eslint/package.json new file mode 100644 index 00000000..b4929cdd --- /dev/null +++ b/config/eslint/package.json @@ -0,0 +1,19 @@ +{ + "name": "eslint-config-libsqlstudio", + "private": true, + "version": "1.0.0", + "files": [ + "./base.js", + "./next.js", + "./react.js" + ], + "devDependencies": { + "@typescript-eslint/eslint-plugin": "^7.6.0", + "@typescript-eslint/parser": "^7.6.0", + "eslint-config-next": "^14.1.4", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-eslint-comments": "^3.2.0", + "eslint-plugin-react": "^7.34.1", + "eslint-plugin-react-hooks": "^4.6.0" + } +} diff --git a/config/eslint/react.js b/config/eslint/react.js new file mode 100644 index 00000000..ef33e317 --- /dev/null +++ b/config/eslint/react.js @@ -0,0 +1,25 @@ +/** @type {import('eslint').Linter.Config} */ +const config = { + overrides: [ + { + files: ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx"], + extends: [ + "plugin:react/recommended", + "plugin:react-hooks/recommended", + // "plugin:jsx-a11y/recommended", + ], + settings: { + react: { + version: "detect", + }, + }, + rules: { + "react/react-in-jsx-scope": "off", + "react/prop-types": "off", + "react/no-unknown-property": "warn" + }, + }, + ], +}; + +module.exports = config; diff --git a/config/eslint/tsconfig.json b/config/eslint/tsconfig.json new file mode 100644 index 00000000..747521af --- /dev/null +++ b/config/eslint/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": ["../tsconfig/base.json"], + "include": ["**/*.cjs"] +} diff --git a/config/tailwind/index.ts b/config/tailwind/index.ts new file mode 100644 index 00000000..8af504f0 --- /dev/null +++ b/config/tailwind/index.ts @@ -0,0 +1,93 @@ +import type { Config } from "tailwindcss"; + +export const LibSqlStudoTailwindPreset: Config = { + darkMode: ["class"], + content: [ + "./pages/**/*.{ts,tsx}", + "./components/**/*.{ts,tsx}", + "./app/**/*.{ts,tsx}", + "./src/**/*.{ts,tsx}", + ], + prefix: "", + theme: { + container: { + center: true, + padding: "2rem", + screens: { + "2xl": "1400px", + }, + }, + extend: { + colors: { + border: "hsl(var(--border))", + input: "hsl(var(--input))", + ring: "hsl(var(--ring))", + background: "hsl(var(--background))", + foreground: "hsl(var(--foreground))", + primary: { + DEFAULT: "hsl(var(--primary))", + foreground: "hsl(var(--primary-foreground))", + }, + secondary: { + DEFAULT: "hsl(var(--secondary))", + foreground: "hsl(var(--secondary-foreground))", + }, + destructive: { + DEFAULT: "hsl(var(--destructive))", + foreground: "hsl(var(--destructive-foreground))", + }, + muted: { + DEFAULT: "hsl(var(--muted))", + foreground: "hsl(var(--muted-foreground))", + }, + accent: { + DEFAULT: "hsl(var(--accent))", + foreground: "hsl(var(--accent-foreground))", + }, + popover: { + DEFAULT: "hsl(var(--popover))", + foreground: "hsl(var(--popover-foreground))", + }, + card: { + DEFAULT: "hsl(var(--card))", + foreground: "hsl(var(--card-foreground))", + }, + }, + borderRadius: { + lg: "var(--radius)", + md: "calc(var(--radius) - 2px)", + sm: "calc(var(--radius) - 4px)", + }, + keyframes: { + "accordion-down": { + from: { height: "0" }, + to: { height: "var(--radix-accordion-content-height)" }, + }, + "accordion-up": { + from: { height: "var(--radix-accordion-content-height)" }, + to: { height: "0" }, + }, + shake: { + "10%, 90%": { + transform: "translate3d(-1px, 0, 0)", + }, + "20%, 80%": { + transform: "translate3d(2px, 0, 0)", + }, + "30%, 50%, 70%": { + transform: "translate3d(-4px, 0, 0)", + }, + "40%, 60%": { + transform: "translate3d(4px, 0, 0)", + }, + }, + }, + animation: { + "accordion-down": "accordion-down 0.2s ease-out", + "accordion-up": "accordion-up 0.2s ease-out", + shake: "shake 0.82s cubic-bezier(.36,.07,.19,.97) both", + }, + }, + }, + plugins: [require("tailwindcss-animate")], +}; diff --git a/config/tailwind/package.json b/config/tailwind/package.json new file mode 100644 index 00000000..a6846b71 --- /dev/null +++ b/config/tailwind/package.json @@ -0,0 +1,17 @@ +{ + "name": "@libsqlstudio/tailwind", + "private": true, + "version": "1.0.0", + "type": "module", + "exports": { + ".": { + "types": "./index.ts", + "default": "./index.ts" + }, + "./css": "./style.css" + }, + "devDependencies": { + "tailwindcss": "^3.4.3", + "tailwindcss-animate": "^1.0.7" + } +} diff --git a/src/app/globals.css b/config/tailwind/style.css similarity index 100% rename from src/app/globals.css rename to config/tailwind/style.css diff --git a/config/tailwind/tsconfig.json b/config/tailwind/tsconfig.json new file mode 100644 index 00000000..95c79a0f --- /dev/null +++ b/config/tailwind/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": ["../tsconfig/base.json"], + "include": ["**/*.ts"] +} diff --git a/config/tsconfig/base.json b/config/tsconfig/base.json new file mode 100644 index 00000000..60502896 --- /dev/null +++ b/config/tsconfig/base.json @@ -0,0 +1,35 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "display": "Strictest", + "compilerOptions": { + "strict": true, + "allowUnusedLabels": false, + "allowUnreachableCode": false, + "noFallthroughCasesInSwitch": true, + "noImplicitOverride": true, + "noImplicitReturns": true, + "noPropertyAccessFromIndexSignature": true, + "noUncheckedIndexedAccess": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + + "isolatedModules": true, + + "allowJs": true, + "checkJs": true, + + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + + "lib": ["es2023"], + "module": "esnext", + "target": "es2022", + "moduleResolution": "bundler", + "moduleDetection": "force", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "noEmit": true, + "incremental": true + } +} diff --git a/config/tsconfig/next.json b/config/tsconfig/next.json new file mode 100644 index 00000000..789e42e8 --- /dev/null +++ b/config/tsconfig/next.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "display": "Next.js", + "extends": "./base.json", + "compilerOptions": { + "lib": ["dom", "dom.iterable", "esnext"], + "jsx": "preserve", + "plugins": [ + { + "name": "next" + } + ] + } +} diff --git a/config/tsconfig/package.json b/config/tsconfig/package.json new file mode 100644 index 00000000..b444629a --- /dev/null +++ b/config/tsconfig/package.json @@ -0,0 +1,11 @@ +{ + "name": "@libsqlstudio/tsconfig", + "private": true, + "version": "1.0.0", + "type": "module", + "files": [ + "./base.json", + "./next.json", + "./react.json" + ] +} diff --git a/config/tsconfig/react.json b/config/tsconfig/react.json new file mode 100644 index 00000000..b8d0747d --- /dev/null +++ b/config/tsconfig/react.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "display": "React", + "extends": "./base.json", + "compilerOptions": { + "target": "ES2020", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "jsx": "react-jsx" + } +} diff --git a/gui/.eslintrc.cjs b/gui/.eslintrc.cjs new file mode 100644 index 00000000..7f0e3719 --- /dev/null +++ b/gui/.eslintrc.cjs @@ -0,0 +1,29 @@ +/** + * @type {import('eslint').Linter.Config} + */ +module.exports = { + root: true, + extends: ["libsqlstudio/base", "libsqlstudio/react"], + rules: { + "@typescript-eslint/no-unsafe-assignment": "off", + "@typescript-eslint/no-unsafe-call": "off", + "@typescript-eslint/consistent-type-imports": "off", + "@typescript-eslint/no-unnecessary-condition": "off", + "@typescript-eslint/no-floating-promises": "off", + "@typescript-eslint/no-unsafe-argument": "off", + "@typescript-eslint/no-unsafe-member-access": "off", + "@typescript-eslint/no-misused-promises": "off", + "@typescript-eslint/prefer-includes": "off", + "@typescript-eslint/prefer-promise-reject-errors": "off", + "@typescript-eslint/no-confusing-void-expression": "off", + "@typescript-eslint/restrict-plus-operands": "off", + "@typescript-eslint/no-base-to-string": "off", + "@typescript-eslint/use-unknown-in-catch-callback-variable": "off", + "@typescript-eslint/require-await": "off", + "@typescript-eslint/no-dynamic-delete": "off", + "@typescript-eslint/non-nullable-type-assertion-style": "off", + "@typescript-eslint/array-type": "off", + "eslint-comments/no-unlimited-disable": "off", + "eslint-comments/disable-enable-pair": "off", + }, +}; diff --git a/gui/.gitignore b/gui/.gitignore new file mode 100644 index 00000000..a547bf36 --- /dev/null +++ b/gui/.gitignore @@ -0,0 +1,24 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/gui/jest.config.cjs b/gui/jest.config.cjs new file mode 100644 index 00000000..fe74d3f8 --- /dev/null +++ b/gui/jest.config.cjs @@ -0,0 +1,9 @@ +/** @type {import('ts-jest').JestConfigWithTsJest} */ +module.exports = { + preset: "ts-jest", + testEnvironment: "jsdom", + rootDir: "./", + moduleNameMapper: { + "^@gui/(.*)$": "/src/$1", + }, +}; diff --git a/gui/package.json b/gui/package.json new file mode 100644 index 00000000..90a478bd --- /dev/null +++ b/gui/package.json @@ -0,0 +1,98 @@ +{ + "name": "@libsqlstudio/gui", + "private": true, + "version": "0.0.0", + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js", + "require": "./dist/index.cjs" + }, + "./css": "./dist/index.css" + }, + "scripts": { + "dev": "tsup --watch", + "build": "tsup", + "staged": "pnpm run typecheck && pnpm run format && pnpm run lint && pnpm run test", + "typecheck": "tsc --noEmit", + "test": "jest", + "test:watch": "jest --watch", + "lint": "eslint .", + "lint:fix": "eslint . --fix", + "format": "prettier --check .", + "format:fix": "prettier --write ." + }, + "peerDependencies": { + "react": "^18.2.0", + "react-dom": "^18.2.0" + }, + "dependencies": { + "@blocknote/core": "^0.12.1", + "@blocknote/react": "^0.12.2", + "@codemirror/commands": "^6.3.3", + "@codemirror/lang-sql": "^6.5.5", + "@codemirror/view": "^6.26.3", + "@dnd-kit/core": "^6.1.0", + "@dnd-kit/sortable": "^8.0.0", + "@justmiracle/result": "^1.2.0", + "@lezer/common": "^1.2.1", + "@lezer/highlight": "^1.2.0", + "@lezer/lr": "^1.4.0", + "@libsql/client": "^0.5.3", + "@radix-ui/react-alert-dialog": "^1.0.5", + "@radix-ui/react-avatar": "^1.0.4", + "@radix-ui/react-checkbox": "^1.0.4", + "@radix-ui/react-context-menu": "^2.1.5", + "@radix-ui/react-dialog": "^1.0.5", + "@radix-ui/react-dropdown-menu": "^2.0.6", + "@radix-ui/react-hover-card": "^1.0.7", + "@radix-ui/react-icons": "^1.3.0", + "@radix-ui/react-label": "^2.0.2", + "@radix-ui/react-menubar": "^1.0.4", + "@radix-ui/react-navigation-menu": "^1.1.4", + "@radix-ui/react-popover": "^1.0.7", + "@radix-ui/react-radio-group": "^1.1.3", + "@radix-ui/react-scroll-area": "^1.0.5", + "@radix-ui/react-select": "^2.0.0", + "@radix-ui/react-separator": "^1.0.3", + "@radix-ui/react-slot": "^1.0.2", + "@radix-ui/react-toggle": "^1.0.3", + "@radix-ui/react-toggle-group": "^1.0.4", + "@radix-ui/react-tooltip": "^1.0.7", + "@tiptap/core": "^2.3.0", + "@tiptap/react": "^2.3.0", + "@uiw/codemirror-extensions-langs": "^4.21.24", + "@uiw/codemirror-themes": "^4.21.21", + "@uiw/react-codemirror": "^4.21.21", + "class-variance-authority": "^0.7.0", + "clsx": "^2.1.0", + "cmdk": "^0.2.0", + "cookies-next": "^4.1.1", + "deep-equal": "^2.2.3", + "lucide-react": "^0.309.0", + "react-resizable-panels": "^1.0.9", + "sonner": "^1.4.41", + "sql-query-identifier": "^2.6.0", + "tailwind-merge": "^2.2.2" + }, + "devDependencies": { + "@libsqlstudio/tailwind": "workspace:*", + "@libsqlstudio/tsconfig": "workspace:*", + "@types/deep-equal": "^1.0.4", + "@types/jest": "^29.5.11", + "@types/react": "^18.2.66", + "@types/react-dom": "^18.2.22", + "@vitejs/plugin-react": "^4.2.1", + "autoprefixer": "^10.4.19", + "eslint-config-libsqlstudio": "workspace:*", + "jest": "^29.7.0", + "jest-environment-jsdom": "^29.7.0", + "postcss": "^8.4.38", + "tailwindcss": "^3.4.3", + "ts-jest": "^29.1.2", + "tsup": "^8.0.2", + "vite": "^5.2.0", + "vite-tsconfig-paths": "^4.3.2" + } +} diff --git a/gui/postcss.config.js b/gui/postcss.config.js new file mode 100644 index 00000000..2aa7205d --- /dev/null +++ b/gui/postcss.config.js @@ -0,0 +1,6 @@ +export default { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +}; diff --git a/src/components/block-editor/editor.tsx b/gui/src/components/block-editor/editor.tsx similarity index 83% rename from src/components/block-editor/editor.tsx rename to gui/src/components/block-editor/editor.tsx index 50515098..38f6699f 100644 --- a/src/components/block-editor/editor.tsx +++ b/gui/src/components/block-editor/editor.tsx @@ -6,9 +6,10 @@ import "./style.css"; import { BlockNoteView } from "@blocknote/react"; import { SuggestionMenu } from "./suggestions"; import { BlockNoteEditor } from "@blocknote/core"; -import { useTheme } from "@/context/theme-provider"; +import { useTheme } from "@gui/contexts/theme-provider"; export interface BlockEditorProps { + // eslint-disable-next-line @typescript-eslint/no-explicit-any editor: BlockNoteEditor; } diff --git a/src/components/block-editor/extensions/code-block.tsx b/gui/src/components/block-editor/extensions/code-block.tsx similarity index 94% rename from src/components/block-editor/extensions/code-block.tsx rename to gui/src/components/block-editor/extensions/code-block.tsx index 44849d1b..5efb10e5 100644 --- a/src/components/block-editor/extensions/code-block.tsx +++ b/gui/src/components/block-editor/extensions/code-block.tsx @@ -1,17 +1,17 @@ -import { Button } from "@/components/ui/button"; +import { Button } from "@gui/components/ui/button"; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, -} from "@/components/ui/command"; +} from "@gui/components/ui/command"; import { Popover, PopoverContent, PopoverTrigger, -} from "@/components/ui/popover"; -import { cn, scoped } from "@/lib/utils"; +} from "@gui/components/ui/popover"; +import { cn, scoped } from "@gui/lib/utils"; import { createReactBlockSpec } from "../utils/create-block-spec"; import ReactCodeMirror from "@uiw/react-codemirror"; import { Check, ChevronsUpDown } from "lucide-react"; @@ -43,6 +43,7 @@ export const CodeBlock = createReactBlockSpec( : "plaintext"; const code = ""; + // eslint-disable-next-line @typescript-eslint/no-explicit-any (chain() as any).BNUpdateBlock(state.selection.from, { type: "codeBlock", props: { language, code }, @@ -93,7 +94,7 @@ export const CodeBlock = createReactBlockSpec( ); }, - }, + } ); interface LanguageSelectorProps { @@ -133,7 +134,7 @@ function LanguageSelector({ value, onValueChange }: LanguageSelectorProps) { {lang} diff --git a/src/components/block-editor/extensions/file-upload.ts b/gui/src/components/block-editor/extensions/file-upload.ts similarity index 80% rename from src/components/block-editor/extensions/file-upload.ts rename to gui/src/components/block-editor/extensions/file-upload.ts index e8a45363..41d0f950 100644 --- a/src/components/block-editor/extensions/file-upload.ts +++ b/gui/src/components/block-editor/extensions/file-upload.ts @@ -1,4 +1,4 @@ -import { uploadFile as uploadUserFile } from "@/lib/file-upload"; +import { uploadFile as uploadUserFile } from "@gui/lib/file-upload"; import { toast } from "sonner"; export async function uploadFile(file: File) { diff --git a/src/components/block-editor/extensions/index.ts b/gui/src/components/block-editor/extensions/index.ts similarity index 90% rename from src/components/block-editor/extensions/index.ts rename to gui/src/components/block-editor/extensions/index.ts index 890493b8..024ef7bb 100644 --- a/src/components/block-editor/extensions/index.ts +++ b/gui/src/components/block-editor/extensions/index.ts @@ -6,8 +6,8 @@ export { uploadFile } from "./file-upload"; export const schema = BlockNoteSchema.create({ blockSpecs: { ...defaultBlockSpecs, - codeBlock: CodeBlock + codeBlock: CodeBlock, }, -}) +}); export type Block = typeof schema.Block; diff --git a/src/components/block-editor/index.tsx b/gui/src/components/block-editor/index.tsx similarity index 85% rename from src/components/block-editor/index.tsx rename to gui/src/components/block-editor/index.tsx index 1df5b5ba..dc81f300 100644 --- a/src/components/block-editor/index.tsx +++ b/gui/src/components/block-editor/index.tsx @@ -6,6 +6,7 @@ export const CONTENT_FORMAT = { BLOCK_NOTE: "BLOCK_NOTE", } as const; +// eslint-disable-next-line @typescript-eslint/no-explicit-any export interface BlockContent { format: "BLOCK_NOTE"; content: TContent[] | undefined; diff --git a/src/components/block-editor/sheet.tsx b/gui/src/components/block-editor/sheet.tsx similarity index 96% rename from src/components/block-editor/sheet.tsx rename to gui/src/components/block-editor/sheet.tsx index e8d05d2a..3e6b3e17 100644 --- a/src/components/block-editor/sheet.tsx +++ b/gui/src/components/block-editor/sheet.tsx @@ -9,7 +9,7 @@ import { Separator } from "../ui/separator"; import { ScrollArea } from "../ui/scroll-area"; import { BlockEditor } from "./editor"; import { BlockContent, CONTENT_FORMAT } from "."; -import { BlockEditorConfigs } from "@/context/block-editor-provider"; +import { BlockEditorConfigs } from "@gui/contexts/block-editor-provider"; export interface BlockEditorSheetProps { configs: BlockEditorConfigs | null; diff --git a/src/components/block-editor/style.css b/gui/src/components/block-editor/style.css similarity index 100% rename from src/components/block-editor/style.css rename to gui/src/components/block-editor/style.css diff --git a/src/components/block-editor/suggestions/index.tsx b/gui/src/components/block-editor/suggestions/index.tsx similarity index 83% rename from src/components/block-editor/suggestions/index.tsx rename to gui/src/components/block-editor/suggestions/index.tsx index d7ab52f3..4c4892ab 100644 --- a/src/components/block-editor/suggestions/index.tsx +++ b/gui/src/components/block-editor/suggestions/index.tsx @@ -1,14 +1,10 @@ -import { - BlockNoteEditor, - filterSuggestionItems, -} from "@blocknote/core"; +import { BlockNoteEditor, filterSuggestionItems } from "@blocknote/core"; import { SuggestionMenuController, getDefaultReactSlashMenuItems, } from "@blocknote/react"; import { insertCodeBlock } from "./insert-code-block"; - // How we want to display the suggestions group // lower number will be displayed first const GROUP_ORDER = { @@ -22,6 +18,7 @@ const GROUP_ORDER = { const CUSTOM_SUGGESTIONS = [insertCodeBlock]; // utility function to get all custom suggestions +// eslint-disable-next-line @typescript-eslint/no-explicit-any function getCustomSlashMenuItems(editor: BlockNoteEditor) { return CUSTOM_SUGGESTIONS.map((item) => item(editor)); } @@ -29,6 +26,7 @@ function getCustomSlashMenuItems(editor: BlockNoteEditor) { export const SuggestionMenu = ({ editor, }: { + // eslint-disable-next-line @typescript-eslint/no-explicit-any editor: BlockNoteEditor; }) => { return ( @@ -42,7 +40,7 @@ export const SuggestionMenu = ({ ]; // sort the suggestions by group - const sortedItems = allItem.toSorted((a, b) => { + const sortedItems = allItem.sort((a, b) => { const aOrder = GROUP_ORDER[a.group || ""] || 5; const bOrder = GROUP_ORDER[b.group || ""] || 5; return aOrder - bOrder; diff --git a/src/components/block-editor/suggestions/insert-code-block.tsx b/gui/src/components/block-editor/suggestions/insert-code-block.tsx similarity index 100% rename from src/components/block-editor/suggestions/insert-code-block.tsx rename to gui/src/components/block-editor/suggestions/insert-code-block.tsx diff --git a/src/components/block-editor/utils/create-block-spec.tsx b/gui/src/components/block-editor/utils/create-block-spec.tsx similarity index 92% rename from src/components/block-editor/utils/create-block-spec.tsx rename to gui/src/components/block-editor/utils/create-block-spec.tsx index 2d0f0dbe..01274c46 100644 --- a/src/components/block-editor/utils/create-block-spec.tsx +++ b/gui/src/components/block-editor/utils/create-block-spec.tsx @@ -1,3 +1,4 @@ +/* eslint-disable */ import { BlockFromConfig, BlockNoteEditor, @@ -45,7 +46,7 @@ export type ReactCustomBlockImplementation< contentRef: (node: HTMLElement | null) => void; }>; parse?: ( - el: HTMLElement, + el: HTMLElement ) => PartialBlockFromConfig["props"] | undefined; addInputRules?: () // block: BlockFromConfig, // editor: BlockNoteEditor, I, S> @@ -71,13 +72,13 @@ export function BlockContentWrapper< // Adds custom HTML attributes {...Object.fromEntries( Object.entries(props.domAttributes || {}).filter( - ([key]) => key !== "class", - ), + ([key]) => key !== "class" + ) )} // Sets blockContent class className={mergeCSSClasses( "bn-block-content", - props.domAttributes?.class || "", + props.domAttributes!["class"] || "" )} // Sets content type attribute data-content-type={props.blockType} @@ -90,11 +91,11 @@ export function BlockContentWrapper< .filter( ([prop, value]) => !inheritedProps.includes(prop) && - value !== props.propSchema[prop].default, + value !== props.propSchema[prop]!.default ) .map(([prop, value]) => { return [camelToDataKebab(prop), value]; - }), + }) )} > {props.children} @@ -110,7 +111,7 @@ export function createReactBlockSpec< const S extends StyleSchema, >( blockConfig: T, - blockImplementation: ReactCustomBlockImplementation, + blockImplementation: ReactCustomBlockImplementation ) { const node = createStronglyTypedTiptapNode({ name: blockConfig.type as T["type"], @@ -128,6 +129,7 @@ export function createReactBlockSpec< return blockImplementation.addInputRules?.() || []; }, + // @ts-expect-error parseHTML() { return getParseRules(blockConfig, blockImplementation.parse); }, @@ -154,7 +156,7 @@ export function createReactBlockSpec< props.getPos, editor, this.editor, - blockConfig.type, + blockConfig.type ) as any; // Gets the custom HTML attributes for `blockContent` nodes const blockContentDOMAttributes = @@ -181,7 +183,7 @@ export function createReactBlockSpec< }, { className: "bn-react-node-view-renderer", - }, + } )(props); }, }); @@ -208,11 +210,14 @@ export function createReactBlockSpec< /> ), - editor, + editor ); output.contentDOM?.setAttribute("data-editable", ""); - return output; + return output as { + dom: HTMLElement; + contentDOM: HTMLElement | undefined; + }; }, toExternalHTML: (block, editor) => { const blockContentDOMAttributes = @@ -238,7 +243,10 @@ export function createReactBlockSpec< }, editor); output.contentDOM?.setAttribute("data-editable", ""); - return output; + return output as { + dom: HTMLElement; + contentDOM: HTMLElement | undefined; + }; }, }); } diff --git a/src/components/block-editor/utils/react-render.tsx b/gui/src/components/block-editor/utils/react-render.tsx similarity index 85% rename from src/components/block-editor/utils/react-render.tsx rename to gui/src/components/block-editor/utils/react-render.tsx index d88cd863..74100a62 100644 --- a/src/components/block-editor/utils/react-render.tsx +++ b/gui/src/components/block-editor/utils/react-render.tsx @@ -4,6 +4,7 @@ import { Root, createRoot } from "react-dom/client"; export function renderToDOMSpec( fc: (refCB: (ref: HTMLElement | null) => void) => React.ReactNode, + // eslint-disable-next-line @typescript-eslint/no-explicit-any editor: BlockNoteEditor | undefined ) { let contentDOM: HTMLElement | undefined; @@ -15,7 +16,7 @@ export function renderToDOMSpec( // This is currently only used for Styles. In this case, react context etc. won't be available inside `fc` root = createRoot(div); flushSync(() => { - root!.render(fc((el) => (contentDOM = el || undefined))); + root?.render(fc((el) => (contentDOM = el || undefined))); }); } else { // Render temporarily using `EditorContent` (which is stored somewhat hacky on `editor._tiptapEditor.contentComponent`) @@ -37,10 +38,8 @@ export function renderToDOMSpec( // clone so we can unmount the react root contentDOM?.setAttribute("data-tmp-find", "true"); const cloneRoot = div.cloneNode(true) as HTMLElement; - const dom = cloneRoot.firstElementChild! as HTMLElement; - const contentDOMClone = cloneRoot.querySelector( - "[data-tmp-find]" - ) as HTMLElement | null; + const dom = cloneRoot.firstElementChild as HTMLElement; + const contentDOMClone = cloneRoot.querySelector("[data-tmp-find]"); contentDOMClone?.removeAttribute("data-tmp-find"); root?.unmount(); diff --git a/src/components/code-preview/index.tsx b/gui/src/components/code-preview/index.tsx similarity index 96% rename from src/components/code-preview/index.tsx rename to gui/src/components/code-preview/index.tsx index caeb9197..a9526704 100644 --- a/src/components/code-preview/index.tsx +++ b/gui/src/components/code-preview/index.tsx @@ -1,7 +1,7 @@ -export default function CodePreview({ code }: { code: string }) { - return ( - -
{code}
-
- ); -} +export default function CodePreview({ code }: { code: string }) { + return ( + +
{code}
+
+ ); +} diff --git a/src/components/connection-dialog.tsx b/gui/src/components/connection-dialog.tsx similarity index 66% rename from src/components/connection-dialog.tsx rename to gui/src/components/connection-dialog.tsx index 6f758a0f..f342e019 100644 --- a/src/components/connection-dialog.tsx +++ b/gui/src/components/connection-dialog.tsx @@ -1,7 +1,6 @@ -import { Button } from "@/components/ui/button"; -import { useConnectionConfig } from "@/context/connection-config-provider"; -import { useRouter } from "next/navigation"; +import { Button } from "@gui/components/ui/button"; import LogoLoading from "./logo-loading"; +import { useConfig } from "@gui/contexts/config-provider"; export default function ConnectingDialog({ message, @@ -11,14 +10,11 @@ export default function ConnectingDialog({ message?: string; onRetry?: () => void; }>) { - const { config } = useConnectionConfig(); - - const router = useRouter(); - + const { name, onBack } = useConfig(); let body = (

- Connecting to {config.name} + Connecting to {name}

); @@ -34,7 +30,7 @@ export default function ConnectingDialog({

-
diff --git a/src/components/context-menu-handler.tsx b/gui/src/components/context-menu-handler.tsx similarity index 93% rename from src/components/context-menu-handler.tsx rename to gui/src/components/context-menu-handler.tsx index 2d6bb2be..9d05f8cb 100644 --- a/src/components/context-menu-handler.tsx +++ b/gui/src/components/context-menu-handler.tsx @@ -1,9 +1,9 @@ -import useMessageListener from "@/hooks/useMessageListener"; -import { MessageChannelName } from "@/messages/const"; -import { +import useMessageListener from "@gui/hooks/useMessageListener"; +import { MessageChannelName } from "@gui/messages/const"; +import type { OpenContextMenuList, OpenContextMenuOptions, -} from "@/messages/openContextMenu"; +} from "@gui/messages/open-context-menu"; import { ContextMenu, ContextMenuTrigger, @@ -15,7 +15,7 @@ import { ContextMenuSub, ContextMenuSubTrigger, ContextMenuSubContent, -} from "@/components/ui/context-menu"; +} from "@gui/components/ui/context-menu"; import { useEffect, useRef, useState } from "react"; function ContextMenuList({ menu }: { menu: OpenContextMenuList }) { diff --git a/src/components/custom/ErrorMessage.tsx b/gui/src/components/custom/ErrorMessage.tsx similarity index 95% rename from src/components/custom/ErrorMessage.tsx rename to gui/src/components/custom/ErrorMessage.tsx index 43f6520b..3dfbec23 100644 --- a/src/components/custom/ErrorMessage.tsx +++ b/gui/src/components/custom/ErrorMessage.tsx @@ -1,7 +1,7 @@ -export default function ErrorMessage({ - message, -}: { - readonly message: string; -}) { - return
{message}
; -} +export default function ErrorMessage({ + message, +}: { + readonly message: string; +}) { + return
{message}
; +} diff --git a/src/components/database-gui.tsx b/gui/src/components/database-gui.tsx similarity index 83% rename from src/components/database-gui.tsx rename to gui/src/components/database-gui.tsx index 9cfd4be4..d65a88f5 100644 --- a/src/components/database-gui.tsx +++ b/gui/src/components/database-gui.tsx @@ -1,85 +1,85 @@ -"use client"; -import { - ResizableHandle, - ResizablePanel, - ResizablePanelGroup, -} from "@/components/ui/resizable"; -import { useEffect, useMemo, useState } from "react"; -import WindowTabs, { WindowTabItemProps } from "./windows-tab"; -import useMessageListener from "@/hooks/useMessageListener"; -import { MessageChannelName } from "@/messages/const"; -import { OpenTabsProps, receiveOpenTabMessage } from "@/messages/open-tab"; -import QueryWindow from "@/components/tabs/query-tab"; -import { LucideCode, LucideDatabase, LucideSettings } from "lucide-react"; -import SidebarTab, { SidebarTabItem } from "./sidebar-tab"; -import SchemaView from "./schema-sidebar"; -import SettingSidebar from "./sidebar/setting-sidebar"; -import { useDatabaseDriver } from "@/context/DatabaseDriverProvider"; - -export default function DatabaseGui() { - const DEFAULT_WIDTH = 300; - - const [defaultWidthPercentage, setDefaultWidthPercentage] = useState(20); - - useEffect(() => { - setDefaultWidthPercentage((DEFAULT_WIDTH / window.innerWidth) * 100); - }, []); - - const { collaborationDriver } = useDatabaseDriver(); - const [selectedTabIndex, setSelectedTabIndex] = useState(0); - const [tabs, setTabs] = useState(() => [ - { - title: "Query", - key: "query", - component: , - icon: LucideCode, - }, - ]); - - useMessageListener( - MessageChannelName.OPEN_NEW_TAB, - (newTab) => { - if (newTab) { - receiveOpenTabMessage({ newTab, setSelectedTabIndex, setTabs }); - } - } - ); - - const sidebarTabs = useMemo(() => { - return [ - { - key: "database", - name: "Database", - content: , - icon: LucideDatabase, - }, - collaborationDriver - ? { - key: "setting", - name: "Setting", - content: , - icon: LucideSettings, - } - : undefined, - ].filter(Boolean) as SidebarTabItem[]; - }, [collaborationDriver]); - - return ( -
- - - - - - - - - -
- ); -} +"use client"; +import { + ResizableHandle, + ResizablePanel, + ResizablePanelGroup, +} from "@gui/components/ui/resizable"; +import { useEffect, useMemo, useState } from "react"; +import WindowTabs, { WindowTabItemProps } from "./windows-tab"; +import useMessageListener from "@gui/hooks/useMessageListener"; +import { MessageChannelName } from "@gui/messages/const"; +import { OpenTabsProps, receiveOpenTabMessage } from "@gui/messages/open-tab"; +import QueryWindow from "@gui/components/tabs/query-tab"; +import { LucideCode, LucideDatabase, LucideSettings } from "lucide-react"; +import SidebarTab, { SidebarTabItem } from "./sidebar-tab"; +import SchemaView from "./schema-sidebar"; +import SettingSidebar from "./sidebar/setting-sidebar"; +import { useDatabaseDriver } from "@gui/contexts/driver-provider"; + +export default function DatabaseGui() { + const DEFAULT_WIDTH = 300; + + const [defaultWidthPercentage, setDefaultWidthPercentage] = useState(20); + + useEffect(() => { + setDefaultWidthPercentage((DEFAULT_WIDTH / window.innerWidth) * 100); + }, []); + + const { collaborationDriver } = useDatabaseDriver(); + const [selectedTabIndex, setSelectedTabIndex] = useState(0); + const [tabs, setTabs] = useState(() => [ + { + title: "Query", + key: "query", + component: , + icon: LucideCode, + }, + ]); + + useMessageListener( + MessageChannelName.OPEN_NEW_TAB, + (newTab) => { + if (newTab) { + receiveOpenTabMessage({ newTab, setSelectedTabIndex, setTabs }); + } + } + ); + + const sidebarTabs = useMemo(() => { + return [ + { + key: "database", + name: "Database", + content: , + icon: LucideDatabase, + }, + collaborationDriver + ? { + key: "setting", + name: "Setting", + content: , + icon: LucideSettings, + } + : undefined, + ].filter(Boolean) as SidebarTabItem[]; + }, [collaborationDriver]); + + return ( +
+ + + + + + + + + +
+ ); +} diff --git a/src/components/list-button-item.tsx b/gui/src/components/list-button-item.tsx similarity index 94% rename from src/components/list-button-item.tsx rename to gui/src/components/list-button-item.tsx index 4a47508d..399cf311 100644 --- a/src/components/list-button-item.tsx +++ b/gui/src/components/list-button-item.tsx @@ -1,5 +1,5 @@ import { buttonVariants } from "./ui/button"; -import { cn } from "@/lib/utils"; +import { cn } from "@gui/lib/utils"; import { LucideIcon } from "lucide-react"; export default function ListButtonItem({ diff --git a/src/components/loading-opacity.tsx b/gui/src/components/loading-opacity.tsx similarity index 100% rename from src/components/loading-opacity.tsx rename to gui/src/components/loading-opacity.tsx diff --git a/src/components/logo-loading.tsx b/gui/src/components/logo-loading.tsx similarity index 96% rename from src/components/logo-loading.tsx rename to gui/src/components/logo-loading.tsx index 62e123b9..a2545b5f 100644 --- a/src/components/logo-loading.tsx +++ b/gui/src/components/logo-loading.tsx @@ -1,21 +1,21 @@ -export default function LogoLoading() { - return ( -
-
- - ✱ - -
- -
-

LibSQL Studio

-
-
- ); -} +export default function LogoLoading() { + return ( +
+
+ + ✱ + +
+ +
+

LibSQL Studio

+
+
+ ); +} diff --git a/src/components/main-connection.tsx b/gui/src/components/main-connection.tsx similarity index 60% rename from src/components/main-connection.tsx rename to gui/src/components/main-connection.tsx index c98014b7..b3cc3512 100644 --- a/src/components/main-connection.tsx +++ b/gui/src/components/main-connection.tsx @@ -1,71 +1,64 @@ -"use client"; -import { useEffect, useLayoutEffect } from "react"; -import DatabaseGui from "./database-gui"; -import { useDatabaseDriver } from "@/context/DatabaseDriverProvider"; -import { TooltipProvider } from "@/components/ui/tooltip"; -import { AutoCompleteProvider } from "@/context/AutoCompleteProvider"; -import ContextMenuHandler from "./context-menu-handler"; -import InternalPubSub from "@/lib/internal-pubsub"; -import { useRouter } from "next/navigation"; -import { SchemaProvider } from "@/context/SchemaProvider"; -import { BlockEditorProvider } from "@/context/block-editor-provider"; -import { useConnectionConfig } from "@/context/connection-config-provider"; - -export interface ConnectionCredential { - url: string; - token: string; -} - -function MainConnection() { - const { databaseDriver: driver } = useDatabaseDriver(); - - useEffect(() => { - return () => { - driver.close(); - }; - }, [driver]); - - return ( - - - - - - ); -} - -function MainConnectionContainer() { - const router = useRouter(); - const { databaseDriver: driver } = useDatabaseDriver(); - const { config } = useConnectionConfig(); - - /** - * We use useLayoutEffect because it executes before - * other component mount. Since we need to attach the - * message handler first before children component - * start listening and sending message to each other - */ - useLayoutEffect(() => { - console.info("Injecting message into window object"); - window.internalPubSub = new InternalPubSub(); - }, [driver, router]); - - useEffect(() => { - document.title = config.name + " - LibSQL Studio"; - }, [config]); - - return ( - <> - - - - - - - - ); -} - -export default function MainScreen() { - return ; -} +"use client"; +import { useEffect, useLayoutEffect } from "react"; +import { TooltipProvider } from "@gui/components/ui/tooltip"; +import ContextMenuHandler from "./context-menu-handler"; +import { useDatabaseDriver } from "@gui/contexts/driver-provider"; +import DatabaseGui from "./database-gui"; +import { useConfig } from "@gui/contexts/config-provider"; +import { AutoCompleteProvider } from "@gui/contexts/auto-complete-provider"; +import { BlockEditorProvider } from "@gui/contexts/block-editor-provider"; +import InternalPubSub from "@gui/lib/internal-pubsub"; +import { SchemaProvider } from "@gui/contexts/schema-provider"; + +function MainConnection() { + const { databaseDriver: driver } = useDatabaseDriver(); + + useEffect(() => { + return () => { + driver.close(); + }; + }, [driver]); + + return ( + + + + + + ); +} + +function MainConnectionContainer() { + const { databaseDriver: driver } = useDatabaseDriver(); + const { name } = useConfig(); + + /** + * We use useLayoutEffect because it executes before + * other component mount. Since we need to attach the + * message handler first before children component + * start listening and sending message to each other + */ + useLayoutEffect(() => { + console.info("Injecting message into window object"); + window.internalPubSub = new InternalPubSub(); + }, [driver]); + + useEffect(() => { + document.title = name + " - LibSQL Studio"; + }, [name]); + + return ( + <> + + + + + + + + ); +} + +export default function MainScreen() { + return ; +} diff --git a/src/components/query-progress-log.tsx b/gui/src/components/query-progress-log.tsx similarity index 93% rename from src/components/query-progress-log.tsx rename to gui/src/components/query-progress-log.tsx index 626a2b0f..b6f6aff6 100644 --- a/src/components/query-progress-log.tsx +++ b/gui/src/components/query-progress-log.tsx @@ -1,85 +1,85 @@ -import { MultipleQueryProgress } from "@/lib/multiple-query"; -import { useEffect, useState } from "react"; -import CodePreview from "./code-preview"; - -function formatTimeAgo(ms: number) { - if (ms < 1000) { - return `${ms}ms`; - } else { - return `${(ms / 1000).toLocaleString(undefined, { - maximumFractionDigits: 2, - minimumFractionDigits: 2, - })}s`; - } -} - -export default function QueryProgressLog({ - progress, -}: { - progress: MultipleQueryProgress; -}) { - const [, setCurrentTime] = useState(() => Date.now()); - - useEffect(() => { - if (!progress.error) { - const intervalId = setInterval(() => setCurrentTime(Date.now()), 200); - return () => clearInterval(intervalId); - } - }, [progress]); - - const last3 = progress.logs.slice(-3).reverse(); - const value = progress.progress; - const total = progress.total; - const isEnded = total === value || !!progress.error; - - return ( -
-
- {isEnded ? ( - - Executed {value}/{total} - - ) : ( - - Executing {value}/{total} - - )} -
- -
- {last3.map((detail) => { - return ( -
- {detail.end && !detail.error && ( -
- [Query #{detail.order + 1}] This query took{" "} - {formatTimeAgo(detail.end - detail.start)} and affected{" "} - {detail.affectedRow} row(s). -
- )} - - {!!detail.error && ( -
-
{detail.error}
-
- )} - - {!detail.end && ( -
- Executing this query  - - {formatTimeAgo(Date.now() - detail.start)} - {" "} - ago. -
- )} - -
- -
- ); - })} -
-
- ); -} +import { MultipleQueryProgress } from "@gui/lib/multiple-query"; +import { useEffect, useState } from "react"; +import CodePreview from "./code-preview"; + +function formatTimeAgo(ms: number) { + if (ms < 1000) { + return `${ms}ms`; + } else { + return `${(ms / 1000).toLocaleString(undefined, { + maximumFractionDigits: 2, + minimumFractionDigits: 2, + })}s`; + } +} + +export default function QueryProgressLog({ + progress, +}: { + progress: MultipleQueryProgress; +}) { + const [, setCurrentTime] = useState(() => Date.now()); + + useEffect(() => { + if (!progress.error) { + const intervalId = setInterval(() => setCurrentTime(Date.now()), 200); + return () => clearInterval(intervalId); + } + }, [progress]); + + const last3 = progress.logs.slice(-3).reverse(); + const value = progress.progress; + const total = progress.total; + const isEnded = total === value || !!progress.error; + + return ( +
+
+ {isEnded ? ( + + Executed {value}/{total} + + ) : ( + + Executing {value}/{total} + + )} +
+ +
+ {last3.map((detail) => { + return ( +
+ {detail.end && !detail.error && ( +
+ [Query #{detail.order + 1}] This query took{" "} + {formatTimeAgo(detail.end - detail.start)} and affected{" "} + {detail.affectedRow} row(s). +
+ )} + + {!!detail.error && ( +
+
{detail.error}
+
+ )} + + {!detail.end && ( +
+ Executing this query  + + {formatTimeAgo(Date.now() - detail.start)} + {" "} + ago. +
+ )} + +
+ +
+ ); + })} +
+
+ ); +} diff --git a/src/components/query-result-table.tsx b/gui/src/components/query-result-table.tsx similarity index 91% rename from src/components/query-result-table.tsx rename to gui/src/components/query-result-table.tsx index 33260762..75044841 100644 --- a/src/components/query-result-table.tsx +++ b/gui/src/components/query-result-table.tsx @@ -1,484 +1,495 @@ -import GenericCell from "@/components/table-cell/GenericCell"; -import NumberCell from "@/components/table-cell/NumberCell"; -import TextCell from "@/components/table-cell/TextCell"; -import OptimizeTable, { - OptimizeTableCellRenderProps, - OptimizeTableHeaderWithIndexProps, -} from "@/components/table-optimized"; -import OptimizeTableState from "@/components/table-optimized/OptimizeTableState"; -import { exportRowsToExcel, exportRowsToSqlInsert } from "@/lib/export-helper"; -import { KEY_BINDING } from "@/lib/key-matcher"; -import { openContextMenuFromEvent } from "@/messages/openContextMenu"; -import { - LucideChevronDown, - LucidePin, - LucidePlus, - LucideSortAsc, - LucideSortDesc, - LucideTrash2, -} from "lucide-react"; -import React, { PropsWithChildren, useCallback, useState } from "react"; -import { - ColumnSortOption, - DatabaseValue, - TableColumnDataType, -} from "@/drivers/base-driver"; -import { useBlockEditor } from "@/context/block-editor-provider"; -import parseSafeJson from "@/lib/json-safe"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuTrigger, - DropdownMenuItem, - DropdownMenuSeparator, -} from "./ui/dropdown-menu"; -import { triggerSelectFiles, uploadFile } from "@/lib/file-upload"; -import { toast } from "sonner"; -import { useDatabaseDriver } from "@/context/DatabaseDriverProvider"; -import BigNumberCell from "./table-cell/BigNumberCell"; - -interface ResultTableProps { - data: OptimizeTableState; - tableName?: string; - onSortColumnChange?: (columns: ColumnSortOption[]) => void; - sortColumns?: ColumnSortOption[]; -} - -function isBlockNoteString(value: DatabaseValue): boolean { - if (typeof value !== "string") return false; - if (!(value.startsWith("{") && value.endsWith("}"))) return false; - - const parsedJson = parseSafeJson(value, null); - if (!parsedJson) return false; - - return parsedJson?.format === "BLOCK_NOTE"; -} - -function Header({ - children, - header, -}: PropsWithChildren<{ header: OptimizeTableHeaderWithIndexProps }>) { - const [open, setOpen] = useState(false); - - return ( - - -
{ - setOpen(true); - }} - > - {header.icon ?
{header.icon}
: null} -
{header.displayName}
- -
-
- - {children} - -
- ); -} - -export default function ResultTable({ - data, - tableName, - onSortColumnChange, -}: ResultTableProps) { - const [stickyHeaderIndex, setStickHeaderIndex] = useState(); - const { openBlockEditor } = useBlockEditor(); - const { databaseDriver } = useDatabaseDriver(); - - const renderHeader = useCallback( - (header: OptimizeTableHeaderWithIndexProps) => { - return ( -
- { - setStickHeaderIndex( - header.index === stickyHeaderIndex ? undefined : header.index - ); - }} - > - - Pin Header - - - { - if (onSortColumnChange) { - onSortColumnChange([{ columnName: header.name, by: "ASC" }]); - } - }} - > - - Sort A → Z - - { - if (onSortColumnChange) { - onSortColumnChange([{ columnName: header.name, by: "DESC" }]); - } - }} - > - - Sort Z → A - -
- ); - }, - [stickyHeaderIndex, tableName, onSortColumnChange] - ); - - const renderCell = useCallback( - ({ y, x, state, header }: OptimizeTableCellRenderProps) => { - const isFocus = state.hasFocus(y, x); - const editMode = isFocus && state.isInEditMode(); - - if (header.dataType === TableColumnDataType.TEXT) { - const value = state.getValue(y, x) as DatabaseValue; - let editor: "input" | "blocknote" = "input"; // this is default editor - - if (isBlockNoteString(value)) { - editor = "blocknote"; - } - - return ( - } - focus={isFocus} - isChanged={state.hasCellChange(y, x)} - onChange={(newValue) => { - state.changeValue(y, x, newValue); - }} - /> - ); - } else if (header.dataType === TableColumnDataType.REAL) { - return ( - } - focus={isFocus} - isChanged={state.hasCellChange(y, x)} - onChange={(newValue) => { - state.changeValue(y, x, newValue); - }} - /> - ); - } else if (header.dataType === TableColumnDataType.INTEGER) { - if (databaseDriver.supportBigInt()) { - return ( - } - focus={isFocus} - isChanged={state.hasCellChange(y, x)} - onChange={(newValue) => { - state.changeValue(y, x, newValue); - }} - /> - ); - } else { - return ( - } - focus={isFocus} - isChanged={state.hasCellChange(y, x)} - onChange={(newValue) => { - state.changeValue(y, x, newValue); - }} - /> - ); - } - } - - return ; - }, - [databaseDriver] - ); - - const onHeaderContextMenu = useCallback((e: React.MouseEvent) => { - e.preventDefault(); - e.stopPropagation(); - }, []); - - const copyCallback = useCallback((state: OptimizeTableState) => { - const focus = state.getFocus(); - if (focus) { - const y = focus.y; - const x = focus.x; - window.navigator.clipboard.writeText(state.getValue(y, x) as string); - } - }, []); - - const pasteCallback = useCallback((state: OptimizeTableState) => { - const focus = state.getFocus(); - if (focus) { - const y = focus.y; - const x = focus.x; - window.navigator.clipboard.readText().then((pasteValue) => { - state.changeValue(y, x, pasteValue); - }); - } - }, []); - - const onCellContextMenu = useCallback( - ({ - state, - event, - }: { - state: OptimizeTableState; - event: React.MouseEvent; - }) => { - const randomUUID = crypto.randomUUID(); - const timestamp = Math.floor(Date.now() / 1000).toString(); - const hasFocus = !!state.getFocus(); - - function setFocusValue(newValue: unknown) { - const focusCell = state.getFocus(); - if (focusCell) { - state.changeValue(focusCell.y, focusCell.x, newValue); - } - } - - function getFocusValue() { - const focusCell = state.getFocus(); - if (focusCell) { - return state.getValue(focusCell.y, focusCell.x); - } - } - - openContextMenuFromEvent([ - { - title: "Insert Value", - disabled: !hasFocus, - subWidth: 200, - sub: [ - { - title:
NULL
, - onClick: () => { - setFocusValue(null); - }, - }, - { - title:
DEFAULT
, - onClick: () => { - setFocusValue(undefined); - }, - }, - { separator: true }, - { - title: ( -
- Unix Timestamp - {timestamp} -
- ), - onClick: () => { - setFocusValue(timestamp); - }, - }, - { separator: true }, - { - title: ( -
- UUID - {randomUUID} -
- ), - onClick: () => { - setFocusValue(randomUUID); - }, - }, - ], - }, - { - title: "Edit with Block Editor", - onClick: () => { - openBlockEditor({ - initialContent: getFocusValue() as string, - onSave: setFocusValue, - }); - }, - }, - - { - title: "Upload File", - onClick: async () => { - const files = await triggerSelectFiles(); - - if (files.error) return toast.error(files.error.message); - - const file = files.value[0]; - - const toastId = toast.loading("Uploading file..."); - const { data, error } = await uploadFile(file); - if (error) - return toast.error("Upload failed!", { - id: toastId, - description: error.message, - }); - - setFocusValue(data.url); - return toast.success("File uploaded!", { id: toastId }); - }, - }, - - { - separator: true, - }, - { - title: "Copy Cell Value", - shortcut: KEY_BINDING.copy.toString(), - onClick: () => { - copyCallback(state); - }, - }, - { - title: "Paste", - shortcut: KEY_BINDING.paste.toString(), - onClick: () => { - pasteCallback(state); - }, - }, - { - separator: true, - }, - { - title: "Copy Row As", - sub: [ - { - title: "Copy as Excel", - onClick: () => { - if (state.getSelectedRowCount() > 0) { - window.navigator.clipboard.writeText( - exportRowsToExcel(state.getSelectedRowsArray()) - ); - } - }, - }, - { - title: "Copy as INSERT SQL", - onClick: () => { - const headers = state - .getHeaders() - .map((column) => column?.name ?? ""); - - if (state.getSelectedRowCount() > 0) { - window.navigator.clipboard.writeText( - exportRowsToSqlInsert( - tableName ?? "UnknownTable", - headers, - state.getSelectedRowsArray() - ) - ); - } - }, - }, - ], - }, - { separator: true }, - { - title: "Insert row", - icon: LucidePlus, - onClick: () => { - data.insertNewRow(); - }, - }, - { - title: "Delete selected row(s)", - icon: LucideTrash2, - onClick: () => { - data.getSelectedRowIndex().forEach((index) => { - data.removeRow(index); - }); - }, - }, - ])(event); - }, - [data, tableName, copyCallback, pasteCallback, openBlockEditor] - ); - - const onKeyDown = useCallback( - (state: OptimizeTableState, e: React.KeyboardEvent) => { - if (state.isInEditMode()) return; - - if (KEY_BINDING.copy.match(e as React.KeyboardEvent)) { - copyCallback(state); - } else if ( - KEY_BINDING.paste.match(e as React.KeyboardEvent) - ) { - pasteCallback(state); - } else if (e.key === "ArrowRight") { - const focus = state.getFocus(); - if (focus && focus.x + 1 < state.getHeaderCount()) { - state.setFocus(focus.y, focus.x + 1); - state.scrollToFocusCell("right", "top"); - } - } else if (e.key === "ArrowLeft") { - const focus = state.getFocus(); - if (focus && focus.x - 1 >= 0) { - state.setFocus(focus.y, focus.x - 1); - state.scrollToFocusCell("left", "top"); - } - } else if (e.key === "ArrowUp") { - const focus = state.getFocus(); - if (focus && focus.y - 1 >= 0) { - state.setFocus(focus.y - 1, focus.x); - state.scrollToFocusCell("left", "top"); - } - } else if (e.key === "ArrowDown") { - const focus = state.getFocus(); - if (focus && focus.y + 1 < state.getRowsCount()) { - state.setFocus(focus.y + 1, focus.x); - state.scrollToFocusCell("left", "bottom"); - } - } else if (e.key === "Tab") { - const focus = state.getFocus(); - if (focus) { - const colCount = state.getHeaderCount(); - const n = focus.y * colCount + focus.x + 1; - const x = n % colCount; - const y = Math.floor(n / colCount); - if (y >= state.getRowsCount()) return; - state.setFocus(y, x); - state.scrollToFocusCell(x === 0 ? "left" : "right", "bottom"); - } - } else if (e.key === "Enter") { - state.enterEditMode(); - } - - e.preventDefault(); - }, - [copyCallback, pasteCallback] - ); - - return ( - - ); -} +import GenericCell from "@gui/components/table-cell/GenericCell"; +import NumberCell from "@gui/components/table-cell/NumberCell"; +import TextCell from "@gui/components/table-cell/TextCell"; +import OptimizeTable, { + OptimizeTableCellRenderProps, + OptimizeTableHeaderWithIndexProps, +} from "@gui/components/table-optimized"; +import OptimizeTableState from "@gui/components/table-optimized/OptimizeTableState"; +import { + exportRowsToExcel, + exportRowsToSqlInsert, +} from "@gui/lib/export-helper"; +import { KEY_BINDING } from "@gui/lib/key-matcher"; +import { openContextMenuFromEvent } from "@gui/messages/open-context-menu"; +import { + LucideChevronDown, + LucidePin, + LucidePlus, + LucideSortAsc, + LucideSortDesc, + LucideTrash2, +} from "lucide-react"; +import React, { PropsWithChildren, useCallback, useState } from "react"; +import { + ColumnSortOption, + DatabaseValue, + TableColumnDataType, +} from "@gui/drivers/base-driver"; +import { useBlockEditor } from "@gui/contexts/block-editor-provider"; +import parseSafeJson from "@gui/lib/json-safe"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuTrigger, + DropdownMenuItem, + DropdownMenuSeparator, +} from "./ui/dropdown-menu"; +import { triggerSelectFiles, uploadFile } from "@gui/lib/file-upload"; +import { toast } from "sonner"; +import BigNumberCell from "./table-cell/BigNumberCell"; +import { useDatabaseDriver } from "@gui/contexts/driver-provider"; + +interface ResultTableProps { + data: OptimizeTableState; + tableName?: string; + onSortColumnChange?: (columns: ColumnSortOption[]) => void; + sortColumns?: ColumnSortOption[]; +} + +function isBlockNoteString(value: DatabaseValue): boolean { + if (typeof value !== "string") return false; + if (!(value.startsWith("{") && value.endsWith("}"))) return false; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const parsedJson = parseSafeJson(value, null); + if (!parsedJson) return false; + + return parsedJson?.format === "BLOCK_NOTE"; +} + +function Header({ + children, + header, +}: PropsWithChildren<{ header: OptimizeTableHeaderWithIndexProps }>) { + const [open, setOpen] = useState(false); + + return ( + + +
{ + setOpen(true); + }} + > + {header.icon ?
{header.icon}
: null} +
{header.displayName}
+ +
+
+ + {children} + +
+ ); +} + +export default function ResultTable({ + data, + tableName, + onSortColumnChange, +}: ResultTableProps) { + const [stickyHeaderIndex, setStickHeaderIndex] = useState(); + const { openBlockEditor } = useBlockEditor(); + const { databaseDriver } = useDatabaseDriver(); + + console.log("henlooooo"); + + const renderHeader = useCallback( + (header: OptimizeTableHeaderWithIndexProps) => { + return ( +
+ { + setStickHeaderIndex( + header.index === stickyHeaderIndex ? undefined : header.index + ); + }} + > + + Pin Header + + + { + if (onSortColumnChange) { + onSortColumnChange([{ columnName: header.name, by: "ASC" }]); + } + }} + > + + Sort A → Z + + { + if (onSortColumnChange) { + onSortColumnChange([{ columnName: header.name, by: "DESC" }]); + } + }} + > + + Sort Z → A + +
+ ); + }, + [stickyHeaderIndex, tableName, onSortColumnChange] + ); + + const renderCell = useCallback( + ({ y, x, state, header }: OptimizeTableCellRenderProps) => { + const isFocus = state.hasFocus(y, x); + const editMode = isFocus && state.isInEditMode(); + + if (header.dataType === TableColumnDataType.TEXT) { + const value = state.getValue(y, x) as DatabaseValue; + let editor: "input" | "blocknote" = "input"; // this is default editor + + if (isBlockNoteString(value)) { + editor = "blocknote"; + } + + return ( + } + focus={isFocus} + isChanged={state.hasCellChange(y, x)} + onChange={(newValue) => { + state.changeValue(y, x, newValue); + }} + /> + ); + } else if (header.dataType === TableColumnDataType.REAL) { + return ( + } + focus={isFocus} + isChanged={state.hasCellChange(y, x)} + onChange={(newValue) => { + state.changeValue(y, x, newValue); + }} + /> + ); + } else if (header.dataType === TableColumnDataType.INTEGER) { + if (databaseDriver.supportBigInt()) { + return ( + } + focus={isFocus} + isChanged={state.hasCellChange(y, x)} + onChange={(newValue) => { + state.changeValue(y, x, newValue); + }} + /> + ); + } else { + return ( + } + focus={isFocus} + isChanged={state.hasCellChange(y, x)} + onChange={(newValue) => { + state.changeValue(y, x, newValue); + }} + /> + ); + } + } + + return ; + }, + [databaseDriver] + ); + + const onHeaderContextMenu = useCallback((e: React.MouseEvent) => { + e.preventDefault(); + e.stopPropagation(); + }, []); + + const copyCallback = useCallback((state: OptimizeTableState) => { + const focus = state.getFocus(); + if (focus) { + const y = focus.y; + const x = focus.x; + window.navigator.clipboard.writeText(state.getValue(y, x) as string); + } + }, []); + + const pasteCallback = useCallback((state: OptimizeTableState) => { + const focus = state.getFocus(); + if (focus) { + const y = focus.y; + const x = focus.x; + window.navigator.clipboard.readText().then((pasteValue) => { + state.changeValue(y, x, pasteValue); + }); + } + }, []); + + const onCellContextMenu = useCallback( + ({ + state, + event, + }: { + state: OptimizeTableState; + event: React.MouseEvent; + }) => { + const randomUUID = crypto.randomUUID(); + const timestamp = Math.floor(Date.now() / 1000).toString(); + const hasFocus = !!state.getFocus(); + + function setFocusValue(newValue: unknown) { + const focusCell = state.getFocus(); + if (focusCell) { + state.changeValue(focusCell.y, focusCell.x, newValue); + } + } + + function getFocusValue() { + const focusCell = state.getFocus(); + if (focusCell) { + return state.getValue(focusCell.y, focusCell.x); + } + + return undefined; + } + + openContextMenuFromEvent([ + { + title: "Insert Value", + disabled: !hasFocus, + subWidth: 200, + sub: [ + { + title:
NULL
, + onClick: () => { + setFocusValue(null); + }, + }, + { + title:
DEFAULT
, + onClick: () => { + setFocusValue(undefined); + }, + }, + { separator: true }, + { + title: ( +
+ Unix Timestamp + {timestamp} +
+ ), + onClick: () => { + setFocusValue(timestamp); + }, + }, + { separator: true }, + { + title: ( +
+ UUID + {randomUUID} +
+ ), + onClick: () => { + setFocusValue(randomUUID); + }, + }, + ], + }, + { + title: "Edit with Block Editor", + onClick: () => { + openBlockEditor({ + initialContent: getFocusValue() as string, + onSave: setFocusValue, + }); + }, + }, + + { + title: "Upload File", + onClick: async () => { + const files = await triggerSelectFiles(); + + if (files.error) return toast.error(files.error.message); + + const file = files.value[0]; + if (!file) return; + + const toastId = toast.loading("Uploading file..."); + const { data, error } = await uploadFile(file); + if (error) + return toast.error("Upload failed!", { + id: toastId, + description: error.message, + }); + + setFocusValue(data.url); + return toast.success("File uploaded!", { id: toastId }); + }, + }, + + { + separator: true, + }, + { + title: "Copy Cell Value", + shortcut: KEY_BINDING.copy.toString(), + onClick: () => { + copyCallback(state); + }, + }, + { + title: "Paste", + shortcut: KEY_BINDING.paste.toString(), + onClick: () => { + pasteCallback(state); + }, + }, + { + separator: true, + }, + { + title: "Copy Row As", + sub: [ + { + title: "Copy as Excel", + onClick: () => { + if (state.getSelectedRowCount() > 0) { + window.navigator.clipboard.writeText( + exportRowsToExcel(state.getSelectedRowsArray()) + ); + } + }, + }, + { + title: "Copy as INSERT SQL", + onClick: () => { + const headers = state + .getHeaders() + .map((column) => column?.name ?? ""); + + if (state.getSelectedRowCount() > 0) { + window.navigator.clipboard.writeText( + exportRowsToSqlInsert( + tableName ?? "UnknownTable", + headers, + state.getSelectedRowsArray() + ) + ); + } + }, + }, + ], + }, + { separator: true }, + { + title: "Insert row", + icon: LucidePlus, + onClick: () => { + data.insertNewRow(); + }, + }, + { + title: "Delete selected row(s)", + icon: LucideTrash2, + onClick: () => { + data.getSelectedRowIndex().forEach((index) => { + data.removeRow(index); + }); + }, + }, + ])(event); + }, + [data, tableName, copyCallback, pasteCallback, openBlockEditor] + ); + + const onKeyDown = useCallback( + (state: OptimizeTableState, e: React.KeyboardEvent) => { + if (state.isInEditMode()) return; + + if (KEY_BINDING.copy.match(e as React.KeyboardEvent)) { + copyCallback(state); + } else if ( + KEY_BINDING.paste.match(e as React.KeyboardEvent) + ) { + pasteCallback(state); + } else if (e.key === "ArrowRight") { + const focus = state.getFocus(); + if (focus && focus.x + 1 < state.getHeaderCount()) { + state.setFocus(focus.y, focus.x + 1); + state.scrollToFocusCell("right", "top"); + } + } else if (e.key === "ArrowLeft") { + const focus = state.getFocus(); + if (focus && focus.x - 1 >= 0) { + state.setFocus(focus.y, focus.x - 1); + state.scrollToFocusCell("left", "top"); + } + } else if (e.key === "ArrowUp") { + const focus = state.getFocus(); + if (focus && focus.y - 1 >= 0) { + state.setFocus(focus.y - 1, focus.x); + state.scrollToFocusCell("left", "top"); + } + } else if (e.key === "ArrowDown") { + const focus = state.getFocus(); + if (focus && focus.y + 1 < state.getRowsCount()) { + state.setFocus(focus.y + 1, focus.x); + state.scrollToFocusCell("left", "bottom"); + } + } else if (e.key === "Tab") { + const focus = state.getFocus(); + if (focus) { + const colCount = state.getHeaderCount(); + const n = focus.y * colCount + focus.x + 1; + const x = n % colCount; + const y = Math.floor(n / colCount); + if (y >= state.getRowsCount()) return; + state.setFocus(y, x); + state.scrollToFocusCell(x === 0 ? "left" : "right", "bottom"); + } + } else if (e.key === "Enter") { + state.enterEditMode(); + } + + e.preventDefault(); + }, + [copyCallback, pasteCallback] + ); + + console.log("Herer"); + + return ( + + ); +} diff --git a/src/components/schema-editor/column-check-popup.tsx b/gui/src/components/schema-editor/column-check-popup.tsx similarity index 92% rename from src/components/schema-editor/column-check-popup.tsx rename to gui/src/components/schema-editor/column-check-popup.tsx index ac64d5e7..05642151 100644 --- a/src/components/schema-editor/column-check-popup.tsx +++ b/gui/src/components/schema-editor/column-check-popup.tsx @@ -1,62 +1,62 @@ -import { DatabaseTableColumnConstraint } from "@/drivers/base-driver"; -import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover"; -import { LucideCheck } from "lucide-react"; -import { Button } from "../ui/button"; -import { ColumnChangeEvent } from "./schema-editor-column-list"; -import { Textarea } from "../ui/textarea"; - -export default function ColumnCheckPopup({ - constraint, - disabled, - onChange, -}: Readonly<{ - constraint: DatabaseTableColumnConstraint; - disabled: boolean; - onChange: ColumnChangeEvent; -}>) { - return ( - - - - - - - -
-
Check
- -