Skip to content

Fully autonomous AI Agents system capable of performing complex penetration testing tasks

feat(frontend): unify list tables with URL sync, navigation, and Vitest

Sergey Kozyrenko5319d1cb65db
diff --git a/frontend/package.json b/frontend/package.json
index fc31b55b..40a5ecf8 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -107,6 +107,10 @@
"@prettier/plugin-xml": "^3.3.1",
"@tailwindcss/postcss": "^4.1.18",
"@tailwindcss/typography": "^0.5.15",
+ "@testing-library/dom": "^10.4.1",
+ "@testing-library/jest-dom": "^6.9.1",
+ "@testing-library/react": "^16.3.2",
+ "@testing-library/user-event": "^14.6.1",
"@types/js-cookie": "^3.0.6",
"@types/lodash": "^4.17.13",
"@types/node": "^22.0.0",
@@ -122,6 +126,7 @@
"eslint-plugin-perfectionist": "^4.15.1",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.0.1",
+ "jsdom": "^29.1.1",
"lint-staged": "^16.2.6",
"postcss": "^8.4.47",
"prettier": "^3.3.3",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 8f9d8a59..1ca4d188 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -199,7 +199,7 @@ importers:
version: 8.5.9(@types/[email protected])([email protected])
recharts:
specifier: ^3.7.0
rehype-highlight:
specifier: ^7.0.2
version: 7.0.2
@@ -270,6 +270,18 @@ importers:
'@tailwindcss/typography':
specifier: ^0.5.15
version: 0.5.19([email protected])
+ '@testing-library/dom':
+ specifier: ^10.4.1
+ version: 10.4.1
+ '@testing-library/jest-dom':
+ specifier: ^6.9.1
+ version: 6.9.1
+ '@testing-library/react':
+ specifier: ^16.3.2
+ '@testing-library/user-event':
+ specifier: ^14.6.1
+ version: 14.6.1(@testing-library/[email protected])
'@types/js-cookie':
specifier: ^3.0.6
version: 3.0.6
@@ -315,6 +327,9 @@ importers:
eslint-plugin-react-hooks:
specifier: ^7.0.1
+ jsdom:
+ specifier: ^29.1.1
+ version: 29.1.1(@noble/[email protected])
lint-staged:
specifier: ^16.2.6
version: 16.4.0
@@ -350,10 +365,13 @@ importers:
vitest:
specifier: ^4.0.0
packages:
+ '@adobe/[email protected]':
+ resolution: {integrity: sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==}
+
resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==}
engines: {node: '>=10'}
@@ -381,6 +399,21 @@ packages:
peerDependencies:
graphql: '*'
+ '@asamuzakjp/[email protected]':
+ resolution: {integrity: sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==}
+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
+
+ '@asamuzakjp/[email protected]':
+ resolution: {integrity: sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==}
+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
+
+ '@asamuzakjp/[email protected]':
+ resolution: {integrity: sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==}
+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
+
+ '@asamuzakjp/[email protected]':
+ resolution: {integrity: sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==}
+
resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}
engines: {node: '>=6.9.0'}
@@ -466,6 +499,10 @@ packages:
resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
engines: {node: '>=18'}
+ '@bramus/[email protected]':
+ resolution: {integrity: sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==}
+ hasBin: true
+
'@commitlint/[email protected]':
resolution: {integrity: sha512-yNkyN/tuKTJS3wdVfsZ2tXDM4G4Gi7z+jW54Cki8N8tZqwKBltbIvUUrSbT4hz1bhW/h0CdR+5sCSpXD+wMKaQ==}
engines: {node: '>=v18'}
@@ -547,6 +584,42 @@ packages:
conventional-commits-parser:
optional: true
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-LMGQLS9EuADloEFkcTBR3BwV/CGHV7zyDxVRtVDTwdI2Ca4it0CCVTT9wCkxSgokjE5Ho41hEPgb8OEUwoXr6Q==}
+ engines: {node: '>=20.19.0'}
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-DtdHlgXh5ZkA43cwBcAm+huzgJiwx3ZTWVjBs94kwz2xKqSimDA3lBgCjphYgwgVUMWatSM0pDd8TILB1yrVVg==}
+ engines: {node: '>=20.19.0'}
+ peerDependencies:
+ '@csstools/css-parser-algorithms': ^4.0.0
+ '@csstools/css-tokenizer': ^4.0.0
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-eZ5XOtyhK+mggRafYUWzA0tvaYOFgdY8AkgQiCJF9qNAePnUo/zmsqqYubBBb3sQ8uNUaSKTY9s9klfRaAXL0g==}
+ engines: {node: '>=20.19.0'}
+ peerDependencies:
+ '@csstools/css-parser-algorithms': ^4.0.0
+ '@csstools/css-tokenizer': ^4.0.0
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==}
+ engines: {node: '>=20.19.0'}
+ peerDependencies:
+ '@csstools/css-tokenizer': ^4.0.0
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-wgsqt92b7C7tQhIdPNxj0n9zuUbQlvAuI1exyzeNrOKOi62SD7ren8zqszmpVREjAOqg8cD2FqYhQfAuKjk4sw==}
+ peerDependencies:
+ css-tree: ^3.2.1
+ peerDependenciesMeta:
+ css-tree:
+ optional: true
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==}
+ engines: {node: '>=20.19.0'}
+
'@date-fns/[email protected]':
resolution: {integrity: sha512-P5LUNhtbj6YfI3iJjw5EL9eUAG6OitD0W3fWQcpQjDRc/QIsL0tRNuO1PcDvPccWL1fSTXXdE1ds+l95DV/OFA==}
@@ -800,6 +873,15 @@ packages:
resolution: {integrity: sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ '@exodus/[email protected]':
+ resolution: {integrity: sha512-UY0nlA+feH81UGSHv92sLEPLCeZFjXOuHhrIo0HQydScuQc8s0A7kL/UdgwgDq8g8ilksmuoF35YVTNphV2aBQ==}
+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
+ peerDependencies:
+ '@noble/hashes': ^1.8.0 || ^2.0.0
+ peerDependenciesMeta:
+ '@noble/hashes':
+ optional: true
+
'@fastify/[email protected]':
resolution: {integrity: sha512-m9FVDXU3GT2ITSe0UaMA5rU3QkfC/UXtCU8y0gSN/GugTqtVldOBWIB5V6V3sbmenVZUIpU6f+mPEO2+m5iTaA==}
@@ -2252,6 +2334,35 @@ packages:
resolution: {integrity: sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==}
engines: {node: '>=12'}
+ '@testing-library/[email protected]':
+ resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==}
+ engines: {node: '>=18'}
+
+ '@testing-library/[email protected]':
+ resolution: {integrity: sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==}
+ engines: {node: '>=14', npm: '>=6', yarn: '>=1'}
+
+ '@testing-library/[email protected]':
+ resolution: {integrity: sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@testing-library/dom': ^10.0.0
+ '@types/react': ^18.0.0 || ^19.0.0
+ '@types/react-dom': ^18.0.0 || ^19.0.0
+ react: ^18.0.0 || ^19.0.0
+ react-dom: ^18.0.0 || ^19.0.0
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+
+ '@testing-library/[email protected]':
+ resolution: {integrity: sha512-vq7fv0rnt+QTXgPxr5Hjc210p6YKq2kmdziLgnsZGgLJ9e6VAShx1pACLuRjd/AS/sr7phAR58OIIpf0LlmQNw==}
+ engines: {node: '>=12', npm: '>=6'}
+ peerDependencies:
+ '@testing-library/dom': '>=7.21.4'
+
'@tiptap/[email protected]':
resolution: {integrity: sha512-L1lhWz6ujGny8LduTJ7MBWYhzigwOvfUJUrJ7IzOJSuy3+OAzisdGDD1GV7LEO/hU0Hr2Mkm1wajRIHExvS9HQ==}
peerDependencies:
@@ -2401,6 +2512,9 @@ packages:
'@tiptap/[email protected]':
resolution: {integrity: sha512-LZ/LYbwH6rnDi5DnRyagkuNsYAVyhM+yJvvz+ZuYA0JkPiTXJV86J5PWSKew8M0gVfMHcNVtKjfQCvViFCeIgw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==}
+
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
@@ -2711,6 +2825,10 @@ packages:
resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==}
engines: {node: '>=12'}
@@ -2722,6 +2840,9 @@ packages:
resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==}
+
resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==}
engines: {node: '>= 0.4'}
@@ -3089,10 +3210,17 @@ packages:
resolution: {integrity: sha512-wPpOYtnsVontu2mODhA19JrqWxNsfdatRKd64kmpRbQgh1KtItko5sTnEpPdpSaJszTOhEMlF/RPz28qj4HqhQ==}
+ resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==}
+ engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0}
+
resolution: {integrity: sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==}
engines: {node: '>= 6'}
+ resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==}
+
resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}
engines: {node: '>=4'}
@@ -3152,6 +3280,10 @@ packages:
resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==}
engines: {node: '>= 12'}
+ resolution: {integrity: sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==}
+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
+
resolution: {integrity: sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==}
engines: {node: '>= 0.4'}
@@ -3189,6 +3321,9 @@ packages:
resolution: {integrity: sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==}
+ resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==}
+
resolution: {integrity: sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==}
@@ -3244,6 +3379,12 @@ packages:
resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}
+
+ resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==}
+
resolution: {integrity: sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag==}
@@ -3317,6 +3458,10 @@ packages:
resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==}
engines: {node: '>=0.12'}
+ resolution: {integrity: sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==}
+ engines: {node: '>=20.19.0'}
+
resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}
engines: {node: '>=6'}
@@ -3791,6 +3936,10 @@ packages:
resolution: {integrity: sha512-LgOWAkrN0rFaQpfdWBQlv/VhkOxb5AsBjk6NQVx4yEzWS923T07X0M1Y0VNko2H52HeSpZrZNNMJ0aFqsdVzQg==}
+ resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==}
+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
+
resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}
@@ -3851,6 +4000,10 @@ packages:
resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==}
engines: {node: '>=0.8.19'}
+ resolution: {integrity: sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
@@ -3980,6 +4133,9 @@ packages:
resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}
+
resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==}
engines: {node: '>= 0.4'}
@@ -4099,6 +4255,15 @@ packages:
resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==}
hasBin: true
+ resolution: {integrity: sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==}
+ engines: {node: ^20.19.0 || ^22.13.0 || >=24.0.0}
+ peerDependencies:
+ canvas: ^3.0.0
+ peerDependenciesMeta:
+ canvas:
+ optional: true
+
resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==}
engines: {node: '>=6'}
@@ -4314,6 +4479,10 @@ packages:
peerDependencies:
react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}
+ hasBin: true
+
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
@@ -4397,6 +4566,9 @@ packages:
resolution: {integrity: sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==}
+ resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==}
+
resolution: {integrity: sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==}
@@ -4523,6 +4695,10 @@ packages:
resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==}
+ engines: {node: '>=4'}
+
resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==}
engines: {node: 18 || 20 || >=22}
@@ -4681,6 +4857,9 @@ packages:
resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}
+ resolution: {integrity: sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==}
+
resolution: {integrity: sha512-uWlGT3YSnK9x3BQJaOdcZwrnV6hPpd8jFH1/ucpiLRPh/2zCVJKS19E4GvYHvaCcACn3foXZ0cLB9Wrx1KGe5g==}
@@ -4809,6 +4988,10 @@ packages:
engines: {node: '>=14'}
hasBin: true
+ resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==}
+ engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0}
+
resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}
@@ -4902,6 +5085,9 @@ packages:
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
+ resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==}
+
resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==}
peerDependencies:
@@ -4991,6 +5177,10 @@ packages:
react-dom: ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-is: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==}
peerDependencies:
@@ -5137,6 +5327,10 @@ packages:
resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}
+ resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}
+ engines: {node: '>=v12.22.7'}
+
resolution: {integrity: sha512-pFwF6H1XrSdYYNLfOcGlM28/j8CGLu8IvdrxqhjWULe2bPcKiKW4CV+OWqR/9fT52mywx65l7ysNkjLKBda7eA==}
@@ -5327,6 +5521,10 @@ packages:
resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==}
engines: {node: '>=8'}
@@ -5362,6 +5560,9 @@ packages:
resolution: {integrity: sha512-b19dMThMV4HVFynSAM1++gBHAbk2Tc/osgLIBZMKsyqh34jb2e8Os7T6ZW/Bt3pJFdBTd2JwAnAAEQV7rSNvcQ==}
engines: {node: '>=0.10'}
+ resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}
+
resolution: {integrity: sha512-IELLEvzHuCfc1uTsshPK58ViSdNqXxlml1U+fmwJIKLYKOr/rAtBrorE2RYm5IHaMpDNlmC0fr1LAvdXvyheEQ==}
engines: {node: '>=18'}
@@ -5417,10 +5618,25 @@ packages:
resolution: {integrity: sha512-e1zGYRvbffpcHIrnuqT0Dh+gEJtDaxDSoG4JAIpq4oDFyooziLBIiYQv0GBT4FUAnUop5uZ1hiIAj7oAF6sOCA==}
+ resolution: {integrity: sha512-uiHN8PIB1VmWyS98eZYja4xzlYqeFZVjb4OuYlJQnZAuJhMw4PbKQOKgHKhBdJR3FE/t5mUQ1Kd80++B+qhD1Q==}
+
+ resolution: {integrity: sha512-ELrFxuqsDdHUwoh0XxDbxuLD3Wnz49Z57IFvTtvWy1hJdcMZjXLIuonjilCiWHlT2GbE4Wlv1wKVTzDFnXH1aw==}
+ hasBin: true
+
resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}
engines: {node: '>=8.0'}
+ resolution: {integrity: sha512-LktZQb3IeoUWB9lqR5EWTHgW/VTITCXg4D21M+lvybRVdylLrRMnqaIONLVb5mav8vM19m44HIcGq4qASeu2Qw==}
+ engines: {node: '>=16'}
+
+ resolution: {integrity: sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==}
+ engines: {node: '>=20'}
+
resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}
@@ -5503,6 +5719,10 @@ packages:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
+ resolution: {integrity: sha512-xXnp4kTyor2Zq+J1FfPI6Eq3ew5h6Vl0F/8d9XU5zZQf1tX9s2Su1/3PiMmUANFULpmksxkClamIZcaUqryHsQ==}
+ engines: {node: '>=20.18.1'}
+
resolution: {integrity: sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==}
@@ -5733,6 +5953,10 @@ packages:
resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}
+ resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==}
@@ -5740,10 +5964,22 @@ packages:
resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}
engines: {node: '>= 8'}
+ resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==}
+ engines: {node: '>=20'}
+
resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==}
+ engines: {node: '>=20'}
+
+ resolution: {integrity: sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==}
+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
+
resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==}
engines: {node: '>= 0.4'}
@@ -5798,6 +6034,13 @@ packages:
utf-8-validate:
optional: true
+ resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==}
+
resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
engines: {node: '>=10'}
@@ -5853,6 +6096,8 @@ packages:
snapshots:
+ '@adobe/[email protected]': {}
+
'@alloc/[email protected]': {}
@@ -5885,6 +6130,26 @@ snapshots:
immutable: 5.1.5
invariant: 2.2.4
+ '@asamuzakjp/[email protected]':
+ dependencies:
+ '@asamuzakjp/generational-cache': 1.0.1
+ '@csstools/css-calc': 3.2.1(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
+ '@csstools/css-color-parser': 4.1.1(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
+ '@csstools/css-parser-algorithms': 4.0.0(@csstools/[email protected])
+ '@csstools/css-tokenizer': 4.0.0
+
+ '@asamuzakjp/[email protected]':
+ dependencies:
+ '@asamuzakjp/generational-cache': 1.0.1
+ '@asamuzakjp/nwsapi': 2.3.9
+ bidi-js: 1.0.3
+ css-tree: 3.2.1
+ is-potential-custom-element-name: 1.0.1
+
+ '@asamuzakjp/[email protected]': {}
+
+ '@asamuzakjp/[email protected]': {}
+
dependencies:
'@babel/helper-validator-identifier': 7.28.5
@@ -5996,6 +6261,10 @@ snapshots:
'@bcoe/[email protected]': {}
+ '@bramus/[email protected]':
+ dependencies:
+ css-tree: 3.2.1
+
dependencies:
'@commitlint/format': 20.5.0
@@ -6118,6 +6387,30 @@ snapshots:
optionalDependencies:
conventional-commits-parser: 6.4.0
+ '@csstools/[email protected]': {}
+
+ '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':
+ dependencies:
+ '@csstools/css-parser-algorithms': 4.0.0(@csstools/[email protected])
+ '@csstools/css-tokenizer': 4.0.0
+
+ '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':
+ dependencies:
+ '@csstools/color-helpers': 6.0.2
+ '@csstools/css-calc': 3.2.1(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
+ '@csstools/css-parser-algorithms': 4.0.0(@csstools/[email protected])
+ '@csstools/css-tokenizer': 4.0.0
+
+ '@csstools/[email protected](@csstools/[email protected])':
+ dependencies:
+ '@csstools/css-tokenizer': 4.0.0
+
+ optionalDependencies:
+ css-tree: 3.2.1
+
+ '@csstools/[email protected]': {}
+
'@date-fns/[email protected]': {}
'@emotion/[email protected]':
@@ -6335,6 +6628,10 @@ snapshots:
'@eslint/core': 0.17.0
levn: 0.4.1
+ optionalDependencies:
+ '@noble/hashes': 1.8.0
+
'@fastify/[email protected]': {}
'@floating-ui/[email protected]':
@@ -7880,6 +8177,40 @@ snapshots:
'@tanstack/[email protected]': {}
+ '@testing-library/[email protected]':
+ dependencies:
+ '@babel/code-frame': 7.29.0
+ '@babel/runtime': 7.29.2
+ '@types/aria-query': 5.0.4
+ aria-query: 5.3.0
+ dom-accessibility-api: 0.5.16
+ lz-string: 1.5.0
+ picocolors: 1.1.1
+ pretty-format: 27.5.1
+
+ '@testing-library/[email protected]':
+ dependencies:
+ '@adobe/css-tools': 4.4.4
+ aria-query: 5.3.2
+ css.escape: 1.5.1
+ dom-accessibility-api: 0.6.3
+ picocolors: 1.1.1
+ redent: 3.0.0
+
+ dependencies:
+ '@babel/runtime': 7.29.2
+ '@testing-library/dom': 10.4.1
+ react: 19.2.5
+ react-dom: 19.2.5([email protected])
+ optionalDependencies:
+ '@types/react': 19.2.14
+ '@types/react-dom': 19.2.3(@types/[email protected])
+
+ '@testing-library/[email protected](@testing-library/[email protected])':
+ dependencies:
+ '@testing-library/dom': 10.4.1
+
dependencies:
'@tiptap/pm': 3.22.5
@@ -8051,6 +8382,8 @@ snapshots:
'@tiptap/extensions': 3.22.5(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
'@tiptap/pm': 3.22.5
+ '@types/[email protected]': {}
+
dependencies:
'@types/deep-eql': 4.0.2
@@ -8271,7 +8604,7 @@ snapshots:
obug: 2.1.1
std-env: 4.0.0
tinyrainbow: 3.1.0
'@vitest/[email protected]':
dependencies:
@@ -8403,6 +8736,8 @@ snapshots:
dependencies:
color-convert: 2.0.1
+
@@ -8411,6 +8746,10 @@ snapshots:
dependencies:
tslib: 2.8.1
+ dependencies:
+ dequal: 2.0.3
+
@@ -8828,8 +9167,15 @@ snapshots:
domutils: 2.8.0
nth-check: 2.1.1
+ dependencies:
+ mdn-data: 2.27.1
+ source-map-js: 1.2.1
+
+
@@ -8876,6 +9222,13 @@ snapshots:
+ dependencies:
+ whatwg-mimetype: 5.0.0
+ whatwg-url: 16.0.1(@noble/[email protected])
+ transitivePeerDependencies:
+ - '@noble/hashes'
+
dependencies:
call-bound: 1.0.4
@@ -8908,6 +9261,8 @@ snapshots:
+
dependencies:
character-entities: 2.0.2
@@ -8954,6 +9309,10 @@ snapshots:
dependencies:
esutils: 2.0.3
+
+
dependencies:
domelementtype: 2.3.0
@@ -9024,6 +9383,8 @@ snapshots:
+
@@ -9697,6 +10058,12 @@ snapshots:
+ dependencies:
+ '@exodus/bytes': 1.15.0(@noble/[email protected])
+ transitivePeerDependencies:
+ - '@noble/hashes'
+
@@ -9751,6 +10118,8 @@ snapshots:
+
@@ -9874,6 +10243,8 @@ snapshots:
+
dependencies:
call-bound: 1.0.4
@@ -9989,6 +10360,32 @@ snapshots:
dependencies:
argparse: 2.0.1
+ dependencies:
+ '@asamuzakjp/css-color': 5.1.11
+ '@asamuzakjp/dom-selector': 7.1.1
+ '@bramus/specificity': 2.4.2
+ '@csstools/css-syntax-patches-for-csstree': 1.1.4([email protected])
+ '@exodus/bytes': 1.15.0(@noble/[email protected])
+ css-tree: 3.2.1
+ data-urls: 7.0.0(@noble/[email protected])
+ decimal.js: 10.6.0
+ html-encoding-sniffer: 6.0.0(@noble/[email protected])
+ is-potential-custom-element-name: 1.0.1
+ lru-cache: 11.3.5
+ parse5: 8.0.1
+ saxes: 6.0.0
+ symbol-tree: 3.2.4
+ tough-cookie: 6.0.1
+ undici: 7.25.0
+ w3c-xmlserializer: 5.0.0
+ webidl-conversions: 8.0.1
+ whatwg-mimetype: 5.0.0
+ whatwg-url: 16.0.1(@noble/[email protected])
+ xml-name-validator: 5.0.0
+ transitivePeerDependencies:
+ - '@noble/hashes'
+
@@ -10192,6 +10589,8 @@ snapshots:
dependencies:
react: 19.2.5
+
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
@@ -10380,6 +10779,8 @@ snapshots:
dependencies:
'@types/mdast': 4.0.4
+
@@ -10598,6 +10999,8 @@ snapshots:
+
dependencies:
brace-expansion: 5.0.5
@@ -10784,6 +11187,10 @@ snapshots:
dependencies:
entities: 6.0.1
+ dependencies:
+ entities: 8.0.0
+
dependencies:
no-case: 3.0.4
@@ -10844,6 +11251,12 @@ snapshots:
+ dependencies:
+ ansi-regex: 5.0.1
+ ansi-styles: 5.2.0
+ react-is: 17.0.2
+
dependencies:
loose-envify: 1.4.0
@@ -10977,6 +11390,8 @@ snapshots:
+
dependencies:
'@types/hast': 3.0.4
@@ -11061,7 +11476,7 @@ snapshots:
dependencies:
clsx: 2.1.1
@@ -11071,7 +11486,7 @@ snapshots:
immer: 10.2.0
react: 19.2.5
react-dom: 19.2.5([email protected])
- react-is: 16.13.1
+ react-is: 17.0.2
reselect: 5.1.1
tiny-invariant: 1.3.3
@@ -11081,6 +11496,11 @@ snapshots:
- '@types/react'
- redux
+ dependencies:
+ indent-string: 4.0.0
+ strip-indent: 3.0.0
+
dependencies:
redux: 5.0.1
@@ -11283,6 +11703,10 @@ snapshots:
+ dependencies:
+ xmlchars: 2.2.0
+
@@ -11508,6 +11932,10 @@ snapshots:
dependencies:
ansi-regex: 6.2.2
+ dependencies:
+ min-indent: 1.0.1
+
@@ -11537,6 +11965,8 @@ snapshots:
+
dependencies:
node-fetch: 3.3.2
@@ -11589,10 +12019,24 @@ snapshots:
dependencies:
tslib: 2.8.1
+
+ dependencies:
+ tldts-core: 7.0.30
+
dependencies:
is-number: 7.0.0
+ dependencies:
+ tldts: 7.0.30
+
+ dependencies:
+ punycode: 2.3.1
+
@@ -11676,6 +12120,8 @@ snapshots:
+
dependencies:
base64-js: 1.5.1
@@ -11885,7 +12331,7 @@ snapshots:
tsx: 4.21.0
yaml: 2.8.3
dependencies:
'@vitest/expect': 4.1.4
@@ -11910,17 +12356,34 @@ snapshots:
optionalDependencies:
'@types/node': 22.19.17
'@vitest/coverage-v8': 4.1.4([email protected])
+ jsdom: 29.1.1(@noble/[email protected])
transitivePeerDependencies:
- msw
+ dependencies:
+ xml-name-validator: 5.0.0
+
+
+
+ dependencies:
+ '@exodus/bytes': 1.15.0(@noble/[email protected])
+ tr46: 6.0.0
+ webidl-conversions: 8.0.1
+ transitivePeerDependencies:
+ - '@noble/hashes'
+
dependencies:
is-bigint: 1.1.0
@@ -11993,6 +12456,10 @@ snapshots:
+
+
diff --git a/frontend/src/components/shared/README.md b/frontend/src/components/shared/README.md
new file mode 100644
index 00000000..d7ba400a
--- /dev/null
+++ b/frontend/src/components/shared/README.md
@@ -0,0 +1,155 @@
+# Shared list/detail building blocks
+
+This directory hosts the reusable surface for list-and-detail pages: a
+filterable table, a Prev/Next/Sheet toolbar that walks the *same* filtered
+subset on detail pages, and the inline-rename + sortable-header primitives
+that every list reuses.
+
+## Mental model
+
+```
+ ┌──────────────────────────────────────────┐
+ │ URL ?q=foo ?page=3 │
+ │ (source of truth — bookmarkable) │
+ └────────┬─────────────────────┬───────────┘
+ │ read/write │ read-only
+ ▼ ▼
+ useTableQueryFilter useTableQueryFilterReader
+ usePagination │
+ │ │
+ ▼ ▼
+ <DataTable> useFilteredListNavigation
+ (list page) │
+ │ ▼
+ ▼ <ListNavigationToolbar>
+ table_4_<path> (detail page)
+ in localStorage
+ (cold-start fallback)
+```
+
+- **URL is authoritative.** Filter (`?q=`) and page (`?page=`) live in the
+ URL so links/bookmarks always reproduce the user's view.
+- **Storage is a warm-restart bag.** The list page persists the URL filter
+ into `localStorage` under `table_4_<path>`. The detail page never writes
+ storage and never replays storage into the URL — opening a shared link
+ shows exactly what the link says.
+- **Prev/Next walks the same subset.** `ListNavigationToolbar` runs the
+ same matcher (`createTextMatcher`) the list filter uses, so siblings stay
+ in lockstep with what the user sees in the table.
+
+## Components
+
+| File | Role |
+| --------------------------------------------------------------- | -------------------------------------------------------------------------- |
+| [`list-navigation-toolbar.tsx`](list-navigation-toolbar.tsx) | Prev / Position / Next cluster + sheet trigger on detail pages. |
+| [`list-navigation-buttons.tsx`](list-navigation-buttons.tsx) | Presentation-only button trio; stateless. |
+| [`list-navigation-sheet.tsx`](list-navigation-sheet.tsx) | WAI-ARIA listbox sheet — roving tabindex, focus reconciliation. |
+| [`sortable-column-header.tsx`](sortable-column-header.tsx) | DRY header for TanStack columns — `none → asc → desc → none` cycle. |
+| [`inline-rename-input.tsx`](inline-rename-input.tsx) | `<input>` + Save/Cancel addon with Enter/Escape keybindings. |
+
+## Hooks (in `@/hooks/`)
+
+| Hook | Source of truth | Writes? | Notes |
+| ------------------------------- | --------------- | ------- | ------------------------------------------------------------------ |
+| `useTableQueryFilter` | URL `?q=` | yes | List pages. Restores from `localStorage` on cold start. |
+| `useTableQueryFilterReader` | URL `?q=` | no | Detail pages. Storage-blind — shared links never gain stale `?q=`. |
+| `usePagination` | URL `?page=` | yes | Canonicalizes `?page=1` away so the URL has one form per view. |
+| `useFilteredListNavigation` | props | no | Pure computation of Prev/Next around a `currentId`. |
+| `useDetailNavigation` | URL + props | no | Bundles the three above into a single hook for detail pages. |
+| `useInlineEditTitle` | local state | no | Edit-mode toggle + deferred focus (Radix dropdown race fix). |
+| `usePageStorageKeys` | router | no | Resolves the three per-page storage keys reactively. |
+
+## Library helpers (in `@/lib/`)
+
+| Module | Purpose |
+| ----------------------- | -------------------------------------------------------------------------------- |
+| `table-filter.ts` | `createTextMatcher` — case + diacritic-insensitive substring matcher. |
+| `table-state.ts` | Unified `table_4_<path>` JSON slot. Carries filter + sorting + columnVis + pageSize. |
+| `table-sort.ts` | `cycleColumnSort` — pure none/asc/desc cycle for TanStack columns. |
+| `view-options-storage.ts` | `viewOptions_4_<path>` for FileManager-style screens (folders-first, etc.). |
+| `storage-keys.ts` | Single source of truth for storage-key conventions and `getTopLevelPath`. |
+| `url-params.ts` | `URL_PARAMS` constants + `mergeHrefWithSearchParams` (preserves hash on merge). |
+
+## How to add a new list + detail pair
+
+1. **List page** (`/<entities>/`):
+ ```tsx
+ const { filter, setFilter } = useTableQueryFilter();
+ const { pageIndex, setPage } = usePagination();
+
+ return (
+ <DataTable
+ columns={columns /* use <SortableColumnHeader column={column} label="..." /> */}
+ data={entities}
+ filterColumn="title"
+ filterValue={filter}
+ onFilterChange={setFilter}
+ onPageChange={setPage}
+ pageIndex={pageIndex}
+ />
+ );
+ ```
+
+2. **Feature-scoped navigation hook** (`@/features/<entity>/use-<entity>-detail-navigation.ts`):
+ ```ts
+ const getLabel = (item: Entity) => item.title;
+ const getHref = (item: Entity) => `/<entities>/${item.id}`;
+
+ export const useEntityDetailNavigation = (currentId: null | string | undefined) => {
+ const { entities } = useEntities();
+
+ return useDetailNavigation<Entity>({ currentId, getHref, getLabel, items: entities });
+ };
+ ```
+
+3. **Detail page** (`/<entities>/:id`):
+ ```tsx
+ const { toolbarProps } = useEntityDetailNavigation(entityId);
+
+ return (
+ <header>
+ <ListNavigationToolbar<Entity>
+ {...toolbarProps}
+ sheetIcon={<Icon className="size-4" />}
+ sheetTitle="Entities"
+ renderItem={(item, isCurrent) => <span>{item.title}</span>}
+ />
+ </header>
+ );
+ ```
+
+## Why URL > storage
+
+A user opens `/flows?q=alpha` in tab A. They navigate to flow B by clicking
+"Next" in the toolbar. They share `/flows/b?q=alpha` with a teammate.
+
+- The teammate opens the link cold. Their detail page reads `q=alpha` from
+ the URL and renders Prev/Next over the filtered subset.
+- The teammate hits "Next". They land on `/flows/c?q=alpha` — still inside
+ the filter, even though they never typed it.
+
+`useTableQueryFilterReader` is the key piece: it observes the URL but never
+writes anything, so a fresh detail-page mount can't accidentally inject the
+**previous tab's** `?q=` into the URL.
+
+## Why one storage key per page
+
+Before the unification, every list page wrote four storage keys
+(`column_4_/flows`, `sorting_4_/flows`, `filter_4_/flows`, `page_4_/flows`)
+in two different write paths (sync + debounced). Refreshing during a typing
+session could land you in an inconsistent state. The unified
+`table_4_<path>` slot is a single JSON object that all preferences live in;
+`migrateLegacyTableState` folds the four legacy keys into it on first mount
+and deletes them.
+
+## Testing notes
+
+- `vitest run` covers the pure utilities (`table-filter`, `table-state`,
+ `view-options-storage`, `url-params`, `table-sort`), the hook behaviours
+ (`use-pagination`, `use-table-query-filter`, `use-inline-edit-title`,
+ `use-page-storage-keys`, `use-detail-navigation`), and the components
+ (`list-navigation-toolbar`, `data-table`).
+- jsdom doesn't ship `Element.prototype.scrollIntoView` or `ResizeObserver`
+ — both are polyfilled in `vitest.setup.ts`.
+- React Testing Library auto-cleans the DOM after every test (see the same
+ setup file). Tests can freely call `render` without leaking nodes.
diff --git a/frontend/src/components/shared/file-manager/file-manager-types.ts b/frontend/src/components/shared/file-manager/file-manager-types.ts
index 4124cd6c..47cc7c7d 100644
--- a/frontend/src/components/shared/file-manager/file-manager-types.ts
+++ b/frontend/src/components/shared/file-manager/file-manager-types.ts
@@ -310,7 +310,7 @@ export interface FileManagerProps {
/**
* When set, the active sort is persisted to `localStorage` under this key
* across page reloads. Ignored in controlled mode (when `sorting` is set).
- * Pass a route-scoped key (e.g. `getSortingStorageKey('/flows/files')`)
+ * Pass a route-scoped key (e.g. `getTableStorageKey('/flows/files')`)
* to avoid collisions across pages.
*/
sortStorageKey?: string;
diff --git a/frontend/src/components/shared/inline-rename-input.tsx b/frontend/src/components/shared/inline-rename-input.tsx
new file mode 100644
index 00000000..5d033a05
--- /dev/null
+++ b/frontend/src/components/shared/inline-rename-input.tsx
@@ -0,0 +1,101 @@
+import { Check, Loader2, X } from 'lucide-react';
+import { type KeyboardEvent, type Ref } from 'react';
+
+import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';
+import { cn } from '@/lib/utils';
+
+interface InlineRenameInputProps {
+ /**
+ * Auto-focus the input on mount. Needed for table-cell call sites that
+ * switch into edit mode in-place: the parent flips a flag (e.g.
+ * `editingFlowId === flow.id`) and this component is freshly mounted,
+ * so focus must be requested explicitly.
+ */
+ autoFocus?: boolean;
+ /** Disable input + Save button while a mutation is in flight. */
+ busy?: boolean;
+ /** Optional className passed through to the outer `<InputGroup>`. */
+ className?: string;
+ /** Initial value rendered inside the uncontrolled input. */
+ defaultValue?: string;
+ /** Ref to the underlying `<input>` element. Pair with `useInlineEditTitle().inputRef`. */
+ inputRef?: Ref<HTMLInputElement>;
+ onCancel: () => void;
+ /**
+ * Save handler. Read the latest text from the bound `inputRef` — kept
+ * uncontrolled because most callers commit on Enter or click and have
+ * no need to reflect every keystroke into React state.
+ */
+ onSave: () => void;
+ placeholder?: string;
+}
+
+/**
+ * Inline rename input used inside table cells and detail-page breadcrumbs.
+ *
+ * Pairs with {@link useInlineEditTitle} — the parent owns the open/close
+ * state and supplies a ref via that hook; this component owns the
+ * presentation (input + Save/Cancel addon buttons), keyboard semantics
+ * (`Enter` saves, `Escape` cancels), and the loading spinner during save.
+ *
+ * The input is uncontrolled (`defaultValue`) to match the pattern across
+ * the codebase: callers read the value at submit time from `inputRef.current`,
+ * not from React state, which avoids a re-render per keystroke for a value
+ * that's only relevant once.
+ */
+export const InlineRenameInput = ({
+ autoFocus = false,
+ busy = false,
+ className,
+ defaultValue,
+ inputRef,
+ onCancel,
+ onSave,
+ placeholder,
+}: InlineRenameInputProps) => {
+ const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ onSave();
+
+ return;
+ }
+
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ onCancel();
+ }
+ };
+
+ return (
+ <InputGroup className={cn('h-8', className)}>
+ <InputGroupInput
+ autoFocus={autoFocus}
+ className="text-foreground"
+ defaultValue={defaultValue}
+ onKeyDown={handleKeyDown}
+ placeholder={placeholder}
+ ref={inputRef}
+ />
+ <InputGroupAddon
+ align="inline-end"
+ className="gap-0 pr-2"
+ >
+ <InputGroupButton
+ aria-label="Save"
+ disabled={busy}
+ onClick={onSave}
+ >
+ {busy ? <Loader2 className="animate-spin" /> : <Check />}
+ </InputGroupButton>
+ <InputGroupButton
+ aria-label="Cancel"
+ disabled={busy}
+ onClick={onCancel}
+ >
+ <X />
+ </InputGroupButton>
+ </InputGroupAddon>
+ </InputGroup>
+ );
+};
diff --git a/frontend/src/components/shared/list-navigation-buttons.tsx b/frontend/src/components/shared/list-navigation-buttons.tsx
new file mode 100644
index 00000000..7a3a1445
--- /dev/null
+++ b/frontend/src/components/shared/list-navigation-buttons.tsx
@@ -0,0 +1,91 @@
+import { ChevronLeft, ChevronRight } from 'lucide-react';
+
+import { Button } from '@/components/ui/button';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+
+interface ListNavigationButtonsProps {
+ /** Disable the position-button when the filtered subset is empty. */
+ hasEntries: boolean;
+ /** No next sibling — disable the right chevron. */
+ nextDisabled: boolean;
+ onNext: () => void;
+ onOpen: () => void;
+ onPrev: () => void;
+ /** Pre-formatted `"3/10"` (or `"–/0"` when no current). */
+ positionLabel: string;
+ /** No previous sibling — disable the left chevron. */
+ prevDisabled: boolean;
+ /** Lowercased plural used in the aria-label / tooltip ("flows", "templates"). */
+ sheetTitle: string;
+}
+
+/**
+ * Prev / Position / Next button cluster for a detail page. Stateless and
+ * presentation-only — `ListNavigationToolbar` owns the navigation logic
+ * and feeds the resolved indices, labels, and click handlers down.
+ *
+ * Kept separate from `ListNavigationSheet` so the same buttons could in
+ * principle be reused without the sheet (e.g. a future variant that ships
+ * keyboard-only navigation without an overlay).
+ */
+export const ListNavigationButtons = ({
+ hasEntries,
+ nextDisabled,
+ onNext,
+ onOpen,
+ onPrev,
+ positionLabel,
+ prevDisabled,
+ sheetTitle,
+}: ListNavigationButtonsProps) => {
+ const lowerTitle = sheetTitle.toLowerCase();
+
+ return (
+ <div className="flex items-center">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ aria-label="Previous"
+ className="size-8 rounded-r-none border-r-0 p-0"
+ disabled={prevDisabled}
+ onClick={onPrev}
+ size="icon"
+ variant="outline"
+ >
+ <ChevronLeft />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Previous</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ aria-label={`Open ${lowerTitle} list (${positionLabel})`}
+ className="h-8 min-w-12 rounded-none border-x px-2 font-mono text-xs tabular-nums"
+ disabled={!hasEntries}
+ onClick={onOpen}
+ variant="outline"
+ >
+ {positionLabel}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Show all matching {lowerTitle}</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ aria-label="Next"
+ className="size-8 rounded-l-none border-l-0 p-0"
+ disabled={nextDisabled}
+ onClick={onNext}
+ size="icon"
+ variant="outline"
+ >
+ <ChevronRight />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Next</TooltipContent>
+ </Tooltip>
+ </div>
+ );
+};
diff --git a/frontend/src/components/shared/list-navigation-sheet.tsx b/frontend/src/components/shared/list-navigation-sheet.tsx
new file mode 100644
index 00000000..2c8fe76a
--- /dev/null
+++ b/frontend/src/components/shared/list-navigation-sheet.tsx
@@ -0,0 +1,308 @@
+import { type KeyboardEvent, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+
+import { ScrollArea } from '@/components/ui/scroll-area';
+import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
+import { cn } from '@/lib/utils';
+
+interface ListNavigationSheetProps<T> {
+ currentId: null | string | undefined;
+ /**
+ * Pre-computed index of `currentId` inside `items` (or `-1` when the
+ * current entry doesn't belong to the filtered subset). Supplied by the
+ * parent toolbar so the sheet doesn't re-scan `items` for membership.
+ */
+ currentIndex: number;
+ getId: (item: T) => string;
+ getLabel: (item: T) => string;
+ /** Filtered + sorted items rendered as the sheet's listbox. */
+ items: readonly T[];
+ onItemSelect: (item: T) => void;
+ onOpenChange: (open: boolean) => void;
+ open: boolean;
+ renderItem?: (item: T, isCurrent: boolean) => ReactNode;
+ sheetIcon?: ReactNode;
+ sheetTitle: string;
+ /** Total count shown in the header — same as `items.length`, named explicitly for clarity. */
+ total: number;
+}
+
+/**
+ * Listbox-style overlay listing the navigable subset.
+ *
+ * Implements the WAI-ARIA single-select listbox pattern with **roving
+ * tabindex**: only the currently-focused option carries `tabIndex={0}`,
+ * the rest are `tabIndex={-1}`. Tab takes the user *past* the listbox in
+ * one step; arrow keys move focus *within* it.
+ *
+ * Initial focus on open targets the current entry (if it's part of the
+ * filtered subset) so users land oriented inside their own context.
+ */
+export function ListNavigationSheet<T>({
+ currentId,
+ currentIndex,
+ getId,
+ getLabel,
+ items,
+ onItemSelect,
+ onOpenChange,
+ open,
+ renderItem,
+ sheetIcon,
+ sheetTitle,
+ total,
+}: ListNavigationSheetProps<T>) {
+ const listRef = useRef<HTMLUListElement>(null);
+ const buttonRefs = useRef(new Map<string, HTMLButtonElement>());
+ const [focusedId, setFocusedId] = useState<null | string>(null);
+
+ const hasEntries = items.length > 0;
+
+ // Build an `id → index` map once per `items`/`getId` change so both the
+ // per-render membership check below and the keyboard handler's lookup
+ // stay O(1) instead of O(n). The IIFE that adjusts focus during render
+ // previously called `items.some(...)` on every commit; the keyboard
+ // handler ran `items.findIndex(...)` on every keystroke. Sharing one
+ // structure between the two also makes the contract explicit: an entry
+ // is "in the filtered subset" iff `indexById.has(id)`.
+ const indexById = useMemo(() => {
+ const map = new Map<string, number>();
+
+ items.forEach((item, index) => {
+ map.set(String(getId(item)), index);
+ });
+
+ return map;
+ }, [items, getId]);
+
+ // Single render-phase focus reconciliation. React's "adjust state when a
+ // prop changes" idiom — see https://react.dev/reference/react/useState#storing-information-from-previous-renders
+ // — collapsed into one comparison so the next desired focus is decided
+ // once per render and committed in the same pass that prompted it (no
+ // flash of stale focus, no double-setState ping-pong on edge cases like
+ // "items change while the sheet was reopening with no current item").
+ //
+ // Priorities, top-down:
+ // 1. open→close / close→open transition: re-pin to `currentId` (or the
+ // first entry when no current exists) on open, and clear on close.
+ // 2. While the sheet stays open, if the focused entry left the
+ // filtered subset (list page narrowed the filter behind it), fall
+ // back to the first survivor — otherwise the keyboard model would
+ // stall on a row that's no longer rendered.
+ // 3. Otherwise hold whatever focus the user chose via arrow keys.
+ //
+ // `lastOpen` starts at `false` so an initial `open=true` still trips
+ // the open transition on the very first render.
+ const [lastOpen, setLastOpen] = useState(false);
+
+ const desiredFocusId = (() => {
+ if (lastOpen !== open) {
+ if (!open) {
+ return null;
+ }
+
+ const firstItem = items[0];
+
+ if (!firstItem) {
+ return null;
+ }
+
+ // `currentId != null` narrows to `string`; the parent toolbar
+ // already verified `currentId` belongs to the filtered subset
+ // when it computed `currentIndex`, so no re-scan needed.
+ return currentId != null && currentIndex >= 0 ? String(currentId) : String(getId(firstItem));
+ }
+
+ if (open && focusedId !== null && hasEntries && !indexById.has(focusedId)) {
+ const fallbackItem = items[0];
+
+ return fallbackItem ? String(getId(fallbackItem)) : null;
+ }
+
+ return focusedId;
+ })();
+
+ if (lastOpen !== open) {
+ setLastOpen(open);
+ }
+
+ if (desiredFocusId !== focusedId) {
+ setFocusedId(desiredFocusId);
+ }
+
+ // After roving focus moves, push the focus into the DOM. `rAF` defers past
+ // Radix's own focus management so we don't fight its open-time focus trap.
+ useEffect(() => {
+ if (!open || focusedId === null) {
+ return;
+ }
+
+ const id = requestAnimationFrame(() => {
+ const node = buttonRefs.current.get(focusedId);
+
+ if (!node) {
+ return;
+ }
+
+ node.focus();
+
+ if (focusedId === String(currentId ?? '')) {
+ node.scrollIntoView({ block: 'center' });
+ }
+ });
+
+ return () => cancelAnimationFrame(id);
+ }, [open, focusedId, currentId]);
+
+ // Translate arrow / Home / End into roving moves over `items`. Using the
+ // array index instead of `querySelectorAll` keeps the keyboard model in
+ // step with the React tree even if the sheet ever virtualises the list.
+ // O(1) lookup via the shared `indexById` map — `findIndex` would scan on
+ // every keystroke for nothing.
+ const handleListKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLUListElement>) => {
+ if (!hasEntries || focusedId === null) {
+ return;
+ }
+
+ const focusedIndex = indexById.get(focusedId);
+
+ if (focusedIndex === undefined) {
+ return;
+ }
+
+ const moveTo = (index: number) => {
+ event.preventDefault();
+ const target = items[index];
+
+ if (target) {
+ setFocusedId(String(getId(target)));
+ }
+ };
+
+ if (event.key === 'ArrowDown') {
+ moveTo(Math.min(focusedIndex + 1, items.length - 1));
+
+ return;
+ }
+
+ if (event.key === 'ArrowUp') {
+ moveTo(Math.max(focusedIndex - 1, 0));
+
+ return;
+ }
+
+ if (event.key === 'Home') {
+ moveTo(0);
+
+ return;
+ }
+
+ if (event.key === 'End') {
+ moveTo(items.length - 1);
+ }
+ },
+ [focusedId, getId, hasEntries, indexById, items],
+ );
+
+ const handleItemClick = useCallback(
+ (item: T) => {
+ onItemSelect(item);
+ },
+ [onItemSelect],
+ );
+
+ // One stable callback ref reused for every button. The previous shape —
+ // `setButtonRef(id) => (node) => …` — manufactured a new closure per id
+ // on every render, which made React re-attach refs (a `delete` + `set`
+ // round-trip on the `Map`) on every list re-render. Reading the id from
+ // `data-item-id` keeps the closure identity-stable and the React-19
+ // cleanup return value handles unmount without leaks.
+ const setButtonRef = useCallback((node: HTMLButtonElement | null) => {
+ if (!node) {
+ return;
+ }
+
+ const id = node.dataset.itemId;
+
+ if (!id) {
+ return;
+ }
+
+ buttonRefs.current.set(id, node);
+
+ return () => {
+ buttonRefs.current.delete(id);
+ };
+ }, []);
+
+ return (
+ <Sheet
+ onOpenChange={onOpenChange}
+ open={open}
+ >
+ <SheetContent
+ className="flex w-full max-w-sm flex-col gap-0 p-0 sm:max-w-sm"
+ side="right"
+ >
+ <SheetHeader className="border-b p-4">
+ <SheetTitle className="flex items-center gap-2 text-base">
+ {sheetIcon}
+ <span>{sheetTitle}</span>
+ <span className="text-muted-foreground ml-auto text-sm font-normal tabular-nums">
+ {total}
+ </span>
+ </SheetTitle>
+ </SheetHeader>
+ {hasEntries ? (
+ <ScrollArea className="flex-1">
+ <ul
+ aria-label={sheetTitle}
+ className="flex flex-col gap-0.5 p-2"
+ onKeyDown={handleListKeyDown}
+ ref={listRef}
+ role="listbox"
+ >
+ {items.map((item) => {
+ const id = String(getId(item));
+ const isCurrent = currentId != null && id === String(currentId);
+ const isFocused = id === focusedId;
+
+ return (
+ <li
+ key={id}
+ role="presentation"
+ >
+ <button
+ aria-selected={isCurrent}
+ className={cn(
+ 'hover:bg-muted/50 focus-visible:ring-ring flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm focus-visible:ring-2 focus-visible:outline-hidden',
+ isCurrent && 'bg-muted text-foreground font-medium',
+ )}
+ data-item-id={id}
+ onClick={() => handleItemClick(item)}
+ onFocus={() => setFocusedId(id)}
+ ref={setButtonRef}
+ role="option"
+ tabIndex={isFocused ? 0 : -1}
+ type="button"
+ >
+ {renderItem ? (
+ renderItem(item, isCurrent)
+ ) : (
+ <span className="truncate">{getLabel(item)}</span>
+ )}
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </ScrollArea>
+ ) : (
+ <div className="text-muted-foreground flex flex-1 items-center justify-center px-4 text-center text-sm">
+ No items match the current filter.
+ </div>
+ )}
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/frontend/src/components/shared/list-navigation-toolbar.test.tsx b/frontend/src/components/shared/list-navigation-toolbar.test.tsx
new file mode 100644
index 00000000..7298274c
--- /dev/null
+++ b/frontend/src/components/shared/list-navigation-toolbar.test.tsx
@@ -0,0 +1,350 @@
+import type { ReactNode } from 'react';
+
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
+import { describe, expect, it } from 'vitest';
+
+import { TooltipProvider } from '@/components/ui/tooltip';
+
+import { ListNavigationToolbar } from './list-navigation-toolbar';
+
+interface Item {
+ id: string;
+ title: string;
+}
+
+const ITEMS: readonly Item[] = [
+ { id: 'a', title: 'Alpha' },
+ { id: 'b', title: 'Bravo' },
+ { id: 'c', title: 'Charlie' },
+ { id: 'd', title: 'Delta' },
+] as const;
+
+const getId = (item: Item) => item.id;
+const getLabel = (item: Item) => item.title;
+const getHref = (item: Item) => `/items/${item.id}`;
+
+const LocationReadout = () => {
+ const { pathname, search } = useLocation();
+
+ return (
+ <span data-testid="location">
+ {pathname}
+ {search}
+ </span>
+ );
+};
+
+const renderToolbar = (overrides: { currentId?: null | string; filter?: string; items?: readonly Item[] } = {}) => {
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter initialEntries={['/items/c?q=' + (overrides.filter ?? '')]}>
+ <TooltipProvider>
+ <LocationReadout />
+ <Routes>
+ <Route
+ element={<>{children}</>}
+ path="/items/:id"
+ />
+ </Routes>
+ </TooltipProvider>
+ </MemoryRouter>
+ );
+
+ return render(
+ <ListNavigationToolbar<Item>
+ currentId={overrides.currentId ?? 'c'}
+ filter={overrides.filter ?? ''}
+ getHref={getHref}
+ getId={getId}
+ getLabel={getLabel}
+ items={overrides.items ?? ITEMS}
+ sheetTitle="Items"
+ />,
+ { wrapper: Wrapper },
+ );
+};
+
+describe('ListNavigationToolbar', () => {
+ it('renders nothing when items list is empty', () => {
+ renderToolbar({ items: [] });
+ // The toolbar should not emit any of its own controls — the wrapper
+ // tree still renders the location readout, so assert on absent
+ // toolbar elements instead of "container empty".
+ expect(screen.queryByRole('button', { name: /Previous/i })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Next/i })).not.toBeInTheDocument();
+ });
+
+ it('shows `${currentIndex + 1}/${total}` for a matched current item', () => {
+ renderToolbar({ currentId: 'c' });
+ expect(screen.getByRole('button', { name: /3\/4/ })).toBeInTheDocument();
+ });
+
+ it('shows `–/total` when current is missing from the filtered subset', () => {
+ renderToolbar({ currentId: 'zzz' });
+ expect(screen.getByRole('button', { name: /–\/4/ })).toBeInTheDocument();
+ });
+
+ it('disables Prev for the first item', () => {
+ renderToolbar({ currentId: 'a' });
+ expect(screen.getByRole('button', { name: /Previous/i })).toBeDisabled();
+ });
+
+ it('disables Next for the last item', () => {
+ renderToolbar({ currentId: 'd' });
+ expect(screen.getByRole('button', { name: /Next/i })).toBeDisabled();
+ });
+
+ it('Next navigates to the next sibling preserving `?q=`', async () => {
+ const user = userEvent.setup();
+ // Filter 'a' matches every item (substring), so prev/next stays
+ // navigable across the full set while still proving the `?q=` URL
+ // round-trip on click.
+ renderToolbar({ currentId: 'a', filter: 'a' });
+
+ await user.click(screen.getByRole('button', { name: /Next/i }));
+
+ await waitFor(() => {
+ const location = screen.getByTestId('location').textContent ?? '';
+ expect(location).toContain('/items/b');
+ });
+ expect(screen.getByTestId('location').textContent).toContain('q=a');
+ });
+
+ it('opens the sheet listbox when the position button is clicked', async () => {
+ const user = userEvent.setup();
+ renderToolbar({ currentId: 'c' });
+
+ await user.click(screen.getByRole('button', { name: /3\/4/ }));
+
+ const listbox = await screen.findByRole('listbox', { name: 'Items' });
+ expect(listbox).toBeInTheDocument();
+ expect(within(listbox).getAllByRole('option')).toHaveLength(4);
+ });
+
+ it('narrows the listbox to filtered items', async () => {
+ const user = userEvent.setup();
+ // "pha" matches only "Alpha" — substring is case-insensitive and
+ // diacritic-insensitive (see lib/table-filter tests).
+ renderToolbar({ currentId: 'a', filter: 'pha' });
+
+ await user.click(screen.getByRole('button', { name: /1\/1/ }));
+
+ const listbox = await screen.findByRole('listbox', { name: 'Items' });
+ const labels = within(listbox)
+ .getAllByRole('option')
+ .map((option) => option.textContent ?? '');
+ expect(labels).toEqual(['Alpha']);
+ });
+
+ it('marks the current item with aria-selected and font-medium', async () => {
+ const user = userEvent.setup();
+ renderToolbar({ currentId: 'c' });
+
+ await user.click(screen.getByRole('button', { name: /3\/4/ }));
+
+ const listbox = await screen.findByRole('listbox');
+ const current = within(listbox).getByRole('option', { selected: true });
+ expect(current).toHaveAttribute('data-item-id', 'c');
+ });
+
+ it('applies roving tabIndex — only the current option is focusable', async () => {
+ const user = userEvent.setup();
+ renderToolbar({ currentId: 'c' });
+
+ await user.click(screen.getByRole('button', { name: /3\/4/ }));
+
+ const listbox = await screen.findByRole('listbox');
+ const options = within(listbox).getAllByRole('option');
+
+ // Wait for the open-time roving focus to land on the current entry.
+ await waitFor(() => {
+ const focusable = options.filter((option) => option.getAttribute('tabindex') === '0');
+ expect(focusable).toHaveLength(1);
+ expect(focusable[0]).toHaveAttribute('data-item-id', 'c');
+ });
+
+ const nonFocusable = options.filter((option) => option.getAttribute('tabindex') === '-1');
+ expect(nonFocusable.length).toBe(options.length - 1);
+ });
+
+ it('ArrowDown moves roving focus to the next option', async () => {
+ const user = userEvent.setup();
+ renderToolbar({ currentId: 'b' });
+
+ await user.click(screen.getByRole('button', { name: /2\/4/ }));
+
+ const listbox = await screen.findByRole('listbox');
+ await waitFor(() => {
+ const focused = within(listbox)
+ .getAllByRole('option')
+ .find((option) => option.getAttribute('tabindex') === '0');
+ expect(focused).toHaveAttribute('data-item-id', 'b');
+ });
+
+ fireEvent.keyDown(listbox, { key: 'ArrowDown' });
+
+ await waitFor(() => {
+ const focused = within(listbox)
+ .getAllByRole('option')
+ .find((option) => option.getAttribute('tabindex') === '0');
+ expect(focused).toHaveAttribute('data-item-id', 'c');
+ });
+ });
+
+ it('ArrowUp at the first option clamps (no wrap)', async () => {
+ const user = userEvent.setup();
+ renderToolbar({ currentId: 'a' });
+
+ await user.click(screen.getByRole('button', { name: /1\/4/ }));
+
+ const listbox = await screen.findByRole('listbox');
+ await waitFor(() => {
+ const focused = within(listbox)
+ .getAllByRole('option')
+ .find((option) => option.getAttribute('tabindex') === '0');
+ expect(focused).toHaveAttribute('data-item-id', 'a');
+ });
+
+ fireEvent.keyDown(listbox, { key: 'ArrowUp' });
+
+ // Focus stays on the first option — no wrap-around.
+ const focused = within(listbox)
+ .getAllByRole('option')
+ .find((option) => option.getAttribute('tabindex') === '0');
+ expect(focused).toHaveAttribute('data-item-id', 'a');
+ });
+
+ it('End jumps roving focus to the last option', async () => {
+ const user = userEvent.setup();
+ renderToolbar({ currentId: 'a' });
+
+ await user.click(screen.getByRole('button', { name: /1\/4/ }));
+
+ const listbox = await screen.findByRole('listbox');
+ fireEvent.keyDown(listbox, { key: 'End' });
+
+ await waitFor(() => {
+ const focused = within(listbox)
+ .getAllByRole('option')
+ .find((option) => option.getAttribute('tabindex') === '0');
+ expect(focused).toHaveAttribute('data-item-id', 'd');
+ });
+ });
+
+ it('Home jumps roving focus to the first option', async () => {
+ const user = userEvent.setup();
+ renderToolbar({ currentId: 'd' });
+
+ await user.click(screen.getByRole('button', { name: /4\/4/ }));
+
+ const listbox = await screen.findByRole('listbox');
+ // Wait for the open-time focus on the current ('d') before issuing Home.
+ await waitFor(() => {
+ const focused = within(listbox)
+ .getAllByRole('option')
+ .find((option) => option.getAttribute('tabindex') === '0');
+ expect(focused).toHaveAttribute('data-item-id', 'd');
+ });
+
+ fireEvent.keyDown(listbox, { key: 'Home' });
+
+ await waitFor(() => {
+ const focused = within(listbox)
+ .getAllByRole('option')
+ .find((option) => option.getAttribute('tabindex') === '0');
+ expect(focused).toHaveAttribute('data-item-id', 'a');
+ });
+ });
+
+ it('clicking an option in the sheet navigates and closes it', async () => {
+ const user = userEvent.setup();
+ renderToolbar({ currentId: 'c' });
+
+ await user.click(screen.getByRole('button', { name: /3\/4/ }));
+
+ const listbox = await screen.findByRole('listbox');
+ await user.click(within(listbox).getByRole('option', { name: 'Alpha' }));
+
+ await waitFor(() => {
+ expect(screen.queryByRole('listbox', { name: 'Items' })).not.toBeInTheDocument();
+ });
+ expect(screen.getByTestId('location').textContent).toContain('/items/a');
+ });
+
+ it('disables the position button when the filter excludes every item', () => {
+ renderToolbar({ currentId: 'c', filter: 'qqqqqqqqq' });
+
+ // With nothing to navigate to, the sheet trigger is disabled — the
+ // empty-state copy lives inside the sheet but the button gating
+ // prevents opening it in the first place.
+ const positionButton = screen.getByRole('button', { name: /–\/0/ });
+ expect(positionButton).toBeDisabled();
+ });
+
+ it('falls back to the first filtered option when current is outside the subset', async () => {
+ const user = userEvent.setup();
+ renderToolbar({ currentId: 'zzz' });
+
+ await user.click(screen.getByRole('button', { name: /–\/4/ }));
+
+ const listbox = await screen.findByRole('listbox');
+ await waitFor(() => {
+ const focused = within(listbox)
+ .getAllByRole('option')
+ .find((option) => option.getAttribute('tabindex') === '0');
+ expect(focused).toHaveAttribute('data-item-id', 'a');
+ });
+ });
+});
+
+describe('ListNavigationToolbar — predicate stability', () => {
+ it('updates the filtered subset when the filter prop changes', async () => {
+ const user = userEvent.setup();
+
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter initialEntries={['/items/a']}>
+ <TooltipProvider>
+ <Routes>
+ <Route
+ element={<>{children}</>}
+ path="/items/:id"
+ />
+ </Routes>
+ </TooltipProvider>
+ </MemoryRouter>
+ );
+
+ const { rerender } = render(
+ <ListNavigationToolbar<Item>
+ currentId="a"
+ filter=""
+ getHref={getHref}
+ getId={getId}
+ getLabel={getLabel}
+ items={ITEMS}
+ sheetTitle="Items"
+ />,
+ { wrapper: Wrapper },
+ );
+
+ expect(screen.getByRole('button', { name: /1\/4/ })).toBeInTheDocument();
+
+ rerender(
+ <ListNavigationToolbar<Item>
+ currentId="a"
+ filter="Alpha"
+ getHref={getHref}
+ getId={getId}
+ getLabel={getLabel}
+ items={ITEMS}
+ sheetTitle="Items"
+ />,
+ );
+
+ expect(screen.getByRole('button', { name: /1\/1/ })).toBeInTheDocument();
+ await act(async () => {
+ await user.tab();
+ });
+ });
+});
diff --git a/frontend/src/components/shared/list-navigation-toolbar.tsx b/frontend/src/components/shared/list-navigation-toolbar.tsx
new file mode 100644
index 00000000..8c0eea9d
--- /dev/null
+++ b/frontend/src/components/shared/list-navigation-toolbar.tsx
@@ -0,0 +1,182 @@
+import { type ReactNode, useCallback, useMemo, useState } from 'react';
+import { useNavigate, useSearchParams } from 'react-router-dom';
+
+import { ListNavigationButtons } from '@/components/shared/list-navigation-buttons';
+import { ListNavigationSheet } from '@/components/shared/list-navigation-sheet';
+import { useFilteredListNavigation } from '@/hooks/use-filtered-list-navigation';
+import { mergeHrefWithSearchParams } from '@/lib/url-params';
+
+export interface ListNavigationToolbarProps<T> {
+ currentId: null | string | undefined;
+ /**
+ * Current free-text filter the list page applies. The toolbar narrows the
+ * navigable subset by running the same `matchesTextFilter` semantics the
+ * list uses — so Prev/Next never drifts out of sync with what the user
+ * sees in the table.
+ */
+ filter: string;
+ /**
+ * Build a navigation target for the given item. The current value of
+ * `?<filterParamName>=` is forwarded so detail-page navigation preserves
+ * the filter the user picked on the list.
+ */
+ getHref: (item: T) => string;
+ /**
+ * Stable accessor for the row's ID. The toolbar uses it for keying both
+ * the navigation lookup and the rendered Sheet list.
+ */
+ getId: (item: T) => string;
+ /**
+ * Default label for items in the Sheet list. Used when `renderItem` is
+ * not provided. Also acts as the default haystack for the filter when
+ * `getSearchableText` is omitted (matches the common case where the list
+ * column filter targets the same field as the label).
+ */
+ getLabel: (item: T) => string;
+ /**
+ * Optional override for the haystack the filter runs against. Pass when
+ * the list column filter is keyed on a different field than the visible
+ * label (e.g. label is `title || #id`, filter is plain `title`).
+ */
+ getSearchableText?: (item: T) => null | string | undefined;
+ items: readonly T[];
+ /**
+ * Optional override for the row in the Sheet. Receives the item and a
+ * boolean indicating whether it's the current detail page.
+ */
+ renderItem?: (item: T, isCurrent: boolean) => ReactNode;
+ sheetIcon?: ReactNode;
+ sheetTitle: string;
+ /** Optional comparator. When omitted, items appear in input order. */
+ sortFn?: (a: T, b: T) => number;
+}
+
+/**
+ * Prev / Position / Next toolbar shown on detail pages whose list page
+ * supports a free-text filter.
+ *
+ * - "Prev" / "Next" walk the same filtered subset the list page renders.
+ * - The middle button opens `<ListNavigationSheet>`, a listbox of every
+ * entry in the filtered subset with the current one highlighted — the
+ * user can jump anywhere in one click.
+ * - When the current item is missing from the filtered subset (e.g. the
+ * server-loaded record doesn't match the active filter, or the record
+ * was just deleted) prev/next are disabled and the position label falls
+ * back to `"–/total"` so the user can still open the Sheet to pick a
+ * neighbour.
+ * - Sibling navigation uses `replace: true` so paging through a list of 50
+ * items doesn't push 50 history entries the user has to back through.
+ *
+ * Returns `null` when there are no items at all — there's nothing useful to
+ * render and a "–/0" disabled toolbar would just be visual noise.
+ */
+export function ListNavigationToolbar<T>({
+ currentId,
+ filter,
+ getHref,
+ getId,
+ getLabel,
+ getSearchableText,
+ items,
+ renderItem,
+ sheetIcon,
+ sheetTitle,
+ sortFn,
+}: ListNavigationToolbarProps<T>) {
+ const navigate = useNavigate();
+ const [searchParams] = useSearchParams();
+ const [isSheetOpen, setIsSheetOpen] = useState(false);
+
+ // The toolbar owns the haystack-resolution rule so list and detail always
+ // agree on what "matches the filter" means — callers only describe the
+ // data shape (`getSearchableText` / `getLabel`), never the comparison.
+ const haystack = getSearchableText ?? getLabel;
+
+ const { currentIndex, filteredItems, nextId, prevId, total } = useFilteredListNavigation({
+ currentId,
+ getId,
+ getSearchableText: haystack,
+ items,
+ query: filter,
+ sortFn,
+ });
+
+ // Forward the current filter (and any other URL state) when navigating
+ // to a sibling — without it the user would lose `?q=` the moment they
+ // hit Prev/Next, breaking the "stay inside the filtered subset" promise.
+ // `mergeHrefWithSearchParams` round-trips through `URL` so the hash
+ // fragment survives and getHref's own query params win on collision.
+ const buildHref = useCallback(
+ (item: T) => mergeHrefWithSearchParams(getHref(item), searchParams),
+ [getHref, searchParams],
+ );
+
+ const goTo = useCallback(
+ (id: null | string) => {
+ if (!id) {
+ return;
+ }
+
+ const target = filteredItems.find((item) => String(getId(item)) === id);
+
+ if (!target) {
+ return;
+ }
+
+ navigate(buildHref(target), { replace: true });
+ },
+ [buildHref, filteredItems, getId, navigate],
+ );
+
+ const handleItemSelect = useCallback(
+ (item: T) => {
+ setIsSheetOpen(false);
+ navigate(buildHref(item), { replace: true });
+ },
+ [buildHref, navigate],
+ );
+
+ const goToPrev = useCallback(() => goTo(prevId), [goTo, prevId]);
+ const goToNext = useCallback(() => goTo(nextId), [goTo, nextId]);
+ const openSheet = useCallback(() => setIsSheetOpen(true), []);
+
+ const positionLabel = useMemo(
+ () => (total === 0 || currentIndex === -1 ? `–/${total}` : `${currentIndex + 1}/${total}`),
+ [currentIndex, total],
+ );
+
+ // Nothing meaningful to render before items show up — saves the user from
+ // a momentary "–/0" flash while the parent provider's data is in flight.
+ if (items.length === 0) {
+ return null;
+ }
+
+ return (
+ <>
+ <ListNavigationButtons
+ hasEntries={total > 0}
+ nextDisabled={!nextId}
+ onNext={goToNext}
+ onOpen={openSheet}
+ onPrev={goToPrev}
+ positionLabel={positionLabel}
+ prevDisabled={!prevId}
+ sheetTitle={sheetTitle}
+ />
+ <ListNavigationSheet<T>
+ currentId={currentId}
+ currentIndex={currentIndex}
+ getId={getId}
+ getLabel={getLabel}
+ items={filteredItems}
+ onItemSelect={handleItemSelect}
+ onOpenChange={setIsSheetOpen}
+ open={isSheetOpen}
+ renderItem={renderItem}
+ sheetIcon={sheetIcon}
+ sheetTitle={sheetTitle}
+ total={total}
+ />
+ </>
+ );
+}
diff --git a/frontend/src/components/shared/sortable-column-header.tsx b/frontend/src/components/shared/sortable-column-header.tsx
new file mode 100644
index 00000000..34ad124f
--- /dev/null
+++ b/frontend/src/components/shared/sortable-column-header.tsx
@@ -0,0 +1,44 @@
+import type { Column } from '@tanstack/react-table';
+import type { ReactNode } from 'react';
+
+import { ArrowDown, ArrowUp } from 'lucide-react';
+
+import { Button } from '@/components/ui/button';
+import { cycleColumnSort } from '@/lib/table-sort';
+
+interface SortableColumnHeaderProps<TData, TValue> {
+ /** TanStack column. Sorting state and the cycle action both target it. */
+ column: Column<TData, TValue>;
+ /** Visible label rendered as the button text. */
+ label: ReactNode;
+}
+
+/**
+ * Reusable header for sortable `DataTable` columns. Wraps the conventional
+ * "label + asc/desc arrow + onClick → cycleColumnSort" pattern so every list
+ * page (Flows, Knowledges, Templates, Settings/*) reuses one component
+ * instead of repeating ~20 lines per column header.
+ *
+ * The header reads sort direction directly from `column.getIsSorted()` so the
+ * caller does not have to plumb it. The arrow icon mirrors the TanStack
+ * convention: `asc` shows ↓ ("ascending continues to grow downward") and
+ * `desc` shows ↑. No arrow means "not sorted by this column".
+ */
+export function SortableColumnHeader<TData, TValue = unknown>({
+ column,
+ label,
+}: SortableColumnHeaderProps<TData, TValue>) {
+ const sorted = column.getIsSorted();
+
+ return (
+ <Button
+ className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
+ onClick={() => cycleColumnSort(column)}
+ variant="link"
+ >
+ {label}
+ {sorted === 'asc' ? <ArrowDown className="size-4" /> : null}
+ {sorted === 'desc' ? <ArrowUp className="size-4" /> : null}
+ </Button>
+ );
+}
diff --git a/frontend/src/components/ui/data-table.test.tsx b/frontend/src/components/ui/data-table.test.tsx
new file mode 100644
index 00000000..3ebe48cd
--- /dev/null
+++ b/frontend/src/components/ui/data-table.test.tsx
@@ -0,0 +1,241 @@
+import type { ColumnDef } from '@tanstack/react-table';
+import type { ReactNode } from 'react';
+
+import { fireEvent, render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter } from 'react-router-dom';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TooltipProvider } from '@/components/ui/tooltip';
+
+import { DataTable } from './data-table';
+
+interface Row {
+ id: string;
+ name: string;
+}
+
+const ROWS: Row[] = [
+ { id: 'a', name: 'Alpha' },
+ { id: 'b', name: 'Bravo' },
+ { id: 'c', name: 'Charlie' },
+];
+
+const COLUMNS: ColumnDef<Row>[] = [
+ { accessorKey: 'id', header: 'ID' },
+ { accessorKey: 'name', filterFn: 'includesString', header: 'Name' },
+];
+
+const Wrapper = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter initialEntries={['/flows']}>
+ <TooltipProvider>{children}</TooltipProvider>
+ </MemoryRouter>
+);
+
+beforeEach(() => {
+ localStorage.clear();
+});
+
+afterEach(() => {
+ localStorage.clear();
+});
+
+describe('DataTable — controlled filter projection', () => {
+ it('projects `filterValue` into the visible rows when a `filterColumn` is set', () => {
+ render(
+ <DataTable<Row>
+ columns={COLUMNS}
+ data={ROWS}
+ filterColumn="name"
+ filterValue="Bravo"
+ onFilterChange={() => {
+ /* no-op */
+ }}
+ />,
+ { wrapper: Wrapper },
+ );
+
+ // The body shows only "Bravo" — Alpha and Charlie are filtered out.
+ expect(screen.getByText('Bravo')).toBeInTheDocument();
+ expect(screen.queryByText('Alpha')).not.toBeInTheDocument();
+ expect(screen.queryByText('Charlie')).not.toBeInTheDocument();
+ });
+
+ it('renders the empty filter as "all rows visible"', () => {
+ render(
+ <DataTable<Row>
+ columns={COLUMNS}
+ data={ROWS}
+ filterColumn="name"
+ filterValue=""
+ onFilterChange={() => {
+ /* no-op */
+ }}
+ />,
+ { wrapper: Wrapper },
+ );
+
+ expect(screen.getByText('Alpha')).toBeInTheDocument();
+ expect(screen.getByText('Bravo')).toBeInTheDocument();
+ expect(screen.getByText('Charlie')).toBeInTheDocument();
+ });
+
+ it('invokes `onFilterChange` with the typed value as the user edits the input', async () => {
+ const onFilterChange = vi.fn();
+ const user = userEvent.setup();
+
+ render(
+ <DataTable<Row>
+ columns={COLUMNS}
+ data={ROWS}
+ filterColumn="name"
+ filterPlaceholder="Filter name..."
+ filterValue=""
+ onFilterChange={onFilterChange}
+ />,
+ { wrapper: Wrapper },
+ );
+
+ const input = screen.getByPlaceholderText('Filter name...');
+ await user.type(input, 'al');
+
+ // userEvent fires keystroke-by-keystroke; the last call carries the
+ // full input — controlled-mode parents receive every intermediate
+ // value because the input is controlled by the column filter API.
+ expect(onFilterChange).toHaveBeenCalled();
+ const lastCall = onFilterChange.mock.calls.at(-1);
+ expect(lastCall?.[0]).toBe('l');
+ });
+
+ it('clears the filter when the trailing X button is clicked', async () => {
+ const onFilterChange = vi.fn();
+ const user = userEvent.setup();
+
+ render(
+ <DataTable<Row>
+ columns={COLUMNS}
+ data={ROWS}
+ filterColumn="name"
+ filterPlaceholder="Filter..."
+ filterValue="Alpha"
+ onFilterChange={onFilterChange}
+ />,
+ { wrapper: Wrapper },
+ );
+
+ // The clear button is rendered only when the filter has content.
+ const input = screen.getByPlaceholderText('Filter...');
+ const inputGroup = input.closest('[data-slot="input-group"]');
+ expect(inputGroup).not.toBeNull();
+ const clearButton = within(inputGroup as HTMLElement).getByRole('button');
+
+ await user.click(clearButton);
+
+ expect(onFilterChange).toHaveBeenCalledWith('');
+ });
+});
+
+describe('DataTable — uncontrolled filter is still routed through the same input', () => {
+ it('falls back to internal column filter state when `filterValue` is omitted', async () => {
+ const user = userEvent.setup();
+ render(
+ <DataTable<Row>
+ columns={COLUMNS}
+ data={ROWS}
+ filterColumn="name"
+ filterPlaceholder="Filter..."
+ />,
+ { wrapper: Wrapper },
+ );
+
+ const input = screen.getByPlaceholderText('Filter...');
+ await user.type(input, 'Bra');
+
+ // The input is uncontrolled here — TanStack reflects the value back
+ // via `column.getFilterValue()`, and only matching rows survive.
+ expect(screen.getByText('Bravo')).toBeInTheDocument();
+ expect(screen.queryByText('Alpha')).not.toBeInTheDocument();
+ });
+});
+
+describe('DataTable — does not render the filter input when `filterColumn` is omitted', () => {
+ it('hides the search input entirely', () => {
+ render(
+ <DataTable<Row>
+ columns={COLUMNS}
+ data={ROWS}
+ />,
+ { wrapper: Wrapper },
+ );
+
+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument();
+ });
+});
+
+describe('DataTable — sorting state persists to storage', () => {
+ it('writes a sorting entry to the unified `table_4_<path>` slot after the user sorts', () => {
+ const user = userEvent.setup();
+ render(
+ <DataTable<Row>
+ columns={[
+ {
+ accessorKey: 'name',
+ enableSorting: true,
+ header: ({ column }) => (
+ <button
+ onClick={() => column.toggleSorting(false)}
+ type="button"
+ >
+ Name
+ </button>
+ ),
+ },
+ ]}
+ data={ROWS}
+ />,
+ { wrapper: Wrapper },
+ );
+
+ const sortButton = screen.getByRole('button', { name: 'Name' });
+ fireEvent.click(sortButton);
+
+ const stored = JSON.parse(localStorage.getItem('table_4_/flows') ?? '{}');
+ expect(stored.sorting).toEqual([{ desc: false, id: 'name' }]);
+ // ESLint will yell about `user` being unused if we remove the import.
+ void user;
+ });
+});
+
+describe('DataTable — empty results', () => {
+ it('does not render "Page 1 of 0" when there are no rows', () => {
+ render(
+ <DataTable<Row>
+ columns={COLUMNS}
+ data={[]}
+ />,
+ { wrapper: Wrapper },
+ );
+
+ expect(screen.queryByText(/Page 1 of 0/)).not.toBeInTheDocument();
+ expect(screen.getByText('No results')).toBeInTheDocument();
+ });
+
+ it('exposes name and id on the filter field when filterColumn is set', () => {
+ render(
+ <DataTable<Row>
+ columns={COLUMNS}
+ data={ROWS}
+ filterColumn="name"
+ filterValue=""
+ onFilterChange={() => {
+ /* no-op */
+ }}
+ />,
+ { wrapper: Wrapper },
+ );
+
+ const input = screen.getByRole('textbox');
+ expect(input).toHaveAttribute('name', 'name');
+ expect(input).toHaveAttribute('id', 'data-table-filter-name');
+ });
+});
diff --git a/frontend/src/components/ui/data-table.tsx b/frontend/src/components/ui/data-table.tsx
index 084d9d6f..b182fc4d 100644
--- a/frontend/src/components/ui/data-table.tsx
+++ b/frontend/src/components/ui/data-table.tsx
@@ -1,4 +1,5 @@
import {
+ type Column,
type ColumnDef,
type ColumnFiltersState,
type ExpandedState,
@@ -11,11 +12,13 @@ import {
type Table as ReactTable,
type Row,
type SortingState,
+ type Updater,
useReactTable,
type VisibilityState,
} from '@tanstack/react-table';
import { ChevronDown, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight, Search, X } from 'lucide-react';
-import { Fragment, type ReactElement, type ReactNode, useCallback, useMemo, useRef, useState } from 'react';
+import { Fragment, type ReactElement, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useLocation } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from '@/components/ui/context-menu';
@@ -29,26 +32,36 @@ import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { useEffectAfterMount } from '@/hooks/use-effect-after-mount';
-import { getColumnStorageKey, getPageStorageKey, getSortingStorageKey } from '@/lib/storage-keys';
-import {
- loadColumnVisibility,
- loadPageState,
- loadSorting,
- saveColumnVisibility,
- savePageState,
- saveSorting,
-} from '@/lib/table-storage';
+import { useLatestRef } from '@/hooks/use-latest-ref';
+import { usePageStorageKeys } from '@/hooks/use-page-storage-keys';
+import { migrateLegacyTableState, updateTableState } from '@/lib/table-state';
import { cn } from '@/lib/utils';
interface DataTableProps<TData, TValue = unknown> {
columns: ColumnDef<TData, TValue>[];
columnVisibility?: VisibilityState;
data: TData[];
+ /**
+ * Column id targeted by the search input. When omitted, the search input
+ * is not rendered — useful for tables where filtering is unnecessary
+ * (e.g. tooling subscreens that already filter server-side, or small
+ * static lists). When provided, the column id must exist in `columns`.
+ */
filterColumn?: string;
filterPlaceholder?: string;
+ /**
+ * Controlled filter value. When provided together with `onFilterChange`
+ * the parent owns the source of truth — typically `useTableQueryFilter`
+ * for URL/storage-backed filters. The value is projected into
+ * `state.columnFilters` and surfaces through TanStack's filter API just
+ * like an uncontrolled value would, so `DataTableFilter` and the column
+ * filter machinery never need to branch on controlled vs uncontrolled.
+ */
+ filterValue?: string;
initialPageSize?: number;
initialSorting?: SortingState;
onColumnVisibilityChange?: (visibility: VisibilityState) => void;
+ onFilterChange?: (value: string) => void;
onPageChange?: (pageIndex: number) => void;
onRowClick?: (row: TData) => void;
pageIndex?: number;
@@ -58,6 +71,14 @@ interface DataTableProps<TData, TValue = unknown> {
const PAGE_SIZE_OPTIONS = [10, 15, 20, 50, 100] as const;
+const columnPickerLabel = <TData,>(column: Column<TData, unknown>): string =>
+ column.columnDef.meta?.columnMenuLabel ?? column.id;
+
+// Shared empty array for the controlled-filter projection. Using a module
+// constant keeps the reference stable across renders so the memoized
+// `controlledColumnFilters` doesn't flap between two distinct empty arrays.
+const EMPTY_COLUMN_FILTERS: ColumnFiltersState = [];
+
interface DataTableFilterProps<TData> {
column: string;
placeholder: string;
@@ -65,14 +86,15 @@ interface DataTableFilterProps<TData> {
}
/**
- * Search input bound to a single TanStack Table column. Reads/writes the column's
- * filter value directly — purely cosmetic shell around the table's existing
- * filter API. Extracted out of `DataTable` so the toolbar JSX doesn't have to
- * inline an IIFE just to capture the current `filterValue` once.
+ * Search input bound to a single TanStack Table column. Reads/writes through
+ * the column's filter API exclusively — `DataTable`'s `onColumnFiltersChange`
+ * funnels the write to the parent (`onFilterChange`) when the table is in
+ * controlled-filter mode, so this component stays uniform regardless.
*/
const DataTableFilter = <TData,>({ column, placeholder, table }: DataTableFilterProps<TData>) => {
const tableColumn = table.getColumn(column);
const filterValue = (tableColumn?.getFilterValue() as string) ?? '';
+ const fieldId = `data-table-filter-${column}`;
return (
<InputGroup className="max-w-sm">
@@ -80,7 +102,10 @@ const DataTableFilter = <TData,>({ column, placeholder, table }: DataTableFilter
<Search />
</InputGroupAddon>
<InputGroupInput
+ aria-label={placeholder}
autoComplete="off"
+ id={fieldId}
+ name={column}
onChange={(event) => tableColumn?.setFilterValue(event.target.value)}
placeholder={placeholder}
type="text"
@@ -104,11 +129,13 @@ function DataTable<TData, TValue = unknown>({
columns,
columnVisibility: externalColumnVisibility,
data,
- filterColumn = 'name',
+ filterColumn,
filterPlaceholder = 'Filter...',
+ filterValue: externalFilterValue,
initialPageSize = 10,
initialSorting = [],
onColumnVisibilityChange,
+ onFilterChange,
onPageChange,
onRowClick,
pageIndex: externalPageIndex,
@@ -117,46 +144,117 @@ function DataTable<TData, TValue = unknown>({
}: DataTableProps<TData, TValue>) {
const isColumnVisibilityControlled = externalColumnVisibility !== undefined;
const isPageControlled = externalPageIndex !== undefined;
+ const isFilterControlled = externalFilterValue !== undefined && onFilterChange !== undefined;
const isRowInteractive = !!onRowClick || !!renderSubComponent;
- const sortingKey = useMemo(() => getSortingStorageKey(), []);
- const columnKey = useMemo(() => getColumnStorageKey(), []);
- const pageKey = useMemo(() => getPageStorageKey(), []);
+ const { pathname } = useLocation();
+ // Reuse the pathname we just read instead of letting the hook subscribe
+ // independently — react-router caches `useLocation` so the cost is
+ // negligible, but the explicit pass keeps the data flow obvious and
+ // makes it easy to migrate the table to a different storage scope (e.g.
+ // a workspace-prefixed path) without grepping for every subscription.
+ const { table: tableKey } = usePageStorageKeys({ pathname });
+
+ // Run the legacy → unified migration exactly once on mount via `useState`
+ // lazy init. The lazy initializer runs in a single commit, so the
+ // localStorage hit happens once even under StrictMode's double-invoke.
+ // After mount, the `useEffect` below re-runs migration when `tableKey`
+ // rotates (route change inside a persistent layout).
+ const [initialState] = useState(() => migrateLegacyTableState(pathname, tableKey));
- const [sorting, setSorting] = useState<SortingState>(() => loadSorting(sortingKey) ?? initialSorting);
- const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
+ const [sorting, setSorting] = useState<SortingState>(() => initialState.sorting ?? initialSorting);
+ const [internalColumnFilters, setInternalColumnFilters] = useState<ColumnFiltersState>([]);
+ const [internalColumnVisibility, setInternalColumnVisibility] = useState<VisibilityState>(() =>
+ isColumnVisibilityControlled ? {} : (initialState.columnVisibility ?? {}),
+ );
+ const [pagination, setPagination] = useState(() => ({
+ pageIndex: isPageControlled ? (externalPageIndex ?? 0) : 0,
+ pageSize: initialState.pageSize ?? initialPageSize,
+ }));
const [rowSelection, setRowSelection] = useState({});
const [expanded, setExpanded] = useState<ExpandedState>({});
- const [internalColumnVisibility, setInternalColumnVisibility] = useState<VisibilityState>(() =>
- isColumnVisibilityControlled ? {} : (loadColumnVisibility(columnKey) ?? {}),
+ // Track which tableKey we've already migrated + seeded from. When the
+ // key rotates (route change inside a persistent layout, or an explicit
+ // override) we re-run the migration for the new path and refresh local
+ // state with whatever's stored under the new key.
+ const seededForKeyReference = useRef(tableKey);
+
+ useEffect(() => {
+ if (seededForKeyReference.current === tableKey) {
+ return;
+ }
+
+ seededForKeyReference.current = tableKey;
+ const stored = migrateLegacyTableState(pathname, tableKey);
+
+ setSorting(stored.sorting ?? initialSorting);
+
+ if (!isColumnVisibilityControlled) {
+ setInternalColumnVisibility(stored.columnVisibility ?? {});
+ }
+
+ setPagination((previous) => ({
+ ...previous,
+ pageSize: stored.pageSize ?? initialPageSize,
+ }));
+ }, [initialPageSize, initialSorting, isColumnVisibilityControlled, pathname, tableKey]);
+
+ // Project the controlled filter value into TanStack's columnFilters shape.
+ // Kept separate from `internalColumnFilters` so the controlled branch
+ // doesn't pull internal state into its deps and trigger spurious memo
+ // invalidations. Memoized so the reference is stable across renders when
+ // the inputs don't change — otherwise TanStack treats every render as a
+ // filter mutation and the downstream `useLatestRef(columnFilters)` would
+ // re-fire its effect each commit.
+ const controlledColumnFilters = useMemo<ColumnFiltersState>(
+ () =>
+ isFilterControlled && filterColumn && externalFilterValue
+ ? [{ id: filterColumn, value: externalFilterValue }]
+ : EMPTY_COLUMN_FILTERS,
+ [externalFilterValue, filterColumn, isFilterControlled],
);
- const [pagination, setPagination] = useState(() => {
- const stored = loadPageState(pageKey);
+ const columnFilters = isFilterControlled ? controlledColumnFilters : internalColumnFilters;
- return {
- pageIndex: isPageControlled ? (externalPageIndex ?? 0) : (stored?.page ?? 0),
- pageSize: stored?.pageSize ?? initialPageSize,
- };
- });
+ const columnFiltersReference = useLatestRef(columnFilters);
+
+ // Funnel every TanStack filter change through the right sink: parent
+ // callback in controlled mode, internal state otherwise.
+ const handleColumnFiltersChange = useCallback(
+ (updater: Updater<ColumnFiltersState>) => {
+ if (!isFilterControlled) {
+ setInternalColumnFilters(updater);
+ return;
+ }
+
+ const next = typeof updater === 'function' ? updater(columnFiltersReference.current) : updater;
+ const entry = filterColumn ? next.find((candidate) => candidate.id === filterColumn) : undefined;
+ onFilterChange?.((entry?.value as string) ?? '');
+ },
+ [columnFiltersReference, filterColumn, isFilterControlled, onFilterChange],
+ );
+
+ // Persist sorting + column visibility + page size into the unified
+ // `table_4_<path>` slot. Skipping the first render is intentional: a
+ // fresh mount would otherwise overwrite the seeded values with the
+ // same payload on the next commit.
useEffectAfterMount(() => {
- saveSorting(sortingKey, sorting);
- }, [sorting, sortingKey]);
+ updateTableState(tableKey, { sorting });
+ }, [sorting, tableKey]);
useEffectAfterMount(() => {
- if (!isColumnVisibilityControlled) {
- saveColumnVisibility(columnKey, internalColumnVisibility);
+ if (isColumnVisibilityControlled) {
+ return;
}
- }, [internalColumnVisibility, columnKey, isColumnVisibilityControlled]);
+
+ updateTableState(tableKey, { columnVisibility: internalColumnVisibility });
+ }, [internalColumnVisibility, isColumnVisibilityControlled, tableKey]);
useEffectAfterMount(() => {
- savePageState(pageKey, {
- page: isPageControlled ? 0 : pagination.pageIndex,
- pageSize: pagination.pageSize,
- });
- }, [pagination.pageIndex, pagination.pageSize, pageKey, isPageControlled]);
+ updateTableState(tableKey, { pageSize: pagination.pageSize });
+ }, [pagination.pageSize, tableKey]);
const columnVisibility = externalColumnVisibility ?? internalColumnVisibility;
@@ -187,8 +285,7 @@ function DataTable<TData, TValue = unknown>({
setPagination({ pageIndex: 0, pageSize: newPageSize });
}, []);
- const paginationReference = useRef(pagination);
- paginationReference.current = pagination;
+ const paginationReference = useLatestRef(pagination);
const handlePaginationChange = useCallback(
(
@@ -204,7 +301,7 @@ function DataTable<TData, TValue = unknown>({
onPageChange(newPagination.pageIndex);
}
},
- [onPageChange],
+ [onPageChange, paginationReference],
);
const table = useReactTable({
@@ -217,7 +314,7 @@ function DataTable<TData, TValue = unknown>({
getFilteredRowModel: getFilteredRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
- onColumnFiltersChange: setColumnFilters,
+ onColumnFiltersChange: handleColumnFiltersChange,
onColumnVisibilityChange: handleColumnVisibilityChange,
onExpandedChange: setExpanded,
onPaginationChange: handlePaginationChange,
@@ -249,6 +346,7 @@ function DataTable<TData, TValue = unknown>({
const totalRows = table.getFilteredRowModel().rows.length;
const rangeStart = totalRows > 0 ? pagination.pageIndex * pagination.pageSize + 1 : 0;
const rangeEnd = Math.min((pagination.pageIndex + 1) * pagination.pageSize, totalRows);
+ const pageCount = table.getPageCount();
return (
<div className="w-full">
@@ -276,12 +374,12 @@ function DataTable<TData, TValue = unknown>({
.map((column) => (
<DropdownMenuCheckboxItem
checked={column.getIsVisible()}
- className="capitalize"
+ className={column.columnDef.meta?.columnMenuLabel ? undefined : 'capitalize'}
key={column.id}
onCheckedChange={(value) => column.toggleVisibility(!!value)}
onSelect={(event) => event.preventDefault()}
>
- {column.id}
+ {columnPickerLabel(column)}
</DropdownMenuCheckboxItem>
))}
</DropdownMenuContent>
@@ -424,9 +522,16 @@ function DataTable<TData, TValue = unknown>({
</SelectContent>
</Select>
</div>
- <div className="flex items-center justify-center text-xs font-medium lg:w-20">
- Page {pagination.pageIndex + 1} of {table.getPageCount()}
- </div>
+ {pageCount > 0 ? (
+ <div className="flex items-center justify-center text-xs font-medium lg:w-20">
+ Page {pagination.pageIndex + 1} of {pageCount}
+ </div>
+ ) : (
+ <div
+ aria-hidden
+ className="lg:w-20"
+ />
+ )}
<div className="flex items-center gap-1">
<Button
disabled={!table.getCanPreviousPage()}
diff --git a/frontend/src/features/flows/use-flow-detail-navigation.ts b/frontend/src/features/flows/use-flow-detail-navigation.ts
new file mode 100644
index 00000000..6847a451
--- /dev/null
+++ b/frontend/src/features/flows/use-flow-detail-navigation.ts
@@ -0,0 +1,29 @@
+import { useDetailNavigation } from '@/hooks/use-detail-navigation';
+import { type Flow, useFlows } from '@/providers/flows-provider';
+
+const getLabel = (item: Flow) => item.title || `Flow #${item.id}`;
+const getSearchableText = (item: Flow) => item.title;
+const getId = (item: Flow) => String(item.id);
+const getHref = (item: Flow) => `/flows/${item.id}`;
+
+/**
+ * Detail-page navigation wired up for flows. Encapsulates the getter
+ * callbacks and the call to `useDetailNavigation` so each detail page just
+ * spreads the returned `toolbarProps` onto `<ListNavigationToolbar<Flow>>`
+ * and adds the presentation-only props (`sheetTitle`, `renderItem`, etc.).
+ *
+ * Pass `null` instead of an id while the page is in a non-viewing state
+ * (e.g. `/flows/new`) so the toolbar reports an unmatched current item.
+ */
+export const useFlowDetailNavigation = (currentId: null | string | undefined) => {
+ const { flows } = useFlows();
+
+ return useDetailNavigation<Flow>({
+ currentId,
+ getHref,
+ getId,
+ getLabel,
+ getSearchableText,
+ items: flows,
+ });
+};
diff --git a/frontend/src/features/knowledges/knowledge-header.tsx b/frontend/src/features/knowledges/knowledge-header.tsx
index c1e5d7c6..26f4d1fc 100644
--- a/frontend/src/features/knowledges/knowledge-header.tsx
+++ b/frontend/src/features/knowledges/knowledge-header.tsx
@@ -1,13 +1,16 @@
import type { ReactNode } from 'react';
-import { Check, Ellipsis, LibraryBig, Loader2, Pencil, Trash, X } from 'lucide-react';
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { Ellipsis, LibraryBig, Loader2, Pencil, Trash } from 'lucide-react';
+import { useCallback, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import type { KnowledgeDocumentFragmentFragment } from '@/graphql/types';
import ConfirmationDialog from '@/components/shared/confirmation-dialog';
+import { InlineRenameInput } from '@/components/shared/inline-rename-input';
+import { ListNavigationToolbar } from '@/components/shared/list-navigation-toolbar';
+import { Badge } from '@/components/ui/badge';
import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage } from '@/components/ui/breadcrumb';
import { Button } from '@/components/ui/button';
import {
@@ -17,11 +20,13 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
-import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';
import { Separator } from '@/components/ui/separator';
import { SidebarTrigger } from '@/components/ui/sidebar';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
-import { useKnowledges } from '@/providers/knowledges-provider';
+import { useInlineEditTitle } from '@/hooks/use-inline-edit-title';
+import { type Knowledge, useKnowledges } from '@/providers/knowledges-provider';
+
+import { useKnowledgeDetailNavigation } from './use-knowledge-detail-navigation';
interface KnowledgeHeaderProps {
isNew: boolean;
@@ -39,13 +44,14 @@ interface KnowledgeHeaderProps {
export const KnowledgeHeader = ({ isNew, knowledge, onBeforeNavigateAway, saveButton }: KnowledgeHeaderProps) => {
const navigate = useNavigate();
const { deleteKnowledge, updateKnowledge } = useKnowledges();
- const [isEditingTitle, setIsEditingTitle] = useState(false);
const [isRenaming, setIsRenaming] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
- const editingInputRef = useRef<HTMLInputElement>(null);
const knowledgeId = knowledge?.id ?? null;
+
+ const { toolbarProps: knowledgeToolbarProps } = useKnowledgeDetailNavigation(knowledgeId);
+
// Title source-of-truth is the server-side `question`. We intentionally do
// not read it from the form draft below — the inline rename flow in this
// header writes through `updateKnowledge`, which refreshes `knowledge` via
@@ -53,44 +59,13 @@ export const KnowledgeHeader = ({ isNew, knowledge, onBeforeNavigateAway, saveBu
const knowledgeName = knowledge?.question ?? null;
const canShowActions = !isNew && !!knowledge;
- // Reset inline-edit state when navigating between documents so the input
- // doesn't carry over a stale draft from a previous document.
- useEffect(() => {
- setIsEditingTitle(false);
- }, [knowledgeId]);
-
- // Focus and select the rename input when the inline editor opens. We can't
- // rely on `autoFocus` here: the input mounts inside the same render cycle
- // that closes the Radix DropdownMenu, and the dropdown's own focus restore
- // (scheduled via `requestAnimationFrame`) wins the race against React's
- // autoFocus effect. Defer our focus to the next frame so it lands *after*
- // Radix has finished its restore.
- useEffect(() => {
- if (!isEditingTitle) {
- return;
- }
-
- const id = requestAnimationFrame(() => {
- const input = editingInputRef.current;
-
- if (!input) {
- return;
- }
-
- input.focus();
- input.select();
- });
-
- return () => cancelAnimationFrame(id);
- }, [isEditingTitle]);
-
- const handleRenameStart = useCallback(() => {
- setIsEditingTitle(true);
- }, []);
-
- const handleRenameCancel = useCallback(() => {
- setIsEditingTitle(false);
- }, []);
+ const {
+ handleDropdownCloseAutoFocus,
+ inputRef: editingInputRef,
+ isEditing: isEditingTitle,
+ startEdit: handleRenameStart,
+ stopEdit: handleRenameCancel,
+ } = useInlineEditTitle({ resetKey: knowledgeId });
const handleRenameSave = useCallback(async () => {
const newQuestion = editingInputRef.current?.value.trim();
@@ -100,7 +75,7 @@ export const KnowledgeHeader = ({ isNew, knowledge, onBeforeNavigateAway, saveBu
}
if (newQuestion === knowledge.question) {
- setIsEditingTitle(false);
+ handleRenameCancel();
return;
}
@@ -118,13 +93,13 @@ export const KnowledgeHeader = ({ isNew, knowledge, onBeforeNavigateAway, saveBu
question: newQuestion,
});
toast.success('Knowledge renamed successfully');
- setIsEditingTitle(false);
+ handleRenameCancel();
} catch {
// Error already handled in provider with toast
} finally {
setIsRenaming(false);
}
- }, [knowledge, updateKnowledge]);
+ }, [editingInputRef, handleRenameCancel, knowledge, updateKnowledge]);
const handleDelete = useCallback(async () => {
if (!knowledgeId) {
@@ -157,45 +132,15 @@ export const KnowledgeHeader = ({ isNew, knowledge, onBeforeNavigateAway, saveBu
<BreadcrumbItem className="gap-2">
<LibraryBig className="size-4 shrink-0" />
{isEditingTitle && canShowActions ? (
- <InputGroup className="h-8 w-64 max-w-full">
- <InputGroupInput
- className="text-foreground"
- defaultValue={knowledgeName ?? ''}
- onKeyDown={(event) => {
- if (event.key === 'Enter') {
- event.preventDefault();
- handleRenameSave();
-
- return;
- }
-
- if (event.key === 'Escape') {
- event.preventDefault();
- handleRenameCancel();
- }
- }}
- placeholder="Knowledge question"
- ref={editingInputRef}
- />
- <InputGroupAddon
- align="inline-end"
- className="gap-0 pr-2"
- >
- <InputGroupButton
- aria-label="Save"
- disabled={isRenaming}
- onClick={() => handleRenameSave()}
- >
- {isRenaming ? <Loader2 className="animate-spin" /> : <Check />}
- </InputGroupButton>
- <InputGroupButton
- aria-label="Cancel"
- onClick={() => handleRenameCancel()}
- >
- <X />
- </InputGroupButton>
- </InputGroupAddon>
- </InputGroup>
+ <InlineRenameInput
+ busy={isRenaming}
+ className="w-64 max-w-full"
+ defaultValue={knowledgeName ?? ''}
+ inputRef={editingInputRef}
+ onCancel={handleRenameCancel}
+ onSave={handleRenameSave}
+ placeholder="Knowledge question"
+ />
) : canShowActions ? (
<Tooltip>
<TooltipTrigger asChild>
@@ -217,6 +162,26 @@ export const KnowledgeHeader = ({ isNew, knowledge, onBeforeNavigateAway, saveBu
</BreadcrumbList>
</Breadcrumb>
<div className="ml-auto flex items-center gap-2">
+ {canShowActions && (
+ <ListNavigationToolbar<Knowledge>
+ {...knowledgeToolbarProps}
+ renderItem={(item, isCurrent) => (
+ <>
+ <Badge
+ className="shrink-0 whitespace-nowrap text-[10px]"
+ variant="outline"
+ >
+ {item.docType}
+ </Badge>
+ <span className={isCurrent ? 'truncate font-medium' : 'truncate'}>
+ {item.question}
+ </span>
+ </>
+ )}
+ sheetIcon={<LibraryBig className="size-4" />}
+ sheetTitle="Knowledges"
+ />
+ )}
{saveButton}
{canShowActions && (
<DropdownMenu>
@@ -233,14 +198,7 @@ export const KnowledgeHeader = ({ isNew, knowledge, onBeforeNavigateAway, saveBu
<DropdownMenuContent
align="end"
className="min-w-24"
- onCloseAutoFocus={(event) => {
- // Radix returns focus to the trigger on close. When the
- // selected action mounts the rename input, prevent that
- // restore so our deferred focus actually wins.
- if (isEditingTitle) {
- event.preventDefault();
- }
- }}
+ onCloseAutoFocus={handleDropdownCloseAutoFocus}
>
<DropdownMenuItem onClick={handleRenameStart}>
<Pencil className="size-3" />
diff --git a/frontend/src/features/knowledges/use-knowledge-detail-navigation.ts b/frontend/src/features/knowledges/use-knowledge-detail-navigation.ts
new file mode 100644
index 00000000..fa441190
--- /dev/null
+++ b/frontend/src/features/knowledges/use-knowledge-detail-navigation.ts
@@ -0,0 +1,21 @@
+import { useDetailNavigation } from '@/hooks/use-detail-navigation';
+import { type Knowledge, useKnowledges } from '@/providers/knowledges-provider';
+
+const getLabel = (item: Knowledge) => item.question;
+const getHref = (item: Knowledge) => `/knowledges/${item.id}`;
+
+/**
+ * Detail-page navigation wired up for knowledge documents. The list page
+ * filters on `question` and the header shows the same, so `getLabel`
+ * doubles as the default searchable text.
+ */
+export const useKnowledgeDetailNavigation = (currentId: null | string | undefined) => {
+ const { knowledges } = useKnowledges();
+
+ return useDetailNavigation<Knowledge>({
+ currentId,
+ getHref,
+ getLabel,
+ items: knowledges,
+ });
+};
diff --git a/frontend/src/features/resources/use-resources-search.ts b/frontend/src/features/resources/use-resources-search.ts
index 9f9faffb..b8447ff9 100644
--- a/frontend/src/features/resources/use-resources-search.ts
+++ b/frontend/src/features/resources/use-resources-search.ts
@@ -1,43 +1,37 @@
-import { zodResolver } from '@hookform/resolvers/zod';
-import { useCallback } from 'react';
-import { useForm, type UseFormReturn } from 'react-hook-form';
-import { z } from 'zod';
-
-import { useDebouncedValue } from '@/hooks/use-debounced-value';
+import { useTableQueryFilter } from '@/hooks/use-table-query-filter';
import { SEARCH_DEBOUNCE_MS } from './resources-constants';
-const resourcesSearchFormSchema = z.object({
- search: z.string(),
-});
-
-export type ResourcesSearchFormValues = z.infer<typeof resourcesSearchFormSchema>;
-
interface UseResourcesSearchResult {
debouncedQuery: string;
- form: UseFormReturn<ResourcesSearchFormValues>;
rawQuery: string;
resetSearch: () => void;
+ setQuery: (value: string) => void;
}
-/** Owns the search form and exposes a debounced version of the typed query. */
+/**
+ * Search state for the Resources file manager.
+ *
+ * Backed by `useTableQueryFilter` so the search query lives in the URL
+ * (`?q=`) with a localStorage fallback — the FileManager survives reloads
+ * with the same filter active and shareable links keep working. The debounce
+ * delay is preserved (`SEARCH_DEBOUNCE_MS`) so the existing client-side
+ * tree filter still gets the throttled value it expects. Storage key is
+ * defaulted to the current pathname inside `useTableQueryFilter`.
+ *
+ * `clearPageParamOnChange: false` because the Resources page has no `?page=`
+ * — there's no pagination to reset on every keystroke.
+ */
export const useResourcesSearch = (): UseResourcesSearchResult => {
- const form = useForm<ResourcesSearchFormValues>({
- defaultValues: { search: '' },
- resolver: zodResolver(resourcesSearchFormSchema),
+ const { debouncedFilter, filter, resetFilter, setFilter } = useTableQueryFilter({
+ clearPageParamOnChange: false,
+ debounceMs: SEARCH_DEBOUNCE_MS,
});
- const rawQuery = form.watch('search');
- const debouncedQuery = useDebouncedValue(rawQuery, SEARCH_DEBOUNCE_MS);
-
- const resetSearch = useCallback(() => {
- form.reset({ search: '' });
- }, [form]);
-
return {
- debouncedQuery,
- form,
- rawQuery,
- resetSearch,
+ debouncedQuery: debouncedFilter,
+ rawQuery: filter,
+ resetSearch: resetFilter,
+ setQuery: setFilter,
};
};
diff --git a/frontend/src/features/templates/use-template-detail-navigation.ts b/frontend/src/features/templates/use-template-detail-navigation.ts
new file mode 100644
index 00000000..da451af9
--- /dev/null
+++ b/frontend/src/features/templates/use-template-detail-navigation.ts
@@ -0,0 +1,23 @@
+import { useDetailNavigation } from '@/hooks/use-detail-navigation';
+import { type Template, useTemplates } from '@/providers/templates-provider';
+
+const getLabel = (item: Template) => item.title;
+const getId = (item: Template) => String(item.id);
+const getHref = (item: Template) => `/templates/${item.id}`;
+
+/**
+ * Detail-page navigation wired up for templates. The list page filters on
+ * `title` and the breadcrumb shows the same, so `getLabel` doubles as the
+ * default searchable text (no explicit `getSearchableText` needed).
+ */
+export const useTemplateDetailNavigation = (currentId: null | string | undefined) => {
+ const { templates } = useTemplates();
+
+ return useDetailNavigation<Template>({
+ currentId,
+ getHref,
+ getId,
+ getLabel,
+ items: templates,
+ });
+};
diff --git a/frontend/src/hooks/use-adaptive-column-visibility.ts b/frontend/src/hooks/use-adaptive-column-visibility.ts
deleted file mode 100644
index d070be69..00000000
--- a/frontend/src/hooks/use-adaptive-column-visibility.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import type { VisibilityState } from '@tanstack/react-table';
-
-import { useCallback, useEffect, useMemo, useState } from 'react';
-
-import { getColumnStorageKey } from '@/lib/storage-keys';
-
-export interface ColumnPriority {
- alwaysVisible?: boolean;
- id: string;
- priority: number;
-}
-
-interface UseAdaptiveColumnVisibilityOptions {
- breakpoints?: { hiddenPriorities: number[]; width: number }[];
- columns: ColumnPriority[];
- tableKey: string;
-}
-
-const DEFAULT_BREAKPOINTS = [
- { hiddenPriorities: [], width: 1400 },
- { hiddenPriorities: [5], width: 1200 },
- { hiddenPriorities: [4, 5], width: 1000 },
- { hiddenPriorities: [3, 4, 5], width: 800 },
- { hiddenPriorities: [2, 3, 4, 5], width: 600 },
- { hiddenPriorities: [1, 2, 3, 4, 5], width: 0 },
-];
-
-function loadUserPreferences(key: string): Record<string, boolean> {
- try {
- const stored = localStorage.getItem(key);
-
- return stored ? JSON.parse(stored) : {};
- } catch {
- return {};
- }
-}
-
-export const useAdaptiveColumnVisibility = ({
- breakpoints = DEFAULT_BREAKPOINTS,
- columns,
- tableKey,
-}: UseAdaptiveColumnVisibilityOptions) => {
- const [windowWidth, setWindowWidth] = useState(typeof window !== 'undefined' ? window.innerWidth : 1400);
-
- const localStorageKey = useMemo(() => getColumnStorageKey(tableKey), [tableKey]);
-
- const [userPreferences, setUserPreferences] = useState<Record<string, boolean>>(() =>
- loadUserPreferences(localStorageKey),
- );
-
- const saveUserPreferences = useCallback(
- (preferences: Record<string, boolean>) => {
- try {
- localStorage.setItem(localStorageKey, JSON.stringify(preferences));
- setUserPreferences(preferences);
- } catch {
- /* localStorage may be unavailable */
- }
- },
- [localStorageKey],
- );
-
- useEffect(() => {
- const handleResize = () => setWindowWidth(window.innerWidth);
-
- window.addEventListener('resize', handleResize);
-
- return () => window.removeEventListener('resize', handleResize);
- }, []);
-
- const columnVisibility = useMemo((): VisibilityState => {
- const activeBreakpoint = breakpoints.find((breakpoint) => windowWidth >= breakpoint.width) ??
- breakpoints.at(-1) ?? { hiddenPriorities: [], width: 0 };
-
- return Object.fromEntries(
- columns.map((column) => {
- if (column.alwaysVisible) {
- return [column.id, true];
- }
-
- const shouldHideByWidth = activeBreakpoint.hiddenPriorities.includes(column.priority);
- const userPreference = userPreferences[column.id];
-
- const isVisible =
- userPreference !== undefined ? !shouldHideByWidth && userPreference : !shouldHideByWidth;
-
- return [column.id, isVisible];
- }),
- );
- }, [windowWidth, userPreferences, columns, breakpoints]);
-
- const updateColumnVisibility = useCallback(
- (columnId: string, visible: boolean) => {
- saveUserPreferences({
- ...userPreferences,
- [columnId]: visible,
- });
- },
- [userPreferences, saveUserPreferences],
- );
-
- return {
- columnVisibility,
- updateColumnVisibility,
- userPreferences,
- };
-};
diff --git a/frontend/src/hooks/use-detail-navigation.test.tsx b/frontend/src/hooks/use-detail-navigation.test.tsx
new file mode 100644
index 00000000..3976490f
--- /dev/null
+++ b/frontend/src/hooks/use-detail-navigation.test.tsx
@@ -0,0 +1,205 @@
+import type { ReactNode } from 'react';
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { MemoryRouter, Route, Routes, useNavigate, useSearchParams } from 'react-router-dom';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { useDetailNavigation } from './use-detail-navigation';
+
+interface Item {
+ id: string;
+ title: string;
+}
+
+const ITEMS: readonly Item[] = [
+ { id: 'a', title: 'Alpha' },
+ { id: 'b', title: 'Bravo' },
+ { id: 'c', title: 'Charlie' },
+] as const;
+
+const getHref = (item: Item) => `/items/${item.id}`;
+const getLabel = (item: Item) => item.title;
+const getSearchableText = (item: Item) => item.title;
+
+const renderInRoute = (initialEntries: string[]) => {
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter initialEntries={initialEntries}>
+ <Routes>
+ <Route
+ element={<>{children}</>}
+ path="/items/:id"
+ />
+ </Routes>
+ </MemoryRouter>
+ );
+
+ return Wrapper;
+};
+
+beforeEach(() => {
+ localStorage.clear();
+});
+
+afterEach(() => {
+ localStorage.clear();
+});
+
+describe('useDetailNavigation — default getId', () => {
+ it('uses item.id when no `getId` override is provided', () => {
+ const { result } = renderHook(
+ () =>
+ useDetailNavigation<Item>({
+ currentId: 'b',
+ getHref,
+ getLabel,
+ getSearchableText,
+ items: ITEMS,
+ }),
+ { wrapper: renderInRoute(['/items/b']) },
+ );
+
+ expect(result.current.toolbarProps.getId(ITEMS[1])).toBe('b');
+ });
+
+ it('keeps `toolbarProps` reference stable when the caller re-renders without changes', () => {
+ const { rerender, result } = renderHook(
+ () =>
+ useDetailNavigation<Item>({
+ currentId: 'b',
+ getHref,
+ getLabel,
+ getSearchableText,
+ items: ITEMS,
+ }),
+ { wrapper: renderInRoute(['/items/b']) },
+ );
+
+ const first = result.current.toolbarProps;
+ rerender();
+ // Downstream toolbar memos rely on this identity stability.
+ expect(result.current.toolbarProps).toBe(first);
+ });
+});
+
+describe('useDetailNavigation — filter forwarding', () => {
+ it('exposes the URL `?q=` value through `toolbarProps.filter` (debounced)', async () => {
+ const { result } = renderHook(
+ () =>
+ useDetailNavigation<Item>({
+ currentId: 'b',
+ getHref,
+ getLabel,
+ getSearchableText,
+ items: ITEMS,
+ }),
+ { wrapper: renderInRoute(['/items/b?q=alpha']) },
+ );
+
+ // `toolbarProps.filter` is the debounced value — wait for the debounce
+ // to settle (default 200ms) before asserting equality.
+ await waitFor(() => {
+ expect(result.current.toolbarProps.filter).toBe('alpha');
+ });
+ expect(result.current.debouncedFilter).toBe('alpha');
+ });
+
+ it('does NOT replay `localStorage` into the URL on a fresh detail mount', async () => {
+ // Detail pages use `useTableQueryFilterReader` under the hood, which
+ // is explicitly storage-blind. A shared `/items/abc` link should not
+ // gain a stale `?q=` from a previous tab's filter.
+ localStorage.setItem('table_4_/items', JSON.stringify({ filter: 'stored' }));
+
+ const ProbeChild = ({ onMount }: { onMount: (search: string) => void }) => {
+ const [searchParams] = useSearchParams();
+ onMount(searchParams.toString());
+
+ return null;
+ };
+
+ const seen: string[] = [];
+ renderHook(
+ () => {
+ const nav = useDetailNavigation<Item>({
+ currentId: 'b',
+ getHref,
+ getLabel,
+ getSearchableText,
+ items: ITEMS,
+ });
+
+ return nav;
+ },
+ { wrapper: renderInRoute(['/items/b']) },
+ );
+
+ // Drain pending tasks — any storage→URL replay would land here.
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ renderHook(() => null, {
+ wrapper: ({ children }) => (
+ <MemoryRouter initialEntries={['/items/b']}>
+ <ProbeChild onMount={(search) => seen.push(search)} />
+ {children}
+ </MemoryRouter>
+ ),
+ });
+
+ expect(seen.every((search) => !search.includes('q='))).toBe(true);
+ });
+});
+
+describe('useDetailNavigation — current item bookkeeping', () => {
+ it('treats a missing currentId as "no match" without throwing', () => {
+ const { result } = renderHook(
+ () =>
+ useDetailNavigation<Item>({
+ currentId: undefined,
+ getHref,
+ getLabel,
+ getSearchableText,
+ items: ITEMS,
+ }),
+ { wrapper: renderInRoute(['/items/b']) },
+ );
+
+ expect(result.current.toolbarProps.currentId).toBeUndefined();
+ expect(result.current.toolbarProps.items).toBe(ITEMS);
+ });
+});
+
+describe('useDetailNavigation — navigation back to list does not leak the filter', () => {
+ it('keeps the URL `?q=` intact after a navigate inside the same router', async () => {
+ const Harness = () => {
+ const navigate = useNavigate();
+ const nav = useDetailNavigation<Item>({
+ currentId: 'b',
+ getHref,
+ getLabel,
+ getSearchableText,
+ items: ITEMS,
+ });
+
+ return { nav, navigate };
+ };
+
+ const { result } = renderHook(() => Harness(), {
+ wrapper: renderInRoute(['/items/b?q=alpha']),
+ });
+
+ await waitFor(() => {
+ expect(result.current.nav.debouncedFilter).toBe('alpha');
+ });
+
+ // Navigating to another detail page should not alter the filter
+ // value the hook observes — the URL still carries it.
+ act(() => {
+ result.current.navigate('/items/a?q=alpha');
+ });
+
+ await waitFor(() => {
+ expect(result.current.nav.debouncedFilter).toBe('alpha');
+ });
+ });
+});
diff --git a/frontend/src/hooks/use-detail-navigation.ts b/frontend/src/hooks/use-detail-navigation.ts
new file mode 100644
index 00000000..53bb0503
--- /dev/null
+++ b/frontend/src/hooks/use-detail-navigation.ts
@@ -0,0 +1,121 @@
+import { useMemo } from 'react';
+
+import type { ListNavigationToolbarProps } from '@/components/shared/list-navigation-toolbar';
+
+import { usePageStorageKeys } from '@/hooks/use-page-storage-keys';
+import { useTableQueryFilterReader } from '@/hooks/use-table-query-filter';
+
+/**
+ * Data-only slice of `ListNavigationToolbarProps<T>`. Derived from the
+ * single source of truth in `list-navigation-toolbar.tsx` so a new required
+ * prop (or a rename) can't silently desync the two surfaces.
+ *
+ * Presentation-only fields (`sheetTitle`, `sheetIcon`, `renderItem`,
+ * `sortFn`) are intentionally excluded — those are supplied per-page at the
+ * call site of the toolbar, not by the navigation hook.
+ */
+type ListNavigationToolbarDataProps<T> = Pick<
+ ListNavigationToolbarProps<T>,
+ 'currentId' | 'filter' | 'getHref' | 'getId' | 'getLabel' | 'getSearchableText' | 'items'
+>;
+
+/**
+ * Restricts the override to strings that start with a `/`. Pure-string types
+ * (`string`) would let an empty `""` or a bare `"flows"` slip through and
+ * either collide on the shared `filter_4_` key or generate a different slot
+ * than the actual list page. Template-literal types catch this at compile
+ * time without runtime guards.
+ *
+ * `${string}` is unconstrained on purpose — we only care that the value
+ * begins with a slash, not what follows.
+ */
+type ParentPath = `/${string}`;
+
+interface UseDetailNavigationOptions<T extends { id: string }> {
+ currentId: null | string | undefined;
+ getHref: (item: T) => string;
+ getId?: (item: T) => string;
+ getLabel: (item: T) => string;
+ getSearchableText?: (item: T) => null | string | undefined;
+ items: readonly T[];
+ /**
+ * Optional override for the parent list path used to look up the shared
+ * filter storage slot. Defaults to the top-level segment of the current
+ * pathname, which works for top-level routes (`/flows`, `/templates`,
+ * `/knowledges`). Nested routes (`/admin/flows/:id`) must pass an
+ * explicit value here because the default would key into `/admin`
+ * rather than `/admin/flows`.
+ *
+ * Typed as a slash-prefixed string so the compiler rejects empty or
+ * unprefixed overrides — those used to silently fall back to the
+ * top-level path, which produced surprising key collisions. Pass an
+ * explicit slash path (e.g. `'/admin/flows'`) when overriding.
+ */
+ parentPath?: ParentPath;
+}
+
+interface UseDetailNavigationResult<T extends { id: string }> {
+ debouncedFilter: string;
+ toolbarProps: ListNavigationToolbarDataProps<T>;
+}
+
+// Module-level so the reference is stable across renders. Typed against
+// the wider `{ id: string }` so it is assignable to `(item: T) => string`
+// for any `T extends { id: string }` via function-parameter contravariance
+// — no cast at the call site.
+const defaultGetId = (item: { id: string }): string => item.id;
+
+/**
+ * Convenience wrapper for detail pages that need a Prev/Next toolbar tied
+ * to the parent list's free-text filter.
+ *
+ * The hook bundles the three things every detail page repeats:
+ * 1. resolving the parent list's storage slot via `usePageStorageKeys`,
+ * 2. subscribing to the URL filter through `useTableQueryFilterReader`
+ * (read-only — the detail page never mutates the filter from here),
+ * 3. supplying a default `getId` (most domain types use a plain `id`).
+ *
+ * The returned `toolbarProps` plug straight into `<ListNavigationToolbar>` —
+ * callers add presentation-only props (`sheetTitle`, `renderItem`, etc.).
+ *
+ * Pass each callback through `useCallback`: the toolbar's filter memo relies
+ * on identity stability, and an inline arrow defeats it.
+ */
+export const useDetailNavigation = <T extends { id: string }>({
+ currentId,
+ getHref,
+ getId,
+ getLabel,
+ getSearchableText,
+ items,
+ parentPath,
+}: UseDetailNavigationOptions<T>): UseDetailNavigationResult<T> => {
+ // `parentPath` is typed as `/${string}` so the empty / unprefixed case
+ // is rejected at compile time — we only need to branch on presence here.
+ const hasExplicitParentPath = parentPath !== undefined;
+ const { table: filterStorageKey } = usePageStorageKeys({
+ pathname: hasExplicitParentPath ? parentPath : undefined,
+ useTopLevel: !hasExplicitParentPath,
+ });
+ const { debouncedFilter } = useTableQueryFilterReader({ storageKey: filterStorageKey });
+
+ // Memoize so passing `getId={undefined}` keeps the reference stable when
+ // the caller re-renders for unrelated reasons. Without the memo the
+ // `toolbarProps` memo below would invalidate on every render.
+ const resolvedGetId = useMemo<(item: T) => string>(() => getId ?? defaultGetId, [getId]);
+
+ const toolbarProps = useMemo<ListNavigationToolbarDataProps<T>>(
+ () => ({
+ currentId,
+ filter: debouncedFilter,
+ getHref,
+ getId: resolvedGetId,
+ getLabel,
+ getSearchableText,
+ items,
+ }),
+ [currentId, debouncedFilter, getHref, getLabel, getSearchableText, items, resolvedGetId],
+ );
+
+ return { debouncedFilter, toolbarProps };
+};
diff --git a/frontend/src/hooks/use-filtered-list-navigation.test.ts b/frontend/src/hooks/use-filtered-list-navigation.test.ts
new file mode 100644
index 00000000..ff9df8f0
--- /dev/null
+++ b/frontend/src/hooks/use-filtered-list-navigation.test.ts
@@ -0,0 +1,280 @@
+import { describe, expect, it } from 'vitest';
+
+import { computeListNavigation } from './use-filtered-list-navigation';
+
+interface Row {
+ id: string;
+ title: string;
+}
+
+const getId = (row: Row) => row.id;
+const getTitle = (row: Row) => row.title;
+
+const ROWS: readonly Row[] = [
+ { id: 'a', title: 'Alpha' },
+ { id: 'b', title: 'Bravo' },
+ { id: 'c', title: 'Charlie' },
+ { id: 'd', title: 'Delta' },
+] as const;
+
+describe('computeListNavigation', () => {
+ it('returns prev/next neighbours for a middle item', () => {
+ const result = computeListNavigation({
+ currentId: 'c',
+ getId,
+ items: ROWS,
+ });
+
+ expect(result.currentIndex).toBe(2);
+ expect(result.prevId).toBe('b');
+ expect(result.nextId).toBe('d');
+ expect(result.total).toBe(4);
+ });
+
+ it('returns null prev for the first item', () => {
+ const result = computeListNavigation({
+ currentId: 'a',
+ getId,
+ items: ROWS,
+ });
+
+ expect(result.currentIndex).toBe(0);
+ expect(result.prevId).toBeNull();
+ expect(result.nextId).toBe('b');
+ });
+
+ it('returns null next for the last item', () => {
+ const result = computeListNavigation({
+ currentId: 'd',
+ getId,
+ items: ROWS,
+ });
+
+ expect(result.currentIndex).toBe(3);
+ expect(result.prevId).toBe('c');
+ expect(result.nextId).toBeNull();
+ });
+
+ it('reports currentIndex=-1 when the current item is missing from the filtered subset', () => {
+ const result = computeListNavigation({
+ currentId: 'zzz',
+ getId,
+ items: ROWS,
+ });
+
+ expect(result.currentIndex).toBe(-1);
+ expect(result.currentItem).toBeNull();
+ expect(result.prevId).toBeNull();
+ expect(result.nextId).toBeNull();
+ expect(result.total).toBe(4);
+ });
+
+ it('reports currentIndex=-1 when currentId is null or undefined', () => {
+ const nullResult = computeListNavigation({
+ currentId: null,
+ getId,
+ items: ROWS,
+ });
+
+ expect(nullResult.currentIndex).toBe(-1);
+ expect(nullResult.prevId).toBeNull();
+ expect(nullResult.nextId).toBeNull();
+
+ const undefinedResult = computeListNavigation({
+ currentId: undefined,
+ getId,
+ items: ROWS,
+ });
+
+ expect(undefinedResult.currentIndex).toBe(-1);
+ });
+
+ it('honours `query` when narrowing the subset', () => {
+ const result = computeListNavigation({
+ currentId: 'c',
+ getId,
+ getSearchableText: getTitle,
+ items: ROWS,
+ // Substring "c" matches "Charlie" (case-insensitive).
+ query: 'c',
+ });
+
+ expect(result.filteredItems.map(getId)).toEqual(['c']);
+ expect(result.currentIndex).toBe(0);
+ expect(result.prevId).toBeNull();
+ expect(result.nextId).toBeNull();
+ expect(result.total).toBe(1);
+ });
+
+ it('drops the current item from the result when it does not match the query', () => {
+ const result = computeListNavigation({
+ currentId: 'a',
+ getId,
+ getSearchableText: getTitle,
+ items: ROWS,
+ query: 'Bravo',
+ });
+
+ expect(result.filteredItems.map(getId)).toEqual(['b']);
+ expect(result.currentIndex).toBe(-1);
+ expect(result.prevId).toBeNull();
+ expect(result.nextId).toBeNull();
+ });
+
+ it('treats an empty/undefined query as "no filter" even when getSearchableText is provided', () => {
+ const empty = computeListNavigation({
+ currentId: 'c',
+ getId,
+ getSearchableText: getTitle,
+ items: ROWS,
+ query: '',
+ });
+
+ expect(empty.filteredItems.map(getId)).toEqual(['a', 'b', 'c', 'd']);
+
+ const missing = computeListNavigation({
+ currentId: 'c',
+ getId,
+ getSearchableText: getTitle,
+ items: ROWS,
+ });
+
+ expect(missing.filteredItems.map(getId)).toEqual(['a', 'b', 'c', 'd']);
+ });
+
+ it('skips filtering silently when query is non-empty but getSearchableText is missing', () => {
+ // Documents the boundary: without a haystack accessor we cannot evaluate
+ // the query against rows, so we degrade to "no filter" instead of
+ // throwing — keeps the hook usable while a caller forgets to wire one up.
+ const result = computeListNavigation({
+ currentId: 'c',
+ getId,
+ items: ROWS,
+ query: 'pha',
+ });
+
+ expect(result.filteredItems.map(getId)).toEqual(['a', 'b', 'c', 'd']);
+ });
+
+ it('preserves input order when no sortFn is provided', () => {
+ const reversed = [...ROWS].reverse();
+ const result = computeListNavigation({
+ currentId: 'c',
+ getId,
+ items: reversed,
+ });
+
+ expect(result.filteredItems.map(getId)).toEqual(['d', 'c', 'b', 'a']);
+ expect(result.currentIndex).toBe(1);
+ expect(result.prevId).toBe('d');
+ expect(result.nextId).toBe('b');
+ });
+
+ it('applies sortFn to the filtered subset', () => {
+ const result = computeListNavigation({
+ currentId: 'b',
+ getId,
+ items: ROWS,
+ sortFn: (a, b) => b.title.localeCompare(a.title),
+ });
+
+ expect(result.filteredItems.map(getId)).toEqual(['d', 'c', 'b', 'a']);
+ expect(result.currentIndex).toBe(2);
+ expect(result.prevId).toBe('c');
+ expect(result.nextId).toBe('a');
+ });
+
+ it('handles an empty items array', () => {
+ const result = computeListNavigation({
+ currentId: 'anything',
+ getId,
+ items: [],
+ });
+
+ expect(result.filteredItems).toEqual([]);
+ expect(result.total).toBe(0);
+ expect(result.currentIndex).toBe(-1);
+ expect(result.prevId).toBeNull();
+ expect(result.nextId).toBeNull();
+ });
+
+ it('returns the current item when present', () => {
+ const result = computeListNavigation({
+ currentId: 'c',
+ getId,
+ items: ROWS,
+ });
+
+ expect(result.currentItem).toEqual({ id: 'c', title: 'Charlie' });
+ });
+
+ it('does not mutate the input array even when sorting', () => {
+ const before = ROWS.map(getId);
+ computeListNavigation({
+ currentId: 'a',
+ getId,
+ items: ROWS,
+ sortFn: (a, b) => b.title.localeCompare(a.title),
+ });
+
+ expect(ROWS.map(getId)).toEqual(before);
+ });
+
+ it('handles "item deleted, currentId still points to it"', () => {
+ // The user was viewing item `b`, then `b` was deleted (removed from
+ // `items`) — currentId stays `b` until the route updates. The hook
+ // must surface this as currentIndex=-1 / no neighbours so the UI
+ // disables Prev/Next rather than jumping to an unrelated row.
+ const trimmed = ROWS.filter((row) => row.id !== 'b');
+ const result = computeListNavigation({
+ currentId: 'b',
+ getId,
+ items: trimmed,
+ });
+
+ expect(result.filteredItems.map(getId)).toEqual(['a', 'c', 'd']);
+ expect(result.currentIndex).toBe(-1);
+ expect(result.prevId).toBeNull();
+ expect(result.nextId).toBeNull();
+ expect(result.total).toBe(3);
+ });
+
+ it('folds diacritics + case the same way the list filter does', () => {
+ const accented: readonly Row[] = [
+ { id: '1', title: 'Café' },
+ { id: '2', title: 'naïve' },
+ { id: '3', title: 'resume' },
+ ];
+
+ const result = computeListNavigation({
+ currentId: '1',
+ getId,
+ getSearchableText: getTitle,
+ items: accented,
+ query: 'cafe',
+ });
+
+ expect(result.filteredItems.map(getId)).toEqual(['1']);
+ expect(result.currentIndex).toBe(0);
+ });
+
+ it('matches numeric item ids with string currentId', () => {
+ type NumRow = { id: number; title: string };
+ const rows: readonly NumRow[] = [
+ { id: 10, title: 'A' },
+ { id: 20, title: 'B' },
+ { id: 30, title: 'C' },
+ ];
+ const getNumericId = (row: NumRow) => String(row.id);
+
+ const result = computeListNavigation({
+ currentId: '20',
+ getId: getNumericId,
+ items: rows,
+ });
+
+ expect(result.currentIndex).toBe(1);
+ expect(result.prevId).toBe('10');
+ expect(result.nextId).toBe('30');
+ });
+});
diff --git a/frontend/src/hooks/use-filtered-list-navigation.ts b/frontend/src/hooks/use-filtered-list-navigation.ts
new file mode 100644
index 00000000..b75a6c4d
--- /dev/null
+++ b/frontend/src/hooks/use-filtered-list-navigation.ts
@@ -0,0 +1,145 @@
+import { useMemo } from 'react';
+
+import { createTextMatcher } from '@/lib/table-filter';
+
+interface ListNavigationInput<T> {
+ currentId: null | string | undefined;
+ getId: (item: T) => string;
+ /**
+ * Optional accessor for the text the filter runs against. Only consulted
+ * when `query` is non-empty — pages with no filter don't need it.
+ */
+ getSearchableText?: (item: T) => null | string | undefined;
+ items: readonly T[];
+ /**
+ * Free-text filter to narrow the navigable subset. Empty / `undefined` is
+ * treated as "no filter" and every item passes. Matching reuses
+ * `createTextMatcher`, so behaviour matches the list page's column
+ * filter (substring, case + diacritic insensitive).
+ */
+ query?: string;
+ sortFn?: (a: T, b: T) => number;
+}
+
+interface ListNavigationResult<T> {
+ currentIndex: number;
+ currentItem: null | T;
+ filteredItems: readonly T[];
+ nextId: null | string;
+ prevId: null | string;
+ total: number;
+}
+
+/**
+ * Pure core of {@link useFilteredListNavigation}: filter, sort, and resolve
+ * Prev/Next around `currentId`. Exposed without React so the algorithm can be
+ * unit-tested directly — the hook is a thin `useMemo` wrapper around this.
+ *
+ * The Map of `id → index` is built once per invocation so the `currentId`
+ * lookup is O(1) instead of an `Array.find` per render. The map is
+ * intentionally not exposed — callers should walk `filteredItems` or use the
+ * returned `prevId` / `nextId`.
+ */
+export const computeListNavigation = <T>({
+ currentId,
+ getId,
+ getSearchableText,
+ items,
+ query,
+ sortFn,
+}: ListNavigationInput<T>): ListNavigationResult<T> => {
+ const hasQuery = query !== undefined && query.length > 0;
+ const filtered =
+ hasQuery && getSearchableText
+ ? items.filter((item) => createTextMatcher(query)(getSearchableText(item)))
+ : items;
+ const ordered = sortFn ? [...filtered].sort(sortFn) : filtered;
+
+ const indexById = new Map<string, number>();
+
+ ordered.forEach((item, index) => {
+ // Apollo commonly hydrates GraphQL `ID` fields as numbers even though
+ // route params are strings — normalize so lookups stay stable.
+ indexById.set(String(getId(item)), index);
+ });
+
+ const currentIndex = currentId != null ? (indexById.get(String(currentId)) ?? -1) : -1;
+
+ if (currentIndex === -1) {
+ return {
+ currentIndex: -1,
+ currentItem: null,
+ filteredItems: ordered,
+ nextId: null,
+ prevId: null,
+ total: ordered.length,
+ };
+ }
+
+ const prevItem = currentIndex > 0 ? ordered[currentIndex - 1] : null;
+ const nextItem = currentIndex < ordered.length - 1 ? ordered[currentIndex + 1] : null;
+
+ return {
+ currentIndex,
+ currentItem: ordered[currentIndex] ?? null,
+ filteredItems: ordered,
+ nextId: nextItem ? String(getId(nextItem)) : null,
+ prevId: prevItem ? String(getId(prevItem)) : null,
+ total: ordered.length,
+ };
+};
+
+interface UseFilteredListNavigationOptions<T> {
+ currentId: null | string | undefined;
+ getId: (item: T) => string;
+ /**
+ * Accessor for the text the filter runs against. Only required when
+ * `query` is non-empty.
+ */
+ getSearchableText?: (item: T) => null | string | undefined;
+ items: readonly T[];
+ /** Free-text filter. Empty / `undefined` → unfiltered. */
+ query?: string;
+ /**
+ * Optional comparator. When omitted, the input array order is preserved —
+ * the navigation walks `items` exactly as the caller arranged them, which
+ * matches what list pages already render.
+ */
+ sortFn?: (a: T, b: T) => number;
+}
+
+type UseFilteredListNavigationResult<T> = ListNavigationResult<T>;
+
+/**
+ * Resolve Prev/Next siblings for a detail page that's tied to a filtered list.
+ *
+ * The list page holds the same `items` and free-text `query`, so this hook
+ * produces the same ordering as what the user sees in the table — Prev/Next
+ * stays in lockstep with the filter even after the user lands on a detail
+ * URL via a shared link.
+ *
+ * If the current item is missing from the filtered subset (deleted, or no
+ * longer matches the filter), `currentIndex` is `-1` and both `prevId` /
+ * `nextId` are `null` — the caller renders disabled Prev/Next buttons in that
+ * case rather than navigating into an unrelated neighbour.
+ *
+ * Callers pass *data* (`query`, `getSearchableText`) rather than a prebuilt
+ * predicate. That removes the identity-stability footgun the predicate-based
+ * shape had: a fresh-arrow `(item) => …` callback every render would have
+ * defeated the internal `useMemo`. With this shape, only `query` flips per
+ * keystroke, and `getSearchableText` is naturally module-scoped at the
+ * feature level (see `use-flow-detail-navigation` etc.).
+ */
+export const useFilteredListNavigation = <T>({
+ currentId,
+ getId,
+ getSearchableText,
+ items,
+ query,
+ sortFn,
+}: UseFilteredListNavigationOptions<T>): UseFilteredListNavigationResult<T> => {
+ return useMemo(
+ () => computeListNavigation({ currentId, getId, getSearchableText, items, query, sortFn }),
+ [currentId, getId, getSearchableText, items, query, sortFn],
+ );
+};
diff --git a/frontend/src/hooks/use-inline-edit-title.test.tsx b/frontend/src/hooks/use-inline-edit-title.test.tsx
new file mode 100644
index 00000000..ed6261ff
--- /dev/null
+++ b/frontend/src/hooks/use-inline-edit-title.test.tsx
@@ -0,0 +1,136 @@
+import { act, renderHook } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import { useInlineEditTitle } from './use-inline-edit-title';
+
+describe('useInlineEditTitle', () => {
+ it('starts in non-editing state', () => {
+ const { result } = renderHook(() => useInlineEditTitle({ resetKey: 'a' }));
+ expect(result.current.isEditing).toBe(false);
+ });
+
+ it('startEdit flips to editing, stopEdit flips back', () => {
+ const { result } = renderHook(() => useInlineEditTitle({ resetKey: 'a' }));
+
+ act(() => result.current.startEdit());
+ expect(result.current.isEditing).toBe(true);
+
+ act(() => result.current.stopEdit());
+ expect(result.current.isEditing).toBe(false);
+ });
+
+ it('exits edit mode when resetKey changes', () => {
+ const { rerender, result } = renderHook(({ resetKey }) => useInlineEditTitle({ resetKey }), {
+ initialProps: { resetKey: 'a' as null | string | undefined },
+ });
+
+ act(() => result.current.startEdit());
+ expect(result.current.isEditing).toBe(true);
+
+ rerender({ resetKey: 'b' });
+ expect(result.current.isEditing).toBe(false);
+ });
+
+ it('keeps edit mode across rerenders with the same resetKey', () => {
+ const { rerender, result } = renderHook(({ resetKey }) => useInlineEditTitle({ resetKey }), {
+ initialProps: { resetKey: 'a' as null | string | undefined },
+ });
+
+ act(() => result.current.startEdit());
+ rerender({ resetKey: 'a' });
+ expect(result.current.isEditing).toBe(true);
+ });
+
+ it('treats `null` and `undefined` as distinct keys (state reset on transition)', () => {
+ const { rerender, result } = renderHook(({ resetKey }) => useInlineEditTitle({ resetKey }), {
+ initialProps: { resetKey: null as null | string | undefined },
+ });
+
+ act(() => result.current.startEdit());
+
+ // Transition null -> undefined trips the reset because they aren't
+ // strictly equal. Documenting this so callers know to keep the
+ // resetKey type stable.
+ rerender({ resetKey: undefined });
+ expect(result.current.isEditing).toBe(false);
+ });
+
+ it('returns a ref object whose .current starts at null', () => {
+ const { result } = renderHook(() => useInlineEditTitle({ resetKey: 'a' }));
+ expect(result.current.inputRef.current).toBeNull();
+ });
+
+ it('handleDropdownCloseAutoFocus prevents default while editing', () => {
+ const { result } = renderHook(() => useInlineEditTitle({ resetKey: 'a' }));
+
+ act(() => result.current.startEdit());
+
+ // `Event` is cancelable by default but `defaultPrevented` only flips
+ // once `preventDefault` is called — exactly what the hook does.
+ const event = new Event('autofocus', { cancelable: true });
+ result.current.handleDropdownCloseAutoFocus(event);
+
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('handleDropdownCloseAutoFocus is a no-op when not editing', () => {
+ const { result } = renderHook(() => useInlineEditTitle({ resetKey: 'a' }));
+
+ const event = new Event('autofocus', { cancelable: true });
+ result.current.handleDropdownCloseAutoFocus(event);
+
+ expect(event.defaultPrevented).toBe(false);
+ });
+
+ it('focuses and selects the input on the next animation frame after startEdit', async () => {
+ const { result } = renderHook(() => useInlineEditTitle({ resetKey: 'a' }));
+
+ const input = document.createElement('input');
+ input.value = 'hello';
+ document.body.appendChild(input);
+
+ // Attach the ref manually — `useRef` exposes `.current` as writable
+ // even though TypeScript narrows it to readonly. Casting through
+ // an interface keeps the intent visible in the test.
+ (result.current.inputRef as unknown as { current: HTMLInputElement }).current = input;
+
+ act(() => result.current.startEdit());
+
+ // requestAnimationFrame in jsdom resolves in a microtask — wait for it.
+ await act(async () => {
+ await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
+ });
+
+ expect(document.activeElement).toBe(input);
+ expect(input.selectionStart).toBe(0);
+ expect(input.selectionEnd).toBe(input.value.length);
+
+ document.body.removeChild(input);
+ });
+
+ it('cancels the pending focus when isEditing flips off before the frame fires', async () => {
+ const { result } = renderHook(() => useInlineEditTitle({ resetKey: 'a' }));
+
+ const input = document.createElement('input');
+ document.body.appendChild(input);
+ (result.current.inputRef as unknown as { current: HTMLInputElement }).current = input;
+
+ const otherInput = document.createElement('input');
+ document.body.appendChild(otherInput);
+ otherInput.focus();
+
+ act(() => result.current.startEdit());
+ act(() => result.current.stopEdit());
+
+ await act(async () => {
+ await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
+ });
+
+ // Focus must not have moved to the inline input — the effect cleanup
+ // cancelled the rAF before it ran.
+ expect(document.activeElement).toBe(otherInput);
+
+ document.body.removeChild(input);
+ document.body.removeChild(otherInput);
+ });
+});
diff --git a/frontend/src/hooks/use-inline-edit-title.ts b/frontend/src/hooks/use-inline-edit-title.ts
new file mode 100644
index 00000000..621f5dd2
--- /dev/null
+++ b/frontend/src/hooks/use-inline-edit-title.ts
@@ -0,0 +1,112 @@
+import type React from 'react';
+
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+interface UseInlineEditTitleOptions {
+ /**
+ * When this value changes, the edit session is reset (closes any open
+ * input). Use it for the entity id that owns the editor — navigating
+ * between items should not carry a stale draft over.
+ */
+ resetKey?: null | string | undefined;
+}
+
+interface UseInlineEditTitleResult<TElement extends HTMLElement = HTMLInputElement> {
+ /**
+ * Spread onto a Radix `<DropdownMenuContent>` (or any component with the
+ * same `onCloseAutoFocus` semantics) when the dropdown contains a button
+ * that toggles the inline editor. Prevents Radix's default focus-restore
+ * from racing the editor's `requestAnimationFrame`-driven focus below.
+ */
+ handleDropdownCloseAutoFocus: (event: Event) => void;
+ /** Ref to wire to the inline `<input>` element. */
+ inputRef: React.RefObject<null | TElement>;
+ isEditing: boolean;
+ /** Begin an inline edit — the input mounts and receives focus on next frame. */
+ startEdit: () => void;
+ /** End the edit session without committing. */
+ stopEdit: () => void;
+}
+
+/**
+ * Shared state machine for "double-click to rename" headers / table cells.
+ *
+ * Combines four micro-responsibilities that every renameable surface in the
+ * app needs:
+ * - `isEditing` boolean + start/stop helpers,
+ * - a ref for the inline input,
+ * - deferred focus + select-all on the next animation frame, so the focus
+ * lands *after* Radix's dropdown close-focus-restore completes (otherwise
+ * Radix wins the race and the input never receives focus),
+ * - an `onCloseAutoFocus` handler that opts out of Radix's restore while
+ * editing — used together with the deferred focus above.
+ *
+ * Pass the entity id as `resetKey` so navigation between items closes any
+ * stale editor automatically.
+ */
+export const useInlineEditTitle = <TElement extends HTMLElement = HTMLInputElement>({
+ resetKey,
+}: UseInlineEditTitleOptions = {}): UseInlineEditTitleResult<TElement> => {
+ const [isEditing, setIsEditing] = useState(false);
+ const inputRef = useRef<null | TElement>(null);
+
+ // Reset the edit session when `resetKey` changes. React docs call out
+ // "adjust state when a prop changes" as the canonical render-phase
+ // `setState` pattern — it's preferred over `useEffect` because the new
+ // state lands in the same commit (no flash of stale "still editing" UI
+ // on the new item) and it doesn't trigger the "cascading renders"
+ // lint complaint that an effect-based reset would.
+ const [lastResetKey, setLastResetKey] = useState(resetKey);
+
+ if (lastResetKey !== resetKey) {
+ setLastResetKey(resetKey);
+
+ if (isEditing) {
+ setIsEditing(false);
+ }
+ }
+
+ useEffect(() => {
+ if (!isEditing) {
+ return;
+ }
+
+ const id = requestAnimationFrame(() => {
+ const input = inputRef.current;
+
+ if (!input) {
+ return;
+ }
+
+ input.focus();
+
+ // `<input>` and `<textarea>` both expose `select()`, but typing
+ // `TElement extends HTMLElement` is wider than that — guard so
+ // a future caller with `HTMLDivElement` doesn't crash here.
+ if ('select' in input && typeof (input as { select: unknown }).select === 'function') {
+ (input as unknown as HTMLInputElement).select();
+ }
+ });
+
+ return () => cancelAnimationFrame(id);
+ }, [isEditing]);
+
+ const startEdit = useCallback(() => setIsEditing(true), []);
+ const stopEdit = useCallback(() => setIsEditing(false), []);
+
+ // Closure over `isEditing` directly. The callback identity flips on each
+ // edit-mode toggle, but that's fine: Radix's `<DropdownMenuContent>` is
+ // not memoized today and `onCloseAutoFocus` fires inside the same commit
+ // that closes the dropdown — a ref-based stable callback would risk
+ // reading a stale value through `useLatestRef`'s `useEffect` lag.
+ const handleDropdownCloseAutoFocus = useCallback(
+ (event: Event) => {
+ if (isEditing) {
+ event.preventDefault();
+ }
+ },
+ [isEditing],
+ );
+
+ return { handleDropdownCloseAutoFocus, inputRef, isEditing, startEdit, stopEdit };
+};
diff --git a/frontend/src/hooks/use-latest-ref.ts b/frontend/src/hooks/use-latest-ref.ts
index f64736f8..53c4794c 100644
--- a/frontend/src/hooks/use-latest-ref.ts
+++ b/frontend/src/hooks/use-latest-ref.ts
@@ -6,8 +6,22 @@ import { type RefObject, useEffect, useRef } from 'react';
* Useful for the "stable callback" pattern: a memoized child accepts a stable
* handler from the parent, but the handler internally needs to read the most
* recent prop / state value without invalidating downstream memos. Reading
- * `ref.current` inside the stable handler always sees the latest value
- * because this hook re-syncs the ref after every commit.
+ * `ref.current` inside the stable handler sees the value committed in the
+ * most recent successful render.
+ *
+ * **Timing caveat — one-commit lag for synchronous reads.** The ref is
+ * synced inside a passive `useEffect`. This means handlers that fire
+ * *during* a commit (e.g. Radix's `onCloseAutoFocus`, which it dispatches
+ * from its own layout-effect in the same flush) read the *previous* render's
+ * value, because the sync effect from the current render hasn't run yet.
+ * For those cases mutate a `useRef` directly in render — write
+ * `const ref = useRef(value); ref.current = value;` — instead of using this
+ * hook. Render-time mutation is safe so long as nothing *reads* the ref
+ * during render (only handlers and effects do).
+ *
+ * For asynchronous reads — pointer/key events, timers, network callbacks —
+ * the lag never matters because at least one commit cycle has finished by
+ * the time the handler fires. That's the common case this hook is built for.
*
* Don't read `ref.current` during render — use the value prop directly instead.
* Reading the ref during render breaks React's snapshot guarantee (the ref may
diff --git a/frontend/src/hooks/use-page-storage-keys.test.tsx b/frontend/src/hooks/use-page-storage-keys.test.tsx
new file mode 100644
index 00000000..43c484f4
--- /dev/null
+++ b/frontend/src/hooks/use-page-storage-keys.test.tsx
@@ -0,0 +1,92 @@
+import type { ReactNode } from 'react';
+
+import { renderHook } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+import { describe, expect, it } from 'vitest';
+
+import { usePageStorageKeys } from './use-page-storage-keys';
+
+const renderWithRouter = (
+ initialEntries: string[],
+ options?: Parameters<typeof usePageStorageKeys>[0],
+) => {
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter initialEntries={initialEntries}>{children}</MemoryRouter>
+ );
+
+ return renderHook(() => usePageStorageKeys(options), { wrapper: Wrapper });
+};
+
+describe('usePageStorageKeys — defaults', () => {
+ it('builds keys from the live pathname when no override is provided', () => {
+ const { result } = renderWithRouter(['/flows']);
+
+ expect(result.current.table).toBe('table_4_/flows');
+ expect(result.current.period).toBe('period_4_/flows');
+ expect(result.current.viewOptions).toBe('viewOptions_4_/flows');
+ });
+
+ it('reflects the entire pathname — does NOT strip params by default', () => {
+ // A detail page that mounts the hook directly (no override) gets a
+ // unique key per id. This is the correct behaviour for tables on
+ // distinct subroutes; detail pages that want to share with the list
+ // must pass `useTopLevel: true` or an explicit override.
+ const { result } = renderWithRouter(['/flows/abc-123']);
+
+ expect(result.current.table).toBe('table_4_/flows/abc-123');
+ });
+});
+
+describe('usePageStorageKeys — useTopLevel', () => {
+ it('strips id suffixes when `useTopLevel: true`', () => {
+ const { result } = renderWithRouter(['/flows/abc-123'], { useTopLevel: true });
+
+ expect(result.current.table).toBe('table_4_/flows');
+ });
+
+ it('handles a deep path with `useTopLevel: true` — only the first segment survives', () => {
+ const { result } = renderWithRouter(['/knowledges/abc/foo/bar'], { useTopLevel: true });
+
+ expect(result.current.table).toBe('table_4_/knowledges');
+ });
+
+ it('falls back to an empty path for the root', () => {
+ const { result } = renderWithRouter(['/'], { useTopLevel: true });
+
+ // `getTopLevelPath('/')` returns `''`, so the key is `table_4_`.
+ // Documented as the deliberate behaviour — root-route detail pages
+ // would all collide on this key, but no such page exists.
+ expect(result.current.table).toBe('table_4_');
+ });
+});
+
+describe('usePageStorageKeys — explicit pathname override', () => {
+ it('uses the override verbatim, ignoring the live pathname', () => {
+ const { result } = renderWithRouter(['/flows/abc-123'], { pathname: '/admin/flows' });
+
+ expect(result.current.table).toBe('table_4_/admin/flows');
+ });
+
+ it('override + useTopLevel uses the top-level segment of the override', () => {
+ const { result } = renderWithRouter(['/flows/abc'], {
+ pathname: '/admin/flows/xyz',
+ useTopLevel: true,
+ });
+
+ expect(result.current.table).toBe('table_4_/admin');
+ });
+});
+
+describe('usePageStorageKeys — reactivity', () => {
+ it('returns the same memoized object across re-renders when inputs do not change', () => {
+ const { rerender, result } = renderWithRouter(['/flows']);
+
+ const first = result.current;
+
+ rerender();
+
+ // Memoization guarantee — downstream effects depend on this for
+ // their identity-stable dep arrays.
+ expect(result.current).toBe(first);
+ });
+});
diff --git a/frontend/src/hooks/use-page-storage-keys.ts b/frontend/src/hooks/use-page-storage-keys.ts
new file mode 100644
index 00000000..4f55b823
--- /dev/null
+++ b/frontend/src/hooks/use-page-storage-keys.ts
@@ -0,0 +1,68 @@
+import { useMemo } from 'react';
+import { useLocation } from 'react-router-dom';
+
+import {
+ getPeriodStorageKey,
+ getTableStorageKey,
+ getTopLevelPath,
+ getViewOptionsStorageKey,
+} from '@/lib/storage-keys';
+
+interface PageStorageKeys {
+ /** Dashboard analytics time window — single string value, no schema merge. */
+ period: string;
+ /** Unified per-page table state (filter + sorting + columnVisibility + pageSize). */
+ table: string;
+ /** FileManager-style view options (folder-first toggle, expanded dirs, etc.). */
+ viewOptions: string;
+}
+
+interface UsePageStorageKeysOptions {
+ /**
+ * Optional override for the path used to build the keys. Pass when the
+ * caller wants to share a storage bucket with a different route — e.g.
+ * a detail page (`/flows/:id`) keying into the parent list's slot
+ * (`/flows`).
+ *
+ * When omitted, the live `useLocation().pathname` is used as-is.
+ */
+ pathname?: string;
+ /**
+ * If `true`, the effective path is the top-level segment of `pathname`
+ * (e.g. `/flows/abc-123` → `/flows`). Convenience for detail pages that
+ * want to inherit their list's storage slot without spelling it out.
+ */
+ useTopLevel?: boolean;
+}
+
+/**
+ * Resolve the per-route localStorage keys (table, period, viewOptions) for
+ * the current location, reactively.
+ *
+ * Replaces the older pattern of calling individual `get*StorageKey()`
+ * functions without an argument, which read the global `location.pathname`.
+ * The global read is not reactive to react-router navigation and is unsafe
+ * to call during module load (e.g. tests, SSR). Routing through
+ * `useLocation` makes the result re-evaluate whenever the active route
+ * changes.
+ *
+ * Each list page now stores at most **one** key — `table_4_<path>` — that
+ * bundles filter + sorting + columnVisibility + pageSize. Old `column_4_`,
+ * `sorting_4_`, `filter_4_`, `page_4_` slots are migrated into the unified
+ * key on first mount (see `migrateLegacyTableState`).
+ */
+export const usePageStorageKeys = (options: UsePageStorageKeysOptions = {}): PageStorageKeys => {
+ const { pathname: livePathname } = useLocation();
+ const { pathname: override, useTopLevel = false } = options;
+
+ return useMemo(() => {
+ const source = override ?? livePathname;
+ const effective = useTopLevel ? getTopLevelPath(source) : source;
+
+ return {
+ period: getPeriodStorageKey(effective),
+ table: getTableStorageKey(effective),
+ viewOptions: getViewOptionsStorageKey(effective),
+ };
+ }, [livePathname, override, useTopLevel]);
+};
diff --git a/frontend/src/hooks/use-pagination.test.tsx b/frontend/src/hooks/use-pagination.test.tsx
new file mode 100644
index 00000000..51388924
--- /dev/null
+++ b/frontend/src/hooks/use-pagination.test.tsx
@@ -0,0 +1,105 @@
+import type { ReactNode } from 'react';
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { MemoryRouter, useLocation } from 'react-router-dom';
+import { describe, expect, it } from 'vitest';
+
+import { usePagination } from './use-pagination';
+
+interface RenderResult {
+ pageIndex: number;
+ search: string;
+ setPage: (pageIndex: number) => void;
+}
+
+// Bundle `usePagination` + `useLocation` into a single hook so `renderHook`
+// observes both reactively — without this, a sibling `<LocationProbe>` lags
+// one render behind the canonicalization layout effect when the URL is
+// rewritten on mount.
+const usePaginationWithLocation = (): RenderResult => {
+ const { pageIndex, setPage } = usePagination();
+ const { search } = useLocation();
+
+ return { pageIndex, search, setPage };
+};
+
+const renderWithRouter = (initialEntries: string[]) => {
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter initialEntries={initialEntries}>{children}</MemoryRouter>
+ );
+
+ return renderHook(usePaginationWithLocation, { wrapper: Wrapper });
+};
+
+describe('usePagination', () => {
+ it('returns pageIndex 0 when no `?page=` is present', () => {
+ const { result } = renderWithRouter(['/flows']);
+ expect(result.current.pageIndex).toBe(0);
+ });
+
+ it('converts a 1-based `?page=` URL param to a 0-based index', () => {
+ const { result } = renderWithRouter(['/flows?page=3']);
+ expect(result.current.pageIndex).toBe(2);
+ });
+
+ it('falls back to 0 on a non-numeric `?page=`', () => {
+ const { result } = renderWithRouter(['/flows?page=notanumber']);
+ expect(result.current.pageIndex).toBe(0);
+ });
+
+ it('canonicalizes `?page=1` away from the URL on mount', async () => {
+ const { result } = renderWithRouter(['/flows?page=1']);
+
+ // `setSearchParams` from a layout effect schedules a transition that
+ // doesn't always commit in the same `act()` flush as the initial
+ // mount under React 19 + react-router 7, so wait for the URL to
+ // settle.
+ await waitFor(() => {
+ expect(result.current.search).toBe('');
+ });
+ });
+
+ it('canonicalizes `?page=1` but leaves other params untouched', async () => {
+ const { result } = renderWithRouter(['/flows?page=1&q=foo']);
+
+ await waitFor(() => {
+ const params = new URLSearchParams(result.current.search);
+ expect(params.has('page')).toBe(false);
+ });
+
+ expect(new URLSearchParams(result.current.search).get('q')).toBe('foo');
+ });
+
+ it('does not canonicalize `?page=2` (canonical form already)', () => {
+ const { result } = renderWithRouter(['/flows?page=2']);
+ expect(result.current.search).toBe('?page=2');
+ });
+
+ it('setPage(0) removes the `?page=` param entirely', () => {
+ const { result } = renderWithRouter(['/flows?page=5']);
+ act(() => result.current.setPage(0));
+ expect(result.current.search).toBe('');
+ });
+
+ it('setPage(N>0) writes 1-based number to `?page=`', () => {
+ const { result } = renderWithRouter(['/flows']);
+ act(() => result.current.setPage(4));
+ expect(result.current.search).toBe('?page=5');
+ });
+
+ it('setPage preserves other URL params', () => {
+ const { result } = renderWithRouter(['/flows?q=foo']);
+ act(() => result.current.setPage(2));
+ const params = new URLSearchParams(result.current.search ?? '');
+ expect(params.get('q')).toBe('foo');
+ expect(params.get('page')).toBe('3');
+ });
+
+ it('honors a custom paramName override', () => {
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter initialEntries={['/flows?p=4']}>{children}</MemoryRouter>
+ );
+ const { result } = renderHook(() => usePagination({ paramName: 'p' }), { wrapper: Wrapper });
+ expect(result.current.pageIndex).toBe(3);
+ });
+});
diff --git a/frontend/src/hooks/use-pagination.ts b/frontend/src/hooks/use-pagination.ts
new file mode 100644
index 00000000..f434473a
--- /dev/null
+++ b/frontend/src/hooks/use-pagination.ts
@@ -0,0 +1,104 @@
+import { useCallback, useEffect, useMemo } from 'react';
+import { useSearchParams } from 'react-router-dom';
+
+import { URL_PARAMS } from '@/lib/url-params';
+
+interface UsePaginationOptions {
+ /**
+ * Query string parameter that carries the 1-based page number. Default
+ * `URL_PARAMS.PAGE` (`'page'`). Override when a route needs a custom
+ * key (e.g. a page that already uses `?page=` for something else).
+ */
+ paramName?: string;
+}
+
+interface UsePaginationResult {
+ /**
+ * 0-based page index, suitable for handing straight to TanStack Table's
+ * `state.pagination.pageIndex`. The URL stores it 1-based for humans;
+ * the hook handles the off-by-one in both directions.
+ */
+ pageIndex: number;
+ /** Set the page index (0-based). Pass `0` to drop the URL param entirely. */
+ setPage: (pageIndex: number) => void;
+}
+
+/**
+ * URL-backed pagination state. The 1-based page number lives in `?page=`, so
+ * users can bookmark/share specific pages and the back/forward stack reflects
+ * page changes.
+ *
+ * Conventions:
+ * - The URL stores 1-based numbers (`?page=2` = second page) because that's
+ * what users see in pagers ("Page 2 of 10"). The hook converts to/from
+ * 0-based at the boundary.
+ * - `?page=1` is canonicalized away — the first page is the default URL.
+ * That avoids two URLs (`/flows` vs `/flows?page=1`) representing the
+ * same view, which would split the history stack.
+ *
+ * Pages that also use `useTableQueryFilter` get the `?page=` reset for free
+ * when the filter narrows the result set — see that hook's
+ * `clearPageParamOnChange` option.
+ */
+export const usePagination = ({ paramName = URL_PARAMS.PAGE }: UsePaginationOptions = {}): UsePaginationResult => {
+ const [searchParams, setSearchParams] = useSearchParams();
+
+ const pageIndex = useMemo(() => {
+ const page = searchParams.get(paramName);
+
+ if (!page) {
+ return 0;
+ }
+
+ const parsed = Number.parseInt(page, 10);
+
+ return Number.isFinite(parsed) ? Math.max(0, parsed - 1) : 0;
+ }, [paramName, searchParams]);
+
+ // Canonicalize `?<paramName>=1` to a clean URL whenever it shows up.
+ // Two URLs (`/flows` vs `/flows?page=1`) would otherwise denote the same
+ // view — splitting the history stack and giving link-sharers an ugly URL
+ // for "first page". The effect uses `replace: true` so the rewrite never
+ // adds a history entry, and is idempotent: once the param is removed it
+ // re-runs and immediately exits the `if`, no loop.
+ //
+ // `useEffect` (not `useLayoutEffect`) is intentional: the URL bar updates
+ // outside React's paint pipeline, so deferring the rewrite past commit
+ // costs nothing visible to the user, while letting the canonicalization
+ // settle through normal effect scheduling — friendlier to test harnesses
+ // and to react-router's own transition handling.
+ useEffect(() => {
+ if (searchParams.get(paramName) !== '1') {
+ return;
+ }
+
+ setSearchParams(
+ (previous) => {
+ const next = new URLSearchParams(previous);
+ next.delete(paramName);
+
+ return next;
+ },
+ { replace: true },
+ );
+ }, [paramName, searchParams, setSearchParams]);
+
+ const setPage = useCallback(
+ (newPageIndex: number) => {
+ setSearchParams((previous) => {
+ const next = new URLSearchParams(previous);
+
+ if (newPageIndex <= 0) {
+ next.delete(paramName);
+ } else {
+ next.set(paramName, String(newPageIndex + 1));
+ }
+
+ return next;
+ });
+ },
+ [paramName, setSearchParams],
+ );
+
+ return { pageIndex, setPage };
+};
diff --git a/frontend/src/hooks/use-table-query-filter.test.tsx b/frontend/src/hooks/use-table-query-filter.test.tsx
new file mode 100644
index 00000000..c5a6289e
--- /dev/null
+++ b/frontend/src/hooks/use-table-query-filter.test.tsx
@@ -0,0 +1,282 @@
+import type { ReactNode } from 'react';
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { MemoryRouter, useLocation } from 'react-router-dom';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { useTableQueryFilter, useTableQueryFilterReader } from './use-table-query-filter';
+
+const STORAGE_KEY = 'table_4_/flows';
+const SHORT_DEBOUNCE_MS = 5;
+
+interface RenderResult {
+ debouncedFilter: string;
+ filter: string;
+ resetFilter: () => void;
+ search: string;
+ setFilter: (value: string) => void;
+}
+
+const useFilterWithLocation = (options: { debounceMs?: number; storageKey?: string } = {}): RenderResult => {
+ const { debouncedFilter, filter, resetFilter, setFilter } = useTableQueryFilter({
+ debounceMs: options.debounceMs ?? SHORT_DEBOUNCE_MS,
+ storageKey: options.storageKey ?? STORAGE_KEY,
+ });
+ const { search } = useLocation();
+
+ return { debouncedFilter, filter, resetFilter, search, setFilter };
+};
+
+const renderWithRouter = (initialEntries: string[], options?: { debounceMs?: number; storageKey?: string }) => {
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter initialEntries={initialEntries}>{children}</MemoryRouter>
+ );
+
+ return renderHook(() => useFilterWithLocation(options), { wrapper: Wrapper });
+};
+
+beforeEach(() => {
+ localStorage.clear();
+});
+
+afterEach(() => {
+ localStorage.clear();
+});
+
+const readStoredFilter = (key: string): null | string => {
+ const raw = localStorage.getItem(key);
+
+ if (raw === null) {
+ return null;
+ }
+
+ try {
+ const parsed = JSON.parse(raw);
+
+ return typeof parsed?.filter === 'string' ? parsed.filter : null;
+ } catch {
+ return null;
+ }
+};
+
+describe('useTableQueryFilter — URL ↔ storage roundtrip', () => {
+ it('reads the initial filter from `?q=` when present', () => {
+ const { result } = renderWithRouter(['/flows?q=alpha']);
+ expect(result.current.filter).toBe('alpha');
+ });
+
+ it('returns an empty filter when neither URL nor storage have a value', () => {
+ const { result } = renderWithRouter(['/flows']);
+ expect(result.current.filter).toBe('');
+ });
+
+ // The restore-from-storage path lives in a `useEffect` that issues
+ // `setSearchParams` on mount. Under React 19 + react-router 7 the
+ // resulting URL transition lands one micro-task after the initial
+ // `act(render)` flush, so we drain one round of pending updates
+ // through an empty async `act` before asserting.
+ it('restores `?q=` from storage when the URL is empty', async () => {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify({ filter: 'alpha' }));
+ const { result } = renderWithRouter(['/flows']);
+
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(new URLSearchParams(result.current.search).get('q')).toBe('alpha');
+ expect(result.current.filter).toBe('alpha');
+ });
+
+ it('lets the URL win over storage when both have a value', async () => {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify({ filter: 'beta' }));
+ const { result } = renderWithRouter(['/flows?q=alpha']);
+
+ expect(result.current.filter).toBe('alpha');
+
+ // The hook should sync the URL value into storage so a subsequent
+ // tab without `?q=` resumes from the URL's intent, not the old one.
+ await waitFor(() => {
+ expect(readStoredFilter(STORAGE_KEY)).toBe('alpha');
+ });
+ });
+
+ it('setFilter writes the value into the URL', () => {
+ const { result } = renderWithRouter(['/flows']);
+
+ act(() => result.current.setFilter('gamma'));
+
+ expect(new URLSearchParams(result.current.search).get('q')).toBe('gamma');
+ });
+
+ it('setFilter("") drops the URL param entirely (no `?q=` empty entry)', () => {
+ const { result } = renderWithRouter(['/flows?q=alpha']);
+
+ act(() => result.current.setFilter(''));
+
+ expect(result.current.search).toBe('');
+ });
+
+ it('setFilter("") clears the storage entry through the effect-driven write', async () => {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify({ filter: 'alpha' }));
+ const { result } = renderWithRouter(['/flows?q=alpha']);
+
+ act(() => result.current.setFilter(''));
+
+ await waitFor(() => {
+ expect(readStoredFilter(STORAGE_KEY)).toBeNull();
+ });
+ });
+
+ it('persists the URL filter to storage once typing settles', async () => {
+ const { result } = renderWithRouter(['/flows']);
+
+ act(() => result.current.setFilter('persisted'));
+
+ await waitFor(() => {
+ expect(readStoredFilter(STORAGE_KEY)).toBe('persisted');
+ });
+ });
+
+ it('resetFilter is equivalent to setFilter("")', () => {
+ const { result } = renderWithRouter(['/flows?q=alpha']);
+
+ act(() => result.current.resetFilter());
+
+ expect(result.current.search).toBe('');
+ expect(result.current.filter).toBe('');
+ });
+
+ it('debouncedFilter eventually catches up with filter', async () => {
+ const { result } = renderWithRouter(['/flows']);
+
+ act(() => result.current.setFilter('typed'));
+ expect(result.current.filter).toBe('typed');
+
+ await waitFor(() => {
+ expect(result.current.debouncedFilter).toBe('typed');
+ });
+ });
+
+ it('does not clobber unrelated table state when writing the filter', async () => {
+ localStorage.setItem(
+ STORAGE_KEY,
+ JSON.stringify({ columnVisibility: { name: false }, sorting: [{ desc: true, id: 'createdAt' }] }),
+ );
+ const { result } = renderWithRouter(['/flows']);
+
+ act(() => result.current.setFilter('foo'));
+
+ await waitFor(() => {
+ const stored = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}');
+ expect(stored.filter).toBe('foo');
+ expect(stored.sorting).toEqual([{ desc: true, id: 'createdAt' }]);
+ expect(stored.columnVisibility).toEqual({ name: false });
+ });
+ });
+
+ it('re-restores when storageKey rotates while the hook stays mounted', async () => {
+ const FIRST_KEY = 'table_4_/flows';
+ const SECOND_KEY = 'table_4_/templates';
+ localStorage.setItem(SECOND_KEY, JSON.stringify({ filter: 'second-key' }));
+
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter initialEntries={['/flows']}>{children}</MemoryRouter>
+ );
+ const { rerender, result } = renderHook(
+ ({ key }) => {
+ const filter = useTableQueryFilter({ debounceMs: SHORT_DEBOUNCE_MS, storageKey: key });
+ const { search } = useLocation();
+
+ return { ...filter, search };
+ },
+ { initialProps: { key: FIRST_KEY }, wrapper: Wrapper },
+ );
+
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(result.current.filter).toBe('');
+
+ rerender({ key: SECOND_KEY });
+
+ await waitFor(() => {
+ expect(new URLSearchParams(result.current.search).get('q')).toBe('second-key');
+ });
+ });
+});
+
+describe('useTableQueryFilter — page param interaction', () => {
+ it('resets `?page=` when setFilter narrows the result set', () => {
+ const { result } = renderWithRouter(['/flows?page=3']);
+
+ act(() => result.current.setFilter('foo'));
+
+ const params = new URLSearchParams(result.current.search);
+ expect(params.has('page')).toBe(false);
+ expect(params.get('q')).toBe('foo');
+ });
+
+ it('keeps `?page=` when clearPageParamOnChange is false', () => {
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter initialEntries={['/flows?page=3']}>{children}</MemoryRouter>
+ );
+ const { result } = renderHook(
+ () => {
+ const filter = useTableQueryFilter({
+ clearPageParamOnChange: false,
+ debounceMs: SHORT_DEBOUNCE_MS,
+ storageKey: STORAGE_KEY,
+ });
+ const { search } = useLocation();
+
+ return { ...filter, search };
+ },
+ { wrapper: Wrapper },
+ );
+
+ act(() => result.current.setFilter('foo'));
+
+ const params = new URLSearchParams(result.current.search);
+ expect(params.get('page')).toBe('3');
+ });
+});
+
+describe('useTableQueryFilterReader', () => {
+ it('observes the URL filter without writing storage', () => {
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter initialEntries={['/flows/abc?q=alpha']}>{children}</MemoryRouter>
+ );
+ const { result } = renderHook(
+ () => useTableQueryFilterReader({ debounceMs: SHORT_DEBOUNCE_MS, storageKey: STORAGE_KEY }),
+ { wrapper: Wrapper },
+ );
+
+ expect(result.current.filter).toBe('alpha');
+ expect(localStorage.getItem(STORAGE_KEY)).toBeNull();
+ });
+
+ it('does not replay a stored filter into a clean URL', () => {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify({ filter: 'alpha' }));
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter initialEntries={['/flows/abc']}>{children}</MemoryRouter>
+ );
+ const { result } = renderHook(
+ () => {
+ const reader = useTableQueryFilterReader({
+ debounceMs: SHORT_DEBOUNCE_MS,
+ storageKey: STORAGE_KEY,
+ });
+ const { search } = useLocation();
+
+ return { ...reader, search };
+ },
+ { wrapper: Wrapper },
+ );
+
+ // A shared `/flows/abc` link explicitly clears the filter on entry —
+ // detail-page subscribers must not inject the previous tab's `?q=`
+ // back into the URL.
+ expect(result.current.search).toBe('');
+ expect(result.current.filter).toBe('');
+ });
+});
diff --git a/frontend/src/hooks/use-table-query-filter.ts b/frontend/src/hooks/use-table-query-filter.ts
new file mode 100644
index 00000000..675ae691
--- /dev/null
+++ b/frontend/src/hooks/use-table-query-filter.ts
@@ -0,0 +1,204 @@
+import { useCallback, useEffect, useMemo, useRef } from 'react';
+import { useSearchParams } from 'react-router-dom';
+
+import { useDebouncedValue } from '@/hooks/use-debounced-value';
+import { useEffectAfterMount } from '@/hooks/use-effect-after-mount';
+import { usePageStorageKeys } from '@/hooks/use-page-storage-keys';
+import { loadTableState, updateTableState } from '@/lib/table-state';
+import { URL_PARAMS } from '@/lib/url-params';
+
+interface UseTableQueryFilterOptions {
+ /**
+ * Whether to also reset the `?page=` URL param when the filter changes.
+ * Pages that pair URL filter with URL pagination need this so the user
+ * doesn't end up "on page 5 of nothing" after narrowing the result set.
+ * Defaults to `true`.
+ */
+ clearPageParamOnChange?: boolean;
+ debounceMs?: number;
+ /**
+ * The query string param that carries the filter. Default `URL_PARAMS.QUERY`
+ * (`'q'`) matches the conventional "search query" name and is consistent
+ * across pages.
+ */
+ paramName?: string;
+ /**
+ * Stable storage key for persisting the most recent value (a fresh tab
+ * without `?q=` resumes from here). When omitted, defaults to
+ * `usePageStorageKeys().table` — i.e. `table_4_<current pathname>`,
+ * which is the right key for any top-level list route. Override only
+ * for nested routes or when you need to share a storage slot across
+ * paths (the same way a detail page shares its parent list's slot
+ * through `useTableQueryFilterReader`).
+ */
+ storageKey?: string;
+}
+
+interface UseTableQueryFilterReaderResult {
+ debouncedFilter: string;
+ filter: string;
+}
+
+interface UseTableQueryFilterResult extends UseTableQueryFilterReaderResult {
+ resetFilter: () => void;
+ setFilter: (value: string) => void;
+}
+
+/**
+ * Pure URL reader: surface the live + debounced filter without touching
+ * storage or scheduling any side-effects.
+ *
+ * Re-evaluates whenever `?<paramName>=` changes — so a detail page that
+ * subscribes via `useTableQueryFilterReader` (or any caller that wants
+ * read-only access) stays in sync with whatever the list page typed.
+ */
+const useFilterFromUrl = ({
+ debounceMs = 200,
+ paramName = URL_PARAMS.QUERY,
+}: Pick<UseTableQueryFilterOptions, 'debounceMs' | 'paramName'>): UseTableQueryFilterReaderResult => {
+ const [searchParams] = useSearchParams();
+ const filter = searchParams.get(paramName) ?? '';
+ const debouncedFilter = useDebouncedValue(filter, debounceMs);
+
+ return useMemo(() => ({ debouncedFilter, filter }), [debouncedFilter, filter]);
+};
+
+/**
+ * Read-only subscription to the URL filter for pages that observe the value
+ * but never mutate it (typically detail pages, where the toolbar walks the
+ * filtered subset but the user types the filter on the list page).
+ *
+ * Unlike `useTableQueryFilter`, this hook never writes to the URL or storage:
+ * a detail page opened by a shared `/flows/:id` link will not silently inject
+ * the previous tab's `?q=` into the URL. The `storageKey` option is accepted
+ * for API symmetry but ignored here — there is no storage interaction at all.
+ */
+export const useTableQueryFilterReader = (options: UseTableQueryFilterOptions = {}): UseTableQueryFilterReaderResult => {
+ return useFilterFromUrl(options);
+};
+
+/**
+ * URL ↔ localStorage filter for list pages.
+ *
+ * - Source of truth is `?<paramName>=` in the URL — that lets users share /
+ * bookmark a filtered view, and any explicit path-level navigation (a
+ * route change, opening a detail page, etc.) is captured by react-router's
+ * own history entry alongside whatever filter was active at that moment.
+ * - On mount (and whenever the effective `storageKey` rotates — e.g. the
+ * route changes while the hook stays mounted in a shared layout), if the
+ * URL has no `?<paramName>=` but storage does, we replay the stored value
+ * into the URL (using `replace: true`, so the restore doesn't pollute the
+ * back stack).
+ * - Every typed change goes into the URL with `replace: true`. That means
+ * intermediate filter values do **not** create new history entries —
+ * browser back skips past the filter typing session in one step rather
+ * than walking through `'f' → 'fo' → 'foo'`.
+ * - Storage is the single sink. The unified `table` slot
+ * (`updateTableState`) carries `filter` alongside the rest of the table
+ * state — sorting, column visibility, page size — under one key per page.
+ * Each commit writes synchronously through `useEffectAfterMount`: a single
+ * source of truth removes the previous double-write pattern (sync clear +
+ * debounced effect) that risked races on refresh.
+ */
+export const useTableQueryFilter = (options: UseTableQueryFilterOptions = {}): UseTableQueryFilterResult => {
+ const { clearPageParamOnChange = true, paramName = URL_PARAMS.QUERY, storageKey: explicitStorageKey } = options;
+ const [, setSearchParams] = useSearchParams();
+ const { table: defaultStorageKey } = usePageStorageKeys();
+ const storageKey = explicitStorageKey ?? defaultStorageKey;
+
+ const { debouncedFilter, filter } = useFilterFromUrl(options);
+
+ // Track which storageKey we've already restored from. When the key
+ // rotates (route change inside a persistent layout, or an explicit
+ // override prop change) we reset the guard so the new slot gets one
+ // restore attempt — this is the fix for the "lazy useState captured the
+ // mount-time key forever" pitfall the previous design had.
+ const restoredForKeyReference = useRef<null | string>(null);
+
+ // `filter` participates in the dep array directly, not through a ref.
+ // Two reasons:
+ // 1. The `restoredForKeyReference` guard makes the effect a no-op on
+ // keystrokes — the early return fires before any storage write,
+ // so the per-keystroke re-runs cost is one Map lookup.
+ // 2. `useLatestRef`-style refs have a one-commit lag (the sync
+ // `useEffect` runs *after* the consumer). Reading the URL filter
+ // that way at the moment `storageKey` rotates would see the
+ // *previous* route's value. Plain dep gives the freshest value.
+ useEffect(() => {
+ if (restoredForKeyReference.current === storageKey) {
+ return;
+ }
+
+ restoredForKeyReference.current = storageKey;
+
+ if (filter.length > 0) {
+ // The URL already has a value — that beats storage. Sync it into
+ // storage so a fresh tab without `?<paramName>=` resumes from
+ // this intent (e.g. user landed via a shared filtered link).
+ updateTableState(storageKey, { filter });
+
+ return;
+ }
+
+ const stored = loadTableState(storageKey).filter;
+
+ if (!stored || stored.length === 0) {
+ return;
+ }
+
+ setSearchParams(
+ (previous) => {
+ const next = new URLSearchParams(previous);
+ next.set(paramName, stored);
+
+ if (clearPageParamOnChange) {
+ next.delete(URL_PARAMS.PAGE);
+ }
+
+ return next;
+ },
+ { replace: true },
+ );
+ }, [clearPageParamOnChange, filter, paramName, setSearchParams, storageKey]);
+
+ // Persist the URL filter into storage on every commit. Skipping the
+ // first render is intentional: a fresh-mount empty `filter` would
+ // wipe a freshly-restored storage entry before the restore effect
+ // above has had a chance to replay it into the URL.
+ useEffectAfterMount(() => {
+ updateTableState(storageKey, { filter: filter.length > 0 ? filter : undefined });
+ }, [filter, storageKey]);
+
+ const setFilter = useCallback(
+ (value: string) => {
+ setSearchParams(
+ (previous) => {
+ const next = new URLSearchParams(previous);
+
+ if (value.length === 0) {
+ next.delete(paramName);
+ } else {
+ next.set(paramName, value);
+ }
+
+ if (clearPageParamOnChange) {
+ next.delete(URL_PARAMS.PAGE);
+ }
+
+ return next;
+ },
+ { replace: true },
+ );
+ },
+ [clearPageParamOnChange, paramName, setSearchParams],
+ );
+
+ const resetFilter = useCallback(() => {
+ setFilter('');
+ }, [setFilter]);
+
+ return useMemo(
+ () => ({ debouncedFilter, filter, resetFilter, setFilter }),
+ [debouncedFilter, filter, resetFilter, setFilter],
+ );
+};
diff --git a/frontend/src/lib/local-storage.ts b/frontend/src/lib/local-storage.ts
index 37aee7ae..a3dde80c 100644
--- a/frontend/src/lib/local-storage.ts
+++ b/frontend/src/lib/local-storage.ts
@@ -24,6 +24,15 @@ export function getStorageItem<T>(key: string, schema: z.ZodType<T>): null | T {
}
}
+/** Remove `key` from `localStorage`. Silently no-ops on failure. */
+export function removeStorageItem(key: string): void {
+ try {
+ localStorage.removeItem(key);
+ } catch {
+ /* localStorage may be unavailable */
+ }
+}
+
/** Serialize `value` to JSON and store it in `localStorage`. Silently no-ops on failure. */
export function setStorageItem(key: string, value: unknown): void {
try {
diff --git a/frontend/src/lib/storage-keys.test.ts b/frontend/src/lib/storage-keys.test.ts
new file mode 100644
index 00000000..bdfafcc0
--- /dev/null
+++ b/frontend/src/lib/storage-keys.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ getPeriodStorageKey,
+ getStorageKey,
+ getTableStorageKey,
+ getTopLevelPath,
+ getViewOptionsStorageKey,
+} from './storage-keys';
+
+describe('getTopLevelPath', () => {
+ it('returns the first segment with a leading slash for top-level paths', () => {
+ expect(getTopLevelPath('/flows')).toBe('/flows');
+ });
+
+ it('strips the id from detail-page paths', () => {
+ expect(getTopLevelPath('/flows/abc-123')).toBe('/flows');
+ expect(getTopLevelPath('/knowledges/abc/foo')).toBe('/knowledges');
+ });
+
+ it('returns an empty string for the root', () => {
+ expect(getTopLevelPath('/')).toBe('');
+ expect(getTopLevelPath('')).toBe('');
+ });
+
+ it('handles paths without a leading slash', () => {
+ expect(getTopLevelPath('flows/123')).toBe('/flows');
+ });
+
+ it('skips repeated leading slashes', () => {
+ expect(getTopLevelPath('//flows/123')).toBe('/flows');
+ });
+});
+
+describe('getStorageKey', () => {
+ it('joins type and path with the `_4_` separator', () => {
+ expect(getStorageKey('table', '/flows')).toBe('table_4_/flows');
+ expect(getStorageKey('period', '/dashboard')).toBe('period_4_/dashboard');
+ });
+});
+
+describe('typed key helpers', () => {
+ it('getTableStorageKey delegates to the unified `table` namespace', () => {
+ expect(getTableStorageKey('/flows')).toBe('table_4_/flows');
+ });
+
+ it('getPeriodStorageKey delegates to the `period` namespace', () => {
+ expect(getPeriodStorageKey('/dashboard')).toBe('period_4_/dashboard');
+ });
+
+ it('getViewOptionsStorageKey delegates to the `viewOptions` namespace', () => {
+ expect(getViewOptionsStorageKey('/resources')).toBe('viewOptions_4_/resources');
+ });
+});
diff --git a/frontend/src/lib/storage-keys.ts b/frontend/src/lib/storage-keys.ts
index b6936c19..c0133937 100644
--- a/frontend/src/lib/storage-keys.ts
+++ b/frontend/src/lib/storage-keys.ts
@@ -1,30 +1,81 @@
-const STORAGE_KEY_SEPARATOR = '_4_';
+/**
+ * Separator joining the namespace tag and the URL path inside a storage key.
+ * Reads as "for" — e.g. `table_4_/flows` is "table for /flows". Exported so
+ * the legacy-key migration helpers can reuse the exact same delimiter rather
+ * than re-stating it (a desync between the two would silently break
+ * migrations).
+ */
+export const STORAGE_KEY_SEPARATOR = '_4_';
-export type LocalStorageKeyType = 'column' | 'page' | 'period' | 'sorting';
+/**
+ * Discrete storage namespaces. Every list/detail page persists at most three
+ * slots — `table` (filter + sorting + columnVisibility + pageSize as one
+ * JSON object), `period` (dashboard-only time window), and `viewOptions`
+ * (FileManager-style screens that aren't backed by `DataTable`). Add new
+ * namespaces here rather than passing raw strings to {@link getStorageKey}.
+ */
+export type LocalStorageKeyType = 'period' | 'table' | 'viewOptions';
-export function getColumnStorageKey(urlPath?: string): string {
- return getStorageKey('column', urlPath);
+/** Dashboard analytics time window. Lives outside the unified table slot. */
+export function getPeriodStorageKey(urlPath: string): string {
+ return getStorageKey('period', urlPath);
}
-export function getPageStorageKey(urlPath?: string): string {
- return getStorageKey('page', urlPath);
+/**
+ * Build a storage key from a `type` tag and the URL path that owns the slot.
+ *
+ * Format: `${type}_4_${urlPath}` (where `_4_` reads as "for", linking the
+ * type to the path it scopes).
+ *
+ * `urlPath` is required: callers must source it from `useLocation()` (or
+ * pass an override for nested routes), not from a global `location` read.
+ * That keeps this module pure and reactive — when react-router navigates,
+ * a hook that depends on `pathname` re-evaluates the key automatically.
+ */
+export function getStorageKey(type: LocalStorageKeyType, urlPath: string): string {
+ return `${type}${STORAGE_KEY_SEPARATOR}${urlPath}`;
}
-export function getPeriodStorageKey(urlPath?: string): string {
- return getStorageKey('period', urlPath);
+/**
+ * Unified per-page table state slot — one JSON object holds filter, sorting,
+ * column visibility, and page size. Replaces the older four-key fan-out
+ * (`column_4_`, `sorting_4_`, `filter_4_`, `page_4_`); see
+ * `migrateLegacyTableState` in `table-state.ts` for the one-shot reader of
+ * those legacy slots.
+ */
+export function getTableStorageKey(urlPath: string): string {
+ return getStorageKey('table', urlPath);
}
-export function getSortingStorageKey(urlPath?: string): string {
- return getStorageKey('sorting', urlPath);
+/**
+ * Returns the first non-empty segment of a path with a leading `/`.
+ *
+ * Used by detail pages to derive the parent list's path without hardcoding
+ * it. Example:
+ * `/flows` → `/flows`
+ * `/flows/abc-123` → `/flows`
+ * `/knowledges/abc/foo` → `/knowledges`
+ * `/` → `''`
+ *
+ * Limitation: this only walks one level deep, so it will misidentify the
+ * parent for nested lists like `/admin/flows/:id` (returns `/admin` instead
+ * of `/admin/flows`). All current list pages live at the top level, but if
+ * a nested list ships, the corresponding detail page must hardcode its
+ * parent path explicitly instead of using this helper.
+ */
+export function getTopLevelPath(pathname: string): string {
+ const firstSegment = pathname.split('/').filter(Boolean)[0];
+
+ return firstSegment ? `/${firstSegment}` : '';
}
/**
- * Builds a storage key from type and current page path.
- * Format: `${type}_4_${urlPath}`
- * If urlPath is not passed, uses window.location.pathname (client only).
+ * View options for `FileManager`-style screens (currently `/resources`).
+ * Not part of the unified `table` slot because the payload (folder-first
+ * toggle, expanded directory ids) has nothing in common with TanStack
+ * Table state — sharing the key would force a union schema and waste
+ * a Zod validation round-trip on every save.
*/
-export function getStorageKey(type: LocalStorageKeyType, urlPath?: string): string {
- const path = urlPath ?? location?.pathname ?? '';
-
- return `${type}${STORAGE_KEY_SEPARATOR}${path}`;
+export function getViewOptionsStorageKey(urlPath: string): string {
+ return getStorageKey('viewOptions', urlPath);
}
diff --git a/frontend/src/lib/table-filter.test.ts b/frontend/src/lib/table-filter.test.ts
new file mode 100644
index 00000000..6deb594b
--- /dev/null
+++ b/frontend/src/lib/table-filter.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it } from 'vitest';
+
+import { createTextMatcher, matchesTextFilter, normalizeForFilter } from './table-filter';
+
+describe('normalizeForFilter', () => {
+ it('lowercases ASCII text', () => {
+ expect(normalizeForFilter('FooBar')).toBe('foobar');
+ });
+
+ it('strips combining diacritics so accented characters fold to plain', () => {
+ expect(normalizeForFilter('café')).toBe('cafe');
+ expect(normalizeForFilter('résumé')).toBe('resume');
+ expect(normalizeForFilter('naïve')).toBe('naive');
+ });
+
+ it('is idempotent', () => {
+ const once = normalizeForFilter('Café');
+ expect(normalizeForFilter(once)).toBe(once);
+ });
+});
+
+describe('createTextMatcher', () => {
+ it('returns a matcher that accepts everything for an empty query', () => {
+ const matcher = createTextMatcher('');
+
+ expect(matcher('anything')).toBe(true);
+ expect(matcher('')).toBe(true);
+ expect(matcher(null)).toBe(true);
+ expect(matcher(undefined)).toBe(true);
+ });
+
+ it('matches case-insensitively', () => {
+ const matcher = createTextMatcher('Foo');
+
+ expect(matcher('foo')).toBe(true);
+ expect(matcher('FOO')).toBe(true);
+ expect(matcher('hello FOO bar')).toBe(true);
+ expect(matcher('bar')).toBe(false);
+ });
+
+ it('matches across diacritic-folded forms', () => {
+ const matcher = createTextMatcher('cafe');
+
+ expect(matcher('café')).toBe(true);
+ expect(matcher('Café au lait')).toBe(true);
+ expect(matcher('CAFÉ')).toBe(true);
+ });
+
+ it('folds diacritics in the query too', () => {
+ const matcher = createTextMatcher('Café');
+
+ expect(matcher('cafe')).toBe(true);
+ expect(matcher('CAFE')).toBe(true);
+ });
+
+ it('returns false for null and undefined text when query is non-empty', () => {
+ const matcher = createTextMatcher('foo');
+
+ expect(matcher(null)).toBe(false);
+ expect(matcher(undefined)).toBe(false);
+ });
+
+ it('does substring matching, not whole-word or prefix matching', () => {
+ const matcher = createTextMatcher('ell');
+
+ expect(matcher('hello')).toBe(true);
+ expect(matcher('shell shocked')).toBe(true);
+ expect(matcher('apricot')).toBe(false);
+ });
+
+ it('preserves whitespace exactly — does not trim the query', () => {
+ const matcher = createTextMatcher(' foo ');
+
+ expect(matcher(' foo ')).toBe(true);
+ expect(matcher('foo')).toBe(false);
+ });
+
+ it('returns the same matcher behaviour across many invocations (no internal state leak)', () => {
+ const matcher = createTextMatcher('abc');
+
+ for (let i = 0; i < 10; i += 1) {
+ expect(matcher('xxabcyy')).toBe(true);
+ expect(matcher('xyz')).toBe(false);
+ }
+ });
+});
+
+describe('matchesTextFilter', () => {
+ it('delegates to createTextMatcher and produces the same answers', () => {
+ expect(matchesTextFilter('hello', 'ell')).toBe(true);
+ expect(matchesTextFilter('hello', 'world')).toBe(false);
+ expect(matchesTextFilter(null, 'foo')).toBe(false);
+ expect(matchesTextFilter(null, '')).toBe(true);
+ });
+
+ it('folds diacritics symmetrically on both sides', () => {
+ expect(matchesTextFilter('résumé.pdf', 'resume')).toBe(true);
+ expect(matchesTextFilter('resume.pdf', 'résumé')).toBe(true);
+ });
+});
diff --git a/frontend/src/lib/table-filter.ts b/frontend/src/lib/table-filter.ts
new file mode 100644
index 00000000..16356190
--- /dev/null
+++ b/frontend/src/lib/table-filter.ts
@@ -0,0 +1,52 @@
+/**
+ * Normalize a string for case- and diacritic-insensitive substring matching.
+ *
+ * `NFKD` decomposes accented characters into base + combining marks, then we
+ * strip the combining marks (`\p{Diacritic}` regex class) so e.g. `café`
+ * matches `cafe`. Lowercasing happens last to fold case differences.
+ *
+ * Exported for callers that need to align their own search semantics with the
+ * one this module uses (e.g. server-side prefiltering).
+ */
+export const normalizeForFilter = (text: string): string =>
+ text.normalize('NFKD').replace(/\p{Diacritic}/gu, '').toLowerCase();
+
+/**
+ * Build a reusable text-matcher specialised for `query`. The query is
+ * normalized + lowercased once at factory time — when the resulting matcher
+ * is invoked N times during list filtering, that work is amortised to one
+ * allocation instead of N.
+ *
+ * The matcher uses substring matching semantics, with case + diacritic
+ * folding (`café` matches `cafe`). It is intentionally close to TanStack
+ * Table's default `'includesString'` so a single instance can drive both
+ * the list page's column filter and the detail page's Prev/Next subset
+ * without the two paths drifting out of sync.
+ *
+ * - Empty query → every row passes (matcher returns `true`).
+ * - `text === null | undefined` with a non-empty query → no match.
+ */
+export const createTextMatcher = (query: string): ((text: null | string | undefined) => boolean) => {
+ if (!query.length) {
+ return () => true;
+ }
+
+ const normalizedQuery = normalizeForFilter(query);
+
+ return (text) => {
+ if (text === null || text === undefined) {
+ return false;
+ }
+
+ return normalizeForFilter(text).includes(normalizedQuery);
+ };
+};
+
+/**
+ * One-shot variant of {@link createTextMatcher} for callers that need a
+ * single comparison and don't want to bother with the factory. Equivalent to
+ * `createTextMatcher(query)(text)` — kept as a thin wrapper for readability
+ * at call sites and to preserve the original API.
+ */
+export const matchesTextFilter = (text: null | string | undefined, query: string): boolean =>
+ createTextMatcher(query)(text);
diff --git a/frontend/src/lib/table-sort.test.ts b/frontend/src/lib/table-sort.test.ts
new file mode 100644
index 00000000..6d41edc8
--- /dev/null
+++ b/frontend/src/lib/table-sort.test.ts
@@ -0,0 +1,53 @@
+import type { Column } from '@tanstack/react-table';
+
+import { describe, expect, it, vi } from 'vitest';
+
+import { cycleColumnSort } from './table-sort';
+
+interface FakeColumn {
+ clearSorting: ReturnType<typeof vi.fn>;
+ getIsSorted: ReturnType<typeof vi.fn>;
+ toggleSorting: ReturnType<typeof vi.fn>;
+}
+
+// Build a stub that satisfies the subset of `Column` we actually call. Using
+// `unknown as Column<...>` keeps the test free of @tanstack/react-table
+// internals while still letting us pass the stub to the typed function.
+const makeColumn = (sorted: 'asc' | 'desc' | false): FakeColumn => ({
+ clearSorting: vi.fn(),
+ getIsSorted: vi.fn().mockReturnValue(sorted),
+ toggleSorting: vi.fn(),
+});
+
+describe('cycleColumnSort', () => {
+ it('starts the cycle on a column with no sort by setting ascending', () => {
+ const column = makeColumn(false);
+ cycleColumnSort(column as unknown as Column<unknown>);
+
+ expect(column.toggleSorting).toHaveBeenCalledWith(false);
+ expect(column.clearSorting).not.toHaveBeenCalled();
+ });
+
+ it('advances ascending to descending', () => {
+ const column = makeColumn('asc');
+ cycleColumnSort(column as unknown as Column<unknown>);
+
+ expect(column.toggleSorting).toHaveBeenCalledWith(true);
+ expect(column.clearSorting).not.toHaveBeenCalled();
+ });
+
+ it('clears the sort after descending — the third tap removes the sort entirely', () => {
+ const column = makeColumn('desc');
+ cycleColumnSort(column as unknown as Column<unknown>);
+
+ expect(column.clearSorting).toHaveBeenCalledTimes(1);
+ expect(column.toggleSorting).not.toHaveBeenCalled();
+ });
+
+ it('reads `getIsSorted` exactly once per call — no double-evaluation between branches', () => {
+ const column = makeColumn('asc');
+ cycleColumnSort(column as unknown as Column<unknown>);
+
+ expect(column.getIsSorted).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/frontend/src/lib/table-state.test.ts b/frontend/src/lib/table-state.test.ts
new file mode 100644
index 00000000..72b03fc3
--- /dev/null
+++ b/frontend/src/lib/table-state.test.ts
@@ -0,0 +1,188 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { loadTableState, migrateLegacyTableState, updateTableState } from './table-state';
+
+const PATH = '/flows';
+const UNIFIED_KEY = `table_4_${PATH}`;
+
+const LEGACY_COLUMN_KEY = `column_4_${PATH}`;
+const LEGACY_SORTING_KEY = `sorting_4_${PATH}`;
+const LEGACY_FILTER_KEY = `filter_4_${PATH}`;
+const LEGACY_PAGE_KEY = `page_4_${PATH}`;
+
+beforeEach(() => {
+ localStorage.clear();
+});
+
+afterEach(() => {
+ localStorage.clear();
+});
+
+describe('loadTableState', () => {
+ it('returns an empty object when the key is missing', () => {
+ expect(loadTableState(UNIFIED_KEY)).toEqual({});
+ });
+
+ it('returns an empty object when the payload is invalid JSON', () => {
+ localStorage.setItem(UNIFIED_KEY, 'not json');
+ expect(loadTableState(UNIFIED_KEY)).toEqual({});
+ });
+
+ it('returns an empty object when the payload fails the schema', () => {
+ localStorage.setItem(UNIFIED_KEY, JSON.stringify({ filter: 42 }));
+ expect(loadTableState(UNIFIED_KEY)).toEqual({});
+ });
+
+ it('round-trips a full state object', () => {
+ const state = {
+ columnVisibility: { name: false },
+ filter: 'alpha',
+ pageSize: 25,
+ sorting: [{ desc: true, id: 'createdAt' }],
+ };
+ localStorage.setItem(UNIFIED_KEY, JSON.stringify(state));
+ expect(loadTableState(UNIFIED_KEY)).toEqual(state);
+ });
+});
+
+describe('updateTableState', () => {
+ it('writes a partial patch on top of the existing state', () => {
+ localStorage.setItem(UNIFIED_KEY, JSON.stringify({ filter: 'alpha', pageSize: 25 }));
+ updateTableState(UNIFIED_KEY, { sorting: [{ desc: false, id: 'name' }] });
+
+ const stored = JSON.parse(localStorage.getItem(UNIFIED_KEY) ?? '{}');
+ expect(stored.filter).toBe('alpha');
+ expect(stored.pageSize).toBe(25);
+ expect(stored.sorting).toEqual([{ desc: false, id: 'name' }]);
+ });
+
+ it('clears a field via `undefined`', () => {
+ localStorage.setItem(UNIFIED_KEY, JSON.stringify({ filter: 'alpha', pageSize: 25 }));
+ updateTableState(UNIFIED_KEY, { filter: undefined });
+
+ const stored = JSON.parse(localStorage.getItem(UNIFIED_KEY) ?? '{}');
+ expect('filter' in stored).toBe(false);
+ expect(stored.pageSize).toBe(25);
+ });
+
+ it('collapses empty strings / arrays / records to "no value"', () => {
+ localStorage.setItem(
+ UNIFIED_KEY,
+ JSON.stringify({ columnVisibility: { name: false }, filter: 'foo', sorting: [{ desc: true, id: 'a' }] }),
+ );
+
+ updateTableState(UNIFIED_KEY, { columnVisibility: {}, filter: '', sorting: [] });
+
+ const stored = JSON.parse(localStorage.getItem(UNIFIED_KEY) ?? '{}');
+ expect(stored).toEqual({});
+ });
+
+ it('removes the storage key when the merged state is empty', () => {
+ localStorage.setItem(UNIFIED_KEY, JSON.stringify({ filter: 'alpha' }));
+
+ updateTableState(UNIFIED_KEY, { filter: undefined });
+
+ expect(localStorage.getItem(UNIFIED_KEY)).toBeNull();
+ });
+
+ it('returns the merged state for the caller', () => {
+ const next = updateTableState(UNIFIED_KEY, { pageSize: 50 });
+ expect(next).toEqual({ pageSize: 50 });
+ });
+});
+
+describe('migrateLegacyTableState', () => {
+ it('short-circuits to loadTableState when no legacy keys exist', () => {
+ localStorage.setItem(UNIFIED_KEY, JSON.stringify({ filter: 'unified' }));
+
+ const result = migrateLegacyTableState(PATH, UNIFIED_KEY);
+
+ expect(result).toEqual({ filter: 'unified' });
+ // Storage should remain untouched.
+ expect(JSON.parse(localStorage.getItem(UNIFIED_KEY) ?? '{}')).toEqual({ filter: 'unified' });
+ });
+
+ it('folds legacy sorting / column / filter / page-size into the unified slot', () => {
+ localStorage.setItem(LEGACY_SORTING_KEY, JSON.stringify([{ desc: true, id: 'createdAt' }]));
+ localStorage.setItem(LEGACY_COLUMN_KEY, JSON.stringify({ name: false }));
+ localStorage.setItem(LEGACY_FILTER_KEY, JSON.stringify('alpha'));
+ localStorage.setItem(LEGACY_PAGE_KEY, JSON.stringify({ page: 4, pageSize: 25 }));
+
+ const result = migrateLegacyTableState(PATH, UNIFIED_KEY);
+
+ expect(result).toEqual({
+ columnVisibility: { name: false },
+ filter: 'alpha',
+ pageSize: 25,
+ sorting: [{ desc: true, id: 'createdAt' }],
+ });
+
+ // Legacy keys must be deleted after the fold so they never resurface.
+ expect(localStorage.getItem(LEGACY_SORTING_KEY)).toBeNull();
+ expect(localStorage.getItem(LEGACY_COLUMN_KEY)).toBeNull();
+ expect(localStorage.getItem(LEGACY_FILTER_KEY)).toBeNull();
+ expect(localStorage.getItem(LEGACY_PAGE_KEY)).toBeNull();
+ });
+
+ it('drops the legacy `page` field — only `pageSize` survives the migration', () => {
+ // The page index now lives in `?page=`, not storage. Carrying the
+ // old `page` field forward would put it back into a place the rest
+ // of the app no longer reads from.
+ localStorage.setItem(LEGACY_PAGE_KEY, JSON.stringify({ page: 4, pageSize: 25 }));
+
+ const result = migrateLegacyTableState(PATH, UNIFIED_KEY);
+
+ expect(result).toEqual({ pageSize: 25 });
+ expect((result as { page?: number }).page).toBeUndefined();
+ });
+
+ it('is idempotent — a second invocation reads the unified slot only', () => {
+ localStorage.setItem(LEGACY_SORTING_KEY, JSON.stringify([{ desc: true, id: 'x' }]));
+
+ migrateLegacyTableState(PATH, UNIFIED_KEY);
+ const second = migrateLegacyTableState(PATH, UNIFIED_KEY);
+
+ expect(second).toEqual({ sorting: [{ desc: true, id: 'x' }] });
+ });
+
+ it('skips fields whose legacy payload fails the schema', () => {
+ // A legacy `column_4_` key that holds non-boolean values (e.g.
+ // because the format changed mid-history). The migration should
+ // silently drop it instead of polluting the unified state.
+ localStorage.setItem(LEGACY_COLUMN_KEY, JSON.stringify({ name: 'visible' }));
+ localStorage.setItem(LEGACY_FILTER_KEY, JSON.stringify('alpha'));
+
+ const result = migrateLegacyTableState(PATH, UNIFIED_KEY);
+
+ expect(result).toEqual({ filter: 'alpha' });
+ // Legacy keys must still be deleted — they're invalid either way.
+ expect(localStorage.getItem(LEGACY_COLUMN_KEY)).toBeNull();
+ expect(localStorage.getItem(LEGACY_FILTER_KEY)).toBeNull();
+ });
+
+ it('migrates legacy keys stored under the trailing-slash pathname variant', () => {
+ const pathNoSlash = '/flows';
+ const pathSlash = `${pathNoSlash}/`;
+ const unifiedKey = `table_4_${pathNoSlash}`;
+ localStorage.setItem(`sorting_4_${pathSlash}`, JSON.stringify([{ desc: false, id: 'title' }]));
+
+ const result = migrateLegacyTableState(pathNoSlash, unifiedKey);
+
+ expect(result.sorting).toEqual([{ desc: false, id: 'title' }]);
+ expect(localStorage.getItem(`sorting_4_${pathSlash}`)).toBeNull();
+ expect(localStorage.getItem(`sorting_4_${pathNoSlash}`)).toBeNull();
+ });
+
+ it('migrates legacy keys from the canonical path when migration is invoked with a trailing slash', () => {
+ const pathSlash = '/flows/';
+ const pathCanonical = '/flows';
+ const unifiedKey = `table_4_${pathSlash}`;
+ localStorage.setItem(`filter_4_${pathCanonical}`, JSON.stringify('needle'));
+
+ const result = migrateLegacyTableState(pathSlash, unifiedKey);
+
+ expect(result.filter).toBe('needle');
+ expect(localStorage.getItem(`filter_4_${pathCanonical}`)).toBeNull();
+ expect(localStorage.getItem(`filter_4_${pathSlash}`)).toBeNull();
+ });
+});
diff --git a/frontend/src/lib/table-state.ts b/frontend/src/lib/table-state.ts
new file mode 100644
index 00000000..4061c471
--- /dev/null
+++ b/frontend/src/lib/table-state.ts
@@ -0,0 +1,144 @@
+import { z } from 'zod';
+
+import { getStorageItem, removeStorageItem, setStorageItem } from './local-storage';
+import { STORAGE_KEY_SEPARATOR } from './storage-keys';
+
+const sortingSchema = z.array(z.object({ desc: z.boolean(), id: z.string() }));
+const visibilitySchema = z.record(z.string(), z.boolean());
+
+/**
+ * Unified table state schema. All per-page table preferences live under one
+ * JSON key (`table_4_<path>`) instead of fanning out into `column_4_/`,
+ * `sorting_4_/`, `filter_4_/` etc. Every field is optional so partial state
+ * (e.g. only a filter, no custom column visibility) doesn't force defaults
+ * into storage.
+ *
+ * `pageSize` is the user's chosen rows-per-page; the current `page` index
+ * stays in the URL where it can be bookmarked.
+ */
+const tableStateSchema = z.object({
+ columnVisibility: visibilitySchema.optional(),
+ filter: z.string().optional(),
+ pageSize: z.number().int().positive().optional(),
+ sorting: sortingSchema.optional(),
+});
+
+export type TableState = z.infer<typeof tableStateSchema>;
+
+const LEGACY_TYPES = ['column', 'sorting', 'filter', 'page'] as const;
+const legacyPageSchema = z.object({ page: z.number(), pageSize: z.number() });
+
+/** Paths that historically wrote legacy keys with or without a trailing `/`. */
+const legacyStoragePathVariants = (path: string): string[] => {
+ if (path === '/') {
+ return ['/'];
+ }
+
+ const withoutTrailing = path.replace(/\/+$/, '');
+ const canonical = withoutTrailing === '' ? '/' : withoutTrailing;
+ const withSlash = `${canonical}/`;
+
+ return canonical === path ? [canonical, withSlash] : [path, canonical];
+};
+
+const legacyKeysForPath = (p: string): string[] =>
+ LEGACY_TYPES.map((type) => `${type}${STORAGE_KEY_SEPARATOR}${p}`);
+
+/** Read the unified state. Returns `{}` when missing or invalid. */
+export const loadTableState = (key: string): TableState => getStorageItem(key, tableStateSchema) ?? {};
+
+/**
+ * Merge `patch` into the stored state. `undefined` values clear the
+ * corresponding field. When the result is empty, the storage key is removed
+ * so an unsubscribed page leaves no residue (callers can rely on
+ * `loadTableState() === {}` ≡ "no preferences set").
+ */
+export const updateTableState = (key: string, patch: Partial<TableState>): TableState => {
+ const current = loadTableState(key);
+ const merged: TableState = { ...current };
+
+ for (const [field, value] of Object.entries(patch) as [keyof TableState, TableState[keyof TableState]][]) {
+ if (value === undefined) {
+ delete merged[field];
+ continue;
+ }
+
+ // Empty string / empty array / empty object all collapse to "no value"
+ // so storage holds the same canonical shape as `loadTableState()` of
+ // a fresh user — keeps comparison ergonomic and prevents key churn.
+ const isEmptyString = typeof value === 'string' && value.length === 0;
+ const isEmptyArray = Array.isArray(value) && value.length === 0;
+ const isEmptyRecord =
+ value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === 0;
+
+ if (isEmptyString || isEmptyArray || isEmptyRecord) {
+ delete merged[field];
+ continue;
+ }
+
+ (merged as Record<string, unknown>)[field] = value;
+ }
+
+ if (Object.keys(merged).length === 0) {
+ removeStorageItem(key);
+
+ return merged;
+ }
+
+ setStorageItem(key, merged);
+
+ return merged;
+};
+
+/**
+ * One-shot migration from the pre-unified storage layout. Reads the four
+ * legacy keys (`column_4_`, `sorting_4_`, `filter_4_`, `page_4_`), folds
+ * them into the new unified key, and deletes the legacy slots. Returns the
+ * resulting state.
+ *
+ * Idempotent: once the legacy keys are gone, subsequent runs short-circuit
+ * to a plain `loadTableState`. Safe to call on every page mount.
+ *
+ * Note on `page`: the legacy schema stored `{ page, pageSize }`. We carry
+ * over `pageSize` only — the current page index now lives in `?page=` so
+ * the user can share a paginated view via URL.
+ */
+export const migrateLegacyTableState = (path: string, unifiedKey: string): TableState => {
+ const variants = legacyStoragePathVariants(path);
+ const allLegacyKeys = variants.flatMap(legacyKeysForPath);
+ const anyLegacyPresent = allLegacyKeys.some((key) => localStorage.getItem(key) !== null);
+
+ if (!anyLegacyPresent) {
+ return loadTableState(unifiedKey);
+ }
+
+ const pickFirst = <T>(reader: (scopedPath: string) => null | T): null | T => {
+ for (const scopedPath of variants) {
+ const value = reader(scopedPath);
+
+ if (value !== null) {
+ return value;
+ }
+ }
+
+ return null;
+ };
+
+ const legacySorting = pickFirst((p) => getStorageItem(`sorting${STORAGE_KEY_SEPARATOR}${p}`, sortingSchema));
+ const legacyVisibility = pickFirst((p) => getStorageItem(`column${STORAGE_KEY_SEPARATOR}${p}`, visibilitySchema));
+ const legacyFilter = pickFirst((p) => getStorageItem(`filter${STORAGE_KEY_SEPARATOR}${p}`, z.string()));
+ const legacyPage = pickFirst((p) => getStorageItem(`page${STORAGE_KEY_SEPARATOR}${p}`, legacyPageSchema));
+
+ const merged = updateTableState(unifiedKey, {
+ columnVisibility: legacyVisibility ?? undefined,
+ filter: legacyFilter ?? undefined,
+ pageSize: legacyPage?.pageSize,
+ sorting: legacySorting ?? undefined,
+ });
+
+ for (const key of allLegacyKeys) {
+ removeStorageItem(key);
+ }
+
+ return merged;
+};
diff --git a/frontend/src/lib/table-storage.ts b/frontend/src/lib/table-storage.ts
deleted file mode 100644
index 339d8c0f..00000000
--- a/frontend/src/lib/table-storage.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import type { SortingState, VisibilityState } from '@tanstack/react-table';
-
-import { z } from 'zod';
-
-import { getStorageItem, setStorageItem } from './local-storage';
-
-const sortingSchema = z.array(z.object({ desc: z.boolean(), id: z.string() }));
-
-const visibilitySchema = z.record(z.string(), z.boolean());
-
-const pageStateSchema = z.object({ page: z.number(), pageSize: z.number() });
-
-export type StoredPageState = z.infer<typeof pageStateSchema>;
-
-export const loadSorting = (key: string): null | SortingState => getStorageItem(key, sortingSchema);
-
-export const loadColumnVisibility = (key: string): null | VisibilityState => getStorageItem(key, visibilitySchema);
-
-export const loadPageState = (key: string): null | StoredPageState => getStorageItem(key, pageStateSchema);
-
-export const saveSorting = (key: string, sorting: SortingState): void => setStorageItem(key, sorting);
-
-export const saveColumnVisibility = (key: string, visibility: VisibilityState): void => setStorageItem(key, visibility);
-
-export const savePageState = (key: string, state: StoredPageState): void => setStorageItem(key, state);
diff --git a/frontend/src/lib/url-params.test.ts b/frontend/src/lib/url-params.test.ts
new file mode 100644
index 00000000..3712df66
--- /dev/null
+++ b/frontend/src/lib/url-params.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest';
+
+import { mergeHrefWithSearchParams } from './url-params';
+
+describe('mergeHrefWithSearchParams', () => {
+ it('appends incoming params to a path-only href', () => {
+ const result = mergeHrefWithSearchParams('/flows/1', new URLSearchParams('q=foo'));
+ expect(result).toBe('/flows/1?q=foo');
+ });
+
+ it('lets the href keep its own query params when keys collide', () => {
+ const result = mergeHrefWithSearchParams('/flows/1?bar=keep', new URLSearchParams('bar=overridden&q=x'));
+ expect(result).toBe('/flows/1?bar=keep&q=x');
+ });
+
+ it('preserves the hash fragment', () => {
+ const result = mergeHrefWithSearchParams('/flows/1#tab=logs', new URLSearchParams('q=foo'));
+ expect(result).toBe('/flows/1?q=foo#tab=logs');
+ });
+
+ it('returns the href unchanged when nothing is incoming', () => {
+ expect(mergeHrefWithSearchParams('/flows/1', new URLSearchParams())).toBe('/flows/1');
+ expect(mergeHrefWithSearchParams('/flows/1?bar=1', new URLSearchParams())).toBe('/flows/1?bar=1');
+ });
+
+ it('accepts an entries iterable as well as URLSearchParams', () => {
+ const entries: [string, string][] = [
+ ['q', 'foo'],
+ ['x', '1'],
+ ];
+
+ const result = mergeHrefWithSearchParams('/flows/1', entries);
+ expect(result).toBe('/flows/1?q=foo&x=1');
+ });
+
+ it('round-trips through URLSearchParams encoding (spaces ↔ +, special chars escaped)', () => {
+ // URLSearchParams decodes `+` as space on read, then re-encodes spaces
+ // as `+` on toString — so a literal `+` in the input is interpreted
+ // as a space. We document the actual behaviour here so callers know
+ // what to expect.
+ const result = mergeHrefWithSearchParams('/flows/1', new URLSearchParams('q=a b&keep=%23anchor'));
+ expect(result).toBe('/flows/1?q=a+b&keep=%23anchor');
+ });
+});
diff --git a/frontend/src/lib/url-params.ts b/frontend/src/lib/url-params.ts
new file mode 100644
index 00000000..d19a6153
--- /dev/null
+++ b/frontend/src/lib/url-params.ts
@@ -0,0 +1,53 @@
+/**
+ * URL query parameter keys shared across list/detail pages.
+ *
+ * Keep all conventional names here so the filter hook, the pagination
+ * handlers, and any future feature that wants to coordinate with them agree
+ * on a single source of truth — renaming a key shouldn't require grepping
+ * the codebase for string literals.
+ */
+export const URL_PARAMS = {
+ /** `?page=` — 1-based page number for list-style pagination. */
+ PAGE: 'page',
+ /** `?q=` — free-text filter applied by `useTableQueryFilter`. */
+ QUERY: 'q',
+} as const;
+
+/**
+ * Synthetic base for `new URL(path, base)`. `URL` rejects a path-only first
+ * argument unless a base is provided; we strip the origin from the output
+ * below by reading only `pathname` / `search` / `hash`. The constant is
+ * intentionally bland — anything resolvable as a URL works.
+ */
+const URL_PARSE_BASE = 'http://_';
+
+/**
+ * Merge a relative href with an iterable of "current" query params: every key
+ * that the iterable supplies is added to the href, unless the href already
+ * specifies that key (then the href wins).
+ *
+ * Built around `URL` rather than string `split('?')` so the hash fragment
+ * survives untouched and the contract holds even if `base` happens to grow
+ * an `#anchor` someday.
+ *
+ * Examples:
+ * merge('/flows/1', new URLSearchParams('q=foo')) // '/flows/1?q=foo'
+ * merge('/flows/1?bar=1', new URLSearchParams('bar=2&q=x')) // '/flows/1?bar=1&q=x'
+ * merge('/flows/1#tab=logs', new URLSearchParams('q=foo')) // '/flows/1?q=foo#tab=logs'
+ */
+export const mergeHrefWithSearchParams = (
+ base: string,
+ incoming: Iterable<[string, string]> | URLSearchParams,
+): string => {
+ const url = new URL(base, URL_PARSE_BASE);
+
+ const source = incoming instanceof URLSearchParams ? incoming.entries() : incoming;
+
+ for (const [key, value] of source) {
+ if (!url.searchParams.has(key)) {
+ url.searchParams.set(key, value);
+ }
+ }
+
+ return `${url.pathname}${url.search}${url.hash}`;
+};
diff --git a/frontend/src/lib/view-options-storage.test.ts b/frontend/src/lib/view-options-storage.test.ts
new file mode 100644
index 00000000..2b5afe50
--- /dev/null
+++ b/frontend/src/lib/view-options-storage.test.ts
@@ -0,0 +1,122 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { loadViewOptions, migrateLegacyViewOptions, saveViewOptions } from './view-options-storage';
+
+const PATH = '/resources';
+const UNIFIED_KEY = `viewOptions_4_${PATH}`;
+const LEGACY_KEY = `column_4_${PATH}`;
+
+beforeEach(() => {
+ localStorage.clear();
+});
+
+afterEach(() => {
+ localStorage.clear();
+});
+
+describe('loadViewOptions', () => {
+ it('returns an empty object when the key is missing', () => {
+ expect(loadViewOptions(UNIFIED_KEY)).toEqual({});
+ });
+
+ it('returns an empty object when the payload is invalid JSON', () => {
+ localStorage.setItem(UNIFIED_KEY, 'not json');
+ expect(loadViewOptions(UNIFIED_KEY)).toEqual({});
+ });
+
+ it('returns an empty object when a value is not boolean', () => {
+ // The schema is `Record<string, boolean>` — a numeric value should
+ // be rejected wholesale rather than silently coerced.
+ localStorage.setItem(UNIFIED_KEY, JSON.stringify({ foldersFirst: 1 }));
+ expect(loadViewOptions(UNIFIED_KEY)).toEqual({});
+ });
+
+ it('round-trips a multi-flag payload', () => {
+ const value = { foldersFirst: true, relativeTimestamp: false };
+ localStorage.setItem(UNIFIED_KEY, JSON.stringify(value));
+ expect(loadViewOptions(UNIFIED_KEY)).toEqual(value);
+ });
+});
+
+describe('saveViewOptions', () => {
+ it('writes the payload as JSON', () => {
+ saveViewOptions(UNIFIED_KEY, { foldersFirst: true });
+
+ const raw = localStorage.getItem(UNIFIED_KEY);
+ expect(raw).not.toBeNull();
+ expect(JSON.parse(raw ?? 'null')).toEqual({ foldersFirst: true });
+ });
+
+ it('removes the storage key when the payload is empty — keeps storage tidy', () => {
+ localStorage.setItem(UNIFIED_KEY, JSON.stringify({ foldersFirst: true }));
+
+ saveViewOptions(UNIFIED_KEY, {});
+
+ expect(localStorage.getItem(UNIFIED_KEY)).toBeNull();
+ });
+
+ it('replaces (does not merge) the existing payload', () => {
+ // The function is deliberately a setter, not a patcher — the caller
+ // is expected to merge if they want partial updates. This test pins
+ // that contract.
+ saveViewOptions(UNIFIED_KEY, { foldersFirst: true, relativeTimestamp: true });
+ saveViewOptions(UNIFIED_KEY, { foldersFirst: false });
+
+ expect(loadViewOptions(UNIFIED_KEY)).toEqual({ foldersFirst: false });
+ });
+});
+
+describe('migrateLegacyViewOptions', () => {
+ it('short-circuits to loadViewOptions when no legacy key exists', () => {
+ localStorage.setItem(UNIFIED_KEY, JSON.stringify({ foldersFirst: true }));
+
+ const result = migrateLegacyViewOptions(PATH, UNIFIED_KEY);
+
+ expect(result).toEqual({ foldersFirst: true });
+ // The unified slot must remain untouched.
+ expect(JSON.parse(localStorage.getItem(UNIFIED_KEY) ?? '{}')).toEqual({ foldersFirst: true });
+ });
+
+ it('folds the legacy `column_4_<path>` payload into the unified key', () => {
+ localStorage.setItem(LEGACY_KEY, JSON.stringify({ foldersFirst: true, relativeTimestamp: false }));
+
+ const result = migrateLegacyViewOptions(PATH, UNIFIED_KEY);
+
+ expect(result).toEqual({ foldersFirst: true, relativeTimestamp: false });
+ expect(localStorage.getItem(LEGACY_KEY)).toBeNull();
+ });
+
+ it('merges legacy values on top of pre-existing unified values', () => {
+ // Possible if a partial migration happened on a different tab. The
+ // legacy payload represents the most recent user intent (it was
+ // never cleared), so we accept it as the winner on overlap.
+ localStorage.setItem(UNIFIED_KEY, JSON.stringify({ foldersFirst: false, modified: true }));
+ localStorage.setItem(LEGACY_KEY, JSON.stringify({ foldersFirst: true }));
+
+ const result = migrateLegacyViewOptions(PATH, UNIFIED_KEY);
+
+ expect(result).toEqual({ foldersFirst: true, modified: true });
+ expect(localStorage.getItem(LEGACY_KEY)).toBeNull();
+ });
+
+ it('still deletes the legacy key when its payload is invalid', () => {
+ // An invalid legacy payload contributes nothing, but we must not
+ // leave it in storage — a future call would otherwise repeatedly
+ // re-parse the same garbage.
+ localStorage.setItem(LEGACY_KEY, JSON.stringify({ foldersFirst: 'truthy' }));
+
+ const result = migrateLegacyViewOptions(PATH, UNIFIED_KEY);
+
+ expect(result).toEqual({});
+ expect(localStorage.getItem(LEGACY_KEY)).toBeNull();
+ });
+
+ it('is idempotent — a second invocation reads only the unified key', () => {
+ localStorage.setItem(LEGACY_KEY, JSON.stringify({ foldersFirst: true }));
+
+ migrateLegacyViewOptions(PATH, UNIFIED_KEY);
+ const second = migrateLegacyViewOptions(PATH, UNIFIED_KEY);
+
+ expect(second).toEqual({ foldersFirst: true });
+ });
+});
diff --git a/frontend/src/lib/view-options-storage.ts b/frontend/src/lib/view-options-storage.ts
new file mode 100644
index 00000000..3b8042b0
--- /dev/null
+++ b/frontend/src/lib/view-options-storage.ts
@@ -0,0 +1,49 @@
+import { z } from 'zod';
+
+import { getStorageItem, removeStorageItem, setStorageItem } from './local-storage';
+
+const viewOptionsSchema = z.record(z.string(), z.boolean());
+
+export type ViewOptionsRecord = Record<string, boolean>;
+
+/** Read a per-page `Record<string, boolean>` view-options bag. Returns `{}` when missing/invalid. */
+export const loadViewOptions = (key: string): ViewOptionsRecord => getStorageItem(key, viewOptionsSchema) ?? {};
+
+/** Persist the bag. Empty objects clear the slot so storage stays tidy. */
+export const saveViewOptions = (key: string, value: ViewOptionsRecord): void => {
+ if (Object.keys(value).length === 0) {
+ removeStorageItem(key);
+
+ return;
+ }
+
+ setStorageItem(key, value);
+};
+
+/**
+ * One-shot migration of pre-unification `column_4_<path>` view-options storage
+ * to the new `viewOptions_4_<path>` slot. Reads the legacy key, writes the
+ * payload under the new key (if any), removes the legacy entry, and returns
+ * the resulting record.
+ *
+ * Idempotent: once the legacy key is gone, subsequent invocations short-circuit
+ * to a plain `loadViewOptions`. Safe to call on every page mount.
+ */
+export const migrateLegacyViewOptions = (path: string, unifiedKey: string): ViewOptionsRecord => {
+ const legacyKey = `column_4_${path}`;
+ const legacyRaw = localStorage.getItem(legacyKey);
+
+ if (legacyRaw === null) {
+ return loadViewOptions(unifiedKey);
+ }
+
+ const legacyValue = getStorageItem(legacyKey, viewOptionsSchema);
+
+ if (legacyValue !== null) {
+ saveViewOptions(unifiedKey, { ...loadViewOptions(unifiedKey), ...legacyValue });
+ }
+
+ removeStorageItem(legacyKey);
+
+ return loadViewOptions(unifiedKey);
+};
diff --git a/frontend/src/pages/dashboard/dashboard.tsx b/frontend/src/pages/dashboard/dashboard.tsx
index 1fd023a7..89765f28 100644
--- a/frontend/src/pages/dashboard/dashboard.tsx
+++ b/frontend/src/pages/dashboard/dashboard.tsx
@@ -1,12 +1,12 @@
import { LayoutDashboard } from 'lucide-react';
-import { useMemo, useState } from 'react';
+import { useState } from 'react';
import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage } from '@/components/ui/breadcrumb';
import { Separator } from '@/components/ui/separator';
import { SidebarTrigger } from '@/components/ui/sidebar';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { UsageStatsPeriod } from '@/graphql/types';
-import { getPeriodStorageKey } from '@/lib/storage-keys';
+import { usePageStorageKeys } from '@/hooks/use-page-storage-keys';
import { DashboardAnalytics } from '@/pages/dashboard/dashboard-analytics';
import { DashboardOverview } from '@/pages/dashboard/dashboard-overview';
@@ -41,7 +41,7 @@ const savePeriod = (storageKey: string, value: UsageStatsPeriod): void => {
};
const Dashboard = () => {
- const periodStorageKey = useMemo(() => getPeriodStorageKey(), []);
+ const { period: periodStorageKey } = usePageStorageKeys();
const [activeTab, setActiveTab] = useState('analytics');
const [period, setPeriod] = useState<UsageStatsPeriod>(() => loadPeriod(periodStorageKey));
diff --git a/frontend/src/pages/flows/flow.tsx b/frontend/src/pages/flows/flow.tsx
index 1d7e12be..a4dbb682 100644
--- a/frontend/src/pages/flows/flow.tsx
+++ b/frontend/src/pages/flows/flow.tsx
@@ -1,10 +1,10 @@
import {
- Check,
ChevronDown,
Copy,
Download,
Ellipsis,
ExternalLink,
+ GitFork,
GripVertical,
Loader2,
NotepadText,
@@ -12,9 +12,8 @@ import {
PencilLine,
Star,
Trash,
- X,
} from 'lucide-react';
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
@@ -22,6 +21,9 @@ import { FlowStatusIcon } from '@/components/icons/flow-status-icon';
import { ProviderIcon } from '@/components/icons/provider-icon';
import ConfirmationDialog from '@/components/shared/confirmation-dialog';
import { HeaderButton } from '@/components/shared/header-button';
+import { InlineRenameInput } from '@/components/shared/inline-rename-input';
+import { ListNavigationToolbar } from '@/components/shared/list-navigation-toolbar';
+import { Badge } from '@/components/ui/badge';
import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage } from '@/components/ui/breadcrumb';
import { Button } from '@/components/ui/button';
import {
@@ -31,22 +33,23 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
-import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';
import { Separator } from '@/components/ui/separator';
import { SidebarTrigger } from '@/components/ui/sidebar';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import FlowCentralTabs from '@/features/flows/flow-central-tabs';
import FlowTabs from '@/features/flows/flow-tabs';
+import { useFlowDetailNavigation } from '@/features/flows/use-flow-detail-navigation';
import { ResultType, StatusType, useRenameFlowMutation } from '@/graphql/types';
import { useBreakpoint } from '@/hooks/use-breakpoint';
import { useFlowTabDetection } from '@/hooks/use-flow-tab-detection';
+import { useInlineEditTitle } from '@/hooks/use-inline-edit-title';
import { Log } from '@/lib/log';
import { copyToClipboard, downloadTextFile, generateFileName, generateReport } from '@/lib/report';
import { formatName } from '@/lib/utils/format';
import { useFavorites } from '@/providers/favorites-provider';
import { useFlow } from '@/providers/flow-provider';
-import { useFlows } from '@/providers/flows-provider';
+import { type Flow as FlowItem, useFlows } from '@/providers/flows-provider';
const FlowReportDropdown = () => {
const { flowData, flowId } = useFlow();
@@ -175,45 +178,25 @@ const Flow = () => {
const flowTitle = flow?.title ?? '';
const isFlowRunning = flow ? ![StatusType.Failed, StatusType.Finished].includes(flow.status) : false;
- const [isEditingTitle, setIsEditingTitle] = useState(false);
+ // Walk the same `?q=` filtered subset the list page renders. The hook
+ // also restores the filter from `localStorage` when the page is opened
+ // via a bookmark, so the toolbar stays in lockstep with the user's last
+ // persisted intent.
+ const { toolbarProps: flowToolbarProps } = useFlowDetailNavigation(flowId);
+
+ const {
+ handleDropdownCloseAutoFocus,
+ inputRef: editingInputRef,
+ isEditing: isEditingTitle,
+ startEdit: handleFlowRenameStart,
+ stopEdit: handleFlowRenameCancel,
+ } = useInlineEditTitle({ resetKey: flowId });
+
const [isFinishing, setIsFinishing] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
- const editingInputRef = useRef<HTMLInputElement>(null);
const [renameFlowMutation, { loading: isRenameLoading }] = useRenameFlowMutation();
- // Reset inline-edit state when navigating between flows so the input doesn't
- // carry over a stale draft from a previous flow.
- useEffect(() => {
- setIsEditingTitle(false);
- }, [flowId]);
-
- // Focus and select the rename input when the inline editor opens. We can't
- // rely on `autoFocus` here: the input mounts inside the same render cycle
- // that closes the Radix DropdownMenu, and the dropdown's own focus restore
- // (which it schedules via `requestAnimationFrame`) wins the race against
- // React's autoFocus effect. Defer our focus to the next frame so it lands
- // *after* Radix has finished its restore. Selecting the text lets the user
- // overwrite the title in one keystroke.
- useEffect(() => {
- if (!isEditingTitle) {
- return;
- }
-
- const id = requestAnimationFrame(() => {
- const input = editingInputRef.current;
-
- if (!input) {
- return;
- }
-
- input.focus();
- input.select();
- });
-
- return () => cancelAnimationFrame(id);
- }, [isEditingTitle]);
-
// Redirect to flows list if there's an error loading flow data or flow not found
useEffect(() => {
if (flowError || (!isFlowLoading && !flowData?.flow)) {
@@ -221,14 +204,6 @@ const Flow = () => {
}
}, [flowError, flowData, isFlowLoading, navigate]);
- const handleFlowRenameStart = useCallback(() => {
- setIsEditingTitle(true);
- }, []);
-
- const handleFlowRenameCancel = useCallback(() => {
- setIsEditingTitle(false);
- }, []);
-
const handleFlowRenameSave = useCallback(async () => {
const newTitle = editingInputRef.current?.value.trim();
@@ -246,13 +221,13 @@ const Flow = () => {
if (data?.renameFlow === ResultType.Success) {
toast.success('Flow renamed successfully');
- setIsEditingTitle(false);
+ handleFlowRenameCancel();
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Failed to rename flow';
toast.error(errorMessage);
}
- }, [flowId, renameFlowMutation]);
+ }, [editingInputRef, flowId, handleFlowRenameCancel, renameFlowMutation]);
const handleFlowFinish = useCallback(async () => {
if (!flow) {
@@ -333,45 +308,15 @@ const Flow = () => {
</>
)}
{isEditingTitle && flow ? (
- <InputGroup className="h-8 w-64 max-w-full">
- <InputGroupInput
- className="text-foreground"
- defaultValue={flowTitle}
- onKeyDown={(event) => {
- if (event.key === 'Enter') {
- event.preventDefault();
- handleFlowRenameSave();
-
- return;
- }
-
- if (event.key === 'Escape') {
- event.preventDefault();
- handleFlowRenameCancel();
- }
- }}
- placeholder="Flow title"
- ref={editingInputRef}
- />
- <InputGroupAddon
- align="inline-end"
- className="gap-0 pr-2"
- >
- <InputGroupButton
- aria-label="Save"
- disabled={isRenameLoading}
- onClick={() => handleFlowRenameSave()}
- >
- {isRenameLoading ? <Loader2 className="animate-spin" /> : <Check />}
- </InputGroupButton>
- <InputGroupButton
- aria-label="Cancel"
- onClick={() => handleFlowRenameCancel()}
- >
- <X />
- </InputGroupButton>
- </InputGroupAddon>
- </InputGroup>
+ <InlineRenameInput
+ busy={isRenameLoading}
+ className="w-64 max-w-full"
+ defaultValue={flowTitle}
+ inputRef={editingInputRef}
+ onCancel={handleFlowRenameCancel}
+ onSave={handleFlowRenameSave}
+ placeholder="Flow title"
+ />
) : flow ? (
<Tooltip>
<TooltipTrigger asChild>
@@ -392,6 +337,30 @@ const Flow = () => {
</Breadcrumb>
</div>
<div className="flex items-center gap-2">
+ {flow && (
+ <ListNavigationToolbar<FlowItem>
+ {...flowToolbarProps}
+ renderItem={(item, isCurrent) => (
+ <>
+ <FlowStatusIcon
+ className="size-3 shrink-0"
+ status={item.status}
+ />
+ <span className={isCurrent ? 'truncate font-medium' : 'truncate'}>
+ {item.title || `Flow #${item.id}`}
+ </span>
+ <Badge
+ className="ml-auto shrink-0 font-mono text-[10px]"
+ variant="outline"
+ >
+ #{item.id}
+ </Badge>
+ </>
+ )}
+ sheetIcon={<GitFork className="size-4" />}
+ sheetTitle="Flows"
+ />
+ )}
{flowId && (
<Button
className="shrink-0"
@@ -417,14 +386,7 @@ const Flow = () => {
<DropdownMenuContent
align="end"
className="min-w-24"
- onCloseAutoFocus={(event) => {
- // Radix returns focus to the trigger on close. When the
- // selected action mounts the rename input, prevent that
- // restore so the input's `autoFocus` actually wins.
- if (isEditingTitle) {
- event.preventDefault();
- }
- }}
+ onCloseAutoFocus={handleDropdownCloseAutoFocus}
>
<DropdownMenuItem onClick={handleFlowRenameStart}>
<PencilLine className="size-3" />
diff --git a/frontend/src/pages/flows/flows.tsx b/frontend/src/pages/flows/flows.tsx
index a48e2a69..1ae27a0b 100644
--- a/frontend/src/pages/flows/flows.tsx
+++ b/frontend/src/pages/flows/flows.tsx
@@ -2,30 +2,18 @@ import type { ColumnDef } from '@tanstack/react-table';
import { format, isToday } from 'date-fns';
import { enUS } from 'date-fns/locale';
-import {
- ArrowDown,
- ArrowUp,
- Ellipsis,
- Eye,
- GitFork,
- Loader2,
- Pause,
- Pencil,
- PencilLine,
- Plus,
- Star,
- Trash,
-} from 'lucide-react';
-import { Check, CheckCircle2, X, XCircle } from 'lucide-react';
+import { Ellipsis, Eye, GitFork, Loader2, Pause, Pencil, PencilLine, Plus, Star, Trash } from 'lucide-react';
+import { CheckCircle2, XCircle } from 'lucide-react';
import { useCallback, useMemo, useRef, useState } from 'react';
-import { useNavigate } from 'react-router-dom';
-import { useSearchParams } from 'react-router-dom';
+import { useLocation, useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import { FlowStatusIcon } from '@/components/icons/flow-status-icon';
import { ProviderIcon } from '@/components/icons/provider-icon';
import ConfirmationDialog from '@/components/shared/confirmation-dialog';
import { HeaderButton } from '@/components/shared/header-button';
+import { InlineRenameInput } from '@/components/shared/inline-rename-input';
+import { SortableColumnHeader } from '@/components/shared/sortable-column-header';
import { Badge } from '@/components/ui/badge';
import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage } from '@/components/ui/breadcrumb';
import { Button } from '@/components/ui/button';
@@ -38,13 +26,15 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
-import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';
import { Separator } from '@/components/ui/separator';
import { SidebarTrigger } from '@/components/ui/sidebar';
import { StatusCard } from '@/components/ui/status-card';
import { Toggle } from '@/components/ui/toggle';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { ResultType, StatusType, type TerminalFragmentFragment, useRenameFlowMutation } from '@/graphql/types';
+import { usePagination } from '@/hooks/use-pagination';
+import { useTableQueryFilter } from '@/hooks/use-table-query-filter';
+import { mergeHrefWithSearchParams } from '@/lib/url-params';
import { useFavorites } from '@/providers/favorites-provider';
import { type Flow, useFlows } from '@/providers/flows-provider';
@@ -92,7 +82,7 @@ const formatFullDateTime = (dateString: string) => {
const Flows = () => {
const navigate = useNavigate();
- const [searchParams, setSearchParams] = useSearchParams();
+ const location = useLocation();
const { deleteFlow, finishFlow, flows, isLoading } = useFlows();
const { isFavoriteFlow, toggleFavoriteFlow } = useFavorites();
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
@@ -103,55 +93,14 @@ const Flows = () => {
const editingInputRef = useRef<HTMLInputElement>(null);
const [renameFlowMutation, { loading: isRenameLoading }] = useRenameFlowMutation();
- // Three-way sorting handler: null -> asc -> desc -> null
- const handleColumnSort = useMemo(
- () =>
- (column: {
- clearSorting: () => void;
- getIsSorted: () => 'asc' | 'desc' | false;
- toggleSorting: (desc?: boolean) => void;
- }) => {
- const sorted = column.getIsSorted();
-
- if (sorted === 'asc') {
- column.toggleSorting(true);
- } else if (sorted === 'desc') {
- column.clearSorting();
- } else {
- column.toggleSorting(false);
- }
- },
- [],
- );
-
- // Get current page from URL
- const currentPage = useMemo(() => {
- const page = searchParams.get('page');
-
- return page ? Math.max(0, Number.parseInt(page, 10) - 1) : 0;
- }, [searchParams]);
-
- // Handle page change
- const handlePageChange = useCallback(
- (pageIndex: number) => {
- const newParams = new URLSearchParams(searchParams);
-
- if (pageIndex === 0) {
- newParams.delete('page');
- } else {
- newParams.set('page', String(pageIndex + 1));
- }
-
- setSearchParams(newParams);
- },
- [searchParams, setSearchParams],
- );
+ const { filter, setFilter } = useTableQueryFilter();
+ const { pageIndex: currentPage, setPage: handlePageChange } = usePagination();
const handleFlowOpen = useCallback(
(flowId: string) => {
- navigate(`/flows/${flowId}`);
+ navigate(mergeHrefWithSearchParams(`/flows/${flowId}`, new URLSearchParams(location.search)));
},
- [navigate],
+ [navigate, location.search],
);
const handleFlowDeleteDialogOpen = useCallback((flow: Flow) => {
@@ -239,24 +188,12 @@ const Flows = () => {
accessorKey: 'id',
cell: ({ row }) => <div className="font-mono text-sm">{row.getValue('id')}</div>,
enableHiding: false,
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- ID
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => (
+ <SortableColumnHeader
+ column={column}
+ label="ID"
+ />
+ ),
maxSize: 80,
minSize: 60,
size: 70,
@@ -270,68 +207,29 @@ const Flows = () => {
if (isEditing) {
return (
- <InputGroup
- className="h-8"
- onClick={(e) => e.stopPropagation()}
- >
- <InputGroupInput
+ <div onClick={(e) => e.stopPropagation()}>
+ <InlineRenameInput
autoFocus
+ busy={isRenameLoading}
defaultValue={title}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- handleFlowRenameSave();
-
- return;
- }
-
- if (e.key === 'Escape') {
- handleFlowRenameCancel();
-
- return;
- }
- }}
+ inputRef={editingInputRef}
+ onCancel={handleFlowRenameCancel}
+ onSave={handleFlowRenameSave}
placeholder="Flow title"
- ref={editingInputRef}
/>
- <InputGroupAddon
- align="inline-end"
- className="gap-0 pr-2"
- >
- <InputGroupButton
- disabled={isRenameLoading}
- onClick={() => handleFlowRenameSave()}
- >
- {isRenameLoading ? <Loader2 className="animate-spin" /> : <Check />}
- </InputGroupButton>
- <InputGroupButton onClick={() => handleFlowRenameCancel()}>
- <X />
- </InputGroupButton>
- </InputGroupAddon>
- </InputGroup>
+ </div>
);
}
return <div className="truncate font-medium">{title}</div>;
},
enableHiding: false,
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- Title
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => (
+ <SortableColumnHeader
+ column={column}
+ label="Title"
+ />
+ ),
minSize: 200,
size: 300,
},
@@ -351,24 +249,12 @@ const Flows = () => {
</Badge>
);
},
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- Status
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => (
+ <SortableColumnHeader
+ column={column}
+ label="Status"
+ />
+ ),
maxSize: 130,
minSize: 80,
size: 100,
@@ -388,24 +274,12 @@ const Flows = () => {
</div>
);
},
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- Provider
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => (
+ <SortableColumnHeader
+ column={column}
+ label="Provider"
+ />
+ ),
maxSize: 150,
minSize: 80,
size: 100,
@@ -459,24 +333,12 @@ const Flows = () => {
</Tooltip>
);
},
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- Terminals
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => (
+ <SortableColumnHeader
+ column={column}
+ label="Terminals"
+ />
+ ),
maxSize: 220,
minSize: 160,
size: 180,
@@ -503,25 +365,14 @@ const Flows = () => {
</Tooltip>
);
},
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- Created
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => (
+ <SortableColumnHeader
+ column={column}
+ label="Created"
+ />
+ ),
maxSize: 140,
+ meta: { columnMenuLabel: 'Created' },
minSize: 100,
size: 120,
sortingFn: (rowA, rowB) => {
@@ -547,25 +398,14 @@ const Flows = () => {
</Tooltip>
);
},
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- Updated
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => (
+ <SortableColumnHeader
+ column={column}
+ label="Updated"
+ />
+ ),
maxSize: 140,
+ meta: { columnMenuLabel: 'Updated' },
minSize: 100,
size: 120,
sortingFn: (rowA, rowB) => {
@@ -671,7 +511,6 @@ const Flows = () => {
deletingFlowIds,
editingFlowId,
finishingFlowIds,
- handleColumnSort,
handleFlowDeleteDialogOpen,
handleFlowFinish,
handleFlowOpen,
@@ -822,6 +661,8 @@ const Flows = () => {
data={flows}
filterColumn="title"
filterPlaceholder="Filter flows..."
+ filterValue={filter}
+ onFilterChange={setFilter}
onPageChange={handlePageChange}
onRowClick={handleRowClick}
pageIndex={currentPage}
diff --git a/frontend/src/pages/knowledges/knowledges.tsx b/frontend/src/pages/knowledges/knowledges.tsx
index a6bcdace..14e04e2a 100644
--- a/frontend/src/pages/knowledges/knowledges.tsx
+++ b/frontend/src/pages/knowledges/knowledges.tsx
@@ -1,26 +1,16 @@
import type { ColumnDef } from '@tanstack/react-table';
-import {
- ArrowDown,
- ArrowUp,
- Check,
- Ellipsis,
- LibraryBig,
- Loader2,
- Pencil,
- PencilLine,
- Plus,
- Trash,
- X,
-} from 'lucide-react';
+import { Ellipsis, LibraryBig, Loader2, Pencil, PencilLine, Plus, Trash } from 'lucide-react';
import { useCallback, useRef, useState } from 'react';
-import { useNavigate } from 'react-router-dom';
+import { useLocation, useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import type { BadgeVariant } from '@/components/ui/badge';
import ConfirmationDialog from '@/components/shared/confirmation-dialog';
import { HeaderButton } from '@/components/shared/header-button';
+import { InlineRenameInput } from '@/components/shared/inline-rename-input';
+import { SortableColumnHeader } from '@/components/shared/sortable-column-header';
import { Badge } from '@/components/ui/badge';
import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage } from '@/components/ui/breadcrumb';
import { Button } from '@/components/ui/button';
@@ -33,12 +23,12 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
-import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';
import { Separator } from '@/components/ui/separator';
import { SidebarTrigger } from '@/components/ui/sidebar';
import { StatusCard } from '@/components/ui/status-card';
import { KnowledgeDocType } from '@/graphql/types';
-import { cycleColumnSort } from '@/lib/table-sort';
+import { useTableQueryFilter } from '@/hooks/use-table-query-filter';
+import { mergeHrefWithSearchParams } from '@/lib/url-params';
import { type Knowledge, useKnowledges } from '@/providers/knowledges-provider';
const docTypeBadgeVariant: Record<KnowledgeDocType, BadgeVariant> = {
@@ -65,6 +55,7 @@ const docTypeSubtype = (k: Knowledge): null | string => {
const Knowledges = () => {
const navigate = useNavigate();
+ const location = useLocation();
const { deleteKnowledge, isLoading, knowledges, updateKnowledge } = useKnowledges();
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
const [deletingKnowledge, setDeletingKnowledge] = useState<Knowledge | null>(null);
@@ -73,11 +64,13 @@ const Knowledges = () => {
const [isRenameLoading, setIsRenameLoading] = useState(false);
const editingInputRef = useRef<HTMLInputElement>(null);
+ const { filter, setFilter } = useTableQueryFilter();
+
const handleOpen = useCallback(
(id: string) => {
- navigate(`/knowledges/${id}`);
+ navigate(mergeHrefWithSearchParams(`/knowledges/${id}`, new URLSearchParams(location.search)));
},
- [navigate],
+ [navigate, location.search],
);
const handleDeleteDialogOpen = useCallback((knowledge: Knowledge) => {
@@ -178,24 +171,7 @@ const Knowledges = () => {
</div>
);
},
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => cycleColumnSort(column)}
- variant="link"
- >
- Type
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => <SortableColumnHeader column={column} label="Type" />,
maxSize: 180,
minSize: 110,
size: 130,
@@ -209,48 +185,17 @@ const Knowledges = () => {
if (isEditing) {
return (
- <InputGroup
- className="h-8"
- onClick={(e) => e.stopPropagation()}
- >
- <InputGroupInput
+ <div onClick={(e) => e.stopPropagation()}>
+ <InlineRenameInput
autoFocus
+ busy={isRenameLoading}
defaultValue={question}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- handleKnowledgeRenameSave();
-
- return;
- }
-
- if (e.key === 'Escape') {
- e.preventDefault();
- handleKnowledgeRenameCancel();
- }
- }}
+ inputRef={editingInputRef}
+ onCancel={handleKnowledgeRenameCancel}
+ onSave={handleKnowledgeRenameSave}
placeholder="Knowledge question"
- ref={editingInputRef}
/>
- <InputGroupAddon
- align="inline-end"
- className="gap-0 pr-2"
- >
- <InputGroupButton
- aria-label="Save"
- disabled={isRenameLoading}
- onClick={() => handleKnowledgeRenameSave()}
- >
- {isRenameLoading ? <Loader2 className="animate-spin" /> : <Check />}
- </InputGroupButton>
- <InputGroupButton
- aria-label="Cancel"
- onClick={() => handleKnowledgeRenameCancel()}
- >
- <X />
- </InputGroupButton>
- </InputGroupAddon>
- </InputGroup>
+ </div>
);
}
@@ -263,24 +208,7 @@ const Knowledges = () => {
</div>
);
},
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => cycleColumnSort(column)}
- variant="link"
- >
- Question
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => <SortableColumnHeader column={column} label="Question" />,
minSize: 180,
size: 280,
},
@@ -303,6 +231,7 @@ const Knowledges = () => {
<span className="text-muted-foreground inline-flex items-center text-sm font-medium">Preview</span>
),
maxSize: 800,
+ meta: { columnMenuLabel: 'Preview' },
minSize: 160,
size: 380,
},
@@ -333,6 +262,7 @@ const Knowledges = () => {
header: () => null,
id: 'flags',
maxSize: 200,
+ meta: { columnMenuLabel: 'Flags' },
minSize: 110,
size: 150,
},
@@ -494,6 +424,8 @@ const Knowledges = () => {
data={knowledges}
filterColumn="question"
filterPlaceholder="Filter knowledge documents..."
+ filterValue={filter}
+ onFilterChange={setFilter}
onRowClick={(k) => {
if (editingKnowledgeId !== k.id) {
handleOpen(k.id);
diff --git a/frontend/src/pages/resources/resources.tsx b/frontend/src/pages/resources/resources.tsx
index e83449a6..0afe1225 100644
--- a/frontend/src/pages/resources/resources.tsx
+++ b/frontend/src/pages/resources/resources.tsx
@@ -37,7 +37,6 @@ import {
} from '@/components/ui/dropdown-menu';
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty';
import { FileDropZone } from '@/components/ui/file-drop-zone';
-import { Form, FormControl, FormField, FormItem } from '@/components/ui/form';
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';
import { Separator } from '@/components/ui/separator';
import { SidebarTrigger } from '@/components/ui/sidebar';
@@ -51,9 +50,9 @@ import { useResourcesSearch } from '@/features/resources/use-resources-search';
import { useResourcesUpload } from '@/features/resources/use-resources-upload';
import { useEffectAfterMount } from '@/hooks/use-effect-after-mount';
import { useFilesDragAndDrop } from '@/hooks/use-files-drag-and-drop';
+import { usePageStorageKeys } from '@/hooks/use-page-storage-keys';
import { copyToClipboard } from '@/lib/report';
-import { getColumnStorageKey } from '@/lib/storage-keys';
-import { loadColumnVisibility, saveColumnVisibility } from '@/lib/table-storage';
+import { migrateLegacyViewOptions, saveViewOptions } from '@/lib/view-options-storage';
import { useResources } from '@/providers/resources-provider';
/**
@@ -65,8 +64,9 @@ import { useResources } from '@/providers/resources-provider';
* the FileManager default) when `true`, or as an
* absolute, minute-precision timestamp when `false`
*
- * All flags persist into the same `column` storage bucket because the schema is
- * `Record<string, boolean>` — adding more toggles later does not require a new key.
+ * All flags persist into the page's `viewOptions` storage bucket; the schema
+ * is `Record<string, boolean>` so adding more toggles later does not require
+ * a new key.
*/
interface ResourcesViewOptions {
foldersFirst: boolean;
@@ -75,6 +75,8 @@ interface ResourcesViewOptions {
size: boolean;
}
+const RESOURCES_PATH = '/resources';
+
/** Defaults match FileManager's out-of-the-box behaviour (relative dates, folders first, both columns visible). */
const defaultViewOptions: ResourcesViewOptions = {
foldersFirst: true,
@@ -85,8 +87,8 @@ const defaultViewOptions: ResourcesViewOptions = {
type ResourcesViewOptionKey = keyof ResourcesViewOptions;
-const loadViewOptions = (storageKey: string): ResourcesViewOptions => {
- const stored = loadColumnVisibility(storageKey) ?? {};
+const seedViewOptions = (storageKey: string): ResourcesViewOptions => {
+ const stored = migrateLegacyViewOptions(RESOURCES_PATH, storageKey);
return {
foldersFirst: stored.foldersFirst ?? defaultViewOptions.foldersFirst,
@@ -112,14 +114,14 @@ const Resources = () => {
const [filesToMove, setFilesToMove] = useState<FileNode[] | null>(null);
const [filesToCopy, setFilesToCopy] = useState<FileNode[] | null>(null);
- const viewOptionsStorageKey = useMemo(() => getColumnStorageKey('/resources'), []);
- const [viewOptions, setViewOptions] = useState<ResourcesViewOptions>(() => loadViewOptions(viewOptionsStorageKey));
+ const { viewOptions: viewOptionsStorageKey } = usePageStorageKeys();
+ const [viewOptions, setViewOptions] = useState<ResourcesViewOptions>(() => seedViewOptions(viewOptionsStorageKey));
useEffectAfterMount(() => {
// Cast: `ResourcesViewOptions` is structurally a `Record<string, boolean>`
// but TS doesn't widen object types with declared keys to an index
// signature implicitly.
- saveColumnVisibility(viewOptionsStorageKey, viewOptions as unknown as Record<string, boolean>);
+ saveViewOptions(viewOptionsStorageKey, viewOptions as unknown as Record<string, boolean>);
}, [viewOptions, viewOptionsStorageKey]);
const toggleViewOption = useCallback((option: ResourcesViewOptionKey) => {
@@ -470,39 +472,29 @@ const Resources = () => {
)}
<div className="flex items-center gap-2">
- <Form {...search.form}>
- <FormField
- control={search.form.control}
- name="search"
- render={({ field }) => (
- <FormItem className="max-w-sm flex-1">
- <FormControl>
- <InputGroup>
- <InputGroupAddon>
- <Search />
- </InputGroupAddon>
- <InputGroupInput
- {...field}
- autoComplete="off"
- placeholder="Search resources..."
- type="text"
- />
- {field.value && (
- <InputGroupAddon align="inline-end">
- <InputGroupButton
- onClick={search.resetSearch}
- type="button"
- >
- <X />
- </InputGroupButton>
- </InputGroupAddon>
- )}
- </InputGroup>
- </FormControl>
- </FormItem>
- )}
+ <InputGroup className="max-w-sm flex-1">
+ <InputGroupAddon>
+ <Search />
+ </InputGroupAddon>
+ <InputGroupInput
+ aria-label="Search resources"
+ autoComplete="off"
+ onChange={(event) => search.setQuery(event.target.value)}
+ placeholder="Search resources..."
+ type="text"
+ value={search.rawQuery}
/>
- </Form>
+ {search.rawQuery ? (
+ <InputGroupAddon align="inline-end">
+ <InputGroupButton
+ onClick={search.resetSearch}
+ type="button"
+ >
+ <X />
+ </InputGroupButton>
+ </InputGroupAddon>
+ ) : null}
+ </InputGroup>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
diff --git a/frontend/src/pages/settings/settings-api-tokens.tsx b/frontend/src/pages/settings/settings-api-tokens.tsx
index b895348a..92b7e186 100644
--- a/frontend/src/pages/settings/settings-api-tokens.tsx
+++ b/frontend/src/pages/settings/settings-api-tokens.tsx
@@ -4,8 +4,6 @@ import { format, isToday } from 'date-fns';
import { enUS } from 'date-fns/locale';
import {
AlertCircle,
- ArrowDown,
- ArrowUp,
CalendarIcon,
Check,
Copy,
@@ -19,12 +17,12 @@ import {
X,
} from 'lucide-react';
import { useCallback, useMemo, useRef, useState } from 'react';
-import { useSearchParams } from 'react-router-dom';
import { toast } from 'sonner';
import type { ApiTokenFragmentFragment } from '@/graphql/types';
import ConfirmationDialog from '@/components/shared/confirmation-dialog';
+import { SortableColumnHeader } from '@/components/shared/sortable-column-header';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
@@ -54,6 +52,7 @@ import {
useDeleteApiTokenMutation,
useUpdateApiTokenMutation,
} from '@/graphql/types';
+import { usePagination } from '@/hooks/use-pagination';
import { cn } from '@/lib/utils';
import { baseUrl } from '@/models/api';
@@ -191,7 +190,6 @@ const createNewTokenPlaceholder: APIToken = {
};
const SettingsAPITokens = () => {
- const [searchParams, setSearchParams] = useSearchParams();
const { data, error, loading: isLoading } = useApiTokensQuery();
const [createAPIToken, { error: createError, loading: isCreateLoading }] = useCreateApiTokenMutation();
const [updateAPIToken, { error: updateError, loading: isUpdateLoading }] = useUpdateApiTokenMutation();
@@ -209,48 +207,7 @@ const SettingsAPITokens = () => {
const editingInputRef = useRef<HTMLInputElement>(null);
const creatingInputRef = useRef<HTMLInputElement>(null);
- // Get current page from URL
- const currentPage = useMemo(() => {
- const page = searchParams.get('page');
-
- return page ? Math.max(0, Number.parseInt(page, 10) - 1) : 0;
- }, [searchParams]);
-
- // Handle page change
- const handlePageChange = useCallback(
- (pageIndex: number) => {
- const newParams = new URLSearchParams(searchParams);
-
- if (pageIndex === 0) {
- newParams.delete('page');
- } else {
- newParams.set('page', String(pageIndex + 1));
- }
-
- setSearchParams(newParams);
- },
- [searchParams, setSearchParams],
- );
-
- // Three-way sorting handler: null -> asc -> desc -> null
- const handleColumnSort = useCallback(
- (column: {
- clearSorting: () => void;
- getIsSorted: () => 'asc' | 'desc' | false;
- toggleSorting: (desc?: boolean) => void;
- }) => {
- const sorted = column.getIsSorted();
-
- if (sorted === 'asc') {
- column.toggleSorting(true);
- } else if (sorted === 'desc') {
- column.clearSorting();
- } else {
- column.toggleSorting(false);
- }
- },
- [],
- );
+ const { pageIndex: currentPage, setPage: handlePageChange } = usePagination();
useApiTokenCreatedSubscription({
onData: ({ client }) => {
@@ -432,24 +389,7 @@ const SettingsAPITokens = () => {
);
},
enableHiding: false,
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- Name
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => <SortableColumnHeader column={column} label="Name" />,
size: 300,
},
{
@@ -478,24 +418,7 @@ const SettingsAPITokens = () => {
);
},
enableHiding: false,
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- Token ID
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => <SortableColumnHeader column={column} label="Token ID" />,
size: 200,
},
{
@@ -539,24 +462,7 @@ const SettingsAPITokens = () => {
return <Badge variant={statusDisplay.variant}>{statusDisplay.label}</Badge>;
},
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- Status
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => <SortableColumnHeader column={column} label="Status" />,
size: 120,
},
{
@@ -620,24 +526,7 @@ const SettingsAPITokens = () => {
</Tooltip>
);
},
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- Expires
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => <SortableColumnHeader column={column} label="Expires" />,
size: 150,
sortingFn: (rowA, rowB) => {
const expiresA = getTokenExpirationDate(rowA.original);
@@ -669,24 +558,8 @@ const SettingsAPITokens = () => {
</Tooltip>
);
},
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- Created
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => <SortableColumnHeader column={column} label="Created" />,
+ meta: { columnMenuLabel: 'Created' },
size: 120,
sortingFn: (rowA, rowB) => {
const dateA = new Date(rowA.getValue('createdAt') as string);
@@ -809,7 +682,6 @@ const SettingsAPITokens = () => {
editingTokenId,
handleCancelCreate,
handleCancelEdit,
- handleColumnSort,
handleCopyTokenId,
handleCreate,
handleDeleteDialogOpen,
diff --git a/frontend/src/pages/settings/settings-providers.tsx b/frontend/src/pages/settings/settings-providers.tsx
index a5f8fac9..1b08dfdf 100644
--- a/frontend/src/pages/settings/settings-providers.tsx
+++ b/frontend/src/pages/settings/settings-providers.tsx
@@ -2,21 +2,9 @@ import type { ColumnDef } from '@tanstack/react-table';
import { format, isToday } from 'date-fns';
import { enUS } from 'date-fns/locale';
-import {
- AlertCircle,
- ArrowDown,
- ArrowUp,
- ChevronDown,
- Copy,
- Ellipsis,
- Loader2,
- Pencil,
- Plus,
- Settings,
- Trash,
-} from 'lucide-react';
+import { AlertCircle, ChevronDown, Copy, Ellipsis, Loader2, Pencil, Plus, Settings, Trash } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
-import { useNavigate, useSearchParams } from 'react-router-dom';
+import { useNavigate } from 'react-router-dom';
import type { ProviderConfigFragmentFragment } from '@/graphql/types';
@@ -31,6 +19,7 @@ import Ollama from '@/components/icons/ollama';
import OpenAi from '@/components/icons/open-ai';
import Qwen from '@/components/icons/qwen';
import ConfirmationDialog from '@/components/shared/confirmation-dialog';
+import { SortableColumnHeader } from '@/components/shared/sortable-column-header';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
@@ -46,6 +35,7 @@ import {
import { StatusCard } from '@/components/ui/status-card';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { ProviderType, useDeleteProviderMutation, useSettingsProvidersQuery } from '@/graphql/types';
+import { usePagination } from '@/hooks/use-pagination';
type Provider = ProviderConfigFragmentFragment;
const providerIcons: Record<ProviderType, React.ComponentType<any>> = {
@@ -134,7 +124,6 @@ const SettingsProvidersHeader = () => {
};
const SettingsProviders = () => {
- const [searchParams, setSearchParams] = useSearchParams();
const { data, error, loading: isLoading } = useSettingsProvidersQuery();
const [deleteProvider, { error: deleteError, loading: isDeleteLoading }] = useDeleteProviderMutation();
const [deleteErrorMessage, setDeleteErrorMessage] = useState<null | string>(null);
@@ -142,48 +131,7 @@ const SettingsProviders = () => {
const [deletingProvider, setDeletingProvider] = useState<null | Provider>(null);
const navigate = useNavigate();
- // Get current page from URL
- const currentPage = useMemo(() => {
- const page = searchParams.get('page');
-
- return page ? Math.max(0, Number.parseInt(page, 10) - 1) : 0;
- }, [searchParams]);
-
- // Handle page change
- const handlePageChange = useCallback(
- (pageIndex: number) => {
- const newParams = new URLSearchParams(searchParams);
-
- if (pageIndex === 0) {
- newParams.delete('page');
- } else {
- newParams.set('page', String(pageIndex + 1));
- }
-
- setSearchParams(newParams);
- },
- [searchParams, setSearchParams],
- );
-
- // Three-way sorting handler: null -> asc -> desc -> null
- const handleColumnSort = useCallback(
- (column: {
- clearSorting: () => void;
- getIsSorted: () => 'asc' | 'desc' | false;
- toggleSorting: (desc?: boolean) => void;
- }) => {
- const sorted = column.getIsSorted();
-
- if (sorted === 'asc') {
- column.toggleSorting(true);
- } else if (sorted === 'desc') {
- column.clearSorting();
- } else {
- column.toggleSorting(false);
- }
- },
- [],
- );
+ const { pageIndex: currentPage, setPage: handlePageChange } = usePagination();
const handleProviderDelete = useCallback(
async (providerId: string | undefined) => {
@@ -233,24 +181,7 @@ const SettingsProviders = () => {
accessorKey: 'name',
cell: ({ row }) => <div className="font-medium">{row.getValue('name')}</div>,
enableHiding: false,
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- Name
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => <SortableColumnHeader column={column} label="Name" />,
size: 400,
},
{
@@ -266,24 +197,7 @@ const SettingsProviders = () => {
</Badge>
);
},
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- Type
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => <SortableColumnHeader column={column} label="Type" />,
size: 160,
},
{
@@ -302,24 +216,8 @@ const SettingsProviders = () => {
</Tooltip>
);
},
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- Created
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => <SortableColumnHeader column={column} label="Created" />,
+ meta: { columnMenuLabel: 'Created' },
size: 120,
sortingFn: (rowA, rowB) => {
const dateA = new Date(rowA.getValue('createdAt') as string);
@@ -344,24 +242,7 @@ const SettingsProviders = () => {
</Tooltip>
);
},
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => handleColumnSort(column)}
- variant="link"
- >
- Updated
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => <SortableColumnHeader column={column} label="Updated" />,
size: 120,
sortingFn: (rowA, rowB) => {
const dateA = new Date(rowA.getValue('updatedAt') as string);
@@ -427,14 +308,7 @@ const SettingsProviders = () => {
size: 48,
},
],
- [
- handleColumnSort,
- handleProviderClone,
- handleProviderDeleteDialogOpen,
- handleProviderEdit,
- isDeleteLoading,
- deletingProvider,
- ],
+ [handleProviderClone, handleProviderDeleteDialogOpen, handleProviderEdit, isDeleteLoading, deletingProvider],
);
const renderSubComponent = ({ row }: { row: any }) => {
diff --git a/frontend/src/pages/templates/template.tsx b/frontend/src/pages/templates/template.tsx
index 4e02da4d..4205fac4 100644
--- a/frontend/src/pages/templates/template.tsx
+++ b/frontend/src/pages/templates/template.tsx
@@ -1,24 +1,25 @@
import { zodResolver } from '@hookform/resolvers/zod';
import {
- Check,
ChevronDown,
Ellipsis,
FileSymlink,
+ FileText,
Loader2,
PanelRightClose,
PanelRightOpen,
Pencil,
Save,
Trash,
- X,
} from 'lucide-react';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { useNavigate, useParams } from 'react-router-dom';
import { toast } from 'sonner';
import { z } from 'zod';
import ConfirmationDialog from '@/components/shared/confirmation-dialog';
+import { InlineRenameInput } from '@/components/shared/inline-rename-input';
+import { ListNavigationToolbar } from '@/components/shared/list-navigation-toolbar';
import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage } from '@/components/ui/breadcrumb';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
@@ -32,22 +33,18 @@ import {
} from '@/components/ui/dropdown-menu';
import { Form, FormControl, FormField, FormItem } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
-import {
- InputGroup,
- InputGroupAddon,
- InputGroupButton,
- InputGroupInput,
- InputGroupTextareaAutosize,
-} from '@/components/ui/input-group';
+import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupTextareaAutosize } from '@/components/ui/input-group';
import { Separator } from '@/components/ui/separator';
import { Sheet, SheetContent } from '@/components/ui/sheet';
import { SidebarTrigger } from '@/components/ui/sidebar';
import { Spinner } from '@/components/ui/spinner';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { useTemplateDetailNavigation } from '@/features/templates/use-template-detail-navigation';
import { useFlowTemplateQuery } from '@/graphql/types';
import { useBreakpoint } from '@/hooks/use-breakpoint';
+import { useInlineEditTitle } from '@/hooks/use-inline-edit-title';
import { cn } from '@/lib/utils';
-import { useTemplates } from '@/providers/templates-provider';
+import { type Template, useTemplates } from '@/providers/templates-provider';
const formSchema = z.object({
text: z.string().trim().min(1, { message: 'Text is required' }),
@@ -240,16 +237,28 @@ const Template = () => {
const { isMobile } = useBreakpoint();
const isNew = templateId === 'new';
+
+ // Pass `null` while creating a new template — there is no "current item"
+ // to highlight, and the toolbar shouldn't render at all anyway (gated
+ // below by `canShowActions`).
+ const { toolbarProps: templateToolbarProps } = useTemplateDetailNavigation(isNew ? null : templateId);
+
const [isAsideOpen, setIsAsideOpen] = useState(false);
const [expandedPresetIndex, setExpandedPresetIndex] = useState<null | number>(null);
const [isReplaceConfirmOpen, setIsReplaceConfirmOpen] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [pendingPreset, setPendingPreset] = useState<null | { text: string; title: string }>(null);
- const [isEditingTitle, setIsEditingTitle] = useState(false);
const [isRenaming, setIsRenaming] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
- const editingInputRef = useRef<HTMLInputElement>(null);
+
+ const {
+ handleDropdownCloseAutoFocus,
+ inputRef: editingInputRef,
+ isEditing: isEditingTitle,
+ startEdit: handleTemplateRenameStart,
+ stopEdit: handleTemplateRenameCancel,
+ } = useInlineEditTitle({ resetKey: templateId });
// Fetch template data when editing
const { data: templateData, loading: isLoadingTemplate } = useFlowTemplateQuery({
@@ -275,50 +284,10 @@ const Template = () => {
reset({ text, title }, { keepDefaultValues: false });
}, [templateData, isNew, reset]);
- // Reset inline-edit state when navigating between templates so the input
- // doesn't carry over a stale draft from a previous template.
- useEffect(() => {
- setIsEditingTitle(false);
- }, [templateId]);
-
- // Focus and select the rename input when the inline editor opens. We can't
- // rely on `autoFocus` here: the input mounts inside the same render cycle
- // that closes the Radix DropdownMenu, and the dropdown's own focus restore
- // (which it schedules via `requestAnimationFrame`) wins the race against
- // React's autoFocus effect. Defer our focus to the next frame so it lands
- // *after* Radix has finished its restore. Selecting the text lets the user
- // overwrite the title in one keystroke.
- useEffect(() => {
- if (!isEditingTitle) {
- return;
- }
-
- const id = requestAnimationFrame(() => {
- const input = editingInputRef.current;
-
- if (!input) {
- return;
- }
-
- input.focus();
- input.select();
- });
-
- return () => cancelAnimationFrame(id);
- }, [isEditingTitle]);
-
// Check if form has unsaved changes
const hasUnsavedChanges = formState.isDirty;
const templateName = templateData?.flowTemplate?.title ?? null;
- const handleTemplateRenameStart = useCallback(() => {
- setIsEditingTitle(true);
- }, []);
-
- const handleTemplateRenameCancel = useCallback(() => {
- setIsEditingTitle(false);
- }, []);
-
const handleTemplateRenameSave = useCallback(async () => {
const newTitle = editingInputRef.current?.value.trim();
const template = templateData?.flowTemplate;
@@ -328,7 +297,7 @@ const Template = () => {
}
if (newTitle === template.title) {
- setIsEditingTitle(false);
+ handleTemplateRenameCancel();
return;
}
@@ -340,13 +309,13 @@ const Template = () => {
// rename never overwrites unsaved edits in the form below.
await updateTemplate(templateId, { text: template.text, title: newTitle });
toast.success('Template renamed successfully');
- setIsEditingTitle(false);
+ handleTemplateRenameCancel();
} catch {
// Error already handled in provider with toast
} finally {
setIsRenaming(false);
}
- }, [templateId, templateData?.flowTemplate, updateTemplate]);
+ }, [editingInputRef, handleTemplateRenameCancel, templateId, templateData?.flowTemplate, updateTemplate]);
const handleTemplateDelete = useCallback(async () => {
if (!templateId) {
@@ -435,45 +404,15 @@ const Template = () => {
<BreadcrumbList>
<BreadcrumbItem className="gap-2">
{isEditingTitle && canShowActions ? (
- <InputGroup className="h-8 w-64 max-w-full">
- <InputGroupInput
- className="text-foreground"
- defaultValue={templateName ?? ''}
- onKeyDown={(event) => {
- if (event.key === 'Enter') {
- event.preventDefault();
- handleTemplateRenameSave();
-
- return;
- }
-
- if (event.key === 'Escape') {
- event.preventDefault();
- handleTemplateRenameCancel();
- }
- }}
- placeholder="Template title"
- ref={editingInputRef}
- />
- <InputGroupAddon
- align="inline-end"
- className="gap-0 pr-2"
- >
- <InputGroupButton
- aria-label="Save"
- disabled={isRenaming}
- onClick={() => handleTemplateRenameSave()}
- >
- {isRenaming ? <Loader2 className="animate-spin" /> : <Check />}
- </InputGroupButton>
- <InputGroupButton
- aria-label="Cancel"
- onClick={() => handleTemplateRenameCancel()}
- >
- <X />
- </InputGroupButton>
- </InputGroupAddon>
- </InputGroup>
+ <InlineRenameInput
+ busy={isRenaming}
+ className="w-64 max-w-full"
+ defaultValue={templateName ?? ''}
+ inputRef={editingInputRef}
+ onCancel={handleTemplateRenameCancel}
+ onSave={handleTemplateRenameSave}
+ placeholder="Template title"
+ />
) : canShowActions ? (
<Tooltip>
<TooltipTrigger asChild>
@@ -493,6 +432,13 @@ const Template = () => {
</BreadcrumbList>
</Breadcrumb>
<div className="ml-auto flex items-center gap-2">
+ {canShowActions && (
+ <ListNavigationToolbar<Template>
+ {...templateToolbarProps}
+ sheetIcon={<FileText className="size-4" />}
+ sheetTitle="Templates"
+ />
+ )}
<Button
onClick={() => setIsAsideOpen((open) => !open)}
size="icon"
@@ -514,14 +460,7 @@ const Template = () => {
<DropdownMenuContent
align="end"
className="min-w-24"
- onCloseAutoFocus={(event) => {
- // Radix returns focus to the trigger on close. When the
- // selected action mounts the rename input, prevent that
- // restore so our deferred focus actually wins.
- if (isEditingTitle) {
- event.preventDefault();
- }
- }}
+ onCloseAutoFocus={handleDropdownCloseAutoFocus}
>
<DropdownMenuItem onClick={handleTemplateRenameStart}>
<Pencil className="size-3" />
diff --git a/frontend/src/pages/templates/templates.tsx b/frontend/src/pages/templates/templates.tsx
index 00d109ed..dae6d39f 100644
--- a/frontend/src/pages/templates/templates.tsx
+++ b/frontend/src/pages/templates/templates.tsx
@@ -1,24 +1,14 @@
import type { ColumnDef } from '@tanstack/react-table';
-import {
- ArrowDown,
- ArrowUp,
- Check,
- Ellipsis,
- FileText,
- Loader2,
- Pencil,
- PencilLine,
- Plus,
- Trash,
- X,
-} from 'lucide-react';
+import { Ellipsis, FileText, Loader2, Pencil, PencilLine, Plus, Trash } from 'lucide-react';
import { useCallback, useRef, useState } from 'react';
-import { useNavigate } from 'react-router-dom';
+import { useLocation, useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import ConfirmationDialog from '@/components/shared/confirmation-dialog';
import { HeaderButton } from '@/components/shared/header-button';
+import { InlineRenameInput } from '@/components/shared/inline-rename-input';
+import { SortableColumnHeader } from '@/components/shared/sortable-column-header';
import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage } from '@/components/ui/breadcrumb';
import { Button } from '@/components/ui/button';
import { ContextMenuItem, ContextMenuSeparator } from '@/components/ui/context-menu';
@@ -30,15 +20,16 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
-import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';
import { Separator } from '@/components/ui/separator';
import { SidebarTrigger } from '@/components/ui/sidebar';
import { StatusCard } from '@/components/ui/status-card';
-import { cycleColumnSort } from '@/lib/table-sort';
+import { useTableQueryFilter } from '@/hooks/use-table-query-filter';
+import { mergeHrefWithSearchParams } from '@/lib/url-params';
import { type Template, useTemplates } from '@/providers/templates-provider';
const Templates = () => {
const navigate = useNavigate();
+ const location = useLocation();
const { deleteTemplate, templates, updateTemplate } = useTemplates();
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
const [deletingTemplate, setDeletingTemplate] = useState<null | Template>(null);
@@ -47,11 +38,13 @@ const Templates = () => {
const [isRenameLoading, setIsRenameLoading] = useState(false);
const editingInputRef = useRef<HTMLInputElement>(null);
+ const { filter, setFilter } = useTableQueryFilter();
+
const handleTemplateOpen = useCallback(
(templateId: string) => {
- navigate(`/templates/${templateId}`);
+ navigate(mergeHrefWithSearchParams(`/templates/${templateId}`, new URLSearchParams(location.search)));
},
- [navigate],
+ [navigate, location.search],
);
const handleDeleteDialogOpen = useCallback((template: Template) => {
@@ -131,71 +124,23 @@ const Templates = () => {
if (isEditing) {
return (
- <InputGroup
- className="h-8"
- onClick={(e) => e.stopPropagation()}
- >
- <InputGroupInput
+ <div onClick={(e) => e.stopPropagation()}>
+ <InlineRenameInput
autoFocus
+ busy={isRenameLoading}
defaultValue={title}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- handleTemplateRenameSave();
-
- return;
- }
-
- if (e.key === 'Escape') {
- e.preventDefault();
- handleTemplateRenameCancel();
- }
- }}
+ inputRef={editingInputRef}
+ onCancel={handleTemplateRenameCancel}
+ onSave={handleTemplateRenameSave}
placeholder="Template title"
- ref={editingInputRef}
/>
- <InputGroupAddon
- align="inline-end"
- className="gap-0 pr-2"
- >
- <InputGroupButton
- aria-label="Save"
- disabled={isRenameLoading}
- onClick={() => handleTemplateRenameSave()}
- >
- {isRenameLoading ? <Loader2 className="animate-spin" /> : <Check />}
- </InputGroupButton>
- <InputGroupButton
- aria-label="Cancel"
- onClick={() => handleTemplateRenameCancel()}
- >
- <X />
- </InputGroupButton>
- </InputGroupAddon>
- </InputGroup>
+ </div>
);
}
return <div className="font-medium">{title}</div>;
},
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => cycleColumnSort(column)}
- variant="link"
- >
- Title
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => <SortableColumnHeader column={column} label="Title" />,
},
{
accessorKey: 'text',
@@ -204,24 +149,7 @@ const Templates = () => {
return <div className="text-muted-foreground max-w-[380px] truncate text-sm">{text}</div>;
},
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => cycleColumnSort(column)}
- variant="link"
- >
- Text
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
+ header: ({ column }) => <SortableColumnHeader column={column} label="Text" />,
},
{
cell: ({ row }) => {
@@ -364,6 +292,8 @@ const Templates = () => {
data={templates}
filterColumn="title"
filterPlaceholder="Filter templates..."
+ filterValue={filter}
+ onFilterChange={setFilter}
onRowClick={(template) => {
if (editingTemplateId !== template.id) {
handleTemplateOpen(template.id);
diff --git a/frontend/src/types/tanstack-table.d.ts b/frontend/src/types/tanstack-table.d.ts
index 13d399cb..ab5258d8 100644
--- a/frontend/src/types/tanstack-table.d.ts
+++ b/frontend/src/types/tanstack-table.d.ts
@@ -4,6 +4,8 @@ declare module '@tanstack/react-table' {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface ColumnMeta<TData, TValue> {
cellClassName?: string;
+ /** Label for the Columns visibility menu when `column.id` is not human-readable. */
+ columnMenuLabel?: string;
headerClassName?: string;
preventRowClick?: boolean;
}
diff --git a/frontend/types/vitest.d.ts b/frontend/types/vitest.d.ts
new file mode 100644
index 00000000..c08c340b
--- /dev/null
+++ b/frontend/types/vitest.d.ts
@@ -0,0 +1,5 @@
+// Augment Vitest's `expect` with @testing-library/jest-dom matchers
+// (`toBeInTheDocument`, `toBeDisabled`, `toHaveAttribute`, etc.) globally so
+// individual test files don't need a per-file `import type {} from
+// '@testing-library/jest-dom'` to satisfy the type checker.
+import '@testing-library/jest-dom/vitest';
diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.ts
new file mode 100644
index 00000000..50419e71
--- /dev/null
+++ b/frontend/vitest.config.ts
@@ -0,0 +1,23 @@
+import path from 'node:path';
+import { defineConfig } from 'vitest/config';
+
+// Vitest config lives in its own file so the production `vite.config.ts`
+// stays free of test-only concerns (jsdom, setup files, etc).
+//
+// `jsdom` is the environment because most tests under `src/` reach into
+// React Testing Library at some point — pure-function suites pay a small
+// fixed cost (a few ms per file) but the alternative of per-file
+// `@vitest-environment` comments fragments quickly.
+export default defineConfig({
+ resolve: {
+ alias: {
+ '@': path.resolve(__dirname, './src'),
+ },
+ },
+ test: {
+ environment: 'jsdom',
+ globals: false,
+ include: ['src/**/*.{test,spec}.{ts,tsx}'],
+ setupFiles: ['./vitest.setup.ts'],
+ },
+});
diff --git a/frontend/vitest.setup.ts b/frontend/vitest.setup.ts
new file mode 100644
index 00000000..1077c3e1
--- /dev/null
+++ b/frontend/vitest.setup.ts
@@ -0,0 +1,39 @@
+import '@testing-library/jest-dom/vitest';
+
+import { cleanup } from '@testing-library/react';
+import { afterEach } from 'vitest';
+
+// jsdom doesn't implement `Element.prototype.scrollIntoView` — components
+// that call it from effects (e.g. roving-focus + scroll into view) crash in
+// tests without this no-op polyfill.
+if (typeof Element !== 'undefined' && !Element.prototype.scrollIntoView) {
+ Element.prototype.scrollIntoView = function scrollIntoView() {
+ /* no-op for jsdom */
+ };
+}
+
+// Radix ScrollArea (used inside the navigation sheet) calls
+// `new ResizeObserver(...)` from a layout effect; jsdom doesn't ship one.
+// The component degrades gracefully — a no-op observer never invokes the
+// callback, which is fine for tests that don't assert on overflow state.
+if (typeof globalThis.ResizeObserver === 'undefined') {
+ class NoopResizeObserver implements ResizeObserver {
+ disconnect() {
+ /* no-op */
+ }
+ observe() {
+ /* no-op */
+ }
+ unobserve() {
+ /* no-op */
+ }
+ }
+ globalThis.ResizeObserver = NoopResizeObserver as unknown as typeof ResizeObserver;
+}
+
+// React Testing Library leaves rendered nodes attached to `document.body`
+// after each test. Without this, tests would leak DOM state into each other
+// — e.g. two `render(<X />)` calls would both end up on screen at once.
+afterEach(() => {
+ cleanup();
+});