diff --git a/package-lock.json b/package-lock.json index 56a26bd5..7353e0a0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,7 +50,8 @@ "cross-env": "^10.1.0", "mode-watcher": "^1.1.0", "svelte": "^5.55.5", - "vite": "^8.0.12" + "vite": "^8.0.12", + "vitest": "^4.1.9" } }, "node_modules/@antfu/install-pkg": { @@ -99,7 +100,6 @@ "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==", "devOptional": true, "license": "MIT", - "peer": true, "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" @@ -111,7 +111,6 @@ "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", "devOptional": true, "license": "MIT", - "peer": true, "dependencies": { "tslib": "^2.4.0" } @@ -207,7 +206,6 @@ "resolved": "https://registry.npmjs.org/@internationalized/date/-/date-3.12.1.tgz", "integrity": "sha512-6IedsVWXyq4P9Tj+TxuU8WGWM70hYLl12nbYU8jkikVpa6WXapFazPUcHUMDMoWftIDE2ILDkFFte6W2nFCkRQ==", "license": "Apache-2.0", - "peer": true, "dependencies": { "@swc/helpers": "^0.5.0" } @@ -657,6 +655,13 @@ "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==", "license": "MIT" }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, "node_modules/@svelte-put/shortcut": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/@svelte-put/shortcut/-/shortcut-4.1.0.tgz", @@ -1317,6 +1322,17 @@ "tslib": "^2.4.0" } }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, "node_modules/@types/d3": { "version": "7.4.3", "resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz", @@ -1570,6 +1586,13 @@ "@types/d3-selection": "*" } }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", @@ -1628,6 +1651,119 @@ "d3-transition": "^3.0.1" } }, + "node_modules/@vitest/expect": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.9.tgz", + "integrity": "sha512-vl/rYsUKcBr3SnQn166+XR5ZQcgMx3DQhFWdfli/cWpLnLUmbxZvyrJZotLFUryib+LtArYMSTJ5RbQ57ZqrlA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.1.9", + "@vitest/utils": "4.1.9", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.9.tgz", + "integrity": "sha512-EVkXzBjrPGM+cK8/ANWgBrkUCfJfb38/EfTSO8h7pWvKkyPkpWxvR7BkD2MyItMF62C97zAEoqdpUixwR/e+Rw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.1.9", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.9.tgz", + "integrity": "sha512-s0iufns3iIFitdgm+YR7g1whCAaGtXz459VS9/PqyKDEEFgYIhsHOQmXgIgDuYCt7DeQmiZT0Qe2OA2p4ZPu5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.9.tgz", + "integrity": "sha512-KXLMDtc7oe70+3mJfGrPUWPesswH+3sTxAMAMl8DG7I8IUQT4XW718dY5ID3vPUcmlu27CcKfY4P3h3I29SLJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.1.9", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.9.tgz", + "integrity": "sha512-Jc7RKGNBo8Z28WYIm0Niej4xdSPByRf6mU58VpHQkd6Zh05rlnA+twjbK5HyeIGHxrzsc3mJgS43uM0CZKzaIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.9", + "@vitest/utils": "4.1.9", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.9.tgz", + "integrity": "sha512-fHpsS6mIi+PiEW+vcRVOMkX1oSaPKne3VOclSFICPcGOmfKgXPU5iAah+wcNcj2xPrCCmfq99IDGf+EojhhvhA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.9.tgz", + "integrity": "sha512-A51o8ymO5PpqlWNnBP9ZHPXDIpuMtTLlGSjN7la4US+LJzoUMyhwjA5QXlm39JexgwHKW4Xjs8Z2d3dLCXOeuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.9", + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/@xyflow/svelte": { "version": "1.5.2", "resolved": "https://registry.npmjs.org/@xyflow/svelte/-/svelte-1.5.2.tgz", @@ -1663,7 +1799,6 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -1686,6 +1821,16 @@ "node": ">= 0.4" } }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/axobject-query": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", @@ -1749,6 +1894,16 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/character-entities-html4": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", @@ -1806,6 +1961,13 @@ "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", "license": "MIT" }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, "node_modules/cose-base": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-1.0.3.tgz", @@ -1853,7 +2015,6 @@ "resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.33.4.tgz", "integrity": "sha512-HIN5Pmd9MrX9BkV7tDwnOcEJCSFvCpc8X97h3f508J6I5FsqAY65wKOCvgH2CuP42CaahWaz4tuh32SOOIH7ww==", "license": "MIT", - "peer": true, "engines": { "node": ">=0.10" } @@ -2263,7 +2424,6 @@ "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz", "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==", "license": "ISC", - "peer": true, "engines": { "node": ">=12" } @@ -2491,6 +2651,13 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/es-module-lexer": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.1.0.tgz", + "integrity": "sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==", + "dev": true, + "license": "MIT" + }, "node_modules/es-toolkit": { "version": "1.47.0", "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.47.0.tgz", @@ -2524,6 +2691,26 @@ } } }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", + "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -3353,6 +3540,13 @@ "node": ">=8" } }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -3364,7 +3558,6 @@ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -3607,6 +3800,13 @@ "node": ">=20" } }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, "node_modules/slot-text": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/slot-text/-/slot-text-0.2.2.tgz", @@ -3657,6 +3857,20 @@ "sql-formatter": "bin/sql-formatter-cli.cjs" } }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.1.0.tgz", + "integrity": "sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==", + "dev": true, + "license": "MIT" + }, "node_modules/stringify-entities": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", @@ -3691,7 +3905,6 @@ "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.55.9.tgz", "integrity": "sha512-fTjjT8cHLDwigcu2j3pv7Jq04LklXevPB8uBgyHNiTXv+RMNvVnrjS4UEYrLMkhuq1vpCodHjiW+z/95SDs/fg==", "license": "MIT", - "peer": true, "dependencies": { "@jridgewell/remapping": "^2.3.4", "@jridgewell/sourcemap-codec": "^1.5.0", @@ -3751,7 +3964,6 @@ "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.6.0.tgz", "integrity": "sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w==", "license": "MIT", - "peer": true, "funding": { "type": "github", "url": "https://github.com/sponsors/dcastil" @@ -3780,8 +3992,7 @@ "version": "4.3.0", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.0.tgz", "integrity": "sha512-y6nxMGB1nMW9R6k96e5gdIFzcfL/gTJRNaqGes1YvkLnPVXzWgbqFF2yLC0T8G774n24cx3Pe8XrKoniCOAH+Q==", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/tapable": { "version": "2.3.3", @@ -3796,6 +4007,13 @@ "url": "https://opencollective.com/webpack" } }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, "node_modules/tinyexec": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.2.tgz", @@ -3821,6 +4039,16 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tinyrainbow": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz", + "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/trim-lines": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", @@ -3969,7 +4197,6 @@ "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.14.tgz", "integrity": "sha512-s4BJJ+5y1pYL6Otw51FHhVJQhPnuRinKig64g/1+EUNaJsd3gCKdD31IPFvswUgW9/60QT9oFHbZHbQK5imcxw==", "license": "MIT", - "peer": true, "dependencies": { "lightningcss": "^1.32.0", "picomatch": "^4.0.4", @@ -4062,6 +4289,96 @@ } } }, + "node_modules/vitest": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.9.tgz", + "integrity": "sha512-nE3/LEyc0z87uHYLZebqCUOaJr2hdtuPp7BQ4BosVFnfltxgAvMG08NyrSGlPpOUWvR27c5flSmYFTNr78L9GQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.1.9", + "@vitest/mocker": "4.1.9", + "@vitest/pretty-format": "4.1.9", + "@vitest/runner": "4.1.9", + "@vitest/snapshot": "4.1.9", + "@vitest/spy": "4.1.9", + "@vitest/utils": "4.1.9", + "es-module-lexer": "^2.0.0", + "expect-type": "^1.3.0", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^4.0.0-rc.1", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.1.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.1.9", + "@vitest/browser-preview": "4.1.9", + "@vitest/browser-webdriverio": "4.1.9", + "@vitest/coverage-istanbul": "4.1.9", + "@vitest/coverage-v8": "4.1.9", + "@vitest/ui": "4.1.9", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -4078,6 +4395,23 @@ "node": ">= 8" } }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/zimmerframe": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz", diff --git a/package.json b/package.json index 1e8c91ce..fcf647d3 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,8 @@ "cross-env": "^10.1.0", "mode-watcher": "^1.1.0", "svelte": "^5.55.5", - "vite": "^8.0.12" + "vite": "^8.0.12", + "vitest": "^4.1.9" }, "dependencies": { "@dagrejs/dagre": "^3.0.0", diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 84ef9db7..d7933cf0 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -122,10 +122,10 @@ pub fn toggle_devtools(window: tauri::WebviewWindow) { use crate::db::{ connect, connect_clickhouse, connect_d1, connect_duckdb, connect_libsql, connect_mssql, connect_mysql, connect_sqlite, disconnect, delete_table_row, delete_table_rows, execute_ddl, execute_sql, execute_sql_multi, get_table_rows, insert_table_row, - list_schemas, list_tables, list_indexes, list_enums, list_triggers, list_sequences, + list_schemas, list_tables, list_indexes, list_enums, list_functions, list_triggers, list_sequences, ping_connection, truncate_table, drop_table, get_table_column_structure, get_incoming_foreign_keys, get_table_ddl as db_get_table_ddl, test_clickhouse_connection, test_connection, test_d1_connection, test_duckdb_connection, test_libsql_connection, test_mssql_connection, test_mysql_connection, test_sqlite_connection, - update_table_cell, ConnectionConfig, D1Config, DbState, EnumInfo, ExplainResult, IndexInfo, LibSqlConfig, + update_table_cell, ConnectionConfig, D1Config, DbState, EnumInfo, FunctionInfo, ExplainResult, IndexInfo, LibSqlConfig, SqlResult, SqliteConfig, TableInfo, TableRows, TriggerInfo, SequenceInfo, ColumnStructureRow, IncomingForeignKey, InsertRowResult, TunnelState, explain_pg, explain_mysql, explain_sqlite, @@ -360,6 +360,19 @@ pub async fn pg_list_sequences( list_sequences(state, schema).await } +#[tauri::command] +pub async fn pg_list_functions( + state: State<'_, DbState>, + schema: String, +) -> Result, String> { + list_functions(state, schema).await +} + +#[tauri::command] +pub async fn ping_db_connection(state: State<'_, DbState>) -> Result<(), String> { + ping_connection(state).await +} + #[tauri::command] pub async fn pg_truncate_table( state: State<'_, DbState>, @@ -523,6 +536,18 @@ pub async fn pg_insert_table_row( insert_table_row(state, schema, table, values).await } +// ── Cancel running query ────────────────────────────────────────────────────── + +#[tauri::command] +pub async fn cancel_query(state: State<'_, DbState>) -> Result<(), String> { + if let Ok(mut guard) = state.cancel_tx.lock() { + if let Some(tx) = guard.take() { + let _ = tx.send(()); + } + } + Ok(()) +} + // ── License ─────────────────────────────────────────────────────────────────── #[tauri::command] diff --git a/src-tauri/src/db/connection.rs b/src-tauri/src/db/connection.rs index e81ecd84..3034fded 100644 --- a/src-tauri/src/db/connection.rs +++ b/src-tauri/src/db/connection.rs @@ -7,6 +7,7 @@ use sqlx::{ConnectOptions, MySqlPool, PgPool, SqlitePool}; use std::sync::{Arc, Mutex}; use std::time::Duration; use tauri::State; +use tokio::sync::oneshot; use super::ssh_tunnel::{SshConfig, SshTunnel, TunnelState}; @@ -228,11 +229,15 @@ impl ActiveConnection { pub struct DbState { pub conn: Arc>>, + pub cancel_tx: Arc>>>, } impl Default for DbState { fn default() -> Self { - Self { conn: Arc::new(Mutex::new(None)) } + Self { + conn: Arc::new(Mutex::new(None)), + cancel_tx: Arc::new(Mutex::new(None)), + } } } diff --git a/src-tauri/src/db/mod.rs b/src-tauri/src/db/mod.rs index 89e488d0..8b71f553 100644 --- a/src-tauri/src/db/mod.rs +++ b/src-tauri/src/db/mod.rs @@ -22,13 +22,13 @@ pub use explain::{explain_pg, explain_mysql, explain_sqlite, ExplainResult}; pub use ssh_tunnel::TunnelState; pub use query::{ delete_table_row, delete_table_rows, execute_ddl, execute_sql, execute_sql_multi, execute_sql_on_conn, - get_column_stats, get_table_rows, insert_table_row, update_table_cell, + get_column_stats, get_table_rows, insert_table_row, update_table_cell, ping_connection, ColumnStats, InsertRowResult, RowFilter, SqlResult, TableRows, }; pub use schema::{ list_schemas, list_tables, list_schemas_on_conn, list_tables_on_conn, - list_indexes, list_enums, list_triggers, list_sequences, + list_indexes, list_enums, list_functions, list_triggers, list_sequences, truncate_table, drop_table, get_table_column_structure, get_incoming_foreign_keys, get_table_ddl, get_table_ddl_on_conn, - TableInfo, IndexInfo, EnumInfo, TriggerInfo, SequenceInfo, ColumnStructureRow, IncomingForeignKey, + TableInfo, IndexInfo, EnumInfo, FunctionInfo, TriggerInfo, SequenceInfo, ColumnStructureRow, IncomingForeignKey, }; diff --git a/src-tauri/src/db/query.rs b/src-tauri/src/db/query.rs index ab65ac8d..8b2f7392 100644 --- a/src-tauri/src/db/query.rs +++ b/src-tauri/src/db/query.rs @@ -1632,20 +1632,30 @@ pub async fn execute_ddl(state: State<'_, DbState>, sql: String) -> Result<(), S } pub async fn execute_sql(state: State<'_, DbState>, sql: String) -> Result { - let sql_str = sql.trim(); + let sql_str = sql.trim().to_string(); if sql_str.is_empty() { return Err("Query is empty".into()); } - match require_conn(&state)? { - ActiveConnection::Postgres(pool) => execute_sql_pg(&pool, sql_str).await, - ActiveConnection::Sqlite(pool) => super::sqlite::execute_sql(&pool, sql_str).await, - ActiveConnection::D1(cfg) => super::d1::query(&cfg, sql_str, vec![]).await, - ActiveConnection::LibSql(cfg) => super::libsql::query(&cfg, sql_str, vec![]).await, - ActiveConnection::Mysql(pool) => super::mysql::execute_sql(&pool, sql_str).await, - ActiveConnection::Clickhouse(cfg) => super::clickhouse::query(&cfg, sql_str).await, - ActiveConnection::Duckdb(h) => super::duckdb::execute_sql(&h, sql_str).await, - ActiveConnection::Mssql(h) => super::mssql::execute_sql(&h, sql_str).await, - } + let conn = require_conn(&state)?; + let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel::<()>(); + *state.cancel_tx.lock().map_err(|e| e.to_string())? = Some(cancel_tx); + let result = tokio::select! { + r = async move { + match conn { + ActiveConnection::Postgres(pool) => execute_sql_pg(&pool, &sql_str).await, + ActiveConnection::Sqlite(pool) => super::sqlite::execute_sql(&pool, &sql_str).await, + ActiveConnection::D1(cfg) => super::d1::query(&cfg, &sql_str, vec![]).await, + ActiveConnection::LibSql(cfg) => super::libsql::query(&cfg, &sql_str, vec![]).await, + ActiveConnection::Mysql(pool) => super::mysql::execute_sql(&pool, &sql_str).await, + ActiveConnection::Clickhouse(cfg) => super::clickhouse::query(&cfg, &sql_str).await, + ActiveConnection::Duckdb(h) => super::duckdb::execute_sql(&h, &sql_str).await, + ActiveConnection::Mssql(h) => super::mssql::execute_sql(&h, &sql_str).await, + } + } => r, + _ = async { let _ = cancel_rx.await; } => Err("Query cancelled".to_string()), + }; + if let Ok(mut guard) = state.cancel_tx.lock() { *guard = None; } + result } /// Execute a SQL query against an arbitrary saved connection without changing @@ -1920,34 +1930,44 @@ async fn execute_sql_multi_pg(pool: &sqlx::PgPool, sql: &str) -> Result, sql: String) -> Result, String> { - let sql_str = sql.trim(); + let sql_str = sql.trim().to_string(); if sql_str.is_empty() { return Err("Query is empty".into()); } - match require_conn(&state)? { - ActiveConnection::Postgres(pool) => execute_sql_multi_pg(&pool, sql_str).await, - ActiveConnection::Sqlite(pool) => { - super::sqlite::execute_sql(&pool, sql_str).await.map(|r| vec![r]) - } - ActiveConnection::D1(cfg) => { - super::d1::query(&cfg, sql_str, vec![]).await.map(|r| vec![r]) - } - ActiveConnection::LibSql(cfg) => { - super::libsql::query(&cfg, sql_str, vec![]).await.map(|r| vec![r]) - } - ActiveConnection::Mysql(pool) => { - super::mysql::execute_sql(&pool, sql_str).await.map(|r| vec![r]) - } - ActiveConnection::Clickhouse(cfg) => { - super::clickhouse::query(&cfg, sql_str).await.map(|r| vec![r]) - } - ActiveConnection::Duckdb(h) => { - super::duckdb::execute_sql(&h, sql_str).await.map(|r| vec![r]) - } - ActiveConnection::Mssql(h) => { - super::mssql::execute_sql(&h, sql_str).await.map(|r| vec![r]) - } - } + let conn = require_conn(&state)?; + let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel::<()>(); + *state.cancel_tx.lock().map_err(|e| e.to_string())? = Some(cancel_tx); + let result = tokio::select! { + r = async move { + match conn { + ActiveConnection::Postgres(pool) => execute_sql_multi_pg(&pool, &sql_str).await, + ActiveConnection::Sqlite(pool) => { + super::sqlite::execute_sql(&pool, &sql_str).await.map(|r| vec![r]) + } + ActiveConnection::D1(cfg) => { + super::d1::query(&cfg, &sql_str, vec![]).await.map(|r| vec![r]) + } + ActiveConnection::LibSql(cfg) => { + super::libsql::query(&cfg, &sql_str, vec![]).await.map(|r| vec![r]) + } + ActiveConnection::Mysql(pool) => { + super::mysql::execute_sql(&pool, &sql_str).await.map(|r| vec![r]) + } + ActiveConnection::Clickhouse(cfg) => { + super::clickhouse::query(&cfg, &sql_str).await.map(|r| vec![r]) + } + ActiveConnection::Duckdb(h) => { + super::duckdb::execute_sql(&h, &sql_str).await.map(|r| vec![r]) + } + ActiveConnection::Mssql(h) => { + super::mssql::execute_sql(&h, &sql_str).await.map(|r| vec![r]) + } + } + } => r, + _ = async { let _ = cancel_rx.await; } => Err("Query cancelled".to_string()), + }; + if let Ok(mut guard) = state.cancel_tx.lock() { *guard = None; } + result } // ── D1 helpers (thin wrappers that build SQLite-compatible SQL) ─────────────── @@ -2591,3 +2611,26 @@ pub async fn get_column_stats( Ok(ColumnStats { column, count, null_count, distinct_count, min, max, avg }) } + +/// Lightweight connection health check — runs `SELECT 1` against the active +/// connection. HTTP-based engines (D1, LibSQL, Clickhouse) are stateless so we +/// return Ok immediately; a real request would validate their tokens but also +/// incur network cost every 30 s. +pub async fn ping_connection(state: State<'_, DbState>) -> Result<(), String> { + let conn = require_conn(&state)?; + match conn { + ActiveConnection::Postgres(pool) => { + sqlx::query("SELECT 1").execute(&pool).await.map(|_| ()).map_err(|e| e.to_string()) + } + ActiveConnection::Sqlite(pool) => { + sqlx::query("SELECT 1").execute(&pool).await.map(|_| ()).map_err(|e| e.to_string()) + } + ActiveConnection::Mysql(pool) => { + sqlx::query("SELECT 1").execute(&pool).await.map(|_| ()).map_err(|e| e.to_string()) + } + // HTTP-based: stateless, no persistent TCP connection to validate + ActiveConnection::D1(_) | ActiveConnection::LibSql(_) | ActiveConnection::Clickhouse(_) => Ok(()), + ActiveConnection::Duckdb(h) => super::duckdb::execute_sql(&h, "SELECT 1").await.map(|_| ()), + ActiveConnection::Mssql(h) => super::mssql::execute_sql(&h, "SELECT 1").await.map(|_| ()), + } +} diff --git a/src-tauri/src/db/schema.rs b/src-tauri/src/db/schema.rs index 42753bfb..2e190370 100644 --- a/src-tauri/src/db/schema.rs +++ b/src-tauri/src/db/schema.rs @@ -70,8 +70,15 @@ const LIST_TABLES_SQL: &str = r#" END AS kind, CASE WHEN c.relkind IN ('v', 'f') THEN -1 - WHEN s.n_live_tup IS NOT NULL THEN GREATEST(s.n_live_tup::bigint, 0) - WHEN c.reltuples >= 0 THEN c.reltuples::bigint + -- Trust the stats/planner estimate ONLY when it is strictly positive. + -- A zero or missing estimate is ambiguous: a freshly created table, + -- bulk-loaded data, a restored dump, or a server where autovacuum / + -- the stats collector hasn't run yet all report n_live_tup = 0 even + -- when rows exist. We mark those as -1 (unknown) and resolve them with + -- an exact COUNT(*) below. Large tables keep a positive estimate and + -- skip the (potentially slow) exact count. + WHEN COALESCE(s.n_live_tup, 0) > 0 THEN s.n_live_tup::bigint + WHEN c.reltuples > 0 THEN c.reltuples::bigint ELSE -1 END AS row_count, CASE WHEN c.relkind IN ('r', 'p') THEN c.relrowsecurity ELSE false END AS rls_enabled @@ -411,6 +418,46 @@ async fn list_schemas_mysql(pool: &MySqlPool) -> Result, String> { Ok(vec![db.unwrap_or_else(|| "default".to_string())]) } +async fn mysql_exact_row_count(pool: &MySqlPool, schema: &str, table: &str) -> Result { + let q = |id: &str| format!("`{}`", id.replace('`', "``")); + let sql = format!("SELECT COUNT(*) FROM {}.{}", q(schema), q(table)); + sqlx::query_scalar::<_, i64>(&sql) + .fetch_one(pool) + .await + .map_err(|e| format!("Failed to count rows for {table}: {e}")) +} + +/// Replace ambiguous (-1) row counts with an exact COUNT(*). Mirrors the +/// PostgreSQL `resolve_unknown_row_counts` path. +async fn resolve_unknown_row_counts_mysql(pool: &MySqlPool, schema: &str, tables: &mut [TableInfo]) { + for t in tables.iter_mut() { + if t.row_count < 0 && t.kind == "view" { + t.row_count = 0; + } + } + + let needs_count: Vec = tables + .iter() + .enumerate() + .filter(|(_, t)| t.row_count < 0) + .map(|(i, _)| i) + .collect(); + + if needs_count.is_empty() { + return; + } + + let futs: Vec<_> = needs_count + .iter() + .map(|&i| mysql_exact_row_count(pool, schema, &tables[i].name)) + .collect(); + let counts = futures::future::join_all(futs).await; + + for (&idx, result) in needs_count.iter().zip(counts.iter()) { + tables[idx].row_count = result.as_ref().copied().unwrap_or(0); + } +} + async fn list_tables_mysql(pool: &MySqlPool, schema: &str) -> Result, String> { let rows = sqlx::query( "SELECT TABLE_NAME, TABLE_TYPE, COALESCE(TABLE_ROWS, 0) \ @@ -423,18 +470,25 @@ async fn list_tables_mysql(pool: &MySqlPool, schema: &str) -> Result = rows .iter() .filter_map(|r| { let name: String = r.try_get(0).ok()?; let ty: String = r.try_get(1).unwrap_or_else(|_| "BASE TABLE".to_string()); // TABLE_ROWS is BIGINT UNSIGNED. COALESCE makes it non-nullable so // decode as u64 directly; Option can silently fail on non-null columns. - let row_count: i64 = r.try_get::(2).unwrap_or(0) as i64; + // For InnoDB this is only an estimate and is frequently 0 (or far off) + // until ANALYZE TABLE runs — so a 0 estimate is treated as unknown (-1) + // and resolved with an exact COUNT(*) below. + let est: i64 = r.try_get::(2).unwrap_or(0) as i64; let kind = if ty == "VIEW" { "view" } else { "table" }.to_string(); + let row_count = if est > 0 { est } else { -1 }; Some(TableInfo { name, kind, row_count, rls_enabled: None }) }) - .collect()) + .collect(); + + resolve_unknown_row_counts_mysql(pool, schema, &mut tables).await; + Ok(tables) } async fn list_indexes_mysql(pool: &MySqlPool, schema: &str) -> Result, String> { @@ -503,6 +557,19 @@ pub struct TriggerInfo { pub enabled: bool, } +// ── Functions / Procedures (PostgreSQL only) ───────────────────────────────── + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FunctionInfo { + pub name: String, + /// Full call signature e.g. "fn(arg1 text, arg2 int)" + pub signature: String, + pub return_type: String, + /// "function" | "procedure" | "aggregate" + pub kind: String, +} + // ── Sequences (PostgreSQL only) ─────────────────────────────────────────────── #[derive(Debug, Clone, Serialize)] @@ -701,6 +768,57 @@ pub async fn list_indexes(state: State<'_, DbState>, schema: String) -> Result Result, String> { + let rows = sqlx::query( + r#" + SELECT DISTINCT ON (p.proname) + p.proname::text AS name, + pg_get_function_arguments(p.oid) AS arg_types, + COALESCE(pg_get_function_result(p.oid), 'void') AS return_type, + CASE p.prokind + WHEN 'f' THEN 'function' + WHEN 'p' THEN 'procedure' + WHEN 'a' THEN 'aggregate' + ELSE 'function' + END AS kind + FROM pg_catalog.pg_proc p + JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = $1 + AND p.prokind IN ('f', 'p', 'a') + ORDER BY p.proname + "#, + ) + .bind(schema) + .fetch_all(pool) + .await + .map_err(|e| format!("Failed to list functions: {e}"))?; + + rows.iter() + .map(|row| { + let name: String = row.try_get("name").map_err(|e| e.to_string())?; + let arg_types: String = row.try_get("arg_types").map_err(|e| e.to_string())?; + let return_type: String = row.try_get("return_type").map_err(|e| e.to_string())?; + let kind: String = row.try_get("kind").map_err(|e| e.to_string())?; + Ok(FunctionInfo { + signature: format!("{}({})", name, arg_types), + name, + return_type, + kind, + }) + }) + .collect() +} + +pub async fn list_functions(state: State<'_, DbState>, schema: String) -> Result, String> { + match require_conn(&state)? { + ActiveConnection::Postgres(pool) => { + validate_ident(&schema)?; + list_functions_pg(&pool, &schema).await + } + _ => Ok(vec![]), + } +} + pub async fn list_enums(state: State<'_, DbState>, schema: String) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index cc7655bc..5380480a 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -57,7 +57,10 @@ pub fn run() { let _ = metrics::set_process_title("stroke".into()); // Create the shared connection Arc — both DbState and McpState point to the same lock. let db_conn: Arc>> = Arc::new(Mutex::new(None)); - let db_state = DbState { conn: Arc::clone(&db_conn) }; + let db_state = DbState { + conn: Arc::clone(&db_conn), + cancel_tx: Arc::new(std::sync::Mutex::new(None)), + }; let mcp_state = McpState::new(db_conn); tauri::Builder::default() @@ -251,8 +254,10 @@ pub fn run() { commands::pg_get_table_column_structure, commands::pg_get_incoming_foreign_keys, commands::pg_list_enums, + commands::pg_list_functions, commands::pg_list_triggers, commands::pg_list_sequences, + commands::ping_db_connection, commands::pg_truncate_table, commands::pg_drop_table, commands::get_table_ddl, @@ -302,6 +307,7 @@ pub fn run() { commands::enable_autostart, commands::disable_autostart, commands::get_autostart_status, + commands::cancel_query, #[cfg(debug_assertions)] commands::debug_set_trial_days_ago, #[cfg(debug_assertions)] diff --git a/src/App.svelte b/src/App.svelte index 92de490b..6b8f2d93 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -3,6 +3,7 @@ import { Toaster } from '$lib/components/ui/sonner/index.js' import StudioShell from './lib/components/StudioShell.svelte' import LicenseGate from './lib/components/LicenseGate.svelte' + import AppErrorBoundary from './lib/components/AppErrorBoundary.svelte' import { loadSettings, applySettings, installZoomShortcuts } from '$lib/stores/settings.js' import { installPlatformClass } from '$lib/platform.js' @@ -41,6 +42,8 @@ - - - + + + + + diff --git a/src/app.css b/src/app.css index 53cdce51..e6a82bfc 100644 --- a/src/app.css +++ b/src/app.css @@ -519,6 +519,14 @@ html[data-os="linux"] { --window-radius: 8px; } } } + /* Canvas table: promote scroll container to a compositing layer so WebKit's + CADisplayLink runs at the display's native rate (120Hz on ProMotion) instead + of the default 60Hz timer path. will-change:scroll-position does NOT create + a new stacking context, so position:sticky inside is unaffected. */ + [data-canvas-table] { + will-change: scroll-position; + } + /* Minimal thin scrollbars — all platforms */ :is(.app-scroll, .overflow-auto, .overflow-y-auto, .overflow-x-auto) { scrollbar-width: thin; diff --git a/src/lib/ai.js b/src/lib/ai.js index cad7b26f..c25d538f 100644 --- a/src/lib/ai.js +++ b/src/lib/ai.js @@ -1352,11 +1352,20 @@ SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() ORDER B (ctx.userSkills ?? []).map((s) => `### ${s.name}\n${s.content}`).join('\n\n') : '' + const envLine = ctx.environment + ? ctx.environment === 'prod' + ? `Environment: PRODUCTION — treat all destructive queries (DELETE, DROP, TRUNCATE, UPDATE without WHERE) with extreme caution. Always confirm scope before executing.` + : ctx.environment === 'staging' + ? `Environment: STAGING` + : `Environment: DEV` + : '' + return `You are an expert ${DB_LABEL[dbType] ?? 'SQL'} database assistant embedded in Stroke — a database GUI. Your job: help users explore, query, analyse, and visualise their database through tool calls and clear explanations. === DATABASE === Engine: ${DB_LABEL[dbType] ?? dbType} +${envLine} ${DB_NOTES[dbType] ?? ''} Available schemas: ${ctx.schemas.length ? ctx.schemas.join(', ') : ctx.activeSchema} diff --git a/src/lib/api.js b/src/lib/api.js index 70a15c36..519a08c0 100644 --- a/src/lib/api.js +++ b/src/lib/api.js @@ -347,6 +347,24 @@ export async function listSequences(schema) { } } +/** @param {string} schema */ +export async function listFunctions(schema) { + try { + return await invoke('pg_list_functions', { schema }) + } catch (err) { + throw new Error(formatInvokeError(err)) + } +} + +/** @returns {Promise} */ +export async function pingConnection() { + try { + await invoke('ping_db_connection') + } catch (err) { + throw new Error(formatInvokeError(err)) + } +} + /** * @param {string} schema * @param {string} table @@ -442,6 +460,11 @@ export async function getColumnStats(schema, table, column) { } } +/** Cancel the currently-running SQL query (no-op if none is running). */ +export async function cancelQuery() { + return inv('cancel_query') +} + /** @param {string} sql */ export async function executeSql(sql) { try { diff --git a/src/lib/components/AiChat.svelte b/src/lib/components/AiChat.svelte index 13b7190c..c42d24c6 100644 --- a/src/lib/components/AiChat.svelte +++ b/src/lib/components/AiChat.svelte @@ -1035,7 +1035,7 @@ URL.revokeObjectURL(url); c.toBlob((b) => { if (!b) { - toast.error("Failed to export PNG"); + toast.error("Could not export PNG"); return; } const pngUrl = URL.createObjectURL(b); @@ -1051,7 +1051,7 @@ }; img.onerror = () => { URL.revokeObjectURL(url); - toast.error("Failed to export PNG"); + toast.error("Could not export PNG"); }; img.src = url; } diff --git a/src/lib/components/AiSidebar.svelte b/src/lib/components/AiSidebar.svelte index c583e7e1..e8abb89e 100644 --- a/src/lib/components/AiSidebar.svelte +++ b/src/lib/components/AiSidebar.svelte @@ -624,7 +624,7 @@ -
+
Assistant diff --git a/src/lib/components/AppErrorBoundary.svelte b/src/lib/components/AppErrorBoundary.svelte new file mode 100644 index 00000000..181f3274 --- /dev/null +++ b/src/lib/components/AppErrorBoundary.svelte @@ -0,0 +1,45 @@ + + + { try { console.error('[app-boundary]', e) } catch { /* noop */ } }}> + {@render children()} + + {#snippet failed(error, reset)} +
+
+ +
+ +
+

Something went wrong

+

+ The interface hit an unexpected error. Try to recover, or reload — your + connections and data are safe. +

+
+ +
{String(/** @type {any} */ (error)?.message ?? error)}
+ +
+ + +
+
+ {/snippet} +
diff --git a/src/lib/components/BackupPage.svelte b/src/lib/components/BackupPage.svelte index 49ec0053..3e5e278f 100644 --- a/src/lib/components/BackupPage.svelte +++ b/src/lib/components/BackupPage.svelte @@ -182,7 +182,7 @@ if (exportCancelled) return; exportError = String(/** @type {any} */ (e)?.message ?? e); exportPhase = "error"; - toast.error("Export failed"); + toast.error("Could not export", { description: exportError }); } finally { stopExportLog(); } @@ -285,7 +285,7 @@ if (importCancelled) return; importError = String(/** @type {any} */ (e)?.message ?? e); importPhase = "error"; - toast.error("Restore failed"); + toast.error("Could not restore", { description: importError }); } finally { stopRestoreLog(); } diff --git a/src/lib/components/CommandPalette.svelte b/src/lib/components/CommandPalette.svelte index fdcb8add..ce769969 100644 --- a/src/lib/components/CommandPalette.svelte +++ b/src/lib/components/CommandPalette.svelte @@ -148,35 +148,84 @@ import Search from '@lucide/svelte/icons/search' let paletteSearch = $state('') const TABLES_PAGE_CAP = 100 - // Pre-lowercase table names ONCE per table-list change (not per keystroke), so - // filtering thousands of tables stays cheap as the user types — the keystroke - // path then only runs the integer-scoring loop, never N× String.toLowerCase(). - const _loweredRegular = $derived(regularTables.map((t) => ({ t, l: t.name.toLowerCase() }))) - const _loweredViews = $derived(viewTables.map((t) => ({ t, l: t.name.toLowerCase() }))) - const _loweredMatViews = $derived(matViewTables.map((t) => ({ t, l: t.name.toLowerCase() }))) + // Strip word separators so "-", "_", "." and spaces are all interchangeable: + // "product likes", "product-likes", "productlikes" all match "product_likes". + const stripSep = (/** @type {string} */ s) => s.replace(/[\s_.\-]+/g, '') + + // Precompute per table ONCE per table-list change (not per keystroke): lowercased + // name, separator-stripped form, word segments, and word initials (for acronym + // matches like "pv" → product_visitor). The keystroke path then only runs the + // integer scorer, never re-lowercasing/splitting N names — so it stays instant + // (sub-millisecond) for thousands of tables WITHOUT a debounce. + /** @param {{ name: string }} t */ + const prep = (t) => { + const l = t.name.toLowerCase() + const words = l.split(/[\s_.\-]+/).filter(Boolean) + return { t, l, loose: stripSep(l), words, initials: words.map((w) => w[0]).join('') } + } + const _loweredRegular = $derived(regularTables.map(prep)) + const _loweredViews = $derived(viewTables.map(prep)) + const _loweredMatViews = $derived(matViewTables.map(prep)) + + /** + * Subsequence check with a tightness bonus: returns -1 if `q`'s chars don't all + * appear in order in `text`, otherwise a score that's higher when the matched + * chars are closer together (fewer gaps) and the first match is earlier. + * @param {string} text @param {string} q (both lowercased, separator-stripped) + */ + function subseqScore(text, q) { + let ti = 0, qi = 0, gaps = 0, first = -1, last = -1 + while (ti < text.length && qi < q.length) { + if (text[ti] === q[qi]) { + if (first === -1) first = ti + if (last >= 0) gaps += ti - last - 1 + last = ti + qi++ + } + ti++ + } + if (qi < q.length) return -1 + return Math.max(0, 80 - gaps - first) + } /** - * Substring score against an already-lowercased name: exact > starts-with > contains. - * @param {string} nLower @param {string} q (already trimmed + lowercased) + * Intuitive relevance score, separator-insensitive. Tiers (high→low): + * exact, loose-exact, prefix, loose-prefix, word-prefix, acronym, substring, + * loose-substring, fuzzy subsequence. 0 = no match. + * @param {{ l: string, loose: string, words: string[], initials: string }} x + * @param {string} q lowercased query @param {string} qLoose separator-stripped query */ - function scoreLower(nLower, q) { - if (nLower === q) return 1000 - if (nLower.startsWith(q)) return 900 - const sub = nLower.indexOf(q) - return sub !== -1 ? 800 - sub : 0 + function scoreName(x, q, qLoose) { + if (x.l === q) return 1000 + if (x.loose === qLoose) return 980 + if (x.l.startsWith(q)) return 940 - Math.min(x.l.length - q.length, 60) + if (x.loose.startsWith(qLoose)) return 900 - Math.min(x.loose.length - qLoose.length, 60) + for (const w of x.words) if (w.startsWith(q)) return 860 + if (qLoose.length >= 2) { + if (x.initials.startsWith(qLoose)) return 840 + if (x.initials.includes(qLoose)) return 800 + } + const sub = x.l.indexOf(q) + if (sub !== -1) return 760 - Math.min(sub, 60) + const lsub = x.loose.indexOf(qLoose) + if (lsub !== -1) return 700 - Math.min(lsub, 60) + const ss = subseqScore(x.loose, qLoose) + return ss >= 0 ? 400 + ss : 0 } - /** @param {{ t: { name: string }, l: string }[]} lowered */ - function filterAndCap(lowered) { + /** @param {ReturnType[]} prepped */ + function filterAndCap(prepped) { const q = paletteSearch.trim().toLowerCase() - if (!q) return { items: lowered.slice(0, TABLES_PAGE_CAP).map((x) => x.t), total: lowered.length } - /** @type {{ t: { name: string }, s: number }[]} */ + if (!q) return { items: prepped.slice(0, TABLES_PAGE_CAP).map((x) => x.t), total: prepped.length } + const qLoose = stripSep(q) + /** @type {{ t: { name: string }, s: number, len: number }[]} */ const scored = [] - for (const x of lowered) { - const s = scoreLower(x.l, q) - if (s > 0) scored.push({ t: x.t, s }) + for (const x of prepped) { + const s = scoreName(x, q, qLoose) + if (s > 0) scored.push({ t: x.t, s, len: x.l.length }) } - scored.sort((a, b) => b.s - a.s) + // Higher score first; ties broken by shorter name (more relevant) then A–Z. + scored.sort((a, b) => b.s - a.s || a.len - b.len || (a.t.name < b.t.name ? -1 : 1)) return { items: scored.slice(0, TABLES_PAGE_CAP).map((x) => x.t), total: scored.length } } @@ -192,7 +241,10 @@ import Search from '@lucide/svelte/icons/search' /** @type {(value: string, search: string) => number} */ const commandFilter = (value, search) => { if (!search) return 1 - return value.toLowerCase().includes(search.toLowerCase()) ? 1 : 0 + const v = value.toLowerCase(), s = search.toLowerCase() + if (v.includes(s)) return 1 + // Separator-insensitive fallback so "newtable"/"new-table" match "new table". + return stripSep(v).includes(stripSep(s)) ? 1 : 0 } /** @param {() => void} action */ diff --git a/src/lib/components/ConnectionModal.svelte b/src/lib/components/ConnectionModal.svelte index 5720d667..1979d805 100644 --- a/src/lib/components/ConnectionModal.svelte +++ b/src/lib/components/ConnectionModal.svelte @@ -17,6 +17,7 @@ import Server from '@lucide/svelte/icons/server' import FolderOpen from '@lucide/svelte/icons/folder-open' import Terminal from '@lucide/svelte/icons/terminal' + import Lock from '@lucide/svelte/icons/lock' import ChevronDown from '@lucide/svelte/icons/chevron-down' import Check from '@lucide/svelte/icons/check' import CloudflareLogin from './CloudflareLogin.svelte' @@ -139,6 +140,11 @@ let connectionUri = $state('') let uriHint = $state('') + // ── Connection options ─────────────────────────────────────────────────────── + /** @type {'prod' | 'staging' | 'dev' | null} */ + let environment = $state(null) + let readOnly = $state(false) + // ── SSH tunnel state ───────────────────────────────────────────────────────── let sshEnabled = $state(false) let sshHost = $state('') @@ -216,6 +222,8 @@ const s = conn.ssh sshEnabled = !!s?.host; sshHost = s?.host ?? ''; sshPort = String(s?.port ?? 22) sshUsername = s?.username ?? ''; sshKeyPath = s?.privateKeyPath ?? '' + readOnly = conn.readOnly ?? false + environment = conn.environment ?? null } else { dbType = 'postgres'; name = ''; host = '127.0.0.1'; port = '5432' database = 'postgres'; user = 'postgres'; password = ''; ssl = false; secure = false @@ -223,6 +231,8 @@ filePath = ''; accountId = ''; databaseId = ''; apiToken = '' libsqlUrl = ''; libsqlToken = '' sshEnabled = false; sshHost = ''; sshPort = '22'; sshUsername = ''; sshKeyPath = '' + readOnly = false + environment = null } error = ''; testOk = false; connectionUri = ''; uriHint = '' d1Reset() @@ -354,6 +364,8 @@ id, ...payload, port: hasHostPort ? (Number(payload.port) || defaultPort) : undefined, lastConnectedAt: Date.now(), + readOnly: readOnly || undefined, + environment: environment || undefined, } saved = upsertConnection(saved_conn).sort((a, b) => (b.lastConnectedAt ?? 0) - (a.lastConnectedAt ?? 0)) setLastConnectionId(id) @@ -956,6 +968,40 @@
+ +
+

Environment

+
+ {#each /** @type {Array<{id: 'prod'|'staging'|'dev', label: string, cls: string}>} */ ([ + { id: 'prod', label: 'Production', cls: 'border-red-500/40 bg-red-500/10 text-red-500' }, + { id: 'staging', label: 'Staging', cls: 'border-amber-500/40 bg-amber-500/10 text-amber-500' }, + { id: 'dev', label: 'Dev', cls: 'border-emerald-500/40 bg-emerald-500/10 text-emerald-500' }, + ]) as env (env.id)} + + {/each} +
+
+ + +
+ +
+
{#if error} diff --git a/src/lib/components/CreateSequenceDialog.svelte b/src/lib/components/CreateSequenceDialog.svelte index 0b6f8a41..c3d57e30 100644 --- a/src/lib/components/CreateSequenceDialog.svelte +++ b/src/lib/components/CreateSequenceDialog.svelte @@ -61,7 +61,7 @@ await executeSql(sql) toast.success(`Sequence "${name.trim()}" created`) onrefresh(); reset(); open = false - } catch (e) { toast.error(String(e)) + } catch (e) { toast.error('Could not create sequence', { description: String(e) }) } finally { saving = false; confirmOpen = false } } diff --git a/src/lib/components/CreateTableDialog.svelte b/src/lib/components/CreateTableDialog.svelte index 9bec45dd..ac32655f 100644 --- a/src/lib/components/CreateTableDialog.svelte +++ b/src/lib/components/CreateTableDialog.svelte @@ -131,7 +131,7 @@ oncreated(tableName.trim()) open = false } catch (err) { - toast.error('Failed to create table', { description: String(err) }) + toast.error('Could not create table', { description: String(err) }) } finally { submitting = false } diff --git a/src/lib/components/CreateTriggerDialog.svelte b/src/lib/components/CreateTriggerDialog.svelte index c90c1a8c..1821f3ee 100644 --- a/src/lib/components/CreateTriggerDialog.svelte +++ b/src/lib/components/CreateTriggerDialog.svelte @@ -70,7 +70,7 @@ await executeSql(sql) toast.success(`Trigger "${name.trim()}" created`) onrefresh(); reset(); open = false - } catch (e) { toast.error(String(e)) + } catch (e) { toast.error('Could not create trigger', { description: String(e) }) } finally { saving = false; confirmOpen = false } } diff --git a/src/lib/components/DataTable.svelte b/src/lib/components/DataTable.svelte index 6f85c117..1915394c 100644 --- a/src/lib/components/DataTable.svelte +++ b/src/lib/components/DataTable.svelte @@ -23,6 +23,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; import ChevronDown from "@lucide/svelte/icons/chevron-down"; import ChevronsDownUp from "@lucide/svelte/icons/chevrons-down-up"; import Copy from "@lucide/svelte/icons/copy"; + import CopyPlus from "@lucide/svelte/icons/copy-plus"; import Pencil from "@lucide/svelte/icons/pencil"; import CircleSlash from "@lucide/svelte/icons/circle-slash"; import Trash2 from "@lucide/svelte/icons/trash-2"; @@ -211,6 +212,8 @@ import FilterX from "@lucide/svelte/icons/filter-x"; loadingMore = false, /** Called when the user scrolls near the bottom in infinite scroll mode. */ onloadmore = /** @type {() => void} */ (() => {}), + /** True when every row has been loaded in infinite scroll mode (no more pages). */ + endOfResults = false, } = $props(); /** @@ -844,7 +847,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; if (afterAction) navigateAfterEdit(rowIdx, colIdx, afterAction); else tick().then(() => tableContainer?.focus({ preventScroll: true })); } catch (err) { - toast.error("Save failed", { description: String(err) }); + toast.error("Could not save", { description: String(err) }); } } @@ -861,7 +864,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; okCount++; } catch (err) { failed.push(edit); - toast.error("Save failed", { description: String(err) }); + toast.error("Could not save", { description: String(err) }); } } // Keep only the edits that failed so the user can retry / reset them. @@ -945,9 +948,13 @@ import FilterX from "@lucide/svelte/icons/filter-x"; toast.error('Cannot insert row', { description: built.message }) return } - await oninsertrow(/** @type {Record} */ (built.values)) - newRowDrafts = null - newRowFocusCol = null + try { + await oninsertrow(/** @type {Record} */ (built.values)) + newRowDrafts = null + newRowFocusCol = null + } catch { + // error toast already shown by oninsertrow + } } /** @param {string} colName @param {string} value */ @@ -1149,7 +1156,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; description: out.length > 120 ? out.slice(0, 120) + "…" : out, }); } catch (e) { - toast.error("Transform failed", { description: String(e?.message ?? e) }); + toast.error("Could not apply transform", { description: String(e?.message ?? e) }); } } @@ -1188,7 +1195,21 @@ import FilterX from "@lucide/svelte/icons/filter-x"; n === 1 ? "Row deleted" : `${formatCompactCount(n)} rows deleted`, ); } catch (err) { - toast.error("Delete failed", { description: String(err) }); + toast.error("Could not delete", { description: String(err) }); + } + } + + /** @param {number} rowIdx */ + async function duplicateRow(rowIdx) { + if (readonly) return; + const row = rows[rowIdx]; + if (!row) return; + const record = rowToRecord(columns, row); + for (const pk of primaryKey) delete record[pk]; + try { + await oninsertrow(record); + } catch { + // error toast already shown by oninsertrow } } @@ -1466,6 +1487,25 @@ import FilterX from "@lucide/svelte/icons/filter-x"; (showRowExpand ? 1 : 0) + (showSelection ? 1 : 0) + visibleColumns.length + 1, ) const navigableColumns = $derived(visibleColumns) + + // ── Accessibility: focused-cell announcement ──────────────────────────────── + // The canvas grid has no per-cell DOM, so screen readers get nothing on + // navigation. This derived builds a short description of the focused cell and + // is rendered into an aria-live region. It depends ONLY on focus/edit state and + // the data — NOT on scroll offsets — so it never recomputes during the rAF draw + // loop and cannot affect render throughput. + const a11yCellAnnouncement = $derived.by(() => { + if (focusedRow === null || focusedCol === null) return '' + const ai = visToActualColIdx(focusedCol) + if (ai < 0) return '' + const col = columns[ai] + const row = rows[focusedRow] + if (!col || !row) return '' + const raw = formatCell(row[ai]) + const val = raw.length > 80 ? raw.slice(0, 80) + '…' : raw + const editing = editingCell && editingCell.rowIdx === focusedRow && editingCell.colIdx === ai + return `Row ${focusedRow + 1} of ${rows.length}, ${col.name}: ${val}${editing ? ', editing' : ''}` + }) /** Map of pinned column name → sticky left offset in px. Gutters are not * sticky, so pinned columns stick from the left edge (0). */ const pinnedOffsets = $derived.by(() => { @@ -1881,28 +1921,42 @@ import FilterX from "@lucide/svelte/icons/filter-x"; }) /** @param {Event & { currentTarget: HTMLElement }} e */ + // Continuous rAF loop that drives canvas redraws during scroll. + // Reading scrollTop/scrollLeft inside rAF gives the compositor-synchronized + // position for the frame being painted, eliminating the 1-frame lag that + // a one-shot scheduleDraw() produces (queued from onscroll → fires next frame). + // The loop runs while the user is scrolling and for 200ms after the last + // scroll event to cover momentum/inertia, then stops to save GPU time. + let _scrollLoopId = 0 + let _scrollLoopDeadline = 0 + + function startScrollLoop() { + _scrollLoopDeadline = performance.now() + 200 + if (_scrollLoopId) return + function loop() { + const el = tableContainer + if (!el || !_ctx || performance.now() > _scrollLoopDeadline) { + _scrollLoopId = 0 + return + } + _scrollTop = el.scrollTop + _scrollLeft = el.scrollLeft + draw() + _scrollLoopId = requestAnimationFrame(loop) + } + _scrollLoopId = requestAnimationFrame(loop) + } + function onContainerScroll(e) { const el = e.currentTarget - // Page/layout scroll can shift the canvas on screen — drop the cached rect. invalidateCanvasRect() - const hScrolled = el.scrollLeft !== _scrollLeft - if (el.scrollTop !== _scrollTop) _scrollTop = el.scrollTop - if (hScrolled) _scrollLeft = el.scrollLeft - // For horizontal scroll, draw synchronously — the sticky canvas shows stale - // column positions for a full frame when deferred via rAF, which the eye - // reads as a column shift. Vertical scroll is imperceptible at 1-frame lag - // because adjacent rows look similar, so it stays on the rAF path. - // Re-arm a cleanup rAF so any concurrent reactive updates still get redrawn. - if (_ctx && (editingCell || hScrolled)) { - if (_drawRafId) cancelAnimationFrame(_drawRafId) - draw() - _drawRafId = requestAnimationFrame(() => { _drawRafId = 0 }) - } else { - // Repaint directly from the scroll handler. The big layout effect no longer - // tracks _scrollTop/_scrollLeft, so scrolling skips syncCanvasSurface() - // (style writes + getContext + setTransform) and only does the rAF draw. - scheduleDraw() - } + // Update state immediately so any synchronous consumers (hit-test etc.) are current. + _scrollTop = el.scrollTop + _scrollLeft = el.scrollLeft + // Cancel any pending one-shot draw — the loop handles all scroll redraws at + // the display's native frame rate (120Hz on ProMotion). + if (_drawRafId) { cancelAnimationFrame(_drawRafId); _drawRafId = 0 } + startScrollLoop() // Infinite scroll — trigger load when within 3 rows of the bottom if (infiniteScroll && !loadingMore) { const threshold = ROW_HEIGHT * 3 @@ -2322,11 +2376,14 @@ import FilterX from "@lucide/svelte/icons/filter-x"; ctx.fillRect(0, ry, c.usedW, rh) } - // Non-pinned cells. + // Non-pinned cells. geom.cols is ordered by ascending contentX, so once a + // column starts past the right viewport edge every later one does too — break + // instead of iterating the off-screen tail (matters for very wide tables). for (const col of geom.cols) { if (col.pinned) continue const dx = col.contentX - _scrollLeft - if (dx + col.w <= 0 || dx >= _viewportWidth) continue + if (dx >= _viewportWidth) break + if (dx + col.w <= 0) continue drawCell(ctx, idx, col, dx, ry, rh, c) } @@ -2428,10 +2485,12 @@ import FilterX from "@lucide/svelte/icons/filter-x"; ctx.lineWidth = 1 ctx.beginPath() // Non-pinned column separators (skip ones hidden behind the frozen region). + // Same ascending-contentX ordering → break past the right edge. for (const col of geom.cols) { if (col.pinned) continue const dx = col.contentX - _scrollLeft - if (dx + col.w <= 0 || dx >= vw) continue + if (dx >= vw) break + if (dx + col.w <= 0) continue const ex = dx + col.w - 0.5 if (ex <= frozenW) continue ctx.moveTo(ex, ry); ctx.lineTo(ex, ry + rh) @@ -2673,11 +2732,12 @@ import FilterX from "@lucide/svelte/icons/filter-x"; ctx.fillStyle = withAlpha(c.cMutedBg, 0.38) ctx.fillRect(0, 0, c.W, HEADER_H) - // Non-pinned headers. + // Non-pinned headers. Ordered by ascending contentX → break past the right edge. for (const col of geom.cols) { if (col.pinned) continue const dx = col.contentX - _scrollLeft - if (dx + col.w <= 0 || dx >= c.W) continue + if (dx >= c.W) break + if (dx + col.w <= 0) continue drawHeaderCell(ctx, col, dx, c) } @@ -2944,6 +3004,26 @@ import FilterX from "@lucide/svelte/icons/filter-x"; onDestroy(() => { if (_drawRafId) cancelAnimationFrame(_drawRafId) if (_resizeRafId) cancelAnimationFrame(_resizeRafId) + if (_scrollLoopId) cancelAnimationFrame(_scrollLoopId) + }) + + // Shift+wheel → horizontal scroll. Non-passive so we can call preventDefault, + // but bails out immediately on non-Shift events so the compositor waits <0.05ms. + // Registered via $effect (not onwheel attribute) to keep the Svelte template + // free of any non-passive wheel binding, which would otherwise force the + // compositor to consult JS on every 120Hz trackpad tick. + $effect(() => { + const el = tableContainer + if (!el) return + const onShiftWheel = (/** @type {WheelEvent} */ e) => { + if (!e.shiftKey) return + if (e.deltaY || e.deltaX) { + e.preventDefault() + el.scrollLeft += e.deltaY || e.deltaX + } + } + el.addEventListener('wheel', onShiftWheel, { passive: false }) + return () => el.removeEventListener('wheel', onShiftWheel) }) // Layout / sizing effect — resize the backing store when geometry or viewport changes. @@ -3419,6 +3499,10 @@ import FilterX from "@lucide/svelte/icons/filter-x"; data-canvas-table="" {...props} tabindex={-1} + role="grid" + aria-label={`${tableName || 'Data'} table, ${rows.length} ${rows.length === 1 ? 'row' : 'rows'}`} + aria-rowcount={rows.length} + aria-colcount={navigableColumns.length} class={cn( "app-scroll relative overflow-auto bg-panel select-none outline-none [scrollbar-gutter:stable] [contain:layout] [overflow-anchor:none]", embedded ? "max-h-80" : "min-h-0 flex-1", @@ -3427,19 +3511,6 @@ import FilterX from "@lucide/svelte/icons/filter-x"; oncontextmenu={(e) => onCanvasContextMenu(e, bitsContextMenu)} onscroll={onContainerScroll} onkeydown={handleTableKeydown} - onwheel={(e) => { - // Shift+wheel → horizontal scroll (maps a mouse wheel's vertical - // delta onto the X axis). Everything else — vertical, trackpad, - // diagonal — is left to the browser so macOS momentum/inertia and - // edge overscroll-chaining to the parent stay buttery smooth. - if (e.shiftKey) { - const tc = tableContainer - if (tc && (e.deltaY || e.deltaX)) { - e.preventDefault() - tc.scrollLeft += e.deltaY || e.deltaX - } - } - }} onfocusin={() => { isTableFocused = true; }} onfocusout={(e) => { if (!tableContainer?.contains(e.relatedTarget instanceof Element ? e.relatedTarget : null)) { @@ -3456,14 +3527,24 @@ import FilterX from "@lucide/svelte/icons/filter-x"; style="position:absolute;top:0;left:0;width:0;height:0;overflow:hidden;pointer-events:none" > + +
{a11yCellAnnouncement}
+ + -
+
+ {:else if infiniteScroll && endOfResults && rows.length > 0} + +
+
+ + End of results — {rows.length.toLocaleString()} {rows.length === 1 ? 'row' : 'rows'} + +
+
{/if}
@@ -3854,8 +3945,10 @@ import FilterX from "@lucide/svelte/icons/filter-x"; Open - {#if menuForeignKey && !menuCellNull} + {#if menuForeignKey} runMenuAction(() => onfollowforeignkey({ @@ -3865,8 +3958,8 @@ import FilterX from "@lucide/svelte/icons/filter-x"; )} > - Open Tab - ⌘↵ + {menuCellNull ? 'Open Tab — value is NULL' : 'Open Tab'} + {#if !menuCellNull}⌘↵{/if} {/if} @@ -3976,6 +4069,13 @@ import FilterX from "@lucide/svelte/icons/filter-x"; {selected.has(contextRowIdx) ? "Deselect row" : "Select row"} + runMenuAction(() => duplicateRow(contextRowIdx))} + > + + Duplicate row + - + {#if data?.loading}
- Loading… + Loading related rows…
{:else if data?.error} -
{data.error}
+
+ +
+
Couldn't load related rows
+
{data.error}
+
+
{:else if !rowCount} -
No rows found.
+
+ + No related rows +
{:else}
+ + {#if !activeSupported} + {@render unsupported(activeFeature.label, activeFeature.key)} + - {#if activeType === 'indexes'} + {:else if activeType === 'indexes'} {#if indexes.length === 0} {@render emptyState(Zap, 'No indexes', 'Indexes in this schema will appear here')} {:else if filteredIndexes.length === 0} @@ -500,6 +522,16 @@

No {type} match "{q}"

{/snippet} +{#snippet unsupported(label, key)} +
+ +
+

Not available on this database

+

{unsupportedReason(label, key)}

+
+
+{/snippet} + { if (!open) search = ""; }); function handleSelect(/** @type {any} */ it) { if (it?.disabled) return; + // cmdk re-selects the first item on the items-changed re-render and scrolls + // it into view, which jerks the list back to the top after a non-closing + // toggle (e.g. show/hide columns). Capture the scroll position and restore it + // so the user stays exactly where they were. + const prevTop = listEl?.scrollTop ?? 0; onselect(it); if (closeOnSelect) { open = false; } else { // Refocus the search input after a non-closing select so cmdk's keyboard // selection cursor returns to the input and clears the item highlight. - requestAnimationFrame(() => inputEl?.focus()); + requestAnimationFrame(() => { + inputEl?.focus(); + if (listEl && listEl.scrollTop !== prevTop) listEl.scrollTop = prevTop; + }); } } @@ -111,7 +121,7 @@
{@render header?.()} - + {empty} {#each items as it (it.value)} { + if (!supported) return; if (activeTab === "roles" && roles === null && !rolesLoading) loadRoles(); else if (activeTab === "policies" && policies === null && !policiesLoading) loadPolicies(); @@ -177,9 +184,11 @@ const bool = (v) => v === true || v === "t" || v === "true" || v === 1; const isLoading = $derived( - (activeTab === "roles" && (rolesLoading || roles === null)) || + supported && ( + (activeTab === "roles" && (rolesLoading || roles === null)) || (activeTab === "policies" && (policiesLoading || policies === null)) || - (activeTab === "rls" && (rlsLoading || rlsTables === null)), + (activeTab === "rls" && (rlsLoading || rlsTables === null)) + ) ); const TABS = [ @@ -200,6 +209,22 @@ />
+ {#if !supported} + {@const engineLabel = { + mysql: 'MySQL', mariadb: 'MariaDB', sqlite: 'SQLite', d1: 'Cloudflare D1', + libsql: 'LibSQL', clickhouse: 'ClickHouse', duckdb: 'DuckDB', mssql: 'SQL Server', + }[connectionType ?? ''] ?? (connectionType ?? 'This engine')} +
+ +
+

{engineLabel} does not support roles or RLS

+

+ Row Level Security and role management require PostgreSQL or CockroachDB.
+ Use the SQL console to manage {engineLabel} users and permissions directly. +

+
+
+ {:else}
{#each TABS as tab (tab.id)} @@ -670,6 +695,7 @@ {/if} {/if}
+ {/if}
{#if sqlModal} diff --git a/src/lib/components/SqlConsole.svelte b/src/lib/components/SqlConsole.svelte index 2d8f126f..68720af2 100644 --- a/src/lib/components/SqlConsole.svelte +++ b/src/lib/components/SqlConsole.svelte @@ -1,5 +1,6 @@ @@ -20,6 +40,7 @@ {/if} -
+
@@ -128,6 +128,15 @@ {t.description}
{/if} + {#if t.action} + + {/if}