Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(pam): in-browser data explorer for postgres (#5786)
Saif Ur Rahmandb7750ee1db8
diff --git a/backend/package-lock.json b/backend/package-lock.jsonindex f8b9720957..48604a1c09 100644--- a/backend/package-lock.json+++ b/backend/package-lock.json@@ -1842,6 +1842,7 @@"resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.637.0.tgz","integrity": "sha512-xUi7x4qDubtA8QREtlblPuAcn91GS/09YVEY/RwU7xCY0aqGuFwgszAANlha4OUIqva8oVj2WO4gJuG+iaSnhw==","license": "Apache-2.0",+ "peer": true,"dependencies": {"@aws-crypto/sha256-browser": "5.2.0","@aws-crypto/sha256-js": "5.2.0",@@ -5649,6 +5650,7 @@"version": "3.632.0","resolved": "https://registry.npmjs.org/@aws-sdk/client-sso-oidc/-/client-sso-oidc-3.632.0.tgz","integrity": "sha512-Oh1fIWaoZluihOCb/zDEpRTi+6an82fgJz7fyRBugyLhEtDjmvpCQ3oKjzaOhoN+4EvXAm1ZS/ZgpvXBlIRTgw==",+ "peer": true,"dependencies": {"@aws-crypto/sha256-browser": "5.2.0","@aws-crypto/sha256-js": "5.2.0",@@ -5725,6 +5727,7 @@"version": "3.632.0","resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.632.0.tgz","integrity": "sha512-Ss5cBH09icpTvT+jtGGuQlRdwtO7RyE9BF4ZV/CEPATdd9whtJt4Qxdya8BUnkWR7h5HHTrQHqai3YVYjku41A==",+ "peer": true,"dependencies": {"@aws-crypto/sha256-browser": "5.2.0","@aws-crypto/sha256-js": "5.2.0",@@ -10028,6 +10031,7 @@"integrity": "sha512-vMqyb7XCDMPvJFFOaT9kxtiRh42GwlZEg1/uIgtZshS5a/8OaduUfCi7kynKgc3Tw/6Uo2D+db9qBttghhmxwQ==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@ampproject/remapping": "^2.2.0","@babel/code-frame": "^7.26.2",@@ -12077,6 +12081,7 @@"url": "https://opencollective.com/csstools"}],+ "peer": true,"engines": {"node": ">=18"},@@ -12098,6 +12103,7 @@"url": "https://opencollective.com/csstools"}],+ "peer": true,"engines": {"node": ">=18"}@@ -14751,6 +14757,7 @@"resolved": "https://registry.npmjs.org/zod/-/zod-4.1.13.tgz","integrity": "sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig==","license": "MIT",+ "peer": true,"funding": {"url": "https://github.com/sponsors/colinhacks"}@@ -15463,6 +15470,7 @@"resolved": "https://registry.npmjs.org/@octokit/core/-/core-5.2.1.tgz","integrity": "sha512-dKYCMuPO1bmrpuogcjQ8z7ICCH3FP6WmxpwC03yjzGfZhj9fTJg6+bS1+UAplekbN2C+M61UNllGOOoAfGCrdQ==","license": "MIT",+ "peer": true,"dependencies": {"@octokit/auth-token": "^4.0.0","@octokit/graphql": "^7.1.0",@@ -15906,6 +15914,7 @@"version": "1.9.0","resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz","integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==",+ "peer": true,"engines": {"node": ">=8.0.0"}@@ -16569,6 +16578,7 @@"resolved": "https://registry.npmjs.org/@react-email/body/-/body-0.2.0.tgz","integrity": "sha512-9GCWmVmKUAoRfloboCd+RKm6X17xn7eGL7HnpAZUnjBXBilWCxsKnLMTC/ixSHDKS/A/057M1Tx6ZUXd89sVBw==","license": "MIT",+ "peer": true,"peerDependencies": {"react": "^18.0 || ^19.0 || ^19.0.0-rc"}@@ -16578,6 +16588,7 @@"resolved": "https://registry.npmjs.org/@react-email/button/-/button-0.2.0.tgz","integrity": "sha512-8i+v6cMxr2emz4ihCrRiYJPp2/sdYsNNsBzXStlcA+/B9Umpm5Jj3WJKYpgTPM+aeyiqlG/MMI1AucnBm4f1oQ==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -16590,6 +16601,7 @@"resolved": "https://registry.npmjs.org/@react-email/code-block/-/code-block-0.2.0.tgz","integrity": "sha512-eIrPW9PIFgDopQU0e/OPpwCW2QWQDtNZDSsiN4sJO8KdMnWWnXJicnRfzrit5rHwFo+Y98i+w/Y5ScnBAFr1dQ==","license": "MIT",+ "peer": true,"dependencies": {"prismjs": "^1.30.0"},@@ -16605,6 +16617,7 @@"resolved": "https://registry.npmjs.org/@react-email/code-inline/-/code-inline-0.0.5.tgz","integrity": "sha512-MmAsOzdJpzsnY2cZoPHFPk6uDO/Ncpb4Kh1hAt9UZc1xOW3fIzpe1Pi9y9p6wwUmpaeeDalJxAxH6/fnTquinA==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -16680,6 +16693,7 @@"resolved": "https://registry.npmjs.org/@react-email/container/-/container-0.0.15.tgz","integrity": "sha512-Qo2IQo0ru2kZq47REmHW3iXjAQaKu4tpeq/M8m1zHIVwKduL2vYOBQWbC2oDnMtWPmkBjej6XxgtZByxM6cCFg==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -16713,6 +16727,7 @@"resolved": "https://registry.npmjs.org/@react-email/heading/-/heading-0.0.15.tgz","integrity": "sha512-xF2GqsvBrp/HbRHWEfOgSfRFX+Q8I5KBEIG5+Lv3Vb2R/NYr0s8A5JhHHGf2pWBMJdbP4B2WHgj/VUrhy8dkIg==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -16725,6 +16740,7 @@"resolved": "https://registry.npmjs.org/@react-email/hr/-/hr-0.0.11.tgz","integrity": "sha512-S1gZHVhwOsd1Iad5IFhpfICwNPMGPJidG/Uysy1AwmspyoAP5a4Iw3OWEpINFdgh9MHladbxcLKO2AJO+cA9Lw==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -16749,6 +16765,7 @@"resolved": "https://registry.npmjs.org/@react-email/img/-/img-0.0.11.tgz","integrity": "sha512-aGc8Y6U5C3igoMaqAJKsCpkbm1XjguQ09Acd+YcTKwjnC2+0w3yGUJkjWB2vTx4tN8dCqQCXO8FmdJpMfOA9EQ==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -16761,6 +16778,7 @@"resolved": "https://registry.npmjs.org/@react-email/link/-/link-0.0.12.tgz","integrity": "sha512-vF+xxQk2fGS1CN7UPQDbzvcBGfffr+GjTPNiWM38fhBfsLv6A/YUfaqxWlmL7zLzVmo0K2cvvV9wxlSyNba1aQ==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -16788,6 +16806,7 @@"resolved": "https://registry.npmjs.org/@react-email/preview/-/preview-0.0.13.tgz","integrity": "sha512-F7j9FJ0JN/A4d7yr+aw28p4uX7VLWs7hTHtLo7WRyw4G+Lit6Zucq4UWKRxJC8lpsUdzVmG7aBJnKOT+urqs/w==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -16892,6 +16911,7 @@"resolved": "https://registry.npmjs.org/@react-email/text/-/text-0.1.5.tgz","integrity": "sha512-o5PNHFSE085VMXayxH+SJ1LSOtGsTv+RpNKnTiJDrJUwoBu77G3PlKOsZZQHCNyD28WsQpl9v2WcJLbQudqwPg==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -19033,6 +19053,7 @@"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.23.tgz","integrity": "sha512-yIdlVVVHXpmqRhtyovZAcSy0MiPcYWGkoO4CGe/+jpP0hmNuihm4XhHbADpK++MsiLHP5MVlv+bcgdF99kSiFQ==","license": "MIT",+ "peer": true,"dependencies": {"undici-types": "~6.21.0"}@@ -19523,6 +19544,7 @@"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.20.0.tgz","integrity": "sha512-bYerPDF/H5v6V76MdMYhjwmwgMA+jlPVqjSDq2cRqMi8bP5sR3Z+RLOiOMad3nsnmDVmn2gAFCyNgh/dIrfP/w==","dev": true,+ "peer": true,"dependencies": {"@typescript-eslint/scope-manager": "6.20.0","@typescript-eslint/types": "6.20.0",@@ -19981,6 +20003,7 @@"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz","integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==","license": "MIT",+ "peer": true,"bin": {"acorn": "bin/acorn"},@@ -20469,6 +20492,7 @@"resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz","integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==","license": "MIT",+ "peer": true,"dependencies": {"bn.js": "^4.0.0","inherits": "^2.0.1",@@ -20690,6 +20714,7 @@"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz","integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==","license": "MIT",+ "peer": true,"dependencies": {"follow-redirects": "^1.15.6","form-data": "^4.0.4",@@ -21289,6 +21314,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"baseline-browser-mapping": "^2.8.9","caniuse-lite": "^1.0.30001746",@@ -22718,6 +22744,7 @@"version": "16.4.1","resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.1.tgz","integrity": "sha512-CjA3y+Dr3FyFDOAMnxZEGtnW9KBR2M0JvvUtXNW+dYJL5ROWxP9DUHCwgFqpMk0OXCc0ljhaNTr2w/kutYIcHQ==",+ "peer": true,"engines": {"node": ">=12"},@@ -23104,6 +23131,7 @@"dev": true,"hasInstallScript": true,"license": "MIT",+ "peer": true,"bin": {"esbuild": "bin/esbuild"},@@ -23186,6 +23214,7 @@"resolved": "https://registry.npmjs.org/eslint/-/eslint-8.56.0.tgz","integrity": "sha512-Go19xM6T9puCOWntie1/P997aXxFsOi37JIHRWI514Hc6ZnaHGKY9xFhrU65RT6CcBEzZoGG1e6Nq+DT04ZtZQ==","dev": true,+ "peer": true,"dependencies": {"@eslint-community/eslint-utils": "^4.2.0","@eslint-community/regexpp": "^4.6.1",@@ -23284,6 +23313,7 @@"resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz","integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==","dev": true,+ "peer": true,"bin": {"eslint-config-prettier": "bin/cli.js"},@@ -23372,6 +23402,7 @@"resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.29.1.tgz","integrity": "sha512-BbPC0cuExzhiMo4Ff1BTVwHpjjv28C5R+btTOGaCRC7UEz801up0JadwkeSk5Ued6TG34uaczuVuH6qyy5YUxw==","dev": true,+ "peer": true,"dependencies": {"array-includes": "^3.1.7","array.prototype.findlastindex": "^1.2.3",@@ -23783,6 +23814,7 @@"resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz","integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==","license": "MIT",+ "peer": true,"dependencies": {"accepts": "~1.3.8","array-flatten": "1.1.1",@@ -23844,7 +23876,6 @@"resolved": "https://registry.npmjs.org/express-session/-/express-session-1.18.1.tgz","integrity": "sha512-a5mtTqEaZvBCL9A9aqkrtfz+3SMDhOVUnjafjo+s7A9Txkq+SVX2DLvSp1Zrv4uCXa3lMSK3viWnh9Gg07PBUA==","license": "MIT",- "peer": true,"dependencies": {"cookie": "0.7.2","cookie-signature": "1.0.7",@@ -23862,14 +23893,12 @@"node_modules/express-session/node_modules/cookie-signature": {"version": "1.0.7","resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",- "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",- "peer": true+ "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA=="},"node_modules/express-session/node_modules/debug": {"version": "2.6.9","resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz","integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",- "peer": true,"dependencies": {"ms": "2.0.0"}@@ -23877,8 +23906,7 @@"node_modules/express-session/node_modules/ms": {"version": "2.0.0","resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",- "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",- "peer": true+ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="},"node_modules/express/node_modules/cookie": {"version": "0.7.1",@@ -28722,7 +28750,6 @@"version": "1.0.2","resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz","integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==",- "peer": true,"engines": {"node": ">= 0.8"}@@ -29409,6 +29436,7 @@"version": "3.0.1","resolved": "https://registry.npmjs.org/picomatch/-/picomatch-3.0.1.tgz","integrity": "sha512-I3EurrIQMlRc9IaAZnqRR044Phh2DXY+55o7uJ0V+hYZAcQYSuFWsc9q5PvyDHUSCe1Qxn/iBz+78s86zWnGag==",+ "peer": true,"engines": {"node": ">=10"},@@ -29751,6 +29779,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"nanoid": "^3.3.11","picocolors": "^1.1.1",@@ -29848,6 +29877,7 @@"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.5.3.tgz","integrity": "sha512-QQtaxnoDJeAkDvDKWCLiwIXkTgRhwYDEQCghU9Z6q03iyek/rxRh/2lC3HB7P8sWT2xC/y5JDctPLBIGzHKbhw==","license": "MIT",+ "peer": true,"bin": {"prettier": "bin/prettier.cjs"},@@ -30282,7 +30312,6 @@"version": "1.0.0","resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz","integrity": "sha512-iv7LhNVO047HzYR3InF6pUcUsPQiHTM1Qal51DcGSuZFBil1aBBWG5eHPNek7bvILMaYJ/8RU1e8w1AMdHmLQQ==",- "peer": true,"engines": {"node": ">= 0.8"}@@ -30354,6 +30383,7 @@"resolved": "https://registry.npmjs.org/react/-/react-19.1.0.tgz","integrity": "sha512-FS+XFBNvn3GTAWq26joslQgWNoFu08F4kl0J4CgdNKADkdSGXQyTCnKteIAJy96Br6YbpEU1LSzV5dYtjMkMDg==","license": "MIT",+ "peer": true,"engines": {"node": ">=0.10.0"}@@ -30363,6 +30393,7 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.1.0.tgz","integrity": "sha512-Xs1hdnE+DyKgeHJeJznQmYMIBG3TKIHJJT95Q58nHLSrElKlGQqDTR2HQ9fx5CN/Gk6Vh/kupBTDLU11/nDk/g==","license": "MIT",+ "peer": true,"dependencies": {"scheduler": "^0.26.0"},@@ -33138,6 +33169,7 @@"resolved": "https://registry.npmjs.org/socks/-/socks-2.8.4.tgz","integrity": "sha512-D3YaD0aRxR3mEcqnidIs7ReYJFVzWdd6fXJYUM8ixcQcJRGTka/b3saV0KflYhyVJXKhb947GndU35SxYNResQ==","license": "MIT",+ "peer": true,"dependencies": {"ip-address": "^9.0.5","smart-buffer": "^4.2.0"@@ -34441,6 +34473,7 @@"integrity": "sha512-ytQKuwgmrrkDTFP4LjR0ToE2nqgy886GpvRSpU0JAnrdBYppuY5rLkRUYPU1yCryb24SsKBTL/hlDQAEFVwtZg==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"esbuild": "~0.25.0","get-tsconfig": "^4.7.5"@@ -34608,6 +34641,7 @@"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.3.2.tgz","integrity": "sha512-6l+RyNy7oAHDfxC4FzSJcz9vnjTKxrLpDG5M2Vu4SHRVNg6xzqZp6LYSR9zjqQTu8DU/f5xwxUdADOkbrIX2gQ==","dev": true,+ "peer": true,"bin": {"tsc": "bin/tsc","tsserver": "bin/tsserver"@@ -34648,7 +34682,6 @@"version": "2.1.5","resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz","integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==",- "peer": true,"dependencies": {"random-bytes": "~1.0.0"},@@ -35236,6 +35269,7 @@"integrity": "sha512-ZWyE8YXEXqJrrSLvYgrRP7p62OziLW7xI5HYGWFzOvupfAlrLvURSzv/FyGyy0eidogEM3ujU+kUG1zuHgb6Ug==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"esbuild": "^0.25.0","fdir": "^6.5.0",@@ -35889,6 +35923,7 @@"resolved": "https://registry.npmjs.org/zod/-/zod-3.24.3.tgz","integrity": "sha512-HhY1oqzWCQWuUqvBFnsyrtZRhyPeR7SUGv+C4+MsisMuVfSPx8HpwWqH8tRahSlt6M3PiFAcoeFhZAqIXTxoSg==","license": "MIT",+ "peer": true,"funding": {"url": "https://github.com/sponsors/colinhacks"}diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-data-explorer-metadata.test.ts b/backend/src/ee/services/pam-web-access/pam-postgres-data-explorer-metadata.test.tsnew file mode 100644index 0000000000..3a133db804--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-postgres-data-explorer-metadata.test.ts@@ -0,0 +1,69 @@+import { describe, expect, test } from "vitest";++import { getSchemasQuery, getTableDetailQuery, getTablesQuery } from "./pam-postgres-data-explorer-metadata";++describe("getSchemasQuery", () => {+ test("returns SQL with no parameters", () => {+ const query = getSchemasQuery();+ expect(query.text).toContain("pg_namespace");+ expect(query.text).toContain("pg_catalog");+ expect(query.text).toContain("information_schema");+ expect(query.values).toEqual([]);+ });++ test("excludes system schemas", () => {+ const query = getSchemasQuery();+ expect(query.text).toContain("pg_toast");+ expect(query.text).toContain("pg_temp_");+ });+});++describe("getTablesQuery", () => {+ test("returns parameterized query for schema", () => {+ const query = getTablesQuery("public");+ expect(query.values).toEqual(["public"]);+ expect(query.text).toContain("$1");+ expect(query.text).toContain("pg_class");+ expect(query.text).toContain("relkind");+ });++ test("includes table type mapping", () => {+ const query = getTablesQuery("myschema");+ expect(query.text).toContain("'table'");+ expect(query.text).toContain("'view'");+ expect(query.text).toContain("'materialized_view'");+ });+});++describe("getTableDetailQuery", () => {+ test("returns parameterized query for schema and table", () => {+ const query = getTableDetailQuery("public", "users");+ expect(query.values).toEqual(["public", "users"]);+ expect(query.text).toContain("$1");+ expect(query.text).toContain("$2");+ });++ test("queries columns from pg_attribute", () => {+ const query = getTableDetailQuery("public", "users");+ expect(query.text).toContain("pg_attribute");+ expect(query.text).toContain("pg_type");+ });++ test("queries primary keys from pg_constraint", () => {+ const query = getTableDetailQuery("public", "users");+ expect(query.text).toContain("contype = 'p'");+ });++ test("queries foreign keys from pg_constraint", () => {+ const query = getTableDetailQuery("public", "users");+ expect(query.text).toContain("contype = 'f'");+ });++ test("returns JSON result", () => {+ const query = getTableDetailQuery("public", "users");+ expect(query.text).toContain("json_build_object");+ expect(query.text).toContain("'columns'");+ expect(query.text).toContain("'primaryKeys'");+ expect(query.text).toContain("'foreignKeys'");+ });+});diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-data-explorer-metadata.ts b/backend/src/ee/services/pam-web-access/pam-postgres-data-explorer-metadata.tsnew file mode 100644index 0000000000..0945dc9dfc--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-postgres-data-explorer-metadata.ts@@ -0,0 +1,128 @@+// System catalog SQL queries for the Postgres Data Explorer.+// All queries use parameterized inputs ($1, $2) — no string interpolation.++export const getSchemasQuery = () => ({+ text: `+ SELECT nspname AS name+ FROM pg_namespace+ WHERE nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')+ AND nspname NOT LIKE 'pg_temp_%'+ AND nspname NOT LIKE 'pg_toast_temp_%'+ ORDER BY nspname+ `,+ values: [] as string[]+});++export const getTablesQuery = (schema: string) => ({+ text: `+ SELECT+ c.relname AS name,+ CASE c.relkind+ WHEN 'r' THEN 'table'+ WHEN 'v' THEN 'view'+ WHEN 'm' THEN 'materialized_view'+ WHEN 'f' THEN 'foreign_table'+ WHEN 'p' THEN 'partitioned_table'+ ELSE 'other'+ END AS "tableType"+ FROM pg_class c+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = $1+ AND c.relkind IN ('r', 'v', 'm', 'f', 'p')+ ORDER BY c.relname+ `,+ values: [schema]+});++export const getTableDetailQuery = (schema: string, table: string) => ({+ // Returns a JSON object with columns and primaryKeys+ text: `+ WITH target AS (+ SELECT c.oid AS table_oid+ FROM pg_class c+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = $1 AND c.relname = $2+ ),+ cols AS (+ SELECT json_agg(+ json_build_object(+ 'name', a.attname,+ 'type', CASE WHEN a.attndims > 0 OR t.typelem != 0 AND t.typlen = -1+ THEN (SELECT bt.typname FROM pg_type bt WHERE bt.oid = t.typelem) || '[]'+ ELSE t.typname END,+ -- Left commented out so the query doesn't have to be modified if the UI ever needs these standard catalog values+ -- 'typeOid', a.atttypid,+ 'nullable', NOT a.attnotnull,+ -- Left commented out so the query doesn't have to be modified if the UI ever needs these standard catalog values+ -- 'defaultValue', pg_get_expr(d.adbin, d.adrelid),+ -- 'isIdentity', a.attidentity != '',+ 'identityGeneration', CASE a.attidentity+ WHEN 'a' THEN 'ALWAYS'+ WHEN 'd' THEN 'BY DEFAULT'+ ELSE null END+ -- Left commented out so the query doesn't have to be modified if the UI ever needs these standard catalog values+ -- 'isArray', a.attndims > 0 OR (t.typelem != 0 AND t.typlen = -1),+ -- 'maxLength', CASE WHEN a.atttypmod > 0 THEN a.atttypmod - 4 ELSE null END+ ) ORDER BY a.attnum+ ) AS data+ FROM pg_attribute a+ JOIN target ON a.attrelid = target.table_oid+ JOIN pg_type t ON t.oid = a.atttypid+ LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum+ WHERE a.attnum > 0 AND NOT a.attisdropped+ ),+ pks AS (+ SELECT json_agg(a.attname ORDER BY arr.pos) AS data+ FROM pg_constraint con+ JOIN target ON con.conrelid = target.table_oid+ CROSS JOIN LATERAL unnest(con.conkey) WITH ORDINALITY AS arr(attnum, pos)+ JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = arr.attnum+ WHERE con.contype = 'p'+ ),+ fks AS (+ SELECT json_agg(+ json_build_object(+ 'constraintName', con.conname,+ 'columns', (+ SELECT json_agg(a.attname ORDER BY arr.pos)+ FROM unnest(con.conkey) WITH ORDINALITY AS arr(attnum, pos)+ JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = arr.attnum+ ),+ 'targetSchema', tn.nspname,+ 'targetTable', tc.relname,+ 'targetColumns', (+ SELECT json_agg(a.attname ORDER BY arr.pos)+ FROM unnest(con.confkey) WITH ORDINALITY AS arr(attnum, pos)+ JOIN pg_attribute a ON a.attrelid = con.confrelid AND a.attnum = arr.attnum+ )+ )+ ) AS data+ FROM pg_constraint con+ JOIN target ON con.conrelid = target.table_oid+ JOIN pg_class tc ON tc.oid = con.confrelid+ JOIN pg_namespace tn ON tn.oid = tc.relnamespace+ WHERE con.contype = 'f'+ )+ -- enum_vals AS (+ -- SELECT json_object_agg(+ -- t.typname,+ -- (SELECT json_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid = t.oid)+ -- ) AS data+ -- FROM pg_attribute a+ -- JOIN target ON a.attrelid = target.table_oid+ -- JOIN pg_type t ON t.oid = a.atttypid+ -- WHERE a.attnum > 0+ -- AND NOT a.attisdropped+ -- AND t.typtype = 'e'+ -- )+ SELECT json_build_object(+ 'columns', COALESCE(cols.data, '[]'::json),+ 'primaryKeys', COALESCE(pks.data, '[]'::json),+ 'foreignKeys', COALESCE(fks.data, '[]'::json)+ -- TODO: re-enable when UI needs these+ -- 'enums', COALESCE(enum_vals.data, '{}'::json)+ ) AS result+ FROM cols, pks, fks+ `,+ values: [schema, table]+});diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.test.ts b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.test.tsnew file mode 100644index 0000000000..c5070c3b74--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.test.ts@@ -0,0 +1,168 @@+/* eslint-disable @typescript-eslint/no-unsafe-member-access */+/* eslint-disable @typescript-eslint/no-unsafe-assignment */+/* eslint-disable @typescript-eslint/no-unsafe-call */+/* eslint-disable @typescript-eslint/no-unsafe-argument */+/* eslint-disable @typescript-eslint/unbound-method */+import { beforeEach, describe, expect, test, vi } from "vitest";+import type WebSocket from "ws";++import { PostgresClientMessageType, PostgresServerMessageType } from "./pam-postgres-ws-types";+import { TerminalServerMessageType, type TSessionContext, type TWebSocketServerMessage } from "./pam-web-access-types";++// Mock logger+vi.mock("@app/lib/logger", () => ({+ logger: {+ info: vi.fn(),+ error: vi.fn(),+ debug: vi.fn(),+ warn: vi.fn()+ }+}));++// Mock the REPL (terminal sessions create one eagerly)+vi.mock("./pam-web-access-repl", () => ({+ createPamSqlRepl: vi.fn(() => ({+ getPrompt: vi.fn().mockReturnValue("=> "),+ clearBuffer: vi.fn(),+ processInput: vi.fn().mockResolvedValue({ output: "", prompt: "=> ", shouldClose: false })+ }))+}));++// Mock pg+vi.mock("pg", () => {+ const mockQuery = vi.fn();+ const mockConnect = vi.fn().mockResolvedValue(undefined);+ const mockEnd = vi.fn().mockResolvedValue(undefined);+ const mockOn = vi.fn();++ return {+ default: {+ Client: vi.fn(() => ({+ query: mockQuery,+ connect: mockConnect,+ end: mockEnd,+ on: mockOn+ }))+ }+ };+});++// eslint-disable-next-line import/first+import pg from "pg";++// eslint-disable-next-line import/first+import { handlePostgresSession } from "./pam-postgres-session-handler";++type MockPgClient = {+ query: ReturnType<typeof vi.fn>;+ connect: ReturnType<typeof vi.fn>;+ end: ReturnType<typeof vi.fn>;+ on: ReturnType<typeof vi.fn>;+};++function createMockContext(): TSessionContext & { sentMessages: TWebSocketServerMessage[] } {+ const sentMessages: TWebSocketServerMessage[] = [];+ return {+ socket: {+ on: vi.fn(),+ close: vi.fn(),+ readyState: 1,+ OPEN: 1,+ send: vi.fn()+ } as unknown as WebSocket,+ relayPort: 5432,+ resourceName: "test-db",+ sessionId: "test-session",+ sendMessage: vi.fn((msg: TWebSocketServerMessage) => {+ sentMessages.push(msg);+ }),+ sendSessionEnd: vi.fn(),+ isNearSessionExpiry: vi.fn().mockReturnValue(false),+ onCleanup: vi.fn(),+ sentMessages+ };+}++const mockParams = {+ connectionDetails: { database: "testdb", host: "localhost", port: 5432 },+ credentials: { username: "testuser" }+} as Parameters<typeof handlePostgresSession>[1];++function getPgInstance(): MockPgClient {+ const ClientMock = pg.Client as unknown as { mock: { results: { value: MockPgClient }[] } };+ return ClientMock.mock.results[ClientMock.mock.results.length - 1].value;+}++describe("handlePostgresSession", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ test("connects to database and sends ready message", async () => {+ const ctx = createMockContext();+ const result = await handlePostgresSession(ctx, mockParams);++ expect(pg.Client).toHaveBeenCalledWith(+ expect.objectContaining({+ host: "localhost",+ port: 5432,+ user: "testuser",+ database: "testdb"+ })+ );+ expect(ctx.sendMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ type: TerminalServerMessageType.Ready+ })+ );+ expect(result.cleanup).toBeDefined();+ });++ test("registers message handler on socket", async () => {+ const ctx = createMockContext();+ await handlePostgresSession(ctx, mockParams);++ expect(ctx.socket.on).toHaveBeenCalledWith("message", expect.any(Function));+ });++ test("cleanup closes pg client", async () => {+ const ctx = createMockContext();+ const result = await handlePostgresSession(ctx, mockParams);+ const pgInstance = getPgInstance();++ await result.cleanup();+ expect(pgInstance.end).toHaveBeenCalled();+ });++ test("handles get-schemas data explorer message", async () => {+ const ctx = createMockContext();+ await handlePostgresSession(ctx, mockParams);++ const pgInstance = getPgInstance();+ pgInstance.query.mockResolvedValue({+ rows: [{ name: "public" }, { name: "auth" }]+ });++ // Get the message handler callback+ const messageCall = (ctx.socket.on as ReturnType<typeof vi.fn>).mock.calls.find(+ ([event]: string[]) => event === "message"+ );+ const onMessage = messageCall?.[1] as ((data: Buffer) => void) | undefined;++ if (onMessage) {+ const msg = Buffer.from(+ JSON.stringify({ type: PostgresClientMessageType.GetSchemas, id: "550e8400-e29b-41d4-a716-446655440000" })+ );+ onMessage(msg);++ // Wait for async processing+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 50);+ });++ expect((ctx.socket as unknown as { send: ReturnType<typeof vi.fn> }).send).toHaveBeenCalledWith(+ expect.stringContaining(`"${PostgresServerMessageType.Schemas}"`)+ );+ }+ });+});diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.tsindex 0ec2d68b7f..8b7b88eeaa 100644--- a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts+++ b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts@@ -6,14 +6,20 @@ import {} from "@app/ee/services/pam-resource/postgres/postgres-resource-types";import { logger } from "@app/lib/logger";+import { getSchemasQuery, getTableDetailQuery, getTablesQuery } from "./pam-postgres-data-explorer-metadata";+import {+ PostgresClientMessageSchema,+ PostgresClientMessageType,+ PostgresServerMessageType,+ type TPostgresCorrelatedServerMessage+} from "./pam-postgres-ws-types";+import { parseClientMessage, resolveEndReason } from "./pam-web-access-fns";import { createPamSqlRepl } from "./pam-web-access-repl";import {- parseWsClientMessage,- resolveEndReason,SessionEndReason,+ TerminalServerMessageType,TSessionContext,- TSessionHandlerResult,- WsMessageType+ TSessionHandlerResult} from "./pam-web-access-types";type TPostgresSessionParams = {@@ -48,64 +54,196 @@ export const handlePostgresSession = async (const repl = createPamSqlRepl(pgClient);sendMessage({- type: WsMessageType.Ready,+ type: TerminalServerMessageType.Ready,data: `Connected to ${resourceName} (${connectionDetails.database}) as ${credentials.username}\n\n`,prompt: "=> "});logger.info({ sessionId }, "Postgres web access session established");+ const sendResponse = (msg: TPostgresCorrelatedServerMessage) => {+ try {+ if (socket.readyState === socket.OPEN) {+ socket.send(JSON.stringify(msg));+ }+ } catch (err) {+ logger.error(err, "Failed to send WebSocket message");+ }+ };++ // Shared error handler for correlated query messages+ const sendQueryError = async (id: string, err: unknown) => {+ const pgErr = err as { message?: string; detail?: string; hint?: string };++ // If the failed query was inside a transaction, roll back so the+ // connection is not stuck in an aborted transaction state.+ try {+ await pgClient.query("ROLLBACK");+ } catch {+ // ROLLBACK fails if there was no active transaction — safe to ignore.+ }++ sendResponse({+ type: PostgresServerMessageType.Error,+ id,+ error: pgErr.message ?? "Query execution failed",+ detail: pgErr.detail,+ hint: pgErr.hint+ });+ };+// Sequential message processing to prevent concurrent query issueslet processingPromise = Promise.resolve();socket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {processingPromise = processingPromise.then(async () => {- const message = parseWsClientMessage(rawData);+ const message = parseClientMessage(rawData, PostgresClientMessageSchema);if (!message) {sendMessage({- type: WsMessageType.Output,+ type: TerminalServerMessageType.Output,data: "Invalid message format\n",prompt: repl.getPrompt()});return;}- if (message.type === WsMessageType.Control) {- if (message.data === "quit") {- sendSessionEnd(SessionEndReason.UserQuit);- onCleanup();- socket.close();- return;+ switch (message.type) {+ case PostgresClientMessageType.GetSchemas: {+ try {+ const query = getSchemasQuery();+ const result = await pgClient.query(query.text, query.values);+ sendResponse({+ type: PostgresServerMessageType.Schemas,+ id: message.id,+ data: result.rows as { name: string }[]+ });+ } catch (err) {+ await sendQueryError(message.id, err);+ }+ break;+ }++ case PostgresClientMessageType.GetTables: {+ try {+ const query = getTablesQuery(message.schema);+ const result = await pgClient.query(query.text, query.values);+ sendResponse({+ type: PostgresServerMessageType.Tables,+ id: message.id,+ data: result.rows as { name: string; tableType: string }[]+ });+ } catch (err) {+ await sendQueryError(message.id, err);+ }+ break;}- if (message.data === "clear-buffer") {- repl.clearBuffer();- return;++ case PostgresClientMessageType.GetTableDetail: {+ try {+ const query = getTableDetailQuery(message.schema, message.table);+ const result = await pgClient.query<{ result: string }>(query.text, query.values);+ const rawDetail = result.rows[0]?.result;+ if (!rawDetail) {+ sendResponse({+ type: PostgresServerMessageType.Error,+ id: message.id,+ error: "Table not found or no metadata available"+ });+ break;+ }+ const detail =+ typeof rawDetail === "string"+ ? (JSON.parse(rawDetail) as Record<string, unknown>)+ : (rawDetail as unknown as Record<string, unknown>);+ sendResponse({+ type: PostgresServerMessageType.TableDetail,+ id: message.id,+ data: detail as {+ columns: {+ name: string;+ type: string;+ nullable: boolean;+ identityGeneration: string | null;+ }[];+ primaryKeys: string[];+ foreignKeys: {+ constraintName: string;+ columns: string[];+ targetSchema: string;+ targetTable: string;+ targetColumns: string[];+ }[];+ }+ });+ } catch (err) {+ await sendQueryError(message.id, err);+ }+ break;}- return;- }- if (message.type === WsMessageType.Input) {- const replResult = await repl.processInput(message.data);+ case PostgresClientMessageType.Query: {+ try {+ // Multi-statement SQL (transactions) is executed via PostgreSQL's simple query+ // protocol, which returns only the last statement's result. For transaction-wrapped+ // batches (BEGIN;...;COMMIT;), the result is from COMMIT (no rows/fields).+ const startTime = performance.now();+ const result = await pgClient.query(message.sql);+ const executionTimeMs = Math.round(performance.now() - startTime);+ sendResponse({+ type: PostgresServerMessageType.QueryResult,+ id: message.id,+ rows: (result.rows ?? []) as Record<string, unknown>[],+ fields: (result.fields ?? []).map((f) => ({ name: f.name })),+ rowCount: result.rowCount,+ command: result.command ?? "",+ executionTimeMs+ });+ } catch (err) {+ await sendQueryError(message.id, err);+ }+ break;+ }- if (replResult.shouldClose) {- sendSessionEnd(SessionEndReason.UserQuit);- onCleanup();- socket.close();- return;+ case PostgresClientMessageType.Control: {+ if (message.data === "quit") {+ sendSessionEnd(SessionEndReason.UserQuit);+ onCleanup();+ socket.close();+ return;+ }+ if (message.data === "clear-buffer") {+ repl.clearBuffer();+ }+ break;}- sendMessage({- type: WsMessageType.Output,- data: replResult.output,- prompt: replResult.prompt- });+ case PostgresClientMessageType.Input: {+ const replResult = await repl.processInput(message.data);++ if (replResult.shouldClose) {+ sendSessionEnd(SessionEndReason.UserQuit);+ onCleanup();+ socket.close();+ return;+ }++ sendMessage({+ type: TerminalServerMessageType.Output,+ data: replResult.output,+ prompt: replResult.prompt+ });+ break;+ }++ default:+ break;}}).catch((err) => {logger.error(err, "Error processing Postgres message");sendMessage({- type: WsMessageType.Output,+ type: TerminalServerMessageType.Output,data: "Internal error\n",prompt: "=> "});diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.ts b/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.tsnew file mode 100644index 0000000000..c88208b5b9--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.ts@@ -0,0 +1,166 @@+import { z } from "zod";++import { SessionEndReason } from "./pam-web-access-types";++export enum PostgresClientMessageType {+ Input = "input",+ Control = "control",+ GetSchemas = "get-schemas",+ GetTables = "get-tables",+ GetTableDetail = "get-table-detail",+ Query = "query"+}++export enum PostgresServerMessageType {+ Ready = "ready",+ Output = "output",+ SessionEnd = "session_end",+ Schemas = "schemas",+ Tables = "tables",+ TableDetail = "table-detail",+ QueryResult = "query-result",+ Error = "error"+}++// --- Shared base for correlated request/response messages ---++const CorrelatedBaseSchema = z.object({ id: z.string().uuid() });++// =====================================================================+// Client messages (client → server) — single flat discriminated union+// =====================================================================++const InputSchema = z.object({ type: z.literal(PostgresClientMessageType.Input), data: z.string() });++const ControlSchema = z.object({ type: z.literal(PostgresClientMessageType.Control), data: z.string() });++const GetSchemasRequestSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresClientMessageType.GetSchemas)+});++const GetTablesRequestSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresClientMessageType.GetTables),+ schema: z.string()+});++const GetTableDetailRequestSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresClientMessageType.GetTableDetail),+ schema: z.string(),+ table: z.string()+});++const QueryRequestSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresClientMessageType.Query),+ sql: z.string().max(50 * 1024)+});++export const PostgresClientMessageSchema = z.discriminatedUnion("type", [+ InputSchema,+ ControlSchema,+ GetSchemasRequestSchema,+ GetTablesRequestSchema,+ GetTableDetailRequestSchema,+ QueryRequestSchema+]);++export type TPostgresClientMessage = z.infer<typeof PostgresClientMessageSchema>;++// =====================================================================+// Server messages (server → client) — single flat discriminated union+// =====================================================================++const OutputSchema = z.object({+ type: z.enum([PostgresServerMessageType.Ready, PostgresServerMessageType.Output]),+ data: z.string(),+ prompt: z.string().default("")+});++const SessionEndSchema = z.object({+ type: z.literal(PostgresServerMessageType.SessionEnd),+ reason: z.nativeEnum(SessionEndReason)+});++const SchemasResponseSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresServerMessageType.Schemas),+ data: z.array(z.object({ name: z.string() }))+});++const TablesResponseSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresServerMessageType.Tables),+ data: z.array(z.object({ name: z.string(), tableType: z.string() }))+});++const TableDetailResponseSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresServerMessageType.TableDetail),+ data: z.object({+ columns: z.array(+ z.object({+ name: z.string(),+ type: z.string(),+ // Left commented out so the schema doesn't have to be modified if the UI ever needs these standard catalog values+ // typeOid: z.number(),+ nullable: z.boolean(),+ // Left commented out so the schema doesn't have to be modified if the UI ever needs these standard catalog values+ // defaultValue: z.string().nullable(),+ // isIdentity: z.boolean(),+ identityGeneration: z.string().nullable()+ // Left commented out so the schema doesn't have to be modified if the UI ever needs these standard catalog values+ // isArray: z.boolean(),+ // maxLength: z.number().nullable()+ })+ ),+ primaryKeys: z.array(z.string()),+ foreignKeys: z.array(+ z.object({+ constraintName: z.string(),+ columns: z.array(z.string()),+ targetSchema: z.string(),+ targetTable: z.string(),+ targetColumns: z.array(z.string())+ })+ )+ // Left commented out so the schema doesn't have to be modified if the UI ever needs these standard catalog values+ // enums: z.record(z.string(), z.array(z.string()))+ })+});++const QueryResultResponseSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresServerMessageType.QueryResult),+ rows: z.array(z.record(z.string(), z.unknown())),+ fields: z.array(+ z.object({+ name: z.string()+ // Left commented out so the schema doesn't have to be modified if the UI ever needs this standard catalog value+ // dataTypeID: z.number()+ })+ ),+ rowCount: z.number().nullable(),+ command: z.string(),+ executionTimeMs: z.number()+});++const ErrorResponseSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresServerMessageType.Error),+ error: z.string(),+ detail: z.string().optional(),+ hint: z.string().optional()+});++export const PostgresServerMessageSchema = z.discriminatedUnion("type", [+ OutputSchema,+ SessionEndSchema,+ SchemasResponseSchema,+ TablesResponseSchema,+ TableDetailResponseSchema,+ QueryResultResponseSchema,+ ErrorResponseSchema+]);++// Correlated server messages only (excludes lifecycle messages like ready/output/session_end)+export type TPostgresCorrelatedServerMessage = z.infer<+ | typeof SchemasResponseSchema+ | typeof TablesResponseSchema+ | typeof TableDetailResponseSchema+ | typeof QueryResultResponseSchema+ | typeof ErrorResponseSchema+>;diff --git a/backend/src/ee/services/pam-web-access/pam-redis-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-redis-session-handler.tsindex 7258c682c5..5b9e43fb85 100644--- a/backend/src/ee/services/pam-web-access/pam-redis-session-handler.ts+++ b/backend/src/ee/services/pam-web-access/pam-redis-session-handler.ts@@ -7,13 +7,13 @@ import {import { logger } from "@app/lib/logger";import { formatRedisReply, tokenizeRedisInput } from "./pam-redis-formatter";+import { RedisClientMessageSchema, RedisClientMessageType } from "./pam-redis-ws-types";+import { parseClientMessage, resolveEndReason } from "./pam-web-access-fns";import {- parseWsClientMessage,- resolveEndReason,SessionEndReason,+ TerminalServerMessageType,TSessionContext,- TSessionHandlerResult,- WsMessageType+ TSessionHandlerResult} from "./pam-web-access-types";type TRedisSessionParams = {@@ -83,7 +83,7 @@ export const handleRedisSession = async (const prompt = `${connectionDetails.host}:${connectionDetails.port}> `;sendMessage({- type: WsMessageType.Ready,+ type: TerminalServerMessageType.Ready,data: `Connected to ${resourceName} (${connectionDetails.host}:${connectionDetails.port}) as ${credentials.username || "default"}\n\n`,prompt});@@ -96,17 +96,17 @@ export const handleRedisSession = async (socket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {processingPromise = processingPromise.then(async () => {- const message = parseWsClientMessage(rawData);+ const message = parseClientMessage(rawData, RedisClientMessageSchema);if (!message) {sendMessage({- type: WsMessageType.Output,+ type: TerminalServerMessageType.Output,data: "Invalid message format\n",prompt});return;}- if (message.type === WsMessageType.Control) {+ if (message.type === RedisClientMessageType.Control) {if (message.data === "quit") {sendSessionEnd(SessionEndReason.UserQuit);onCleanup();@@ -119,7 +119,7 @@ export const handleRedisSession = async (return;}- if (message.type === WsMessageType.Input) {+ if (message.type === RedisClientMessageType.Input) {const result = await executeCommand(redisClient, message.data);if (result.shouldClose) {@@ -130,7 +130,7 @@ export const handleRedisSession = async (}sendMessage({- type: WsMessageType.Output,+ type: TerminalServerMessageType.Output,data: result.output,prompt});@@ -139,7 +139,7 @@ export const handleRedisSession = async (.catch((err) => {logger.error(err, "Error processing Redis message");sendMessage({- type: WsMessageType.Output,+ type: TerminalServerMessageType.Output,data: "Internal error\n",prompt});diff --git a/backend/src/ee/services/pam-web-access/pam-redis-ws-types.ts b/backend/src/ee/services/pam-web-access/pam-redis-ws-types.tsnew file mode 100644index 0000000000..40c3abcd6e--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-redis-ws-types.ts@@ -0,0 +1,11 @@+import { z } from "zod";++export enum RedisClientMessageType {+ Input = "input",+ Control = "control"+}++const InputSchema = z.object({ type: z.literal(RedisClientMessageType.Input), data: z.string() });+const ControlSchema = z.object({ type: z.literal(RedisClientMessageType.Control), data: z.string() });++export const RedisClientMessageSchema = z.discriminatedUnion("type", [InputSchema, ControlSchema]);diff --git a/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.tsindex f9a4191c7a..04bda1c6da 100644--- a/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.ts+++ b/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.ts@@ -6,13 +6,13 @@ import {} from "@app/ee/services/pam-resource/ssh/ssh-resource-types";import { logger } from "@app/lib/logger";+import { SshClientMessageSchema, SshClientMessageType } from "./pam-ssh-ws-types";+import { parseClientMessage, resolveEndReason } from "./pam-web-access-fns";import {- parseWsClientMessage,- resolveEndReason,SessionEndReason,+ TerminalServerMessageType,TSessionContext,- TSessionHandlerResult,- WsMessageType+ TSessionHandlerResult} from "./pam-web-access-types";type TSSHSessionParams = {@@ -54,7 +54,7 @@ export const handleSSHSession = async (// Send Ready messagesendMessage({- type: WsMessageType.Ready,+ type: TerminalServerMessageType.Ready,data: `Connected to ${resourceName} as ${credentials.username}\r\n`});@@ -63,34 +63,34 @@ export const handleSSHSession = async (// SSH -> WS: forward output from remote shell to WebSocketshellStream.on("data", (data: Buffer) => {sendMessage({- type: WsMessageType.Output,+ type: TerminalServerMessageType.Output,data: data.toString("utf-8")});});shellStream.stderr.on("data", (data: Buffer) => {sendMessage({- type: WsMessageType.Output,+ type: TerminalServerMessageType.Output,data: data.toString("utf-8")});});// WS -> SSH: forward input from WebSocket to remote shellsocket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {- const message = parseWsClientMessage(rawData);+ const message = parseClientMessage(rawData, SshClientMessageSchema);if (!message) return;- if (message.type === WsMessageType.Input) {+ if (message.type === SshClientMessageType.Input) {// Raw keystroke forwarding — no buffering, no local echoshellStream.write(message.data);- } else if (message.type === WsMessageType.Resize) {+ } else if (message.type === SshClientMessageType.Resize) {try {const { rows, cols } = JSON.parse(message.data) as { rows: number; cols: number };shellStream.setWindow(rows, cols, 0, 0);} catch {logger.debug("Invalid resize data received");}- } else if (message.type === WsMessageType.Control) {+ } else if (message.type === SshClientMessageType.Control) {if (message.data === "quit") {shellStream.close();client.end();diff --git a/backend/src/ee/services/pam-web-access/pam-ssh-ws-types.ts b/backend/src/ee/services/pam-web-access/pam-ssh-ws-types.tsnew file mode 100644index 0000000000..4015375f38--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-ssh-ws-types.ts@@ -0,0 +1,13 @@+import { z } from "zod";++export enum SshClientMessageType {+ Input = "input",+ Control = "control",+ Resize = "resize"+}++const InputSchema = z.object({ type: z.literal(SshClientMessageType.Input), data: z.string() });+const ControlSchema = z.object({ type: z.literal(SshClientMessageType.Control), data: z.string() });+const ResizeSchema = z.object({ type: z.literal(SshClientMessageType.Resize), data: z.string() });++export const SshClientMessageSchema = z.discriminatedUnion("type", [InputSchema, ControlSchema, ResizeSchema]);diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-fns.ts b/backend/src/ee/services/pam-web-access/pam-web-access-fns.tsnew file mode 100644index 0000000000..d6a842671d--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-web-access-fns.ts@@ -0,0 +1,25 @@+import { SessionEndReason } from "./pam-web-access-types";++export const rawBufferToString = (rawData: Buffer | ArrayBuffer | Buffer[]): string => {+ if (Buffer.isBuffer(rawData)) return rawData.toString();+ if (Array.isArray(rawData)) return Buffer.concat(rawData).toString();+ return Buffer.from(rawData).toString();+};++export const resolveEndReason = (isNearSessionExpiry: () => boolean): SessionEndReason =>+ isNearSessionExpiry() ? SessionEndReason.SessionCompleted : SessionEndReason.ConnectionLost;++export const parseClientMessage = <T>(+ rawData: Buffer | ArrayBuffer | Buffer[],+ schema: { safeParse: (data: unknown) => { success: true; data: T } | { success: false } }+): T | null => {+ const str = rawBufferToString(rawData);+ let parsed: unknown;+ try {+ parsed = JSON.parse(str);+ } catch {+ return null;+ }+ const result = schema.safeParse(parsed);+ return result.success ? result.data : null;+};diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts b/backend/src/ee/services/pam-web-access/pam-web-access-service.tsindex c1868b3c63..05896ef102 100644--- a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts+++ b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts@@ -50,14 +50,14 @@ import {DEFAULT_WEB_SESSION_DURATION_MS,MAX_WEB_SESSIONS_PER_USER,SessionEndReason,+ TerminalServerMessageType,TIssueWebSocketTicketDTO,TSessionContext,TSessionHandlerResult,TWebSocketServerMessage,WebSocketServerMessageSchema,WS_IDLE_TIMEOUT_MS,- WS_PING_INTERVAL_MS,- WsMessageType+ WS_PING_INTERVAL_MS} from "./pam-web-access-types";const SUPPORTED_WEB_ACCESS_RESOURCES = [PamResource.Postgres, PamResource.SSH, PamResource.Redis];@@ -128,7 +128,28 @@ export const pamWebAccessServiceFactory = ({};const sendSessionEnd = (socket: WebSocket, reason: SessionEndReason): void => {- sendMessage(socket, { type: WsMessageType.SessionEnd, reason });+ sendMessage(socket, { type: TerminalServerMessageType.SessionEnd, reason });+ };++ /**+ * Send a session_end message and close the socket only after the message has been flushed.+ * This avoids the race where socket.close() sends a close frame before the session_end+ * data frame reaches the client.+ */+ const sendSessionEndAndClose = (socket: WebSocket, reason: SessionEndReason): void => {+ try {+ if (socket.readyState === socket.OPEN) {+ const parsed = WebSocketServerMessageSchema.parse({ type: TerminalServerMessageType.SessionEnd, reason });+ socket.send(JSON.stringify(parsed), () => {+ socket.close();+ });+ return;+ }+ } catch (err) {+ logger.error(err, "Failed to send session end message");+ }+ // Fallback: close immediately if send failed or socket wasn't open+ socket.close();};const issueWebSocketTicket = async ({@@ -415,10 +436,10 @@ export const pamWebAccessServiceFactory = ({const activeCount = await pamSessionDAL.countActiveWebSessions(userId, projectId);if (activeCount >= MAX_WEB_SESSIONS_PER_USER) {sendMessage(socket, {- type: WsMessageType.Output,- data: `Maximum concurrent web sessions (${MAX_WEB_SESSIONS_PER_USER}) reached. Please close an existing session first.\n`+ type: TerminalServerMessageType.Output,+ data: `${SessionEndReason.SessionLimitReached}\n`});- socket.close();+ sendSessionEndAndClose(socket, SessionEndReason.SessionLimitReached);return;}@@ -566,9 +587,8 @@ export const pamWebAccessServiceFactory = ({if (idleTimer) clearTimeout(idleTimer);idleTimer = setTimeout(() => {if (!cleanedUp) {- sendSessionEnd(socket, SessionEndReason.IdleTimeout);void cleanup();- socket.close();+ sendSessionEndAndClose(socket, SessionEndReason.IdleTimeout);}}, WS_IDLE_TIMEOUT_MS);};@@ -602,9 +622,8 @@ export const pamWebAccessServiceFactory = ({// Session expiry timerexpiryTimer = setTimeout(() => {if (!cleanedUp) {- sendSessionEnd(socket, SessionEndReason.SessionCompleted);void cleanup();- socket.close();+ sendSessionEndAndClose(socket, SessionEndReason.SessionCompleted);}}, DEFAULT_WEB_SESSION_DURATION_MS);@@ -620,9 +639,8 @@ export const pamWebAccessServiceFactory = ({});} catch (err) {logger.error(err, "Failed to establish web access session");- sendSessionEnd(socket, SessionEndReason.SetupFailed);await cleanup();- socket.close();+ sendSessionEndAndClose(socket, SessionEndReason.SetupFailed);}};diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-types.ts b/backend/src/ee/services/pam-web-access/pam-web-access-types.tsindex d39f302b66..ee7bf4182b 100644--- a/backend/src/ee/services/pam-web-access/pam-web-access-types.ts+++ b/backend/src/ee/services/pam-web-access/pam-web-access-types.ts@@ -4,57 +4,47 @@ import { z } from "zod";import { AuditLogInfo } from "@app/ee/services/audit-log/audit-log-types";import { ProjectServiceActor } from "@app/lib/types";-// Default session duration for web access sessions (1 hour in ms)-export const DEFAULT_WEB_SESSION_DURATION_MS = 60 * 60 * 1000;--// Maximum concurrent web access sessions per user per project-export const MAX_WEB_SESSIONS_PER_USER = 5;--// WebSocket ping interval (ms) — keeps ALB from killing idle connections (default 60s timeout)-export const WS_PING_INTERVAL_MS = 30000;--// Idle timeout (ms) — auto-close sessions with no user input/control messages-export const WS_IDLE_TIMEOUT_MS = 5 * 60 * 1000;+export enum SessionEndReason {+ SessionCompleted = "Session duration complete",+ UserQuit = "Goodbye",+ ConnectionLost = "Connection lost",+ SetupFailed = "Failed to establish connection",+ IdleTimeout = "Session closed due to inactivity",+ SessionLimitReached = "Maximum concurrent sessions reached"+}-export enum WsMessageType {+export enum TerminalServerMessageType {Ready = "ready",Output = "output",- Input = "input",- Control = "control",- Resize = "resize",SessionEnd = "session_end"}-export enum SessionEndReason {- SessionCompleted = "Session duration complete. Connection closed.",- UserQuit = "Goodbye!",- ConnectionLost = "Connection lost. Session ended.",- SetupFailed = "Failed to establish connection.",- IdleTimeout = "Session closed due to inactivity."-}--const WebSocketOutputMessageSchema = z.object({- type: z.enum([WsMessageType.Ready, WsMessageType.Output]),- data: z.string(),- prompt: z.string().default("")-});--const WebSocketSessionEndMessageSchema = z.object({- type: z.literal(WsMessageType.SessionEnd),- reason: z.nativeEnum(SessionEndReason)-});-+// Terminal server message schema — used by TSessionContext.sendMessageexport const WebSocketServerMessageSchema = z.discriminatedUnion("type", [- WebSocketOutputMessageSchema,- WebSocketSessionEndMessageSchema+ z.object({+ type: z.enum([TerminalServerMessageType.Ready, TerminalServerMessageType.Output]),+ data: z.string(),+ prompt: z.string().default("")+ }),+ z.object({+ type: z.literal(TerminalServerMessageType.SessionEnd),+ reason: z.nativeEnum(SessionEndReason)+ })]);export type TWebSocketServerMessage = z.input<typeof WebSocketServerMessageSchema>;-export const WebSocketClientMessageSchema = z.object({- type: z.enum([WsMessageType.Input, WsMessageType.Control, WsMessageType.Resize]),- data: z.string()-});+// Default session duration for web access sessions (1 hour in ms)+export const DEFAULT_WEB_SESSION_DURATION_MS = 60 * 60 * 1000;++// Maximum concurrent web access sessions per user per project+export const MAX_WEB_SESSIONS_PER_USER = 5;++// WebSocket ping interval (ms) — keeps ALB from killing idle connections (default 60s timeout)+export const WS_PING_INTERVAL_MS = 30000;++// Idle timeout (ms) — auto-close sessions with no user input/control messages+export const WS_IDLE_TIMEOUT_MS = 5 * 60 * 1000;export type TSessionContext = {socket: WebSocket;@@ -71,27 +61,6 @@ export type TSessionHandlerResult = {cleanup: () => Promise<void>;};-export const resolveEndReason = (isNearSessionExpiry: () => boolean): SessionEndReason =>- isNearSessionExpiry() ? SessionEndReason.SessionCompleted : SessionEndReason.ConnectionLost;--export const parseWsClientMessage = (- rawData: Buffer | ArrayBuffer | Buffer[]-): z.infer<typeof WebSocketClientMessageSchema> | null => {- let data: string;- if (Buffer.isBuffer(rawData)) data = rawData.toString();- else if (Array.isArray(rawData)) data = Buffer.concat(rawData).toString();- else data = Buffer.from(rawData).toString();-- let parsed: unknown;- try {- parsed = JSON.parse(data);- } catch {- return null;- }- const result = WebSocketClientMessageSchema.safeParse(parsed);- return result.success ? result.data : null;-};-export type TIssueWebSocketTicketDTO = {accountId: string;projectId: string;diff --git a/docs/documentation/platform/pam/getting-started/resources/postgresql.mdx b/docs/documentation/platform/pam/getting-started/resources/postgresql.mdxindex f024660cc6..d9eeb70fa3 100644--- a/docs/documentation/platform/pam/getting-started/resources/postgresql.mdx+++ b/docs/documentation/platform/pam/getting-started/resources/postgresql.mdx@@ -151,7 +151,7 @@ There are two ways to access a PostgreSQL account: through the browser via Web A### Web Access-PostgreSQL resources can be accessed directly from the browser using Infisical's web-based SQL console. This provides a convenient way to run queries without installing any local tools.+PostgreSQL resources can be accessed directly from the browser using the **Data Explorer** — a visual interface for browsing and editing tables — or the **SQL Terminal** for running ad-hoc queries.For details, see [PostgreSQL Web Access](/documentation/platform/pam/product-reference/web-access/postgresql).diff --git a/docs/documentation/platform/pam/product-reference/web-access/overview.mdx b/docs/documentation/platform/pam/product-reference/web-access/overview.mdxindex a797ea28df..23c02697fb 100644--- a/docs/documentation/platform/pam/product-reference/web-access/overview.mdx+++ b/docs/documentation/platform/pam/product-reference/web-access/overview.mdx@@ -7,7 +7,7 @@ description: "Access PAM-managed resources directly from your browser with an inInfisical PAM Web Access provides a browser-based portal for interacting with your infrastructure directly from your browser via the Infisical dashboard — no client tools or CLI required.<Info>- Web Access currently supports **PostgreSQL** databases, **Redis** servers, and **SSH** servers.+ Web Access currently supports **PostgreSQL** databases (with a visual Data Explorer and SQL terminal), **Redis** servers, and **SSH** servers.</Info>## How It Works@@ -46,7 +46,7 @@ Sessions that exceed the idle timeout or max duration are automatically terminat<CardGroup cols={2}><Card title="PostgreSQL" icon="database" href="/documentation/platform/pam/product-reference/web-access/postgresql">- Interactive SQL terminal with psql-style output formatting.+ Visual Data Explorer for browsing and editing tables, plus an interactive SQL terminal.</Card><Card title="Redis" icon="database" href="/documentation/platform/pam/product-reference/web-access/redis">Interactive Redis REPL with redis-cli-style output formatting.diff --git a/docs/documentation/platform/pam/product-reference/web-access/postgresql.mdx b/docs/documentation/platform/pam/product-reference/web-access/postgresql.mdxindex 51a4bc712d..c28a52e70d 100644--- a/docs/documentation/platform/pam/product-reference/web-access/postgresql.mdx+++ b/docs/documentation/platform/pam/product-reference/web-access/postgresql.mdx@@ -1,12 +1,18 @@---title: "PostgreSQL Web Access"sidebarTitle: "PostgreSQL"-description: "Run SQL queries against PostgreSQL databases directly from your browser."+description: "Browse, query, and edit PostgreSQL databases directly from your browser."----The PostgreSQL web access terminal provides a `psql`-like experience in your browser. It is designed for light, ad-hoc usage — quick queries, debugging, and administrative tasks — not as a replacement for a full database client or long-running workloads.+-## Connecting+PostgreSQL web access provides two modes for interacting with your database directly from the browser: the **Data Explorer** for visual browsing and editing, and the **SQL Terminal** for running ad-hoc queries.++## Data Explorer++The Data Explorer is a visual interface for browsing and editing PostgreSQL tables. It provides schema and table navigation, filtering, sorting, inline editing, and full CRUD operations — all without writing SQL.++### Connecting<Steps><Step title="Navigate to Account">@@ -19,10 +25,42 @@ The PostgreSQL web access terminal provides a `psql`-like experience in your bro</Step>- <Step title="Connect in Browser">- In the connect modal, click **Connect in Browser** to open the web access terminal.+ <Step title="Open Data Explorer">+ In the connect modal, click **Open Data Explorer** to launch the Data Explorer in a new tab.- + + </Step>+</Steps>++Once connected, you get a spreadsheet-like interface for your database where you can:++- Browse tables and explore their data+- Filter and sort to quickly find what you need+- Edit data directly — add, update, or delete rows++++## SQL Terminal++The SQL terminal provides a `psql`-like experience in your browser. It is designed for ad-hoc usage — quick queries, debugging, and administrative tasks.++### Connecting++<Steps>+ <Step title="Navigate to Account">+ Go to the **Resources** tab in your PAM project, open the PostgreSQL resource, and find the account you want to access. Click the **Connect** button next to the account.++ ++ Alternatively, if you are on the account page, click the **Access** button.++ + </Step>++ <Step title="Open Console">+ In the connect modal, click **Open Console** to launch the SQL terminal in a new tab.++ </Step><Step title="End Session">@@ -32,7 +70,7 @@ The PostgreSQL web access terminal provides a `psql`-like experience in your bro-## Usage+### UsageOnce connected, you'll see a `=>` prompt. Type SQL queries as you would in `psql`:@@ -45,7 +83,7 @@ Once connected, you'll see a `=>` prompt. Type SQL queries as you would in `psql(2 rows)```-### Transactions+#### TransactionsTransactions are fully supported. You can use `BEGIN`, `COMMIT`, and `ROLLBACK` as you would in `psql`:@@ -71,7 +109,10 @@ In addition to the [common session limits](/documentation/platform/pam/product-r## FAQ<AccordionGroup>- <Accordion title="Is this an actual psql session?">- No. The web access terminal is not a `psql` client. It is a custom SQL REPL that connects directly to PostgreSQL and provides a `psql`-like experience, including familiar prompts and tabular output formatting. Backslash commands like `\dt` or `\d` are not supported.+ <Accordion title="Is the SQL terminal an actual psql session?">+ No. The SQL terminal is not a `psql` client. It is a custom SQL REPL that connects directly to PostgreSQL and provides a `psql`-like experience, including familiar prompts and tabular output formatting. Backslash commands like `\dt` or `\d` are not supported.+ </Accordion>+ <Accordion title="Can I edit data in the Data Explorer for all tables?">+ Editing is only available for tables that have a primary key defined. Tables without a primary key, as well as views, are displayed in read-only mode.</Accordion></AccordionGroup>diff --git a/docs/images/pam/product-reference/web-access/pg-connect-in-browser.png b/docs/images/pam/product-reference/web-access/pg-connect-in-browser.pngdeleted file mode 100644index 79a8153852..0000000000Binary files a/docs/images/pam/product-reference/web-access/pg-connect-in-browser.png and /dev/null differdiff --git a/docs/images/pam/product-reference/web-access/pg-data-explorer-connect-button.png b/docs/images/pam/product-reference/web-access/pg-data-explorer-connect-button.pngnew file mode 100644index 0000000000..76cb1e54baBinary files /dev/null and b/docs/images/pam/product-reference/web-access/pg-data-explorer-connect-button.png differdiff --git a/docs/images/pam/product-reference/web-access/pg-data-explorer-overview.png b/docs/images/pam/product-reference/web-access/pg-data-explorer-overview.pngnew file mode 100644index 0000000000..6bc747133cBinary files /dev/null and b/docs/images/pam/product-reference/web-access/pg-data-explorer-overview.png differdiff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex c78b6b5b21..8701a628fb 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -33,7 +33,9 @@"@radix-ui/react-alert-dialog": "^1.1.3","@radix-ui/react-checkbox": "^1.1.3","@radix-ui/react-collapsible": "^1.1.2",+ "@radix-ui/react-context-menu": "^2.2.16","@radix-ui/react-dialog": "^1.1.3",+ "@radix-ui/react-direction": "^1.1.1","@radix-ui/react-dropdown-menu": "^2.1.3","@radix-ui/react-hover-card": "^1.1.3","@radix-ui/react-label": "^2.1.1",@@ -53,6 +55,8 @@"@sindresorhus/slugify": "^2.2.1","@tanstack/react-query": "^5.62.7","@tanstack/react-router": "^1.95.1",+ "@tanstack/react-table": "^8.21.3",+ "@tanstack/react-virtual": "^3.13.23","@tanstack/virtual-file-routes": "^1.87.6","@tanstack/zod-adapter": "^1.91.0","@types/dagre": "^0.7.52",@@ -162,8 +166,7 @@"resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.4.tgz","integrity": "sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==","dev": true,- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/@alloc/quick-lru": {"version": "5.2.0",@@ -208,6 +211,7 @@"integrity": "sha512-2BCOP7TN8M+gVDj7/ht3hsaO/B/n5oDbiAyyvnRlNOs+u1o+JWNYTQrmpuNp1/Wq2gcFrI01JAW+paEKDMx/CA==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/code-frame": "^7.27.1","@babel/generator": "^7.28.3",@@ -500,6 +504,7 @@"resolved": "https://registry.npmjs.org/@casl/ability/-/ability-6.7.2.tgz","integrity": "sha512-KjKXlcjKbUz8dKw7PY56F7qlfOFgxTU6tnlJ8YrbDyWkJMIlHa6VRWzCD8RU20zbJUC1hExhOFggZjm6tf1mUw==","license": "MIT",+ "peer": true,"dependencies": {"@ucast/mongo2js": "^1.3.0"},@@ -580,6 +585,7 @@"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz","integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==","license": "MIT",+ "peer": true,"dependencies": {"@dnd-kit/accessibility": "^3.1.1","@dnd-kit/utilities": "^3.2.2",@@ -1406,6 +1412,7 @@"resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-svg-core/-/fontawesome-svg-core-6.7.1.tgz","integrity": "sha512-8dBIHbfsKlCk2jHQ9PoRBg2Z+4TwyE3vZICSnoDlnsHA6SiMlTwfmW6yX0lHsRmWJugkeb92sA0hZdkXJhuz+g==","license": "MIT",+ "peer": true,"dependencies": {"@fortawesome/fontawesome-common-types": "6.7.1"},@@ -2096,6 +2103,7 @@"resolved": "https://registry.npmjs.org/@octokit/core/-/core-6.1.2.tgz","integrity": "sha512-hEb7Ma4cGJGEUNOAVmyfdB/3WirWMg5hDuNFVejGEDFqupeOysLc2sG6HJxY2etBp5YQu5Wtxwi020jS9xlUwg==","license": "MIT",+ "peer": true,"dependencies": {"@octokit/auth-token": "^5.0.0","@octokit/graphql": "^8.0.0",@@ -2241,6 +2249,7 @@"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz","integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==","license": "Apache-2.0",+ "peer": true,"engines": {"node": ">=8.0.0"}@@ -2784,6 +2793,21 @@}}},+ "node_modules/@radix-ui/react-accordion/node_modules/@radix-ui/react-direction": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.0.tgz",+ "integrity": "sha512-BUuBvgThEiAXh2DWu93XsT+a3aWrGqolGlqqw5VU1kG7p/ZH2cuDlM1sRLNnY3QcBS69UIz2mcKhMxDsdewhjg==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },"node_modules/@radix-ui/react-alert-dialog": {"version": "1.1.3","resolved": "https://registry.npmjs.org/@radix-ui/react-alert-dialog/-/react-alert-dialog-1.1.3.tgz",@@ -2945,7 +2969,494 @@"integrity": "sha512-RApLLOcINYJA+dMVbOju7MYv1Mb2EBp2nH4HdDzXTSyaR5optlm6Otrz1euW3HbdOR8UmmFK06TD+A9frYWv+g==","license": "MIT","dependencies": {- "@radix-ui/react-compose-refs": "1.1.1"+ "@radix-ui/react-compose-refs": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-compose-refs": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.1.tgz",+ "integrity": "sha512-Y9VzoRDSJtgFMUCoiZBDVo084VQ5hfpXxVE+NgkdNsjiDBByiImMZKKhxMwCbdHvhlENG6a833CbFkOQvTricw==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.1.tgz",+ "integrity": "sha512-UASk9zi+crv9WteK/NU4PLvOoL3OuE6BWVKNF6hPRBtYBDXQ2u5iu3O59zUlJiTVvkyuycnqrztsHVJwcK9K+Q==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu": {+ "version": "2.2.16",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-context-menu/-/react-context-menu-2.2.16.tgz",+ "integrity": "sha512-O8morBEW+HsVG28gYDZPTrT9UUovQUlJue5YO836tiTJhuIWBm/zQHc7j388sHWtdH/xUZurK9olD2+pcqx5ww==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-menu": "2.1.16",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-callback-ref": "1.1.1",+ "@radix-ui/react-use-controllable-state": "1.2.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/primitive": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz",+ "integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==",+ "license": "MIT"+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-arrow": {+ "version": "1.1.7",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.7.tgz",+ "integrity": "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-primitive": "2.1.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-collection": {+ "version": "1.1.7",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.7.tgz",+ "integrity": "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-slot": "1.2.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-compose-refs": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.2.tgz",+ "integrity": "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-context": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.2.tgz",+ "integrity": "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-dismissable-layer": {+ "version": "1.1.11",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.11.tgz",+ "integrity": "sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-callback-ref": "1.1.1",+ "@radix-ui/react-use-escape-keydown": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-focus-guards": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.3.tgz",+ "integrity": "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-focus-scope": {+ "version": "1.1.7",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.7.tgz",+ "integrity": "sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-callback-ref": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-id": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.1.tgz",+ "integrity": "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-menu": {+ "version": "2.1.16",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-menu/-/react-menu-2.1.16.tgz",+ "integrity": "sha512-72F2T+PLlphrqLcAotYPp0uJMr5SjP5SL01wfEspJbru5Zs5vQaSHb4VB3ZMJPimgHHCHG7gMOeOB9H3Hdmtxg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-collection": "1.1.7",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-direction": "1.1.1",+ "@radix-ui/react-dismissable-layer": "1.1.11",+ "@radix-ui/react-focus-guards": "1.1.3",+ "@radix-ui/react-focus-scope": "1.1.7",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-popper": "1.2.8",+ "@radix-ui/react-portal": "1.1.9",+ "@radix-ui/react-presence": "1.1.5",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-roving-focus": "1.1.11",+ "@radix-ui/react-slot": "1.2.3",+ "@radix-ui/react-use-callback-ref": "1.1.1",+ "aria-hidden": "^1.2.4",+ "react-remove-scroll": "^2.6.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-popper": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.2.8.tgz",+ "integrity": "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw==",+ "license": "MIT",+ "dependencies": {+ "@floating-ui/react-dom": "^2.0.0",+ "@radix-ui/react-arrow": "1.1.7",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-callback-ref": "1.1.1",+ "@radix-ui/react-use-layout-effect": "1.1.1",+ "@radix-ui/react-use-rect": "1.1.1",+ "@radix-ui/react-use-size": "1.1.1",+ "@radix-ui/rect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-portal": {+ "version": "1.1.9",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.9.tgz",+ "integrity": "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-presence": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.5.tgz",+ "integrity": "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-primitive": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz",+ "integrity": "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-slot": "1.2.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-roving-focus": {+ "version": "1.1.11",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.11.tgz",+ "integrity": "sha512-7A6S9jSgm/S+7MdtNDSb+IU859vQqJ/QAtcYQcfFC6W8RS4IxIZDldLR0xqCFZ6DCyrQLjLPsxtTNch5jVA4lA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-collection": "1.1.7",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-direction": "1.1.1",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-callback-ref": "1.1.1",+ "@radix-ui/react-use-controllable-state": "1.2.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-use-callback-ref": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz",+ "integrity": "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-use-controllable-state": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.2.2.tgz",+ "integrity": "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-effect-event": "0.0.2",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-use-escape-keydown": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.1.tgz",+ "integrity": "sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-callback-ref": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-use-layout-effect": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz",+ "integrity": "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-use-rect": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-rect/-/react-use-rect-1.1.1.tgz",+ "integrity": "sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/rect": "1.1.1"},"peerDependencies": {"@types/react": "*",@@ -2957,11 +3468,14 @@}}},- "node_modules/@radix-ui/react-compose-refs": {+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-use-size": {"version": "1.1.1",- "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.1.tgz",- "integrity": "sha512-Y9VzoRDSJtgFMUCoiZBDVo084VQ5hfpXxVE+NgkdNsjiDBByiImMZKKhxMwCbdHvhlENG6a833CbFkOQvTricw==",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.1.tgz",+ "integrity": "sha512-ewrXRDTAqAXlkl6t/fkXWNAhFX9I+CkKlw6zjEwk86RSPKwZr3xpBRso655aqYafwtnbpHLj6toFzmd6xdVptQ==","license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },"peerDependencies": {"@types/react": "*","react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"@@ -2972,14 +3486,30 @@}}},- "node_modules/@radix-ui/react-context": {+ "node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/rect": {"version": "1.1.1",- "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.1.tgz",- "integrity": "sha512-UASk9zi+crv9WteK/NU4PLvOoL3OuE6BWVKNF6hPRBtYBDXQ2u5iu3O59zUlJiTVvkyuycnqrztsHVJwcK9K+Q==",+ "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.1.tgz",+ "integrity": "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw==",+ "license": "MIT"+ },+ "node_modules/@radix-ui/react-context-menu/node_modules/react-remove-scroll": {+ "version": "2.7.2",+ "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz",+ "integrity": "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==","license": "MIT",+ "dependencies": {+ "react-remove-scroll-bar": "^2.3.7",+ "react-style-singleton": "^2.2.3",+ "tslib": "^2.1.0",+ "use-callback-ref": "^1.3.3",+ "use-sidecar": "^1.1.3"+ },+ "engines": {+ "node": ">=10"+ },"peerDependencies": {"@types/react": "*",- "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"},"peerDependenciesMeta": {"@types/react": {@@ -3042,9 +3572,9 @@}},"node_modules/@radix-ui/react-direction": {- "version": "1.1.0",- "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.0.tgz",- "integrity": "sha512-BUuBvgThEiAXh2DWu93XsT+a3aWrGqolGlqqw5VU1kG7p/ZH2cuDlM1sRLNnY3QcBS69UIz2mcKhMxDsdewhjg==",+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.1.tgz",+ "integrity": "sha512-1UEWRX6jnOA2y4H5WczZ44gOOjTEmlqv1uNW4GAJEO5+bauCBhv8snY65Iw5/VOS/ghKN9gr2KjnLKxrsvoMVw==","license": "MIT","peerDependencies": {"@types/react": "*",@@ -3264,6 +3794,21 @@}}},+ "node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-direction": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.0.tgz",+ "integrity": "sha512-BUuBvgThEiAXh2DWu93XsT+a3aWrGqolGlqqw5VU1kG7p/ZH2cuDlM1sRLNnY3QcBS69UIz2mcKhMxDsdewhjg==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-slot": {"version": "1.1.1","resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.1.1.tgz",@@ -3514,6 +4059,21 @@}}},+ "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-direction": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.0.tgz",+ "integrity": "sha512-BUuBvgThEiAXh2DWu93XsT+a3aWrGqolGlqqw5VU1kG7p/ZH2cuDlM1sRLNnY3QcBS69UIz2mcKhMxDsdewhjg==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },"node_modules/@radix-ui/react-roving-focus": {"version": "1.1.1","resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.1.tgz",@@ -3545,6 +4105,21 @@}}},+ "node_modules/@radix-ui/react-roving-focus/node_modules/@radix-ui/react-direction": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.0.tgz",+ "integrity": "sha512-BUuBvgThEiAXh2DWu93XsT+a3aWrGqolGlqqw5VU1kG7p/ZH2cuDlM1sRLNnY3QcBS69UIz2mcKhMxDsdewhjg==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },"node_modules/@radix-ui/react-scroll-area": {"version": "1.2.10","resolved": "https://registry.npmjs.org/@radix-ui/react-scroll-area/-/react-scroll-area-1.2.10.tgz",@@ -3618,21 +4193,6 @@}}},- "node_modules/@radix-ui/react-scroll-area/node_modules/@radix-ui/react-direction": {- "version": "1.1.1",- "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.1.tgz",- "integrity": "sha512-1UEWRX6jnOA2y4H5WczZ44gOOjTEmlqv1uNW4GAJEO5+bauCBhv8snY65Iw5/VOS/ghKN9gr2KjnLKxrsvoMVw==",- "license": "MIT",- "peerDependencies": {- "@types/react": "*",- "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"- },- "peerDependenciesMeta": {- "@types/react": {- "optional": true- }- }- },"node_modules/@radix-ui/react-scroll-area/node_modules/@radix-ui/react-presence": {"version": "1.1.5","resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.5.tgz",@@ -3753,6 +4313,21 @@}}},+ "node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-direction": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.0.tgz",+ "integrity": "sha512-BUuBvgThEiAXh2DWu93XsT+a3aWrGqolGlqqw5VU1kG7p/ZH2cuDlM1sRLNnY3QcBS69UIz2mcKhMxDsdewhjg==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },"node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-slot": {"version": "1.1.1","resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.1.1.tgz",@@ -3942,6 +4517,21 @@}}},+ "node_modules/@radix-ui/react-tabs/node_modules/@radix-ui/react-direction": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.0.tgz",+ "integrity": "sha512-BUuBvgThEiAXh2DWu93XsT+a3aWrGqolGlqqw5VU1kG7p/ZH2cuDlM1sRLNnY3QcBS69UIz2mcKhMxDsdewhjg==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },"node_modules/@radix-ui/react-toast": {"version": "1.2.3","resolved": "https://registry.npmjs.org/@radix-ui/react-toast/-/react-toast-1.2.3.tgz",@@ -4944,6 +5534,7 @@"integrity": "sha512-RnO1SaiCFHn666wNz2QfZEFxvmiNRqhzaMXHXxXXKt+MEP7aajlPxUSMIQpKAaJfverpovEYqjBOXDq6dDcaOQ==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@typescript-eslint/utils": "^8.13.0","eslint-visitor-keys": "^4.2.0",@@ -5569,6 +6160,7 @@"resolved": "https://registry.npmjs.org/@tanstack/react-router/-/react-router-1.95.1.tgz","integrity": "sha512-P5x4yNhcdkYsCEoYeGZP8Q9Jlxf0WXJa4G/xvbmM905seZc9FqJqvCSRvX3dWTPOXRABhl4g+8DHqfft0c/AvQ==","license": "MIT",+ "peer": true,"dependencies": {"@tanstack/history": "1.95.0","@tanstack/react-store": "^0.7.0",@@ -5606,13 +6198,33 @@"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"}},+ "node_modules/@tanstack/react-table": {+ "version": "8.21.3",+ "resolved": "https://registry.npmjs.org/@tanstack/react-table/-/react-table-8.21.3.tgz",+ "integrity": "sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww==",+ "license": "MIT",+ "dependencies": {+ "@tanstack/table-core": "8.21.3"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/tannerlinsley"+ },+ "peerDependencies": {+ "react": ">=16.8",+ "react-dom": ">=16.8"+ }+ },"node_modules/@tanstack/react-virtual": {- "version": "3.11.1",- "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.11.1.tgz",- "integrity": "sha512-orn2QNe5tF6SqjucHJ6cKTKcRDe3GG7bcYqPNn72Yejj7noECdzgAyRfGt2pGDPemhYim3d1HIR/dgruCnLfUA==",+ "version": "3.13.23",+ "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.13.23.tgz",+ "integrity": "sha512-XnMRnHQ23piOVj2bzJqHrRrLg4r+F86fuBcwteKfbIjJrtGxb4z7tIvPVAe4B+4UVwo9G4Giuz5fmapcrnZ0OQ==","license": "MIT","dependencies": {- "@tanstack/virtual-core": "3.10.9"+ "@tanstack/virtual-core": "3.13.23"},"funding": {"type": "github",@@ -5734,10 +6346,23 @@"url": "https://github.com/sponsors/tannerlinsley"}},+ "node_modules/@tanstack/table-core": {+ "version": "8.21.3",+ "resolved": "https://registry.npmjs.org/@tanstack/table-core/-/table-core-8.21.3.tgz",+ "integrity": "sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/tannerlinsley"+ }+ },"node_modules/@tanstack/virtual-core": {- "version": "3.10.9",- "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.10.9.tgz",- "integrity": "sha512-kBknKOKzmeR7lN+vSadaKWXaLS0SZZG+oqpQ/k80Q6g9REn6zRHS/ZYdrIzHnpHgy/eWs00SujveUN/GJT2qTw==",+ "version": "3.13.23",+ "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.13.23.tgz",+ "integrity": "sha512-zSz2Z2HNyLjCplANTDyl3BcdQJc2k1+yyFoKhNRmCr7V7dY8o8q5m8uFTI1/Pg1kL+Hgrz6u3Xo6eFUB7l66cg==","license": "MIT","funding": {"type": "github",@@ -5780,7 +6405,6 @@"integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@babel/code-frame": "^7.10.4","@babel/runtime": "^7.12.5",@@ -5801,7 +6425,6 @@"integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==","dev": true,"license": "Apache-2.0",- "peer": true,"dependencies": {"dequal": "^2.0.3"}@@ -5812,7 +6435,6 @@"integrity": "sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@adobe/css-tools": "^4.4.0","aria-query": "^5.0.0",@@ -5832,8 +6454,7 @@"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.6.3.tgz","integrity": "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==","dev": true,- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/@testing-library/user-event": {"version": "14.6.1",@@ -5841,7 +6462,6 @@"integrity": "sha512-vq7fv0rnt+QTXgPxr5Hjc210p6YKq2kmdziLgnsZGgLJ9e6VAShx1pACLuRjd/AS/sr7phAR58OIIpf0LlmQNw==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">=12","npm": ">=6"@@ -5862,8 +6482,7 @@"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz","integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==","dev": true,- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/@types/babel__core": {"version": "7.20.5",@@ -5916,7 +6535,6 @@"integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@types/deep-eql": "*","assertion-error": "^2.0.1"@@ -5990,8 +6608,7 @@"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz","integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==","dev": true,- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/@types/doctrine": {"version": "0.0.9",@@ -6126,6 +6743,7 @@"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.16.tgz","integrity": "sha512-oh8AMIC4Y2ciKufU8hnKgs+ufgbA/dhPTACaZPM86AbwX9QwnFtSoPWEeRUj8fge+v6kFt78BXcDhAU1SrrAsw==","license": "MIT",+ "peer": true,"dependencies": {"@types/prop-types": "*","csstype": "^3.0.2"@@ -6137,6 +6755,7 @@"integrity": "sha512-P4t6saawp+b/dFrUr2cvkVsfvPguwsxtH6dNIYRllMsefqFzkZk5UIjzyDOv5g1dXIPdG4Sp1yCR4Z6RCUsG/Q==","devOptional": true,"license": "MIT",+ "peer": true,"peerDependencies": {"@types/react": "^18.0.0"}@@ -6184,6 +6803,7 @@"integrity": "sha512-QXwAlHlbcAwNlEEMKQS2RCgJsgXrTJdjXT08xEgbPFa2yYQgVjBymxP5DrfrE7X7iodSzd9qBUHUycdyVJTW1w==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@eslint-community/regexpp": "^4.10.0","@typescript-eslint/scope-manager": "8.34.0",@@ -6224,6 +6844,7 @@"integrity": "sha512-vxXJV1hVFx3IXz/oy2sICsJukaBrtDEQSBiV48/YIV5KWjX1dO+bcIr/kCPrW6weKXvsaGKFNlwH0v2eYdRRbA==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@typescript-eslint/scope-manager": "8.34.0","@typescript-eslint/types": "8.34.0",@@ -6495,7 +7116,6 @@"integrity": "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@types/chai": "^5.2.2","@vitest/spy": "3.2.4",@@ -6513,7 +7133,6 @@"integrity": "sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@vitest/spy": "3.2.4","estree-walker": "^3.0.3",@@ -6541,7 +7160,6 @@"integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@types/estree": "^1.0.0"}@@ -6552,7 +7170,6 @@"integrity": "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"tinyrainbow": "^2.0.0"},@@ -6566,7 +7183,6 @@"integrity": "sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"tinyspy": "^4.0.3"},@@ -6580,7 +7196,6 @@"integrity": "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@vitest/pretty-format": "3.2.4","loupe": "^3.1.4",@@ -6609,7 +7224,8 @@"version": "5.5.0","resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz","integrity": "sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/@xyflow/react": {"version": "12.4.4",@@ -6675,6 +7291,7 @@"integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==","dev": true,"license": "MIT",+ "peer": true,"bin": {"acorn": "bin/acorn"},@@ -6791,7 +7408,6 @@"integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==","dev": true,"license": "Apache-2.0",- "peer": true,"engines": {"node": ">= 0.4"}@@ -6840,7 +7456,6 @@"integrity": "sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"call-bind": "^1.0.7","define-properties": "^1.2.1",@@ -6921,7 +7536,6 @@"integrity": "sha512-p6Fx8B7b7ZhL/gmUsAy0D15WhvDccw3mnGNbZpi3pmeJdxtWsj2jEaI4Y6oo3XiHfzuSgPwKc04MYt6KgvC/wA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"call-bind": "^1.0.7","define-properties": "^1.2.1",@@ -7009,7 +7623,6 @@"integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">=12"}@@ -7020,7 +7633,6 @@"integrity": "sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"tslib": "^2.0.1"},@@ -7033,8 +7645,7 @@"resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.8.tgz","integrity": "sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==","dev": true,- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/asynckit": {"version": "0.4.0",@@ -7084,7 +7695,6 @@"integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==","dev": true,"license": "Apache-2.0",- "peer": true,"engines": {"node": ">= 0.4"}@@ -7186,7 +7796,6 @@"integrity": "sha512-aVNobHnJqLiUelTaHat9DZ1qM2w0C0Eym4LPI/3JxOnSokGVdsl1T1kN7TFvsEAD8G47A6VKQ0TVHqbBnYMJlQ==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"open": "^8.0.4"},@@ -7423,6 +8032,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"baseline-browser-mapping": "^2.8.9","caniuse-lite": "^1.0.30001746",@@ -7604,7 +8214,6 @@"integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"assertion-error": "^2.0.1","check-error": "^2.1.1",@@ -7675,7 +8284,6 @@"integrity": "sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">= 16"}@@ -8506,8 +9114,7 @@"resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz","integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==","dev": true,- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/cssesc": {"version": "3.0.0",@@ -8526,7 +9133,8 @@"version": "3.1.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz","integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/cva": {"name": "class-variance-authority",@@ -8598,6 +9206,7 @@"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"}@@ -8651,8 +9260,7 @@"resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz","integrity": "sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==","dev": true,- "license": "BSD-2-Clause",- "peer": true+ "license": "BSD-2-Clause"},"node_modules/data-view-buffer": {"version": "1.0.1",@@ -8768,7 +9376,6 @@"integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">=6"}@@ -8803,7 +9410,6 @@"integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">=8"}@@ -8934,8 +9540,7 @@"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz","integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==","dev": true,- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/dom-helpers": {"version": "5.2.1",@@ -9146,7 +9751,6 @@"integrity": "sha512-tpxqxncxnpw3c93u8n3VOzACmRFoVmWJqbWXvX/JfKbkhBw1oslgPrUfeSt2psuqyEJFD6N/9lg5i7bsKpoq+Q==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"call-bind": "^1.0.7","define-properties": "^1.2.1",@@ -9230,6 +9834,7 @@"dev": true,"hasInstallScript": true,"license": "MIT",+ "peer": true,"bin": {"esbuild": "bin/esbuild"},@@ -9271,7 +9876,6 @@"integrity": "sha512-H2/S7Pm8a9CL1uhp9OvjwrBh5Pvx0H8qVOxNu8Wed9Y7qv56MPtq+GGM8RJpq6glYJn9Wspr8uw7l55uyinNeg==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"debug": "^4.3.4"},@@ -9308,6 +9912,7 @@"deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@eslint-community/eslint-utils": "^4.2.0","@eslint-community/regexpp": "^4.6.1",@@ -9364,6 +9969,7 @@"integrity": "sha512-T75QYQVQX57jiNgpF9r1KegMICE94VYwoFQyMGhrvc+lB8YF2E/M/PYDaQe1AJcWaEgqLE+ErXV1Og/+6Vyzew==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"eslint-config-airbnb-base": "^15.0.0","object.assign": "^4.1.2",@@ -9386,6 +9992,7 @@"integrity": "sha512-xaX3z4ZZIcFLvh2oUNvcX5oEofXda7giYmuplVxoOg5A7EXJMrUyqRgR+mhDhPK8LZ4PttFOBvCYDbX3sUoUig==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"confusing-browser-globals": "^1.0.10","object.assign": "^4.1.2",@@ -9416,6 +10023,7 @@"integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==","dev": true,"license": "MIT",+ "peer": true,"bin": {"eslint-config-prettier": "bin/cli.js"},@@ -9515,6 +10123,7 @@"integrity": "sha512-ixmkI62Rbc2/w8Vfxyh1jQRTdRTF52VxwRVHl/ykPAmqG+Nb7/kNn+byLP0LxPgI7zWA16Jt82SybJInmMia3A==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@rtsao/scc": "^1.1.0","array-includes": "^3.1.8",@@ -9644,7 +10253,6 @@"integrity": "sha512-EsTAnj9fLVr/GZleBLFbj/sSuXeWmp1eXIN60ceYnZveqEaUCyW4X+Vh4WTdUhCkW4xutXYqTXCUSyqD4rB75w==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"array-includes": "^3.1.8","array.prototype.findlast": "^1.2.5",@@ -9678,6 +10286,7 @@"integrity": "sha512-QzliNJq4GinDBcD8gPB5v0wh6g8q3SUi6EFF0x8N/BL9PoVs0atuGc47ozMRyOWAKdwaZ5OnbOEa3WR+dSGKuQ==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=10"},@@ -9701,7 +10310,6 @@"integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==","dev": true,"license": "Apache-2.0",- "peer": true,"dependencies": {"esutils": "^2.0.2"},@@ -9715,7 +10323,6 @@"integrity": "sha512-U7WjGVG9sH8tvjW5SmGbQuui75FiyjAX72HX15DwBBwF9dNiQZRQAg9nnPhYy+TUnE0+VcrttuvNI8oSxZcocA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"is-core-module": "^2.13.0","path-parse": "^1.0.7",@@ -9734,7 +10341,6 @@"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==","dev": true,"license": "ISC",- "peer": true,"bin": {"semver": "bin/semver.js"}@@ -9896,7 +10502,6 @@"integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==","dev": true,"license": "BSD-2-Clause",- "peer": true,"bin": {"esparse": "bin/esparse.js","esvalidate": "bin/esvalidate.js"@@ -10927,6 +11532,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"@babel/runtime": "^7.23.2"},@@ -11020,7 +11626,6 @@"integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">=8"}@@ -11288,7 +11893,6 @@"integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==","dev": true,"license": "MIT",- "peer": true,"bin": {"is-docker": "cli.js"},@@ -11610,7 +12214,6 @@"integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"is-docker": "^2.0.0"},@@ -11645,7 +12248,6 @@"resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz","integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==","license": "MIT",- "peer": true,"funding": {"type": "GitHub Sponsors ❤","url": "https://github.com/sponsors/dmonad"@@ -11657,7 +12259,6 @@"integrity": "sha512-x4WH0BWmrMmg4oHHl+duwubhrvczGlyuGAZu3nvrf0UXOfPu8IhZObFEr7DE/iv01YgVZrsOiRcqw2srkKEDIA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"define-data-property": "^1.1.4","es-object-atoms": "^1.0.0",@@ -11807,7 +12408,6 @@"integrity": "sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"array-includes": "^3.1.6","array.prototype.flat": "^1.3.1",@@ -11842,8 +12442,7 @@"resolved": "https://registry.npmjs.org/language-subtag-registry/-/language-subtag-registry-0.3.23.tgz","integrity": "sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ==","dev": true,- "license": "CC0-1.0",- "peer": true+ "license": "CC0-1.0"},"node_modules/language-tags": {"version": "1.0.9",@@ -11851,7 +12450,6 @@"integrity": "sha512-MbjN408fEndfiQXbFQ1vnd+1NoLDsnQW41410oQBXiyXDMYH5z505juWa4KUE1LqxRC7DgOgZDbKLxHIwm27hA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"language-subtag-registry": "^0.3.20"},@@ -11884,7 +12482,6 @@"resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.102.tgz","integrity": "sha512-g70kydI0I1sZU0ChO8mBbhw0oUW/8U0GHzygpvEIx8k+jgOpqnTSb/E+70toYVqHxBhrERD21TwD5QcZJQ40ZQ==","license": "MIT",- "peer": true,"dependencies": {"isomorphic.js": "^0.2.4"},@@ -12215,8 +12812,7 @@"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz","integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==","dev": true,- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/lru-cache": {"version": "5.1.1",@@ -12243,7 +12839,6 @@"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==","dev": true,"license": "MIT",- "peer": true,"bin": {"lz-string": "bin/bin.js"}@@ -12935,7 +13530,6 @@"integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">=4"}@@ -13284,7 +13878,6 @@"integrity": "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"define-lazy-prop": "^2.0.0","is-docker": "^2.1.1",@@ -13553,7 +14146,6 @@"integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">= 14.16"}@@ -13714,6 +14306,7 @@"integrity": "sha512-e9MewbtFo+Fevyuxn/4rrcDAaq0IYxPGLvObpQjiZBMAzB9IGmzlnG9RZy3FFas+eBMu2vA0CszMeduow5dIuQ==","dev": true,"license": "MIT",+ "peer": true,"bin": {"prettier": "bin/prettier.cjs"},@@ -13830,7 +14423,6 @@"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"ansi-regex": "^5.0.1","ansi-styles": "^5.0.0",@@ -13846,7 +14438,6 @@"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">=10"},@@ -13859,8 +14450,7 @@"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz","integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==","dev": true,- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/prismjs": {"version": "1.30.0",@@ -14091,6 +14681,7 @@"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz","integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0"},@@ -14118,6 +14709,7 @@"resolved": "https://registry.npmjs.org/react/-/react-16.14.0.tgz","integrity": "sha512-0X2CImDkJGApiAlcf0ODKIneSwBPhqJawOa5wCtKbu7ZECrmS26NvtSILynQ66cgkT/RJ4LidJOc3bUESwmU8g==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0","object-assign": "^4.1.1",@@ -14222,6 +14814,7 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz","integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0","scheduler": "^0.23.2"@@ -14272,6 +14865,7 @@"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.3.tgz","integrity": "sha512-IK18V6GVbab4TAo1/cz3kqajxbDPGofdF0w7VHdCo0Nt8PrPlOZcuuDq9YYIV1BtjcX78x0XsldbQRQnQXWXmw==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -14521,7 +15115,6 @@"integrity": "sha512-YTUo+Flmw4ZXiWfQKGcwwc11KnoRAYgzAE2E7mXKCjSviTKShtxBsN6YUUBB2gtaBzKzeKunxhUwNHQuRryhWA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"ast-types": "^0.16.1","esprima": "~4.0.0",@@ -14539,7 +15132,6 @@"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==","dev": true,"license": "BSD-3-Clause",- "peer": true,"engines": {"node": ">=0.10.0"}@@ -14556,7 +15148,6 @@"integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"indent-string": "^4.0.0","strip-indent": "^3.0.0"@@ -14571,7 +15162,6 @@"integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"min-indent": "^1.0.0"},@@ -14786,6 +15376,7 @@"integrity": "sha512-3GuObel8h7Kqdjt0gxkEzaifHTqLVW56Y/bjN7PSQtkKr0w3V/QYSdt6QWYtd7A1xUtYQigtdUfgj1RvWVtorw==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@types/estree": "1.0.8"},@@ -15304,7 +15895,6 @@"integrity": "sha512-o7+c9bW6zpAdJHTtujeePODAhkuicdAryFsfVKwA+wGw89wJ4GTY484WTucM9hLtDEOpOvI+aHnzqnC5lHp4Rg==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"call-bind": "^1.0.7","define-properties": "^1.2.1",@@ -15320,7 +15910,6 @@"integrity": "sha512-NUdh0aDavY2og7IbBPenWqR9exH+E26Sv8e0/eTe1tltDGZL+GtBkDAnnyBtmekfK6/Dq3MkcGtzXFEd1LQrtg==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"call-bind": "^1.0.7","define-properties": "^1.2.1",@@ -15348,7 +15937,6 @@"integrity": "sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"define-properties": "^1.1.3","es-abstract": "^1.17.5"@@ -15569,7 +16157,8 @@"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.14.tgz","integrity": "sha512-b7pCxjGO98LnxVkKjaZSDeNuljC4ueKUddjENJOADtubtdo8llTaJy7HwBMeLNSSo2N5QIAgklslK1+Ir8r6CA==","dev": true,- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/tapable": {"version": "2.2.1",@@ -15673,7 +16262,6 @@"integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">=14.0.0"}@@ -15684,7 +16272,6 @@"integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">=14.0.0"}@@ -15979,6 +16566,7 @@"integrity": "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==","devOptional": true,"license": "Apache-2.0",+ "peer": true,"bin": {"tsc": "bin/tsc","tsserver": "bin/tsserver"@@ -16363,6 +16951,7 @@"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"esbuild": "^0.25.0","fdir": "^6.4.4",@@ -16779,7 +17368,6 @@"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">=10.0.0"},@@ -16856,6 +17444,7 @@"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.6.1.tgz","integrity": "sha512-7r0XPzioN/Q9kXBro/XPnA6kznR73DHq+GXh5ON7ZozRO6aMjbmiBuKste2wslTFkC5d1dw0GooOCepZXJ2SAg==","license": "ISC",+ "peer": true,"bin": {"yaml": "bin.mjs"},@@ -17006,6 +17595,7 @@"resolved": "https://registry.npmjs.org/zod/-/zod-3.24.1.tgz","integrity": "sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A==","license": "MIT",+ "peer": true,"funding": {"url": "https://github.com/sponsors/colinhacks"}diff --git a/frontend/package.json b/frontend/package.jsonindex 93469e6e4f..b3295ae3ef 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -42,7 +42,9 @@"@radix-ui/react-alert-dialog": "^1.1.3","@radix-ui/react-checkbox": "^1.1.3","@radix-ui/react-collapsible": "^1.1.2",+ "@radix-ui/react-context-menu": "^2.2.16","@radix-ui/react-dialog": "^1.1.3",+ "@radix-ui/react-direction": "^1.1.1","@radix-ui/react-dropdown-menu": "^2.1.3","@radix-ui/react-hover-card": "^1.1.3","@radix-ui/react-label": "^2.1.1",@@ -62,6 +64,8 @@"@sindresorhus/slugify": "^2.2.1","@tanstack/react-query": "^5.62.7","@tanstack/react-router": "^1.95.1",+ "@tanstack/react-table": "^8.21.3",+ "@tanstack/react-virtual": "^3.13.23","@tanstack/virtual-file-routes": "^1.87.6","@tanstack/zod-adapter": "^1.91.0","@types/dagre": "^0.7.52",diff --git a/frontend/src/components/v3/generic/DataGrid/compose-refs.ts b/frontend/src/components/v3/generic/DataGrid/compose-refs.tsnew file mode 100644index 0000000000..f17a11dee2--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/compose-refs.ts@@ -0,0 +1,72 @@+/**+ * @see https://github.com/radix-ui/primitives/blob/main/packages/react/compose-refs/src/compose-refs.tsx+ */++import * as React from "react";++type PossibleRef<T> = React.Ref<T> | undefined;++/**+ * Set a given ref to a given value+ * This utility takes care of different types of refs: callback refs and RefObject(s)+ */+// eslint-disable-next-line consistent-return+function setRef<T>(ref: PossibleRef<T>, value: T) {+ if (typeof ref === "function") {+ return ref(value);+ }++ if (ref !== null && ref !== undefined) {+ // @ts-expect-error -- React 19 makes RefObject.current read-only, but this vendored Radix utility needs to write it+ // eslint-disable-next-line no-param-reassign+ ref.current = value;+ }+}++/**+ * A utility to compose multiple refs together+ * Accepts callback refs and RefObject(s)+ */+function composeRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {+ // eslint-disable-next-line consistent-return+ return (node) => {+ let hasCleanup = false;+ const cleanups = refs.map((ref) => {+ const cleanup = setRef(ref, node);+ if (!hasCleanup && typeof cleanup === "function") {+ hasCleanup = true;+ }+ return cleanup;+ });++ // React <19 will log an error to the console if a callback ref returns a+ // value. We don't use ref cleanups internally so this will only happen if a+ // user's ref callback returns a value, which we only expect if they are+ // using the cleanup functionality added in React 19.+ if (hasCleanup) {+ return () => {+ // eslint-disable-next-line no-plusplus+ for (let i = 0; i < cleanups.length; i++) {+ const cleanup = cleanups[i];+ if (typeof cleanup === "function") {+ // @ts-expect-error -- cleanup type narrowing issue with React 19 ref callback return types+ cleanup();+ } else {+ setRef(refs[i], null);+ }+ }+ };+ }+ };+}++/**+ * A custom hook that composes multiple refs+ * Accepts callback refs and RefObject(s)+ */+function useComposedRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {+ // biome-ignore lint/correctness/useExhaustiveDependencies: we want to memoize by all values+ return React.useCallback(composeRefs(...refs), refs);+}++export { composeRefs, useComposedRefs };diff --git a/frontend/src/components/v3/generic/DataGrid/data-grid-cell-variants.tsx b/frontend/src/components/v3/generic/DataGrid/data-grid-cell-variants.tsxnew file mode 100644index 0000000000..cb0d047b15--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/data-grid-cell-variants.tsx@@ -0,0 +1,2019 @@+// eslint-disable-next-line @typescript-eslint/ban-ts-comment+// @ts-nocheck -- vendored Dice UI component, large file with complex generic types pending cleanup+/* eslint-disable no-restricted-syntax, no-nested-ternary, no-continue, no-param-reassign, @typescript-eslint/no-shadow, jsx-a11y/no-noninteractive-element-interactions, jsx-a11y/role-supports-aria-props */++import * as React from "react";+import { Check, Upload, X } from "lucide-react";+import { toast } from "sonner";++import { Badge } from "@app/components/v3/generic/Badge";+import { Button } from "@app/components/v3/generic/Button";+import { Calendar } from "@app/components/v3/generic/Calendar";+import { Checkbox } from "@app/components/v3/generic/Checkbox";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+ CommandSeparator+} from "@app/components/v3/generic/Command";+import { Popover, PopoverAnchor, PopoverContent } from "@app/components/v3/generic/Popover";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@app/components/v3/generic/Select";+import { Skeleton } from "@app/components/v3/generic/Skeleton";+import { TextArea as Textarea } from "@app/components/v3/generic/TextArea";+import { cn } from "@app/components/v3/utils";++import { useBadgeOverflow } from "./hooks/use-badge-overflow";+import { useDebouncedCallback } from "./hooks/use-debounced-callback";+import { DataGridCellWrapper } from "./data-grid-cell-wrapper";+import type { DataGridCellProps, FileCellData } from "./data-grid-types";+import {+ formatDateForDisplay,+ formatDateToString,+ formatFileSize,+ getCellKey,+ getFileIcon,+ getLineCount,+ getUrlHref,+ parseLocalDate+} from "./data-grid-utils";++export function ShortTextCell<TData>({+ cell,+ tableMeta,+ rowIndex,+ columnId,+ rowHeight,+ isEditing,+ isFocused,+ isSelected,+ isSearchMatch,+ isActiveSearchMatch,+ isDirty,+ readOnly+}: DataGridCellProps<TData>) {+ const initialValue = cell.getValue() as string;+ const [value, setValue] = React.useState(initialValue);+ const cellRef = React.useRef<HTMLDivElement>(null);+ const containerRef = React.useRef<HTMLDivElement>(null);+ const prefilledRef = React.useRef<string | null>(null);++ const prevInitialValueRef = React.useRef(initialValue);+ if (initialValue !== prevInitialValueRef.current) {+ prevInitialValueRef.current = initialValue;+ setValue(initialValue);+ if (cellRef.current && !isEditing) {+ cellRef.current.textContent = initialValue ?? "";+ }+ }++ // When commit + discard are batched by React 18, the intermediate initialValue+ // change is never seen, so prevInitialValueRef misses it and value stays stale.+ // Reset value to match initialValue when not editing to prevent showing stale data.+ if (!isEditing && value !== initialValue) {+ setValue(initialValue);+ }++ const onBlur = React.useCallback(() => {+ // Read the current value directly from the DOM to avoid stale state+ const currentValue = cellRef.current?.textContent ?? "";+ if (!readOnly && currentValue !== initialValue) {+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: currentValue });+ }+ tableMeta?.onCellEditingStop?.();+ }, [tableMeta, rowIndex, columnId, initialValue, readOnly]);++ const onInput = React.useCallback(+ (event: React.FormEvent<HTMLDivElement>) => {+ const currentValue = event.currentTarget.textContent ?? "";+ setValue(currentValue);+ if (!readOnly) {+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: currentValue });+ }+ },+ [readOnly, tableMeta, rowIndex, columnId]+ );++ const onWrapperKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ if (isEditing) {+ if (event.key === "Enter") {+ event.preventDefault();+ tableMeta?.onCellEditingStop?.({ moveToNextRow: true });+ } else if (event.key === "Tab") {+ event.preventDefault();+ tableMeta?.onCellEditingStop?.({+ direction: event.shiftKey ? "left" : "right"+ });+ } else if (event.key === "Escape") {+ event.preventDefault();+ setValue(initialValue);+ // Revert the data to the original value since onInput may have committed intermediate edits+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: initialValue });+ cellRef.current?.blur();+ }+ } else if (isFocused && event.key.length === 1 && !event.ctrlKey && !event.metaKey) {+ // Handle typing to pre-fill the value when editing starts+ prefilledRef.current = event.key;+ setValue(event.key);++ queueMicrotask(() => {+ if (cellRef.current && cellRef.current.contentEditable === "true") {+ cellRef.current.textContent = event.key;+ const range = document.createRange();+ const selection = window.getSelection();+ range.selectNodeContents(cellRef.current);+ range.collapse(false);+ selection?.removeAllRanges();+ selection?.addRange(range);+ }+ });+ }+ },+ [isEditing, isFocused, initialValue, tableMeta, rowIndex, columnId]+ );++ React.useEffect(() => {+ if (isEditing && cellRef.current) {+ // Use pre-filled character if user typed to start editing,+ // otherwise always sync from initialValue to prevent stale values+ // (e.g. after batched commit+discard where prevInitialValueRef misses the change)+ const prefilled = prefilledRef.current;+ prefilledRef.current = null;+ const editValue = prefilled ?? initialValue ?? "";++ setValue(editValue);+ cellRef.current.textContent = editValue;+ cellRef.current.focus();++ if (cellRef.current.textContent) {+ const range = document.createRange();+ const selection = window.getSelection();+ range.selectNodeContents(cellRef.current);+ range.collapse(false);+ selection?.removeAllRanges();+ selection?.addRange(range);+ }+ }+ // Only run on edit start — not on every value change (which moves cursor to end)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [isEditing]);++ const isNull = value === null || value === undefined;+ const displayValue = !isEditing ? (value ?? "") : "";++ return (+ <DataGridCellWrapper<TData>+ ref={containerRef}+ cell={cell}+ tableMeta={tableMeta}+ rowIndex={rowIndex}+ columnId={columnId}+ rowHeight={rowHeight}+ isEditing={isEditing}+ isFocused={isFocused}+ isSelected={isSelected}+ isSearchMatch={isSearchMatch}+ isActiveSearchMatch={isActiveSearchMatch}+ isDirty={isDirty}+ readOnly={readOnly}+ onKeyDown={onWrapperKeyDown}+ >+ {isNull && !isEditing ? (+ <span data-slot="grid-cell-content" className="text-xs text-muted/50 italic select-none">+ NULL+ </span>+ ) : (+ <div+ role="textbox"+ data-slot="grid-cell-content"+ contentEditable={isEditing}+ tabIndex={-1}+ ref={cellRef}+ onBlur={onBlur}+ onInput={onInput}+ suppressContentEditableWarning+ className={cn("size-full outline-none", {+ "overflow-hidden": !isEditing,+ "no-scrollbar overflow-x-auto": isEditing,+ "whitespace-nowrap **:inline **:whitespace-nowrap [&_br]:hidden": isEditing+ })}+ >+ {displayValue}+ </div>+ )}+ </DataGridCellWrapper>+ );+}++export function LongTextCell<TData>({+ cell,+ tableMeta,+ rowIndex,+ columnId,+ rowHeight,+ isFocused,+ isEditing,+ isSelected,+ isSearchMatch,+ isActiveSearchMatch,+ isDirty,+ readOnly+}: DataGridCellProps<TData>) {+ const initialValue = cell.getValue() as string;+ const [value, setValue] = React.useState(initialValue ?? "");+ const textareaRef = React.useRef<HTMLTextAreaElement>(null);+ const containerRef = React.useRef<HTMLDivElement>(null);+ const pendingCharRef = React.useRef<string | null>(null);+ const sideOffset = -(containerRef.current?.clientHeight ?? 0);++ const prevInitialValueRef = React.useRef(initialValue);+ if (initialValue !== prevInitialValueRef.current) {+ prevInitialValueRef.current = initialValue;+ setValue(initialValue ?? "");+ }++ if (!isEditing && value !== (initialValue ?? "")) {+ setValue(initialValue ?? "");+ }++ const debouncedSave = useDebouncedCallback((newValue: string) => {+ if (!readOnly) {+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: newValue });+ }+ }, 300);++ const onSave = React.useCallback(() => {+ // Immediately save any pending changes and close the popover+ if (!readOnly && value !== initialValue) {+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value });+ }+ tableMeta?.onCellEditingStop?.();+ }, [tableMeta, value, initialValue, rowIndex, columnId, readOnly]);++ const onCancel = React.useCallback(() => {+ // Restore the original value+ setValue(initialValue ?? "");+ if (!readOnly) {+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: initialValue });+ }+ tableMeta?.onCellEditingStop?.();+ }, [tableMeta, initialValue, rowIndex, columnId, readOnly]);++ const onOpenChange = React.useCallback(+ (open: boolean) => {+ if (open && !readOnly) {+ tableMeta?.onCellEditingStart?.(rowIndex, columnId);+ } else {+ // Immediately save any pending changes when closing+ if (!readOnly && value !== initialValue) {+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value });+ }+ tableMeta?.onCellEditingStop?.();+ }+ },+ [tableMeta, value, initialValue, rowIndex, columnId, readOnly]+ );++ const onOpenAutoFocus: NonNullable<+ React.ComponentProps<typeof PopoverContent>["onOpenAutoFocus"]+ > = React.useCallback((event) => {+ event.preventDefault();+ if (textareaRef.current) {+ textareaRef.current.focus();+ const { length } = textareaRef.current.value;+ textareaRef.current.setSelectionRange(length, length);++ // Insert pending character using execCommand so it's part of undo history+ // Use requestAnimationFrame to ensure focus has fully settled+ if (pendingCharRef.current) {+ const char = pendingCharRef.current;+ pendingCharRef.current = null;+ requestAnimationFrame(() => {+ if (textareaRef.current && document.activeElement === textareaRef.current) {+ document.execCommand("insertText", false, char);+ textareaRef.current.scrollTop = textareaRef.current.scrollHeight;+ }+ });+ } else {+ textareaRef.current.scrollTop = textareaRef.current.scrollHeight;+ }+ }+ }, []);++ const onWrapperKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ if (+ isFocused &&+ !isEditing &&+ !readOnly &&+ event.key.length === 1 &&+ !event.ctrlKey &&+ !event.metaKey+ ) {+ // Store the character to be inserted after textarea focuses+ // This ensures it's part of the textarea's undo history+ pendingCharRef.current = event.key;+ }+ },+ [isFocused, isEditing, readOnly]+ );++ const onBlur = React.useCallback(() => {+ // Immediately save any pending changes on blur+ if (!readOnly && value !== initialValue) {+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value });+ }+ tableMeta?.onCellEditingStop?.();+ }, [tableMeta, value, initialValue, rowIndex, columnId, readOnly]);++ const onChange = React.useCallback(+ (event: React.ChangeEvent<HTMLTextAreaElement>) => {+ const newValue = event.target.value;+ setValue(newValue);+ debouncedSave(newValue);+ },+ [debouncedSave]+ );++ const onKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLTextAreaElement>) => {+ if (event.key === "Escape") {+ event.preventDefault();+ onCancel();+ } else if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) {+ event.preventDefault();+ onSave();+ } else if (event.key === "Tab") {+ event.preventDefault();+ // Save any pending changes+ if (value !== initialValue) {+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value });+ }+ tableMeta?.onCellEditingStop?.({+ direction: event.shiftKey ? "left" : "right"+ });+ return;+ }+ // Stop propagation to prevent grid navigation+ event.stopPropagation();+ },+ [onSave, onCancel, value, initialValue, tableMeta, rowIndex, columnId]+ );++ return (+ <Popover open={isEditing} onOpenChange={onOpenChange}>+ <PopoverAnchor asChild>+ <DataGridCellWrapper<TData>+ ref={containerRef}+ cell={cell}+ tableMeta={tableMeta}+ rowIndex={rowIndex}+ columnId={columnId}+ rowHeight={rowHeight}+ isEditing={isEditing}+ isFocused={isFocused}+ isSelected={isSelected}+ isSearchMatch={isSearchMatch}+ isActiveSearchMatch={isActiveSearchMatch}+ isDirty={isDirty}+ readOnly={readOnly}+ onKeyDown={onWrapperKeyDown}+ >+ <span data-slot="grid-cell-content">{value}</span>+ </DataGridCellWrapper>+ </PopoverAnchor>+ <PopoverContent+ data-grid-cell-editor=""+ align="start"+ side="bottom"+ sideOffset={sideOffset}+ className="w-[400px] rounded-none p-0"+ onOpenAutoFocus={onOpenAutoFocus}+ >+ <Textarea+ placeholder="Enter text..."+ className="max-h-[300px] min-h-[150px] resize-none overflow-y-auto rounded-none border-0 shadow-none focus-visible:ring-1 focus-visible:ring-ring"+ ref={textareaRef}+ value={value}+ onBlur={onBlur}+ onChange={onChange}+ onKeyDown={onKeyDown}+ />+ </PopoverContent>+ </Popover>+ );+}++export function NumberCell<TData>({+ cell,+ tableMeta,+ rowIndex,+ columnId,+ rowHeight,+ isFocused,+ isEditing,+ isSelected,+ isSearchMatch,+ isActiveSearchMatch,+ isDirty,+ readOnly+}: DataGridCellProps<TData>) {+ const initialValue = cell.getValue() as number;+ const [value, setValue] = React.useState(String(initialValue ?? ""));+ const inputRef = React.useRef<HTMLInputElement>(null);+ const containerRef = React.useRef<HTMLDivElement>(null);++ const cellOpts = cell.column.columnDef.meta?.cell;+ const numberCellOpts = cellOpts?.variant === "number" ? cellOpts : null;+ const min = numberCellOpts?.min;+ const max = numberCellOpts?.max;+ const step = numberCellOpts?.step;++ const prevIsEditingRef = React.useRef(isEditing);++ const prevInitialValueRef = React.useRef(initialValue);+ if (initialValue !== prevInitialValueRef.current) {+ prevInitialValueRef.current = initialValue;+ setValue(String(initialValue ?? ""));+ }++ const onBlur = React.useCallback(() => {+ const numValue = value === "" ? null : Number(value);+ if (!readOnly && numValue !== initialValue) {+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: numValue });+ }+ tableMeta?.onCellEditingStop?.();+ }, [tableMeta, rowIndex, columnId, initialValue, value, readOnly]);++ const onChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => {+ setValue(event.target.value);+ }, []);++ const onWrapperKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ if (isEditing) {+ if (event.key === "Enter") {+ event.preventDefault();+ const numValue = value === "" ? null : Number(value);+ if (numValue !== initialValue) {+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: numValue });+ }+ tableMeta?.onCellEditingStop?.({ moveToNextRow: true });+ } else if (event.key === "Tab") {+ event.preventDefault();+ const numValue = value === "" ? null : Number(value);+ if (numValue !== initialValue) {+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: numValue });+ }+ tableMeta?.onCellEditingStop?.({+ direction: event.shiftKey ? "left" : "right"+ });+ } else if (event.key === "Escape") {+ event.preventDefault();+ setValue(String(initialValue ?? ""));+ inputRef.current?.blur();+ }+ } else if (isFocused) {+ // Handle Backspace to start editing with empty value+ if (event.key === "Backspace") {+ setValue("");+ } else if (event.key.length === 1 && !event.ctrlKey && !event.metaKey) {+ // Handle typing to pre-fill the value when editing starts+ setValue(event.key);+ }+ }+ },+ [isEditing, isFocused, initialValue, tableMeta, rowIndex, columnId, value]+ );++ React.useEffect(() => {+ const wasEditing = prevIsEditingRef.current;+ prevIsEditingRef.current = isEditing;++ // Only focus when we start editing (transition from false to true)+ if (isEditing && !wasEditing && inputRef.current) {+ inputRef.current.focus();+ }+ }, [isEditing]);++ return (+ <DataGridCellWrapper<TData>+ ref={containerRef}+ cell={cell}+ tableMeta={tableMeta}+ rowIndex={rowIndex}+ columnId={columnId}+ rowHeight={rowHeight}+ isEditing={isEditing}+ isFocused={isFocused}+ isSelected={isSelected}+ isSearchMatch={isSearchMatch}+ isActiveSearchMatch={isActiveSearchMatch}+ isDirty={isDirty}+ readOnly={readOnly}+ onKeyDown={onWrapperKeyDown}+ >+ {isEditing ? (+ <input+ type="number"+ ref={inputRef}+ value={value}+ min={min}+ max={max}+ step={step}+ className="w-full [appearance:textfield] border-none bg-transparent p-0 outline-none [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"+ onBlur={onBlur}+ onChange={onChange}+ />+ ) : (+ <span data-slot="grid-cell-content">{value}</span>+ )}+ </DataGridCellWrapper>+ );+}++export function UrlCell<TData>({+ cell,+ tableMeta,+ rowIndex,+ columnId,+ rowHeight,+ isEditing,+ isFocused,+ isSelected,+ isSearchMatch,+ isActiveSearchMatch,+ isDirty,+ readOnly+}: DataGridCellProps<TData>) {+ const initialValue = cell.getValue() as string;+ const [value, setValue] = React.useState(initialValue ?? "");+ const cellRef = React.useRef<HTMLDivElement>(null);+ const containerRef = React.useRef<HTMLDivElement>(null);+ const prefilledRef = React.useRef<string | null>(null);++ const prevInitialValueRef = React.useRef(initialValue);+ if (initialValue !== prevInitialValueRef.current) {+ prevInitialValueRef.current = initialValue;+ setValue(initialValue ?? "");+ if (cellRef.current && !isEditing) {+ cellRef.current.textContent = initialValue ?? "";+ }+ }++ if (!isEditing && value !== (initialValue ?? "")) {+ setValue(initialValue ?? "");+ }++ const onBlur = React.useCallback(() => {+ const currentValue = cellRef.current?.textContent?.trim() ?? "";++ if (!readOnly && currentValue !== initialValue) {+ tableMeta?.onDataUpdate?.({+ rowIndex,+ columnId,+ value: currentValue || null+ });+ }+ tableMeta?.onCellEditingStop?.();+ }, [tableMeta, rowIndex, columnId, initialValue, readOnly]);++ const onInput = React.useCallback(+ (event: React.FormEvent<HTMLDivElement>) => {+ const currentValue = event.currentTarget.textContent ?? "";+ setValue(currentValue);+ if (!readOnly) {+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: currentValue || null });+ }+ },+ [readOnly, tableMeta, rowIndex, columnId]+ );++ const onWrapperKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ if (isEditing) {+ if (event.key === "Enter") {+ event.preventDefault();+ tableMeta?.onCellEditingStop?.({ moveToNextRow: true });+ } else if (event.key === "Tab") {+ event.preventDefault();+ tableMeta?.onCellEditingStop?.({+ direction: event.shiftKey ? "left" : "right"+ });+ } else if (event.key === "Escape") {+ event.preventDefault();+ setValue(initialValue ?? "");+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: initialValue });+ cellRef.current?.blur();+ }+ } else if (+ isFocused &&+ !readOnly &&+ event.key.length === 1 &&+ !event.ctrlKey &&+ !event.metaKey+ ) {+ // Handle typing to pre-fill the value when editing starts+ prefilledRef.current = event.key;+ setValue(event.key);++ queueMicrotask(() => {+ if (cellRef.current && cellRef.current.contentEditable === "true") {+ cellRef.current.textContent = event.key;+ const range = document.createRange();+ const selection = window.getSelection();+ range.selectNodeContents(cellRef.current);+ range.collapse(false);+ selection?.removeAllRanges();+ selection?.addRange(range);+ }+ });+ }+ },+ [isEditing, isFocused, initialValue, tableMeta, rowIndex, columnId, readOnly]+ );++ const onLinkClick = React.useCallback(+ (event: React.MouseEvent<HTMLAnchorElement>) => {+ if (isEditing) {+ event.preventDefault();+ return;+ }++ // Check if URL was rejected due to dangerous protocol+ const href = getUrlHref(value);+ if (!href) {+ event.preventDefault();+ toast.error("Invalid URL", {+ description: "URL contains a dangerous protocol (javascript:, data:, vbscript:, or file:)"+ });+ return;+ }++ // Stop propagation to prevent grid from interfering with link navigation+ event.stopPropagation();+ },+ [isEditing, value]+ );++ React.useEffect(() => {+ if (isEditing && cellRef.current) {+ const prefilled = prefilledRef.current;+ prefilledRef.current = null;+ const editValue = prefilled ?? initialValue ?? "";++ setValue(editValue);+ cellRef.current.textContent = editValue;+ cellRef.current.focus();++ if (cellRef.current.textContent) {+ const range = document.createRange();+ const selection = window.getSelection();+ range.selectNodeContents(cellRef.current);+ range.collapse(false);+ selection?.removeAllRanges();+ selection?.addRange(range);+ }+ }+ // Only run on edit start — not on every value change (which moves cursor to end)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [isEditing]);++ const displayValue = !isEditing ? (value ?? "") : "";+ const urlHref = displayValue ? getUrlHref(displayValue) : "";+ const isDangerousUrl = displayValue && !urlHref;++ return (+ <DataGridCellWrapper<TData>+ ref={containerRef}+ cell={cell}+ tableMeta={tableMeta}+ rowIndex={rowIndex}+ columnId={columnId}+ rowHeight={rowHeight}+ isEditing={isEditing}+ isFocused={isFocused}+ isSelected={isSelected}+ isSearchMatch={isSearchMatch}+ isActiveSearchMatch={isActiveSearchMatch}+ isDirty={isDirty}+ readOnly={readOnly}+ onKeyDown={onWrapperKeyDown}+ >+ {!isEditing && displayValue ? (+ <div data-slot="grid-cell-content" className="size-full overflow-hidden">+ <a+ data-focused={isFocused && !isDangerousUrl ? "" : undefined}+ data-invalid={isDangerousUrl ? "" : undefined}+ href={urlHref}+ target="_blank"+ rel="noopener noreferrer"+ className="data-invalid:text-destructive data-invalid:decoration-destructive/50 data-invalid:hover:decoration-destructive/70 truncate text-primary underline decoration-primary/30 underline-offset-2 hover:decoration-primary/60 data-focused:text-foreground data-focused:decoration-foreground/50 data-focused:hover:decoration-foreground/70 data-invalid:cursor-not-allowed"+ onClick={onLinkClick}+ >+ {displayValue}+ </a>+ </div>+ ) : (+ <div+ role="textbox"+ data-slot="grid-cell-content"+ contentEditable={isEditing}+ tabIndex={-1}+ ref={cellRef}+ onBlur={onBlur}+ onInput={onInput}+ suppressContentEditableWarning+ className={cn("size-full outline-none", {+ "overflow-hidden": !isEditing,+ "no-scrollbar overflow-x-auto": isEditing,+ "whitespace-nowrap **:inline **:whitespace-nowrap [&_br]:hidden": isEditing+ })}+ >+ {displayValue}+ </div>+ )}+ </DataGridCellWrapper>+ );+}++export function CheckboxCell<TData>({+ cell,+ tableMeta,+ rowIndex,+ columnId,+ rowHeight,+ isFocused,+ isSelected,+ isSearchMatch,+ isActiveSearchMatch,+ readOnly+}: Omit<DataGridCellProps<TData>, "isEditing">) {+ const initialValue = cell.getValue() as boolean;+ const [value, setValue] = React.useState(Boolean(initialValue));+ const containerRef = React.useRef<HTMLDivElement>(null);++ const prevInitialValueRef = React.useRef(initialValue);+ if (initialValue !== prevInitialValueRef.current) {+ prevInitialValueRef.current = initialValue;+ setValue(Boolean(initialValue));+ }++ const onCheckedChange = React.useCallback(+ (checked: boolean) => {+ if (readOnly) return;+ setValue(checked);+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: checked });+ },+ [tableMeta, rowIndex, columnId, readOnly]+ );++ const onWrapperKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ if (isFocused && !readOnly && (event.key === " " || event.key === "Enter")) {+ event.preventDefault();+ event.stopPropagation();+ onCheckedChange(!value);+ } else if (isFocused && event.key === "Tab") {+ event.preventDefault();+ tableMeta?.onCellEditingStop?.({+ direction: event.shiftKey ? "left" : "right"+ });+ }+ },+ [isFocused, value, onCheckedChange, tableMeta, readOnly]+ );++ const onWrapperClick = React.useCallback(+ (event: React.MouseEvent) => {+ if (isFocused && !readOnly) {+ event.preventDefault();+ event.stopPropagation();+ onCheckedChange(!value);+ }+ },+ [isFocused, value, onCheckedChange, readOnly]+ );++ const onCheckboxClick = React.useCallback((event: React.MouseEvent) => {+ event.stopPropagation();+ }, []);++ const onCheckboxMouseDown = React.useCallback((event: React.MouseEvent<HTMLButtonElement>) => {+ event.stopPropagation();+ }, []);++ const onCheckboxDoubleClick = React.useCallback((event: React.MouseEvent<HTMLButtonElement>) => {+ event.stopPropagation();+ }, []);++ return (+ <DataGridCellWrapper<TData>+ ref={containerRef}+ cell={cell}+ tableMeta={tableMeta}+ rowIndex={rowIndex}+ columnId={columnId}+ rowHeight={rowHeight}+ isEditing={false}+ isFocused={isFocused}+ isSelected={isSelected}+ isSearchMatch={isSearchMatch}+ isActiveSearchMatch={isActiveSearchMatch}+ isDirty={isDirty}+ readOnly={readOnly}+ className="flex size-full justify-center"+ onClick={onWrapperClick}+ onKeyDown={onWrapperKeyDown}+ >+ <Checkbox+ checked={value}+ onCheckedChange={onCheckedChange}+ disabled={readOnly}+ className="border-primary"+ onClick={onCheckboxClick}+ onMouseDown={onCheckboxMouseDown}+ onDoubleClick={onCheckboxDoubleClick}+ />+ </DataGridCellWrapper>+ );+}++export function SelectCell<TData>({+ cell,+ tableMeta,+ rowIndex,+ columnId,+ rowHeight,+ isFocused,+ isEditing,+ isSelected,+ isSearchMatch,+ isActiveSearchMatch,+ isDirty,+ readOnly+}: DataGridCellProps<TData>) {+ const initialValue = cell.getValue() as string;+ const [value, setValue] = React.useState(initialValue);+ const containerRef = React.useRef<HTMLDivElement>(null);+ const cellOpts = cell.column.columnDef.meta?.cell;+ const options = cellOpts?.variant === "select" ? cellOpts.options : [];++ const prevInitialValueRef = React.useRef(initialValue);+ if (initialValue !== prevInitialValueRef.current) {+ prevInitialValueRef.current = initialValue;+ setValue(initialValue);+ }++ const onValueChange = React.useCallback(+ (newValue: string) => {+ if (readOnly) return;+ setValue(newValue);+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: newValue });+ tableMeta?.onCellEditingStop?.();+ },+ [tableMeta, rowIndex, columnId, readOnly]+ );++ const onOpenChange = React.useCallback(+ (open: boolean) => {+ if (open && !readOnly) {+ tableMeta?.onCellEditingStart?.(rowIndex, columnId);+ } else {+ tableMeta?.onCellEditingStop?.();+ }+ },+ [tableMeta, rowIndex, columnId, readOnly]+ );++ const onWrapperKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ if (isEditing && event.key === "Escape") {+ event.preventDefault();+ setValue(initialValue);+ tableMeta?.onCellEditingStop?.();+ } else if (isFocused && event.key === "Tab") {+ event.preventDefault();+ tableMeta?.onCellEditingStop?.({+ direction: event.shiftKey ? "left" : "right"+ });+ }+ },+ [isEditing, isFocused, initialValue, tableMeta]+ );++ const displayLabel = options.find((opt) => opt.value === value)?.label ?? value;++ return (+ <DataGridCellWrapper<TData>+ ref={containerRef}+ cell={cell}+ tableMeta={tableMeta}+ rowIndex={rowIndex}+ columnId={columnId}+ rowHeight={rowHeight}+ isEditing={isEditing}+ isFocused={isFocused}+ isSelected={isSelected}+ isSearchMatch={isSearchMatch}+ isActiveSearchMatch={isActiveSearchMatch}+ isDirty={isDirty}+ readOnly={readOnly}+ onKeyDown={onWrapperKeyDown}+ >+ {isEditing ? (+ <Select+ value={value}+ onValueChange={onValueChange}+ open={isEditing}+ onOpenChange={onOpenChange}+ >+ <SelectTrigger+ size="sm"+ className="size-full items-start border-none bg-transparent p-0 shadow-none focus-visible:ring-0 [&_svg]:hidden"+ >+ {displayLabel ? (+ <Badge variant="secondary" className="px-1.5 py-px whitespace-pre-wrap">+ <SelectValue />+ </Badge>+ ) : (+ <SelectValue />+ )}+ </SelectTrigger>+ <SelectContent+ data-grid-cell-editor=""+ // compensate for the wrapper padding+ align="start"+ alignOffset={-8}+ sideOffset={-8}+ className="min-w-[calc(var(--radix-select-trigger-width)+16px)]"+ >+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ ) : displayLabel ? (+ <Badge+ data-slot="grid-cell-content"+ variant="secondary"+ className="px-1.5 py-px whitespace-pre-wrap"+ >+ {displayLabel}+ </Badge>+ ) : null}+ </DataGridCellWrapper>+ );+}++export function MultiSelectCell<TData>({+ cell,+ tableMeta,+ rowIndex,+ columnId,+ rowHeight,+ isFocused,+ isEditing,+ isSelected,+ isSearchMatch,+ isActiveSearchMatch,+ isDirty,+ readOnly+}: DataGridCellProps<TData>) {+ const cellValue = React.useMemo(() => {+ const value = cell.getValue() as string[];+ return value ?? [];+ }, [cell]);++ const cellKey = getCellKey(rowIndex, columnId);+ const prevCellKeyRef = React.useRef(cellKey);++ const [selectedValues, setSelectedValues] = React.useState<string[]>(cellValue);+ const [searchValue, setSearchValue] = React.useState("");+ const containerRef = React.useRef<HTMLDivElement>(null);+ const inputRef = React.useRef<HTMLInputElement>(null);+ const cellOpts = cell.column.columnDef.meta?.cell;+ const options = cellOpts?.variant === "multi-select" ? cellOpts.options : [];+ const sideOffset = -(containerRef.current?.clientHeight ?? 0);++ const prevCellValueRef = React.useRef(cellValue);+ if (cellValue !== prevCellValueRef.current) {+ prevCellValueRef.current = cellValue;+ setSelectedValues(cellValue);+ }++ if (prevCellKeyRef.current !== cellKey) {+ prevCellKeyRef.current = cellKey;+ setSearchValue("");+ }++ const onValueChange = React.useCallback(+ (value: string) => {+ if (readOnly) return;+ const newValues = selectedValues.includes(value)+ ? selectedValues.filter((v) => v !== value)+ : [...selectedValues, value];++ setSelectedValues(newValues);+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: newValues });+ setSearchValue("");+ queueMicrotask(() => inputRef.current?.focus());+ },+ [selectedValues, tableMeta, rowIndex, columnId, readOnly]+ );++ const removeValue = React.useCallback(+ (valueToRemove: string, event?: React.MouseEvent) => {+ if (readOnly) return;+ event?.stopPropagation();+ event?.preventDefault();+ const newValues = selectedValues.filter((v) => v !== valueToRemove);+ setSelectedValues(newValues);+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: newValues });+ // Focus back on input after removing+ setTimeout(() => inputRef.current?.focus(), 0);+ },+ [selectedValues, tableMeta, rowIndex, columnId, readOnly]+ );++ const clearAll = React.useCallback(() => {+ if (readOnly) return;+ setSelectedValues([]);+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: [] });+ queueMicrotask(() => inputRef.current?.focus());+ }, [tableMeta, rowIndex, columnId, readOnly]);++ const onOpenChange = React.useCallback(+ (open: boolean) => {+ if (open && !readOnly) {+ tableMeta?.onCellEditingStart?.(rowIndex, columnId);+ } else {+ setSearchValue("");+ tableMeta?.onCellEditingStop?.();+ }+ },+ [tableMeta, rowIndex, columnId, readOnly]+ );++ const onOpenAutoFocus: NonNullable<+ React.ComponentProps<typeof PopoverContent>["onOpenAutoFocus"]+ > = React.useCallback((event) => {+ event.preventDefault();+ inputRef.current?.focus();+ }, []);++ const onWrapperKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ if (isEditing && event.key === "Escape") {+ event.preventDefault();+ setSelectedValues(cellValue);+ setSearchValue("");+ tableMeta?.onCellEditingStop?.();+ } else if (isFocused && event.key === "Tab") {+ event.preventDefault();+ setSearchValue("");+ tableMeta?.onCellEditingStop?.({+ direction: event.shiftKey ? "left" : "right"+ });+ }+ },+ [isEditing, isFocused, cellValue, tableMeta]+ );++ const onInputKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLInputElement>) => {+ // Handle backspace when input is empty - remove last selected item+ if (event.key === "Backspace" && searchValue === "" && selectedValues.length > 0) {+ event.preventDefault();+ const lastValue = selectedValues[selectedValues.length - 1];+ if (lastValue) {+ removeValue(lastValue);+ }+ }+ // Prevent escape from propagating to close the popover immediately+ // Let the command handle it first+ if (event.key === "Escape") {+ event.stopPropagation();+ }+ },+ [searchValue, selectedValues, removeValue]+ );++ const displayLabels = selectedValues+ .map((val) => options.find((opt) => opt.value === val)?.label ?? val)+ .filter(Boolean);++ const lineCount = getLineCount(rowHeight);++ const { visibleItems: visibleLabels, hiddenCount: hiddenBadgeCount } = useBadgeOverflow({+ items: displayLabels,+ getLabel: (label) => label,+ containerRef,+ lineCount+ });++ return (+ <DataGridCellWrapper<TData>+ ref={containerRef}+ cell={cell}+ tableMeta={tableMeta}+ rowIndex={rowIndex}+ columnId={columnId}+ rowHeight={rowHeight}+ isEditing={isEditing}+ isFocused={isFocused}+ isSelected={isSelected}+ isSearchMatch={isSearchMatch}+ isActiveSearchMatch={isActiveSearchMatch}+ isDirty={isDirty}+ readOnly={readOnly}+ onKeyDown={onWrapperKeyDown}+ >+ {isEditing ? (+ <Popover open={isEditing} onOpenChange={onOpenChange}>+ <PopoverAnchor asChild>+ <div className="absolute inset-0" />+ </PopoverAnchor>+ <PopoverContent+ data-grid-cell-editor=""+ align="start"+ sideOffset={sideOffset}+ className="w-[300px] rounded-none p-0"+ onOpenAutoFocus={onOpenAutoFocus}+ >+ <Command className="**:data-[slot=command-input-wrapper]:h-auto **:data-[slot=command-input-wrapper]:border-none **:data-[slot=command-input-wrapper]:p-0 [&_[data-slot=command-input-wrapper]_svg]:hidden">+ <div className="flex min-h-9 flex-wrap items-center gap-1 border-b px-3 py-1.5">+ {selectedValues.map((value) => {+ const option = options.find((opt) => opt.value === value);+ const label = option?.label ?? value;++ return (+ <Badge key={value} variant="secondary" className="gap-1 px-1.5 py-px">+ {label}+ <button+ type="button"+ onClick={(event) => removeValue(value, event)}+ onPointerDown={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ >+ <X className="size-3" />+ </button>+ </Badge>+ );+ })}+ <CommandInput+ ref={inputRef}+ value={searchValue}+ onValueChange={setSearchValue}+ onKeyDown={onInputKeyDown}+ placeholder="Search..."+ className="h-auto flex-1 p-0"+ />+ </div>+ <CommandList className="max-h-full">+ <CommandEmpty>No options found.</CommandEmpty>+ <CommandGroup className="max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto">+ {options.map((option) => {+ const isSelected = selectedValues.includes(option.value);++ return (+ <CommandItem+ key={option.value}+ value={option.label}+ onSelect={() => onValueChange(option.value)}+ >+ <div+ className={cn(+ "flex size-4 items-center justify-center rounded-sm border border-primary",+ isSelected+ ? "text-primary-foreground bg-primary"+ : "opacity-50 [&_svg]:invisible"+ )}+ >+ <Check className="size-3" />+ </div>+ <span>{option.label}</span>+ </CommandItem>+ );+ })}+ </CommandGroup>+ {selectedValues.length > 0 && (+ <>+ <CommandSeparator />+ <CommandGroup>+ <CommandItem onSelect={clearAll} className="justify-center text-muted">+ Clear all+ </CommandItem>+ </CommandGroup>+ </>+ )}+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ ) : null}+ {displayLabels.length > 0 ? (+ <div className="flex flex-wrap items-center gap-1 overflow-hidden">+ {visibleLabels.map((label, index) => (+ <Badge key={selectedValues[index]} variant="secondary" className="px-1.5 py-px">+ {label}+ </Badge>+ ))}+ {hiddenBadgeCount > 0 && (+ <Badge variant="outline" className="px-1.5 py-px text-muted">+ +{hiddenBadgeCount}+ </Badge>+ )}+ </div>+ ) : null}+ </DataGridCellWrapper>+ );+}++export function DateCell<TData>({+ cell,+ tableMeta,+ rowIndex,+ columnId,+ rowHeight,+ isFocused,+ isEditing,+ isSelected,+ isSearchMatch,+ isActiveSearchMatch,+ isDirty,+ readOnly+}: DataGridCellProps<TData>) {+ const initialValue = cell.getValue() as string;+ const [value, setValue] = React.useState(initialValue ?? "");+ const containerRef = React.useRef<HTMLDivElement>(null);++ const prevInitialValueRef = React.useRef(initialValue);+ if (initialValue !== prevInitialValueRef.current) {+ prevInitialValueRef.current = initialValue;+ setValue(initialValue ?? "");+ }++ // Parse date as local time to avoid timezone shifts+ const selectedDate = value ? (parseLocalDate(value) ?? undefined) : undefined;++ const onDateSelect = React.useCallback(+ (date: Date | undefined) => {+ if (!date || readOnly) return;++ // Format using local date components to avoid timezone issues+ const formattedDate = formatDateToString(date);+ setValue(formattedDate);+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: formattedDate });+ tableMeta?.onCellEditingStop?.();+ },+ [tableMeta, rowIndex, columnId, readOnly]+ );++ const onOpenChange = React.useCallback(+ (open: boolean) => {+ if (open && !readOnly) {+ tableMeta?.onCellEditingStart?.(rowIndex, columnId);+ } else {+ tableMeta?.onCellEditingStop?.();+ }+ },+ [tableMeta, rowIndex, columnId, readOnly]+ );++ const onWrapperKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ if (isEditing && event.key === "Escape") {+ event.preventDefault();+ setValue(initialValue);+ tableMeta?.onCellEditingStop?.();+ } else if (isFocused && event.key === "Tab") {+ event.preventDefault();+ tableMeta?.onCellEditingStop?.({+ direction: event.shiftKey ? "left" : "right"+ });+ }+ },+ [isEditing, isFocused, initialValue, tableMeta]+ );++ return (+ <DataGridCellWrapper<TData>+ ref={containerRef}+ cell={cell}+ tableMeta={tableMeta}+ rowIndex={rowIndex}+ columnId={columnId}+ rowHeight={rowHeight}+ isEditing={isEditing}+ isFocused={isFocused}+ isSelected={isSelected}+ isSearchMatch={isSearchMatch}+ isActiveSearchMatch={isActiveSearchMatch}+ isDirty={isDirty}+ readOnly={readOnly}+ onKeyDown={onWrapperKeyDown}+ >+ <Popover open={isEditing} onOpenChange={onOpenChange}>+ <PopoverAnchor asChild>+ <span data-slot="grid-cell-content">{formatDateForDisplay(value)}</span>+ </PopoverAnchor>+ {isEditing && (+ <PopoverContent+ data-grid-cell-editor=""+ align="start"+ alignOffset={-8}+ className="w-auto p-0"+ >+ <Calendar+ autoFocus+ captionLayout="dropdown"+ mode="single"+ defaultMonth={selectedDate ?? new Date()}+ selected={selectedDate}+ onSelect={onDateSelect}+ />+ </PopoverContent>+ )}+ </Popover>+ </DataGridCellWrapper>+ );+}++export function FileCell<TData>({+ cell,+ tableMeta,+ rowIndex,+ columnId,+ rowHeight,+ isFocused,+ isEditing,+ isSelected,+ isSearchMatch,+ isActiveSearchMatch,+ isDirty,+ readOnly+}: DataGridCellProps<TData>) {+ const cellValue = React.useMemo(() => (cell.getValue() as FileCellData[]) ?? [], [cell]);++ const cellKey = getCellKey(rowIndex, columnId);+ const prevCellKeyRef = React.useRef(cellKey);++ const labelId = React.useId();+ const descriptionId = React.useId();++ const [files, setFiles] = React.useState<FileCellData[]>(cellValue);+ const [uploadingFiles, setUploadingFiles] = React.useState<Set<string>>(new Set());+ const [deletingFiles, setDeletingFiles] = React.useState<Set<string>>(new Set());+ const [isDraggingOver, setIsDraggingOver] = React.useState(false);+ const [isDragging, setIsDragging] = React.useState(false);+ const [error, setError] = React.useState<string | null>(null);++ const isUploading = uploadingFiles.size > 0;+ const isDeleting = deletingFiles.size > 0;+ const isPending = isUploading || isDeleting;+ const containerRef = React.useRef<HTMLDivElement>(null);+ const fileInputRef = React.useRef<HTMLInputElement>(null);+ const dropzoneRef = React.useRef<HTMLDivElement>(null);+ const cellOpts = cell.column.columnDef.meta?.cell;+ const sideOffset = -(containerRef.current?.clientHeight ?? 0);++ const fileCellOpts = cellOpts?.variant === "file" ? cellOpts : null;+ const maxFileSize = fileCellOpts?.maxFileSize ?? 10 * 1024 * 1024;+ const maxFiles = fileCellOpts?.maxFiles ?? 10;+ const accept = fileCellOpts?.accept;+ const multiple = fileCellOpts?.multiple ?? false;++ const acceptedTypes = React.useMemo(+ () => (accept ? accept.split(",").map((t) => t.trim()) : null),+ [accept]+ );++ const prevCellValueRef = React.useRef(cellValue);+ if (cellValue !== prevCellValueRef.current) {+ prevCellValueRef.current = cellValue;+ for (const file of files) {+ if (file.url) {+ URL.revokeObjectURL(file.url);+ }+ }+ setFiles(cellValue);+ setError(null);+ }++ if (prevCellKeyRef.current !== cellKey) {+ prevCellKeyRef.current = cellKey;+ setError(null);+ }++ const validateFile = React.useCallback(+ (file: File): string | null => {+ if (maxFileSize && file.size > maxFileSize) {+ return `File size exceeds ${formatFileSize(maxFileSize)}`;+ }+ if (acceptedTypes) {+ const fileExtension = `.${file.name.split(".").pop()}`;+ const isAccepted = acceptedTypes.some((type) => {+ if (type.endsWith("/*")) {+ const baseType = type.slice(0, -2);+ return file.type.startsWith(`${baseType}/`);+ }+ if (type.startsWith(".")) {+ return fileExtension.toLowerCase() === type.toLowerCase();+ }+ return file.type === type;+ });+ if (!isAccepted) {+ return "File type not accepted";+ }+ }+ return null;+ },+ [maxFileSize, acceptedTypes]+ );++ const addFiles = React.useCallback(+ async (newFiles: File[], skipUpload = false) => {+ if (readOnly || isPending) return;+ setError(null);++ if (maxFiles && files.length + newFiles.length > maxFiles) {+ const errorMessage = `Maximum ${maxFiles} files allowed`;+ setError(errorMessage);+ toast(errorMessage);+ setTimeout(() => {+ setError(null);+ }, 2000);+ return;+ }++ const rejectedFiles: Array<{ name: string; reason: string }> = [];+ const filesToValidate: File[] = [];++ for (const file of newFiles) {+ const validationError = validateFile(file);+ if (validationError) {+ rejectedFiles.push({ name: file.name, reason: validationError });+ continue;+ }+ filesToValidate.push(file);+ }++ if (rejectedFiles.length > 0) {+ const firstError = rejectedFiles[0];+ if (firstError) {+ setError(firstError.reason);++ const truncatedName =+ firstError.name.length > 20 ? `${firstError.name.slice(0, 20)}...` : firstError.name;++ if (rejectedFiles.length === 1) {+ toast(firstError.reason, {+ description: `"${truncatedName}" has been rejected`+ });+ } else {+ toast(firstError.reason, {+ description: `"${truncatedName}" and ${rejectedFiles.length - 1} more rejected`+ });+ }++ setTimeout(() => {+ setError(null);+ }, 2000);+ }+ }++ if (filesToValidate.length > 0) {+ if (!skipUpload) {+ const tempFiles = filesToValidate.map((f) => ({+ id: crypto.randomUUID(),+ name: f.name,+ size: f.size,+ type: f.type,+ url: undefined+ }));+ const filesWithTemp = [...files, ...tempFiles];+ setFiles(filesWithTemp);++ const uploadingIds = new Set(tempFiles.map((f) => f.id));+ setUploadingFiles(uploadingIds);++ let uploadedFiles: FileCellData[] = [];++ if (tableMeta?.onFilesUpload) {+ try {+ uploadedFiles = await tableMeta.onFilesUpload({+ files: filesToValidate,+ rowIndex,+ columnId+ });+ } catch (error) {+ toast.error(+ error instanceof Error+ ? error.message+ : `Failed to upload ${filesToValidate.length} file${filesToValidate.length !== 1 ? "s" : ""}`+ );+ setFiles((prev) => prev.filter((f) => !uploadingIds.has(f.id)));+ setUploadingFiles(new Set());+ return;+ }+ } else {+ uploadedFiles = filesToValidate.map((f, i) => ({+ id: tempFiles[i]?.id ?? crypto.randomUUID(),+ name: f.name,+ size: f.size,+ type: f.type,+ url: URL.createObjectURL(f)+ }));+ }++ const finalFiles = filesWithTemp+ .map((f) => {+ if (uploadingIds.has(f.id)) {+ return uploadedFiles.find((uf) => uf.name === f.name) ?? f;+ }+ return f;+ })+ .filter((f) => f.url !== undefined);++ setFiles(finalFiles);+ setUploadingFiles(new Set());+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: finalFiles });+ } else {+ const newFilesData: FileCellData[] = filesToValidate.map((f) => ({+ id: crypto.randomUUID(),+ name: f.name,+ size: f.size,+ type: f.type,+ url: URL.createObjectURL(f)+ }));+ const updatedFiles = [...files, ...newFilesData];+ setFiles(updatedFiles);+ tableMeta?.onDataUpdate?.({+ rowIndex,+ columnId,+ value: updatedFiles+ });+ }+ }+ },+ [files, maxFiles, validateFile, tableMeta, rowIndex, columnId, readOnly, isPending]+ );++ const removeFile = React.useCallback(+ async (fileId: string) => {+ if (readOnly || isPending) return;+ setError(null);++ const fileToRemove = files.find((f) => f.id === fileId);+ if (!fileToRemove) return;++ setDeletingFiles((prev) => new Set(prev).add(fileId));++ if (tableMeta?.onFilesDelete) {+ try {+ await tableMeta.onFilesDelete({+ fileIds: [fileId],+ rowIndex,+ columnId+ });+ } catch (error) {+ toast.error(+ error instanceof Error ? error.message : `Failed to delete ${fileToRemove.name}`+ );+ setDeletingFiles((prev) => {+ const next = new Set(prev);+ next.delete(fileId);+ return next;+ });+ return;+ }+ }++ if (fileToRemove.url?.startsWith("blob:")) {+ URL.revokeObjectURL(fileToRemove.url);+ }++ const updatedFiles = files.filter((f) => f.id !== fileId);+ setFiles(updatedFiles);+ setDeletingFiles((prev) => {+ const next = new Set(prev);+ next.delete(fileId);+ return next;+ });+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: updatedFiles });+ },+ [files, tableMeta, rowIndex, columnId, readOnly, isPending]+ );++ const clearAll = React.useCallback(async () => {+ if (readOnly || isPending) return;+ setError(null);++ const fileIds = files.map((f) => f.id);+ setDeletingFiles(new Set(fileIds));++ if (tableMeta?.onFilesDelete && files.length > 0) {+ try {+ await tableMeta.onFilesDelete({+ fileIds,+ rowIndex,+ columnId+ });+ } catch (error) {+ toast.error(error instanceof Error ? error.message : "Failed to delete files");+ setDeletingFiles(new Set());+ return;+ }+ }++ for (const file of files) {+ if (file.url?.startsWith("blob:")) {+ URL.revokeObjectURL(file.url);+ }+ }+ setFiles([]);+ setDeletingFiles(new Set());+ tableMeta?.onDataUpdate?.({ rowIndex, columnId, value: [] });+ }, [files, tableMeta, rowIndex, columnId, readOnly, isPending]);++ const onCellDragEnter = React.useCallback((event: React.DragEvent) => {+ event.preventDefault();+ event.stopPropagation();+ if (event.dataTransfer.types.includes("Files")) {+ setIsDraggingOver(true);+ }+ }, []);++ const onCellDragLeave = React.useCallback((event: React.DragEvent) => {+ event.preventDefault();+ event.stopPropagation();+ const rect = event.currentTarget.getBoundingClientRect();+ const x = event.clientX;+ const y = event.clientY;++ if (x <= rect.left || x >= rect.right || y <= rect.top || y >= rect.bottom) {+ setIsDraggingOver(false);+ }+ }, []);++ const onCellDragOver = React.useCallback((event: React.DragEvent) => {+ event.preventDefault();+ event.stopPropagation();+ }, []);++ const onCellDrop = React.useCallback(+ (event: React.DragEvent) => {+ event.preventDefault();+ event.stopPropagation();+ setIsDraggingOver(false);++ const droppedFiles = Array.from(event.dataTransfer.files);+ if (droppedFiles.length > 0) {+ addFiles(droppedFiles, false);+ }+ },+ [addFiles]+ );++ const onDropzoneDragEnter = React.useCallback((event: React.DragEvent) => {+ event.preventDefault();+ event.stopPropagation();+ setIsDragging(true);+ }, []);++ const onDropzoneDragLeave = React.useCallback((event: React.DragEvent) => {+ event.preventDefault();+ event.stopPropagation();+ const rect = event.currentTarget.getBoundingClientRect();+ const x = event.clientX;+ const y = event.clientY;++ if (x <= rect.left || x >= rect.right || y <= rect.top || y >= rect.bottom) {+ setIsDragging(false);+ }+ }, []);++ const onDropzoneDragOver = React.useCallback((event: React.DragEvent) => {+ event.preventDefault();+ event.stopPropagation();+ }, []);++ const onDropzoneDrop = React.useCallback(+ (event: React.DragEvent) => {+ event.preventDefault();+ event.stopPropagation();+ setIsDragging(false);++ const droppedFiles = Array.from(event.dataTransfer.files);+ addFiles(droppedFiles, false);+ },+ [addFiles]+ );++ const onDropzoneClick = React.useCallback(() => {+ fileInputRef.current?.click();+ }, []);++ const onDropzoneKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ onDropzoneClick();+ }+ },+ [onDropzoneClick]+ );++ const onFileInputChange = React.useCallback(+ (event: React.ChangeEvent<HTMLInputElement>) => {+ const selectedFiles = Array.from(event.target.files ?? []);+ addFiles(selectedFiles, false);+ event.target.value = "";+ },+ [addFiles]+ );++ const onOpenChange = React.useCallback(+ (open: boolean) => {+ if (open && !readOnly) {+ setError(null);+ tableMeta?.onCellEditingStart?.(rowIndex, columnId);+ } else {+ setError(null);+ tableMeta?.onCellEditingStop?.();+ }+ },+ [tableMeta, rowIndex, columnId, readOnly]+ );++ const onEscapeKeyDown: NonNullable<+ React.ComponentProps<typeof PopoverContent>["onEscapeKeyDown"]+ > = React.useCallback((event) => {+ // Prevent the escape key from propagating to the data grid's keyboard handler+ // which would call blurCell() and remove focus from the cell+ event.stopPropagation();+ }, []);++ const onOpenAutoFocus: NonNullable<+ React.ComponentProps<typeof PopoverContent>["onOpenAutoFocus"]+ > = React.useCallback((event) => {+ event.preventDefault();+ queueMicrotask(() => {+ dropzoneRef.current?.focus();+ });+ }, []);++ const onWrapperKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ if (isEditing) {+ if (event.key === "Escape") {+ event.preventDefault();+ setFiles(cellValue);+ setError(null);+ tableMeta?.onCellEditingStop?.();+ } else if (event.key === " ") {+ event.preventDefault();+ onDropzoneClick();+ } else if (event.key === "Tab") {+ event.preventDefault();+ tableMeta?.onCellEditingStop?.({+ direction: event.shiftKey ? "left" : "right"+ });+ }+ } else if (isFocused && event.key === "Enter") {+ event.preventDefault();+ tableMeta?.onCellEditingStart?.(rowIndex, columnId);+ } else if (isFocused && event.key === "Tab") {+ event.preventDefault();+ tableMeta?.onCellEditingStop?.({+ direction: event.shiftKey ? "left" : "right"+ });+ }+ },+ [isEditing, isFocused, cellValue, tableMeta, onDropzoneClick, rowIndex, columnId]+ );++ React.useEffect(() => {+ return () => {+ for (const file of files) {+ if (file.url) {+ URL.revokeObjectURL(file.url);+ }+ }+ };+ }, [files]);++ const lineCount = getLineCount(rowHeight);++ const { visibleItems: visibleFiles, hiddenCount: hiddenFileCount } = useBadgeOverflow({+ items: files,+ getLabel: (file) => file.name,+ containerRef,+ lineCount,+ cacheKeyPrefix: "file",+ iconSize: 12,+ maxWidth: 100+ });++ return (+ <DataGridCellWrapper<TData>+ ref={containerRef}+ cell={cell}+ tableMeta={tableMeta}+ rowIndex={rowIndex}+ columnId={columnId}+ rowHeight={rowHeight}+ isEditing={isEditing}+ isFocused={isFocused}+ isSelected={isSelected}+ isSearchMatch={isSearchMatch}+ isActiveSearchMatch={isActiveSearchMatch}+ isDirty={isDirty}+ readOnly={readOnly}+ className={cn({+ "ring-1 ring-primary/80 ring-inset": isDraggingOver+ })}+ onDragEnter={onCellDragEnter}+ onDragLeave={onCellDragLeave}+ onDragOver={onCellDragOver}+ onDrop={onCellDrop}+ onKeyDown={onWrapperKeyDown}+ >+ {isEditing ? (+ <Popover open={isEditing} onOpenChange={onOpenChange}>+ <PopoverAnchor asChild>+ <div className="absolute inset-0" />+ </PopoverAnchor>+ <PopoverContent+ data-grid-cell-editor=""+ align="start"+ sideOffset={sideOffset}+ className="w-[400px] rounded-none p-0"+ onEscapeKeyDown={onEscapeKeyDown}+ onOpenAutoFocus={onOpenAutoFocus}+ >+ <div className="flex flex-col gap-2 p-3">+ <span id={labelId} className="sr-only">+ File upload+ </span>+ <div+ role="region"+ aria-labelledby={labelId}+ aria-describedby={descriptionId}+ aria-invalid={!!error}+ aria-disabled={isPending}+ data-dragging={isDragging ? "" : undefined}+ data-invalid={error ? "" : undefined}+ data-disabled={isPending ? "" : undefined}+ tabIndex={isDragging || isPending ? -1 : 0}+ className="data-invalid:border-destructive data-invalid:ring-destructive/20 flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border-2 border-dashed p-6 transition-colors outline-none hover:bg-accent/30 focus-visible:border-ring/50 data-disabled:pointer-events-none data-disabled:opacity-50 data-dragging:border-primary/30 data-dragging:bg-accent/30"+ ref={dropzoneRef}+ onClick={onDropzoneClick}+ onDragEnter={onDropzoneDragEnter}+ onDragLeave={onDropzoneDragLeave}+ onDragOver={onDropzoneDragOver}+ onDrop={onDropzoneDrop}+ onKeyDown={onDropzoneKeyDown}+ >+ <Upload className="size-8 text-muted" />+ <div className="text-center text-sm">+ <p className="font-medium">+ {isDragging ? "Drop files here" : "Drag files here"}+ </p>+ <p className="text-xs text-muted">or click to browse</p>+ </div>+ <p id={descriptionId} className="text-xs text-muted">+ {maxFileSize+ ? `Max size: ${formatFileSize(maxFileSize)}${maxFiles ? ` • Max ${maxFiles} files` : ""}`+ : maxFiles+ ? `Max ${maxFiles} files`+ : "Select files to upload"}+ </p>+ </div>+ <input+ type="file"+ aria-labelledby={labelId}+ aria-describedby={descriptionId}+ multiple={multiple}+ accept={accept}+ className="sr-only"+ ref={fileInputRef}+ onChange={onFileInputChange}+ />+ {files.length > 0 && (+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between">+ <p className="text-xs font-medium text-muted">+ {files.length} {files.length === 1 ? "file" : "files"}+ </p>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-6 text-xs text-muted"+ onClick={clearAll}+ disabled={isPending}+ >+ Clear all+ </Button>+ </div>+ <div className="max-h-[200px] space-y-1 overflow-y-auto">+ {files.map((file) => {+ const FileIcon = getFileIcon(file.type);+ const isFileUploading = uploadingFiles.has(file.id);+ const isFileDeleting = deletingFiles.has(file.id);+ const isFilePending = isFileUploading || isFileDeleting;++ return (+ <div+ key={file.id}+ data-pending={isFilePending ? "" : undefined}+ className="flex items-center gap-2 rounded-md border bg-muted/50 px-2 py-1.5 data-pending:opacity-60"+ >+ {FileIcon && <FileIcon className="size-4 shrink-0 text-muted" />}+ <div className="flex-1 overflow-hidden">+ <p className="truncate text-sm">{file.name}</p>+ <p className="text-xs text-muted">+ {isFileUploading+ ? "Uploading..."+ : isFileDeleting+ ? "Deleting..."+ : formatFileSize(file.size)}+ </p>+ </div>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="size-5 rounded-sm"+ onClick={() => removeFile(file.id)}+ disabled={isPending}+ >+ <X className="size-3" />+ </Button>+ </div>+ );+ })}+ </div>+ </div>+ )}+ </div>+ </PopoverContent>+ </Popover>+ ) : null}+ {isDraggingOver ? (+ <div className="flex items-center justify-center gap-2 text-sm text-primary">+ <Upload className="size-4" />+ <span>Drop files here</span>+ </div>+ ) : files.length > 0 ? (+ <div className="flex flex-wrap items-center gap-1 overflow-hidden">+ {visibleFiles.map((file) => {+ // eslint-disable-next-line @typescript-eslint/no-shadow+ const isUploading = uploadingFiles.has(file.id);++ if (isUploading) {+ return (+ <Skeleton+ key={file.id}+ className="h-5 shrink-0 px-1.5"+ style={{+ width: `${Math.min(file.name.length * 8 + 30, 100)}px`+ }}+ />+ );+ }++ const FileIcon = getFileIcon(file.type);++ return (+ <Badge key={file.id} variant="secondary" className="gap-1 px-1.5 py-px">+ {FileIcon && <FileIcon className="size-3 shrink-0" />}+ <span className="max-w-[100px] truncate">{file.name}</span>+ </Badge>+ );+ })}+ {hiddenFileCount > 0 && (+ <Badge variant="outline" className="px-1.5 py-px text-muted">+ +{hiddenFileCount}+ </Badge>+ )}+ </div>+ ) : null}+ </DataGridCellWrapper>+ );+}diff --git a/frontend/src/components/v3/generic/DataGrid/data-grid-cell-wrapper.tsx b/frontend/src/components/v3/generic/DataGrid/data-grid-cell-wrapper.tsxnew file mode 100644index 0000000000..d6542f58d0--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/data-grid-cell-wrapper.tsx@@ -0,0 +1,187 @@+import * as React from "react";++import { cn } from "@app/components/v3/utils";++import { useComposedRefs } from "./compose-refs";+import type { DataGridCellProps } from "./data-grid-types";+import { getCellKey } from "./data-grid-utils";++interface DataGridCellWrapperProps<TData>+ extends DataGridCellProps<TData>,+ React.ComponentProps<"div"> {}++export function DataGridCellWrapper<TData>({+ tableMeta,+ rowIndex,+ columnId,+ isEditing,+ isFocused,+ isSelected,+ isSearchMatch,+ isActiveSearchMatch,+ isDirty,+ readOnly,+ rowHeight,+ className,+ onClick: onClickProp,+ onKeyDown: onKeyDownProp,+ ref,+ ...props+}: DataGridCellWrapperProps<TData>) {+ const cellMapRef = tableMeta?.cellMapRef;++ const onCellChange = React.useCallback(+ (node: HTMLDivElement | null) => {+ if (!cellMapRef?.current) return;++ const cellKey = getCellKey(rowIndex, columnId);++ if (node) {+ cellMapRef.current.set(cellKey, node);+ } else {+ cellMapRef.current.delete(cellKey);+ }+ },+ [rowIndex, columnId, cellMapRef]+ );++ const composedRef = useComposedRefs(ref as React.Ref<HTMLDivElement> | undefined, onCellChange);++ const onClick = React.useCallback(+ (event: React.MouseEvent<HTMLDivElement>) => {+ if (!isEditing) {+ event.preventDefault();+ onClickProp?.(event);+ if (isFocused && !readOnly) {+ tableMeta?.onCellEditingStart?.(rowIndex, columnId);+ } else {+ tableMeta?.onCellClick?.(rowIndex, columnId, event);+ }+ }+ },+ [tableMeta, rowIndex, columnId, isEditing, isFocused, readOnly, onClickProp]+ );++ const onContextMenu = React.useCallback(+ (event: React.MouseEvent) => {+ tableMeta?.onCellContextMenu?.(rowIndex, columnId, event);+ },+ [tableMeta, rowIndex, columnId]+ );++ const onDoubleClick = React.useCallback(+ (event: React.MouseEvent) => {+ if (!isEditing) {+ event.preventDefault();+ tableMeta?.onCellDoubleClick?.(rowIndex, columnId);+ }+ },+ [tableMeta, rowIndex, columnId, isEditing]+ );++ const onKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ onKeyDownProp?.(event);++ if (event.defaultPrevented) return;++ if (+ event.key === "ArrowUp" ||+ event.key === "ArrowDown" ||+ event.key === "ArrowLeft" ||+ event.key === "ArrowRight" ||+ event.key === "Home" ||+ event.key === "End" ||+ event.key === "PageUp" ||+ event.key === "PageDown" ||+ event.key === "Tab"+ ) {+ return;+ }++ if (isFocused && !isEditing && !readOnly) {+ if (event.key === "F2" || event.key === "Enter") {+ event.preventDefault();+ event.stopPropagation();+ tableMeta?.onCellEditingStart?.(rowIndex, columnId);+ return;+ }++ if (event.key === " ") {+ event.preventDefault();+ event.stopPropagation();+ tableMeta?.onCellEditingStart?.(rowIndex, columnId);+ return;+ }++ if (event.key.length === 1 && !event.ctrlKey && !event.metaKey) {+ event.preventDefault();+ event.stopPropagation();+ tableMeta?.onCellEditingStart?.(rowIndex, columnId);+ }+ }+ },+ [onKeyDownProp, isFocused, isEditing, readOnly, tableMeta, rowIndex, columnId]+ );++ const onMouseDown = React.useCallback(+ (event: React.MouseEvent) => {+ if (!isEditing) {+ tableMeta?.onCellMouseDown?.(rowIndex, columnId, event);+ }+ },+ [tableMeta, rowIndex, columnId, isEditing]+ );++ const onMouseEnter = React.useCallback(() => {+ if (!isEditing) {+ tableMeta?.onCellMouseEnter?.(rowIndex, columnId);+ }+ }, [tableMeta, rowIndex, columnId, isEditing]);++ const onMouseUp = React.useCallback(() => {+ if (!isEditing) {+ tableMeta?.onCellMouseUp?.();+ }+ }, [tableMeta, isEditing]);++ return (+ <div+ role="button"+ data-slot="grid-cell-wrapper"+ data-editing={isEditing ? "" : undefined}+ data-focused={isFocused ? "" : undefined}+ data-selected={isSelected ? "" : undefined}+ tabIndex={isFocused && !isEditing ? 0 : -1}+ {...props}+ ref={composedRef}+ className={cn(+ "flex size-full items-center px-3 py-1.5 text-start text-sm text-mineshaft-200 outline-none **:data-[slot=grid-cell-content]:h-auto",+ {+ "ring-1 ring-ring ring-inset": isFocused,+ "bg-yellow-900/30": isSearchMatch && !isActiveSearchMatch,+ "bg-orange-900/50": isActiveSearchMatch,+ "bg-warning/10": isDirty && !isSelected && !isSearchMatch && !isActiveSearchMatch,+ "bg-foreground/[0.07]": isSelected && !isEditing,+ "cursor-default": !isEditing,+ "**:data-[slot=grid-cell-content]:line-clamp-1 **:data-[slot=grid-cell-content]:break-all":+ !isEditing && rowHeight === "short",+ "**:data-[slot=grid-cell-content]:line-clamp-2 **:data-[slot=grid-cell-content]:break-all":+ !isEditing && rowHeight === "medium",+ "**:data-[slot=grid-cell-content]:line-clamp-3 **:data-[slot=grid-cell-content]:break-all":+ !isEditing && rowHeight === "tall",+ "**:data-[slot=grid-cell-content]:line-clamp-4 **:data-[slot=grid-cell-content]:break-all":+ !isEditing && rowHeight === "extra-tall"+ },+ className+ )}+ onClick={onClick}+ onContextMenu={onContextMenu}+ onDoubleClick={onDoubleClick}+ onMouseDown={onMouseDown}+ onMouseEnter={onMouseEnter}+ onMouseUp={onMouseUp}+ onKeyDown={onKeyDown}+ />+ );+}diff --git a/frontend/src/components/v3/generic/DataGrid/data-grid-cell.tsx b/frontend/src/components/v3/generic/DataGrid/data-grid-cell.tsxnew file mode 100644index 0000000000..b01f960ea4--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/data-grid-cell.tsx@@ -0,0 +1,113 @@+import * as React from "react";++import {+ CheckboxCell,+ DateCell,+ FileCell,+ LongTextCell,+ MultiSelectCell,+ NumberCell,+ SelectCell,+ ShortTextCell,+ UrlCell+} from "./data-grid-cell-variants";+import type { DataGridCellProps } from "./data-grid-types";++// eslint-disable-next-line @typescript-eslint/no-use-before-define+export const DataGridCell = React.memo(DataGridCellImpl, (prev, next) => {+ // Fast path: check stable primitive props first+ if (prev.isFocused !== next.isFocused) return false;+ if (prev.isEditing !== next.isEditing) return false;+ if (prev.isSelected !== next.isSelected) return false;+ if (prev.isSearchMatch !== next.isSearchMatch) return false;+ if (prev.isActiveSearchMatch !== next.isActiveSearchMatch) return false;+ if (prev.isDirty !== next.isDirty) return false;+ if (prev.readOnly !== next.readOnly) return false;+ if (prev.rowIndex !== next.rowIndex) return false;+ if (prev.columnId !== next.columnId) return false;+ if (prev.rowHeight !== next.rowHeight) return false;++ // Check cell value using row.original instead of getValue() for stability+ // getValue() is unstable and recreates on every render, breaking memoization+ const prevValue = (prev.cell.row.original as Record<string, unknown>)[prev.columnId];+ const nextValue = (next.cell.row.original as Record<string, unknown>)[next.columnId];+ if (prevValue !== nextValue) {+ return false;+ }++ // Check cell/row identity+ if (prev.cell.row.id !== next.cell.row.id) return false;++ return true;+}) as typeof DataGridCellImpl;++function DataGridCellImpl<TData>({+ cell,+ tableMeta,+ rowIndex,+ columnId,+ isFocused,+ isEditing,+ isSelected,+ isSearchMatch,+ isActiveSearchMatch,+ isDirty,+ readOnly,+ rowHeight+}: DataGridCellProps<TData>) {+ const cellOpts = cell.column.columnDef.meta?.cell;+ const variant = cellOpts?.variant ?? "text";++ let Comp: React.ComponentType<DataGridCellProps<TData>>;++ switch (variant) {+ case "short-text":+ Comp = ShortTextCell;+ break;+ case "long-text":+ Comp = LongTextCell;+ break;+ case "number":+ Comp = NumberCell;+ break;+ case "url":+ Comp = UrlCell;+ break;+ case "checkbox":+ Comp = CheckboxCell;+ break;+ case "select":+ Comp = SelectCell;+ break;+ case "multi-select":+ Comp = MultiSelectCell;+ break;+ case "date":+ Comp = DateCell;+ break;+ case "file":+ Comp = FileCell;+ break;++ default:+ Comp = ShortTextCell;+ break;+ }++ return (+ <Comp+ cell={cell}+ tableMeta={tableMeta}+ rowIndex={rowIndex}+ columnId={columnId}+ rowHeight={rowHeight}+ isEditing={isEditing}+ isFocused={isFocused}+ isSelected={isSelected}+ isSearchMatch={isSearchMatch}+ isActiveSearchMatch={isActiveSearchMatch}+ isDirty={isDirty}+ readOnly={readOnly}+ />+ );+}diff --git a/frontend/src/components/v3/generic/DataGrid/data-grid-column-header.tsx b/frontend/src/components/v3/generic/DataGrid/data-grid-column-header.tsxnew file mode 100644index 0000000000..201e333fa3--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/data-grid-column-header.tsx@@ -0,0 +1,134 @@+import * as React from "react";+import type { Header, Table } from "@tanstack/react-table";+import { KeyRoundIcon, Link2Icon } from "lucide-react";++import { Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3/generic/Tooltip";+import { cn } from "@app/components/v3/utils";++interface DataGridColumnHeaderProps<TData, TValue> extends React.ComponentProps<"div"> {+ header: Header<TData, TValue>;+ table: Table<TData>;+}++export function DataGridColumnHeader<TData, TValue>({+ header,+ table,+ className,+ ...props+}: DataGridColumnHeaderProps<TData, TValue>) {+ const { column } = header;+ // eslint-disable-next-line no-nested-ternary+ const label = column.columnDef.meta?.label+ ? column.columnDef.meta.label+ : typeof column.columnDef.header === "string"+ ? column.columnDef.header+ : column.id;++ return (+ <>+ <div+ className={cn(+ "flex size-full items-center gap-2 px-3 py-1.5 text-xs text-accent select-none",+ className+ )}+ {...props}+ >+ <div className="flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden">+ {/* eslint-disable-next-line no-nested-ternary */}+ {column.columnDef.meta?.columnIndicator?.type === "pk" ? (+ <KeyRoundIcon size={12} className="shrink-0 text-yellow-500" />+ ) : column.columnDef.meta?.columnIndicator?.type === "fk" ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Link2Icon size={12} className="shrink-0 text-blue-400" />+ </TooltipTrigger>+ {column.columnDef.meta.columnIndicator.tooltip && (+ <TooltipContent side="bottom">+ {column.columnDef.meta.columnIndicator.tooltip}+ </TooltipContent>+ )}+ </Tooltip>+ ) : null}+ <span className="truncate text-mineshaft-200">{label}</span>+ {column.columnDef.meta?.typeLabel && (+ <span className="shrink-0 font-normal text-accent">+ {column.columnDef.meta.typeLabel}+ </span>+ )}+ {column.columnDef.meta?.columnIndicator && (+ <span+ className={cn(+ "shrink-0 rounded px-1 py-0.5 text-[10px] leading-none font-medium",+ column.columnDef.meta.columnIndicator.type === "pk"+ ? "bg-yellow-500/15 text-yellow-500"+ : "bg-blue-400/15 text-blue-400"+ )}+ >+ {column.columnDef.meta.columnIndicator.type === "pk" ? "PK" : "FK"}+ </span>+ )}+ </div>+ </div>+ {header.column.getCanResize() && (+ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ <DataGridColumnResizer header={header} table={table} label={label} />+ )}+ </>+ );+}++// eslint-disable-next-line @typescript-eslint/no-use-before-define+const DataGridColumnResizer = React.memo(DataGridColumnResizerImpl, (prev, next) => {+ const prevColumn = prev.header.column;+ const nextColumn = next.header.column;++ if (+ prevColumn.getIsResizing() !== nextColumn.getIsResizing() ||+ prevColumn.getSize() !== nextColumn.getSize()+ ) {+ return false;+ }++ if (prev.label !== next.label) return false;++ return true;+}) as typeof DataGridColumnResizerImpl;++interface DataGridColumnResizerProps<TData, TValue> {+ header: Header<TData, TValue>;+ table: Table<TData>;+ label: string;+}++function DataGridColumnResizerImpl<TData, TValue>({+ header,+ table,+ label+}: DataGridColumnResizerProps<TData, TValue>) {+ // eslint-disable-next-line no-underscore-dangle+ const defaultColumnDef = table._getDefaultColumnDef();++ const onDoubleClick = React.useCallback(() => {+ header.column.resetSize();+ }, [header.column]);++ return (+ // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions, jsx-a11y/no-noninteractive-tabindex+ <div+ role="separator"+ aria-orientation="vertical"+ aria-label={`Resize ${label} column`}+ aria-valuenow={header.column.getSize()}+ aria-valuemin={defaultColumnDef.minSize}+ aria-valuemax={defaultColumnDef.maxSize}+ tabIndex={0} // eslint-disable-line jsx-a11y/no-noninteractive-tabindex+ className={cn(+ "absolute -end-px top-0 z-50 h-full w-0.5 cursor-ew-resize touch-none bg-border transition-opacity select-none after:absolute after:inset-y-0 after:start-1/2 after:h-full after:w-[18px] after:-translate-x-1/2 after:content-[''] hover:bg-foreground focus:bg-foreground focus:outline-none",+ header.column.getIsResizing() ? "bg-foreground" : "opacity-0 hover:opacity-100"+ )}+ onDoubleClick={onDoubleClick}+ onMouseDown={header.getResizeHandler()}+ onTouchStart={header.getResizeHandler()}+ />+ );+}diff --git a/frontend/src/components/v3/generic/DataGrid/data-grid-context-menu.tsx b/frontend/src/components/v3/generic/DataGrid/data-grid-context-menu.tsxnew file mode 100644index 0000000000..8e01c082b3--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/data-grid-context-menu.tsx@@ -0,0 +1,211 @@+import * as React from "react";+import type { ColumnDef, TableMeta } from "@tanstack/react-table";+import { CircleOffIcon, EraserIcon } from "lucide-react";+import { toast } from "sonner";++import {+ UnstableDropdownMenu as DropdownMenu,+ UnstableDropdownMenuContent as DropdownMenuContent,+ UnstableDropdownMenuItem as DropdownMenuItem,+ UnstableDropdownMenuTrigger as DropdownMenuTrigger+} from "@app/components/v3/generic/Dropdown";++import { useAsRef } from "./hooks/use-as-ref";+import type { CellUpdate, ContextMenuState } from "./data-grid-types";+import { parseCellKey } from "./data-grid-utils";++interface DataGridContextMenuProps<TData> {+ tableMeta: TableMeta<TData>;+ columns: Array<ColumnDef<TData>>;+ contextMenu: ContextMenuState;+}++export function DataGridContextMenu<TData>({+ tableMeta,+ columns,+ contextMenu+}: DataGridContextMenuProps<TData>) {+ const onContextMenuOpenChange = tableMeta?.onContextMenuOpenChange;+ const selectionState = tableMeta?.selectionState;+ const dataGridRef = tableMeta?.dataGridRef;+ const onDataUpdate = tableMeta?.onDataUpdate;+ const onRowsDelete = tableMeta?.onRowsDelete;+ const onCellsCopy = tableMeta?.onCellsCopy;+ const onCellsCut = tableMeta?.onCellsCut;++ if (!contextMenu.open) return null;++ return (+ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ <ContextMenu+ tableMeta={tableMeta}+ columns={columns}+ dataGridRef={dataGridRef}+ contextMenu={contextMenu}+ onContextMenuOpenChange={onContextMenuOpenChange}+ selectionState={selectionState}+ onDataUpdate={onDataUpdate}+ onRowsDelete={onRowsDelete}+ onCellsCopy={onCellsCopy}+ onCellsCut={onCellsCut}+ />+ );+}++interface ContextMenuProps<TData>+ extends Pick<+ TableMeta<TData>,+ | "dataGridRef"+ | "onContextMenuOpenChange"+ | "selectionState"+ | "onDataUpdate"+ | "onRowsDelete"+ | "onCellsCopy"+ | "onCellsCut"+ | "readOnly"+ >,+ Required<Pick<TableMeta<TData>, "contextMenu">> {+ tableMeta: TableMeta<TData>;+ columns: Array<ColumnDef<TData>>;+}++// eslint-disable-next-line @typescript-eslint/no-use-before-define+const ContextMenu = React.memo(ContextMenuImpl, (prev, next) => {+ if (prev.contextMenu.open !== next.contextMenu.open) return false;+ if (!next.contextMenu.open) return true;+ if (prev.contextMenu.x !== next.contextMenu.x) return false;+ if (prev.contextMenu.y !== next.contextMenu.y) return false;++ const prevSize = prev.selectionState?.selectedCells?.size ?? 0;+ const nextSize = next.selectionState?.selectedCells?.size ?? 0;+ if (prevSize !== nextSize) return false;++ return true;+}) as typeof ContextMenuImpl;++function ContextMenuImpl<TData>({+ tableMeta,+ columns,+ dataGridRef,+ contextMenu,+ onContextMenuOpenChange,+ selectionState,+ onDataUpdate,+ onRowsDelete,+ onCellsCopy,+ onCellsCut+}: ContextMenuProps<TData>) {+ const propsRef = useAsRef({+ dataGridRef,+ selectionState,+ onDataUpdate,+ onRowsDelete,+ onCellsCopy,+ onCellsCut,+ columns+ });++ const triggerStyle = React.useMemo<React.CSSProperties>(+ () => ({+ position: "fixed",+ left: `${contextMenu.x}px`,+ top: `${contextMenu.y}px`,+ width: "1px",+ height: "1px",+ padding: 0,+ margin: 0,+ border: "none",+ background: "transparent",+ pointerEvents: "none",+ opacity: 0+ }),+ [contextMenu.x, contextMenu.y]+ );++ const onCloseAutoFocus: NonNullable<+ React.ComponentProps<typeof DropdownMenuContent>["onCloseAutoFocus"]+ > = React.useCallback(+ (event) => {+ event.preventDefault();+ propsRef.current.dataGridRef?.current?.focus();+ },+ [propsRef]+ );++ const onClear = React.useCallback(() => {+ // eslint-disable-next-line @typescript-eslint/no-shadow+ const { selectionState, columns, onDataUpdate } = propsRef.current;++ if (!selectionState?.selectedCells || selectionState.selectedCells.size === 0) return;++ const updates: Array<CellUpdate> = [];++ // eslint-disable-next-line no-restricted-syntax+ for (const cellKey of selectionState.selectedCells) {+ const { rowIndex, columnId } = parseCellKey(cellKey);++ // Get column from columns array+ const column = columns.find((col) => {+ if (col.id) return col.id === columnId;+ if ("accessorKey" in col) return col.accessorKey === columnId;+ return false;+ });+ const cellVariant = column?.meta?.cell?.variant;++ let emptyValue: unknown = "";+ if (cellVariant === "multi-select" || cellVariant === "file") {+ emptyValue = [];+ } else if (cellVariant === "number" || cellVariant === "date") {+ emptyValue = null;+ } else if (cellVariant === "checkbox") {+ emptyValue = false;+ }++ updates.push({ rowIndex, columnId, value: emptyValue });+ }++ onDataUpdate?.(updates);++ toast.success(`${updates.length} cell${updates.length !== 1 ? "s" : ""} cleared`);+ }, [propsRef]);++ const onSetNull = React.useCallback(() => {+ // eslint-disable-next-line @typescript-eslint/no-shadow+ const { selectionState, onDataUpdate } = propsRef.current;++ if (!selectionState?.selectedCells || selectionState.selectedCells.size === 0) return;++ const updates: Array<CellUpdate> = [];++ // eslint-disable-next-line no-restricted-syntax+ for (const cellKey of selectionState.selectedCells) {+ const { rowIndex, columnId } = parseCellKey(cellKey);+ updates.push({ rowIndex, columnId, value: null });+ }++ onDataUpdate?.(updates);++ toast.success(`${updates.length} cell${updates.length !== 1 ? "s" : ""} set to NULL`);+ }, [propsRef]);++ return (+ <DropdownMenu open={contextMenu.open} onOpenChange={onContextMenuOpenChange}>+ <DropdownMenuTrigger style={triggerStyle} />+ <DropdownMenuContent+ data-grid-popover=""+ align="start"+ className="min-w-[140px] p-0.5 [&_[role=menuitem]]:gap-1.5 [&_[role=menuitem]]:px-2 [&_[role=menuitem]]:py-1 [&_[role=menuitem]]:text-xs [&_svg]:size-3"+ onCloseAutoFocus={onCloseAutoFocus}+ >+ <DropdownMenuItem onSelect={onClear} isDisabled={tableMeta?.readOnly}>+ <EraserIcon />+ Clear+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={onSetNull} isDisabled={tableMeta?.readOnly}>+ <CircleOffIcon />+ Set NULL+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/frontend/src/components/v3/generic/DataGrid/data-grid-keyboard-shortcuts.tsx b/frontend/src/components/v3/generic/DataGrid/data-grid-keyboard-shortcuts.tsxnew file mode 100644index 0000000000..eff6af5c00--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/data-grid-keyboard-shortcuts.tsx@@ -0,0 +1,320 @@+import * as React from "react";+import { SearchIcon, XIcon } from "lucide-react";++import { Button } from "@app/components/v3/generic/Button";+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle+} from "@app/components/v3/generic/Dialog";+import { UnstableInput as Input } from "@app/components/v3/generic/Input";+import { UnstableSeparator as Separator } from "@app/components/v3/generic/Separator";++import { Kbd, KbdGroup } from "./ui/kbd";++const SHORTCUT_KEY = "/";++interface ShortcutGroup {+ title: string;+ shortcuts: Array<{+ keys: string[];+ description: string;+ }>;+}++interface DataGridKeyboardShortcutsProps {+ enableSearch?: boolean;+}++// eslint-disable-next-line @typescript-eslint/no-use-before-define+export const DataGridKeyboardShortcuts = React.memo(DataGridKeyboardShortcutsImpl, (prev, next) => {+ return prev.enableSearch === next.enableSearch;+});++function DataGridKeyboardShortcutsImpl({ enableSearch = false }: DataGridKeyboardShortcutsProps) {+ const [open, setOpen] = React.useState(false);+ const [input, setInput] = React.useState("");+ const inputRef = React.useRef<HTMLInputElement>(null);++ const isMac =+ typeof navigator !== "undefined" ? /Mac|iPhone|iPad|iPod/.test(navigator.userAgent) : false;++ const modKey = isMac ? "⌘" : "Ctrl";++ const onOpenChange = React.useCallback((isOpen: boolean) => {+ setOpen(isOpen);+ if (!isOpen) {+ setInput("");+ }+ }, []);++ const onOpenAutoFocus = React.useCallback((event: Event) => {+ event.preventDefault();+ inputRef.current?.focus();+ }, []);++ const onInputChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => {+ setInput(event.target.value);+ }, []);++ const shortcutGroups: ShortcutGroup[] = React.useMemo(+ () => [+ {+ title: "Navigation",+ shortcuts: [+ {+ keys: ["↑", "↓", "←", "→"],+ description: "Navigate between cells"+ },+ {+ keys: ["Tab"],+ description: "Move to next cell"+ },+ {+ keys: ["Shift", "Tab"],+ description: "Move to previous cell"+ },+ {+ keys: ["Home"],+ description: "Move to first column"+ },+ {+ keys: ["End"],+ description: "Move to last column"+ },+ {+ keys: [modKey, "Home"],+ description: "Move to first cell"+ },+ {+ keys: [modKey, "End"],+ description: "Move to last cell"+ },+ {+ keys: ["PgUp"],+ description: "Move up one page"+ },+ {+ keys: ["PgDn"],+ description: "Move down one page"+ }+ ]+ },+ {+ title: "Selection",+ shortcuts: [+ {+ keys: ["Shift", "↑↓←→"],+ description: "Extend selection"+ },+ {+ keys: [modKey, "A"],+ description: "Select all cells"+ },+ {+ keys: [modKey, "Click"],+ description: "Toggle cell selection"+ },+ {+ keys: ["Shift", "Click"],+ description: "Select range"+ },+ {+ keys: ["Esc"],+ description: "Clear selection"+ }+ ]+ },+ {+ title: "Editing",+ shortcuts: [+ {+ keys: ["Enter"],+ description: "Start editing cell"+ },+ {+ keys: ["Double Click"],+ description: "Start editing cell"+ },+ {+ keys: ["Delete"],+ description: "Clear selected cells"+ },+ {+ keys: ["Backspace"],+ description: "Clear selected cells"+ }+ ]+ },+ ...(enableSearch+ ? [+ {+ title: "Search",+ shortcuts: [+ {+ keys: [modKey, "F"],+ description: "Open search"+ },+ {+ keys: ["Enter"],+ description: "Next match"+ },+ {+ keys: ["Shift", "Enter"],+ description: "Previous match"+ },+ {+ keys: ["Esc"],+ description: "Close search"+ }+ ]+ }+ ]+ : []),+ {+ title: "Sorting",+ shortcuts: [+ {+ keys: [modKey, "Shift", "S"],+ description: "Toggle the sort menu"+ },+ {+ keys: ["Backspace"],+ description: "Remove sort (when focused)"+ },+ {+ keys: ["Delete"],+ description: "Remove sort (when focused)"+ }+ ]+ },+ {+ title: "General",+ shortcuts: [+ {+ keys: [modKey, "/"],+ description: "Show keyboard shortcuts"+ }+ ]+ }+ ],+ [modKey, enableSearch]+ );++ const filteredGroups = React.useMemo(() => {+ if (!input.trim()) return shortcutGroups;++ const query = input.toLowerCase();+ return shortcutGroups+ .map((group) => ({+ ...group,+ shortcuts: group.shortcuts.filter(+ (shortcut) =>+ shortcut.description.toLowerCase().includes(query) ||+ shortcut.keys.some((key) => key.toLowerCase().includes(query))+ )+ }))+ .filter((group) => group.shortcuts.length > 0);+ }, [shortcutGroups, input]);++ React.useEffect(() => {+ function onKeyDown(event: KeyboardEvent) {+ if ((event.ctrlKey || event.metaKey) && event.key === SHORTCUT_KEY) {+ event.preventDefault();+ setOpen(true);+ }+ }++ window.addEventListener("keydown", onKeyDown);+ return () => {+ window.removeEventListener("keydown", onKeyDown);+ };+ }, []);++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent+ className="max-w-2xl px-0"+ onOpenAutoFocus={onOpenAutoFocus}+ showCloseButton={false}+ >+ <DialogClose className="absolute top-6 right-6" asChild>+ <Button variant="ghost" size="xs" className="size-6">+ <XIcon />+ </Button>+ </DialogClose>+ <DialogHeader className="px-6">+ <DialogTitle>Keyboard shortcuts</DialogTitle>+ <DialogDescription className="sr-only">+ Use these keyboard shortcuts to navigate and interact with the data grid more+ efficiently.+ </DialogDescription>+ </DialogHeader>+ <div className="px-6">+ <div className="relative">+ <SearchIcon className="absolute top-1/2 left-3 size-3.5 -translate-y-1/2 text-muted" />+ <Input+ ref={inputRef}+ placeholder="Search shortcuts..."+ className="h-8 pl-8"+ value={input}+ onChange={onInputChange}+ />+ </div>+ </div>+ <Separator className="mx-auto data-[orientation=horizontal]:w-[calc(100%-(--spacing(12)))]" />+ <div className="h-[40vh] overflow-y-auto px-6">+ {filteredGroups.length === 0 ? (+ <div className="flex h-full flex-col items-center justify-center gap-3 text-center">+ <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground">+ <SearchIcon className="pointer-events-none size-6" />+ </div>+ <div className="flex flex-col gap-1">+ <div className="text-lg font-medium tracking-tight">No shortcuts found</div>+ <p className="text-sm text-muted">Try searching for a different term.</p>+ </div>+ </div>+ ) : (+ <div className="flex flex-col gap-6">+ {filteredGroups.map((shortcutGroup) => (+ <div key={shortcutGroup.title} className="flex flex-col gap-2">+ <h3 className="text-sm font-semibold text-foreground">{shortcutGroup.title}</h3>+ <div className="divide-y divide-border rounded-md border">+ {shortcutGroup.shortcuts.map((shortcut, index) => (+ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ <ShortcutCard+ // eslint-disable-next-line react/no-array-index-key+ key={index}+ keys={shortcut.keys}+ description={shortcut.description}+ />+ ))}+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ </DialogContent>+ </Dialog>+ );+}++function ShortcutCard({ keys, description }: ShortcutGroup["shortcuts"][number]) {+ return (+ <div className="flex items-center gap-4 px-3 py-2">+ <span className="flex-1 text-sm">{description}</span>+ <KbdGroup className="shrink-0">+ {keys.map((key, index) => (+ <React.Fragment key={key}>+ {index > 0 && <span className="text-xs text-muted">+</span>}+ <Kbd>{key}</Kbd>+ </React.Fragment>+ ))}+ </KbdGroup>+ </div>+ );+}diff --git a/frontend/src/components/v3/generic/DataGrid/data-grid-paste-dialog.tsx b/frontend/src/components/v3/generic/DataGrid/data-grid-paste-dialog.tsxnew file mode 100644index 0000000000..b5a33ecc73--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/data-grid-paste-dialog.tsx@@ -0,0 +1,138 @@+import * as React from "react";+import type { TableMeta } from "@tanstack/react-table";++import { Button } from "@app/components/v3/generic/Button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle+} from "@app/components/v3/generic/Dialog";+import { cn } from "@app/components/v3/utils";++import { useAsRef } from "./hooks/use-as-ref";+import type { PasteDialogState } from "./data-grid-types";++interface DataGridPasteDialogProps<TData> {+ tableMeta: TableMeta<TData>;+ pasteDialog: PasteDialogState;+}++export function DataGridPasteDialog<TData>({+ tableMeta,+ pasteDialog+}: DataGridPasteDialogProps<TData>) {+ const onPasteDialogOpenChange = tableMeta?.onPasteDialogOpenChange;+ const onCellsPaste = tableMeta?.onCellsPaste;++ if (!pasteDialog.open) return null;++ return (+ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ <PasteDialog+ pasteDialog={pasteDialog}+ onPasteDialogOpenChange={onPasteDialogOpenChange}+ onCellsPaste={onCellsPaste}+ />+ );+}++interface PasteDialogProps+ extends Pick<TableMeta<unknown>, "onPasteDialogOpenChange" | "onCellsPaste">,+ Required<Pick<TableMeta<unknown>, "pasteDialog">> {}++// eslint-disable-next-line @typescript-eslint/no-use-before-define+const PasteDialog = React.memo(PasteDialogImpl, (prev, next) => {+ if (prev.pasteDialog.open !== next.pasteDialog.open) return false;+ if (!next.pasteDialog.open) return true;+ if (prev.pasteDialog.rowsNeeded !== next.pasteDialog.rowsNeeded) return false;++ return true;+});++function PasteDialogImpl({ pasteDialog, onPasteDialogOpenChange, onCellsPaste }: PasteDialogProps) {+ const propsRef = useAsRef({+ onPasteDialogOpenChange,+ onCellsPaste+ });++ const expandRadioRef = React.useRef<HTMLInputElement | null>(null);++ const onOpenChange = React.useCallback(+ (open: boolean) => {+ propsRef.current.onPasteDialogOpenChange?.(open);+ },+ [propsRef]+ );++ const onCancel = React.useCallback(() => {+ propsRef.current.onPasteDialogOpenChange?.(false);+ }, [propsRef]);++ const onContinue = React.useCallback(() => {+ propsRef.current.onCellsPaste?.(expandRadioRef.current?.checked ?? false);+ }, [propsRef]);++ return (+ <Dialog open={pasteDialog.open} onOpenChange={onOpenChange}>+ <DialogContent data-grid-popover="">+ <DialogHeader>+ <DialogTitle>Do you want to add more rows?</DialogTitle>+ <DialogDescription>+ We need <strong>{pasteDialog.rowsNeeded}</strong> additional row+ {pasteDialog.rowsNeeded !== 1 ? "s" : ""} to paste everything from your clipboard.+ </DialogDescription>+ </DialogHeader>+ <div className="flex flex-col gap-3 py-1">+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}+ <label className="flex cursor-pointer items-start gap-3">+ {/* eslint-disable-next-line @typescript-eslint/no-use-before-define */}+ <RadioItem ref={expandRadioRef} name="expand-option" value="expand" defaultChecked />+ <div className="flex flex-col gap-1">+ <span className="text-sm leading-none font-medium">Create new rows</span>+ <span className="text-sm text-muted">+ Add {pasteDialog.rowsNeeded} new row+ {pasteDialog.rowsNeeded !== 1 ? "s" : ""} to the table and paste all data+ </span>+ </div>+ </label>+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}+ <label className="flex cursor-pointer items-start gap-3">+ {/* eslint-disable-next-line @typescript-eslint/no-use-before-define */}+ <RadioItem name="expand-option" value="no-expand" />+ <div className="flex flex-col gap-1">+ <span className="text-sm leading-none font-medium">Keep current rows</span>+ <span className="text-sm text-muted">Paste only what fits in the existing rows</span>+ </div>+ </label>+ </div>+ <DialogFooter>+ <Button variant="outline" onClick={onCancel}>+ Cancel+ </Button>+ <Button onClick={onContinue}>Continue</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++// eslint-disable-next-line react/prop-types+function RadioItem({ className, ...props }: React.ComponentProps<"input">) {+ return (+ <input+ type="radio"+ className={cn(+ "border-input relative size-4 shrink-0 appearance-none rounded-full border bg-background shadow-xs transition-[color,box-shadow] outline-none",+ "text-primary focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",+ "disabled:cursor-not-allowed disabled:opacity-50",+ "checked:before:absolute checked:before:start-1/2 checked:before:top-1/2 checked:before:size-2 checked:before:-translate-x-1/2 checked:before:-translate-y-1/2 checked:before:rounded-full checked:before:bg-primary checked:before:content-['']",+ "bg-input/30",+ className+ )}+ {...props}+ />+ );+}diff --git a/frontend/src/components/v3/generic/DataGrid/data-grid-row.tsx b/frontend/src/components/v3/generic/DataGrid/data-grid-row.tsxnew file mode 100644index 0000000000..b78070b653--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/data-grid-row.tsx@@ -0,0 +1,299 @@+import * as React from "react";+import type { ColumnPinningState, Row, TableMeta, VisibilityState } from "@tanstack/react-table";+import type { VirtualItem } from "@tanstack/react-virtual";++import { cn } from "@app/components/v3/utils";++import { useComposedRefs } from "./compose-refs";+import { DataGridCell } from "./data-grid-cell";+import type { CellPosition, Direction, RowHeightValue } from "./data-grid-types";+import {+ flexRender,+ getCellKey,+ getColumnBorderVisibility,+ getColumnPinningStyle,+ getRowHeightValue,+ sanitizeCssId+} from "./data-grid-utils";++interface DataGridRowProps<TData> extends React.ComponentProps<"div"> {+ row: Row<TData>;+ tableMeta: TableMeta<TData>;+ virtualItem: VirtualItem;+ measureElement: (node: Element | null) => void;+ rowMapRef: React.RefObject<Map<number, HTMLDivElement>>;+ rowHeight: RowHeightValue;+ columnVisibility: VisibilityState;+ columnPinning: ColumnPinningState;+ focusedCell: CellPosition | null;+ editingCell: CellPosition | null;+ cellSelectionKeys: Set<string>;+ searchMatchColumns: Set<string> | null;+ activeSearchMatch: CellPosition | null;+ dir: Direction;+ readOnly: boolean;+ stretchColumns: boolean;+ adjustLayout: boolean;+}++// eslint-disable-next-line @typescript-eslint/no-use-before-define+export const DataGridRow = React.memo(DataGridRowImpl, (prev, next) => {+ const prevRowIndex = prev.virtualItem.index;+ const nextRowIndex = next.virtualItem.index;++ // Re-render if row identity changed+ if (prev.row.id !== next.row.id) {+ return false;+ }++ // Re-render if row data (original) reference changed+ if (prev.row.original !== next.row.original) {+ return false;+ }++ // Re-render if virtual position changed (handles transform updates)+ if (prev.virtualItem.start !== next.virtualItem.start) {+ return false;+ }++ // Re-render if focus state changed for this row+ const prevHasFocus = prev.focusedCell?.rowIndex === prevRowIndex;+ const nextHasFocus = next.focusedCell?.rowIndex === nextRowIndex;++ if (prevHasFocus !== nextHasFocus) {+ return false;+ }++ // Re-render if focused column changed within this row+ if (nextHasFocus && prevHasFocus) {+ if (prev.focusedCell?.columnId !== next.focusedCell?.columnId) {+ return false;+ }+ }++ // Re-render if editing state changed for this row+ const prevHasEditing = prev.editingCell?.rowIndex === prevRowIndex;+ const nextHasEditing = next.editingCell?.rowIndex === nextRowIndex;++ if (prevHasEditing !== nextHasEditing) {+ return false;+ }++ // Re-render if editing column changed within this row+ if (nextHasEditing && prevHasEditing) {+ if (prev.editingCell?.columnId !== next.editingCell?.columnId) {+ return false;+ }+ }++ // Re-render if this row's selected cells changed+ // Using stable Set reference that only includes this row's cells+ if (prev.cellSelectionKeys !== next.cellSelectionKeys) {+ return false;+ }++ // Re-render if column visibility changed+ if (prev.columnVisibility !== next.columnVisibility) {+ return false;+ }++ // Re-render if row height changed+ if (prev.rowHeight !== next.rowHeight) {+ return false;+ }++ // Re-render if column pinning state changed+ if (prev.columnPinning !== next.columnPinning) {+ return false;+ }++ // Re-render if readOnly changed+ if (prev.readOnly !== next.readOnly) {+ return false;+ }++ // Re-render if search match columns changed for this row+ if (prev.searchMatchColumns !== next.searchMatchColumns) {+ return false;+ }++ // Re-render if active search match changed for this row+ if (prev.activeSearchMatch?.columnId !== next.activeSearchMatch?.columnId) {+ return false;+ }++ // Re-render if direction changed+ if (prev.dir !== next.dir) {+ return false;+ }++ // Re-render if adjustLayout state changed+ if (prev.adjustLayout !== next.adjustLayout) {+ return false;+ }++ // Re-render if stretchColumns changed+ if (prev.stretchColumns !== next.stretchColumns) {+ return false;+ }++ // Skip re-render - props are equal+ return true;+}) as typeof DataGridRowImpl;++function DataGridRowImpl<TData>({+ row,+ tableMeta,+ virtualItem,+ measureElement,+ rowMapRef,+ rowHeight,+ columnVisibility,+ columnPinning,+ focusedCell,+ editingCell,+ cellSelectionKeys,+ searchMatchColumns,+ activeSearchMatch,+ dir,+ readOnly,+ stretchColumns,+ adjustLayout,+ className,+ style,+ ref,+ ...props+}: DataGridRowProps<TData>) {+ const virtualRowIndex = virtualItem.index;++ const onRowChange = React.useCallback(+ (node: HTMLDivElement | null) => {+ if (typeof virtualRowIndex === "undefined") return;++ if (node) {+ measureElement(node);+ rowMapRef.current?.set(virtualRowIndex, node);+ } else {+ rowMapRef.current?.delete(virtualRowIndex);+ }+ },+ [virtualRowIndex, measureElement, rowMapRef]+ );++ const rowRef = useComposedRefs(ref as React.Ref<HTMLDivElement> | undefined, onRowChange);++ const isRowSelected = row.getIsSelected();++ // Memoize visible cells to avoid recreating cell array on every render+ // Though TanStack returns new Cell wrappers, memoizing the array helps React's reconciliation+ // biome-ignore lint/correctness/useExhaustiveDependencies: columnVisibility and columnPinning are used for calculating the visible cells+ const visibleCells = React.useMemo(+ () => row.getVisibleCells(),+ [row, columnVisibility, columnPinning]+ );++ const isRowNew = tableMeta?.getIsRowNew?.(virtualRowIndex) ?? false;++ const isRowDirty = React.useMemo(() => {+ if (isRowNew) return false;+ if (!tableMeta?.getIsCellDirty) return false;+ return visibleCells.some(+ (cell) =>+ cell.column.id !== "select" && tableMeta.getIsCellDirty!(virtualRowIndex, cell.column.id)+ );+ }, [isRowNew, visibleCells, tableMeta, virtualRowIndex]);++ return (+ <div+ key={row.id}+ role="row"+ aria-rowindex={virtualRowIndex + 2}+ aria-selected={isRowSelected}+ data-index={virtualRowIndex}+ data-slot="grid-row"+ tabIndex={-1}+ {...props}+ ref={rowRef}+ className={cn(+ "absolute flex w-full border-b border-border",+ !adjustLayout && "will-change-transform",+ isRowNew && "bg-success/[0.07]",+ isRowDirty && "bg-warning/[0.07]",+ isRowSelected && "bg-danger/[0.07]",+ className+ )}+ style={{+ height: `${getRowHeightValue(rowHeight)}px`,+ ...(adjustLayout+ ? { top: `${virtualItem.start}px` }+ : { transform: `translateY(${virtualItem.start}px)` }),+ ...style+ }}+ >+ {visibleCells.map((cell, colIndex) => {+ const columnId = cell.column.id;++ const isCellFocused =+ focusedCell?.rowIndex === virtualRowIndex && focusedCell?.columnId === columnId;+ const isCellEditing =+ editingCell?.rowIndex === virtualRowIndex && editingCell?.columnId === columnId;+ const isCellSelected =+ cellSelectionKeys?.has(getCellKey(virtualRowIndex, columnId)) ?? false;++ const isSearchMatch = searchMatchColumns?.has(columnId) ?? false;+ const isActiveSearchMatch = activeSearchMatch?.columnId === columnId;+ const isCellDirty =+ !isRowNew && (tableMeta?.getIsCellDirty?.(virtualRowIndex, columnId) ?? false);++ const nextCell = visibleCells[colIndex + 1];+ const isLastColumn = colIndex === visibleCells.length - 1;+ const { showEndBorder, showStartBorder } = getColumnBorderVisibility({+ column: cell.column,+ nextColumn: nextCell?.column,+ isLastColumn+ });++ return (+ <div+ key={cell.id}+ role="gridcell"+ aria-colindex={colIndex + 1}+ data-highlighted={isCellFocused ? "" : undefined}+ data-slot="grid-cell"+ tabIndex={-1}+ className={cn({+ grow: stretchColumns && columnId !== "select",+ "border-e": showEndBorder && columnId !== "select",+ "border-s": showStartBorder && columnId !== "select"+ })}+ style={{+ ...getColumnPinningStyle({ column: cell.column, dir }),+ width: `calc(var(--col-${sanitizeCssId(columnId)}-size) * 1px)`+ }}+ >+ {typeof cell.column.columnDef.header === "function" ? (+ <div className="flex size-full items-center px-3 py-1.5">+ {flexRender(cell.column.columnDef.cell, cell.getContext())}+ </div>+ ) : (+ <DataGridCell+ cell={cell}+ tableMeta={tableMeta}+ rowIndex={virtualRowIndex}+ columnId={columnId}+ rowHeight={rowHeight}+ isFocused={isCellFocused}+ isEditing={isCellEditing}+ isSelected={isCellSelected && !isRowSelected}+ isSearchMatch={isSearchMatch}+ isActiveSearchMatch={isActiveSearchMatch}+ isDirty={isCellDirty}+ readOnly={readOnly}+ />+ )}+ </div>+ );+ })}+ </div>+ );+}diff --git a/frontend/src/components/v3/generic/DataGrid/data-grid-search.tsx b/frontend/src/components/v3/generic/DataGrid/data-grid-search.tsxnew file mode 100644index 0000000000..385b6702ec--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/data-grid-search.tsx@@ -0,0 +1,224 @@+import * as React from "react";+import { ChevronDown, ChevronUp, X } from "lucide-react";++import { Button } from "@app/components/v3/generic/Button";+import { UnstableInput as Input } from "@app/components/v3/generic/Input";++import { useAsRef } from "./hooks/use-as-ref";+import { useDebouncedCallback } from "./hooks/use-debounced-callback";+import type { SearchState } from "./data-grid-types";++// eslint-disable-next-line @typescript-eslint/no-empty-object-type+interface DataGridSearchProps extends SearchState {}++// eslint-disable-next-line @typescript-eslint/no-use-before-define+export const DataGridSearch = React.memo(DataGridSearchImpl, (prev, next) => {+ if (prev.searchOpen !== next.searchOpen) return false;++ if (!next.searchOpen) return true;++ if (prev.searchQuery !== next.searchQuery || prev.matchIndex !== next.matchIndex) {+ return false;+ }++ if (prev.searchMatches.length !== next.searchMatches.length) return false;++ // eslint-disable-next-line no-plusplus+ for (let i = 0; i < prev.searchMatches.length; i++) {+ const prevMatch = prev.searchMatches[i];+ const nextMatch = next.searchMatches[i];++ if (!prevMatch || !nextMatch) return false;++ if (prevMatch.rowIndex !== nextMatch.rowIndex || prevMatch.columnId !== nextMatch.columnId) {+ return false;+ }+ }++ return true;+});++function DataGridSearchImpl({+ searchMatches,+ matchIndex,+ searchOpen,+ onSearchOpenChange,+ searchQuery,+ onSearchQueryChange,+ onSearch,+ onNavigateToNextMatch,+ onNavigateToPrevMatch+}: DataGridSearchProps) {+ const propsRef = useAsRef({+ onSearchOpenChange,+ onSearchQueryChange,+ onSearch,+ onNavigateToNextMatch,+ onNavigateToPrevMatch+ });++ const inputRef = React.useRef<HTMLInputElement>(null);++ React.useEffect(() => {+ if (searchOpen) {+ requestAnimationFrame(() => {+ inputRef.current?.focus();+ });+ }+ }, [searchOpen]);++ React.useEffect(() => {+ if (!searchOpen) return undefined;++ function onEscape(event: KeyboardEvent) {+ if (event.key === "Escape") {+ event.preventDefault();+ propsRef.current.onSearchOpenChange(false);+ }+ }++ document.addEventListener("keydown", onEscape);+ return () => document.removeEventListener("keydown", onEscape);+ }, [searchOpen, propsRef]);++ const onKeyDown = React.useCallback(+ (event: React.KeyboardEvent) => {+ event.stopPropagation();++ if (event.key === "Enter") {+ event.preventDefault();+ if (event.shiftKey) {+ propsRef.current.onNavigateToPrevMatch();+ } else {+ propsRef.current.onNavigateToNextMatch();+ }+ }+ },+ [propsRef]+ );++ const debouncedSearch = useDebouncedCallback((query: string) => {+ propsRef.current.onSearch(query);+ }, 150);++ const onChange = React.useCallback(+ (event: React.ChangeEvent<HTMLInputElement>) => {+ const { value } = event.target;+ propsRef.current.onSearchQueryChange(value);+ debouncedSearch(value);+ },+ [propsRef, debouncedSearch]+ );++ const onTriggerPointerDown = React.useCallback((event: React.PointerEvent<HTMLButtonElement>) => {+ // prevent implicit pointer capture+ const { target } = event;+ if (!(target instanceof HTMLElement)) return;+ if (target.hasPointerCapture(event.pointerId)) {+ target.releasePointerCapture(event.pointerId);+ }++ // Only prevent default if we're not clicking on the input+ // This allows text selection in the input while still preventing focus stealing elsewhere+ if (+ event.button === 0 &&+ event.ctrlKey === false &&+ event.pointerType === "mouse" &&+ !(event.target instanceof HTMLInputElement)+ ) {+ event.preventDefault();+ }+ }, []);++ const onPrevMatchPointerDown = React.useCallback(+ (event: React.PointerEvent<HTMLButtonElement>) => onTriggerPointerDown(event),+ [onTriggerPointerDown]+ );++ const onNextMatchPointerDown = React.useCallback(+ (event: React.PointerEvent<HTMLButtonElement>) => onTriggerPointerDown(event),+ [onTriggerPointerDown]+ );++ const onClose = React.useCallback(() => {+ propsRef.current.onSearchOpenChange(false);+ }, [propsRef]);++ const onPrevMatch = React.useCallback(() => {+ propsRef.current.onNavigateToPrevMatch();+ }, [propsRef]);++ const onNextMatch = React.useCallback(() => {+ propsRef.current.onNavigateToNextMatch();+ }, [propsRef]);++ if (!searchOpen) return null;++ return (+ <div+ role="search"+ data-slot="grid-search"+ className="absolute end-4 top-4 z-50 flex animate-in flex-col gap-2 rounded-lg border bg-background p-2 shadow-lg fade-in-0 slide-in-from-top-2"+ >+ <div className="flex items-center gap-2">+ <Input+ autoComplete="off"+ autoCorrect="off"+ autoCapitalize="off"+ spellCheck={false}+ placeholder="Find in table..."+ className="h-8 w-64"+ ref={inputRef}+ value={searchQuery}+ onChange={onChange}+ onKeyDown={onKeyDown}+ />+ <div className="flex items-center gap-1">+ <Button+ aria-label="Previous match"+ variant="ghost"+ size="xs"+ className="size-7"+ onClick={onPrevMatch}+ onPointerDown={onPrevMatchPointerDown}+ disabled={searchMatches.length === 0}+ >+ <ChevronUp />+ </Button>+ <Button+ aria-label="Next match"+ variant="ghost"+ size="xs"+ className="size-7"+ onClick={onNextMatch}+ onPointerDown={onNextMatchPointerDown}+ disabled={searchMatches.length === 0}+ >+ <ChevronDown />+ </Button>+ <Button+ aria-label="Close search"+ variant="ghost"+ size="xs"+ className="size-7"+ onClick={onClose}+ >+ <X />+ </Button>+ </div>+ </div>+ <div className="flex items-center gap-1 text-xs whitespace-nowrap text-muted">+ {/* eslint-disable-next-line no-nested-ternary */}+ {searchMatches.length > 0 ? (+ <span>+ {matchIndex + 1} of {searchMatches.length}+ </span>+ ) : searchQuery ? (+ <span>No results</span>+ ) : (+ <span>Type to search</span>+ )}+ </div>+ </div>+ );+}diff --git a/frontend/src/components/v3/generic/DataGrid/data-grid-types.ts b/frontend/src/components/v3/generic/DataGrid/data-grid-types.tsnew file mode 100644index 0000000000..c2e4e9cfaa--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/data-grid-types.ts@@ -0,0 +1,255 @@+import type { Cell, RowData, TableMeta } from "@tanstack/react-table";++export type Direction = "ltr" | "rtl";++export type RowHeightValue = "short" | "medium" | "tall" | "extra-tall";++export interface CellSelectOption {+ label: string;+ value: string;+ icon?: React.FC<React.SVGProps<SVGSVGElement>>;+ count?: number;+}++export type CellOpts =+ | {+ variant: "short-text";+ }+ | {+ variant: "long-text";+ }+ | {+ variant: "number";+ min?: number;+ max?: number;+ step?: number;+ }+ | {+ variant: "select";+ options: CellSelectOption[];+ }+ | {+ variant: "multi-select";+ options: CellSelectOption[];+ }+ | {+ variant: "checkbox";+ }+ | {+ variant: "date";+ }+ | {+ variant: "url";+ }+ | {+ variant: "file";+ maxFileSize?: number;+ maxFiles?: number;+ accept?: string;+ multiple?: boolean;+ };++export interface CellUpdate {+ rowIndex: number;+ columnId: string;+ value: unknown;+}++declare module "@tanstack/react-table" {+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ interface ColumnMeta<TData extends RowData, TValue> {+ label?: string;+ typeLabel?: string;+ cell?: CellOpts;+ columnIndicator?: {+ type: "pk" | "fk";+ tooltip?: string;+ };+ }++ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ interface TableMeta<TData extends RowData> {+ dataGridRef?: React.RefObject<HTMLElement | null>;+ cellMapRef?: React.RefObject<Map<string, HTMLDivElement>>;+ focusedCell?: CellPosition | null;+ editingCell?: CellPosition | null;+ selectionState?: SelectionState;+ searchOpen?: boolean;+ getIsCellSelected?: (rowIndex: number, columnId: string) => boolean;+ getIsSearchMatch?: (rowIndex: number, columnId: string) => boolean;+ getIsActiveSearchMatch?: (rowIndex: number, columnId: string) => boolean;+ getIsCellDirty?: (rowIndex: number, columnId: string) => boolean;+ getIsRowNew?: (rowIndex: number) => boolean;+ getVisualRowIndex?: (rowId: string) => number | undefined;+ rowHeight?: RowHeightValue;+ onRowHeightChange?: (value: RowHeightValue) => void;+ onRowSelect?: (rowIndex: number, checked: boolean, shiftKey: boolean) => void;+ onDataUpdate?: (params: CellUpdate | Array<CellUpdate>) => void;+ onRowsDelete?: (rowIndices: number[]) => void | Promise<void>;+ onColumnClick?: (columnId: string) => void;+ onCellClick?: (rowIndex: number, columnId: string, event?: React.MouseEvent) => void;+ onCellDoubleClick?: (rowIndex: number, columnId: string) => void;+ onCellMouseDown?: (rowIndex: number, columnId: string, event: React.MouseEvent) => void;+ onCellMouseEnter?: (rowIndex: number, columnId: string) => void;+ onCellMouseUp?: () => void;+ onCellContextMenu?: (rowIndex: number, columnId: string, event: React.MouseEvent) => void;+ onCellEditingStart?: (rowIndex: number, columnId: string) => void;+ onCellEditingStop?: (opts?: {+ direction?: NavigationDirection;+ moveToNextRow?: boolean;+ }) => void;+ onCellsCopy?: () => void;+ onCellsCut?: () => void;+ onCellsPaste?: (expand?: boolean) => void;+ onSelectionClear?: () => void;+ onFilesUpload?: (params: {+ files: File[];+ rowIndex: number;+ columnId: string;+ }) => Promise<FileCellData[]>;+ onFilesDelete?: (params: {+ fileIds: string[];+ rowIndex: number;+ columnId: string;+ }) => void | Promise<void>;+ contextMenu?: ContextMenuState;+ onContextMenuOpenChange?: (open: boolean) => void;+ pasteDialog?: PasteDialogState;+ onPasteDialogOpenChange?: (open: boolean) => void;+ readOnly?: boolean;+ }+}++export interface CellPosition {+ rowIndex: number;+ columnId: string;+}++export interface CellRange {+ start: CellPosition;+ end: CellPosition;+}++export interface SelectionState {+ selectedCells: Set<string>;+ selectionRange: CellRange | null;+ isSelecting: boolean;+}++export interface ContextMenuState {+ open: boolean;+ x: number;+ y: number;+}++export interface PasteDialogState {+ open: boolean;+ rowsNeeded: number;+ clipboardText: string;+}++export type NavigationDirection =+ | "up"+ | "down"+ | "left"+ | "right"+ | "home"+ | "end"+ | "ctrl+up"+ | "ctrl+down"+ | "ctrl+home"+ | "ctrl+end"+ | "pageup"+ | "pagedown"+ | "pageleft"+ | "pageright";++export interface SearchState {+ searchMatches: CellPosition[];+ matchIndex: number;+ searchOpen: boolean;+ onSearchOpenChange: (open: boolean) => void;+ searchQuery: string;+ onSearchQueryChange: (query: string) => void;+ onSearch: (query: string) => void;+ onNavigateToNextMatch: () => void;+ onNavigateToPrevMatch: () => void;+}++export interface DataGridCellProps<TData> {+ cell: Cell<TData, unknown>;+ tableMeta: TableMeta<TData>;+ rowIndex: number;+ columnId: string;+ rowHeight: RowHeightValue;+ isEditing: boolean;+ isFocused: boolean;+ isSelected: boolean;+ isSearchMatch: boolean;+ isActiveSearchMatch: boolean;+ isDirty: boolean;+ readOnly: boolean;+}++export interface FileCellData {+ id: string;+ name: string;+ size: number;+ type: string;+ url?: string;+}++export type TextFilterOperator =+ | "contains"+ | "notContains"+ | "equals"+ | "notEquals"+ | "startsWith"+ | "endsWith"+ | "isEmpty"+ | "isNotEmpty";++export type NumberFilterOperator =+ | "equals"+ | "notEquals"+ | "lessThan"+ | "lessThanOrEqual"+ | "greaterThan"+ | "greaterThanOrEqual"+ | "isBetween"+ | "isEmpty"+ | "isNotEmpty";++export type DateFilterOperator =+ | "equals"+ | "notEquals"+ | "before"+ | "after"+ | "onOrBefore"+ | "onOrAfter"+ | "isBetween"+ | "isEmpty"+ | "isNotEmpty";++export type SelectFilterOperator =+ | "is"+ | "isNot"+ | "isAnyOf"+ | "isNoneOf"+ | "isEmpty"+ | "isNotEmpty";++export type BooleanFilterOperator = "isTrue" | "isFalse";++export type FilterOperator =+ | TextFilterOperator+ | NumberFilterOperator+ | DateFilterOperator+ | SelectFilterOperator+ | BooleanFilterOperator;++export interface FilterValue {+ operator: FilterOperator;+ value?: string | number | string[];+ endValue?: string | number;+}diff --git a/frontend/src/components/v3/generic/DataGrid/data-grid-utils.ts b/frontend/src/components/v3/generic/DataGrid/data-grid-utils.tsnew file mode 100644index 0000000000..e995e9a7bb--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/data-grid-utils.ts@@ -0,0 +1,351 @@+import type * as React from "react";+import type { Column, Table } from "@tanstack/react-table";+import {+ BaselineIcon,+ CalendarIcon,+ CheckSquareIcon,+ File,+ FileArchive,+ FileAudio,+ FileIcon,+ FileImage,+ FileSpreadsheet,+ FileText,+ FileVideo,+ HashIcon,+ LinkIcon,+ ListChecksIcon,+ ListIcon,+ Presentation,+ TextInitialIcon+} from "lucide-react";++import type {+ CellOpts,+ CellPosition,+ Direction,+ FileCellData,+ RowHeightValue+} from "./data-grid-types";++export function flexRender<TProps extends object>(+ Comp: ((props: TProps) => React.ReactNode) | string | undefined,+ props: TProps+): React.ReactNode {+ if (typeof Comp === "string") {+ return Comp;+ }+ return Comp?.(props);+}++export function getIsFileCellData(item: unknown): item is FileCellData {+ return (+ !!item &&+ typeof item === "object" &&+ "id" in item &&+ "name" in item &&+ "size" in item &&+ "type" in item+ );+}++export function matchSelectOption(+ value: string,+ options: { value: string; label: string }[]+): string | undefined {+ return options.find(+ (o) =>+ o.value === value ||+ o.value.toLowerCase() === value.toLowerCase() ||+ o.label.toLowerCase() === value.toLowerCase()+ )?.value;+}++export function sanitizeCssId(id: string): string {+ return id.replace(/[^a-zA-Z0-9_-]/g, "_");+}++export function getCellKey(rowIndex: number, columnId: string) {+ return `${rowIndex}:${columnId}`;+}++export function parseCellKey(cellKey: string): Required<CellPosition> {+ const parts = cellKey.split(":");+ const rowIndexStr = parts[0];+ const columnId = parts[1];+ if (rowIndexStr && columnId) {+ const rowIndex = parseInt(rowIndexStr, 10);+ if (!Number.isNaN(rowIndex)) {+ return { rowIndex, columnId };+ }+ }+ return { rowIndex: 0, columnId: "" };+}++export function getRowHeightValue(rowHeight: RowHeightValue): number {+ const rowHeightMap: Record<RowHeightValue, number> = {+ short: 36,+ medium: 56,+ tall: 76,+ "extra-tall": 96+ };++ return rowHeightMap[rowHeight];+}++export function getLineCount(rowHeight: RowHeightValue): number {+ const lineCountMap: Record<RowHeightValue, number> = {+ short: 1,+ medium: 2,+ tall: 3,+ "extra-tall": 4+ };++ return lineCountMap[rowHeight];+}++export function getColumnBorderVisibility<TData>(params: {+ column: Column<TData>;+ nextColumn?: Column<TData>;+ isLastColumn: boolean;+}): {+ showEndBorder: boolean;+ showStartBorder: boolean;+} {+ const { column, nextColumn, isLastColumn } = params;++ const isPinned = column.getIsPinned();+ const isFirstRightPinnedColumn = isPinned === "right" && column.getIsFirstColumn("right");+ const isLastRightPinnedColumn = isPinned === "right" && column.getIsLastColumn("right");++ const nextIsPinned = nextColumn?.getIsPinned();+ const isBeforeRightPinned = nextIsPinned === "right" && nextColumn?.getIsFirstColumn("right");++ const showEndBorder = !isBeforeRightPinned && (isLastColumn || !isLastRightPinnedColumn);++ const showStartBorder = isFirstRightPinnedColumn;++ return {+ showEndBorder,+ showStartBorder+ };+}++export function getColumnPinningStyle<TData>(params: {+ column: Column<TData>;+ withBorder?: boolean;+ dir?: Direction;+}): React.CSSProperties {+ const { column, dir = "ltr", withBorder = false } = params;++ const isPinned = column.getIsPinned();+ const isLastLeftPinnedColumn = isPinned === "left" && column.getIsLastColumn("left");+ const isFirstRightPinnedColumn = isPinned === "right" && column.getIsFirstColumn("right");++ const isRtl = dir === "rtl";++ const leftPosition = isPinned === "left" ? `${column.getStart("left")}px` : undefined;+ const rightPosition = isPinned === "right" ? `${column.getAfter("right")}px` : undefined;++ return {+ // eslint-disable-next-line no-nested-ternary+ boxShadow: withBorder+ ? // eslint-disable-next-line no-nested-ternary+ isLastLeftPinnedColumn+ ? isRtl+ ? "4px 0 4px -4px var(--border) inset"+ : "-4px 0 4px -4px var(--border) inset"+ : // eslint-disable-next-line no-nested-ternary+ isFirstRightPinnedColumn+ ? isRtl+ ? "-4px 0 4px -4px var(--border) inset"+ : "4px 0 4px -4px var(--border) inset"+ : undefined+ : undefined,+ left: isRtl ? rightPosition : leftPosition,+ right: isRtl ? leftPosition : rightPosition,+ opacity: isPinned ? 0.97 : 1,+ position: isPinned ? "sticky" : "relative",+ background: isPinned ? "var(--container)" : "var(--container)",+ width: column.getSize(),+ zIndex: isPinned ? 1 : undefined+ };+}++export function getScrollDirection(+ direction: string+): "left" | "right" | "home" | "end" | undefined {+ if (+ direction === "left" ||+ direction === "right" ||+ direction === "home" ||+ direction === "end"+ ) {+ return direction as "left" | "right" | "home" | "end";+ }+ if (direction === "pageleft") return "left";+ if (direction === "pageright") return "right";+ return undefined;+}++export function scrollCellIntoView<TData>(params: {+ container: HTMLDivElement;+ targetCell: HTMLDivElement;+ tableRef: React.RefObject<Table<TData> | null>;+ viewportOffset: number;+ direction?: "left" | "right" | "home" | "end";+ isRtl: boolean;+}): void {+ const { container, targetCell, tableRef, direction, viewportOffset, isRtl } = params;++ const containerRect = container.getBoundingClientRect();+ const cellRect = targetCell.getBoundingClientRect();++ const hasNegativeScroll = container.scrollLeft < 0;+ const isActuallyRtl = isRtl || hasNegativeScroll;++ const currentTable = tableRef.current;+ const leftPinnedColumns = currentTable?.getLeftVisibleLeafColumns() ?? [];+ const rightPinnedColumns = currentTable?.getRightVisibleLeafColumns() ?? [];++ const leftPinnedWidth = leftPinnedColumns.reduce((sum, c) => sum + c.getSize(), 0);+ const rightPinnedWidth = rightPinnedColumns.reduce((sum, c) => sum + c.getSize(), 0);++ const viewportLeft = isActuallyRtl+ ? containerRect.left + rightPinnedWidth + viewportOffset+ : containerRect.left + leftPinnedWidth + viewportOffset;+ const viewportRight = isActuallyRtl+ ? containerRect.right - leftPinnedWidth - viewportOffset+ : containerRect.right - rightPinnedWidth - viewportOffset;++ const isFullyVisible = cellRect.left >= viewportLeft && cellRect.right <= viewportRight;++ if (isFullyVisible) return;++ const isClippedLeft = cellRect.left < viewportLeft;+ const isClippedRight = cellRect.right > viewportRight;++ let scrollDelta = 0;++ if (!direction) {+ if (isClippedRight) {+ scrollDelta = cellRect.right - viewportRight;+ } else if (isClippedLeft) {+ scrollDelta = -(viewportLeft - cellRect.left);+ }+ } else {+ const shouldScrollRight = isActuallyRtl+ ? direction === "right" || direction === "home"+ : direction === "right" || direction === "end";++ if (shouldScrollRight) {+ scrollDelta = cellRect.right - viewportRight;+ } else {+ scrollDelta = -(viewportLeft - cellRect.left);+ }+ }++ container.scrollLeft += scrollDelta;+}++export function getIsInPopover(element: unknown): boolean {+ return (+ element instanceof Element &&+ (element.closest("[data-grid-cell-editor]") || element.closest("[data-grid-popover]")) !== null+ );+}++export function getColumnVariant(variant?: CellOpts["variant"]): {+ icon: React.ComponentType<React.SVGProps<SVGSVGElement>>;+ label: string;+} | null {+ switch (variant) {+ case "short-text":+ return { label: "Short text", icon: BaselineIcon };+ case "long-text":+ return { label: "Long text", icon: TextInitialIcon };+ case "number":+ return { label: "Number", icon: HashIcon };+ case "url":+ return { label: "URL", icon: LinkIcon };+ case "checkbox":+ return { label: "Checkbox", icon: CheckSquareIcon };+ case "select":+ return { label: "Select", icon: ListIcon };+ case "multi-select":+ return { label: "Multi-select", icon: ListChecksIcon };+ case "date":+ return { label: "Date", icon: CalendarIcon };+ case "file":+ return { label: "File", icon: FileIcon };+ default:+ return null;+ }+}++export function getUrlHref(urlString: string): string {+ if (!urlString || urlString.trim() === "") return "";++ const trimmed = urlString.trim();++ // Reject dangerous protocols (extra safety, though our http:// prefix would neutralize them)+ if (/^(javascript|data|vbscript|file):/i.test(trimmed)) {+ return "";+ }++ if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {+ return trimmed;+ }++ return `http://${trimmed}`;+}++export function parseLocalDate(dateStr: unknown): Date | null {+ if (!dateStr) return null;+ if (dateStr instanceof Date) return dateStr;+ if (typeof dateStr !== "string") return null;+ const [year, month, day] = dateStr.split("-").map(Number);+ if (!year || !month || !day) return null;+ const date = new Date(year, month - 1, day);+ // Verify date wasn't auto-corrected (e.g. Feb 30 -> Mar 1)+ if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {+ return null;+ }+ return date;+}++export function formatDateToString(date: Date): string {+ const year = date.getFullYear();+ const month = String(date.getMonth() + 1).padStart(2, "0");+ const day = String(date.getDate()).padStart(2, "0");+ return `${year}-${month}-${day}`;+}++export function formatDateForDisplay(dateStr: unknown): string {+ if (!dateStr) return "";+ const date = parseLocalDate(dateStr);+ if (!date) return typeof dateStr === "string" ? dateStr : "";+ return date.toLocaleDateString();+}++export function formatFileSize(bytes: number): string {+ if (bytes <= 0 || !Number.isFinite(bytes)) return "0 B";+ const k = 1024;+ const sizes = ["B", "KB", "MB", "GB"];+ const i = Math.min(sizes.length - 1, Math.floor(Math.log(bytes) / Math.log(k)));+ return `${Number.parseFloat((bytes / k ** i).toFixed(1))} ${sizes[i]}`;+}++export function getFileIcon(type: string): React.ComponentType<React.SVGProps<SVGSVGElement>> {+ if (type.startsWith("image/")) return FileImage;+ if (type.startsWith("video/")) return FileVideo;+ if (type.startsWith("audio/")) return FileAudio;+ if (type.includes("pdf")) return FileText;+ if (type.includes("zip") || type.includes("rar")) return FileArchive;+ if (type.includes("word") || type.includes("document") || type.includes("doc")) return FileText;+ if (type.includes("sheet") || type.includes("excel") || type.includes("xls"))+ return FileSpreadsheet;+ if (type.includes("presentation") || type.includes("powerpoint") || type.includes("ppt"))+ return Presentation;+ return File;+}diff --git a/frontend/src/components/v3/generic/DataGrid/data-grid.tsx b/frontend/src/components/v3/generic/DataGrid/data-grid.tsxnew file mode 100644index 0000000000..8a64a65676--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/data-grid.tsx@@ -0,0 +1,265 @@+import * as React from "react";+import { Plus } from "lucide-react";++import { cn } from "@app/components/v3/utils";++import { useAsRef } from "./hooks/use-as-ref";+import { DataGridColumnHeader } from "./data-grid-column-header";+import { DataGridContextMenu } from "./data-grid-context-menu";+import { DataGridPasteDialog } from "./data-grid-paste-dialog";+import { DataGridRow } from "./data-grid-row";+import { DataGridSearch } from "./data-grid-search";+import type { Direction } from "./data-grid-types";+import {+ flexRender,+ getColumnBorderVisibility,+ getColumnPinningStyle,+ sanitizeCssId+} from "./data-grid-utils";+import type { useDataGrid } from "./use-data-grid";++const EMPTY_CELL_SELECTION_SET = new Set<string>();++interface DataGridProps<TData>+ extends Omit<ReturnType<typeof useDataGrid<TData>>, "dir">,+ Omit<React.ComponentProps<"div">, "contextMenu"> {+ dir?: Direction;+ height?: number;+ stretchColumns?: boolean;+}++export function DataGrid<TData>({+ dataGridRef,+ headerRef,+ rowMapRef,+ footerRef,+ dir = "ltr",+ table,+ tableMeta,+ virtualTotalSize,+ virtualItems,+ measureElement,+ columns,+ columnSizeVars,+ searchState,+ searchMatchesByRow,+ activeSearchMatch,+ cellSelectionMap,+ focusedCell,+ editingCell,+ rowHeight,+ contextMenu,+ pasteDialog,+ onRowAdd: onRowAddProp,+ height,+ stretchColumns = false,+ adjustLayout = false,+ className,+ ...props+}: DataGridProps<TData>) {+ const { rows } = table.getRowModel();+ const readOnly = tableMeta?.readOnly ?? false;+ const { columnVisibility } = table.getState();+ const { columnPinning } = table.getState();++ const onRowAddRef = useAsRef(onRowAddProp);++ const onRowAdd = React.useCallback(+ (event: React.MouseEvent<HTMLDivElement>) => {+ onRowAddRef.current?.(event);+ },+ [onRowAddRef]+ );++ const onDataGridContextMenu = React.useCallback((event: React.MouseEvent<HTMLDivElement>) => {+ event.preventDefault();+ }, []);++ const onFooterCellKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ if (!onRowAddRef.current) return;++ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ onRowAddRef.current();+ }+ },+ [onRowAddRef]+ );++ return (+ <div+ data-slot="grid-wrapper"+ dir={dir}+ {...props}+ className={cn("relative flex w-full flex-col", className)}+ >+ {searchState && <DataGridSearch {...searchState} />}+ <DataGridContextMenu tableMeta={tableMeta} columns={columns} contextMenu={contextMenu} />+ <DataGridPasteDialog tableMeta={tableMeta} pasteDialog={pasteDialog} />+ <div+ role="grid"+ aria-label="Data grid"+ aria-rowcount={rows.length + (onRowAddProp ? 1 : 0)}+ aria-colcount={columns.length}+ data-slot="grid"+ tabIndex={0}+ ref={dataGridRef}+ className="relative grid thin-scrollbar flex-1 grid-rows-[auto_1fr_auto] overflow-auto rounded-md border border-border bg-container select-none focus:outline-none"+ style={{+ ...columnSizeVars,+ ...(height ? { maxHeight: `${height}px` } : {})+ }}+ onContextMenu={onDataGridContextMenu}+ >+ <div+ role="rowgroup"+ data-slot="grid-header"+ ref={headerRef}+ className="sticky top-0 z-10 grid border-b border-border bg-container"+ >+ {table.getHeaderGroups().map((headerGroup, rowIndex) => (+ <div+ key={headerGroup.id}+ role="row"+ aria-rowindex={rowIndex + 1}+ data-slot="grid-header-row"+ tabIndex={-1}+ className="flex w-full"+ >+ {headerGroup.headers.map((header, colIndex) => {+ const { sorting } = table.getState();+ const currentSort = sorting.find((sort) => sort.id === header.column.id);+ const isSortable = header.column.getCanSort();++ const nextHeader = headerGroup.headers[colIndex + 1];+ const isLastColumn = colIndex === headerGroup.headers.length - 1;++ const { showEndBorder, showStartBorder } = getColumnBorderVisibility({+ column: header.column,+ nextColumn: nextHeader?.column,+ isLastColumn+ });++ return (+ <div+ key={header.id}+ role="columnheader"+ aria-colindex={colIndex + 1}+ aria-sort={+ // eslint-disable-next-line no-nested-ternary+ currentSort?.desc === false+ ? "ascending"+ : currentSort?.desc === true // eslint-disable-line no-nested-ternary+ ? "descending"+ : isSortable // eslint-disable-line no-nested-ternary+ ? "none"+ : undefined+ }+ data-slot="grid-header-cell"+ tabIndex={-1}+ className={cn("relative overflow-hidden", {+ grow: stretchColumns && header.column.id !== "select",+ "border-e": showEndBorder && header.column.id !== "select",+ "border-s": showStartBorder && header.column.id !== "select"+ })}+ style={{+ ...getColumnPinningStyle({ column: header.column, dir }),+ width: `calc(var(--header-${sanitizeCssId(header.id)}-size) * 1px)`+ }}+ >+ {/* eslint-disable-next-line no-nested-ternary */}+ {header.isPlaceholder ? null : typeof header.column.columnDef.header ===+ "function" ? (+ <div className="size-full px-3 py-1.5">+ {flexRender(header.column.columnDef.header, header.getContext())}+ </div>+ ) : (+ <DataGridColumnHeader header={header} table={table} />+ )}+ </div>+ );+ })}+ </div>+ ))}+ </div>+ <div+ role="rowgroup"+ data-slot="grid-body"+ className="relative grid"+ style={{+ height: `${virtualTotalSize}px`,+ contain: adjustLayout ? "layout paint" : "strict"+ }}+ >+ {virtualItems.map((virtualItem) => {+ const row = rows[virtualItem.index];+ if (!row) return null;++ const cellSelectionKeys =+ cellSelectionMap?.get(virtualItem.index) ?? EMPTY_CELL_SELECTION_SET;++ const searchMatchColumns = searchMatchesByRow?.get(virtualItem.index) ?? null;+ const isActiveSearchRow = activeSearchMatch?.rowIndex === virtualItem.index;++ return (+ <DataGridRow+ key={row.id}+ row={row}+ tableMeta={tableMeta}+ rowMapRef={rowMapRef}+ virtualItem={virtualItem}+ measureElement={measureElement}+ rowHeight={rowHeight}+ columnVisibility={columnVisibility}+ columnPinning={columnPinning}+ focusedCell={focusedCell}+ editingCell={editingCell}+ cellSelectionKeys={cellSelectionKeys}+ searchMatchColumns={searchMatchColumns}+ activeSearchMatch={isActiveSearchRow ? activeSearchMatch : null}+ dir={dir}+ adjustLayout={adjustLayout}+ stretchColumns={stretchColumns}+ readOnly={readOnly}+ />+ );+ })}+ </div>+ {!readOnly && onRowAdd && (+ <div+ role="rowgroup"+ data-slot="grid-footer"+ ref={footerRef}+ className="sticky bottom-0 z-10 grid border-t border-border bg-container"+ >+ <div+ role="row"+ aria-rowindex={rows.length + 2}+ data-slot="grid-add-row"+ tabIndex={-1}+ className="flex w-full"+ >+ <div+ role="gridcell"+ tabIndex={0}+ className="relative flex h-9 grow items-center bg-muted/30 transition-colors hover:bg-muted/50 focus:bg-muted/50 focus:outline-none"+ style={{+ width: table.getTotalSize(),+ minWidth: table.getTotalSize()+ }}+ onClick={onRowAdd}+ onKeyDown={onFooterCellKeyDown}+ >+ <div className="sticky start-0 flex items-center gap-2 px-3 text-muted">+ <Plus className="size-3.5" />+ <span className="text-sm">Add row</span>+ </div>+ </div>+ </div>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/frontend/src/components/v3/generic/DataGrid/hooks/use-as-ref.ts b/frontend/src/components/v3/generic/DataGrid/hooks/use-as-ref.tsnew file mode 100644index 0000000000..5f93347cd4--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/hooks/use-as-ref.ts@@ -0,0 +1,15 @@+import * as React from "react";++import { useIsomorphicLayoutEffect } from "./use-isomorphic-layout-effect";++function useAsRef<T>(props: T) {+ const ref = React.useRef<T>(props);++ useIsomorphicLayoutEffect(() => {+ ref.current = props;+ });++ return ref;+}++export { useAsRef };diff --git a/frontend/src/components/v3/generic/DataGrid/hooks/use-badge-overflow.ts b/frontend/src/components/v3/generic/DataGrid/hooks/use-badge-overflow.tsnew file mode 100644index 0000000000..6c2df5416f--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/hooks/use-badge-overflow.ts@@ -0,0 +1,178 @@+import * as React from "react";++const badgeWidthCache = new Map<string, number>();++const DEFAULT_CONTAINER_PADDING = 16; // px-2 = 8px * 2+const DEFAULT_BADGE_GAP = 4; // gap-1 = 4px+const DEFAULT_OVERFLOW_BADGE_WIDTH = 40; // Approximate width of "+N" badge++interface MeasureBadgeWidthProps {+ label: string;+ cacheKey: string;+ iconSize?: number;+ maxWidth?: number;+ className?: string;+}++function measureBadgeWidth({+ label,+ cacheKey,+ iconSize,+ maxWidth,+ className+}: MeasureBadgeWidthProps): number {+ const cached = badgeWidthCache.get(cacheKey);+ if (cached !== undefined) {+ return cached;+ }++ const measureEl = document.createElement("div");+ measureEl.className = `inline-flex items-center rounded-md border px-1.5 text-xs font-semibold h-5 gap-1 shrink-0 absolute invisible pointer-events-none ${+ className ?? ""+ }`;+ measureEl.style.whiteSpace = "nowrap";++ if (iconSize) {+ const icon = document.createElement("span");+ icon.className = "shrink-0";+ icon.style.width = `${iconSize}px`;+ icon.style.height = `${iconSize}px`;+ measureEl.appendChild(icon);+ }++ if (maxWidth) {+ const text = document.createElement("span");+ text.className = "truncate";+ text.style.maxWidth = `${maxWidth}px`;+ text.textContent = label;+ measureEl.appendChild(text);+ } else {+ measureEl.textContent = label;+ }++ document.body.appendChild(measureEl);+ const width = measureEl.offsetWidth;+ document.body.removeChild(measureEl);++ badgeWidthCache.set(cacheKey, width);+ return width;+}++interface UseBadgeOverflowProps<T> {+ items: T[];+ getLabel: (item: T) => string;+ containerRef: React.RefObject<HTMLElement | null>;+ lineCount: number;+ cacheKeyPrefix?: string;+ iconSize?: number;+ maxWidth?: number;+ className?: string;+ containerPadding?: number;+ badgeGap?: number;+ overflowBadgeWidth?: number;+}++interface UseBadgeOverflowReturn<T> {+ visibleItems: T[];+ hiddenCount: number;+ containerWidth: number;+}++export function useBadgeOverflow<T>({+ items,+ getLabel,+ containerRef,+ lineCount,+ cacheKeyPrefix = "",+ containerPadding = DEFAULT_CONTAINER_PADDING,+ badgeGap = DEFAULT_BADGE_GAP,+ overflowBadgeWidth = DEFAULT_OVERFLOW_BADGE_WIDTH,+ iconSize,+ maxWidth,+ className+}: UseBadgeOverflowProps<T>): UseBadgeOverflowReturn<T> {+ const [containerWidth, setContainerWidth] = React.useState(0);++ React.useEffect(() => {+ if (!containerRef.current) return undefined;++ function measureWidth() {+ if (containerRef.current) {+ const width = containerRef.current.clientWidth - containerPadding;+ setContainerWidth(width);+ }+ }++ measureWidth();++ const resizeObserver = new ResizeObserver(measureWidth);+ resizeObserver.observe(containerRef.current);++ return () => {+ resizeObserver.disconnect();+ };+ }, [containerRef, containerPadding]);++ const result = React.useMemo(() => {+ if (!containerWidth || items.length === 0) {+ return { visibleItems: items, hiddenCount: 0, containerWidth };+ }++ let currentLineWidth = 0;+ let currentLine = 1;+ const visible: T[] = [];++ // eslint-disable-next-line no-restricted-syntax+ for (const item of items) {+ const label = getLabel(item);+ const cacheKey = cacheKeyPrefix ? `${cacheKeyPrefix}:${label}` : label;+ const badgeWidth = measureBadgeWidth({+ label,+ cacheKey,+ iconSize,+ maxWidth,+ className+ });+ const widthWithGap = badgeWidth + badgeGap;++ if (currentLineWidth + widthWithGap <= containerWidth) {+ currentLineWidth += widthWithGap;+ visible.push(item);+ } else if (currentLine < lineCount) {+ // eslint-disable-next-line no-plusplus+ currentLine++;+ currentLineWidth = widthWithGap;+ visible.push(item);+ } else {+ if (currentLineWidth + overflowBadgeWidth > containerWidth && visible.length > 0) {+ visible.pop();+ }++ break;+ }+ }++ return {+ visibleItems: visible,+ hiddenCount: Math.max(0, items.length - visible.length),+ containerWidth+ };+ }, [+ items,+ getLabel,+ containerWidth,+ lineCount,+ cacheKeyPrefix,+ iconSize,+ maxWidth,+ className,+ badgeGap,+ overflowBadgeWidth+ ]);++ return result;+}++export function clearBadgeWidthCache(): void {+ badgeWidthCache.clear();+}diff --git a/frontend/src/components/v3/generic/DataGrid/hooks/use-callback-ref.ts b/frontend/src/components/v3/generic/DataGrid/hooks/use-callback-ref.tsnew file mode 100644index 0000000000..6124d75076--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/hooks/use-callback-ref.ts@@ -0,0 +1,22 @@+import * as React from "react";++/**+ * @see https://github.com/radix-ui/primitives/blob/main/packages/react/use-callback-ref/src/useCallbackRef.tsx+ */++/**+ * A custom hook that converts a callback to a ref to avoid triggering re-renders when passed as a+ * prop or avoid re-executing effects when passed as a dependency+ */+function useCallbackRef<T extends (...args: never[]) => unknown>(callback: T | undefined): T {+ const callbackRef = React.useRef(callback);++ React.useEffect(() => {+ callbackRef.current = callback;+ });++ // https://github.com/facebook/react/issues/19240+ return React.useMemo(() => ((...args) => callbackRef.current?.(...args)) as T, []);+}++export { useCallbackRef };diff --git a/frontend/src/components/v3/generic/DataGrid/hooks/use-debounced-callback.ts b/frontend/src/components/v3/generic/DataGrid/hooks/use-debounced-callback.tsnew file mode 100644index 0000000000..e2d350f10a--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/hooks/use-debounced-callback.ts@@ -0,0 +1,22 @@+import * as React from "react";++import { useCallbackRef } from "./use-callback-ref";++export function useDebouncedCallback<T extends (...args: never[]) => unknown>(+ callback: T,+ delay: number+) {+ const handleCallback = useCallbackRef(callback);+ const debounceTimerRef = React.useRef(0);+ React.useEffect(() => () => window.clearTimeout(debounceTimerRef.current), []);++ const setValue = React.useCallback(+ (...args: Parameters<T>) => {+ window.clearTimeout(debounceTimerRef.current);+ debounceTimerRef.current = window.setTimeout(() => handleCallback(...args), delay);+ },+ [handleCallback, delay]+ );++ return setValue;+}diff --git a/frontend/src/components/v3/generic/DataGrid/hooks/use-isomorphic-layout-effect.ts b/frontend/src/components/v3/generic/DataGrid/hooks/use-isomorphic-layout-effect.tsnew file mode 100644index 0000000000..b416bd4147--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/hooks/use-isomorphic-layout-effect.ts@@ -0,0 +1,6 @@+import * as React from "react";++const useIsomorphicLayoutEffect =+ typeof window !== "undefined" ? React.useLayoutEffect : React.useEffect;++export { useIsomorphicLayoutEffect };diff --git a/frontend/src/components/v3/generic/DataGrid/hooks/use-lazy-ref.ts b/frontend/src/components/v3/generic/DataGrid/hooks/use-lazy-ref.tsnew file mode 100644index 0000000000..d6262cec47--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/hooks/use-lazy-ref.ts@@ -0,0 +1,13 @@+import * as React from "react";++function useLazyRef<T>(fn: () => T) {+ const ref = React.useRef<T | null>(null);++ if (ref.current === null) {+ ref.current = fn();+ }++ return ref as React.RefObject<T>;+}++export { useLazyRef };diff --git a/frontend/src/components/v3/generic/DataGrid/index.ts b/frontend/src/components/v3/generic/DataGrid/index.tsnew file mode 100644index 0000000000..a44d53d730--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/index.ts@@ -0,0 +1,3 @@+export { DataGrid } from "./data-grid";+export type { CellOpts, CellUpdate, ContextMenuState } from "./data-grid-types";+export { useDataGrid } from "./use-data-grid";diff --git a/frontend/src/components/v3/generic/DataGrid/ui/kbd.tsx b/frontend/src/components/v3/generic/DataGrid/ui/kbd.tsxnew file mode 100644index 0000000000..5edfa14214--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/ui/kbd.tsx@@ -0,0 +1,20 @@+// Minimal Kbd component for Dice UI DataGrid keyboard shortcuts dialog+import * as React from "react";++import { cn } from "@app/components/v3/utils";++export function Kbd({ className, ...props }: React.HTMLAttributes<HTMLElement>) {+ return (+ <kbd+ className={cn(+ "pointer-events-none inline-flex h-5 items-center gap-1 rounded border border-border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted select-none",+ className+ )}+ {...props}+ />+ );+}++export function KbdGroup({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {+ return <div className={cn("flex items-center gap-0.5", className)} {...props} />;+}diff --git a/frontend/src/components/v3/generic/DataGrid/use-data-grid.ts b/frontend/src/components/v3/generic/DataGrid/use-data-grid.tsnew file mode 100644index 0000000000..7a71d1c47f--- /dev/null+++ b/frontend/src/components/v3/generic/DataGrid/use-data-grid.ts@@ -0,0 +1,3103 @@+/* eslint-disable */+// @ts-nocheck -- vendored Dice UI component, API compatibility fixes pending+import * as React from "react";+import { useDirection } from "@radix-ui/react-direction";+import {+ type ColumnDef,+ type ColumnFiltersState,+ getCoreRowModel,+ getFilteredRowModel,+ getSortedRowModel,+ type Row,+ type RowSelectionState,+ type SortingState,+ type TableMeta,+ type TableOptions,+ type TableState,+ type Updater,+ useReactTable+} from "@tanstack/react-table";+import { useVirtualizer, type Virtualizer } from "@tanstack/react-virtual";+import { toast } from "sonner";++import { useAsRef } from "./hooks/use-as-ref";+import { useIsomorphicLayoutEffect } from "./hooks/use-isomorphic-layout-effect";+import { useLazyRef } from "./hooks/use-lazy-ref";+import type {+ CellPosition,+ CellUpdate,+ ContextMenuState,+ Direction,+ FileCellData,+ NavigationDirection,+ PasteDialogState,+ RowHeightValue,+ SearchState,+ SelectionState+} from "./data-grid-types";+import {+ getCellKey,+ getIsFileCellData,+ getIsInPopover,+ getRowHeightValue,+ getScrollDirection,+ matchSelectOption,+ parseCellKey,+ sanitizeCssId,+ scrollCellIntoView+} from "./data-grid-utils";++const DEFAULT_ROW_HEIGHT = "short";+const OVERSCAN = 6;+const VIEWPORT_OFFSET = 1;+const HORIZONTAL_PAGE_SIZE = 5;+const SCROLL_SYNC_RETRY_COUNT = 16;+const MIN_COLUMN_SIZE = 60;+const MAX_COLUMN_SIZE = 800;+const SEARCH_SHORTCUT_KEY = "f";+const NON_NAVIGABLE_COLUMN_IDS = ["select", "actions"];++const DOMAIN_REGEX = /^[\w.-]+\.[a-z]{2,}(\/\S*)?$/i;+const ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}.*)?$/;+const TRUTHY_BOOLEANS = new Set(["true", "1", "yes", "checked"]);+const VALID_BOOLEANS = new Set(["true", "false", "1", "0", "yes", "no", "checked", "unchecked"]);++interface DataGridState {+ sorting: SortingState;+ columnFilters: ColumnFiltersState;+ rowHeight: RowHeightValue;+ rowSelection: RowSelectionState;+ selectionState: SelectionState;+ focusedCell: CellPosition | null;+ editingCell: CellPosition | null;+ cutCells: Set<string>;+ contextMenu: ContextMenuState;+ searchQuery: string;+ searchMatches: CellPosition[];+ matchIndex: number;+ searchOpen: boolean;+ lastClickedRowIndex: number | null;+ pasteDialog: PasteDialogState;+}++interface DataGridStore {+ subscribe: (callback: () => void) => () => void;+ getState: () => DataGridState;+ setState: <K extends keyof DataGridState>(key: K, value: DataGridState[K]) => void;+ notify: () => void;+ batch: (fn: () => void) => void;+}++function useStore<T>(store: DataGridStore, selector: (state: DataGridState) => T): T {+ const getSnapshot = React.useCallback(() => selector(store.getState()), [store, selector]);++ return React.useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);+}++interface UseDataGridProps<TData>+ extends Omit<TableOptions<TData>, "pageCount" | "getCoreRowModel"> {+ onDataChange?: (data: TData[]) => void;+ onRowAdd?: (+ event?: React.MouseEvent<HTMLDivElement>+ ) => Partial<CellPosition> | Promise<Partial<CellPosition> | null> | null;+ onRowsAdd?: (count: number) => void | Promise<void>;+ onRowsDelete?: (rows: TData[], rowIndices: number[]) => void | Promise<void>;+ onPaste?: (updates: Array<CellUpdate>) => void | Promise<void>;+ onFilesUpload?: (params: {+ files: File[];+ rowIndex: number;+ columnId: string;+ }) => Promise<FileCellData[]>;+ onFilesDelete?: (params: {+ fileIds: string[];+ rowIndex: number;+ columnId: string;+ }) => void | Promise<void>;+ rowHeight?: RowHeightValue;+ onRowHeightChange?: (rowHeight: RowHeightValue) => void;+ overscan?: number;+ dir?: Direction;+ autoFocus?: boolean | Partial<CellPosition>;+ enableSingleCellSelection?: boolean;+ enableColumnSelection?: boolean;+ enableSearch?: boolean;+ enablePaste?: boolean;+ readOnly?: boolean;+ onRowSelectionChange?: (rowSelection: RowSelectionState) => void;+}++function useDataGrid<TData>({+ data,+ columns,+ rowHeight: rowHeightProp = DEFAULT_ROW_HEIGHT,+ overscan = OVERSCAN,+ dir: dirProp,+ initialState,+ ...props+}: UseDataGridProps<TData>) {+ const dir = useDirection(dirProp);+ const dataGridRef = React.useRef<HTMLDivElement>(null);+ const tableRef = React.useRef<ReturnType<typeof useReactTable<TData>>>(null);+ const rowVirtualizerRef = React.useRef<Virtualizer<HTMLDivElement, Element>>(null);+ const headerRef = React.useRef<HTMLDivElement>(null);+ const rowMapRef = React.useRef<Map<number, HTMLDivElement>>(new Map());+ const cellMapRef = React.useRef<Map<string, HTMLDivElement>>(new Map());+ const footerRef = React.useRef<HTMLDivElement>(null);+ const focusGuardRef = React.useRef(false);++ const propsRef = useAsRef({+ ...props,+ data,+ columns,+ initialState+ });++ const listenersRef = useLazyRef(() => new Set<() => void>());++ const stateRef = useLazyRef<DataGridState>(() => {+ return {+ sorting: initialState?.sorting ?? [],+ columnFilters: initialState?.columnFilters ?? [],+ rowHeight: rowHeightProp,+ rowSelection: initialState?.rowSelection ?? {},+ selectionState: {+ selectedCells: new Set(),+ selectionRange: null,+ isSelecting: false+ },+ focusedCell: null,+ editingCell: null,+ cutCells: new Set(),+ contextMenu: {+ open: false,+ x: 0,+ y: 0+ },+ searchQuery: "",+ searchMatches: [],+ matchIndex: -1,+ searchOpen: false,+ lastClickedRowIndex: null,+ pasteDialog: {+ open: false,+ rowsNeeded: 0,+ clipboardText: ""+ }+ };+ });++ const store = React.useMemo<DataGridStore>(() => {+ let isBatching = false;+ let pendingNotification = false;++ return {+ subscribe: (callback) => {+ listenersRef.current.add(callback);+ return () => listenersRef.current.delete(callback);+ },+ getState: () => stateRef.current,+ setState: (key, value) => {+ if (Object.is(stateRef.current[key], value)) return;+ stateRef.current[key] = value;++ if (isBatching) {+ pendingNotification = true;+ } else if (!pendingNotification) {+ pendingNotification = true;+ queueMicrotask(() => {+ pendingNotification = false;+ store.notify();+ });+ }+ },+ notify: () => {+ for (const listener of listenersRef.current) {+ listener();+ }+ },+ batch: (fn) => {+ if (isBatching) {+ fn();+ return;+ }++ isBatching = true;+ const wasPending = pendingNotification;+ pendingNotification = false;++ try {+ fn();+ } finally {+ isBatching = false;+ if (pendingNotification || wasPending) {+ pendingNotification = false;+ store.notify();+ }+ }+ }+ };+ }, [listenersRef, stateRef]);++ const focusedCell = useStore(store, (state) => state.focusedCell);+ const editingCell = useStore(store, (state) => state.editingCell);+ const selectionState = useStore(store, (state) => state.selectionState);+ const searchQuery = useStore(store, (state) => state.searchQuery);+ const searchMatches = useStore(store, (state) => state.searchMatches);+ const matchIndex = useStore(store, (state) => state.matchIndex);+ const searchOpen = useStore(store, (state) => state.searchOpen);+ const sorting = useStore(store, (state) => state.sorting);+ const columnFilters = useStore(store, (state) => state.columnFilters);+ const rowSelection = useStore(store, (state) => state.rowSelection);+ const rowHeight = useStore(store, (state) => state.rowHeight);+ const contextMenu = useStore(store, (state) => state.contextMenu);+ const pasteDialog = useStore(store, (state) => state.pasteDialog);++ const rowHeightValue = getRowHeightValue(rowHeight);++ const prevCellSelectionMapRef = useLazyRef(() => new Map<number, Set<string>>());++ // Memoize per-row selection sets to prevent unnecessary row re-renders+ // Each row gets a stable Set reference that only changes when its cells' selection changes+ const cellSelectionMap = React.useMemo(() => {+ const { selectedCells } = selectionState;++ if (selectedCells.size === 0) {+ prevCellSelectionMapRef.current.clear();+ return null;+ }++ const newRowCells = new Map<number, Set<string>>();+ for (const cellKey of selectedCells) {+ const { rowIndex } = parseCellKey(cellKey);+ let rowSet = newRowCells.get(rowIndex);+ if (!rowSet) {+ rowSet = new Set<string>();+ newRowCells.set(rowIndex, rowSet);+ }+ rowSet.add(cellKey);+ }++ const stableMap = new Map<number, Set<string>>();+ for (const [rowIndex, newSet] of newRowCells) {+ const prevSet = prevCellSelectionMapRef.current.get(rowIndex);+ if (prevSet && prevSet.size === newSet.size && [...newSet].every((key) => prevSet.has(key))) {+ stableMap.set(rowIndex, prevSet);+ } else {+ stableMap.set(rowIndex, newSet);+ }+ }++ prevCellSelectionMapRef.current = stableMap;+ return stableMap;+ }, [selectionState.selectedCells, prevCellSelectionMapRef]);++ const visualRowIndexCacheRef = React.useRef<{+ rows: Row<TData>[] | null;+ map: Map<string, number>;+ } | null>(null);++ // Pre-compute visual row index map for O(1) lookups (used by select column)+ // Cache is invalidated when row model identity changes (sorting/filtering)+ const getVisualRowIndex = React.useCallback((rowId: string): number | undefined => {+ const rows = tableRef.current?.getRowModel().rows;+ if (!rows) return undefined;++ if (visualRowIndexCacheRef.current?.rows !== rows) {+ const map = new Map<string, number>();+ for (const [i, row] of rows.entries()) {+ map.set(row.id, i + 1);+ }+ visualRowIndexCacheRef.current = { rows, map };+ }++ return visualRowIndexCacheRef.current.map.get(rowId);+ }, []);++ const columnIds = React.useMemo(() => {+ return columns+ .map((c) => {+ if (c.id) return c.id;+ if ("accessorKey" in c) return c.accessorKey as string;+ return undefined;+ })+ .filter((id): id is string => Boolean(id));+ }, [columns]);++ const navigableColumnIds = React.useMemo(() => {+ return columnIds.filter((c) => !NON_NAVIGABLE_COLUMN_IDS.includes(c));+ }, [columnIds]);++ const onDataUpdate = React.useCallback(+ (updates: CellUpdate | Array<CellUpdate>) => {+ if (propsRef.current.readOnly) return;++ const updateArray = Array.isArray(updates) ? updates : [updates];++ if (updateArray.length === 0) return;++ const currentTable = tableRef.current;+ const currentData = propsRef.current.data;+ const rows = currentTable?.getRowModel().rows;++ const rowUpdatesMap = new Map<number, Array<Omit<CellUpdate, "rowIndex">>>();++ for (const update of updateArray) {+ if (!rows || !currentTable) {+ const existingUpdates = rowUpdatesMap.get(update.rowIndex) ?? [];+ existingUpdates.push({+ columnId: update.columnId,+ value: update.value+ });+ rowUpdatesMap.set(update.rowIndex, existingUpdates);+ } else {+ const row = rows[update.rowIndex];+ if (!row) continue;++ const originalData = row.original;+ const originalRowIndex = currentData.indexOf(originalData);++ const targetIndex = originalRowIndex !== -1 ? originalRowIndex : update.rowIndex;++ const existingUpdates = rowUpdatesMap.get(targetIndex) ?? [];+ existingUpdates.push({+ columnId: update.columnId,+ value: update.value+ });+ rowUpdatesMap.set(targetIndex, existingUpdates);+ }+ }++ const tableRowCount = rows?.length ?? currentData.length;+ const newData: TData[] = new Array(tableRowCount);++ for (let i = 0; i < tableRowCount; i++) {+ const updates = rowUpdatesMap.get(i);+ const existingRow = currentData[i];+ const tableRow = rows?.[i];++ if (updates) {+ const baseRow = existingRow ?? tableRow?.original ?? ({} as TData);+ const updatedRow = { ...baseRow } as Record<string, unknown>;+ for (const { columnId, value } of updates) {+ updatedRow[columnId] = value;+ }+ newData[i] = updatedRow as TData;+ } else {+ newData[i] = existingRow ?? tableRow?.original ?? ({} as TData);+ }+ }++ propsRef.current.onDataChange?.(newData);+ },+ [propsRef]+ );++ const getIsCellSelected = React.useCallback(+ (rowIndex: number, columnId: string) => {+ const currentSelectionState = store.getState().selectionState;+ return currentSelectionState.selectedCells.has(getCellKey(rowIndex, columnId));+ },+ [store]+ );++ const onSelectionClear = React.useCallback(() => {+ store.batch(() => {+ store.setState("selectionState", {+ selectedCells: new Set(),+ selectionRange: null,+ isSelecting: false+ });+ store.setState("rowSelection", {});+ });+ propsRef.current.onRowSelectionChange?.({});+ }, [store, propsRef]);++ const selectAll = React.useCallback(() => {+ const allCells = new Set<string>();+ const currentTable = tableRef.current;+ const rows = currentTable?.getRowModel().rows ?? [];+ const rowCount = rows.length ?? propsRef.current.data.length;++ for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {+ for (const columnId of columnIds) {+ allCells.add(getCellKey(rowIndex, columnId));+ }+ }++ const firstColumnId = columnIds[0];+ const lastColumnId = columnIds[columnIds.length - 1];++ store.setState("selectionState", {+ selectedCells: allCells,+ selectionRange:+ columnIds.length > 0 && rowCount > 0 && firstColumnId && lastColumnId+ ? {+ start: { rowIndex: 0, columnId: firstColumnId },+ end: { rowIndex: rowCount - 1, columnId: lastColumnId }+ }+ : null,+ isSelecting: false+ });+ }, [columnIds, propsRef, store]);++ const selectColumn = React.useCallback(+ (columnId: string) => {+ const currentTable = tableRef.current;+ const rows = currentTable?.getRowModel().rows ?? [];+ const rowCount = rows.length ?? propsRef.current.data.length;++ if (rowCount === 0) return;++ const selectedCells = new Set<string>();++ for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {+ selectedCells.add(getCellKey(rowIndex, columnId));+ }++ store.setState("selectionState", {+ selectedCells,+ selectionRange: {+ start: { rowIndex: 0, columnId },+ end: { rowIndex: rowCount - 1, columnId }+ },+ isSelecting: false+ });+ },+ [propsRef, store]+ );++ const selectRange = React.useCallback(+ (start: CellPosition, end: CellPosition, isSelecting = false) => {+ const startColIndex = columnIds.indexOf(start.columnId);+ const endColIndex = columnIds.indexOf(end.columnId);++ const minRow = Math.min(start.rowIndex, end.rowIndex);+ const maxRow = Math.max(start.rowIndex, end.rowIndex);+ const minCol = Math.min(startColIndex, endColIndex);+ const maxCol = Math.max(startColIndex, endColIndex);++ const selectedCells = new Set<string>();++ for (let rowIndex = minRow; rowIndex <= maxRow; rowIndex++) {+ for (let colIndex = minCol; colIndex <= maxCol; colIndex++) {+ const columnId = columnIds[colIndex];+ if (columnId) {+ selectedCells.add(getCellKey(rowIndex, columnId));+ }+ }+ }++ store.setState("selectionState", {+ selectedCells,+ selectionRange: { start, end },+ isSelecting+ });+ },+ [columnIds, store]+ );++ const onCellsCopy = React.useCallback(async () => {+ const currentState = store.getState();++ let selectedCellsArray: string[];+ if (!currentState.selectionState.selectedCells.size) {+ if (!currentState.focusedCell) return;+ const focusedCellKey = getCellKey(+ currentState.focusedCell.rowIndex,+ currentState.focusedCell.columnId+ );+ selectedCellsArray = [focusedCellKey];+ } else {+ selectedCellsArray = Array.from(currentState.selectionState.selectedCells);+ }++ const currentTable = tableRef.current;+ const rows = currentTable?.getRowModel().rows;+ if (!rows) return;++ const selectedColumnIds: string[] = [];++ for (const cellKey of selectedCellsArray) {+ const { columnId } = parseCellKey(cellKey);+ if (columnId && !selectedColumnIds.includes(columnId)) {+ selectedColumnIds.push(columnId);+ }+ }++ const cellData = new Map<string, string>();+ for (const cellKey of selectedCellsArray) {+ const { rowIndex, columnId } = parseCellKey(cellKey);+ const row = rows[rowIndex];+ if (row) {+ const cell = row.getVisibleCells().find((c) => c.column.id === columnId);+ if (cell) {+ const value = cell.getValue();+ const cellVariant = cell.column.columnDef?.meta?.cell?.variant;++ let serializedValue = "";+ if (cellVariant === "file" || cellVariant === "multi-select") {+ serializedValue = value ? JSON.stringify(value) : "";+ } else if (value instanceof Date) {+ serializedValue = value.toISOString();+ } else {+ serializedValue = String(value ?? "");+ }++ cellData.set(cellKey, serializedValue);+ }+ }+ }++ const rowIndices = new Set<number>();+ const colIndices = new Set<number>();++ for (const cellKey of selectedCellsArray) {+ const { rowIndex, columnId } = parseCellKey(cellKey);+ rowIndices.add(rowIndex);+ const colIndex = selectedColumnIds.indexOf(columnId);+ if (colIndex >= 0) {+ colIndices.add(colIndex);+ }+ }++ const sortedRowIndices = Array.from(rowIndices).sort((a, b) => a - b);+ const sortedColIndices = Array.from(colIndices).sort((a, b) => a - b);+ const sortedColumnIds = sortedColIndices.map((i) => selectedColumnIds[i]);++ const tsvData = sortedRowIndices+ .map((rowIndex) =>+ sortedColumnIds+ .map((columnId) => {+ const cellKey = `${rowIndex}:${columnId}`;+ return cellData.get(cellKey) ?? "";+ })+ .join("\t")+ )+ .join("\n");++ try {+ await navigator.clipboard.writeText(tsvData);++ const currentState = store.getState();+ if (currentState.cutCells.size > 0) {+ store.setState("cutCells", new Set());+ }++ toast.success(+ `${selectedCellsArray.length} cell${selectedCellsArray.length !== 1 ? "s" : ""} copied`+ );+ } catch (error) {+ toast.error(error instanceof Error ? error.message : "Failed to copy to clipboard");+ }+ }, [store]);++ const onCellsCut = React.useCallback(async () => {+ if (propsRef.current.readOnly) return;++ const currentState = store.getState();++ let selectedCellsArray: string[];+ if (!currentState.selectionState.selectedCells.size) {+ if (!currentState.focusedCell) return;+ const focusedCellKey = getCellKey(+ currentState.focusedCell.rowIndex,+ currentState.focusedCell.columnId+ );+ selectedCellsArray = [focusedCellKey];+ } else {+ selectedCellsArray = Array.from(currentState.selectionState.selectedCells);+ }++ const currentTable = tableRef.current;+ const rows = currentTable?.getRowModel().rows;+ if (!rows) return;++ const selectedColumnIds: string[] = [];++ for (const cellKey of selectedCellsArray) {+ const { columnId } = parseCellKey(cellKey);+ if (columnId && !selectedColumnIds.includes(columnId)) {+ selectedColumnIds.push(columnId);+ }+ }++ const cellData = new Map<string, string>();+ for (const cellKey of selectedCellsArray) {+ const { rowIndex, columnId } = parseCellKey(cellKey);+ const row = rows[rowIndex];+ if (row) {+ const cell = row.getVisibleCells().find((c) => c.column.id === columnId);+ if (cell) {+ const value = cell.getValue();+ const cellVariant = cell.column.columnDef?.meta?.cell?.variant;++ let serializedValue = "";+ if (cellVariant === "file" || cellVariant === "multi-select") {+ serializedValue = value ? JSON.stringify(value) : "";+ } else if (value instanceof Date) {+ serializedValue = value.toISOString();+ } else {+ serializedValue = String(value ?? "");+ }++ cellData.set(cellKey, serializedValue);+ }+ }+ }++ const rowIndices = new Set<number>();+ const colIndices = new Set<number>();++ for (const cellKey of selectedCellsArray) {+ const { rowIndex, columnId } = parseCellKey(cellKey);+ rowIndices.add(rowIndex);+ const colIndex = selectedColumnIds.indexOf(columnId);+ if (colIndex >= 0) {+ colIndices.add(colIndex);+ }+ }++ const sortedRowIndices = Array.from(rowIndices).sort((a, b) => a - b);+ const sortedColIndices = Array.from(colIndices).sort((a, b) => a - b);+ const sortedColumnIds = sortedColIndices.map((i) => selectedColumnIds[i]);++ const tsvData = sortedRowIndices+ .map((rowIndex) =>+ sortedColumnIds+ .map((columnId) => {+ const cellKey = `${rowIndex}:${columnId}`;+ return cellData.get(cellKey) ?? "";+ })+ .join("\t")+ )+ .join("\n");++ try {+ await navigator.clipboard.writeText(tsvData);++ store.setState("cutCells", new Set(selectedCellsArray));++ toast.success(+ `${selectedCellsArray.length} cell${selectedCellsArray.length !== 1 ? "s" : ""} cut`+ );+ } catch (error) {+ toast.error(error instanceof Error ? error.message : "Failed to cut to clipboard");+ }+ }, [store, propsRef]);++ const restoreFocus = React.useCallback((element: HTMLDivElement | null) => {+ if (element && document.activeElement !== element) {+ requestAnimationFrame(() => {+ element.focus();+ });+ }+ }, []);++ const onCellsPaste = React.useCallback(+ async (expandRows = false) => {+ if (propsRef.current.readOnly) return;++ const currentState = store.getState();+ if (!currentState.focusedCell) return;++ const currentTable = tableRef.current;+ const rows = currentTable?.getRowModel().rows;+ if (!rows) return;++ try {+ let { clipboardText } = currentState.pasteDialog;++ if (!clipboardText) {+ clipboardText = await navigator.clipboard.readText();+ if (!clipboardText) return;+ }++ const pastedRows = clipboardText.split("\n").filter((row) => row.length > 0);+ const pastedData = pastedRows.map((row) => row.split("\t"));++ const startRowIndex = currentState.focusedCell.rowIndex;+ const startColIndex = navigableColumnIds.indexOf(currentState.focusedCell.columnId);++ if (startColIndex === -1) return;++ const rowCount = rows.length ?? propsRef.current.data.length;+ const rowsNeeded = startRowIndex + pastedData.length - rowCount;++ if (+ rowsNeeded > 0 &&+ !expandRows &&+ propsRef.current.onRowAdd &&+ !currentState.pasteDialog.clipboardText+ ) {+ store.setState("pasteDialog", {+ open: true,+ rowsNeeded,+ clipboardText+ });+ return;+ }++ if (expandRows && rowsNeeded > 0) {+ const expectedRowCount = rowCount + rowsNeeded;++ if (propsRef.current.onRowsAdd) {+ await propsRef.current.onRowsAdd(rowsNeeded);+ } else if (propsRef.current.onRowAdd) {+ for (let i = 0; i < rowsNeeded; i++) {+ await propsRef.current.onRowAdd();+ }+ }++ let attempts = 0;+ const maxAttempts = 50;+ let currentTableRowCount = tableRef.current?.getRowModel().rows.length ?? 0;++ while (currentTableRowCount < expectedRowCount && attempts < maxAttempts) {+ await new Promise((resolve) => setTimeout(resolve, 100));+ currentTableRowCount = tableRef.current?.getRowModel().rows.length ?? 0;+ attempts++;+ }+ }++ const updates: Array<CellUpdate> = [];+ const tableColumns = currentTable?.getAllColumns() ?? [];+ let cellsUpdated = 0;+ let endRowIndex = startRowIndex;+ let endColIndex = startColIndex;++ const updatedTable = tableRef.current;+ const updatedRows = updatedTable?.getRowModel().rows;+ const currentRowCount = updatedRows?.length ?? 0;++ let cellsSkipped = 0;++ const columnMap = new Map(tableColumns.map((c) => [c.id, c]));++ for (let pasteRowIdx = 0; pasteRowIdx < pastedData.length; pasteRowIdx++) {+ const pasteRow = pastedData[pasteRowIdx];+ if (!pasteRow) continue;++ const targetRowIndex = startRowIndex + pasteRowIdx;+ if (targetRowIndex >= currentRowCount) break;++ for (let pasteColIdx = 0; pasteColIdx < pasteRow.length; pasteColIdx++) {+ const targetColIndex = startColIndex + pasteColIdx;+ if (targetColIndex >= navigableColumnIds.length) break;++ const targetColumnId = navigableColumnIds[targetColIndex];+ if (!targetColumnId) continue;++ const pastedValue = pasteRow[pasteColIdx] ?? "";+ const column = columnMap.get(targetColumnId);+ const cellOpts = column?.columnDef?.meta?.cell;+ const cellVariant = cellOpts?.variant;++ let processedValue: unknown = pastedValue;+ let shouldSkip = false;++ switch (cellVariant) {+ case "number": {+ if (!pastedValue) {+ processedValue = null;+ } else {+ const num = Number.parseFloat(pastedValue);+ if (Number.isNaN(num)) shouldSkip = true;+ else processedValue = num;+ }+ break;+ }++ case "checkbox": {+ if (!pastedValue) {+ processedValue = false;+ } else {+ const lower = pastedValue.toLowerCase();+ if (VALID_BOOLEANS.has(lower)) {+ processedValue = TRUTHY_BOOLEANS.has(lower);+ } else {+ shouldSkip = true;+ }+ }+ break;+ }++ case "date": {+ if (!pastedValue) {+ processedValue = null;+ } else {+ const date = new Date(pastedValue);+ if (Number.isNaN(date.getTime())) shouldSkip = true;+ else processedValue = date;+ }+ break;+ }++ case "select": {+ const options = cellOpts?.options ?? [];+ if (!pastedValue) {+ processedValue = "";+ } else {+ const matched = matchSelectOption(pastedValue, options);+ if (matched) processedValue = matched;+ else shouldSkip = true;+ }+ break;+ }++ case "multi-select": {+ const options = cellOpts?.options ?? [];+ let values: string[] = [];+ try {+ const parsed = JSON.parse(pastedValue);+ if (Array.isArray(parsed)) {+ values = parsed.filter((v): v is string => typeof v === "string");+ }+ } catch {+ values = pastedValue ? pastedValue.split(",").map((v) => v.trim()) : [];+ }++ const validated = values+ .map((v) => matchSelectOption(v, options))+ .filter(Boolean) as string[];++ if (values.length > 0 && validated.length === 0) {+ shouldSkip = true;+ } else {+ processedValue = validated;+ }+ break;+ }++ case "file": {+ if (!pastedValue) {+ processedValue = [];+ } else {+ try {+ const parsed = JSON.parse(pastedValue);+ if (!Array.isArray(parsed)) {+ shouldSkip = true;+ } else {+ const validFiles = parsed.filter(getIsFileCellData);+ if (parsed.length > 0 && validFiles.length === 0) {+ shouldSkip = true;+ } else {+ processedValue = validFiles;+ }+ }+ } catch {+ shouldSkip = true;+ }+ }+ break;+ }++ case "url": {+ if (!pastedValue) {+ processedValue = "";+ } else {+ const firstChar = pastedValue[0];+ if (firstChar === "[" || firstChar === "{") {+ shouldSkip = true;+ } else {+ try {+ new URL(pastedValue);+ processedValue = pastedValue;+ } catch {+ if (DOMAIN_REGEX.test(pastedValue)) {+ processedValue = pastedValue;+ } else {+ shouldSkip = true;+ }+ }+ }+ }+ break;+ }++ default: {+ if (!pastedValue) {+ processedValue = "";+ break;+ }++ if (ISO_DATE_REGEX.test(pastedValue)) {+ const date = new Date(pastedValue);+ if (!Number.isNaN(date.getTime())) {+ processedValue = date.toLocaleDateString();+ break;+ }+ }++ const firstChar = pastedValue[0];+ if (+ firstChar === "[" ||+ firstChar === "{" ||+ firstChar === "t" ||+ firstChar === "f"+ ) {+ try {+ const parsed = JSON.parse(pastedValue);++ if (Array.isArray(parsed)) {+ if (parsed.length > 0 && parsed.every(getIsFileCellData)) {+ processedValue = parsed.map((f) => f.name).join(", ");+ } else if (parsed.every((v) => typeof v === "string")) {+ processedValue = (parsed as string[]).join(", ");+ }+ } else if (typeof parsed === "boolean") {+ processedValue = parsed ? "Checked" : "Unchecked";+ }+ } catch {+ const lower = pastedValue.toLowerCase();+ if (lower === "true" || lower === "false") {+ processedValue = lower === "true" ? "Checked" : "Unchecked";+ }+ }+ }+ }+ }++ if (shouldSkip) {+ cellsSkipped++;+ endRowIndex = Math.max(endRowIndex, targetRowIndex);+ endColIndex = Math.max(endColIndex, targetColIndex);+ continue;+ }++ updates.push({+ rowIndex: targetRowIndex,+ columnId: targetColumnId,+ value: processedValue+ });+ cellsUpdated++;++ endRowIndex = Math.max(endRowIndex, targetRowIndex);+ endColIndex = Math.max(endColIndex, targetColIndex);+ }+ }++ if (updates.length > 0) {+ if (propsRef.current.onPaste) {+ await propsRef.current.onPaste(updates);+ }++ const allUpdates = [...updates];++ if (currentState.cutCells.size > 0) {+ for (const cellKey of currentState.cutCells) {+ const { rowIndex, columnId } = parseCellKey(cellKey);++ const column = tableColumns.find((c) => c.id === columnId);+ const cellVariant = column?.columnDef?.meta?.cell?.variant;++ let emptyValue: unknown = "";+ if (cellVariant === "multi-select" || cellVariant === "file") {+ emptyValue = [];+ } else if (cellVariant === "number" || cellVariant === "date") {+ emptyValue = null;+ } else if (cellVariant === "checkbox") {+ emptyValue = false;+ }++ allUpdates.push({ rowIndex, columnId, value: emptyValue });+ }++ store.setState("cutCells", new Set());+ }++ onDataUpdate(allUpdates);++ if (cellsSkipped > 0) {+ toast.success(+ `${cellsUpdated} cell${cellsUpdated !== 1 ? "s" : ""} pasted, ${cellsSkipped} skipped`+ );+ } else {+ toast.success(`${cellsUpdated} cell${cellsUpdated !== 1 ? "s" : ""} pasted`);+ }++ const endColumnId = navigableColumnIds[endColIndex];+ if (endColumnId) {+ selectRange(+ {+ rowIndex: startRowIndex,+ columnId: currentState.focusedCell.columnId+ },+ { rowIndex: endRowIndex, columnId: endColumnId }+ );+ }++ restoreFocus(dataGridRef.current);+ } else if (cellsSkipped > 0) {+ toast.error(+ `${cellsSkipped} cell${cellsSkipped !== 1 ? "s" : ""} skipped pasting for invalid data`+ );+ }++ if (currentState.pasteDialog.open) {+ store.setState("pasteDialog", {+ open: false,+ rowsNeeded: 0,+ clipboardText: ""+ });+ }+ } catch (error) {+ toast.error(error instanceof Error ? error.message : "Failed to paste. Please try again.");+ }+ },+ [store, navigableColumnIds, propsRef, onDataUpdate, selectRange, restoreFocus]+ );++ // Release focus guard after delay to allow async data re-renders to settle.+ // 300ms accounts for db sync and virtualized cell mounting.+ const releaseFocusGuard = React.useCallback((immediate = false) => {+ if (immediate) {+ focusGuardRef.current = false;+ return;+ }++ setTimeout(() => {+ focusGuardRef.current = false;+ }, 300);+ }, []);++ const focusCellWrapper = React.useCallback(+ (rowIndex: number, columnId: string) => {+ focusGuardRef.current = true;++ requestAnimationFrame(() => {+ const cellKey = getCellKey(rowIndex, columnId);+ const cellWrapperElement = cellMapRef.current.get(cellKey);++ if (!cellWrapperElement) {+ const container = dataGridRef.current;+ if (container) {+ container.focus();+ }+ releaseFocusGuard();+ return;+ }++ cellWrapperElement.focus();+ releaseFocusGuard();+ });+ },+ [releaseFocusGuard]+ );++ const focusCell = React.useCallback(+ (rowIndex: number, columnId: string) => {+ store.batch(() => {+ store.setState("focusedCell", { rowIndex, columnId });+ store.setState("editingCell", null);+ });++ const currentState = store.getState();++ if (currentState.searchOpen) return;++ focusCellWrapper(rowIndex, columnId);+ },+ [store, focusCellWrapper]+ );++ const onRowsDelete = React.useCallback(+ async (rowIndices: number[]) => {+ if (propsRef.current.readOnly || !propsRef.current.onRowsDelete || rowIndices.length === 0)+ return;++ const currentTable = tableRef.current;+ const rows = currentTable?.getRowModel().rows;++ if (!rows || rows.length === 0) return;++ const currentState = store.getState();+ const currentFocusedColumn = currentState.focusedCell?.columnId ?? navigableColumnIds[0];++ const minDeletedRowIndex = Math.min(...rowIndices);++ const rowsToDelete: TData[] = [];+ for (const rowIndex of rowIndices) {+ const row = rows[rowIndex];+ if (row) {+ rowsToDelete.push(row.original);+ }+ }++ await propsRef.current.onRowsDelete(rowsToDelete, rowIndices);++ store.batch(() => {+ store.setState("selectionState", {+ selectedCells: new Set(),+ selectionRange: null,+ isSelecting: false+ });+ store.setState("rowSelection", {});+ store.setState("editingCell", null);+ });+ propsRef.current.onRowSelectionChange?.({});++ requestAnimationFrame(() => {+ const currentTable = tableRef.current;+ const currentRows = currentTable?.getRowModel().rows ?? [];+ const newRowCount = currentRows.length ?? propsRef.current.data.length;++ if (newRowCount > 0 && currentFocusedColumn) {+ const targetRowIndex = Math.min(minDeletedRowIndex, newRowCount - 1);+ focusCell(targetRowIndex, currentFocusedColumn);+ }+ });+ },+ [propsRef, store, navigableColumnIds, focusCell]+ );++ const navigateCell = React.useCallback(+ (direction: NavigationDirection) => {+ const currentState = store.getState();+ if (!currentState.focusedCell) return;++ const { rowIndex, columnId } = currentState.focusedCell;+ const currentColIndex = navigableColumnIds.indexOf(columnId);+ const rowVirtualizer = rowVirtualizerRef.current;+ const currentTable = tableRef.current;+ const rows = currentTable?.getRowModel().rows ?? [];+ const rowCount = rows.length ?? propsRef.current.data.length;++ let newRowIndex = rowIndex;+ let newColumnId = columnId;++ const isRtl = dir === "rtl";++ switch (direction) {+ case "up":+ newRowIndex = Math.max(0, rowIndex - 1);+ break;+ case "down":+ newRowIndex = Math.min(rowCount - 1, rowIndex + 1);+ break;+ case "left":+ if (isRtl) {+ if (currentColIndex < navigableColumnIds.length - 1) {+ const nextColumnId = navigableColumnIds[currentColIndex + 1];+ if (nextColumnId) newColumnId = nextColumnId;+ }+ } else if (currentColIndex > 0) {+ const prevColumnId = navigableColumnIds[currentColIndex - 1];+ if (prevColumnId) newColumnId = prevColumnId;+ }+ break;+ case "right":+ if (isRtl) {+ if (currentColIndex > 0) {+ const prevColumnId = navigableColumnIds[currentColIndex - 1];+ if (prevColumnId) newColumnId = prevColumnId;+ }+ } else if (currentColIndex < navigableColumnIds.length - 1) {+ const nextColumnId = navigableColumnIds[currentColIndex + 1];+ if (nextColumnId) newColumnId = nextColumnId;+ }+ break;+ case "home":+ if (navigableColumnIds.length > 0) {+ newColumnId = navigableColumnIds[0] ?? columnId;+ }+ break;+ case "end":+ if (navigableColumnIds.length > 0) {+ newColumnId = navigableColumnIds[navigableColumnIds.length - 1] ?? columnId;+ }+ break;+ case "ctrl+home":+ newRowIndex = 0;+ if (navigableColumnIds.length > 0) {+ newColumnId = navigableColumnIds[0] ?? columnId;+ }+ break;+ case "ctrl+end":+ newRowIndex = Math.max(0, rowCount - 1);+ if (navigableColumnIds.length > 0) {+ newColumnId = navigableColumnIds[navigableColumnIds.length - 1] ?? columnId;+ }+ break;+ case "ctrl+up":+ newRowIndex = 0;+ break;+ case "ctrl+down":+ newRowIndex = Math.max(0, rowCount - 1);+ break;+ case "pageup":+ if (rowVirtualizer) {+ const visibleRange = rowVirtualizer.getVirtualItems();+ const pageSize = visibleRange.length ?? 10;+ newRowIndex = Math.max(0, rowIndex - pageSize);+ } else {+ newRowIndex = Math.max(0, rowIndex - 10);+ }+ break;+ case "pagedown":+ if (rowVirtualizer) {+ const visibleRange = rowVirtualizer.getVirtualItems();+ const pageSize = visibleRange.length ?? 10;+ newRowIndex = Math.min(rowCount - 1, rowIndex + pageSize);+ } else {+ newRowIndex = Math.min(rowCount - 1, rowIndex + 10);+ }+ break;+ case "pageleft":+ if (currentColIndex > 0) {+ const targetIndex = Math.max(0, currentColIndex - HORIZONTAL_PAGE_SIZE);+ const targetColumnId = navigableColumnIds[targetIndex];+ if (targetColumnId) newColumnId = targetColumnId;+ }+ break;+ case "pageright":+ if (currentColIndex < navigableColumnIds.length - 1) {+ const targetIndex = Math.min(+ navigableColumnIds.length - 1,+ currentColIndex + HORIZONTAL_PAGE_SIZE+ );+ const targetColumnId = navigableColumnIds[targetIndex];+ if (targetColumnId) newColumnId = targetColumnId;+ }+ break;+ }++ if (newRowIndex !== rowIndex || newColumnId !== columnId) {+ focusCell(newRowIndex, newColumnId);++ // Calculate and apply scrolls synchronously to avoid flashing+ const container = dataGridRef.current;+ if (!container) return;++ const targetRow = rowMapRef.current.get(newRowIndex);+ const cellKey = getCellKey(newRowIndex, newColumnId);+ const targetCell = cellMapRef.current.get(cellKey);++ // If target row is not rendered, scroll it into view first+ if (!targetRow) {+ if (rowVirtualizer) {+ const align =+ direction === "up" ||+ direction === "pageup" ||+ direction === "ctrl+up" ||+ direction === "ctrl+home"+ ? "start"+ : direction === "down" ||+ direction === "pagedown" ||+ direction === "ctrl+down" ||+ direction === "ctrl+end"+ ? "end"+ : "center";++ rowVirtualizer.scrollToIndex(newRowIndex, { align });++ // Wait for row to render before horizontal scroll+ if (newColumnId !== columnId) {+ requestAnimationFrame(() => {+ const cellKeyRetry = getCellKey(newRowIndex, newColumnId);+ const targetCellRetry = cellMapRef.current.get(cellKeyRetry);++ if (targetCellRetry) {+ const scrollDirection = getScrollDirection(direction);++ scrollCellIntoView({+ container,+ targetCell: targetCellRetry,+ tableRef,+ viewportOffset: VIEWPORT_OFFSET,+ direction: scrollDirection,+ isRtl: dir === "rtl"+ });+ }+ });+ }+ } else {+ // Fallback: use direct scroll calculation when virtualizer is not available+ const rowHeightValue = getRowHeightValue(rowHeight);+ const estimatedScrollTop = newRowIndex * rowHeightValue;+ container.scrollTop = estimatedScrollTop;+ }++ return;+ }++ // Vertical scrolling for rendered rows that changed+ if (newRowIndex !== rowIndex && targetRow) {+ requestAnimationFrame(() => {+ const containerRect = container.getBoundingClientRect();+ const headerHeight = headerRef.current?.getBoundingClientRect().height ?? 0;+ const footerHeight = footerRef.current?.getBoundingClientRect().height ?? 0;+ const viewportTop = containerRect.top + headerHeight + VIEWPORT_OFFSET;+ const viewportBottom = containerRect.bottom - footerHeight - VIEWPORT_OFFSET;++ const rowRect = targetRow.getBoundingClientRect();+ const isFullyVisible = rowRect.top >= viewportTop && rowRect.bottom <= viewportBottom;++ if (!isFullyVisible) {+ // Only apply vertical scroll for vertical navigation+ const isVerticalNavigation =+ direction === "up" ||+ direction === "down" ||+ direction === "pageup" ||+ direction === "pagedown" ||+ direction === "ctrl+up" ||+ direction === "ctrl+down" ||+ direction === "ctrl+home" ||+ direction === "ctrl+end";++ if (isVerticalNavigation) {+ if (+ direction === "down" ||+ direction === "pagedown" ||+ direction === "ctrl+down" ||+ direction === "ctrl+end"+ ) {+ container.scrollTop += rowRect.bottom - viewportBottom;+ } else {+ container.scrollTop -= viewportTop - rowRect.top;+ }+ }+ }+ });+ }++ // Horizontal scrolling for rendered cells+ if (newColumnId !== columnId && targetCell) {+ requestAnimationFrame(() => {+ const scrollDirection = getScrollDirection(direction);++ scrollCellIntoView({+ container,+ targetCell,+ tableRef,+ viewportOffset: VIEWPORT_OFFSET,+ direction: scrollDirection,+ isRtl: dir === "rtl"+ });+ });+ }+ }+ },+ [dir, store, navigableColumnIds, focusCell, propsRef, rowHeight]+ );++ const onCellEditingStart = React.useCallback(+ (rowIndex: number, columnId: string) => {+ if (propsRef.current.readOnly) return;++ store.batch(() => {+ store.setState("focusedCell", { rowIndex, columnId });+ store.setState("editingCell", { rowIndex, columnId });+ });+ },+ [store, propsRef]+ );++ const onCellEditingStop = React.useCallback(+ (opts?: { moveToNextRow?: boolean; direction?: NavigationDirection }) => {+ const currentState = store.getState();+ const currentEditing = currentState.editingCell;++ store.setState("editingCell", null);++ if (opts?.moveToNextRow && currentEditing) {+ const { rowIndex, columnId } = currentEditing;+ const currentTable = tableRef.current;+ const rows = currentTable?.getRowModel().rows ?? [];+ const rowCount = rows.length ?? propsRef.current.data.length;++ const nextRowIndex = rowIndex + 1;+ if (nextRowIndex < rowCount) {+ requestAnimationFrame(() => {+ focusCell(nextRowIndex, columnId);+ });+ }+ } else if (opts?.direction && currentEditing) {+ const { rowIndex, columnId } = currentEditing;+ focusCell(rowIndex, columnId);+ requestAnimationFrame(() => {+ navigateCell(opts.direction ?? "right");+ });+ } else if (currentEditing) {+ const { rowIndex, columnId } = currentEditing;+ focusCellWrapper(rowIndex, columnId);+ }+ },+ [store, propsRef, focusCell, navigateCell, focusCellWrapper]+ );++ const onSearchOpenChange = React.useCallback(+ (open: boolean) => {+ if (open) {+ store.setState("searchOpen", true);+ return;+ }++ const currentState = store.getState();+ const currentMatch =+ currentState.matchIndex >= 0 && currentState.searchMatches[currentState.matchIndex];++ store.batch(() => {+ store.setState("searchOpen", false);+ store.setState("searchQuery", "");+ store.setState("searchMatches", []);+ store.setState("matchIndex", -1);++ if (currentMatch) {+ store.setState("focusedCell", {+ rowIndex: currentMatch.rowIndex,+ columnId: currentMatch.columnId+ });+ }+ });++ if (dataGridRef.current && document.activeElement !== dataGridRef.current) {+ dataGridRef.current.focus();+ }+ },+ [store]+ );++ const onSearch = React.useCallback(+ (query: string) => {+ if (!query.trim()) {+ store.batch(() => {+ store.setState("searchMatches", []);+ store.setState("matchIndex", -1);+ });+ return;+ }++ const matches: CellPosition[] = [];+ const currentTable = tableRef.current;+ const rows = currentTable?.getRowModel().rows ?? [];++ const lowerQuery = query.toLowerCase();++ for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {+ const row = rows[rowIndex];+ if (!row) continue;++ for (const columnId of columnIds) {+ const cell = row.getVisibleCells().find((c) => c.column.id === columnId);+ if (!cell) continue;++ const value = cell.getValue();+ const stringValue = String(value ?? "").toLowerCase();++ if (stringValue.includes(lowerQuery)) {+ matches.push({ rowIndex, columnId });+ }+ }+ }++ store.batch(() => {+ store.setState("searchMatches", matches);+ store.setState("matchIndex", matches.length > 0 ? 0 : -1);+ });++ if (matches.length > 0 && matches[0]) {+ const firstMatch = matches[0];+ rowVirtualizerRef.current?.scrollToIndex(firstMatch.rowIndex, {+ align: "center"+ });+ }+ },+ [columnIds, store]+ );++ const onSearchQueryChange = React.useCallback(+ (query: string) => store.setState("searchQuery", query),+ [store]+ );++ const onNavigateToPrevMatch = React.useCallback(() => {+ const currentState = store.getState();+ if (currentState.searchMatches.length === 0) return;++ const prevIndex =+ currentState.matchIndex - 1 < 0+ ? currentState.searchMatches.length - 1+ : currentState.matchIndex - 1;+ const match = currentState.searchMatches[prevIndex];++ if (match) {+ rowVirtualizerRef.current?.scrollToIndex(match.rowIndex, {+ align: "center"+ });++ requestAnimationFrame(() => {+ store.setState("matchIndex", prevIndex);+ requestAnimationFrame(() => {+ focusCell(match.rowIndex, match.columnId);+ });+ });+ }+ }, [store, focusCell]);++ const onNavigateToNextMatch = React.useCallback(() => {+ const currentState = store.getState();+ if (currentState.searchMatches.length === 0) return;++ const nextIndex = (currentState.matchIndex + 1) % currentState.searchMatches.length;+ const match = currentState.searchMatches[nextIndex];++ if (match) {+ rowVirtualizerRef.current?.scrollToIndex(match.rowIndex, {+ align: "center"+ });++ requestAnimationFrame(() => {+ store.setState("matchIndex", nextIndex);+ requestAnimationFrame(() => {+ focusCell(match.rowIndex, match.columnId);+ });+ });+ }+ }, [store, focusCell]);++ const getIsSearchMatch = React.useCallback(+ (rowIndex: number, columnId: string) => {+ const currentSearchMatches = store.getState().searchMatches;+ return currentSearchMatches.some(+ (match) => match.rowIndex === rowIndex && match.columnId === columnId+ );+ },+ [store]+ );++ const getIsActiveSearchMatch = React.useCallback(+ (rowIndex: number, columnId: string) => {+ const currentState = store.getState();+ if (currentState.matchIndex < 0) return false;+ const currentMatch = currentState.searchMatches[currentState.matchIndex];+ return currentMatch?.rowIndex === rowIndex && currentMatch?.columnId === columnId;+ },+ [store]+ );++ // Compute search match data for targeted row re-renders+ // Maps rowIndex -> Set of columnIds that have matches in that row+ const searchMatchesByRow = React.useMemo(() => {+ if (searchMatches.length === 0) return null;+ const rowMap = new Map<number, Set<string>>();+ for (const match of searchMatches) {+ let columnSet = rowMap.get(match.rowIndex);+ if (!columnSet) {+ columnSet = new Set<string>();+ rowMap.set(match.rowIndex, columnSet);+ }+ columnSet.add(match.columnId);+ }+ return rowMap;+ }, [searchMatches]);++ const activeSearchMatch = React.useMemo<CellPosition | null>(() => {+ if (matchIndex < 0 || searchMatches.length === 0) return null;+ return searchMatches[matchIndex] ?? null;+ }, [searchMatches, matchIndex]);++ const blurCell = React.useCallback(() => {+ const currentState = store.getState();+ if (currentState.editingCell && document.activeElement instanceof HTMLElement) {+ document.activeElement.blur();+ }++ store.batch(() => {+ store.setState("focusedCell", null);+ store.setState("editingCell", null);+ });+ }, [store]);++ const onCellClick = React.useCallback(+ (rowIndex: number, columnId: string, event?: React.MouseEvent) => {+ if (event?.button === 2) {+ return;+ }++ const currentState = store.getState();+ const currentFocused = currentState.focusedCell;++ function scrollToCell() {+ requestAnimationFrame(() => {+ const container = dataGridRef.current;+ const cellKey = getCellKey(rowIndex, columnId);+ const targetCell = cellMapRef.current.get(cellKey);++ if (container && targetCell) {+ scrollCellIntoView({+ container,+ targetCell,+ tableRef,+ viewportOffset: VIEWPORT_OFFSET,+ isRtl: dir === "rtl"+ });+ }+ });+ }++ if (event) {+ if (event.ctrlKey || event.metaKey) {+ event.preventDefault();+ const cellKey = getCellKey(rowIndex, columnId);+ const newSelectedCells = new Set(currentState.selectionState.selectedCells);++ if (newSelectedCells.has(cellKey)) {+ newSelectedCells.delete(cellKey);+ } else {+ newSelectedCells.add(cellKey);+ }++ store.setState("selectionState", {+ selectedCells: newSelectedCells,+ selectionRange: null,+ isSelecting: false+ });+ focusCell(rowIndex, columnId);+ scrollToCell();+ return;+ }++ if (event.shiftKey && currentState.focusedCell) {+ event.preventDefault();+ selectRange(currentState.focusedCell, { rowIndex, columnId });+ scrollToCell();+ return;+ }+ }++ const hasSelectedCells = currentState.selectionState.selectedCells.size > 0;+ const hasSelectedRows = Object.keys(currentState.rowSelection).length > 0;++ if (hasSelectedCells && !currentState.selectionState.isSelecting) {+ const cellKey = getCellKey(rowIndex, columnId);+ const isClickingSelectedCell = currentState.selectionState.selectedCells.has(cellKey);++ if (!isClickingSelectedCell) {+ onSelectionClear();+ } else {+ focusCell(rowIndex, columnId);+ scrollToCell();+ return;+ }+ } else if (hasSelectedRows && columnId !== "select") {+ onSelectionClear();+ }++ if (currentFocused?.rowIndex === rowIndex && currentFocused?.columnId === columnId) {+ onCellEditingStart(rowIndex, columnId);+ } else {+ focusCell(rowIndex, columnId);+ scrollToCell();+ }+ },+ [store, focusCell, onCellEditingStart, selectRange, onSelectionClear, dir]+ );++ const onCellDoubleClick = React.useCallback(+ (rowIndex: number, columnId: string, event?: React.MouseEvent) => {+ if (event?.defaultPrevented) return;++ onCellEditingStart(rowIndex, columnId);+ },+ [onCellEditingStart]+ );++ const onCellMouseDown = React.useCallback(+ (rowIndex: number, columnId: string, event: React.MouseEvent) => {+ if (event.button === 2) {+ return;+ }++ event.preventDefault();++ if (!event.ctrlKey && !event.metaKey && !event.shiftKey) {+ const cellKey = getCellKey(rowIndex, columnId);+ store.batch(() => {+ store.setState("selectionState", {+ selectedCells: propsRef.current.enableSingleCellSelection+ ? new Set([cellKey])+ : new Set(),+ selectionRange: {+ start: { rowIndex, columnId },+ end: { rowIndex, columnId }+ },+ isSelecting: true+ });+ store.setState("rowSelection", {});+ });+ propsRef.current.onRowSelectionChange?.({});+ }+ },+ [store, propsRef]+ );++ const onCellMouseEnter = React.useCallback(+ (rowIndex: number, columnId: string) => {+ const currentState = store.getState();+ if (currentState.selectionState.isSelecting && currentState.selectionState.selectionRange) {+ const { start } = currentState.selectionState.selectionRange;+ const end = { rowIndex, columnId };++ if (+ currentState.focusedCell?.rowIndex !== start.rowIndex ||+ currentState.focusedCell?.columnId !== start.columnId+ ) {+ focusCell(start.rowIndex, start.columnId);+ }++ selectRange(start, end, true);+ }+ },+ [store, selectRange, focusCell]+ );++ const onCellMouseUp = React.useCallback(() => {+ const currentState = store.getState();+ store.setState("selectionState", {+ ...currentState.selectionState,+ isSelecting: false+ });+ }, [store]);++ const onCellContextMenu = React.useCallback(+ (rowIndex: number, columnId: string, event: React.MouseEvent) => {+ event.preventDefault();+ event.stopPropagation();++ const currentState = store.getState();+ const cellKey = getCellKey(rowIndex, columnId);+ const isTargetCellSelected = currentState.selectionState.selectedCells.has(cellKey);++ if (!isTargetCellSelected) {+ store.batch(() => {+ store.setState("selectionState", {+ selectedCells: new Set([cellKey]),+ selectionRange: {+ start: { rowIndex, columnId },+ end: { rowIndex, columnId }+ },+ isSelecting: false+ });+ store.setState("focusedCell", { rowIndex, columnId });+ store.setState("rowSelection", {});+ });+ propsRef.current.onRowSelectionChange?.({});+ }++ store.setState("contextMenu", {+ open: true,+ x: event.clientX,+ y: event.clientY+ });+ },+ [store]+ );++ const onContextMenuOpenChange = React.useCallback(+ (open: boolean) => {+ if (!open) {+ const currentMenu = store.getState().contextMenu;+ store.setState("contextMenu", {+ open: false,+ x: currentMenu.x,+ y: currentMenu.y+ });+ }+ },+ [store]+ );++ const onSortingChange = React.useCallback(+ (updater: Updater<SortingState>) => {+ const currentState = store.getState();+ const newSorting = typeof updater === "function" ? updater(currentState.sorting) : updater;+ store.setState("sorting", newSorting);++ propsRef.current.onSortingChange?.(newSorting);+ },+ [store, propsRef]+ );++ const onColumnFiltersChange = React.useCallback(+ (updater: Updater<ColumnFiltersState>) => {+ const currentState = store.getState();+ const newColumnFilters =+ typeof updater === "function" ? updater(currentState.columnFilters) : updater;+ store.setState("columnFilters", newColumnFilters);++ propsRef.current.onColumnFiltersChange?.(newColumnFilters);+ },+ [store, propsRef]+ );++ const onRowSelectionChange = React.useCallback(+ (updater: Updater<RowSelectionState>) => {+ const currentState = store.getState();+ const newRowSelection =+ typeof updater === "function" ? updater(currentState.rowSelection) : updater;++ // Remove false entries so TanStack's getIsSomeRowsSelected works correctly+ const cleanedRowSelection: RowSelectionState = {};+ for (const key of Object.keys(newRowSelection)) {+ if (newRowSelection[key]) {+ cleanedRowSelection[key] = true;+ }+ }++ const selectedRows = Object.keys(cleanedRowSelection);++ const selectedCells = new Set<string>();+ const rows = tableRef.current?.getRowModel().rows ?? [];++ for (const rowId of selectedRows) {+ const rowIndex = rows.findIndex((r) => r.id === rowId);+ if (rowIndex === -1) continue;++ for (const columnId of columnIds) {+ selectedCells.add(getCellKey(rowIndex, columnId));+ }+ }++ store.batch(() => {+ store.setState("rowSelection", cleanedRowSelection);+ store.setState("selectionState", {+ selectedCells,+ selectionRange: null,+ isSelecting: false+ });+ store.setState("focusedCell", null);+ store.setState("editingCell", null);+ });+ propsRef.current.onRowSelectionChange?.(cleanedRowSelection);+ },+ [store, columnIds, propsRef]+ );++ const onRowSelect = React.useCallback(+ (rowIndex: number, selected: boolean, shiftKey: boolean) => {+ const currentState = store.getState();+ const rows = tableRef.current?.getRowModel().rows ?? [];+ const currentRow = rows[rowIndex];+ if (!currentRow) return;++ if (shiftKey && currentState.lastClickedRowIndex !== null) {+ const startIndex = Math.min(currentState.lastClickedRowIndex, rowIndex);+ const endIndex = Math.max(currentState.lastClickedRowIndex, rowIndex);++ const newRowSelection: RowSelectionState = {+ ...currentState.rowSelection+ };++ for (let i = startIndex; i <= endIndex; i++) {+ const row = rows[i];+ if (row) {+ newRowSelection[row.id] = selected;+ }+ }++ onRowSelectionChange(newRowSelection);+ } else {+ onRowSelectionChange({+ ...currentState.rowSelection,+ [currentRow.id]: selected+ });+ }++ store.setState("lastClickedRowIndex", rowIndex);+ },+ [store, onRowSelectionChange]+ );++ const onRowHeightChange = React.useCallback(+ (updater: Updater<RowHeightValue>) => {+ const currentState = store.getState();+ const newRowHeight =+ typeof updater === "function" ? updater(currentState.rowHeight) : updater;+ store.setState("rowHeight", newRowHeight);+ propsRef.current.onRowHeightChange?.(newRowHeight);+ },+ [store, propsRef]+ );++ const onColumnClick = React.useCallback(+ (columnId: string) => {+ if (!propsRef.current.enableColumnSelection) {+ onSelectionClear();+ return;+ }++ selectColumn(columnId);+ },+ [propsRef, selectColumn, onSelectionClear]+ );++ const onPasteDialogOpenChange = React.useCallback(+ (open: boolean) => {+ if (!open) {+ store.setState("pasteDialog", {+ open: false,+ rowsNeeded: 0,+ clipboardText: ""+ });+ }+ },+ [store]+ );++ const defaultColumn: Partial<ColumnDef<TData>> = React.useMemo(+ () => ({+ // Note: cell is rendered directly in DataGridRow to bypass flexRender's+ // unstable cell.getContext() (see TanStack Table issue #4794)+ minSize: MIN_COLUMN_SIZE,+ maxSize: MAX_COLUMN_SIZE+ }),+ []+ );++ const tableMeta = React.useMemo<TableMeta<TData>>(() => {+ return {+ ...propsRef.current.meta,+ dataGridRef,+ cellMapRef,+ // Use getters for frequently changing state values to avoid recreating meta+ get focusedCell() {+ return store.getState().focusedCell;+ },+ get editingCell() {+ return store.getState().editingCell;+ },+ get selectionState() {+ return store.getState().selectionState;+ },+ get searchOpen() {+ return store.getState().searchOpen;+ },+ get contextMenu() {+ return store.getState().contextMenu;+ },+ get pasteDialog() {+ return store.getState().pasteDialog;+ },+ get rowHeight() {+ return store.getState().rowHeight;+ },+ get readOnly() {+ return propsRef.current.readOnly;+ },+ getIsCellSelected,+ getIsSearchMatch,+ getIsActiveSearchMatch,+ getVisualRowIndex,+ onRowHeightChange,+ onRowSelect,+ onDataUpdate,+ onRowsDelete: propsRef.current.onRowsDelete ? onRowsDelete : undefined,+ onColumnClick,+ onCellClick,+ onCellDoubleClick,+ onCellMouseDown,+ onCellMouseEnter,+ onCellMouseUp,+ onCellContextMenu,+ onCellEditingStart,+ onCellEditingStop,+ onCellsCopy,+ onCellsCut,+ onCellsPaste,+ onSelectionClear,+ onFilesUpload: propsRef.current.onFilesUpload ? propsRef.current.onFilesUpload : undefined,+ onFilesDelete: propsRef.current.onFilesDelete ? propsRef.current.onFilesDelete : undefined,+ onContextMenuOpenChange,+ onPasteDialogOpenChange+ };+ }, [+ propsRef,+ store,+ getIsCellSelected,+ getIsSearchMatch,+ getIsActiveSearchMatch,+ getVisualRowIndex,+ onRowHeightChange,+ onRowSelect,+ onDataUpdate,+ onRowsDelete,+ onColumnClick,+ onCellClick,+ onCellDoubleClick,+ onCellMouseDown,+ onCellMouseEnter,+ onCellMouseUp,+ onCellContextMenu,+ onCellEditingStart,+ onCellEditingStop,+ onCellsCopy,+ onCellsCut,+ onCellsPaste,+ onSelectionClear,+ onContextMenuOpenChange,+ onPasteDialogOpenChange+ ]);++ const getMemoizedCoreRowModel = React.useMemo(() => getCoreRowModel(), []);+ const getMemoizedFilteredRowModel = React.useMemo(() => getFilteredRowModel(), []);+ const getMemoizedSortedRowModel = React.useMemo(() => getSortedRowModel(), []);++ // Memoize state object to reduce shallow equality checks+ const tableState = React.useMemo<Partial<TableState>>(+ () => ({+ ...propsRef.current.state,+ sorting,+ columnFilters,+ rowSelection+ }),+ [propsRef, sorting, columnFilters, rowSelection]+ );++ const tableOptions = React.useMemo<TableOptions<TData>>(() => {+ return {+ ...propsRef.current,+ data,+ columns,+ defaultColumn,+ initialState: propsRef.current.initialState,+ state: tableState,+ onRowSelectionChange,+ onSortingChange,+ onColumnFiltersChange,+ columnResizeMode: "onChange",+ columnResizeDirection: dir,+ getCoreRowModel: getMemoizedCoreRowModel,+ getFilteredRowModel: getMemoizedFilteredRowModel,+ getSortedRowModel: getMemoizedSortedRowModel,+ meta: tableMeta+ };+ }, [+ propsRef,+ data,+ columns,+ defaultColumn,+ tableState,+ dir,+ onRowSelectionChange,+ onSortingChange,+ onColumnFiltersChange,+ getMemoizedCoreRowModel,+ getMemoizedFilteredRowModel,+ getMemoizedSortedRowModel,+ tableMeta+ ]);++ const table = useReactTable(tableOptions);++ if (!tableRef.current) {+ tableRef.current = table;+ }++ // biome-ignore lint/correctness/useExhaustiveDependencies: columnSizingInfo, columnSizing, and columns are used for calculating the column size vars+ const columnSizeVars = React.useMemo(() => {+ const headers = table.getFlatHeaders();+ const colSizes: { [key: string]: number } = {};+ for (const header of headers) {+ colSizes[`--header-${sanitizeCssId(header.id)}-size`] = header.getSize();+ colSizes[`--col-${sanitizeCssId(header.column.id)}-size`] = header.column.getSize();+ }+ return colSizes;+ }, [table.getState().columnSizingInfo, table.getState().columnSizing, columns]);++ const isFirefox = React.useSyncExternalStore(+ React.useCallback(() => () => {}, []),+ React.useCallback(() => {+ if (typeof window === "undefined" || typeof navigator === "undefined") {+ return false;+ }+ return navigator.userAgent.indexOf("Firefox") !== -1;+ }, []),+ React.useCallback(() => false, [])+ );++ // biome-ignore lint/correctness/useExhaustiveDependencies: columnPinning is used for calculating the adjustLayout+ const adjustLayout = React.useMemo(() => {+ const { columnPinning } = table.getState();+ return (+ isFirefox && ((columnPinning.left?.length ?? 0) > 0 || (columnPinning.right?.length ?? 0) > 0)+ );+ }, [isFirefox, table.getState().columnPinning]);++ const rowVirtualizer = useVirtualizer({+ count: table.getRowModel().rows.length,+ getScrollElement: () => dataGridRef.current,+ estimateSize: () => rowHeightValue,+ overscan,+ measureElement: !isFirefox ? (element) => element?.getBoundingClientRect().height : undefined+ });++ if (!rowVirtualizerRef.current) {+ rowVirtualizerRef.current = rowVirtualizer;+ }++ const onScrollToRow = React.useCallback(+ async (opts: Partial<CellPosition>) => {+ const rowIndex = opts?.rowIndex ?? 0;+ const columnId = opts?.columnId;++ focusGuardRef.current = true;++ const navigableIds = propsRef.current.columns+ .map((c) => {+ if (c.id) return c.id;+ if ("accessorKey" in c) return c.accessorKey as string;+ return undefined;+ })+ .filter((id): id is string => Boolean(id))+ .filter((c) => !NON_NAVIGABLE_COLUMN_IDS.includes(c));++ const targetColumnId = columnId ?? navigableIds[0];++ if (!targetColumnId) {+ releaseFocusGuard(true);+ return;+ }++ async function onScrollAndFocus(retryCount: number) {+ if (!targetColumnId) return;+ const currentRowCount = propsRef.current.data.length;++ // If the requested row doesn't exist yet, wait for data to update+ if (rowIndex >= currentRowCount && retryCount > 0) {+ await new Promise((resolve) => setTimeout(resolve, 50));+ await onScrollAndFocus(retryCount - 1);+ return;+ }++ const safeRowIndex = Math.min(rowIndex, Math.max(0, currentRowCount - 1));++ const isBottomHalf = safeRowIndex > currentRowCount / 2;+ rowVirtualizer.scrollToIndex(safeRowIndex, {+ align: isBottomHalf ? "end" : "start"+ });++ await new Promise((resolve) => requestAnimationFrame(resolve));++ // Adjust scroll position to account for sticky header/footer+ const container = dataGridRef.current;+ const targetRow = rowMapRef.current.get(safeRowIndex);++ if (container && targetRow) {+ const containerRect = container.getBoundingClientRect();+ const headerHeight = headerRef.current?.getBoundingClientRect().height ?? 0;+ const footerHeight = footerRef.current?.getBoundingClientRect().height ?? 0;++ const viewportTop = containerRect.top + headerHeight + VIEWPORT_OFFSET;+ const viewportBottom = containerRect.bottom - footerHeight - VIEWPORT_OFFSET;++ const rowRect = targetRow.getBoundingClientRect();+ const isFullyVisible = rowRect.top >= viewportTop && rowRect.bottom <= viewportBottom;++ if (!isFullyVisible) {+ if (rowRect.top < viewportTop) {+ // Row is partially hidden by header - scroll up+ container.scrollTop -= viewportTop - rowRect.top;+ } else if (rowRect.bottom > viewportBottom) {+ // Row is partially hidden by footer - scroll down+ container.scrollTop += rowRect.bottom - viewportBottom;+ }+ }+ }++ store.batch(() => {+ store.setState("focusedCell", {+ rowIndex: safeRowIndex,+ columnId: targetColumnId+ });+ store.setState("editingCell", null);+ });++ const cellKey = getCellKey(safeRowIndex, targetColumnId);+ const cellElement = cellMapRef.current.get(cellKey);++ if (cellElement) {+ cellElement.focus();+ releaseFocusGuard();+ } else if (retryCount > 0) {+ await new Promise((resolve) => requestAnimationFrame(resolve));+ await onScrollAndFocus(retryCount - 1);+ } else {+ dataGridRef.current?.focus();+ releaseFocusGuard();+ }+ }++ await onScrollAndFocus(SCROLL_SYNC_RETRY_COUNT);+ },+ [rowVirtualizer, propsRef, store, releaseFocusGuard]+ );++ const onRowAdd = React.useCallback(+ async (event?: React.MouseEvent<HTMLDivElement>) => {+ if (propsRef.current.readOnly || !propsRef.current.onRowAdd) return;++ const initialRowCount = propsRef.current.data.length;++ let result: Partial<CellPosition> | null;+ try {+ result = await propsRef.current.onRowAdd(event);+ } catch {+ // Callback threw an error, don't proceed with scroll/focus+ return;+ }++ if (result === null || event?.defaultPrevented) return;++ onSelectionClear();++ // Trust the returned rowIndex from the callback+ // onScrollToRow will handle retries if the row isn't rendered yet+ const targetRowIndex = result.rowIndex ?? initialRowCount;+ const targetColumnId = result.columnId;++ onScrollToRow({+ rowIndex: targetRowIndex,+ columnId: targetColumnId+ });+ },+ [propsRef, onScrollToRow, onSelectionClear]+ );++ const onDataGridKeyDown = React.useCallback(+ (event: KeyboardEvent) => {+ const currentState = store.getState();+ const { key, ctrlKey, metaKey, shiftKey, altKey } = event;+ const isCtrlPressed = ctrlKey || metaKey;++ if (+ propsRef.current.enableSearch &&+ isCtrlPressed &&+ !shiftKey &&+ key === SEARCH_SHORTCUT_KEY+ ) {+ event.preventDefault();+ onSearchOpenChange(true);+ return;+ }++ if (propsRef.current.enableSearch && currentState.searchOpen && !currentState.editingCell) {+ if (key === "Enter") {+ event.preventDefault();+ if (shiftKey) {+ onNavigateToPrevMatch();+ } else {+ onNavigateToNextMatch();+ }+ return;+ }+ if (key === "Escape") {+ event.preventDefault();+ onSearchOpenChange(false);+ return;+ }+ return;+ }++ // Cell editing keyboard events (Enter, Tab, Escape) are handled by the cell variants+ // to ensure proper value commitment before navigation+ if (currentState.editingCell) return;++ if (+ isCtrlPressed &&+ (key === "Backspace" || key === "Delete") &&+ !propsRef.current.readOnly &&+ propsRef.current.onRowsDelete+ ) {+ const rowIndices = new Set<number>();++ const selectedRowIds = Object.keys(currentState.rowSelection);+ if (selectedRowIds.length > 0) {+ const currentTable = tableRef.current;+ const rows = currentTable?.getRowModel().rows ?? [];+ for (const row of rows) {+ if (currentState.rowSelection[row.id]) {+ rowIndices.add(row.index);+ }+ }+ } else if (currentState.selectionState.selectedCells.size > 0) {+ for (const cellKey of currentState.selectionState.selectedCells) {+ const { rowIndex } = parseCellKey(cellKey);+ rowIndices.add(rowIndex);+ }+ } else if (currentState.focusedCell) {+ rowIndices.add(currentState.focusedCell.rowIndex);+ }++ if (rowIndices.size > 0) {+ event.preventDefault();+ onRowsDelete(Array.from(rowIndices));+ }+ return;+ }++ if (!currentState.focusedCell) return;++ let direction: NavigationDirection | null = null;++ if (isCtrlPressed && !shiftKey && key === "a") {+ event.preventDefault();+ selectAll();+ return;+ }++ if (isCtrlPressed && !shiftKey && key === "c") {+ event.preventDefault();+ onCellsCopy();+ return;+ }++ if (isCtrlPressed && !shiftKey && key === "x" && !propsRef.current.readOnly) {+ event.preventDefault();+ onCellsCut();+ return;+ }++ if (+ propsRef.current.enablePaste &&+ isCtrlPressed &&+ !shiftKey &&+ key === "v" &&+ !propsRef.current.readOnly+ ) {+ event.preventDefault();+ onCellsPaste();+ return;+ }++ if (+ (key === "Delete" || key === "Backspace") &&+ !isCtrlPressed &&+ !propsRef.current.readOnly+ ) {+ const cellsToClear =+ currentState.selectionState.selectedCells.size > 0+ ? Array.from(currentState.selectionState.selectedCells)+ : currentState.focusedCell+ ? [getCellKey(currentState.focusedCell.rowIndex, currentState.focusedCell.columnId)]+ : [];++ if (cellsToClear.length > 0) {+ event.preventDefault();++ const updates: Array<{+ rowIndex: number;+ columnId: string;+ value: unknown;+ }> = [];++ const currentTable = tableRef.current;+ const tableColumns = currentTable?.getAllColumns() ?? [];++ for (const cellKey of cellsToClear) {+ const { rowIndex, columnId } = parseCellKey(cellKey);++ const column = tableColumns.find((c) => c.id === columnId);+ const cellVariant = column?.columnDef?.meta?.cell?.variant;++ let emptyValue: unknown = "";+ if (cellVariant === "multi-select" || cellVariant === "file") {+ emptyValue = [];+ } else if (cellVariant === "number" || cellVariant === "date") {+ emptyValue = null;+ } else if (cellVariant === "checkbox") {+ emptyValue = false;+ }++ updates.push({ rowIndex, columnId, value: emptyValue });+ }++ onDataUpdate(updates);++ if (currentState.selectionState.selectedCells.size > 0) {+ onSelectionClear();+ }++ if (currentState.cutCells.size > 0) {+ store.setState("cutCells", new Set());+ }+ }+ return;+ }++ if (key === "Enter" && shiftKey && !propsRef.current.readOnly && propsRef.current.onRowAdd) {+ event.preventDefault();+ const initialRowCount = propsRef.current.data.length;+ const currentColumnId = currentState.focusedCell.columnId;++ Promise.resolve(propsRef.current.onRowAdd())+ .then(async (result) => {+ if (result === null) return;++ onSelectionClear();++ const targetRowIndex = result.rowIndex ?? initialRowCount;+ const targetColumnId = result.columnId ?? currentColumnId;++ onScrollToRow({+ rowIndex: targetRowIndex,+ columnId: targetColumnId+ });+ })+ .catch(() => {+ // Callback threw an error, don't proceed with scroll/focus+ });+ return;+ }++ switch (key) {+ case "ArrowUp":+ if (altKey && !isCtrlPressed && !shiftKey) {+ direction = "pageup";+ } else if (isCtrlPressed && shiftKey) {+ const selectionEdge =+ currentState.selectionState.selectionRange?.end || currentState.focusedCell;+ const currentColIndex = navigableColumnIds.indexOf(selectionEdge.columnId);+ const selectionStart =+ currentState.selectionState.selectionRange?.start || currentState.focusedCell;++ selectRange(selectionStart, {+ rowIndex: 0,+ columnId: navigableColumnIds[currentColIndex] ?? selectionEdge.columnId+ });++ const rowVirtualizer = rowVirtualizerRef.current;+ if (rowVirtualizer) {+ rowVirtualizer.scrollToIndex(0, { align: "start" });+ }++ restoreFocus(dataGridRef.current);++ event.preventDefault();+ return;+ } else if (isCtrlPressed && !shiftKey) {+ direction = "ctrl+up";+ } else {+ direction = "up";+ }+ break;+ case "ArrowDown":+ if (altKey && !isCtrlPressed && !shiftKey) {+ direction = "pagedown";+ } else if (isCtrlPressed && shiftKey) {+ const rowCount =+ tableRef.current?.getRowModel().rows.length || propsRef.current.data.length;+ const selectionEdge =+ currentState.selectionState.selectionRange?.end || currentState.focusedCell;+ const currentColIndex = navigableColumnIds.indexOf(selectionEdge.columnId);+ const selectionStart =+ currentState.selectionState.selectionRange?.start || currentState.focusedCell;++ selectRange(selectionStart, {+ rowIndex: Math.max(0, rowCount - 1),+ columnId: navigableColumnIds[currentColIndex] ?? selectionEdge.columnId+ });++ const rowVirtualizer = rowVirtualizerRef.current;+ if (rowVirtualizer) {+ rowVirtualizer.scrollToIndex(Math.max(0, rowCount - 1), {+ align: "end"+ });+ }++ restoreFocus(dataGridRef.current);++ event.preventDefault();+ return;+ } else if (isCtrlPressed && !shiftKey) {+ direction = "ctrl+down";+ } else {+ direction = "down";+ }+ break;+ case "ArrowLeft":+ if (isCtrlPressed && shiftKey) {+ const selectionEdge =+ currentState.selectionState.selectionRange?.end || currentState.focusedCell;+ const selectionStart =+ currentState.selectionState.selectionRange?.start || currentState.focusedCell;+ const targetColumnId =+ dir === "rtl"+ ? navigableColumnIds[navigableColumnIds.length - 1]+ : navigableColumnIds[0];++ if (targetColumnId) {+ selectRange(selectionStart, {+ rowIndex: selectionEdge.rowIndex,+ columnId: targetColumnId+ });++ const container = dataGridRef.current;+ const cellKey = getCellKey(selectionEdge.rowIndex, targetColumnId);+ const targetCell = cellMapRef.current.get(cellKey);+ if (container && targetCell) {+ scrollCellIntoView({+ container,+ targetCell,+ tableRef,+ viewportOffset: VIEWPORT_OFFSET,+ direction: "home",+ isRtl: dir === "rtl"+ });+ }++ restoreFocus(container);+ }+ event.preventDefault();+ return;+ }+ if (isCtrlPressed && !shiftKey) {+ direction = "home";+ } else {+ direction = "left";+ }+ break;+ case "ArrowRight":+ if (isCtrlPressed && shiftKey) {+ const selectionEdge =+ currentState.selectionState.selectionRange?.end || currentState.focusedCell;+ const selectionStart =+ currentState.selectionState.selectionRange?.start || currentState.focusedCell;+ const targetColumnId =+ dir === "rtl"+ ? navigableColumnIds[0]+ : navigableColumnIds[navigableColumnIds.length - 1];++ if (targetColumnId) {+ selectRange(selectionStart, {+ rowIndex: selectionEdge.rowIndex,+ columnId: targetColumnId+ });++ const container = dataGridRef.current;+ const cellKey = getCellKey(selectionEdge.rowIndex, targetColumnId);+ const targetCell = cellMapRef.current.get(cellKey);+ if (container && targetCell) {+ scrollCellIntoView({+ container,+ targetCell,+ tableRef,+ viewportOffset: VIEWPORT_OFFSET,+ direction: "end",+ isRtl: dir === "rtl"+ });+ }++ restoreFocus(container);+ }+ event.preventDefault();+ return;+ }+ if (isCtrlPressed && !shiftKey) {+ direction = "end";+ } else {+ direction = "right";+ }+ break;+ case "Home":+ direction = isCtrlPressed ? "ctrl+home" : "home";+ break;+ case "End":+ direction = isCtrlPressed ? "ctrl+end" : "end";+ break;+ case "PageUp":+ direction = altKey ? "pageleft" : "pageup";+ break;+ case "PageDown":+ direction = altKey ? "pageright" : "pagedown";+ break;+ case "Escape":+ event.preventDefault();+ if (+ currentState.selectionState.selectedCells.size > 0 ||+ Object.keys(currentState.rowSelection).length > 0+ ) {+ onSelectionClear();+ } else {+ blurCell();+ }+ return;+ case "Tab":+ event.preventDefault();+ if (dir === "rtl") {+ direction = event.shiftKey ? "right" : "left";+ } else {+ direction = event.shiftKey ? "left" : "right";+ }+ break;+ }++ if (direction) {+ event.preventDefault();++ if (shiftKey && key !== "Tab" && currentState.focusedCell) {+ const selectionEdge =+ currentState.selectionState.selectionRange?.end || currentState.focusedCell;++ const currentColIndex = navigableColumnIds.indexOf(selectionEdge.columnId);+ let newRowIndex = selectionEdge.rowIndex;+ let newColumnId = selectionEdge.columnId;++ const isRtl = dir === "rtl";++ const rowCount =+ tableRef.current?.getRowModel().rows.length || propsRef.current.data.length;++ switch (direction) {+ case "up":+ newRowIndex = Math.max(0, selectionEdge.rowIndex - 1);+ break;+ case "down":+ newRowIndex = Math.min(rowCount - 1, selectionEdge.rowIndex + 1);+ break;+ case "left":+ if (isRtl) {+ if (currentColIndex < navigableColumnIds.length - 1) {+ const nextColumnId = navigableColumnIds[currentColIndex + 1];+ if (nextColumnId) newColumnId = nextColumnId;+ }+ } else if (currentColIndex > 0) {+ const prevColumnId = navigableColumnIds[currentColIndex - 1];+ if (prevColumnId) newColumnId = prevColumnId;+ }+ break;+ case "right":+ if (isRtl) {+ if (currentColIndex > 0) {+ const prevColumnId = navigableColumnIds[currentColIndex - 1];+ if (prevColumnId) newColumnId = prevColumnId;+ }+ } else if (currentColIndex < navigableColumnIds.length - 1) {+ const nextColumnId = navigableColumnIds[currentColIndex + 1];+ if (nextColumnId) newColumnId = nextColumnId;+ }+ break;+ case "home":+ if (navigableColumnIds.length > 0) {+ newColumnId = navigableColumnIds[0] ?? newColumnId;+ }+ break;+ case "end":+ if (navigableColumnIds.length > 0) {+ newColumnId = navigableColumnIds[navigableColumnIds.length - 1] ?? newColumnId;+ }+ break;+ }++ const selectionStart =+ currentState.selectionState.selectionRange?.start || currentState.focusedCell;++ selectRange(selectionStart, {+ rowIndex: newRowIndex,+ columnId: newColumnId+ });++ const container = dataGridRef.current;+ const targetRow = rowMapRef.current.get(newRowIndex);+ const cellKey = getCellKey(newRowIndex, newColumnId);+ const targetCell = cellMapRef.current.get(cellKey);++ if (+ newRowIndex !== selectionEdge.rowIndex &&+ (direction === "up" || direction === "down")+ ) {+ if (container && targetRow) {+ const containerRect = container.getBoundingClientRect();+ const headerHeight = headerRef.current?.getBoundingClientRect().height ?? 0;+ const footerHeight = footerRef.current?.getBoundingClientRect().height ?? 0;++ const viewportTop = containerRect.top + headerHeight + VIEWPORT_OFFSET;+ const viewportBottom = containerRect.bottom - footerHeight - VIEWPORT_OFFSET;++ const rowRect = targetRow.getBoundingClientRect();+ const isFullyVisible = rowRect.top >= viewportTop && rowRect.bottom <= viewportBottom;++ if (!isFullyVisible) {+ const scrollNeeded =+ direction === "down"+ ? rowRect.bottom - viewportBottom+ : viewportTop - rowRect.top;++ if (direction === "down") {+ container.scrollTop += scrollNeeded;+ } else {+ container.scrollTop -= scrollNeeded;+ }++ restoreFocus(container);+ }+ } else {+ const rowVirtualizer = rowVirtualizerRef.current;+ if (rowVirtualizer) {+ const align = direction === "up" ? "start" : "end";+ rowVirtualizer.scrollToIndex(newRowIndex, { align });++ restoreFocus(container);+ }+ }+ }++ if (+ newColumnId !== selectionEdge.columnId &&+ (direction === "left" ||+ direction === "right" ||+ direction === "home" ||+ direction === "end")+ ) {+ if (container && targetCell) {+ scrollCellIntoView({+ container,+ targetCell,+ tableRef,+ viewportOffset: VIEWPORT_OFFSET,+ direction,+ isRtl+ });+ }+ }+ } else {+ if (currentState.selectionState.selectedCells.size > 0) {+ onSelectionClear();+ }+ navigateCell(direction);+ }+ }+ },+ [+ dir,+ store,+ propsRef,+ blurCell,+ navigateCell,+ selectAll,+ onCellsCopy,+ onCellsCut,+ onCellsPaste,+ onDataUpdate,+ onSelectionClear,+ navigableColumnIds,+ selectRange,+ onSearchOpenChange,+ onNavigateToNextMatch,+ onNavigateToPrevMatch,+ onRowsDelete,+ restoreFocus,+ onScrollToRow+ ]+ );++ const searchState = React.useMemo<SearchState | undefined>(() => {+ if (!propsRef.current.enableSearch) return undefined;++ return {+ searchMatches,+ matchIndex,+ searchOpen,+ onSearchOpenChange,+ searchQuery,+ onSearchQueryChange,+ onSearch,+ onNavigateToNextMatch,+ onNavigateToPrevMatch+ };+ }, [+ propsRef,+ searchMatches,+ matchIndex,+ searchOpen,+ onSearchOpenChange,+ searchQuery,+ onSearchQueryChange,+ onSearch,+ onNavigateToNextMatch,+ onNavigateToPrevMatch+ ]);++ React.useEffect(() => {+ const dataGridElement = dataGridRef.current;+ if (!dataGridElement) return;++ dataGridElement.addEventListener("keydown", onDataGridKeyDown);+ return () => {+ dataGridElement.removeEventListener("keydown", onDataGridKeyDown);+ };+ }, [onDataGridKeyDown]);++ React.useEffect(() => {+ function onGlobalKeyDown(event: KeyboardEvent) {+ const dataGridElement = dataGridRef.current;+ if (!dataGridElement) return;++ const { target } = event;+ if (!(target instanceof HTMLElement)) return;++ const { key, ctrlKey, metaKey, shiftKey } = event;+ const isCommandPressed = ctrlKey || metaKey;++ if (+ propsRef.current.enableSearch &&+ isCommandPressed &&+ !shiftKey &&+ key === SEARCH_SHORTCUT_KEY+ ) {+ const isInInput = target.tagName === "INPUT" || target.tagName === "TEXTAREA";+ const isInDataGrid = dataGridElement.contains(target);+ const isInSearchInput = target.closest('[role="search"]') !== null;++ if (isInDataGrid || isInSearchInput || !isInInput) {+ event.preventDefault();+ event.stopPropagation();++ const nextSearchOpen = !store.getState().searchOpen;+ onSearchOpenChange(nextSearchOpen);++ if (nextSearchOpen && !isInDataGrid && !isInSearchInput) {+ requestAnimationFrame(() => {+ dataGridElement.focus();+ });+ }+ return;+ }+ }++ const isInDataGrid = dataGridElement.contains(target);+ if (!isInDataGrid) return;++ if (key === "Escape") {+ const currentState = store.getState();+ const hasSelections =+ currentState.selectionState.selectedCells.size > 0 ||+ Object.keys(currentState.rowSelection).length > 0;++ if (hasSelections) {+ event.preventDefault();+ event.stopPropagation();+ onSelectionClear();+ }+ }+ }++ window.addEventListener("keydown", onGlobalKeyDown, true);+ return () => {+ window.removeEventListener("keydown", onGlobalKeyDown, true);+ };+ }, [propsRef, onSearchOpenChange, store, onSelectionClear]);++ React.useEffect(() => {+ const currentState = store.getState();+ const { autoFocus } = propsRef.current;++ if (autoFocus && data.length > 0 && columns.length > 0 && !currentState.focusedCell) {+ if (navigableColumnIds.length > 0) {+ const rafId = requestAnimationFrame(() => {+ if (typeof autoFocus === "object") {+ const { rowIndex, columnId } = autoFocus;+ if (columnId) {+ focusCell(rowIndex ?? 0, columnId);+ }+ return;+ }++ const firstColumnId = navigableColumnIds[0];+ if (firstColumnId) {+ focusCell(0, firstColumnId);+ }+ });+ return () => cancelAnimationFrame(rafId);+ }+ }+ }, [store, propsRef, data, columns, navigableColumnIds, focusCell]);++ // Restore focus to container when virtualized cells are unmounted+ React.useEffect(() => {+ const container = dataGridRef.current;+ if (!container) return;++ function onFocusOut(event: FocusEvent) {+ if (focusGuardRef.current) return;++ const currentContainer = dataGridRef.current;+ if (!currentContainer) return;++ const currentState = store.getState();++ if (!currentState.focusedCell || currentState.editingCell) return;++ const { relatedTarget } = event;++ const isFocusMovingOutsideGrid =+ !relatedTarget || !currentContainer.contains(relatedTarget as Node);++ const isFocusMovingToPopover = getIsInPopover(relatedTarget);++ if (isFocusMovingOutsideGrid && !isFocusMovingToPopover) {+ const { rowIndex, columnId } = currentState.focusedCell;+ const cellKey = getCellKey(rowIndex, columnId);+ const cellElement = cellMapRef.current.get(cellKey);++ requestAnimationFrame(() => {+ if (focusGuardRef.current) return;++ if (cellElement && document.body.contains(cellElement)) {+ cellElement.focus();+ } else {+ currentContainer.focus();+ }+ });+ }+ }++ container.addEventListener("focusout", onFocusOut);++ return () => {+ container.removeEventListener("focusout", onFocusOut);+ };+ }, [store]);++ React.useEffect(() => {+ function onOutsideClick(event: MouseEvent) {+ if (event.button === 2) {+ return;+ }++ if (dataGridRef.current && !dataGridRef.current.contains(event.target as Node)) {+ const elements = document.elementsFromPoint(event.clientX, event.clientY);++ // Compensate for event.target bubbling up+ const isInsidePopover = elements.some((element) => getIsInPopover(element));++ if (!isInsidePopover) {+ blurCell();+ const currentState = store.getState();+ if (+ currentState.selectionState.selectedCells.size > 0 ||+ Object.keys(currentState.rowSelection).length > 0+ ) {+ onSelectionClear();+ }+ }+ }+ }++ document.addEventListener("mousedown", onOutsideClick);+ return () => {+ document.removeEventListener("mousedown", onOutsideClick);+ };+ }, [store, blurCell, onSelectionClear]);++ React.useEffect(() => {+ function onSelectStart(event: Event) {+ event.preventDefault();+ }++ function onContextMenu(event: Event) {+ event.preventDefault();+ }++ function onCleanup() {+ document.removeEventListener("selectstart", onSelectStart);+ document.removeEventListener("contextmenu", onContextMenu);+ document.body.style.userSelect = "";+ }++ const onUnsubscribe = store.subscribe(() => {+ const currentState = store.getState();+ if (currentState.selectionState.isSelecting) {+ document.addEventListener("selectstart", onSelectStart);+ document.addEventListener("contextmenu", onContextMenu);+ document.body.style.userSelect = "none";+ } else {+ onCleanup();+ }+ });++ return () => {+ onCleanup();+ onUnsubscribe();+ };+ }, [store]);++ useIsomorphicLayoutEffect(() => {+ const rafId = requestAnimationFrame(() => {+ rowVirtualizer.measure();+ });+ return () => cancelAnimationFrame(rafId);+ }, [+ rowHeight,+ table.getState().columnFilters,+ table.getState().columnOrder,+ table.getState().columnPinning,+ table.getState().columnSizing,+ table.getState().columnVisibility,+ table.getState().expanded,+ table.getState().globalFilter,+ table.getState().grouping,+ table.getState().rowSelection,+ table.getState().sorting+ ]);++ // Calculate virtual values outside of child render to avoid flushSync issues+ const virtualTotalSize = rowVirtualizer.getTotalSize();+ const virtualItems = rowVirtualizer.getVirtualItems();+ const { measureElement } = rowVirtualizer;++ return React.useMemo(+ () => ({+ dataGridRef,+ headerRef,+ rowMapRef,+ footerRef,+ dir,+ table,+ tableMeta,+ virtualTotalSize,+ virtualItems,+ measureElement,+ columns,+ columnSizeVars,+ searchState,+ searchMatchesByRow,+ activeSearchMatch,+ cellSelectionMap,+ focusedCell,+ editingCell,+ rowHeight,+ contextMenu,+ pasteDialog,+ onRowAdd: propsRef.current.onRowAdd ? onRowAdd : undefined,+ adjustLayout+ }),+ [+ propsRef,+ dir,+ table,+ tableMeta,+ virtualTotalSize,+ virtualItems,+ measureElement,+ columns,+ columnSizeVars,+ searchState,+ searchMatchesByRow,+ activeSearchMatch,+ cellSelectionMap,+ focusedCell,+ editingCell,+ rowHeight,+ contextMenu,+ pasteDialog,+ onRowAdd,+ adjustLayout+ ]+ );+}++export {+ useDataGrid,+ //+ type UseDataGridProps+};diff --git a/frontend/src/components/v3/generic/index.ts b/frontend/src/components/v3/generic/index.tsindex 985cfd0b04..a9885b76e6 100644--- a/frontend/src/components/v3/generic/index.ts+++ b/frontend/src/components/v3/generic/index.ts@@ -9,6 +9,7 @@ export * from "./Calendar";export * from "./Card";export * from "./Checkbox";export * from "./Command";+export * from "./DataGrid";export * from "./Detail";export * from "./Dialog";export * from "./Dropdown";diff --git a/frontend/src/const/routes.ts b/frontend/src/const/routes.tsindex 8adf441905..51d9f8d816 100644--- a/frontend/src/const/routes.ts+++ b/frontend/src/const/routes.ts@@ -390,6 +390,10 @@ export const ROUTE_PATHS = Object.freeze({"/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access","/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access"),+ PamDataExplorerPage: setRoute(+ "/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer",+ "/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer"+ ),DiscoveryPage: setRoute("/organizations/$orgId/projects/pam/$projectId/discovery","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/"diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsxindex d89a499d5e..14ef7a4a83 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx@@ -1,6 +1,6 @@import { useMemo, useState } from "react";import { faCopy } from "@fortawesome/free-regular-svg-icons";-import { faTerminal, faUpRightFromSquare } from "@fortawesome/free-solid-svg-icons";+import { faTable, faTerminal, faUpRightFromSquare } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { Link } from "@tanstack/react-router";import ms from "ms";@@ -93,6 +93,8 @@ export const PamAccessAccountModal = ({ isOpen, onOpenChange, account, projectIdaccount.resource.resourceType === PamResourceType.SSH ||account.resource.resourceType === PamResourceType.Redis;+ const showDataExplorer = account.resource.resourceType === PamResourceType.Postgres;+return (<Modal isOpen={isOpen} onOpenChange={onOpenChange}><ModalContent@@ -152,27 +154,46 @@ export const PamAccessAccountModal = ({ isOpen, onOpenChange, account, projectId<div className="w-full border-t border-mineshaft-600" /></div><div className="relative flex justify-center text-xs">- <span className="bg-mineshaft-900 px-2 text-mineshaft-400">OR</span>+ <span className="bg-mineshaft-800 px-2 text-mineshaft-400">OR</span></div></div><div className="py-1"><p className="text-sm font-medium text-mineshaft-400">Browser</p><p className="mb-2 text-xs text-mineshaft-400">Connect directly from your browser</p>- <Link- to={ROUTE_PATHS.Pam.PamAccountAccessPage.path}- params={{- orgId: currentOrg.id,- projectId,- resourceType: account.resource.resourceType,- resourceId: account.resource.id,- accountId: account.id- }}- target="_blank"- className="flex w-full items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-black transition-colors hover:bg-primary/80"- >- <FontAwesomeIcon icon={faTerminal} />- Connect in Browser- </Link>+ <div className="flex gap-2">+ {showDataExplorer && (+ <Link+ to={ROUTE_PATHS.Pam.PamDataExplorerPage.path}+ params={{+ orgId: currentOrg.id,+ projectId,+ resourceType: account.resource.resourceType,+ resourceId: account.resource.id,+ accountId: account.id+ }}+ target="_blank"+ className="flex w-full items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-black transition-colors hover:bg-primary/80"+ >+ <FontAwesomeIcon icon={faTable} />+ Open Data Explorer+ </Link>+ )}+ <Link+ to={ROUTE_PATHS.Pam.PamAccountAccessPage.path}+ params={{+ orgId: currentOrg.id,+ projectId,+ resourceType: account.resource.resourceType,+ resourceId: account.resource.id,+ accountId: account.id+ }}+ target="_blank"+ className={`flex w-full items-center justify-center gap-2 rounded-md px-4 py-2 text-sm font-medium transition-colors ${showDataExplorer ? "border border-primary/30 bg-primary/10 text-primary hover:bg-primary/20" : "bg-primary text-black hover:bg-primary/80"}`}+ >+ <FontAwesomeIcon icon={faTerminal} />+ {showDataExplorer ? "Open Console" : "Connect in Browser"}+ </Link>+ </div></div></>)}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsxnew file mode 100644index 0000000000..682c2e420e--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx@@ -0,0 +1,458 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { useParams } from "@tanstack/react-router";+import { AlertTriangleIcon, DatabaseIcon, ShieldCheckIcon, UnplugIcon } from "lucide-react";++import { Spinner } from "@app/components/v2";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle+} from "@app/components/v3/generic/AlertDialog";+import { Button } from "@app/components/v3/generic/Button";+import { useGetPamAccountById } from "@app/hooks/api/pam";++import { DataExplorerGrid } from "./components/DataExplorerGrid";+import { DataExplorerSidebar } from "./components/DataExplorerSidebar";+import type { SchemaInfo, TableDetail, TableInfo } from "./data-explorer-types";+import { useDataExplorerSession } from "./use-data-explorer-session";++export const PamDataExplorerPage = () => {+ const { accountId, projectId, orgId } = useParams({+ strict: false+ }) as {+ accountId: string;+ projectId: string;+ orgId: string;+ };++ const { data: account } = useGetPamAccountById(accountId);++ const [schemas, setSchemas] = useState<SchemaInfo[]>([]);+ const [selectedSchema, setSelectedSchema] = useState("public");+ const [tables, setTables] = useState<TableInfo[]>([]);+ const [selectedTable, setSelectedTable] = useState<string | null>(null);+ const [tableDetail, setTableDetail] = useState<TableDetail | null>(null);+ const [isLoadingSchemas, setIsLoadingSchemas] = useState(false);+ const [isLoadingTables, setIsLoadingTables] = useState(false);+ const [isLoadingDetail, setIsLoadingDetail] = useState(false);+ const [hasDisconnected, setHasDisconnected] = useState(false);+ const [disconnectReason, setDisconnectReason] = useState<string | null>(null);+ const unsavedChangeCountRef = useRef(0);+ const [pendingTableSwitch, setPendingTableSwitch] = useState<string | null>(null);+ const latestSchemaRequestRef = useRef(0);+ const latestDetailRequestRef = useRef(0);++ const [approvalJustification, setApprovalJustification] = useState("");++ const {+ isConnected,+ isConnecting,+ errorMessage,+ mfaState,+ approvalState,+ connect,+ disconnect,+ reconnect,+ handleMfaVerification,+ submitApprovalRequest,+ approvalRequestUrl,+ fetchSchemas,+ fetchTables,+ fetchTableDetail,+ executeQuery+ } = useDataExplorerSession({+ accountId,+ projectId,+ orgId,+ resourceName: account?.resource?.name ?? "",+ accountName: account?.name ?? "",+ onSessionEnd: (reason?: string) => {+ unsavedChangeCountRef.current = 0;+ setHasDisconnected(true);+ setDisconnectReason(reason ?? null);+ }+ });++ // Drive connection from the page, not the hook.+ // Use a ref callback as the gate (same approach as useWebAccessSession's containerEl).+ // The ref callback fires once after the real DOM mount — StrictMode's simulated+ // unmount/remount does NOT re-fire ref callbacks, so we get exactly one connect.+ const connectedOnceRef = useRef(false);+ const mountRef = useCallback(+ (node: HTMLDivElement | null) => {+ if (node && !connectedOnceRef.current) {+ connectedOnceRef.current = true;+ connect();+ }+ },+ [connect]+ );++ // Cleanup on real unmount+ useEffect(() => {+ return () => {+ disconnect();+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ // Load schemas when connected+ const loadSchemas = useCallback(async () => {+ setIsLoadingSchemas(true);+ try {+ const result = await fetchSchemas();+ setSchemas(result);+ // Determine the active schema+ const hasPublic = result.find((s) => s.name === selectedSchema);+ const activeSchema = hasPublic ? selectedSchema : (result[0]?.name ?? "public");+ if (!hasPublic && result.length > 0) {+ setSelectedSchema(activeSchema);+ }+ // Auto-load tables for the active schema+ if (result.length > 0) {+ setIsLoadingTables(true);+ try {+ const tableResult = await fetchTables(activeSchema);+ setTables(tableResult);+ } catch {+ // Error handled by the hook+ } finally {+ setIsLoadingTables(false);+ }+ }+ } catch {+ // Error handled by the hook+ } finally {+ setIsLoadingSchemas(false);+ }+ }, [fetchSchemas, fetchTables, selectedSchema]);++ const loadTables = useCallback(+ async (schema: string) => {+ // Guard against stale responses when the user switches schemas quickly.+ // Only apply results if this is still the latest request.+ latestSchemaRequestRef.current += 1;+ const requestId = latestSchemaRequestRef.current;+ setIsLoadingTables(true);+ try {+ const result = await fetchTables(schema);+ if (latestSchemaRequestRef.current !== requestId) return;+ setTables(result);+ } catch {+ // Error handled by the hook+ } finally {+ if (latestSchemaRequestRef.current === requestId) {+ setIsLoadingTables(false);+ }+ }+ },+ [fetchTables]+ );++ const loadTableDetail = useCallback(+ async (schema: string, tableName: string) => {+ latestDetailRequestRef.current += 1;+ const requestId = latestDetailRequestRef.current;+ setIsLoadingDetail(true);+ try {+ const result = await fetchTableDetail(schema, tableName);+ if (latestDetailRequestRef.current !== requestId) return;+ setTableDetail(result);+ } catch {+ // Error handled by the hook+ } finally {+ if (latestDetailRequestRef.current === requestId) {+ setIsLoadingDetail(false);+ }+ }+ },+ [fetchTableDetail]+ );++ // Auto-load schemas when we transition to connected+ const wasConnectedRef = useRef(false);+ useEffect(() => {+ if (isConnected && !wasConnectedRef.current) {+ wasConnectedRef.current = true;+ setHasDisconnected(false);+ loadSchemas();+ }+ if (!isConnected) {+ wasConnectedRef.current = false;+ }+ }, [isConnected, loadSchemas]);++ const handleSchemaChange = useCallback(+ (schema: string) => {+ setSelectedSchema(schema);+ // Clear immediately so the grid doesn't fire a stale query+ // against the new schema with the old table name.+ setSelectedTable(null);+ setTableDetail(null);+ loadTables(schema);+ },+ [loadTables]+ );++ const handleTableSelect = useCallback(+ (tableName: string) => {+ if (tableName === selectedTable) return;+ if (unsavedChangeCountRef.current > 0) {+ setPendingTableSwitch(tableName);+ return;+ }+ setSelectedTable(tableName);+ loadTableDetail(selectedSchema, tableName);+ },+ [selectedTable, selectedSchema, loadTableDetail]+ );++ const handleDiscardAndSwitch = useCallback(() => {+ if (!pendingTableSwitch) return;+ unsavedChangeCountRef.current = 0;+ setSelectedTable(pendingTableSwitch);+ loadTableDetail(selectedSchema, pendingTableSwitch);+ setPendingTableSwitch(null);+ }, [pendingTableSwitch, selectedSchema, loadTableDetail]);++ const handleChangeCountUpdate = useCallback((count: number) => {+ unsavedChangeCountRef.current = count;+ }, []);++ const handleFullRefresh = useCallback(async () => {+ // 1. Re-fetch tables for current schema (picks up new/dropped tables)+ setIsLoadingTables(true);+ try {+ const tableResult = await fetchTables(selectedSchema);+ setTables(tableResult);++ // 2. If selected table was dropped, deselect and stop+ if (selectedTable && !tableResult.find((t) => t.name === selectedTable)) {+ setSelectedTable(null);+ setTableDetail(null);+ return;+ }+ } catch {+ // Error handled by the hook+ } finally {+ setIsLoadingTables(false);+ }++ // 3. Re-fetch table detail for current table (picks up column/PK changes)+ if (selectedTable) {+ await loadTableDetail(selectedSchema, selectedTable);+ }+ }, [selectedSchema, selectedTable, fetchTables, loadTableDetail]);++ const handleReconnect = useCallback(() => {+ setHasDisconnected(false);+ setDisconnectReason(null);+ setSchemas([]);+ setTables([]);+ setSelectedTable(null);+ setTableDetail(null);+ reconnect();+ }, [reconnect]);++ // --- Overlay states (shown instead of the main layout) ---++ if (isConnecting && !isConnected) {+ return (+ <div className="flex h-screen w-screen flex-col items-center justify-center gap-4 bg-bunker-800">+ <Spinner className="h-8 w-8" />+ <p className="text-sm text-mineshaft-300">Connecting to database...</p>+ </div>+ );+ }++ if (mfaState?.required) {+ return (+ <div className="flex h-screen w-screen flex-col items-center justify-center gap-3 bg-bunker-800">+ <ShieldCheckIcon className="size-8 text-mineshaft-400" />+ <h2 className="text-sm font-medium text-mineshaft-100">MFA Verification Required</h2>+ <p className="max-w-sm text-center text-xs text-mineshaft-400">+ Multi-factor authentication is required to access this database account.+ </p>+ {mfaState.verifying ? (+ <div className="flex items-center gap-2 text-xs text-mineshaft-400">+ <Spinner className="h-4 w-4" />+ Waiting for verification...+ </div>+ ) : (+ <Button variant="outline" size="xs" onClick={handleMfaVerification}>+ Verify MFA+ </Button>+ )}+ </div>+ );+ }++ if (approvalState?.required) {+ return (+ <div className="flex h-screen w-screen flex-col items-center justify-center gap-3 bg-bunker-800">+ <AlertTriangleIcon className="size-8 text-mineshaft-400" />+ <h2 className="text-sm font-medium text-mineshaft-100">Approval Required</h2>+ <p className="max-w-sm text-center text-xs text-mineshaft-400">+ This account is protected by policy: {approvalState.policyName ?? "Unknown"}+ </p>+ {approvalState.submitted ? (+ <div className="flex flex-col items-center gap-2">+ <p className="text-xs text-mineshaft-300">Approval request created successfully.</p>+ {approvalRequestUrl && (+ <a+ href={approvalRequestUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="text-xs text-primary-500 underline hover:text-primary-400"+ >+ View approval request+ </a>+ )}+ <Button variant="outline" size="xs" onClick={handleReconnect}>+ Reconnect+ </Button>+ </div>+ ) : (+ <div className="flex w-full max-w-sm flex-col gap-2">+ <textarea+ className="w-full rounded border border-mineshaft-600 bg-bunker-700 px-3 py-2 text-xs text-mineshaft-200 placeholder:text-mineshaft-500 focus:border-mineshaft-400 focus:outline-none"+ placeholder="Justification (optional)"+ rows={2}+ value={approvalJustification}+ onChange={(e) => setApprovalJustification(e.target.value)}+ />+ {approvalState.errorMessage && (+ <p className="text-xs text-red-400">{approvalState.errorMessage}</p>+ )}+ <div className="flex justify-center gap-2">+ <Button+ variant="outline"+ size="xs"+ isPending={approvalState.creating}+ onClick={() => submitApprovalRequest(approvalJustification)}+ >+ Create Approval Request+ </Button>+ </div>+ </div>+ )}+ </div>+ );+ }++ if (errorMessage && !isConnected) {+ return (+ <div className="flex h-screen w-screen flex-col items-center justify-center gap-3 bg-bunker-800">+ <AlertTriangleIcon className="size-8 text-mineshaft-400" />+ <h2 className="text-sm font-medium text-mineshaft-100">Connection Error</h2>+ <p className="max-w-sm text-center text-xs text-mineshaft-400">{errorMessage}</p>+ <Button variant="outline" size="xs" onClick={handleReconnect}>+ Try Again+ </Button>+ </div>+ );+ }++ if (hasDisconnected && !isConnected && !isConnecting) {+ return (+ <div className="flex h-screen w-screen flex-col items-center justify-center gap-3 bg-bunker-800">+ <UnplugIcon className="size-8 text-mineshaft-400" />+ <h2 className="text-sm font-medium text-mineshaft-100">Disconnected</h2>+ <p className="text-xs text-mineshaft-400">+ {disconnectReason ?? "The database connection was closed."}+ </p>+ <Button variant="outline" size="xs" onClick={handleReconnect}>+ Reconnect+ </Button>+ </div>+ );+ }++ // --- Main layout ---++ return (+ <div ref={mountRef} className="flex h-screen w-screen flex-col bg-bunker-800">+ {/* Body */}+ <div className="flex flex-1 overflow-hidden">+ <DataExplorerSidebar+ schemas={schemas}+ selectedSchema={selectedSchema}+ onSchemaChange={handleSchemaChange}+ tables={tables}+ selectedTable={selectedTable}+ onTableSelect={handleTableSelect}+ isLoadingSchemas={isLoadingSchemas}+ isLoadingTables={isLoadingTables}+ />++ {selectedTable ? (+ <DataExplorerGrid+ key={`${selectedSchema}.${selectedTable}`}+ tableDetail={tableDetail}+ tableType={tables.find((t) => t.name === selectedTable)?.tableType}+ schema={selectedSchema}+ table={selectedTable}+ executeQuery={executeQuery}+ isLoading={isLoadingDetail}+ onChangeCountUpdate={handleChangeCountUpdate}+ onFullRefresh={handleFullRefresh}+ />+ ) : (+ <div className="flex flex-1 items-center justify-center">+ <div className="text-center">+ <DatabaseIcon className="mx-auto mb-3 size-12 text-mineshaft-600" />+ <p className="text-sm text-mineshaft-400">+ Select a table from the sidebar to browse data+ </p>+ </div>+ </div>+ )}+ </div>++ {/* Status bar */}+ <div className="flex items-center justify-between border-t border-mineshaft-600 bg-mineshaft-800 px-3 py-1.5 text-xs">+ <span className="text-mineshaft-400">+ {tables.length} table{tables.length !== 1 ? "s" : ""}+ </span>+ <div className="flex items-center gap-4">+ <span>+ <span className="text-mineshaft-400">Resource:</span>{" "}+ <span className="text-mineshaft-300">{account?.resource?.name ?? "Database"}</span>+ </span>+ <span className="text-mineshaft-500">|</span>+ <span>+ <span className="text-mineshaft-400">Account:</span>{" "}+ <span className="text-mineshaft-300">{account?.name ?? "Account"}</span>+ </span>+ </div>+ </div>++ <AlertDialog+ open={pendingTableSwitch !== null}+ onOpenChange={(open) => {+ if (!open) setPendingTableSwitch(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Unsaved changes</AlertDialogTitle>+ <AlertDialogDescription>+ Table contains unsaved changes. Do you want to discard them?+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction variant="danger" onClick={handleDiscardAndSwitch}>+ Discard changes+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsxnew file mode 100644index 0000000000..a6f9b8bfb5--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx@@ -0,0 +1,751 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import type { CellContext, ColumnDef, HeaderContext } from "@tanstack/react-table";+import { EyeIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import { ContentLoader } from "@app/components/v2";+import { UnstableAlert, UnstableAlertDescription } from "@app/components/v3/generic/Alert";+import { Checkbox } from "@app/components/v3/generic/Checkbox";+import type { CellOpts } from "@app/components/v3/generic/DataGrid";+import { DataGrid, useDataGrid } from "@app/components/v3/generic/DataGrid";+import { Skeleton } from "@app/components/v3/generic/Skeleton";++import type { ColumnInfo, FieldInfo, ForeignKeyInfo, TableDetail } from "../data-explorer-types";+import type { FilterCondition, SortCondition } from "../sql-generation";+import {+ buildCountQuery,+ buildDeleteQuery,+ buildInsertQuery,+ buildSelectQuery,+ buildUpdateQuery,+ wrapInTransaction+} from "../sql-generation";+import { DataExplorerToolbar } from "./DataExplorerToolbar";++type DataExplorerGridProps = {+ tableDetail: TableDetail | null;+ tableType?: string;+ schema: string;+ table: string;+ executeQuery: (sql: string) => Promise<{+ rows: Record<string, unknown>[];+ fields: FieldInfo[];+ rowCount: number | null;+ command: string;+ executionTimeMs: number;+ }>;+ isLoading: boolean;+ onChangeCountUpdate?: (count: number) => void;+ onFullRefresh?: () => Promise<void>;+};++const ROW_KEY_PREFIX = "__new_";++function cellValuesEqual(a: unknown, b: unknown): boolean {+ if (a === null && b === null) return true;+ if (a === null || b === null) return false;+ if (a === undefined && b === undefined) return true;+ if (a === undefined || b === undefined) return false;+ return String(a) === String(b);+}++function pgTypeToCellOpts(): CellOpts {+ return { variant: "short-text" };+}++function getColumnSize(col: ColumnInfo, hasIndicator: boolean): number {+ // Extra width for PK/FK icon + badge + type label in header+ const indicatorExtra = hasIndicator ? 40 : 0;+ const t = col.type.toLowerCase();+ if (t === "boolean" || t === "bool" || t === "smallint" || t === "int2")+ return 100 + indicatorExtra;+ if (t === "integer" || t === "int4" || t === "serial") return 120 + indicatorExtra;+ if (t === "uuid") return 280 + indicatorExtra;+ if (t === "json" || t === "jsonb") return 250 + indicatorExtra;+ if (t === "text" || t === "xml") return 220 + indicatorExtra;+ // Scale with column name length as a rough heuristic+ return Math.max(180, Math.min(350, col.name.length * 10 + 120)) + indicatorExtra;+}++type RowData = Record<string, unknown>;++type SelectionMeta = {+ onRowSelect?: (rowIndex: number, checked: boolean, shiftKey: boolean) => void;+};++function SelectHeader({ table: t }: HeaderContext<RowData, unknown>) {+ const isAllSelected = t.getIsAllRowsSelected();+ const isSomeSelected = t.getIsSomeRowsSelected();+ return (+ <Checkbox+ isChecked={isAllSelected || isSomeSelected}+ isIndeterminate={isSomeSelected && !isAllSelected}+ onCheckedChange={() => {+ t.toggleAllRowsSelected(!isAllSelected);+ }}+ />+ );+}++function SelectCell({ row, table: t }: CellContext<RowData, unknown>) {+ const meta = t.options.meta as SelectionMeta | undefined;+ const isSelected = row.getIsSelected();+ return (+ <Checkbox+ isChecked={isSelected}+ onCheckedChange={(checked) => {+ if (meta?.onRowSelect) {+ meta.onRowSelect(row.index, Boolean(checked), false);+ } else {+ row.toggleSelected(Boolean(checked));+ }+ }}+ />+ );+}++const SELECT_COLUMN: ColumnDef<RowData> = {+ id: "select",+ header: SelectHeader,+ cell: SelectCell,+ size: 40,+ minSize: 40,+ maxSize: 40,+ enableSorting: false,+ enableHiding: false,+ enablePinning: false,+ enableResizing: false+};++function getColumnIndicator(+ colName: string,+ primaryKeys: string[],+ fkMap: Map<string, ForeignKeyInfo>+): { type: "pk" | "fk"; tooltip?: string } | undefined {+ if (primaryKeys.includes(colName)) return { type: "pk" };+ const fk = fkMap.get(colName);+ if (fk) {+ const targetCol = fk.targetColumns[fk.columns.indexOf(colName)] ?? fk.targetColumns[0];+ return {+ type: "fk",+ tooltip: `\u2192 ${fk.targetSchema}.${fk.targetTable}(${targetCol})`+ };+ }+ return undefined;+}++function buildColumnDefs(+ cols: ColumnInfo[],+ primaryKeys: string[],+ foreignKeys: ForeignKeyInfo[]+): ColumnDef<Record<string, unknown>>[] {+ // Build a map from column name → FK info for O(1) lookup+ const fkMap = new Map<string, ForeignKeyInfo>();+ foreignKeys.forEach((fk) => {+ fk.columns.forEach((c) => {+ if (!fkMap.has(c)) fkMap.set(c, fk);+ });+ });++ return cols.map((col) => {+ const columnIndicator = getColumnIndicator(col.name, primaryKeys, fkMap);+ return {+ id: col.name,+ accessorKey: col.name,+ header: col.name,+ meta: {+ label: col.name,+ typeLabel: col.type,+ cell: pgTypeToCellOpts(),+ columnIndicator+ },+ size: getColumnSize(col, Boolean(columnIndicator)),+ minSize: 80,+ maxSize: 600,+ enableSorting: true,+ enablePinning: true,+ enableHiding: true+ };+ });+}++function getRowKey(row: Record<string, unknown>, primaryKeys: string[]): string {+ if (primaryKeys.length === 0) return "";+ const keyObj: Record<string, unknown> = {};+ primaryKeys.forEach((pk) => {+ keyObj[pk] = row[pk];+ });+ return JSON.stringify(keyObj);+}++function getPkMatch(row: Record<string, unknown>, primaryKeys: string[]): Record<string, unknown> {+ const match: Record<string, unknown> = {};+ primaryKeys.forEach((pk) => {+ match[pk] = row[pk];+ });+ return match;+}++export const DataExplorerGrid = ({+ tableDetail,+ tableType,+ schema,+ table,+ executeQuery,+ isLoading,+ onChangeCountUpdate,+ onFullRefresh+}: DataExplorerGridProps) => {+ const [originalData, setOriginalData] = useState<Record<string, unknown>[]>([]);+ const [currentData, setCurrentData] = useState<Record<string, unknown>[]>([]);+ const [totalCount, setTotalCount] = useState(0);+ const [offset, setOffset] = useState(0);+ const [pageSize, setPageSize] = useState(50);+ const [filters, setFilters] = useState<FilterCondition[]>([]);+ const [sorts, setSorts] = useState<SortCondition[]>([]);+ const [executionTimeMs, setExecutionTimeMs] = useState<number | null>(null);+ const [isSaving, setIsSaving] = useState(false);+ const [isDataLoading, setIsDataLoading] = useState(true);+ const [newRowTempIds, setNewRowTempIds] = useState<Set<string>>(new Set());+ const newRowCounterRef = useRef(0);+ const [hasLoaded, setHasLoaded] = useState(false);+ const isFetchingRef = useRef(false);++ const primaryKeys = tableDetail?.primaryKeys ?? [];+ const foreignKeys = tableDetail?.foreignKeys ?? [];+ const tableColumns = tableDetail?.columns ?? [];+ const hasPrimaryKey = primaryKeys.length > 0;+ const primaryKeysRef = useRef(primaryKeys);+ primaryKeysRef.current = primaryKeys;++ const [selectedRowCount, setSelectedRowCount] = useState(0);+ const gridRef = useRef<ReturnType<typeof useDataGrid<Record<string, unknown>>>["table"] | null>(+ null+ );+ const selectedRowsRef = useRef<Record<string, unknown>[]>([]);++ // Build TanStack Table column definitions from PG metadata+ const columnDefs = useMemo(+ () =>+ hasPrimaryKey+ ? [SELECT_COLUMN, ...buildColumnDefs(tableColumns, primaryKeys, foreignKeys)]+ : buildColumnDefs(tableColumns, primaryKeys, foreignKeys),+ [hasPrimaryKey, tableColumns, primaryKeys, foreignKeys]+ );++ const fetchData = useCallback(+ async (o: number, ps: number, f: FilterCondition[], s: SortCondition[]): Promise<number> => {+ if (!tableDetail) return 0;+ isFetchingRef.current = true;+ setIsDataLoading(true);+ try {+ const selectSql = buildSelectQuery({+ schema,+ table,+ filters: f,+ sorts: s,+ limit: ps,+ offset: o,+ primaryKeys+ });+ const countSql = buildCountQuery({ schema, table, filters: f });++ // These two queries don't share a database snapshot (the backend processes them+ // sequentially, not in a single transaction), so the count could be off by 1 if+ // another session modifies data between them. Acceptable for a data explorer.+ const [dataResult, countResult] = await Promise.all([+ executeQuery(selectSql),+ executeQuery(countSql)+ ]);++ const taggedRows = dataResult.rows.map((row: Record<string, unknown>) => ({+ ...row,+ originalPkKey: getRowKey(row, primaryKeys)+ }));+ setOriginalData(taggedRows);+ setCurrentData(taggedRows);+ setExecutionTimeMs(dataResult.executionTimeMs);+ setTotalCount(Number(countResult.rows[0]?.count ?? 0));+ setNewRowTempIds(new Set());+ setSelectedRowCount(0);+ selectedRowsRef.current = [];+ setHasLoaded(true);+ return dataResult.rows.length;+ } catch (err) {+ createNotification({+ title: "Failed to load data",+ text: err instanceof Error ? err.message : "Unknown error",+ type: "error"+ });+ return -1;+ } finally {+ isFetchingRef.current = false;+ setIsDataLoading(false);+ }+ },+ [tableDetail, schema, table, primaryKeys, executeQuery]+ );++ // Fetch data when filters/sorts/pagination change.+ // Table switches are handled by the parent via key={schema.table} which+ // remounts this component with fresh state — no manual reset needed.+ const prevFetchKeyRef = useRef("");+ const fetchKey = `${schema}.${table}.${offset}.${pageSize}.${JSON.stringify(filters)}.${JSON.stringify(sorts)}`;+ if (fetchKey !== prevFetchKeyRef.current && tableDetail && !isLoading) {+ prevFetchKeyRef.current = fetchKey;+ fetchData(offset, pageSize, filters, sorts);+ } else if (isDataLoading && hasLoaded && !isFetchingRef.current) {+ // Handlers eagerly set isDataLoading so the overlay appears immediately.+ // If the fetchKey didn't actually change (e.g. applying empty filters when+ // none were active), no fetch runs — reset loading to avoid getting stuck.+ setIsDataLoading(false);+ }++ const pageSizeRef = useRef(pageSize);+ pageSizeRef.current = pageSize;+ const sortsRef = useRef(sorts);+ sortsRef.current = sorts;++ const handleFiltersChange = useCallback(+ async (newFilters: FilterCondition[]): Promise<boolean> => {+ setFilters(newFilters);+ setOffset(0);+ // Update prevFetchKeyRef so the render-time pattern doesn't double-fire+ prevFetchKeyRef.current = `${schema}.${table}.${0}.${pageSizeRef.current}.${JSON.stringify(newFilters)}.${JSON.stringify(sortsRef.current)}`;+ const result = await fetchData(0, pageSizeRef.current, newFilters, sortsRef.current);+ return result >= 0;+ },+ [schema, table, fetchData]+ );++ const handleSortsChange = useCallback((newSorts: SortCondition[]) => {+ setIsDataLoading(true);+ setSorts(newSorts);+ setOffset(0);+ }, []);++ const handleOffsetChange = useCallback((newOffset: number) => {+ setIsDataLoading(true);+ setOffset(Math.max(0, newOffset));+ }, []);++ const handlePageSizeChange = useCallback((newSize: number) => {+ setIsDataLoading(true);+ setPageSize(newSize);+ setOffset(0);+ }, []);++ // PK-based lookup map for O(1) original row matching (avoids index misalignment after prepend)+ const originalDataByPk = useMemo(() => {+ if (primaryKeys.length === 0) return null;+ const map = new Map<string, Record<string, unknown>>();+ originalData.forEach((row) => {+ map.set(getRowKey(row, primaryKeys), row);+ });+ return map;+ }, [originalData, primaryKeys]);++ const originalDataByPkRef = useRef(originalDataByPk);+ originalDataByPkRef.current = originalDataByPk;++ // Change tracking — use PK-based lookup so new row prepends don't misalign indices+ const changeCount = useMemo(() => {+ let count = newRowTempIds.size;+ if (!originalDataByPk) return count;+ currentData.forEach((row) => {+ if (row.tempRowId && newRowTempIds.has(String(row.tempRowId))) return;+ const key = row.originalPkKey as string;+ if (!key) return;+ const original = originalDataByPk.get(key);+ if (!original) return;+ const hasChanges = tableColumns.some(+ (col) => !cellValuesEqual(row[col.name], original[col.name])+ );+ if (hasChanges) count += 1;+ });+ return count;+ }, [currentData, originalDataByPk, primaryKeys, newRowTempIds, tableColumns]);++ useEffect(() => {+ onChangeCountUpdate?.(changeCount);+ }, [changeCount, onChangeCountUpdate]);++ const handleAddRecord = useCallback(() => {+ newRowCounterRef.current += 1;+ const tempId = `${ROW_KEY_PREFIX}${newRowCounterRef.current}`;+ const newRow: Record<string, unknown> = { tempRowId: tempId };+ tableColumns.forEach((col) => {+ newRow[col.name] = null;+ });+ setCurrentData((prev) => [newRow, ...prev]);+ setNewRowTempIds((prev) => new Set(prev).add(tempId));+ return null;+ }, [tableColumns]);++ const handleRowsDelete = useCallback(+ async (_rows: Record<string, unknown>[], rowIndices: number[]) => {+ const tempIdsToRemove: string[] = [];+ const deleteStatements: string[] = [];++ rowIndices.forEach((idx) => {+ const row = currentData[idx];+ if (!row) return;+ const tempId = row.tempRowId ? String(row.tempRowId) : null;+ if (tempId) {+ tempIdsToRemove.push(tempId);+ } else {+ deleteStatements.push(+ buildDeleteQuery({ schema, table, primaryKeyMatch: getPkMatch(row, primaryKeys) })+ );+ }+ });++ // Remove unsaved new rows from local state immediately+ if (tempIdsToRemove.length > 0) {+ const tempIdSet = new Set(tempIdsToRemove);+ setCurrentData((prev) =>+ prev.filter((r) => !r.tempRowId || !tempIdSet.has(String(r.tempRowId)))+ );+ setNewRowTempIds((prev) => {+ const next = new Set(prev);+ tempIdsToRemove.forEach((id) => next.delete(id));+ return next;+ });+ }++ // Execute DELETE SQL for persisted rows immediately+ if (deleteStatements.length > 0) {+ try {+ const sql = wrapInTransaction(deleteStatements);+ await executeQuery(sql);+ createNotification({+ text: `Deleted ${deleteStatements.length} row${deleteStatements.length !== 1 ? "s" : ""}`,+ type: "success"+ });+ const rowCount = await fetchData(offset, pageSize, filters, sorts);+ if (rowCount === 0 && offset > 0) {+ setOffset(Math.max(0, offset - pageSize));+ }+ } catch (err) {+ createNotification({+ title: "Delete failed",+ text: err instanceof Error ? err.message : "Unknown error",+ type: "error"+ });+ }+ }+ },+ [+ currentData,+ primaryKeys,+ schema,+ table,+ executeQuery,+ fetchData,+ offset,+ pageSize,+ filters,+ sorts+ ]+ );++ const handleDiscard = useCallback(() => {+ setCurrentData(originalData);+ setNewRowTempIds(new Set());+ }, [originalData]);++ const handleSave = useCallback(async () => {+ setIsSaving(true);+ try {+ const statements: string[] = [];++ // Inserts (new rows)+ currentData.forEach((row) => {+ const tempId = row.tempRowId ? String(row.tempRowId) : null;+ if (!tempId || !newRowTempIds.has(tempId)) return;+ const values: Record<string, unknown> = {};+ tableColumns.forEach((col) => {+ if (+ row[col.name] !== null &&+ row[col.name] !== undefined &&+ String(row[col.name]) !== ""+ ) {+ values[col.name] = row[col.name];+ }+ });+ statements.push(buildInsertQuery({ schema, table, row: values }));+ });++ // Updates (changed rows) — use PK-based lookup so prepends don't misalign+ const pkMap = originalDataByPk;+ currentData.forEach((row) => {+ if (row.tempRowId) return;+ const key = row.originalPkKey as string;+ const original = key && pkMap ? pkMap.get(key) : undefined;+ if (!original) return;+ const changes: Record<string, unknown> = {};+ tableColumns.forEach((col) => {+ if (!cellValuesEqual(row[col.name], original[col.name])) {+ changes[col.name] = row[col.name];+ }+ });+ if (Object.keys(changes).length > 0) {+ statements.push(+ buildUpdateQuery({+ schema,+ table,+ changes,+ primaryKeyMatch: getPkMatch(original, primaryKeys)+ })+ );+ }+ });++ if (statements.length === 0) {+ createNotification({ text: "No changes to save", type: "info" });+ setIsSaving(false);+ return;+ }++ const sql = wrapInTransaction(statements);++ // The WebSocket maxPayload is 64 KB. Guard against sending a query+ // that would exceed the limit and silently kill the connection.+ const MAX_QUERY_SIZE = 50 * 1024;+ if (sql.length > MAX_QUERY_SIZE) {+ createNotification({+ title: "Save failed",+ text: "Changes are too large to save at once. Try saving fewer or smaller changes.",+ type: "error"+ });+ setIsSaving(false);+ return;+ }++ await executeQuery(sql);+ createNotification({+ text: `Saved ${statements.length} change${statements.length !== 1 ? "s" : ""}`,+ type: "success"+ });++ await fetchData(offset, pageSize, filters, sorts);+ } catch (err) {+ createNotification({+ title: "Save failed",+ text: err instanceof Error ? err.message : "Unknown error",+ type: "error"+ });+ } finally {+ setIsSaving(false);+ }+ }, [+ currentData,+ originalDataByPk,+ newRowTempIds,+ tableColumns,+ primaryKeys,+ schema,+ table,+ executeQuery,+ fetchData,+ offset,+ pageSize,+ filters,+ sorts+ ]);++ const handleDataChange = useCallback((newData: Record<string, unknown>[]) => {+ setCurrentData(newData);+ }, []);++ // Use refs so the callback identity is stable (survives tableMeta useMemo)+ // while always reading the latest data.+ const currentDataRef = useRef(currentData);+ currentDataRef.current = currentData;+ const newRowTempIdsRef = useRef(newRowTempIds);+ newRowTempIdsRef.current = newRowTempIds;++ const getIsCellDirty = useCallback((rowIndex: number, columnId: string) => {+ const row = currentDataRef.current[rowIndex];+ if (!row) return false;+ if (row.tempRowId && newRowTempIdsRef.current.has(String(row.tempRowId))) return true;+ const pkMap = originalDataByPkRef.current;+ if (!pkMap) return false;+ const key = row.originalPkKey as string;+ if (!key) return false;+ const original = pkMap.get(key);+ if (!original) return false;+ return !cellValuesEqual(row[columnId], original[columnId]);+ }, []);++ const getIsRowNew = useCallback((rowIndex: number) => {+ const row = currentDataRef.current[rowIndex];+ if (!row) return false;+ return Boolean(row.tempRowId && newRowTempIdsRef.current.has(String(row.tempRowId)));+ }, []);++ // Stable row identity for TanStack Table+ const getRowId = useCallback(+ (row: Record<string, unknown>, index: number) => {+ if (row.tempRowId) return String(row.tempRowId);+ if (row.originalPkKey) return row.originalPkKey as string;+ if (primaryKeys.length > 0) return getRowKey(row, primaryKeys);+ return String(index);+ },+ [primaryKeys]+ );++ // Dice UI DataGrid+ const gridProps = useDataGrid<Record<string, unknown>>({+ data: currentData,+ columns: columnDefs,+ onDataChange: handleDataChange,+ getRowId,+ readOnly: !hasPrimaryKey,+ rowHeight: "short",+ enableSearch: true,+ enablePaste: hasPrimaryKey,+ onRowsDelete: hasPrimaryKey ? handleRowsDelete : undefined,+ onRowSelectionChange: (rowSelection) => {+ const selectedIds = new Set(Object.keys(rowSelection).filter((k) => rowSelection[k]));+ setSelectedRowCount(selectedIds.size);+ if (selectedIds.size > 0) {+ selectedRowsRef.current = currentData.filter((_row, idx) =>+ selectedIds.has(getRowId(_row, idx))+ );+ } else {+ selectedRowsRef.current = [];+ }+ },+ meta: { getIsCellDirty, getIsRowNew } as Record<string, unknown>+ });+ gridRef.current = gridProps.table;++ const handleDeleteSelected = useCallback(async () => {+ // Use the snapshot captured at selection time — by the time this click handler+ // fires, the DataGrid's outside-click listener has already cleared rowSelection.+ const rows = selectedRowsRef.current;+ if (rows.length === 0) return;++ const tempIdsToRemove: string[] = [];+ const deleteStatements: string[] = [];++ rows.forEach((row) => {+ const tempId = row.tempRowId ? String(row.tempRowId) : null;+ if (tempId) {+ tempIdsToRemove.push(tempId);+ } else {+ deleteStatements.push(+ buildDeleteQuery({ schema, table, primaryKeyMatch: getPkMatch(row, primaryKeys) })+ );+ }+ });++ // Remove unsaved new rows from local state immediately+ if (tempIdsToRemove.length > 0) {+ const tempIdSet = new Set(tempIdsToRemove);+ setCurrentData((prev) =>+ prev.filter((r) => !r.tempRowId || !tempIdSet.has(String(r.tempRowId)))+ );+ setNewRowTempIds((prev) => {+ const next = new Set(prev);+ tempIdsToRemove.forEach((id) => next.delete(id));+ return next;+ });+ }++ // Execute DELETE SQL for persisted rows+ if (deleteStatements.length > 0) {+ try {+ const sql = wrapInTransaction(deleteStatements);+ await executeQuery(sql);+ createNotification({+ text: `Deleted ${deleteStatements.length} row${deleteStatements.length !== 1 ? "s" : ""}`,+ type: "success"+ });+ const rowCount = await fetchData(offset, pageSize, filters, sorts);+ if (rowCount === 0 && offset > 0) {+ setOffset(Math.max(0, offset - pageSize));+ }+ } catch (err) {+ createNotification({+ title: "Delete failed",+ text: err instanceof Error ? err.message : "Unknown error",+ type: "error"+ });+ }+ }++ gridRef.current?.resetRowSelection();+ selectedRowsRef.current = [];+ setSelectedRowCount(0);+ }, [schema, table, primaryKeys, executeQuery, fetchData, offset, pageSize, filters, sorts]);++ if (!tableDetail) {+ return (+ <div className="flex flex-1 items-center justify-center">+ <Skeleton className="h-64 w-96" />+ </div>+ );+ }++ return (+ <div className="flex flex-1 flex-col overflow-hidden">+ <DataExplorerToolbar+ columns={tableColumns}+ filters={filters}+ onFiltersChange={handleFiltersChange}+ sorts={sorts}+ onSortsChange={handleSortsChange}+ changeCount={changeCount}+ onSave={handleSave}+ onDiscard={handleDiscard}+ isSaving={isSaving}+ onAddRecord={handleAddRecord}+ selectedRowCount={selectedRowCount}+ onDeleteSelected={handleDeleteSelected}+ totalCount={totalCount}+ offset={offset}+ pageSize={pageSize}+ onOffsetChange={handleOffsetChange}+ onPageSizeChange={handlePageSizeChange}+ executionTimeMs={executionTimeMs}+ hasPrimaryKey={hasPrimaryKey}+ isDataLoading={isDataLoading}+ onRefresh={async () => {+ if (onFullRefresh) await onFullRefresh();+ await fetchData(offset, pageSize, filters, sorts);+ }}+ isRefreshing={isDataLoading && hasLoaded}+ />++ {!hasPrimaryKey && (+ <div className="shrink-0 px-3 py-3">+ <UnstableAlert variant="info" className="py-2">+ <EyeIcon />+ <UnstableAlertDescription>+ {tableType === "view" || tableType === "materialized_view"+ ? "This view is read-only."+ : "This table has no primary key. Browsing is read-only — editing requires a primary key."}+ </UnstableAlertDescription>+ </UnstableAlert>+ </div>+ )}++ {/* Dice UI DataGrid */}+ <div className="data-explorer-grid relative flex min-h-0 flex-1 flex-col overflow-hidden font-mono text-foreground [--color-gray-200:var(--color-border)] [&_[data-slot=grid-footer]]:hidden [&_[data-slot=grid-header]]:bg-container [&_[data-slot=grid]]:thin-scrollbar [&_[data-slot=grid]]:rounded-none [&_[data-slot=grid]]:border-0 [&_[data-slot=grid]]:bg-bunker-800">+ {isDataLoading && !hasLoaded && <ContentLoader className="h-full" />}+ <DataGrid+ {...gridProps}+ className={`min-h-0 flex-1 ${isDataLoading && !hasLoaded ? "hidden" : ""}`}+ stretchColumns+ />+ {isDataLoading && hasLoaded && (+ <div className="absolute inset-0 z-20 flex items-center justify-center bg-bunker-800/60">+ <ContentLoader className="h-auto" lottieClassName="h-24 w-24" />+ </div>+ )}+ </div>+ </div>+ );+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerRowEditor.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerRowEditor.tsxnew file mode 100644index 0000000000..88c2cfd169--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerRowEditor.tsx@@ -0,0 +1,143 @@+// NOTE: This component is not currently wired up but is kept for future use+// as a side-sheet row editor for the data explorer grid.+import { useEffect, useState } from "react";++import { Badge } from "@app/components/v3/generic/Badge";+import { Button } from "@app/components/v3/generic/Button";+import { UnstableInput } from "@app/components/v3/generic/Input";+import {+ Sheet,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle+} from "@app/components/v3/generic/Sheet";+import { TextArea } from "@app/components/v3/generic/TextArea";++import type { ColumnInfo } from "../data-explorer-types";++type DataExplorerRowEditorProps = {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ row: Record<string, unknown> | null;+ columns: ColumnInfo[];+ primaryKeys: string[];+ onApply: (updates: Record<string, unknown>) => void;+};++const JSON_TYPES = new Set(["json", "jsonb", "xml"]);++export const DataExplorerRowEditor = ({+ isOpen,+ onOpenChange,+ row,+ columns,+ primaryKeys,+ onApply+}: DataExplorerRowEditorProps) => {+ const [formValues, setFormValues] = useState<Record<string, string>>({});++ useEffect(() => {+ if (row) {+ const values: Record<string, string> = {};+ columns.forEach((col) => {+ const val = row[col.name];+ values[col.name] = val === null || val === undefined ? "" : String(val);+ });+ setFormValues(values);+ }+ }, [row, columns]);++ const handleApply = () => {+ const updates: Record<string, unknown> = {};+ columns.forEach((col) => {+ const newVal = formValues[col.name] ?? "";+ const oldVal = row?.[col.name];+ const oldStr = oldVal === null || oldVal === undefined ? "" : String(oldVal);+ if (newVal !== oldStr) {+ // If field is empty and column is nullable, set to null+ updates[col.name] = newVal === "" && col.nullable ? null : newVal;+ }+ });+ onApply(updates);+ onOpenChange(false);+ };++ const isPk = (colName: string) => primaryKeys.includes(colName);+ const isReadOnly = (col: ColumnInfo) => isPk(col.name) || col.identityGeneration === "ALWAYS";++ return (+ <Sheet open={isOpen} onOpenChange={onOpenChange}>+ <SheetContent className="overflow-y-auto sm:max-w-lg">+ <SheetHeader>+ <SheetTitle>Edit Row</SheetTitle>+ </SheetHeader>+ <div className="space-y-3 py-4">+ {columns.map((col) => {+ const readOnly = isReadOnly(col);+ const value = formValues[col.name] ?? "";+ const isNull = row?.[col.name] === null;+ const isJsonType = JSON_TYPES.has(col.type.replace("[]", ""));++ return (+ <div key={col.name}>+ <div className="mb-1 flex items-center gap-2">+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}+ <label+ htmlFor={`row-editor-${col.name}`}+ className="text-xs font-medium text-mineshaft-200"+ >+ {col.name}+ </label>+ <Badge variant="outline" className="text-[10px]">+ {col.type}+ </Badge>+ {isPk(col.name) && <Badge className="text-[10px]">PK</Badge>}+ {col.nullable && (+ <Badge variant="outline" className="text-[10px]">+ nullable+ </Badge>+ )}+ {isNull && (+ <Badge variant="outline" className="text-[10px] text-yellow-500">+ NULL+ </Badge>+ )}+ </div>+ {isJsonType ? (+ <TextArea+ value={value}+ onChange={(e) =>+ setFormValues((prev) => ({ ...prev, [col.name]: e.target.value }))+ }+ disabled={readOnly}+ className="font-mono text-xs"+ rows={4}+ />+ ) : (+ <UnstableInput+ value={value}+ onChange={(e) =>+ setFormValues((prev) => ({ ...prev, [col.name]: e.target.value }))+ }+ disabled={readOnly}+ className="text-xs"+ placeholder={isNull ? "NULL" : undefined}+ />+ )}+ </div>+ );+ })}+ </div>+ <SheetFooter className="gap-2">+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button variant="info" onClick={handleApply}>+ Apply+ </Button>+ </SheetFooter>+ </SheetContent>+ </Sheet>+ );+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerSidebar.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerSidebar.tsxnew file mode 100644index 0000000000..e557c8890d--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerSidebar.tsx@@ -0,0 +1,126 @@+import { useCallback, useEffect, useState } from "react";+import { DatabaseIcon, SearchIcon, TableIcon, ViewIcon } from "lucide-react";++import { UnstableInput } from "@app/components/v3/generic/Input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@app/components/v3/generic/Select/Select";+import { Skeleton } from "@app/components/v3/generic/Skeleton";+import { cn } from "@app/components/v3/utils";++import type { SchemaInfo, TableInfo } from "../data-explorer-types";++type DataExplorerSidebarProps = {+ schemas: SchemaInfo[];+ selectedSchema: string;+ onSchemaChange: (schema: string) => void;+ tables: TableInfo[];+ selectedTable: string | null;+ onTableSelect: (table: string) => void;+ isLoadingSchemas: boolean;+ isLoadingTables: boolean;+};++export const DataExplorerSidebar = ({+ schemas,+ selectedSchema,+ onSchemaChange,+ tables,+ selectedTable,+ onTableSelect,+ isLoadingSchemas,+ isLoadingTables+}: DataExplorerSidebarProps) => {+ const [search, setSearch] = useState("");++ // Reset search when schema changes+ useEffect(() => {+ setSearch("");+ }, [selectedSchema]);++ const filteredTables = tables.filter((t) => t.name.toLowerCase().includes(search.toLowerCase()));++ const getTableIcon = useCallback((tableType: string) => {+ if (tableType === "view" || tableType === "materialized_view") {+ return <ViewIcon className="size-3.5 shrink-0 text-accent" />;+ }+ return <TableIcon className="size-3.5 shrink-0 text-accent" />;+ }, []);++ return (+ <div className="flex h-full w-64 shrink-0 flex-col border-r border-border bg-container">+ {/* Schema selector + Search */}+ <div className="space-y-2 border-b border-border p-3">+ {isLoadingSchemas ? (+ <Skeleton className="h-8 w-full" />+ ) : (+ <Select value={selectedSchema} onValueChange={onSchemaChange}>+ <SelectTrigger className="h-9 w-full text-xs text-foreground">+ <span className="flex items-center gap-1.5">+ <DatabaseIcon className="size-3.5 text-accent" />+ <SelectValue />+ </span>+ </SelectTrigger>+ <SelectContent position="popper">+ {schemas.map((s) => (+ <SelectItem key={s.name} value={s.name}>+ {s.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ <div className="relative">+ <SearchIcon className="absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-accent" />+ <UnstableInput+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search tables..."+ className="pl-7 text-xs text-foreground"+ />+ </div>+ </div>++ {/* Table list */}+ <div className="thin-scrollbar flex-1 overflow-y-auto">+ {isLoadingTables && tables.length === 0 && (+ <div className="space-y-1 p-2">+ {Array.from({ length: 8 }).map((_, i) => (+ // eslint-disable-next-line react/no-array-index-key+ <Skeleton key={i} className="h-7 w-full" />+ ))}+ </div>+ )}+ {!isLoadingTables && filteredTables.length === 0 && (+ <div className="p-4 text-center text-xs text-accent">+ {search ? "No matching tables" : "No tables in this schema"}+ </div>+ )}+ {!isLoadingTables && filteredTables.length > 0 && (+ <div className="p-1">+ {filteredTables.map((t) => (+ <button+ key={t.name}+ type="button"+ onClick={() => onTableSelect(t.name)}+ className={cn(+ "flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-xs text-muted transition-colors hover:bg-container-hover",+ selectedTable === t.name && "bg-container-hover text-foreground"+ )}+ >+ {getTableIcon(t.tableType)}+ <span className="truncate" title={t.name}>+ {t.name}+ </span>+ </button>+ ))}+ </div>+ )}+ </div>+ </div>+ );+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerToolbar.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerToolbar.tsxnew file mode 100644index 0000000000..55e2f98b02--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerToolbar.tsx@@ -0,0 +1,296 @@+import { useState } from "react";+import {+ ChevronLeftIcon,+ ChevronRightIcon,+ ClockIcon,+ PlusIcon,+ RefreshCwIcon,+ SaveIcon,+ Trash2Icon,+ UndoIcon+} from "lucide-react";++import { Button } from "@app/components/v3/generic/Button";+import { Popover, PopoverContent, PopoverTrigger } from "@app/components/v3/generic/Popover";++import type { ColumnInfo } from "../data-explorer-types";+import type { FilterCondition, SortCondition } from "../sql-generation";+import { FilterPopover } from "./FilterPopover";+import { SortPopover } from "./SortPopover";++type DataExplorerToolbarProps = {+ columns: ColumnInfo[];+ filters: FilterCondition[];+ onFiltersChange: (filters: FilterCondition[]) => Promise<boolean>;+ sorts: SortCondition[];+ onSortsChange: (sorts: SortCondition[]) => void;+ changeCount: number;+ onSave: () => void;+ onDiscard: () => void;+ isSaving: boolean;+ onAddRecord: () => void;+ selectedRowCount: number;+ onDeleteSelected: () => void;+ totalCount: number;+ offset: number;+ pageSize: number;+ onOffsetChange: (offset: number) => void;+ onPageSizeChange: (size: number) => void;+ executionTimeMs: number | null;+ hasPrimaryKey: boolean;+ isDataLoading?: boolean;+ onRefresh: () => void;+ isRefreshing?: boolean;+};++export const DataExplorerToolbar = ({+ columns,+ filters,+ onFiltersChange,+ sorts,+ onSortsChange,+ changeCount,+ onSave,+ onDiscard,+ isSaving,+ onAddRecord,+ selectedRowCount,+ onDeleteSelected,+ totalCount,+ offset,+ pageSize,+ onOffsetChange,+ onPageSizeChange,+ executionTimeMs,+ hasPrimaryKey,+ isDataLoading = false,+ onRefresh,+ isRefreshing = false+}: DataExplorerToolbarProps) => {+ const rangeStart = totalCount === 0 ? 0 : offset + 1;+ const rangeEnd = Math.min(offset + pageSize, totalCount);++ return (+ <div+ role="toolbar"+ data-grid-popover=""+ className="flex items-center justify-between border-b border-border px-3 py-1.5"+ onMouseDown={(e) => e.stopPropagation()}+ >+ <div className="flex items-center gap-2">+ <FilterPopover columns={columns} filters={filters} onFiltersChange={onFiltersChange} />+ <SortPopover+ columns={columns}+ sorts={sorts}+ onSortsChange={onSortsChange}+ disabled={isDataLoading}+ />++ {hasPrimaryKey && (+ <>+ <div className="h-4 w-px bg-border" />+ <Button variant="outline" size="xs" onClick={onAddRecord} className="gap-1">+ <PlusIcon className="size-3" />+ Add record+ </Button>+ </>+ )}++ {selectedRowCount > 0 && hasPrimaryKey && (+ <Button variant="danger" size="xs" onClick={onDeleteSelected} className="gap-1">+ <Trash2Icon className="size-3" />+ Delete {selectedRowCount} record{selectedRowCount !== 1 ? "s" : ""}+ </Button>+ )}++ {changeCount > 0 && (+ <>+ <div className="h-4 w-px bg-border" />+ <Button+ variant="success"+ size="xs"+ onClick={onSave}+ isPending={isSaving}+ className="gap-1"+ >+ <SaveIcon className="size-3" />+ Save {changeCount} change{changeCount !== 1 ? "s" : ""}+ </Button>+ <Button variant="ghost" size="xs" onClick={onDiscard} className="gap-1 underline">+ <UndoIcon className="size-3" />+ Discard changes+ </Button>+ </>+ )}+ </div>++ <div className="flex items-center gap-2">+ {executionTimeMs !== null && (+ <span className="flex items-center gap-1 text-xs text-accent">+ <ClockIcon className="size-3" />+ {executionTimeMs}ms+ </span>+ )}++ {/* Pagination */}+ <Button+ variant="ghost"+ size="xs"+ disabled={offset <= 0}+ onClick={() => onOffsetChange(Math.max(0, offset - pageSize))}+ className="size-7 p-0"+ >+ <ChevronLeftIcon className="size-3.5" />+ </Button>+ {/* eslint-disable-next-line @typescript-eslint/no-use-before-define */}+ <LimitOffsetPopover+ totalCount={totalCount}+ rangeStart={rangeStart}+ rangeEnd={rangeEnd}+ pageSize={pageSize}+ offset={offset}+ onPageSizeChange={onPageSizeChange}+ onOffsetChange={onOffsetChange}+ />+ <Button+ variant="ghost"+ size="xs"+ disabled={offset + pageSize >= totalCount}+ onClick={() => onOffsetChange(offset + pageSize)}+ className="size-7 p-0"+ >+ <ChevronRightIcon className="size-3.5" />+ </Button>++ {/* Refresh */}+ <Button+ variant="ghost"+ size="xs"+ onClick={onRefresh}+ disabled={isRefreshing}+ className="size-7 p-0"+ >+ <RefreshCwIcon className={`size-3.5 ${isRefreshing ? "animate-spin" : ""}`} />+ </Button>+ </div>+ </div>+ );+};++// --- Limit / Offset popover ---++type LimitOffsetPopoverProps = {+ totalCount: number;+ rangeStart: number;+ rangeEnd: number;+ pageSize: number;+ offset: number;+ onPageSizeChange: (size: number) => void;+ onOffsetChange: (offset: number) => void;+};++const LimitOffsetPopover = ({+ totalCount,+ rangeStart,+ rangeEnd,+ pageSize,+ offset,+ onPageSizeChange,+ onOffsetChange+}: LimitOffsetPopoverProps) => {+ const [open, setOpen] = useState(false);+ const [limitInput, setLimitInput] = useState(String(pageSize));+ const [offsetInput, setOffsetInput] = useState(String(offset));++ const handleOpen = (isOpen: boolean) => {+ if (isOpen) {+ setLimitInput(String(pageSize));+ setOffsetInput(String(offset));+ }+ setOpen(isOpen);+ };++ const limitNum = Number(limitInput);+ const getLimitError = (): string | null => {+ if (limitInput === "" || Number.isNaN(limitNum)) return "Must be a number";+ if (limitNum < 1) return "Minimum is 1";+ if (limitNum > 1000) return "Maximum is 1000";+ return null;+ };+ const limitError = getLimitError();++ const offsetNum = Number(offsetInput);+ const getOffsetError = (): string | null => {+ if (offsetInput === "" || Number.isNaN(offsetNum)) return "Must be a number";+ if (offsetNum < 0) return "Must be 0 or greater";+ return null;+ };+ const offsetError = getOffsetError();++ const applyChanges = () => {+ if (limitError || offsetError) return;+ const newLimit = Math.max(1, Math.min(1000, limitNum || 50));+ const newOffset = Math.max(0, offsetNum || 0);+ onPageSizeChange(newLimit);+ onOffsetChange(newOffset);+ setOpen(false);+ };++ return (+ <Popover open={open} onOpenChange={handleOpen}>+ <PopoverTrigger asChild>+ <Button variant="ghost" size="xs" className="text-muted">+ {rangeStart} - {rangeEnd} of {totalCount}+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-auto p-3" align="center">+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-3">+ <div className="flex flex-col items-center gap-1">+ <span className="text-[10px] font-medium text-accent">Limit</span>+ <input+ type="number"+ value={limitInput}+ onChange={(e) => setLimitInput(e.target.value)}+ onKeyDown={(e) => e.key === "Enter" && applyChanges()}+ className={`h-8 w-16 rounded border bg-transparent text-center text-sm text-mineshaft-200 outline-none ${+ limitError+ ? "border-red-500 focus:border-red-500"+ : "border-border focus:border-ring"+ }`}+ min={1}+ />+ </div>+ <div className="flex flex-col items-center gap-1">+ <span className="text-[10px] font-medium text-accent">Offset</span>+ <input+ type="number"+ value={offsetInput}+ onChange={(e) => setOffsetInput(e.target.value)}+ onKeyDown={(e) => e.key === "Enter" && applyChanges()}+ className={`h-8 w-16 rounded border bg-transparent text-center text-sm text-mineshaft-200 outline-none ${+ offsetError+ ? "border-red-500 focus:border-red-500"+ : "border-border focus:border-ring"+ }`}+ min={0}+ />+ </div>+ </div>+ {(limitError || offsetError) && (+ <p className="text-center text-[10px] text-red-400">{limitError || offsetError}</p>+ )}+ <Button+ variant="outline"+ size="xs"+ onClick={applyChanges}+ disabled={Boolean(limitError || offsetError)}+ className="w-full"+ >+ Apply+ </Button>+ </div>+ </PopoverContent>+ </Popover>+ );+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/FilterPopover.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/FilterPopover.tsxnew file mode 100644index 0000000000..4b83ce73f7--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/FilterPopover.tsx@@ -0,0 +1,264 @@+import { useEffect, useState } from "react";+import { CheckIcon, FilterIcon, PlusIcon, XIcon } from "lucide-react";++import { Button } from "@app/components/v3/generic/Button";+import { UnstableInput } from "@app/components/v3/generic/Input";+import { Popover, PopoverContent, PopoverTrigger } from "@app/components/v3/generic/Popover";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@app/components/v3/generic/Select";++import type { ColumnInfo } from "../data-explorer-types";+import type { FilterCondition, FilterOperator } from "../sql-generation";++function getFilterPlaceholder(columnType: string, operator: FilterOperator): string {+ switch (operator) {+ case "LIKE":+ return "%pattern%";+ case "ILIKE":+ return "%pattern% (case-insensitive)";+ case "IN":+ return "a, b, c";+ case "IS NULL":+ case "IS NOT NULL":+ return "";+ default:+ break;+ }++ const t = columnType.toLowerCase().replace("[]", "");+ switch (t) {+ case "int2":+ case "int4":+ case "int8":+ case "serial":+ case "bigserial":+ case "smallserial":+ case "integer":+ case "bigint":+ case "smallint":+ return "42";+ case "float4":+ case "float8":+ case "numeric":+ case "decimal":+ case "real":+ case "double precision":+ case "money":+ return "3.14";+ case "bool":+ case "boolean":+ return "true";+ case "uuid":+ return "550e8400-e29b-41d4-a716-...";+ case "date":+ return "2024-01-15";+ case "timestamp":+ case "timestamptz":+ return "2024-01-15 09:30:00";+ case "time":+ case "timetz":+ return "09:30:00";+ case "json":+ case "jsonb":+ return '{"key": "value"}';+ case "inet":+ case "cidr":+ return "192.168.1.0/24";+ case "text":+ case "varchar":+ case "char":+ case "bpchar":+ case "name":+ case "citext":+ return "some text";+ default:+ return "Value";+ }+}++const OPERATORS: { value: FilterOperator; label: string; needsValue: boolean }[] = [+ { value: "=", label: "equals", needsValue: true },+ { value: "<>", label: "not equals", needsValue: true },+ { value: ">", label: "greater than", needsValue: true },+ { value: "<", label: "less than", needsValue: true },+ { value: ">=", label: "greater or equal", needsValue: true },+ { value: "<=", label: "less or equal", needsValue: true },+ { value: "LIKE", label: "like", needsValue: true },+ { value: "ILIKE", label: "ilike", needsValue: true },+ { value: "IS NULL", label: "is null", needsValue: false },+ { value: "IS NOT NULL", label: "is not null", needsValue: false },+ { value: "IN", label: "in", needsValue: true }+];++type FilterPopoverProps = {+ columns: ColumnInfo[];+ filters: FilterCondition[];+ onFiltersChange: (filters: FilterCondition[]) => Promise<boolean>;+};++export const FilterPopover = ({ columns, filters, onFiltersChange }: FilterPopoverProps) => {+ const [open, setOpen] = useState(false);+ const [draft, setDraft] = useState<FilterCondition[]>(filters);+ const [isApplying, setIsApplying] = useState(false);++ // Sync draft when external filters change (e.g. cleared from outside)+ useEffect(() => {+ if (!open) {+ setDraft(filters);+ }+ }, [filters, open]);++ // Reset draft when popover opens; prevent close while applying+ const handleOpenChange = (isOpen: boolean) => {+ if (!isOpen && isApplying) return;+ if (isOpen) {+ setDraft(filters);+ }+ setOpen(isOpen);+ };++ const addFilter = () => {+ if (columns.length === 0) return;+ setDraft((prev) => [...prev, { column: columns[0].name, operator: "=", value: "" }]);+ };++ const removeFilter = (index: number) => {+ setDraft((prev) => prev.filter((_, i) => i !== index));+ };++ const updateFilter = (index: number, update: Partial<FilterCondition>) => {+ setDraft((prev) => prev.map((f, i) => (i === index ? { ...f, ...update } : f)));+ };++ const clearAll = async () => {+ setIsApplying(true);+ await onFiltersChange([]);+ setIsApplying(false);+ setOpen(false);+ };++ const applyFilters = async () => {+ setIsApplying(true);+ const success = await onFiltersChange(draft);+ setIsApplying(false);+ if (success) setOpen(false);+ };++ return (+ <Popover open={open} onOpenChange={handleOpenChange}>+ <PopoverTrigger asChild>+ <Button variant="outline" size="xs" className="gap-1.5">+ <FilterIcon className="size-3" />+ Filter+ {filters.length > 0 && (+ <span className="rounded-full bg-primary/20 px-1.5 text-[10px] font-medium text-primary">+ {filters.length}+ </span>+ )}+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-[580px] p-3" align="start">+ <div className="mb-2 flex items-center justify-between">+ <span className="text-sm font-medium text-mineshaft-200">Filters</span>+ {draft.length > 0 && (+ <Button variant="ghost" size="xs" onClick={clearAll} className="h-auto p-0 text-xs">+ Clear all+ </Button>+ )}+ </div>++ {draft.length === 0 ? (+ <p className="py-3 text-center text-xs text-mineshaft-400">No filters applied</p>+ ) : (+ <div className="space-y-2">+ {draft.map((filter, index) => {+ const opConfig = OPERATORS.find((o) => o.value === filter.operator);+ const colInfo = columns.find((c) => c.name === filter.column);+ return (+ // eslint-disable-next-line react/no-array-index-key+ <div key={index} className="flex items-center gap-1.5">+ <Select+ value={filter.column}+ onValueChange={(val) => updateFilter(index, { column: val })}+ >+ <SelectTrigger+ size="sm"+ className="w-40 text-xs text-mineshaft-200"+ title={filter.column}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {columns.map((col) => (+ <SelectItem key={col.name} value={col.name}>+ {col.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>++ <Select+ value={filter.operator}+ onValueChange={(val) =>+ updateFilter(index, { operator: val as FilterOperator })+ }+ >+ <SelectTrigger size="sm" className="w-28 text-xs text-mineshaft-200">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {OPERATORS.map((op) => (+ <SelectItem key={op.value} value={op.value}>+ {op.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>++ {opConfig?.needsValue !== false && (+ <UnstableInput+ value={filter.value}+ onChange={(e) => updateFilter(index, { value: e.target.value })}+ placeholder={getFilterPlaceholder(colInfo?.type ?? "", filter.operator)}+ className="h-7 flex-1 text-xs text-mineshaft-200"+ />+ )}++ <button+ type="button"+ onClick={() => removeFilter(index)}+ className="rounded p-1 text-mineshaft-400 hover:bg-mineshaft-700 hover:text-mineshaft-200"+ >+ <XIcon className="size-3" />+ </button>+ </div>+ );+ })}+ </div>+ )}++ <div className="mt-3 flex items-center justify-between">+ <Button variant="outline" size="xs" onClick={addFilter} className="gap-1">+ <PlusIcon className="size-3" />+ Add filter+ </Button>+ <Button+ variant="info"+ size="xs"+ onClick={applyFilters}+ isPending={isApplying}+ className="gap-1"+ >+ <CheckIcon className="size-3" />+ Apply+ </Button>+ </div>+ </PopoverContent>+ </Popover>+ );+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/SortPopover.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/SortPopover.tsxnew file mode 100644index 0000000000..aa912071e9--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/SortPopover.tsx@@ -0,0 +1,102 @@+import { ArrowUpDownIcon, CheckIcon } from "lucide-react";++import { Button } from "@app/components/v3/generic/Button";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList+} from "@app/components/v3/generic/Command";+import { Popover, PopoverContent, PopoverTrigger } from "@app/components/v3/generic/Popover";+import { cn } from "@app/components/v3/utils";++import type { ColumnInfo } from "../data-explorer-types";+import type { SortCondition } from "../sql-generation";++type SortPopoverProps = {+ columns: ColumnInfo[];+ sorts: SortCondition[];+ onSortsChange: (sorts: SortCondition[]) => void;+ disabled?: boolean;+};++export const SortPopover = ({+ columns,+ sorts,+ onSortsChange,+ disabled = false+}: SortPopoverProps) => {+ const activeSort = sorts[0] ?? null;+ const isAscending = activeSort?.direction !== "DESC";++ const handleColumnSelect = (colName: string) => {+ if (activeSort?.column === colName) {+ onSortsChange([]);+ } else {+ onSortsChange([{ column: colName, direction: isAscending ? "ASC" : "DESC" }]);+ }+ };++ const handleDirectionToggle = () => {+ if (!activeSort) return;+ onSortsChange([+ { column: activeSort.column, direction: activeSort.direction === "ASC" ? "DESC" : "ASC" }+ ]);+ };++ return (+ <Popover>+ <PopoverTrigger asChild>+ <Button variant="outline" size="xs" className="gap-1.5" disabled={disabled}>+ <ArrowUpDownIcon className="size-3" />+ Sort+ {activeSort && (+ <span className="rounded-full bg-primary/20 px-1.5 text-[10px] font-medium text-primary">+ {activeSort.column}+ </span>+ )}+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-[300px] p-0" align="start">+ <div className="flex items-center justify-between border-b border-border px-3 py-2">+ <span className="text-sm font-medium text-foreground">Sort by</span>+ <button+ type="button"+ onClick={handleDirectionToggle}+ disabled={!activeSort || disabled}+ className="flex items-center gap-1.5 rounded px-2 py-0.5 text-xs text-muted transition-colors hover:bg-foreground/5 disabled:opacity-40"+ >+ {isAscending ? "Ascending" : "Descending"}+ <ArrowUpDownIcon className="size-3" />+ </button>+ </div>+ <Command>+ <CommandInput placeholder="Search columns..." />+ <CommandList>+ <CommandEmpty>No matching columns</CommandEmpty>+ <CommandGroup>+ {columns.map((col) => (+ <CommandItem+ key={col.name}+ value={col.name}+ onSelect={() => handleColumnSelect(col.name)}+ disabled={disabled}+ >+ <CheckIcon+ className={cn(+ "size-3.5",+ activeSort?.column === col.name ? "opacity-100" : "opacity-0"+ )}+ />+ <span className="truncate">{col.name}</span>+ </CommandItem>+ ))}+ </CommandGroup>+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ );+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.ts b/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.tsnew file mode 100644index 0000000000..435da716ec--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.ts@@ -0,0 +1,59 @@+// WebSocket message types for the Postgres Data Explorer++export type DataExplorerClientMessage =+ | { type: "get-schemas"; id: string }+ | { type: "get-tables"; id: string; schema: string }+ | { type: "get-table-detail"; id: string; schema: string; table: string }+ | { type: "query"; id: string; sql: string };++export type DataExplorerServerMessage =+ | { type: "schemas"; id: string; data: SchemaInfo[] }+ | { type: "tables"; id: string; data: TableInfo[] }+ | { type: "table-detail"; id: string; data: TableDetail }+ | {+ type: "query-result";+ id: string;+ rows: Record<string, unknown>[];+ fields: FieldInfo[];+ rowCount: number | null;+ command: string;+ executionTimeMs: number;+ }+ | { type: "error"; id: string; error: string; detail?: string; hint?: string }+ // Lifecycle messages (reused from terminal)+ | { type: "ready"; data: string; prompt: string }+ | { type: "session_end"; reason: string };++export type SchemaInfo = {+ name: string;+};++export type TableInfo = {+ name: string;+ tableType: string;+};++export type ColumnInfo = {+ name: string;+ type: string;+ nullable: boolean;+ identityGeneration: string | null;+};++export type ForeignKeyInfo = {+ constraintName: string;+ columns: string[];+ targetSchema: string;+ targetTable: string;+ targetColumns: string[];+};++export type TableDetail = {+ columns: ColumnInfo[];+ primaryKeys: string[];+ foreignKeys: ForeignKeyInfo[];+};++export type FieldInfo = {+ name: string;+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/route.tsx b/frontend/src/pages/pam/PamDataExplorerPage/route.tsxnew file mode 100644index 0000000000..67dd85a439--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/route.tsx@@ -0,0 +1,9 @@+import { createFileRoute } from "@tanstack/react-router";++import { PamDataExplorerPage } from "./PamDataExplorerPage";++export const Route = createFileRoute(+ "/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer"+)({+ component: PamDataExplorerPage+});diff --git a/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts b/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.tsnew file mode 100644index 0000000000..8790880a93--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts@@ -0,0 +1,175 @@+// Client-side SQL generation for the Postgres Data Explorer.+// All identifiers are properly quoted to prevent SQL injection.++export function quoteIdent(name: string): string {+ return `"${name.replace(/"/g, '""')}"`;+}++export function quoteLiteral(value: unknown): string {+ if (value === null || value === undefined) return "NULL";+ if (typeof value === "number") {+ if (!Number.isFinite(value)) return "NULL";+ return String(value);+ }+ if (typeof value === "boolean") return value ? "TRUE" : "FALSE";+ const str = String(value);+ // Use dollar-quoting if the string contains single quotes and no dollar signs+ if (str.includes("'") && !str.includes("$")) {+ return `$$${str}$$`;+ }+ return `'${str.replace(/'/g, "''")}'`;+}++export type FilterCondition = {+ column: string;+ operator: FilterOperator;+ value: string;+};++export type FilterOperator =+ | "="+ | "<>"+ | ">"+ | "<"+ | ">="+ | "<="+ | "LIKE"+ | "ILIKE"+ | "IS NULL"+ | "IS NOT NULL"+ | "IN";++export type SortCondition = {+ column: string;+ direction: "ASC" | "DESC";+};++function buildWhereClause(filters: FilterCondition[]): string {+ if (filters.length === 0) return "";+ const conditions = filters.map((f) => {+ const col = quoteIdent(f.column);+ switch (f.operator) {+ case "IS NULL":+ return `${col} IS NULL`;+ case "IS NOT NULL":+ return `${col} IS NOT NULL`;+ case "IN": {+ const values = f.value+ .split(",")+ .map((v) => quoteLiteral(v.trim()))+ .join(", ");+ return `${col} IN (${values})`;+ }+ case "LIKE":+ case "ILIKE":+ return `${col} ${f.operator} ${quoteLiteral(f.value)}`;+ default:+ return `${col} ${f.operator} ${quoteLiteral(f.value)}`;+ }+ });+ return ` WHERE ${conditions.join(" AND ")}`;+}++function buildOrderByClause(sorts: SortCondition[]): string {+ if (sorts.length === 0) return "";+ const parts = sorts.map((s) => `${quoteIdent(s.column)} ${s.direction}`);+ return ` ORDER BY ${parts.join(", ")}`;+}++export function buildSelectQuery(params: {+ schema: string;+ table: string;+ filters: FilterCondition[];+ sorts: SortCondition[];+ limit: number;+ offset: number;+ primaryKeys?: string[];+}): string {+ const { schema, table, filters, sorts, limit, offset, primaryKeys } = params;+ const tableName = `${quoteIdent(schema)}.${quoteIdent(table)}`;+ const where = buildWhereClause(filters);++ // Default sort by PK for stable pagination+ let orderBy: string;+ if (sorts.length > 0) {+ orderBy = buildOrderByClause(sorts);+ } else if (primaryKeys && primaryKeys.length > 0) {+ orderBy = buildOrderByClause(+ primaryKeys.map((pk) => ({ column: pk, direction: "ASC" as const }))+ );+ } else {+ orderBy = "";+ }++ return `SELECT * FROM ${tableName}${where}${orderBy} LIMIT ${limit} OFFSET ${offset}`;+}++export function buildCountQuery(params: {+ schema: string;+ table: string;+ filters: FilterCondition[];+}): string {+ const { schema, table, filters } = params;+ const tableName = `${quoteIdent(schema)}.${quoteIdent(table)}`;+ const where = buildWhereClause(filters);+ return `SELECT COUNT(*) AS count FROM ${tableName}${where}`;+}++export function buildInsertQuery(params: {+ schema: string;+ table: string;+ row: Record<string, unknown>;+}): string {+ const { schema, table, row } = params;+ const tableName = `${quoteIdent(schema)}.${quoteIdent(table)}`;+ const entries = Object.entries(row).filter(([, v]) => v !== undefined && v !== "");+ if (entries.length === 0) {+ return `INSERT INTO ${tableName} DEFAULT VALUES RETURNING *`;+ }+ const columns = entries.map(([k]) => quoteIdent(k)).join(", ");+ const values = entries.map(([, v]) => quoteLiteral(v)).join(", ");+ return `INSERT INTO ${tableName} (${columns}) VALUES (${values}) RETURNING *`;+}++export function buildUpdateQuery(params: {+ schema: string;+ table: string;+ changes: Record<string, unknown>;+ primaryKeyMatch: Record<string, unknown>;+}): string {+ const { schema, table, changes, primaryKeyMatch } = params;+ if (Object.keys(primaryKeyMatch).length === 0) {+ throw new Error("UPDATE requires at least one primary key condition");+ }+ const tableName = `${quoteIdent(schema)}.${quoteIdent(table)}`;+ const setClauses = Object.entries(changes)+ .map(([col, val]) => `${quoteIdent(col)} = ${quoteLiteral(val)}`)+ .join(", ");+ const whereClauses = Object.entries(primaryKeyMatch)+ .map(([col, val]) => `${quoteIdent(col)} = ${quoteLiteral(val)}`)+ .join(" AND ");+ return `UPDATE ${tableName} SET ${setClauses} WHERE ${whereClauses} RETURNING *`;+}++export function buildDeleteQuery(params: {+ schema: string;+ table: string;+ primaryKeyMatch: Record<string, unknown>;+}): string {+ const { schema, table, primaryKeyMatch } = params;+ if (Object.keys(primaryKeyMatch).length === 0) {+ throw new Error("DELETE requires at least one primary key condition");+ }+ const tableName = `${quoteIdent(schema)}.${quoteIdent(table)}`;+ const whereClauses = Object.entries(primaryKeyMatch)+ .map(([col, val]) => `${quoteIdent(col)} = ${quoteLiteral(val)}`)+ .join(" AND ");+ return `DELETE FROM ${tableName} WHERE ${whereClauses}`;+}++// Note: RETURNING * in individual INSERT/UPDATE statements is harmless but unused when+// wrapped here — pgClient.query() returns only the last statement's result (COMMIT).+// The frontend re-fetches data after save anyway.+export function wrapInTransaction(statements: string[]): string {+ return `BEGIN;\n${statements.join(";\n")};\nCOMMIT;`;+}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts b/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.tsnew file mode 100644index 0000000000..5ec38ce200--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts@@ -0,0 +1,440 @@+import { useCallback, useEffect, useRef, useState } from "react";++import { apiRequest } from "@app/config/request";+import { MfaSessionStatus, TMfaSessionStatusResponse } from "@app/hooks/api/mfaSession/types";++import type {+ DataExplorerClientMessage,+ DataExplorerServerMessage,+ FieldInfo,+ SchemaInfo,+ TableDetail,+ TableInfo+} from "./data-explorer-types";++type PendingRequest = {+ resolve: (msg: DataExplorerServerMessage) => void;+ reject: (err: Error) => void;+ timer: ReturnType<typeof setTimeout>;+};++type MfaState = {+ required: boolean;+ sessionId?: string;+ method?: string;+ verifying: boolean;+};++type ApprovalState = {+ required: boolean;+ policyName?: string;+ policyId?: string;+ creating: boolean;+ submitted: boolean;+ approvalRequestId?: string;+ errorMessage?: string;+};++type UseDataExplorerSessionOptions = {+ accountId: string;+ projectId: string;+ orgId: string;+ resourceName: string;+ accountName: string;+ onSessionEnd?: (reason?: string) => void;+};++const REQUEST_TIMEOUT_MS = 30_000;++export const useDataExplorerSession = ({+ accountId,+ projectId,+ orgId,+ resourceName,+ accountName,+ onSessionEnd+}: UseDataExplorerSessionOptions) => {+ const [isConnected, setIsConnected] = useState(false);+ const [isConnecting, setIsConnecting] = useState(false);+ const [errorMessage, setErrorMessage] = useState<string | null>(null);+ const [mfaState, setMfaState] = useState<MfaState | null>(null);+ const [approvalState, setApprovalState] = useState<ApprovalState | null>(null);++ const wsRef = useRef<WebSocket | null>(null);+ const pendingRequestsRef = useRef<Map<string, PendingRequest>>(new Map());+ const readyResolveRef = useRef<(() => void) | null>(null);+ const readyRejectRef = useRef<((err: Error) => void) | null>(null);+ const readyPromiseRef = useRef<Promise<void> | null>(null);+ const onSessionEndRef = useRef(onSessionEnd);++ useEffect(() => {+ onSessionEndRef.current = onSessionEnd;+ }, [onSessionEnd]);++ const rejectAllPending = useCallback((reason: string) => {+ const pending = pendingRequestsRef.current;+ pending.forEach(({ reject: rej, timer }) => {+ clearTimeout(timer);+ rej(new Error(reason));+ });+ pending.clear();+ }, []);++ // --- WebSocket lifecycle (imperative, mirrors useWebAccessSession) ---++ const openWebSocket = useCallback(+ (ticket: string) => {+ const { protocol, host } = window.location;+ const wsProtocol = protocol === "https:" ? "wss:" : "ws:";+ const wsUrl = `${wsProtocol}//${host}/api/v1/pam/accounts/${accountId}/web-access?ticket=${encodeURIComponent(ticket)}`;+ const ws = new WebSocket(wsUrl);+ wsRef.current = ws;++ ws.onmessage = (event) => {+ let serverMsg: DataExplorerServerMessage;+ try {+ serverMsg = JSON.parse(event.data as string) as DataExplorerServerMessage;+ } catch {+ return;+ }++ if (serverMsg.type === "ready") {+ setIsConnected(true);+ setIsConnecting(false);+ readyResolveRef.current?.();+ return;+ }++ if (serverMsg.type === "session_end") {+ wsRef.current = null;+ setIsConnected(false);+ setIsConnecting(false);+ rejectAllPending("Session ended");+ readyRejectRef.current?.(new Error("Session ended"));+ onSessionEndRef.current?.(serverMsg.reason);+ return;+ }++ // Request-response correlation+ if ("id" in serverMsg && serverMsg.id) {+ const pending = pendingRequestsRef.current.get(serverMsg.id);+ if (pending) {+ pendingRequestsRef.current.delete(serverMsg.id);+ clearTimeout(pending.timer);++ if (serverMsg.type === "error") {+ const errMsg = [serverMsg.error, serverMsg.detail, serverMsg.hint]+ .filter(Boolean)+ .join("\n");+ pending.reject(new Error(errMsg));+ } else {+ pending.resolve(serverMsg);+ }+ }+ }+ };++ ws.onclose = () => {+ // If wsRef was already cleared (by disconnect/cleanup or session_end handler), skip.+ if (wsRef.current !== ws) return;++ wsRef.current = null;+ setIsConnected(false);+ setIsConnecting(false);+ rejectAllPending("Connection closed");+ readyRejectRef.current?.(new Error("Connection closed"));+ onSessionEndRef.current?.();+ };++ ws.onerror = () => {+ // onclose always fires after onerror+ };+ },+ [accountId, rejectAllPending]+ );++ const connect = useCallback(+ async (mfaSessionId?: string) => {+ setIsConnecting(true);+ setErrorMessage(null);+ setMfaState(null);+ setApprovalState(null);++ readyPromiseRef.current = new Promise<void>((resolve, reject) => {+ readyResolveRef.current = resolve;+ readyRejectRef.current = reject;+ });+ // Prevent unhandled rejection — callers of sendRequest will see the error+ // when they await readyPromiseRef.current.+ readyPromiseRef.current.catch(() => {});++ try {+ const { data } = await apiRequest.post<{ ticket: string }>(+ `/api/v1/pam/accounts/${accountId}/web-access-ticket`,+ { projectId, mfaSessionId }+ );+ openWebSocket(data.ticket);+ } catch (err: unknown) {+ const axiosErr = err as {+ response?: {+ data?: {+ error?: string;+ message?: string;+ details?: {+ mfaSessionId?: string;+ mfaMethod?: string;+ policyId?: string;+ policyName?: string;+ };+ };+ };+ };++ if (axiosErr?.response?.data?.error === "SESSION_MFA_REQUIRED") {+ const { details } = axiosErr.response!.data!;+ setMfaState({+ required: true,+ sessionId: details?.mfaSessionId,+ method: details?.mfaMethod,+ verifying: false+ });+ setIsConnecting(false);+ return;+ }++ if (axiosErr?.response?.data?.error === "PolicyViolationError") {+ const { details } = axiosErr.response!.data!;+ setApprovalState({+ required: true,+ policyName: details?.policyName,+ policyId: details?.policyId,+ creating: false,+ submitted: false+ });+ setIsConnecting(false);+ return;+ }++ setErrorMessage(axiosErr?.response?.data?.message ?? "Failed to connect to database");+ setIsConnecting(false);+ readyRejectRef.current?.(new Error("Failed to connect"));+ }+ },+ [accountId, projectId, openWebSocket]+ );++ const disconnect = useCallback(() => {+ const ws = wsRef.current;+ // Clear ref BEFORE close — so onclose sees wsRef.current !== ws and skips.+ wsRef.current = null;+ if (ws) ws.close();+ rejectAllPending("Disconnected");+ }, [rejectAllPending]);++ const reconnect = useCallback(() => {+ disconnect();+ connect();+ }, [disconnect, connect]);++ // MFA flow+ const handleMfaVerification = useCallback(async () => {+ if (!mfaState?.sessionId) return;++ const mfaUrl = `${window.location.origin}/mfa-session/${mfaState.sessionId}`;+ window.open(mfaUrl, "_blank");++ setMfaState((prev) => (prev ? { ...prev, verifying: true } : null));++ const MFA_POLL_INTERVAL = 2000;+ const MFA_TIMEOUT = 5 * 60 * 1000;+ const startTime = Date.now();++ const verified = await new Promise<boolean>((resolve) => {+ const interval = setInterval(async () => {+ if (Date.now() - startTime > MFA_TIMEOUT) {+ clearInterval(interval);+ resolve(false);+ return;+ }+ try {+ const resp = await apiRequest.get<TMfaSessionStatusResponse>(+ `/api/v2/mfa-sessions/${mfaState.sessionId}/status`+ );+ if (resp.data.status === MfaSessionStatus.ACTIVE) {+ clearInterval(interval);+ resolve(true);+ }+ } catch {+ clearInterval(interval);+ resolve(false);+ }+ }, MFA_POLL_INTERVAL);+ });++ if (verified) {+ connect(mfaState.sessionId);+ } else {+ setMfaState((prev) => (prev ? { ...prev, verifying: false } : null));+ setErrorMessage("MFA verification timed out or failed");+ }+ }, [mfaState, connect]);++ // Approval request flow+ const submitApprovalRequest = useCallback(+ async (justification?: string) => {+ if (!approvalState?.required) return;+ setApprovalState((prev) =>+ prev ? { ...prev, creating: true, errorMessage: undefined } : null+ );++ try {+ const { data: approvalData } = await apiRequest.post<{ request: { id: string } }>(+ "/api/v1/approval-policies/pam-access/requests",+ {+ projectId,+ requestData: {+ accessDuration: "1h",+ resourceName,+ accountName+ },+ justification: justification?.trim() || undefined+ }+ );+ setApprovalState((prev) =>+ prev+ ? {+ ...prev,+ creating: false,+ submitted: true,+ approvalRequestId: approvalData.request.id+ }+ : null+ );+ } catch {+ setApprovalState((prev) =>+ prev+ ? { ...prev, creating: false, errorMessage: "Failed to create approval request" }+ : null+ );+ }+ },+ [approvalState, projectId, resourceName, accountName]+ );++ const approvalRequestUrl = approvalState?.approvalRequestId+ ? `${window.location.origin}/organizations/${orgId}/projects/pam/${projectId}/approval-requests/${approvalState.approvalRequestId}`+ : undefined;++ // --- Request helpers ---++ const sendRequest = useCallback(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ async <T extends DataExplorerServerMessage>(msg: Record<string, any>): Promise<T> => {+ if (readyPromiseRef.current) {+ await readyPromiseRef.current;+ }++ const id = crypto.randomUUID();+ const fullMsg = { ...msg, id } as DataExplorerClientMessage;++ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => {+ pendingRequestsRef.current.delete(id);+ reject(new Error("Request timed out"));+ }, REQUEST_TIMEOUT_MS);++ pendingRequestsRef.current.set(id, {+ resolve: resolve as (m: DataExplorerServerMessage) => void,+ reject,+ timer+ });++ const ws = wsRef.current;+ if (ws && ws.readyState === WebSocket.OPEN) {+ ws.send(JSON.stringify(fullMsg));+ } else {+ pendingRequestsRef.current.delete(id);+ clearTimeout(timer);+ reject(new Error("WebSocket not connected"));+ }+ });+ },+ []+ );++ const fetchSchemas = useCallback(async (): Promise<SchemaInfo[]> => {+ const resp = await sendRequest<Extract<DataExplorerServerMessage, { type: "schemas" }>>({+ type: "get-schemas"+ });+ return resp.data;+ }, [sendRequest]);++ const fetchTables = useCallback(+ async (schema: string): Promise<TableInfo[]> => {+ const resp = await sendRequest<Extract<DataExplorerServerMessage, { type: "tables" }>>({+ type: "get-tables",+ schema+ });+ return resp.data;+ },+ [sendRequest]+ );++ const fetchTableDetail = useCallback(+ async (schema: string, table: string): Promise<TableDetail> => {+ const resp = await sendRequest<Extract<DataExplorerServerMessage, { type: "table-detail" }>>({+ type: "get-table-detail",+ schema,+ table+ });+ return resp.data;+ },+ [sendRequest]+ );++ const executeQuery = useCallback(+ async (+ sql: string+ ): Promise<{+ rows: Record<string, unknown>[];+ fields: FieldInfo[];+ rowCount: number | null;+ command: string;+ executionTimeMs: number;+ }> => {+ const resp = await sendRequest<Extract<DataExplorerServerMessage, { type: "query-result" }>>({+ type: "query",+ sql+ });+ return {+ rows: resp.rows,+ fields: resp.fields,+ rowCount: resp.rowCount,+ command: resp.command,+ executionTimeMs: resp.executionTimeMs+ };+ },+ [sendRequest]+ );++ // No auto-connect here — the page component drives connection lifecycle,+ // same as useWebAccessSession where containerEl gates the connect call.++ return {+ isConnected,+ isConnecting,+ errorMessage,+ mfaState,+ approvalState,+ connect,+ disconnect,+ reconnect,+ handleMfaVerification,+ submitApprovalRequest,+ approvalRequestUrl,+ fetchSchemas,+ fetchTables,+ fetchTableDetail,+ executeQuery+ };+};diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.tsindex d5f666899b..478c02dc20 100644--- a/frontend/src/routeTree.gen.ts+++ b/frontend/src/routeTree.gen.ts@@ -249,6 +249,7 @@ import { Route as secretManagerIntegrationsAwsParameterStoreConfigurePageRouteImimport { Route as secretManagerIntegrationsAwsParameterStoreAuthorizePageRouteImport } from './pages/secret-manager/integrations/AwsParameterStoreAuthorizePage/route'import { Route as pamPamDiscoveryDetailPageRouteImport } from './pages/pam/PamDiscoveryDetailPage/route'import { Route as certManagerInstallationDetailsByIDPageRouteImport } from './pages/cert-manager/InstallationDetailsByIDPage/route'+import { Route as pamPamDataExplorerPageRouteImport } from './pages/pam/PamDataExplorerPage/route'import { Route as pamPamAccountAccessPageRouteImport } from './pages/pam/PamAccountAccessPage/route'import { Route as secretManagerIntegrationsVercelOauthCallbackPageRouteImport } from './pages/secret-manager/integrations/VercelOauthCallbackPage/route'import { Route as secretManagerSecretSyncDetailsByIDPageRouteImport } from './pages/secret-manager/SecretSyncDetailsByIDPage/route'@@ -2402,6 +2403,13 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManag} as any,)+const pamPamDataExplorerPageRouteRoute =+ pamPamDataExplorerPageRouteImport.update({+ id: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer',+ path: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer',+ getParentRoute: () => middlewaresInjectOrgDetailsRoute,+ } as any)+const pamPamAccountAccessPageRouteRoute =pamPamAccountAccessPageRouteImport.update({id: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access',@@ -4506,6 +4514,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof pamPamAccountAccessPageRouteImportparentRoute: typeof middlewaresInjectOrgDetailsImport}+ '/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer': {+ id: '/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer'+ path: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer'+ fullPath: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer'+ preLoaderRoute: typeof pamPamDataExplorerPageRouteImport+ parentRoute: typeof middlewaresInjectOrgDetailsImport+ }'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId': {id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId'path: '/$commitId'@@ -5667,6 +5682,7 @@ interface middlewaresInjectOrgDetailsRouteChildren {redirectsOrganizationRedirectRoute: typeof redirectsOrganizationRedirectRouteredirectsProjectRedirectRoute: typeof redirectsProjectRedirectRoutepamPamAccountAccessPageRouteRoute: typeof pamPamAccountAccessPageRouteRoute+ pamPamDataExplorerPageRouteRoute: typeof pamPamDataExplorerPageRouteRoute}const middlewaresInjectOrgDetailsRouteChildren: middlewaresInjectOrgDetailsRouteChildren =@@ -5677,6 +5693,7 @@ const middlewaresInjectOrgDetailsRouteChildren: middlewaresInjectOrgDetailsRouteredirectsOrganizationRedirectRoute: redirectsOrganizationRedirectRoute,redirectsProjectRedirectRoute: redirectsProjectRedirectRoute,pamPamAccountAccessPageRouteRoute: pamPamAccountAccessPageRouteRoute,+ pamPamDataExplorerPageRouteRoute: pamPamDataExplorerPageRouteRoute,}const middlewaresInjectOrgDetailsRouteWithChildren =@@ -6078,6 +6095,7 @@ export interface FileRoutesByFullPath {'/organizations/$orgId/projects/secret-management/$projectId/integrations/secret-syncs/$destination/$syncId': typeof secretManagerSecretSyncDetailsByIDPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/integrations/vercel/oauth2/callback': typeof secretManagerIntegrationsVercelOauthCallbackPageRouteRoute'/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access': typeof pamPamAccountAccessPageRouteRoute+ '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer': typeof pamPamDataExplorerPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutCommitsEnvironmentFolderIdCommitIdRouteWithChildren'/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/': typeof secretManagerCommitDetailsPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/restore': typeof secretManagerCommitDetailsPageComponentsRollbackPreviewTabRouteRoute@@ -6335,6 +6353,7 @@ export interface FileRoutesByTo {'/organizations/$orgId/projects/secret-management/$projectId/integrations/secret-syncs/$destination/$syncId': typeof secretManagerSecretSyncDetailsByIDPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/integrations/vercel/oauth2/callback': typeof secretManagerIntegrationsVercelOauthCallbackPageRouteRoute'/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access': typeof pamPamAccountAccessPageRouteRoute+ '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer': typeof pamPamDataExplorerPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId': typeof secretManagerCommitDetailsPageRouteRoute'/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/restore': typeof secretManagerCommitDetailsPageComponentsRollbackPreviewTabRouteRoute'/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId': typeof pamPamAccountByIDPageRouteRoute@@ -6622,6 +6641,7 @@ export interface FileRoutesById {'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/secret-syncs/$destination/$syncId': typeof secretManagerSecretSyncDetailsByIDPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/vercel/oauth2/callback': typeof secretManagerIntegrationsVercelOauthCallbackPageRouteRoute'/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access': typeof pamPamAccountAccessPageRouteRoute+ '/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer': typeof pamPamDataExplorerPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutCommitsEnvironmentFolderIdCommitIdRouteWithChildren'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/': typeof secretManagerCommitDetailsPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/restore': typeof secretManagerCommitDetailsPageComponentsRollbackPreviewTabRouteRoute@@ -6900,6 +6920,7 @@ export interface FileRouteTypes {| '/organizations/$orgId/projects/secret-management/$projectId/integrations/secret-syncs/$destination/$syncId'| '/organizations/$orgId/projects/secret-management/$projectId/integrations/vercel/oauth2/callback'| '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access'+ | '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer'| '/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId'| '/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/'| '/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/restore'@@ -7156,6 +7177,7 @@ export interface FileRouteTypes {| '/organizations/$orgId/projects/secret-management/$projectId/integrations/secret-syncs/$destination/$syncId'| '/organizations/$orgId/projects/secret-management/$projectId/integrations/vercel/oauth2/callback'| '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access'+ | '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer'| '/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId'| '/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/restore'| '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId'@@ -7441,6 +7463,7 @@ export interface FileRouteTypes {| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/secret-syncs/$destination/$syncId'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/vercel/oauth2/callback'| '/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access'+ | '/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/restore'@@ -7562,7 +7585,8 @@ export const routeTree = rootRoute"/_authenticate/_inject-org-details/admin","/_authenticate/_inject-org-details/organization/$","/_authenticate/_inject-org-details/projects/$",- "/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access"+ "/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access",+ "/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer"]},"/_authenticate/personal-settings": {@@ -8966,6 +8990,10 @@ export const routeTree = rootRoute"filePath": "pam/PamAccountAccessPage/route.tsx","parent": "/_authenticate/_inject-org-details"},+ "/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer": {+ "filePath": "pam/PamDataExplorerPage/route.tsx",+ "parent": "/_authenticate/_inject-org-details"+ },"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId": {"filePath": "","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId",diff --git a/frontend/src/routes.ts b/frontend/src/routes.tsindex 7f735b45f0..b4ef7e9351 100644--- a/frontend/src/routes.ts+++ b/frontend/src/routes.ts@@ -414,6 +414,11 @@ const pamAccessRoute = route("pam/PamAccountAccessPage/route.tsx");+const pamDataExplorerRoute = route(+ "/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/data-explorer",+ "pam/PamDataExplorerPage/route.tsx"+);+const organizationRoutes = route("/organizations/$orgId", [route("/projects", "organization/ProjectsPage/route.tsx"),route("/access-management", "organization/AccessManagementPage/route.tsx"),@@ -483,6 +488,7 @@ export const routes = rootRoute("root.tsx", [route("/projects/$", "redirects/project-redirect.tsx"),adminRoute,pamAccessRoute,+ pamDataExplorerRoute,layout("org-layout", "organization/layout.tsx", [organizationRoutes,route("/organizations/$orgId/secret-manager/$projectId", [