Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): improve community unread, drag interactions, and Inbox (#1048)

Generd9007c98a10c
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c8b97833e..ebf677c38 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -259,30 +259,9 @@ importers:
'@alook/shared':
specifier: workspace:*
version: link:../shared
- '@atlaskit/pragmatic-drag-and-drop':
- specifier: 3.1.0
- version: 3.1.0
- '@atlaskit/pragmatic-drag-and-drop-auto-scroll':
- specifier: 3.2.1
- version: 3.2.1
- '@atlaskit/pragmatic-drag-and-drop-hitbox':
- specifier: 2.2.2
- version: 2.2.2
- '@atlaskit/pragmatic-drag-and-drop-live-region':
- specifier: 2.1.0
- version: 2.1.0
'@base-ui/react':
specifier: ^1.9.0
version: 1.9.0(patch_hash=51d33f6e4f128a90fe02d40ba5c0f2cd5614eabbab780845f28186dc473cab0a)(@date-fns/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])
- '@dnd-kit/core':
- specifier: ^6.3.1
- '@dnd-kit/sortable':
- specifier: ^10.0.0
- '@dnd-kit/utilities':
- specifier: ^3.2.2
- version: 3.2.2([email protected])
'@emoji-mart/data':
specifier: ^1.2.1
version: 1.2.1
@@ -412,6 +391,9 @@ importers:
clsx:
specifier: ^2.1.1
version: 2.1.1
+ dnd-multi-backend:
+ specifier: 9.0.0
+ version: 9.0.0([email protected])
emoji-mart:
specifier: ^5.6.0
version: 5.6.0
@@ -478,6 +460,18 @@ importers:
react:
specifier: 19.3.1
version: 19.3.1
+ react-dnd:
+ specifier: 16.0.1
+ version: 16.0.1(@types/[email protected])(@types/[email protected])([email protected])
+ react-dnd-html5-backend:
+ specifier: 16.0.1
+ version: 16.0.1
+ react-dnd-scrolling:
+ specifier: 1.3.10
+ react-dnd-touch-backend:
+ specifier: 16.0.1
+ version: 16.0.1
react-dom:
specifier: 19.3.1
version: 19.3.1([email protected])
@@ -610,7 +604,7 @@ importers:
version: 9.39.5([email protected])
eslint-config-next:
specifier: 16.4.1
eslint-plugin-tailwind-canonical-classes:
specifier: ^1.4.1
@@ -623,6 +617,9 @@ importers:
knip:
specifier: ^6.32.2
version: 6.32.2
+ react-dnd-test-backend:
+ specifier: 16.0.1
+ version: 16.0.1
react-scan:
specifier: 0.5.7
@@ -793,21 +790,6 @@ packages:
'@astrojs/[email protected]':
resolution: {integrity: sha512-eouss7G8ygdZqHuke033VMcVw5HTZUu+PXd/h06DGDUg/jt5btPYPqh66ENWw/mU78rBrf/oeC4oqoBwMtDMNA==}
- '@atlaskit/[email protected]':
- resolution: {integrity: sha512-2fhWAG48EjPoKhoHLG6RcT3/VaCzYEbRb6BtA/Vcfx4FrL0P1KrEgBJ6OAwB0X8MOV6UH22YgjFFHjv8fQD9rA==}
-
- '@atlaskit/[email protected]':
- resolution: {integrity: sha512-2Or4BWVX9ZlgsCCvgbmGEwjv2134vZARL5SezP8Dsrh3ayPYThU55Ug4dBzDAqiIJE2q8aPn+zO8YYoATa4wuA==}
-
- '@atlaskit/[email protected]':
- resolution: {integrity: sha512-7THqnYhsSQnVqyVBCdMvdjWTjE3bUd5WKqs8g2SVv6UgJTIKunVmCH5lg6oySmqGGyVtHyOf7aXgpVpgUS9kbg==}
-
- '@atlaskit/[email protected]':
- resolution: {integrity: sha512-VU+2Oh6OgvC6D1xiX3lfm1gZJsaSPD+ZKjAHodOQ9IO6RfOvAyReLlK5ut9gIUpPmbD8d09wlCs7y4A6/I8c5Q==}
-
- '@atlaskit/[email protected]':
- resolution: {integrity: sha512-pyDo2B5NiaExoKGmgeXKGNUL4aR4UzzSZm8QWWjYTEyBLVqSqKyKUwtVxMw2YEkakagOGFONUdHM32LAH2nPug==}
-
'@aws-crypto/[email protected]':
resolution: {integrity: sha512-OH6lveCFfcDjX4dbAvCFSYUjJZjDr/3XJ3xHtjn3Oj5b9RjojQo8npoLeA/bNwkOkrSQ0wgrHzXk4tDRxGKJeg==}
@@ -1347,28 +1329,6 @@ packages:
'@date-fns/[email protected]':
resolution: {integrity: sha512-P5LUNhtbj6YfI3iJjw5EL9eUAG6OitD0W3fWQcpQjDRc/QIsL0tRNuO1PcDvPccWL1fSTXXdE1ds+l95DV/OFA==}
- '@dnd-kit/[email protected]':
- resolution: {integrity: sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==}
- peerDependencies:
- react: '>=16.8.0'
-
- '@dnd-kit/[email protected]':
- resolution: {integrity: sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==}
- peerDependencies:
- react: '>=16.8.0'
- react-dom: '>=16.8.0'
-
- '@dnd-kit/[email protected]':
- resolution: {integrity: sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==}
- peerDependencies:
- '@dnd-kit/core': ^6.3.0
- react: '>=16.8.0'
-
- '@dnd-kit/[email protected]':
- resolution: {integrity: sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==}
- peerDependencies:
- react: '>=16.8.0'
-
'@dotenvx/[email protected]':
resolution: {integrity: sha512-/BITOC9dmS/edY2zQwZNicQ059O6RKabtQfyEafV0nGtfYRNHYy1DIPiYVcov40+tob9hfmBnbR963dS+EQ1DQ==}
hasBin: true
@@ -2331,6 +2291,7 @@ packages:
'@opentelemetry/[email protected]':
resolution: {integrity: sha512-H19x/TX/LZdqiYOjM7fqtSxwlplC5pgelavqbQdHbhdq0q/AI/TGkM2dfGuuynTXmJPeF2HoZVoPDu+TGoW78A==}
engines: {node: ^18.19.0 || >=20.6.0}
+ deprecated: Use @opentelemetry/sdk-trace package
peerDependencies:
'@opentelemetry/api': '>=1.3.0 <1.10.0'
@@ -2884,6 +2845,15 @@ packages:
engines: {node: '>=18'}
hasBin: true
+ '@react-dnd/[email protected]':
+ resolution: {integrity: sha512-WLyfoHvxhs0V9U+GTsGilGgf2QsPl6ZZ44fnv0/b8T3nQyvzxidxsg/ZltbWssbsRDlYW8UKSQMTGotuTotZ6A==}
+
+ '@react-dnd/[email protected]':
+ resolution: {integrity: sha512-xKCTqAK/FFauOM9Ta2pswIyT3D8AQlfrYdOi/toTPEhqCuAs1v5tcJ3Y08Izh1cJ5Jchwy9SeAXmMg6zrKs2iw==}
+
+ '@react-dnd/[email protected]':
+ resolution: {integrity: sha512-/RVXdLvJxLg4QKvMoM5WlwNR9ViO9z8B/qPcc+C0Sa/teJY7QG7kJ441DwzOjMYEY7GmU4dj5EcGHIkKZiQZCA==}
+
'@react-grab/[email protected]':
resolution: {integrity: sha512-LVfA+j5cFT0Szd958WRD8W/B8ucCtz4ViiveDKWLqAwBkZFW9VRW1ZvwOUhp/M3SmVPtjDaRkW12GvAuTArP+Q==}
hasBin: true
@@ -4243,10 +4213,6 @@ packages:
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
typescript: '>=4.8.4 <6.1.0'
- '@typescript-eslint/[email protected]':
- resolution: {integrity: sha512-ybYnPTUwg3VQQOFEiBPLs8Jxl1ry2vXdn1kVKguomBbvxpetdu3MKTNDqFNUrlG8ylP9MpZosmXMFYlGQHk1oQ==}
- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
-
'@typescript-eslint/[email protected]':
resolution: {integrity: sha512-y5Ukl3oVp7e/VGxqIoEXoeb/Roj71PAJ4WG/N/RGj+eeDvKRLM15kGr9MijLbN0i03S52zxu31Z98E5gWChJKw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -4814,9 +4780,6 @@ packages:
resolution: {integrity: sha512-nbE1WxOTTrUWIfsfZ4aHGYu5DOuNkbxGokjV6Z2kxfJK3uaAb8zNK1muzOeipoLHZjInT4Br88BHpzevc681xA==}
- resolution: {integrity: sha512-PJvH288AWQhKs2v9zyfYdPzlPqf5bXbGMmhmUIY9x4dAUGIWgomO771oBQNwJnMQSnUIXhKu6sgzpBRXTlvb8Q==}
-
resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==}
@@ -5508,6 +5471,14 @@ packages:
resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==}
engines: {node: '>=0.3.1'}
+ resolution: {integrity: sha512-HK294sl7tbw6F6IeuK16YSBUoorvHpY8RHO+9yFfaJyCDVb6n7PRcezrOEOa2SBCqiYpemh5Jx20ZcjKdFAVng==}
+
+ resolution: {integrity: sha512-BCUFes4x0LA2bZyEZFHeQzZ1CBZo6PB40zMOG/gNgICxjAZfN2jHgISowqkR1isdx/msUNzscxEb17SP7yc4KQ==}
+ peerDependencies:
+ dnd-core: ^16.0.1
+
resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==}
engines: {node: '>=0.10.0'}
@@ -5717,8 +5688,8 @@ packages:
resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==}
- resolution: {integrity: sha512-BldNY5mwkVu+cQ5Ymn3e6hB9Sx8XHx4ZevWbiUyZbfKxJxYO27Hf0wfzkxIaD5CAJMaGl3YspKELj0ff/7nCMA==}
+ resolution: {integrity: sha512-yWGe1O/j+almnV4hOYrmZo8u58JdnmXEMneRQAYkWtqSiT86yoMIEKF4rpqEDj52tbYl3xceBD3DQIBwcsC9Pw==}
resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==}
@@ -6047,8 +6018,8 @@ packages:
resolution: {integrity: sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==}
- resolution: {integrity: sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==}
+ resolution: {integrity: sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==}
resolution: {integrity: sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==}
@@ -6399,6 +6370,9 @@ packages:
resolution: {integrity: sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==}
+ resolution: {integrity: sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==}
+
resolution: {integrity: sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==}
engines: {node: '>=16.9.0'}
@@ -7117,6 +7091,9 @@ packages:
resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}
+ resolution: {integrity: sha512-wIkUCfVKpVsWo3JSZlc+8MB5it+2AN5W8J7YVMST30UrvcQNZ1Okbj+rbVniijTWE6FGYy4XJq/rHkas8qJMLQ==}
+
resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==}
@@ -7168,9 +7145,6 @@ packages:
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
- resolution: {integrity: sha512-llBEhWm1SacoRwgHUoQJYtwp4PBLF4faQi5TCpIGyGs9n4y5+juI0tDgyKIfpqxckRHaHzouUEph3THklWh03w==}
-
resolution: {integrity: sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==}
@@ -7943,6 +7917,9 @@ packages:
resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==}
+ resolution: {integrity: sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==}
+
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -8001,10 +7978,6 @@ packages:
resolution: {integrity: sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==}
engines: {node: ^10 || ^12 || >=14}
- resolution: {integrity: sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==}
- engines: {node: ^10 || ^12 || >=14}
-
resolution: {integrity: sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==}
engines: {node: ^10 || ^12 || >=14}
@@ -8137,8 +8110,8 @@ packages:
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
- resolution: {integrity: sha512-tQkJl2GRWh83ui2DiPTJz9wEiMN20syf+5oKfB03yYP7ioZcJwsIK8FjrtLwH1m7C7e+Tt2yYBlrOpdT+dyeIQ==}
+ resolution: {integrity: sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==}
resolution: {integrity: sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==}
@@ -8160,6 +8133,37 @@ packages:
resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==}
hasBin: true
+ resolution: {integrity: sha512-Wu3dw5aDJmOGw8WjH1I1/yTH+vlXEL4vmjk5p+MHxP8HuHJS1lAGeIdG/hze1AvNeXWo/JgULV87LyQOr+r5jw==}
+
+ resolution: {integrity: sha512-Vbe7tp6ZC2kgBx/8P1LXa3+3ao61Ve8HcoVzicnAuRiaV/r3lmccE9JVsa0TeZ+pzTBodb+MzQW0tMOMSRmtwg==}
+ peerDependencies:
+ react: 16.x || 17.x || 18.x
+ react-dnd: 10.x || 11.x || 14.x || 15.x || 16.x
+ react-dom: 16.x || 17.x || 18.x
+
+ resolution: {integrity: sha512-sUsQKMmoachP3AGaHLZD4JZWq2dHPoiLRG3YVuC0gXJtGENk3PVR+uRIrml7BEnnTyv+RVeoNK2ziL38Ggh8cw==}
+
+ resolution: {integrity: sha512-NonoCABzzjyWGZuDxSG77dbgMZ2Wad7eQiCd/ECtsR2/NBLTjGksPUx9UPezZ1nQ/L7iD130Tz3RUshL/ClKLA==}
+
+ resolution: {integrity: sha512-QeoM/i73HHu2XF9aKksIUuamHPDvRglEwdHL4jsp784BgUuWcg6mzfxT0QDdQz8Wj0qyRKx2eMg8iZtWvU4E2Q==}
+ peerDependencies:
+ '@types/hoist-non-react-statics': '>= 3.3.1'
+ '@types/node': '>= 12'
+ '@types/react': '>= 16'
+ react: '>= 16.14'
+ peerDependenciesMeta:
+ '@types/hoist-non-react-statics':
+ optional: true
+ '@types/node':
+ optional: true
+ '@types/react':
+ optional: true
+
resolution: {integrity: sha512-4Ach00KtfnfjTBGgr2PyPgHua85vT/UfPY5sR0bHgRAc/QSu0JInA0GHCL6a7WFGMeGUrxtGnI8oqZinG44BOA==}
engines: {node: ^20.19.0 || >=22.13.0}
@@ -8238,6 +8242,9 @@ packages:
resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w==}
+
resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==}
engines: {node: '>= 0.4'}
@@ -9745,32 +9752,6 @@ snapshots:
'@astrojs/[email protected]': {}
- '@atlaskit/[email protected]':
- dependencies:
- '@atlaskit/pragmatic-drag-and-drop': 4.0.0
- '@babel/runtime': 7.29.7
-
- '@atlaskit/[email protected]':
- dependencies:
- '@atlaskit/pragmatic-drag-and-drop': 3.1.0
- '@babel/runtime': 7.29.7
-
- '@atlaskit/[email protected]':
- dependencies:
- '@babel/runtime': 7.29.7
-
- '@atlaskit/[email protected]':
- dependencies:
- '@babel/runtime': 7.29.7
- bind-event-listener: 3.0.0
- raf-schd: 4.0.3
-
- '@atlaskit/[email protected]':
- dependencies:
- '@babel/runtime': 7.29.10
- bind-event-listener: 3.0.0
- raf-schd: 4.0.3
-
'@aws-crypto/[email protected]':
dependencies:
'@aws-crypto/supports-web-crypto': 5.2.0
@@ -10664,31 +10645,6 @@ snapshots:
'@date-fns/[email protected]':
optional: true
- dependencies:
- react: 19.3.1
- tslib: 2.8.1
-
- dependencies:
- '@dnd-kit/accessibility': 3.1.1([email protected])
- '@dnd-kit/utilities': 3.2.2([email protected])
- react: 19.3.1
- react-dom: 19.3.1([email protected])
- tslib: 2.8.1
-
- dependencies:
- '@dnd-kit/utilities': 3.2.2([email protected])
- react: 19.3.1
- tslib: 2.8.1
-
- dependencies:
- react: 19.3.1
- tslib: 2.8.1
-
'@dotenvx/[email protected]':
dependencies:
'@dotenvx/primitives': 0.8.0
@@ -12054,6 +12010,12 @@ snapshots:
- react-native-b4a
- supports-color
+ '@react-dnd/[email protected]': {}
+
+ '@react-dnd/[email protected]': {}
+
+ '@react-dnd/[email protected]': {}
+
'@react-grab/[email protected]':
dependencies:
agent-install: 0.0.6
@@ -13581,7 +13543,7 @@ snapshots:
magicast: 0.5.5
obug: 2.2.1
tinyrainbow: 3.2.0
transitivePeerDependencies:
- supports-color
@@ -13597,7 +13559,7 @@ snapshots:
obug: 2.2.1
std-env: 4.3.0
tinyrainbow: 3.2.0
'@vitest/[email protected]':
dependencies:
@@ -13737,7 +13699,7 @@ snapshots:
dependencies:
fast-deep-equal: 3.1.3
- fast-uri: 3.1.8
+ fast-uri: 3.1.2
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
@@ -13995,8 +13957,6 @@ snapshots:
-
dependencies:
file-uri-to-path: 1.0.0
@@ -14714,6 +14674,16 @@ snapshots:
+ dependencies:
+ '@react-dnd/asap': 5.0.2
+ '@react-dnd/invariant': 4.0.2
+ redux: 4.2.1
+
+ dependencies:
+ dnd-core: 16.0.1
+
dependencies:
esutils: 2.0.3
@@ -14886,7 +14856,7 @@ snapshots:
dependencies:
@@ -14977,13 +14947,13 @@ snapshots:
optionalDependencies:
source-map: 0.6.1
dependencies:
'@next/eslint-plugin-next': 16.4.1([email protected]([email protected]))
eslint: 9.39.5([email protected])
eslint-import-resolver-node: 0.3.10
- eslint-plugin-import: 2.32.0([email protected])([email protected]([email protected]))
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
eslint-plugin-react-hooks: 7.1.1([email protected]([email protected]))
@@ -15005,7 +14975,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.3
@@ -15016,21 +14986,22 @@ snapshots:
tinyglobby: 0.2.17
unrs-resolver: 1.12.2
optionalDependencies:
- eslint-plugin-import: 2.32.0([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
+ '@typescript-eslint/parser': 8.71.2([email protected]([email protected]))([email protected])
eslint: 9.39.5([email protected])
eslint-import-resolver-node: 0.3.10
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
dependencies:
'@rtsao/scc': 1.1.0
array-includes: 3.2.0
@@ -15041,7 +15012,7 @@ snapshots:
doctrine: 2.1.0
eslint: 9.39.5([email protected])
eslint-import-resolver-node: 0.3.10
hasown: 2.0.4
is-core-module: 2.17.0
is-glob: 4.0.3
@@ -15052,6 +15023,8 @@ snapshots:
semver: 6.3.1
string.prototype.trimend: 1.0.10
tsconfig-paths: 3.15.0
+ optionalDependencies:
+ '@typescript-eslint/parser': 8.71.2([email protected]([email protected]))([email protected])
transitivePeerDependencies:
- eslint-import-resolver-typescript
- eslint-import-resolver-webpack
@@ -15411,7 +15384,7 @@ snapshots:
fast-string-truncated-width: 3.0.3
optional: true
dependencies:
@@ -15886,6 +15859,10 @@ snapshots:
dependencies:
hermes-estree: 0.25.1
+ dependencies:
+ react-is: 16.13.1
+
@@ -15970,7 +15947,7 @@ snapshots:
dependencies:
cjs-module-lexer: 2.3.0
- es-module-lexer: 3.0.4
+ es-module-lexer: 3.0.3
module-details-from-path: 1.0.4
@@ -16585,6 +16562,8 @@ snapshots:
+
@@ -17855,6 +17834,8 @@ snapshots:
+
@@ -18095,7 +18076,9 @@ snapshots:
+ dependencies:
+ performance-now: 2.1.0
@@ -18122,6 +18105,41 @@ snapshots:
minimist: 1.2.8
strip-json-comments: 2.0.1
+ dependencies:
+ dnd-core: 16.0.1
+
+ dependencies:
+ hoist-non-react-statics: 3.3.2
+ lodash.throttle: 4.1.1
+ prop-types: 15.8.1
+ raf: 3.4.1
+ react: 19.3.1
+ react-dnd: 16.0.1(@types/[email protected])(@types/[email protected])([email protected])
+ react-dom: 19.3.1([email protected])
+
+ dependencies:
+ dnd-core: 16.0.1
+
+ dependencies:
+ '@react-dnd/invariant': 4.0.2
+ dnd-core: 16.0.1
+
+ dependencies:
+ '@react-dnd/invariant': 4.0.2
+ '@react-dnd/shallowequal': 4.0.2
+ dnd-core: 16.0.1
+ fast-deep-equal: 3.1.3
+ hoist-non-react-statics: 3.3.2
+ react: 19.3.1
+ optionalDependencies:
+ '@types/node': 25.9.4
+ '@types/react': 19.3.0
+
dependencies:
'@astrojs/compiler': 4.0.0
@@ -18264,6 +18282,10 @@ snapshots:
indent-string: 4.0.0
strip-indent: 3.0.0
+ dependencies:
+ '@babel/runtime': 7.29.10
+
dependencies:
call-bind: 1.0.9
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index 153464d61..e395a2e01 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -53,7 +53,7 @@ export const SPEC_SECONDS = {
"35-bot-token-usage-quota.spec.ts": 10.867,
"35-channel-ref-directory-states.spec.ts": 12.626,
"36-server-switch-pending-checkpoint.spec.ts": 5.732,
- "37-server-rail-pdd.spec.ts": 21.594,
+ "37-server-rail-dnd.spec.ts": 21.594,
"38-community-navigation-checkpoint-matrix.spec.ts": 4.646,
"39-mobile-composer-send.spec.ts": 16.534,
"39-mobile-message-interactions.spec.ts": 58.479,
diff --git a/scripts/ci/fixtures/d1-dynamic-bind-sites.json b/scripts/ci/fixtures/d1-dynamic-bind-sites.json
index 432f1077c..9da1646e1 100644
--- a/scripts/ci/fixtures/d1-dynamic-bind-sites.json
+++ b/scripts/ci/fixtures/d1-dynamic-bind-sites.json
@@ -317,6 +317,9 @@
{
"key": "src/shared/src/db/queries/community/channel.ts:getDirectChildThreadsByIds:inArray:1"
},
+ {
+ "key": "src/shared/src/db/queries/community/channel.ts:getServerRootChannelsByIds:inArray:1"
+ },
{
"key": "src/shared/src/db/queries/community/channel.ts:listChildChannelsByParentMessageIds:inArray:1"
},
diff --git a/src/daemon/src/telemetry/dailyTokenUsage.test.ts b/src/daemon/src/telemetry/dailyTokenUsage.test.ts
index 9e6787f1e..b0b456a29 100644
--- a/src/daemon/src/telemetry/dailyTokenUsage.test.ts
+++ b/src/daemon/src/telemetry/dailyTokenUsage.test.ts
@@ -95,17 +95,20 @@ describe("DailyTokenUsageStore", () => {
it("exposes 30 UTC days while retaining two recovery days", async () => {
const root = mkdtempSync(join(tmpdir(), "alook-token-retention-"));
roots.push(root);
- let now = new Date("2026-07-27T12:00:00Z");
- const store = new DailyTokenUsageStore(root, () => now, "UTC");
- for (let day = 0; day < 33; day += 1) {
- await store.record("bot", delta(day, day, day));
- now = new Date(now.getTime() + 86_400_000);
- }
- now = new Date("2026-08-28T12:00:00Z");
+ const directory = join(root, ".telemetry");
+ mkdirSync(directory);
+ const history = Array.from({ length: 32 }, (_, index) => ({
+ botId: "bot",
+ day: new Date(Date.UTC(2026, 6, 27 + index)).toISOString().slice(0, 10),
+ metrics: delta(index, index, index),
+ }));
+ writeFileSync(join(directory, "daily-token-usage.json"), JSON.stringify({ version: 1, bots: { bot: history } }));
+ const store = new DailyTokenUsageStore(root, () => new Date("2026-08-28T12:00:00Z"), "UTC");
+ await store.record("bot", delta(32, 32, 32));
const snapshots = await store.snapshots("bot");
expect(snapshots).toHaveLength(30);
expect(snapshots.at(0)?.day).toBe("2026-07-30");
- expect(snapshots.at(-1)?.day).toBe("2026-08-28");
+ expect(snapshots.at(-1)).toEqual({ botId: "bot", day: "2026-08-28", metrics: delta(32, 32, 32) });
const persisted = JSON.parse(readFileSync(
join(root, ".telemetry", "daily-token-usage.json"),
diff --git a/src/shared/src/community-attention.ts b/src/shared/src/community-attention.ts
index d5803b53a..240d48ee5 100644
--- a/src/shared/src/community-attention.ts
+++ b/src/shared/src/community-attention.ts
@@ -10,6 +10,7 @@ export const AttentionScopeSchema = z.strictObject({
parentChannelId: id.nullable().optional(),
ordinaryUnread: z.boolean(),
lastUnreadSeq: z.number().int().nonnegative(),
+ unreadCount: z.number().int().nonnegative().optional(),
lastAttentionSeq: z.number().int().nonnegative().nullable().optional(),
attentionCount: z.number().int().nonnegative(),
})
diff --git a/src/shared/src/community-channel-order.ts b/src/shared/src/community-channel-order.ts
new file mode 100644
index 000000000..9355cfec0
--- /dev/null
+++ b/src/shared/src/community-channel-order.ts
@@ -0,0 +1,9 @@
+import { z } from "zod"
+
+export const channelReorderRequestSchema = z.strictObject({
+ channelIds: z.array(z.string().min(1)).min(1).refine((ids) => new Set(ids).size === ids.length, "channelIds must be unique"),
+ move: z.strictObject({ channelId: z.string().min(1), categoryId: z.string().min(1).nullable() }).optional(),
+}).refine((request) => !request.move || request.channelIds.includes(request.move.channelId), "moved channel must be included in channelIds")
+
+export type ChannelReorderRequest = z.infer<typeof channelReorderRequestSchema>
+export type ChannelCategoryMove = NonNullable<ChannelReorderRequest["move"]>
diff --git a/src/shared/src/community-server-rail.test.ts b/src/shared/src/community-server-rail.test.ts
index edc59042c..b1d7df121 100644
--- a/src/shared/src/community-server-rail.test.ts
+++ b/src/shared/src/community-server-rail.test.ts
@@ -1,14 +1,16 @@
import { describe, expect, it } from "vitest";
import {
projectServerRailCommit,
+ serverRailTopOrder,
+ serverRailServerIds,
serverRailCommitRequestSchema,
type ServerRailState,
} from "./community-server-rail";
function snapshot(): ServerRailState {
return {
- serverOrder: ["a", "b", "c", "d", "e"],
- folderOrder: ["one", "two"],
+ serverIds: ["a", "b", "c", "d", "e"],
+ folderIds: ["one", "two"],
folders: {
one: { id: "one", name: "One", serverIds: ["c", "d"] },
two: { id: "two", name: "Two", serverIds: ["e"] },
@@ -65,21 +67,52 @@ describe("server rail wire contract", () => {
it("accepts a complete 101+ membership reorder without a cardinality cliff", () => {
const ids = Array.from({ length: 125 }, (_, index) => `server-${index}`);
- const state: ServerRailState = { serverOrder: ids, folderOrder: [], folders: {} };
+ const state: ServerRailState = { serverIds: ids, folderIds: [], folders: {} };
const result = projectServerRailCommit(state, {
- commands: [{ kind: "reorder-servers", serverIds: [...ids].reverse() }],
+ commands: [{ kind: "reorder-top-level", entries: [...ids].reverse().map((id) => ({ kind: "server", id })) }],
}, () => "unused");
expect(result.ok).toBe(true);
- if (result.ok) expect(result.value.after.serverOrder).toEqual([...ids].reverse());
+ if (result.ok) expect(result.value.after.topOrder).toEqual([...ids].reverse().map((id) => ({ kind: "server", id })));
});
it("requires complete reorder sets and rejects no-ops", () => {
expect(projectServerRailCommit(snapshot(), {
- commands: [{ kind: "reorder-servers", serverIds: ["a", "b"] }],
- }, () => "new")).toMatchObject({ ok: false, error: "serverIds must match current memberships" });
+ commands: [{ kind: "reorder-top-level", entries: [{ kind: "server", id: "a" }, { kind: "server", id: "b" }] }],
+ }, () => "new")).toMatchObject({ ok: false, error: "top-level entries must match current servers and folders" });
expect(projectServerRailCommit(snapshot(), {
- commands: [{ kind: "reorder-folders", folderIds: ["one", "two"] }],
+ commands: [{ kind: "reorder-top-level", entries: serverRailTopOrder(snapshot()) }],
}, () => "new")).toMatchObject({ ok: false, error: "rail command is a no-op" });
});
});
+
+describe("personal mixed top-level order", () => {
+ it("validates the exact visible set and maps new folder identities", () => {
+ const state: ServerRailState = { serverIds: ["a", "b", "c"], folderIds: [], folders: {} };
+ const result = projectServerRailCommit(state, { commands: [
+ { kind: "create-folder", clientId: "temp", name: "Group", serverIds: ["b", "a"] },
+ { kind: "reorder-top-level", entries: [{ kind: "folder", id: "temp" }, { kind: "server", id: "c" }] },
+ ] }, () => "confirmed");
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ expect(result.value.after.topOrder).toEqual([{ kind: "folder", id: "confirmed" }, { kind: "server", id: "c" }]);
+ expect(result.value.reorderTopLevel).toBe(true);
+ }
+ for (const entries of [
+ [{ kind: "server" as const, id: "foreign" }],
+ [{ kind: "server" as const, id: "a" }, { kind: "server" as const, id: "a" }, { kind: "server" as const, id: "b" }, { kind: "server" as const, id: "c" }],
+ ]) expect(projectServerRailCommit(state, { commands: [{ kind: "reorder-top-level", entries }] }, () => "unused").ok).toBe(false);
+ });
+ it("rejects a same-order no-op and duplicate top-order commands", () => {
+ const state: ServerRailState = { serverIds: ["a", "b"], folderIds: [], folders: {} };
+ const command = { kind: "reorder-top-level" as const, entries: [{ kind: "server" as const, id: "a" }, { kind: "server" as const, id: "b" }] };
+ expect(projectServerRailCommit(state, { commands: [command] }, () => "unused").ok).toBe(false);
+ expect(projectServerRailCommit(state, { commands: [command, command] }, () => "unused")).toMatchObject({ ok: false, error: "duplicate reorder-top-level command" });
+ });
+});
+
+it("rejects obsolete independent order commands and flattens only canonical roots", () => {
+ for (const kind of ["reorder-servers", "reorder-folders"]) expect(serverRailCommitRequestSchema.safeParse({ commands: [{ kind, serverIds: ["a"], folderIds: [] }] }).success).toBe(false);
+ const state = { ...snapshot(), topOrder: [{ kind: "folder" as const, id: "two" }, { kind: "server" as const, id: "b" }, { kind: "folder" as const, id: "one" }, { kind: "server" as const, id: "a" }] };
+ expect(serverRailServerIds(state)).toEqual(["e", "b", "c", "d", "a"]);
+});
diff --git a/src/shared/src/community-server-rail.ts b/src/shared/src/community-server-rail.ts
index 9219e599b..6e5f72911 100644
--- a/src/shared/src/community-server-rail.ts
+++ b/src/shared/src/community-server-rail.ts
@@ -4,20 +4,22 @@ import { MAX_FOLDER_NAME_LENGTH } from "./constants/community";
export const MAX_SERVER_RAIL_COMMANDS = 3;
export const MAX_SERVER_RAIL_FOLDERS = 10;
export const MAX_SERVER_RAIL_REQUEST_BYTES = 1_000_000;
-export const SERVER_RAIL_SNAPSHOT_STATEMENTS = 3;
-export const SERVER_RAIL_MAX_WRITE_STATEMENTS = 13;
+export const SERVER_RAIL_SNAPSHOT_STATEMENTS = 4;
+export const SERVER_RAIL_MAX_WRITE_STATEMENTS = 11;
const idSchema = z.string().trim().min(1);
const idsSchema = z.array(idSchema);
-const reorderServersSchema = z.strictObject({
- kind: z.literal("reorder-servers"),
- serverIds: idsSchema,
-});
-const reorderFoldersSchema = z.strictObject({
- kind: z.literal("reorder-folders"),
- folderIds: idsSchema,
+export const serverRailEntrySchema = z.discriminatedUnion("kind", [
+ z.strictObject({ kind: z.literal("server"), id: idSchema }),
+ z.strictObject({ kind: z.literal("folder"), id: idSchema }),
+]);
+export type ServerRailEntry = z.infer<typeof serverRailEntrySchema>;
+const reorderTopLevelSchema = z.strictObject({
+ kind: z.literal("reorder-top-level"),
+ entries: z.array(serverRailEntrySchema),
});
+
const replaceFolderItemsSchema = z.strictObject({
kind: z.literal("replace-folder-items"),
folderId: idSchema,
@@ -35,8 +37,7 @@ const createFolderSchema = z.strictObject({
});
export const serverRailCommandSchema = z.discriminatedUnion("kind", [
- reorderServersSchema,
- reorderFoldersSchema,
+ reorderTopLevelSchema,
replaceFolderItemsSchema,
deleteFolderSchema,
createFolderSchema,
@@ -60,8 +61,9 @@ export type ServerRailFolderState = {
};
export type ServerRailState = {
- serverOrder: string[];
- folderOrder: string[];
+ topOrder?: ServerRailEntry[];
+ serverIds: string[];
+ folderIds: string[];
folders: Record<string, ServerRailFolderState>;
};
@@ -72,8 +74,7 @@ export type ServerRailProjection = {
movedServerIds: string[];
createdFolders: ServerRailFolderState[];
deletedFolderIds: string[];
- reorderServers: boolean;
- reorderFolders: boolean;
+ reorderTopLevel: boolean;
createdFolderIds: Record<string, string>;
};
@@ -83,8 +84,9 @@ export type ServerRailProjectionResult =
function cloneState(state: ServerRailState): ServerRailState {
return {
- serverOrder: [...state.serverOrder],
- folderOrder: [...state.folderOrder],
+ ...(state.topOrder ? { topOrder: state.topOrder.map((entry) => ({ ...entry })) } : {}),
+ serverIds: [...state.serverIds],
+ folderIds: [...state.folderIds],
folders: Object.fromEntries(
Object.entries(state.folders).map(([id, folder]) => [
id,
@@ -94,6 +96,33 @@ function cloneState(state: ServerRailState): ServerRailState {
};
}
+export function serverRailTopOrder(state: ServerRailState): ServerRailEntry[] {
+ const claimed = new Set(state.folderIds.flatMap((id) => state.folders[id]?.serverIds ?? []));
+ const entries: ServerRailEntry[] = [
+ ...state.serverIds.filter((id) => !claimed.has(id)).map((id) => ({ kind: "server" as const, id })),
+ ...state.folderIds.filter((id) => !!state.folders[id]?.serverIds.length).map((id) => ({ kind: "folder" as const, id })),
+ ];
+ const allowed = new Set(entries.map((entry) => `${entry.kind}:${entry.id}`));
+ const seen = new Set<string>();
+ return [...(state.topOrder ?? []), ...entries].filter((entry) => {
+ const key = `${entry.kind}:${entry.id}`;
+ if (!allowed.has(key) || seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+}
+
+export function serverRailServerIds(state: ServerRailState): string[] {
+ return serverRailTopOrder(state).flatMap((entry) =>
+ entry.kind === "server" ? [entry.id] : state.folders[entry.id]?.serverIds ?? [],
+ );
+}
+
+export function sortServerRailRows<T extends { id: string }>(state: ServerRailState, rows: T[]): T[] {
+ const ranks = new Map(serverRailServerIds(state).map((id, index) => [id, index]));
+ return rows.slice().sort((a, b) => (ranks.get(a.id) ?? Infinity) - (ranks.get(b.id) ?? Infinity));
+}
+
function hasDuplicates(values: readonly string[]): boolean {
return new Set(values).size !== values.length;
}
@@ -109,9 +138,9 @@ function sameSet(left: readonly string[], right: readonly string[]): boolean {
function parentByServer(state: ServerRailState): Map<string, string | null> {
const parents = new Map<string, string | null>(
- state.serverOrder.map((serverId) => [serverId, null]),
+ state.serverIds.map((serverId) => [serverId, null]),
);
- for (const folderId of state.folderOrder) {
+ for (const folderId of state.folderIds) {
for (const serverId of state.folders[folderId]?.serverIds ?? []) {
parents.set(serverId, folderId);
}
@@ -123,14 +152,14 @@ function validateFinalState(
state: ServerRailState,
options: { allowFolderOverflow?: boolean } = {},
): string | null {
- if (hasDuplicates(state.serverOrder)) return "serverIds must be unique";
- if (hasDuplicates(state.folderOrder)) return "folderIds must be unique";
- if (!options.allowFolderOverflow && state.folderOrder.length > MAX_SERVER_RAIL_FOLDERS) {
+ if (hasDuplicates(state.serverIds)) return "serverIds must be unique";
+ if (hasDuplicates(state.folderIds)) return "folderIds must be unique";
+ if (!options.allowFolderOverflow && state.folderIds.length > MAX_SERVER_RAIL_FOLDERS) {
return "folder limit reached";
}
- const membershipIds = new Set(state.serverOrder);
+ const membershipIds = new Set(state.serverIds);
const claimed = new Set<string>();
- for (const folderId of state.folderOrder) {
+ for (const folderId of state.folderIds) {
const folder = state.folders[folderId];
if (!folder) return `folder ${folderId} not found`;
if (folder.serverIds.length === 0) return `folder ${folderId} must not be empty`;
@@ -141,16 +170,17 @@ function validateFinalState(
claimed.add(serverId);
}
}
- if (Object.keys(state.folders).some((folderId) => !state.folderOrder.includes(folderId))) {
+ if (Object.keys(state.folders).some((folderId) => !state.folderIds.includes(folderId))) {
return "folder state contains unordered folders";
}
return null;
}
function sameState(left: ServerRailState, right: ServerRailState): boolean {
- if (!sameArray(left.serverOrder, right.serverOrder)) return false;
- if (!sameArray(left.folderOrder, right.folderOrder)) return false;
- return left.folderOrder.every((folderId) => {
+ if (!sameArray(serverRailTopOrder(left).map((entry) => `${entry.kind}:${entry.id}`), serverRailTopOrder(right).map((entry) => `${entry.kind}:${entry.id}`))) return false;
+ if (!sameSet(left.serverIds, right.serverIds)) return false;
+ if (!sameSet(left.folderIds, right.folderIds)) return false;
+ return left.folderIds.every((folderId) => {
const a = left.folders[folderId];
const b = right.folders[folderId];
return a?.name === b?.name && sameArray(a?.serverIds ?? [], b?.serverIds ?? []);
@@ -162,7 +192,7 @@ export function projectServerRailCommit(
request: ServerRailCommitRequest,
createFolderId: (clientId: string) => string,
): ServerRailProjectionResult {
- const recoveringFolderOverflow = snapshot.folderOrder.length > MAX_SERVER_RAIL_FOLDERS;
+ const recoveringFolderOverflow = snapshot.folderIds.length > MAX_SERVER_RAIL_FOLDERS;
const beforeError = validateFinalState(snapshot, {
allowFolderOverflow: recoveringFolderOverflow,
});
@@ -180,26 +210,14 @@ export function projectServerRailCommit(
const createdFolders: ServerRailFolderState[] = [];
const createdFolderIds: Record<string, string> = {};
const commandResources = new Set<string>();
- let reorderServers = false;
- let reorderFolders = false;
+ let requestedTopOrder: ServerRailEntry[] | undefined;
let existingFolderMutations = 0;
let createCount = 0;
for (const command of request.commands) {
- if (command.kind === "reorder-servers") {
- if (reorderServers) return { ok: false, error: "duplicate reorder-servers command", status: 400 };
- if (!sameSet(command.serverIds, snapshot.serverOrder)) {
- return { ok: false, error: "serverIds must match current memberships", status: 400 };
- }
- after.serverOrder = [...command.serverIds];
- reorderServers = true;
- continue;
- }
-
- if (command.kind === "reorder-folders") {
- if (reorderFolders) return { ok: false, error: "duplicate reorder-folders command", status: 400 };
- after.folderOrder = [...command.folderIds];
- reorderFolders = true;
+ if (command.kind === "reorder-top-level") {
+ if (requestedTopOrder) return { ok: false, error: "duplicate reorder-top-level command", status: 400 };
+ requestedTopOrder = command.entries;
continue;
}
@@ -214,7 +232,7 @@ export function projectServerRailCommit(
createdFolderIds[command.clientId] = id;
createdFolders.push(folder);
after.folders[id] = folder;
- after.folderOrder.push(id);
+ after.folderIds.push(id);
continue;
}
@@ -233,7 +251,7 @@ export function projectServerRailCommit(
affectedFolderIds.add(command.folderId);
if (command.kind === "delete-folder") {
delete after.folders[command.folderId];
- after.folderOrder = after.folderOrder.filter((id) => id !== command.folderId);
+ after.folderIds = after.folderIds.filter((id) => id !== command.folderId);
deletedFolderIds.add(command.folderId);
} else {
after.folders[command.folderId] = {
@@ -243,11 +261,18 @@ export function projectServerRailCommit(
}
}
- if (reorderFolders && !sameSet(after.folderOrder, Object.keys(after.folders))) {
- return { ok: false, error: "folderIds must match post-command folders", status: 400 };
+ if (requestedTopOrder) {
+ const entries = requestedTopOrder.map((entry) => entry.kind === "folder" ? { ...entry, id: createdFolderIds[entry.id] ?? entry.id } : entry);
+ const expected = serverRailTopOrder(after).map((entry) => `${entry.kind}:${entry.id}`);
+ if (!sameSet(entries.map((entry) => `${entry.kind}:${entry.id}`), expected)) {
+ return { ok: false, error: "top-level entries must match current servers and folders", status: 400 };
+ }
+ after.topOrder = entries;
+ } else {
+ after.topOrder = serverRailTopOrder(after);
}
-
- const folderCountImproved = after.folderOrder.length < snapshot.folderOrder.length;
+ const reorderTopLevel = !sameArray(serverRailTopOrder(snapshot).map((entry) => `${entry.kind}:${entry.id}`), serverRailTopOrder(after).map((entry) => `${entry.kind}:${entry.id}`));
+ const folderCountImproved = after.folderIds.length < snapshot.folderIds.length;
if (recoveringFolderOverflow && !folderCountImproved) {
return { ok: false, error: "folder limit recovery must reduce the folder count", status: 400 };
}
@@ -259,7 +284,7 @@ export function projectServerRailCommit(
const beforeParents = parentByServer(snapshot);
const afterParents = parentByServer(after);
- const movedServerIds = after.serverOrder.filter(
+ const movedServerIds = after.serverIds.filter(
(serverId) => beforeParents.get(serverId) !== afterParents.get(serverId),
);
@@ -272,8 +297,7 @@ export function projectServerRailCommit(
movedServerIds,
createdFolders,
deletedFolderIds: [...deletedFolderIds],
- reorderServers,
- reorderFolders,
+ reorderTopLevel,
createdFolderIds,
},
};
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index d03142a60..b75192cf4 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -148,6 +148,10 @@ const communityServerUpdateSchema = z.strictObject({
}),
})
+const communityServerRailChangedSchema = z.strictObject({
+ type: z.literal("community:server_rail.changed"),
+})
+
const communityServerDeleteSchema = z.strictObject({
type: z.literal("community:server.delete"),
serverId: string,
@@ -461,6 +465,7 @@ const commonCommunityEventSchemas = [
communityTypingStartSchema,
communityTypingStopSchema,
communityServerUpdateSchema,
+ communityServerRailChangedSchema,
communityServerDeleteSchema,
communityChannelDeleteSchema,
communityChannelReorderSchema,
@@ -563,6 +568,7 @@ export type CommunityTypingStart = Extract<CommunityWsEvent, { type: "community:
export type CommunityTypingStop = Extract<CommunityWsEvent, { type: "community:typing.stop" }>
export type CommunityChildChannelCreate = Extract<CommunityWsEvent, { type: "community:channel.child_create" }>
export type CommunityChildChannelUpdate = Extract<CommunityWsEvent, { type: "community:channel.child_update" }>
+export type CommunityServerRailChanged = Extract<CommunityWsEvent, { type: "community:server_rail.changed" }>
export type CommunityServerUpdate = Extract<CommunityWsEvent, { type: "community:server.update" }>
export type CommunityServerDelete = Extract<CommunityWsEvent, { type: "community:server.delete" }>
export type CommunityChannelCreate = Extract<CommunityWsEvent, { type: "community:channel.create" }>
@@ -636,6 +642,7 @@ export const WS_EVENTS = {
CHILD_CHANNEL_CREATE: "community:channel.child_create",
CHILD_CHANNEL_UPDATE: "community:channel.child_update",
SERVER_UPDATE: "community:server.update",
+ SERVER_RAIL_CHANGED: "community:server_rail.changed",
SERVER_DELETE: "community:server.delete",
CHANNEL_CREATE: "community:channel.create",
CHANNEL_UPDATE: "community:channel.update",
diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.ts
index 9524c718e..51a62c1f0 100644
--- a/src/shared/src/db/community-schema.ts
+++ b/src/shared/src/db/community-schema.ts
@@ -11,6 +11,7 @@ import {
} from "drizzle-orm/sqlite-core";
import { and, desc, eq, isNotNull, sql } from "drizzle-orm";
import { nanoid } from "nanoid";
+import type { ServerRailEntry } from "../community-server-rail";
import { user } from "./schema";
// ---------------------------------------------------------------------------
@@ -218,18 +219,21 @@ export const communityServerMember = sqliteTable(
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
role: text("role").default("member"),
- railOrder: integer("rail_order").default(0),
joinedAt: text("joined_at").notNull().$defaultFn(() => new Date().toISOString()),
},
(t) => [
unique("uq_server_member_server_user").on(t.serverId, t.userId),
index("idx_server_member_user").on(t.userId),
- index("idx_server_member_user_rail_order").on(t.userId, t.railOrder),
// Serves listMembersPaginated's WHERE server_id ORDER BY (joined_at, id).
index("idx_server_member_server_joined").on(t.serverId, t.joinedAt),
]
);
+export const communityServerRail = sqliteTable("community_server_rail", {
+ userId: text("user_id").primaryKey().references(() => user.id, { onDelete: "cascade" }),
+ entries: text("entries", { mode: "json" }).$type<ServerRailEntry[]>().notNull(),
+});
+
// 8. community_server_folder
export const communityServerFolder = sqliteTable(
"community_server_folder",
@@ -239,9 +243,8 @@ export const communityServerFolder = sqliteTable(
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
name: text("name").notNull(),
- position: integer("position").default(0),
},
- (t) => [index("idx_server_folder_user_position").on(t.userId, t.position)]
+ (t) => [index("idx_server_folder_user").on(t.userId)]
);
// 9. community_server_folder_item
diff --git a/src/shared/src/db/queries/community/attention.test.ts b/src/shared/src/db/queries/community/attention.test.ts
index 64fb9850b..b367c5432 100644
--- a/src/shared/src/db/queries/community/attention.test.ts
+++ b/src/shared/src/db/queries/community/attention.test.ts
@@ -47,6 +47,7 @@ beforeEach(() => {
otherUserAvatarVersion: 1,
lastMessageAt: "2026-09-27T00:00:00.000Z",
lastUnreadSeq: 4,
+ unreadCount: 2,
}])
mocks.listActionableIncomingRequests.mockResolvedValue([])
mocks.listUnreadMentionScopes.mockResolvedValue([])
@@ -69,6 +70,7 @@ describe("getAccountAttentionSnapshot", () => {
parentChannelId: null,
ordinaryUnread: true,
lastUnreadSeq: 4,
+ unreadCount: 2,
lastAttentionSeq: null,
attentionCount: 0,
}])
diff --git a/src/shared/src/db/queries/community/attention.ts b/src/shared/src/db/queries/community/attention.ts
index 1c6074ad6..c1418d3b9 100644
--- a/src/shared/src/db/queries/community/attention.ts
+++ b/src/shared/src/db/queries/community/attention.ts
@@ -67,6 +67,7 @@ export async function getAccountAttentionSnapshot(
parentChannelId: null,
ordinaryUnread: true,
lastUnreadSeq: row.lastUnreadSeq,
+ unreadCount: row.unreadCount,
lastAttentionSeq: null,
attentionCount: 0,
})
diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.ts
index 214993779..c4b196179 100644
--- a/src/shared/src/db/queries/community/channel.ts
+++ b/src/shared/src/db/queries/community/channel.ts
@@ -1,3 +1,5 @@
+import { readServerRailSnapshot } from "./server-rail";
+import { sortServerRailRows } from "../../../community-server-rail";
import { eq, and, asc, desc, isNotNull, isNull, inArray, count, ne, or, sql } from "drizzle-orm";
import type { SQLWrapper } from "drizzle-orm";
import {
@@ -15,6 +17,8 @@ import { canSeePrivateChannel, visibilityIsDmParticipant, ROLES } from "../../..
import { formatHandle } from "../../../lib/discriminator";
import { user } from "../../schema";
import { chunk, D1_MAX_IN_PARAMS, maxInParams, maxRowsPerInsert } from "../_chunk";
+import { jsonTextSet } from "../_json-set";
+import type { ChannelCategoryMove } from "../../../community-channel-order";
// Column selection shared by every read query.
const CHANNEL_COLUMNS = {
@@ -565,20 +569,28 @@ export async function listChildChannelsByParentMessageIds(
export async function reorderChannels(
db: Database,
- _serverId: string,
- channelIds: string[]
+ serverId: string,
+ channelIds: string[],
+ move?: ChannelCategoryMove,
) {
const statements = channelIds.map((id, index) =>
db
.update(communityChannel)
- .set({ position: index })
- .where(eq(communityChannel.id, id))
+ .set({ position: index, ...(move?.channelId === id ? { categoryId: move.categoryId } : {}) })
+ .where(and(eq(communityChannel.serverId, serverId), eq(communityChannel.id, id), isNull(communityChannel.parentChannelId)))
);
if (statements.length > 0) {
await db.batch(statements as [typeof statements[0], ...typeof statements]);
}
}
+export async function getServerRootChannelsByIds(db: Database, serverId: string, channelIds: string[]) {
+ return db.select(CHANNEL_COLUMNS).from(communityChannel).where(and(
+ eq(communityChannel.serverId, serverId), isNull(communityChannel.parentChannelId),
+ inArray(communityChannel.id, jsonTextSet(db, channelIds)),
+ ));
+}
+
export async function getChannelsByIds(db: Database, channelIds: string[]) {
if (channelIds.length === 0) return [];
// Hydration on the mentions/unreads paths passes up to a full page (200) of
@@ -1083,7 +1095,7 @@ export async function listChannelRefDirectoryForUser(db: Database, userId: strin
eq(communityServerMember.userId, userId)
)
)
- .orderBy(asc(communityServerMember.railOrder), asc(communityServer.id)),
+ .orderBy(asc(communityServerMember.joinedAt), asc(communityServer.id)),
db
.select({
serverId: communityChannel.serverId,
@@ -1120,7 +1132,6 @@ export async function listChannelRefDirectoryForUser(db: Database, userId: strin
)
)
.orderBy(
- asc(communityServerMember.railOrder),
asc(communityServerMember.serverId),
sql`${communityChannel.categoryId} IS NULL`,
asc(communityCategory.position),
@@ -1129,7 +1140,7 @@ export async function listChannelRefDirectoryForUser(db: Database, userId: strin
asc(communityChannel.id)
),
]);
- return groupChannelRefDirectoryRows(servers, channels);
+ return groupChannelRefDirectoryRows(sortServerRailRows(await readServerRailSnapshot(db, userId), servers), channels);
}
// Shared visibility computation for the nested-membership model. Assembles the
diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.ts
index 240aef664..1fcdeec29 100644
--- a/src/shared/src/db/queries/community/inbox.ts
+++ b/src/shared/src/db/queries/community/inbox.ts
@@ -1,4 +1,4 @@
-import { aliasedTable, and, eq, gt, isNotNull, isNull, inArray, ne, or, sql } from "drizzle-orm";
+import { aliasedTable, and, count, eq, gt, isNotNull, isNull, inArray, ne, or, sql } from "drizzle-orm";
import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";
import { jsonTextSet } from "../_json-set";
import {
@@ -541,6 +541,7 @@ export interface UnreadDmRow {
export interface EligibleUnreadDmRow extends UnreadDmRow {
lastUnreadSeq: number;
+ unreadCount: number;
}
/**
@@ -682,6 +683,7 @@ export async function listEligibleUnreadDms(
otherUserAvatarVersion: user.avatarVersion,
lastMessageAt: sql<string>`MAX(${communityMessage.createdAt})`,
lastUnreadSeq: sql<number>`MAX(${communityMessage.seq})`.mapWith(Number),
+ unreadCount: count(),
})
.from(communityMessage)
.innerJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))
diff --git a/src/shared/src/db/queries/community/invite.ts b/src/shared/src/db/queries/community/invite.ts
index 99343ce01..efc7befc3 100644
--- a/src/shared/src/db/queries/community/invite.ts
+++ b/src/shared/src/db/queries/community/invite.ts
@@ -130,7 +130,6 @@ export async function useInvite(
serverId: communityServerInvite.serverId,
userId: sql<string>`${userId}`.as("user_id"),
role: sql<string>`${"member"}`.as("role"),
- railOrder: sql<number>`0`.as("rail_order"),
joinedAt: sql<string>`${joinedAt}`.as("joined_at"),
})
.from(communityServerInvite)
diff --git a/src/shared/src/db/queries/community/server-folder.test.ts b/src/shared/src/db/queries/community/server-folder.test.ts
index ea29ef1b1..b831b48a1 100644
--- a/src/shared/src/db/queries/community/server-folder.test.ts
+++ b/src/shared/src/db/queries/community/server-folder.test.ts
@@ -1,35 +1,21 @@
-import { describe, expect, it, vi } from "vitest"
-import { listFolders } from "./server-folder"
+import { describe, expect, it, vi } from "vitest";
+const { readServerRailSnapshot } = vi.hoisted(() => ({ readServerRailSnapshot: vi.fn() }));
+vi.mock("./server-rail", () => ({ readServerRailSnapshot }));
+import { listFolders } from "./server-folder";
describe("listFolders", () => {
- it("keeps an unavailable server reference renderable", async () => {
- const folderChain: Record<string, ReturnType<typeof vi.fn>> = {}
- folderChain.from = vi.fn(() => folderChain)
- folderChain.where = vi.fn(() => folderChain)
- folderChain.orderBy = vi.fn().mockResolvedValue([{ id: "folder_1", name: "Saved", position: 0 }])
-
- const itemChain: Record<string, ReturnType<typeof vi.fn>> = {}
- itemChain.from = vi.fn(() => itemChain)
- itemChain.leftJoin = vi.fn(() => itemChain)
- itemChain.where = vi.fn(() => itemChain)
- itemChain.orderBy = vi.fn().mockResolvedValue([{
- serverId: "server_missing",
- position: 0,
- serverName: null,
- serverIcon: null,
- }])
-
- const db = {
- select: vi.fn()
- .mockReturnValueOnce(folderChain)
- .mockReturnValueOnce(itemChain),
- }
-
- await expect(listFolders(db as never, "user_1")).resolves.toEqual([{
- id: "folder_1",
- name: "Saved",
- position: 0,
- servers: [{ id: "server_missing", name: "Server unavailable", icon: null }],
- }])
- })
-})
+ it("uses canonical folder order and scoped live member data", async () => {
+ const topOrder = [{ kind: "folder", id: "second" }, { kind: "server", id: "a" }, { kind: "folder", id: "first" }];
+ readServerRailSnapshot.mockResolvedValue({
+ serverIds: ["a", "b", "c"], folderIds: ["first", "second"], topOrder,
+ folders: { first: { id: "first", name: "First", serverIds: ["b"] }, second: { id: "second", name: "Second", serverIds: ["c"] } },
+ });
+ const chain: any = { from: () => chain, innerJoin: async () => [{ id: "b", name: "B", icon: null }, { id: "c", name: "C", icon: "c.png" }] };
+ const db = { select: () => chain };
+ await expect(listFolders(db as never, "viewer")).resolves.toEqual({ topOrder, folders: [
+ { id: "second", name: "Second", servers: [{ id: "c", name: "C", icon: "c.png" }] },
+ { id: "first", name: "First", servers: [{ id: "b", name: "B", icon: null }] },
+ ] });
+ expect(readServerRailSnapshot).toHaveBeenCalledWith(db, "viewer");
+ });
+});
diff --git a/src/shared/src/db/queries/community/server-folder.ts b/src/shared/src/db/queries/community/server-folder.ts
index b31adb103..980eb773f 100644
--- a/src/shared/src/db/queries/community/server-folder.ts
+++ b/src/shared/src/db/queries/community/server-folder.ts
@@ -1,43 +1,22 @@
-import { eq, asc } from "drizzle-orm";
-import {
- communityServerFolder,
- communityServerFolderItem,
- communityServer,
-} from "../../community-schema";
+import { and, eq } from "drizzle-orm";
+import { communityServer, communityServerMember } from "../../community-schema";
import type { Database } from "../../index";
-export async function listFolders(db: Database, userId: string) {
- const folderRows = await db
- .select()
- .from(communityServerFolder)
- .where(eq(communityServerFolder.userId, userId))
- .orderBy(asc(communityServerFolder.position));
-
- const folders = await Promise.all(
- folderRows.map(async (folder) => {
- const items = await db
- .select({
- serverId: communityServerFolderItem.serverId,
- position: communityServerFolderItem.position,
- serverName: communityServer.name,
- serverIcon: communityServer.icon,
- })
- .from(communityServerFolderItem)
- .leftJoin(communityServer, eq(communityServerFolderItem.serverId, communityServer.id))
- .where(eq(communityServerFolderItem.folderId, folder.id))
- .orderBy(asc(communityServerFolderItem.position));
+import { serverRailTopOrder } from "../../../community-server-rail";
+import { readServerRailSnapshot } from "./server-rail";
- return {
- id: folder.id,
- name: folder.name,
- position: folder.position ?? 0,
- servers: items.map((item) => ({
- id: item.serverId,
- name: item.serverName ?? "Server unavailable",
- icon: item.serverIcon ?? null,
- })),
- };
- })
- );
-
- return folders;
+export async function listFolders(db: Database, userId: string) {
+ const [state, servers] = await Promise.all([
+ readServerRailSnapshot(db, userId),
+ db.select({ id: communityServer.id, name: communityServer.name, icon: communityServer.icon })
+ .from(communityServer)
+ .innerJoin(communityServerMember, and(eq(communityServerMember.serverId, communityServer.id), eq(communityServerMember.userId, userId))),
+ ]);
+ const byId = new Map(servers.map((server) => [server.id, server]));
+ const topOrder = serverRailTopOrder(state);
+ const folders = topOrder.flatMap((entry) => {
+ if (entry.kind !== "folder") return [];
+ const folder = state.folders[entry.id]!;
+ return [{ id: folder.id, name: folder.name, servers: folder.serverIds.flatMap((id) => byId.get(id) ? [byId.get(id)!] : []) }];
+ });
+ return { folders, topOrder };
}
diff --git a/src/shared/src/db/queries/community/server-rail.ts b/src/shared/src/db/queries/community/server-rail.ts
index 2423df06c..567c9279d 100644
--- a/src/shared/src/db/queries/community/server-rail.ts
+++ b/src/shared/src/db/queries/community/server-rail.ts
@@ -1,11 +1,13 @@
-import { and, asc, eq, sql } from "drizzle-orm";
+import { and, asc, eq, exists, lt, sql } from "drizzle-orm";
import { alias } from "drizzle-orm/sqlite-core";
import type { ServerRailProjection, ServerRailState } from "../../../community-server-rail";
import {
MAX_SERVER_RAIL_FOLDERS,
+ serverRailTopOrder,
SERVER_RAIL_MAX_WRITE_STATEMENTS,
} from "../../../community-server-rail";
import {
+ communityServerRail,
communityServerFolder,
communityServerFolderItem,
communityServerMember,
@@ -22,7 +24,6 @@ export async function readServerRailSnapshot(
.from(communityServerMember)
.where(eq(communityServerMember.userId, userId))
.orderBy(
- asc(communityServerMember.railOrder),
asc(communityServerMember.joinedAt),
asc(communityServerMember.serverId),
);
@@ -34,7 +35,6 @@ export async function readServerRailSnapshot(
.from(communityServerFolder)
.where(eq(communityServerFolder.userId, userId))
.orderBy(
- asc(sql`COALESCE(${communityServerFolder.position}, 0)`),
asc(communityServerFolder.id),
);
const items = db
@@ -56,20 +56,22 @@ export async function readServerRailSnapshot(
)
.where(eq(communityServerFolder.userId, userId))
.orderBy(
- asc(sql`COALESCE(${communityServerFolder.position}, 0)`),
asc(communityServerFolder.id),
asc(communityServerFolderItem.position),
asc(communityServerFolderItem.serverId),
);
- const [membershipRows, folderRows, itemRows] = await db.batch([
+ const rail = db.select({ entries: communityServerRail.entries }).from(communityServerRail).where(eq(communityServerRail.userId, userId));
+ const [membershipRows, folderRows, itemRows, railRows] = await db.batch([
memberships,
folders,
items,
+ rail,
] as any) as unknown as [
Array<{ serverId: string }>,
Array<{ id: string; name: string }>,
Array<{ folderId: string; serverId: string }>,
+ Array<{ entries: NonNullable<ServerRailState["topOrder"]> }>,
];
const claimedServerIds = new Set<string>();
@@ -81,8 +83,8 @@ export async function readServerRailSnapshot(
const projectedFolderIds = new Set(projectedItemRows.map((row) => row.folderId));
const projectedFolderRows = folderRows.filter((row) => projectedFolderIds.has(row.id));
const state: ServerRailState = {
- serverOrder: membershipRows.map((row) => row.serverId),
- folderOrder: projectedFolderRows.map((row) => row.id),
+ serverIds: membershipRows.map((row) => row.serverId),
+ folderIds: projectedFolderRows.map((row) => row.id),
folders: Object.fromEntries(projectedFolderRows.map((row) => [
row.id,
{ id: row.id, name: row.name, serverIds: [] },
@@ -91,6 +93,7 @@ export async function readServerRailSnapshot(
for (const item of projectedItemRows) {
state.folders[item.folderId]?.serverIds.push(item.serverId);
}
+ state.topOrder = serverRailTopOrder({ ...state, topOrder: railRows[0]?.entries ?? [] });
return state;
}
@@ -103,54 +106,6 @@ function idListCte(db: Database, alias: string, ids: readonly string[]) {
);
}
-function membershipReorderStatement(
- db: Database,
- userId: string,
- serverIds: readonly string[],
-) {
- const desired = idListCte(db, "desired_member_order", serverIds);
- return db.with(desired)
- .update(communityServerMember)
- .set({
- railOrder: sql<number>`(
- SELECT ${desired.position}
- FROM ${desired}
- WHERE ${desired.id} = ${communityServerMember.serverId}
- )`,
- })
- .where(and(
- eq(communityServerMember.userId, userId),
- sql`EXISTS (
- SELECT 1 FROM ${desired}
- WHERE ${desired.id} = ${communityServerMember.serverId}
- )`,
- ));
-}
-
-function folderReorderStatement(
- db: Database,
- userId: string,
- folderIds: readonly string[],
-) {
- const desired = idListCte(db, "desired_folder_order", folderIds);
- return db.with(desired)
- .update(communityServerFolder)
- .set({
- position: sql<number>`(
- SELECT ${desired.position}
- FROM ${desired}
- WHERE ${desired.id} = ${communityServerFolder.id}
- )`,
- })
- .where(and(
- eq(communityServerFolder.userId, userId),
- sql`EXISTS (
- SELECT 1 FROM ${desired}
- WHERE ${desired.id} = ${communityServerFolder.id}
- )`,
- ));
-}
-
function createFolderStatement(
db: Database,
userId: string,
@@ -160,11 +115,6 @@ function createFolderStatement(
id: sql<string>`${folder.id}`.as("id"),
userId: sql<string>`${userId}`.as("user_id"),
name: sql<string>`${folder.name}`.as("name"),
- position: sql<number>`(
- SELECT COALESCE(MAX(${communityServerFolder.position}), -1) + 1
- FROM ${communityServerFolder}
- WHERE ${communityServerFolder.userId} = ${userId}
- )`.as("position"),
}).from(sql`(SELECT 1)`)
.where(sql`(
SELECT COUNT(*)
@@ -261,25 +211,21 @@ function deleteDanglingFolderItemsStatement(db: Database, userId: string) {
}
function deleteDuplicateFolderItemsStatement(db: Database, userId: string) {
- return db.delete(communityServerFolderItem)
- .where(sql`EXISTS (
- SELECT 1
- FROM community_server_folder_item AS preferred_item
- INNER JOIN community_server_folder AS preferred_folder
- ON preferred_folder.id = preferred_item.folder_id
- INNER JOIN community_server_folder AS current_folder
- ON current_folder.id = ${communityServerFolderItem.folderId}
- WHERE preferred_item.server_id = ${communityServerFolderItem.serverId}
- AND preferred_folder.user_id = ${userId}
- AND current_folder.user_id = ${userId}
- AND (
- COALESCE(preferred_folder.position, 0) < COALESCE(current_folder.position, 0)
- OR (
- COALESCE(preferred_folder.position, 0) = COALESCE(current_folder.position, 0)
- AND preferred_folder.id < current_folder.id
- )
- )
- )`);
+ const preferredItem = alias(communityServerFolderItem, "preferred_item");
+ const preferredFolder = alias(communityServerFolder, "preferred_folder");
+ const currentFolder = alias(communityServerFolder, "current_folder");
+ return db.delete(communityServerFolderItem).where(exists(
+ db.select({ serverId: preferredItem.serverId })
+ .from(preferredItem)
+ .innerJoin(preferredFolder, eq(preferredFolder.id, preferredItem.folderId))
+ .innerJoin(currentFolder, eq(currentFolder.id, communityServerFolderItem.folderId))
+ .where(and(
+ eq(preferredItem.serverId, communityServerFolderItem.serverId),
+ eq(preferredFolder.userId, userId),
+ eq(currentFolder.userId, userId),
+ lt(preferredFolder.id, currentFolder.id),
+ )),
+ ));
}
function insertFolderItemsStatement(
@@ -316,31 +262,6 @@ function insertFolderItemsStatement(
return db.with(desired).insert(communityServerFolderItem).select(selected);
}
-function normalizeFolderPositionsStatement(db: Database, userId: string) {
- const ranked = db.$with("ranked_folders").as(
- db.select({
- id: communityServerFolder.id,
- position: sql<number>`ROW_NUMBER() OVER (
- ORDER BY COALESCE(${communityServerFolder.position}, 0), ${communityServerFolder.id}
- ) - 1`.as("position"),
- })
- .from(communityServerFolder)
- .where(eq(communityServerFolder.userId, userId)),
- );
- return db.with(ranked)
- .update(communityServerFolder)
- .set({
- position: sql<number>`(
- SELECT ${ranked.position} FROM ${ranked}
- WHERE ${ranked.id} = ${communityServerFolder.id}
- )`,
- })
- .where(and(
- eq(communityServerFolder.userId, userId),
- sql`EXISTS (SELECT 1 FROM ${ranked} WHERE ${ranked.id} = ${communityServerFolder.id})`,
- ));
-}
-
function normalizeFolderItemPositionsStatement(db: Database, userId: string) {
const ranked = db.$with("ranked_folder_items").as(
db.select({
@@ -399,6 +320,9 @@ export function buildServerRailWriteStatements(
...projection.movedServerIds,
...desiredItems.map((item) => item.serverId),
])];
+ if (projection.deletedFolderIds.length > 0) {
+ statements.push(deleteFoldersStatement(db, userId, projection.deletedFolderIds));
+ }
if (projection.createdFolders.length > 0) {
statements.push(createFolderStatement(db, userId, projection.createdFolders[0]!));
}
@@ -408,21 +332,15 @@ export function buildServerRailWriteStatements(
if (projection.affectedFolderIds.length > 0) {
statements.push(clearAffectedFolderItemsStatement(db, userId, projection.affectedFolderIds));
}
- if (projection.deletedFolderIds.length > 0) {
- statements.push(deleteFoldersStatement(db, userId, projection.deletedFolderIds));
- }
if (desiredItems.length > 0) {
statements.push(insertFolderItemsStatement(db, userId, desiredItems));
}
- if (projection.reorderServers) {
- statements.push(membershipReorderStatement(db, userId, projection.after.serverOrder));
- }
- if (projection.reorderFolders) {
- statements.push(folderReorderStatement(db, userId, projection.after.folderOrder));
+ if (projection.reorderTopLevel) {
+ const entries = serverRailTopOrder(projection.after);
+ statements.push(db.insert(communityServerRail).values({ userId, entries }).onConflictDoUpdate({ target: communityServerRail.userId, set: { entries } }));
}
statements.push(deleteEmptyFoldersStatement(db, userId));
- statements.push(normalizeFolderPositionsStatement(db, userId));
statements.push(normalizeFolderItemPositionsStatement(db, userId));
if (statements.length === 0 || statements.length > SERVER_RAIL_MAX_WRITE_STATEMENTS) {
throw new Error(`invalid server rail write statement count: ${statements.length}`);
diff --git a/src/shared/src/db/queries/community/server.ts b/src/shared/src/db/queries/community/server.ts
index d804537d7..1f4005718 100644
--- a/src/shared/src/db/queries/community/server.ts
+++ b/src/shared/src/db/queries/community/server.ts
@@ -18,6 +18,8 @@ import { withUniqueDiscriminator } from "../user";
import { parseNameAndTag } from "../../../lib/discriminator";
import { notificationEligibleSql } from "./notification-eligibility";
import { channelReadableSql } from "./channel";
+import { readServerRailSnapshot } from "./server-rail";
+import { sortServerRailRows } from "../../../community-server-rail";
export async function createServer(
db: Database,
@@ -91,7 +93,6 @@ export async function createServer(
serverId: id,
userId: data.ownerId,
role: "owner",
- railOrder: 0,
}).returning({
id: communityServerMember.id,
userId: communityServerMember.userId,
@@ -231,7 +232,7 @@ export async function listUserServers(db: Database, userId: string) {
.groupBy(communityChannel.serverId)
.as("mention_counts");
- return db
+ const rows = await db
.select({
id: communityServer.id,
name: communityServer.name,
@@ -243,7 +244,6 @@ export async function listUserServers(db: Database, userId: string) {
createdAt: communityServer.createdAt,
role: communityServerMember.role,
memberId: communityServerMember.id,
- railOrder: communityServerMember.railOrder,
// COALESCE has no ORM operator in this Drizzle version — the LEFT JOIN
// yields NULL for servers with zero unread mentions. Wrap the aggregate
// column with a narrow `sql` cast so the client always receives a
@@ -259,7 +259,8 @@ export async function listUserServers(db: Database, userId: string) {
)
)
.leftJoin(mentionCounts, eq(mentionCounts.serverId, communityServer.id))
- .orderBy(asc(communityServerMember.railOrder));
+ .orderBy(asc(communityServerMember.joinedAt), asc(communityServer.id));
+ return sortServerRailRows(await readServerRailSnapshot(db, userId), rows);
}
/**
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 2b6f4637c..67a2583de 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -604,6 +604,7 @@ export type {
CommunityChildChannelCreate,
CommunityChildChannelUpdate,
CommunityServerUpdate,
+ CommunityServerRailChanged,
CommunityServerDelete,
CommunityChannelCreate,
CommunityChannelUpdate,
@@ -712,11 +713,16 @@ export {
MAX_SERVER_RAIL_REQUEST_BYTES,
SERVER_RAIL_SNAPSHOT_STATEMENTS,
SERVER_RAIL_MAX_WRITE_STATEMENTS,
+ serverRailEntrySchema,
+ serverRailTopOrder,
+ serverRailServerIds,
+ sortServerRailRows,
serverRailCommandSchema,
serverRailCommitRequestSchema,
projectServerRailCommit,
} from "./community-server-rail";
export type {
+ ServerRailEntry,
ServerRailCommand,
ServerRailCommitRequest,
ServerRailCommitResponse,
@@ -729,7 +735,7 @@ export * as schema from "./db/schema";
export * as queries from "./db/queries-index";
export { BotCreationError, resolveBotCreationConfiguration, BotCreationProposalSchema, BotCreationSubmitSchema, BotCreationPayloadSchema, BotCreationDecisionSchema, BOT_CREATION_MAX_ITEMS, BOT_CREATION_BODY_MAX_BYTES } from "./community-bot-creation";
export type { BotCreationProposal, BotCreationSubmit, BotCreationItem, BotCreationPayload } from "./community-bot-creation";
-export { communityServer, communityServerInvite, communityFriendship, communityServerMember, communityServerFolder, communityServerFolderItem, communityBotActivityEvent, communityBotDailyActivity, communityPushDevice } from "./db/community-schema";
+export { communityServer, communityServerInvite, communityFriendship, communityServerMember, communityServerRail, communityServerFolder, communityServerFolderItem, communityBotActivityEvent, communityBotDailyActivity, communityPushDevice } from "./db/community-schema";
// Logger
export { Logger, createLogger } from "./logger"
@@ -831,5 +837,6 @@ export * from "./community-resources";
export * from "./runtime-models-contract";
export { readBoundedJsonRequest } from "./http-json";
+export { channelReorderRequestSchema, type ChannelReorderRequest, type ChannelCategoryMove } from "./community-channel-order";
export type { PlatformMachineRequest, PlatformBotRequest } from "./community-platform";
diff --git a/src/shared/test/community-ws-bundle.contract.test.ts b/src/shared/test/community-ws-bundle.contract.test.ts
index 4115e322e..a86d98cf8 100644
--- a/src/shared/test/community-ws-bundle.contract.test.ts
+++ b/src/shared/test/community-ws-bundle.contract.test.ts
@@ -145,7 +145,7 @@ describe("community WS batch transport contract", () => {
expect(isCommunityDeliveryDigest("a".repeat(63))).toBe(false)
})
- it("round-trips one strict outer frame without entering the 47-event union", async () => {
+ it("round-trips one strict outer frame without entering the 48-event union", async () => {
const operationId = await deriveCommunityDeliveryOperationId("message-1")
const prepared = await prepareCommunityDeliveryEvents(children)
expect(prepared.ok).toBe(true)
@@ -173,7 +173,7 @@ describe("community WS batch transport contract", () => {
})
expect(isCommunityBrowserEventBatchCandidate(encoded.batch)).toBe(true)
expect(Object.values(WS_EVENTS)).not.toContain(COMMUNITY_BROWSER_EVENT_BATCH_TYPE)
- expect(Object.values(WS_EVENTS)).toHaveLength(47)
+ expect(Object.values(WS_EVENTS)).toHaveLength(48)
})
it("rejects invalid count, child, operation metadata, digest mismatch, and strict outer keys", async () => {
diff --git a/src/shared/test/community-ws-events.contract.test.ts b/src/shared/test/community-ws-events.contract.test.ts
index 3b38cdd1f..a10ff6c69 100644
--- a/src/shared/test/community-ws-events.contract.test.ts
+++ b/src/shared/test/community-ws-events.contract.test.ts
@@ -65,13 +65,13 @@ describe("Community browser event runtime contract", () => {
const fixtures = Object.values(communityWsEventFixtures)
const names = Object.values(WS_EVENTS).sort()
- it("locks the exact 47-event inventory", () => {
- expect(names).toHaveLength(47)
+ it("locks the exact 48-event inventory", () => {
+ expect(names).toHaveLength(48)
expect(Object.keys(communityWsEventFixtures).sort()).toEqual(names)
expect(Object.keys(requiredFixturePaths).sort()).toEqual(names)
})
- it("decodes and canonically encodes all 47 current event fixtures", () => {
+ it("decodes and canonically encodes all 48 current event fixtures", () => {
for (const fixture of fixtures) {
expect(decodeCommunityBrowserEvent(fixture)).toEqual({ ok: true, event: fixture })
const encoded = encodeCommunityBrowserEvent(fixture)
@@ -93,9 +93,10 @@ describe("Community browser event runtime contract", () => {
expect(decodeCommunityBrowserEvent(event)).toEqual({ ok: true, event })
})
- it("rejects one required-field corruption for every event", () => {
+ it("rejects missing fields or extra payload on every event", () => {
for (const fixture of fixtures) {
- const corrupted = withoutPath(fixture, requiredFixturePaths[fixture.type])
+ const path = requiredFixturePaths[fixture.type]
+ const corrupted = path.length ? withoutPath(fixture, path) : { ...fixture, entries: [] }
expect(decodeCommunityBrowserEvent(corrupted)).toMatchObject({
ok: false,
reason: "invalid-payload",
@@ -273,3 +274,11 @@ describe("explicit v3 browser events", () => {
expect(encodeCommunityBrowserEvent({ ...communityResourceMessageFixture, message: { ...communityResourceMessageFixture.message, content: "😀".repeat(COMMUNITY_BROWSER_EVENT_MAX_BYTES) } }, 3).ok).toBe(false)
})
})
+
+it("server rail hints carry no order or account payload in either contract", () => {
+ for (const contract of [2, 3] as const) {
+ const hint = { type: "community:server_rail.changed" };
+ expect(decodeCommunityBrowserEvent(hint, contract)).toMatchObject({ ok: true, event: hint });
+ for (const extra of [{ entries: [] }, { userId: "other" }]) expect(decodeCommunityBrowserEvent({ ...hint, ...extra }, contract)).toMatchObject({ ok: false, reason: "invalid-payload" });
+ }
+});
diff --git a/src/shared/test/community-ws-events.fixtures.ts b/src/shared/test/community-ws-events.fixtures.ts
index a2afea1e0..5660fbdfd 100644
--- a/src/shared/test/community-ws-events.fixtures.ts
+++ b/src/shared/test/community-ws-events.fixtures.ts
@@ -108,6 +108,7 @@ export const communityWsEventFixtures = {
channelId: "thread-1",
changes: { name: "Renamed" },
},
+ "community:server_rail.changed": { type: "community:server_rail.changed" },
"community:server.update": {
type: "community:server.update",
serverId: "server-1",
@@ -308,6 +309,7 @@ export const requiredFixturePaths = {
"community:channel.child_create": ["channel"],
"community:channel.child_update": ["changes"],
"community:server.update": ["changes"],
+ "community:server_rail.changed": [],
"community:server.delete": ["serverId"],
"community:channel.create": ["channel"],
"community:channel.update": ["changes"],
diff --git a/src/shared/test/community-ws-events.test.ts b/src/shared/test/community-ws-events.test.ts
index 7be4b94c5..f29ff6bfb 100644
--- a/src/shared/test/community-ws-events.test.ts
+++ b/src/shared/test/community-ws-events.test.ts
@@ -64,7 +64,7 @@ describe("CommunityMessageEdited address contract", () => {
describe("isCommunityEvent", () => {
it("accepts every exact event declared by WS_EVENTS", () => {
- expect(Object.values(WS_EVENTS)).toHaveLength(47);
+ expect(Object.values(WS_EVENTS)).toHaveLength(48);
for (const type of Object.values(WS_EVENTS)) {
expect(isCommunityEvent({ type })).toBe(true);
}
diff --git a/src/shared/test/queries/community-channel-directory.test.ts b/src/shared/test/queries/community-channel-directory.test.ts
index fcf3f7f46..d9231a2f2 100644
--- a/src/shared/test/queries/community-channel-directory.test.ts
+++ b/src/shared/test/queries/community-channel-directory.test.ts
@@ -61,8 +61,12 @@ describe("listChannelRefDirectoryForUser", () => {
id TEXT PRIMARY KEY,
server_id TEXT NOT NULL,
user_id TEXT NOT NULL,
- rail_order INTEGER
+ joined_at TEXT DEFAULT '2026-01-01'
);
+ CREATE TABLE community_server_rail (user_id TEXT PRIMARY KEY, entries TEXT NOT NULL);
+ CREATE TABLE community_server_folder (id TEXT PRIMARY KEY, user_id TEXT, name TEXT);
+ CREATE TABLE community_server_folder_item (folder_id TEXT, server_id TEXT, position INTEGER);
+ INSERT INTO community_server_rail VALUES ('viewer', '[{"kind":"server","id":"s2"},{"kind":"server","id":"s1"}]');
CREATE TABLE community_category (
id TEXT PRIMARY KEY,
server_id TEXT NOT NULL,
@@ -90,10 +94,10 @@ describe("listChannelRefDirectoryForUser", () => {
('s1', 'First', '0001'),
('s2', 'Second', '0002'),
('s3', 'Not joined', '0003');
- INSERT INTO community_server_member (id, server_id, user_id, rail_order) VALUES
- ('sm2', 's2', 'viewer', 0),
- ('sm1', 's1', 'viewer', 1),
- ('sm3', 's3', 'someone_else', 0);
+ INSERT INTO community_server_member (id, server_id, user_id) VALUES
+ ('sm2', 's2', 'viewer'),
+ ('sm1', 's1', 'viewer'),
+ ('sm3', 's3', 'someone_else');
INSERT INTO community_category (id, server_id, position, private) VALUES
('public', 's1', 0, 0),
('private', 's1', 1, 1),
@@ -116,6 +120,7 @@ describe("listChannelRefDirectoryForUser", () => {
('cm_dm', 'dm', 'viewer', 'access');
`);
db = drizzle(sqlite) as unknown as Database;
+ (db as any).batch = async (statements: any[]) => statements.map((statement) => statement.all());
});
afterEach(() => sqlite.close());
diff --git a/src/shared/test/queries/community-channel-order.test.ts b/src/shared/test/queries/community-channel-order.test.ts
new file mode 100644
index 000000000..aebf2fcde
--- /dev/null
+++ b/src/shared/test/queries/community-channel-order.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest";
+import { communityWriteDb } from "../helpers/community-write-db";
+import { getServerRootChannelsByIds, reorderChannels } from "../../src/db/queries/community/channel";
+import { channelReorderRequestSchema } from "../../src/community-channel-order";
+
+function fixture() {
+ const f = communityWriteDb();
+ f.sqlite.exec(`
+ INSERT INTO community_category (id, private) VALUES ('a',1),('b',1);
+ INSERT INTO community_channel (id,server_id,category_id,name,position,created_at) VALUES
+ ('c1','s1','a','one',0,'now'),('c2','s1','b','two',1,'now'),('c3','s1','b','three',2,'now'),('foreign','s2',NULL,'foreign',7,'now');
+ INSERT INTO community_channel (id,server_id,name,type,parent_channel_id,position,created_at) VALUES ('child','s1','child','thread','c1',9,'now');
+ INSERT INTO community_channel_member (id,channel_id,user_id,added_at) VALUES ('roster','c1','peer','now');
+ `);
+ return f;
+}
+const order = (sqlite: ReturnType<typeof fixture>["sqlite"]) => sqlite.prepare("SELECT id,server_id,category_id,position FROM community_channel ORDER BY id").all();
+
+describe("atomic server channel order", () => {
+ it("updates the category and exact positions in one transaction, preserving private membership", async () => {
+ const { sqlite, db, batchSizes } = fixture();
+ try {
+ const members = sqlite.prepare("SELECT * FROM community_channel_member").all();
+ await reorderChannels(db, "s1", ["c2", "c1", "c3"], { channelId: "c1", categoryId: "b" });
+ expect(sqlite.prepare("SELECT id,category_id FROM community_channel WHERE server_id='s1' AND parent_channel_id IS NULL ORDER BY position").all()).toEqual([
+ { id: "c2", category_id: "b" }, { id: "c1", category_id: "b" }, { id: "c3", category_id: "b" },
+ ]);
+ expect(batchSizes).toHaveLength(1);
+ expect(batchSizes[0]).toHaveLength(3);
+ expect(sqlite.prepare("SELECT * FROM community_channel_member").all()).toEqual(members);
+ } finally { sqlite.close(); }
+ });
+ it("restores all fields when a later order statement aborts", async () => {
+ const { sqlite, db, batchSizes } = fixture();
+ try {
+ const before = order(sqlite);
+ sqlite.exec("CREATE TRIGGER reject_order BEFORE UPDATE OF position ON community_channel WHEN OLD.id='c3' BEGIN SELECT RAISE(ABORT,'order rejected'); END;");
+ await expect(reorderChannels(db, "s1", ["c2", "c1", "c3"], { channelId: "c1", categoryId: "b" })).rejects.toThrow("order rejected");
+ expect(order(sqlite)).toEqual(before);
+ expect(batchSizes).toHaveLength(1);
+ } finally { sqlite.close(); }
+ });
+ it("scopes reads and writes to server roots, including more than100 requested identities", async () => {
+ const { sqlite, db } = fixture();
+ try {
+ const insert = sqlite.prepare("INSERT INTO community_channel(id,server_id,name,created_at) VALUES (?,'s1',?,'now')");
+ const ids = Array.from({ length: 125 }, (_, i) => `root-${i}`);
+ for (const id of ids) insert.run(id, id);
+ const actual = await getServerRootChannelsByIds(db, "s1", [...ids, "c1", "foreign", "child", "missing"]);
+ expect(actual.map((channel) => channel.id).sort()).toEqual([...ids, "c1"].sort());
+ await reorderChannels(db, "s1", ["foreign", "c1", "child"]);
+ expect(sqlite.prepare("SELECT position FROM community_channel WHERE id='foreign'").get()).toEqual({ position: 7 });
+ expect(sqlite.prepare("SELECT position FROM community_channel WHERE id='child'").get()).toEqual({ position: 9 });
+ expect(sqlite.prepare("SELECT position FROM community_channel WHERE id='c1'").get()).toEqual({ position: 1 });
+ } finally { sqlite.close(); }
+ });
+ it("does no batch for an empty internal request", async () => {
+ const { sqlite, db, batchSizes } = fixture();
+ try {
+ await reorderChannels(db, "s1", []);
+ expect(await getServerRootChannelsByIds(db, "s1", [])).toEqual([]);
+ expect(batchSizes).toEqual([]);
+ } finally { sqlite.close(); }
+ });
+});
+
+it("validates one optional included category move without changing the existing reorder shape", () => {
+ expect(channelReorderRequestSchema.parse({ channelIds: ["a"] })).toEqual({ channelIds: ["a"] });
+ expect(channelReorderRequestSchema.parse({ channelIds: ["a"], move: { channelId: "a", categoryId: null } }).move).toEqual({ channelId: "a", categoryId: null });
+ for (const request of [{ channelIds: ["a","a"] }, { channelIds: [""] }, { channelIds: [] }, { channelIds: ["a"], move: { channelId: "b", categoryId: "c" } }, { channelIds: ["a"], move: { channelId: "a", categoryId: "c", other: true } }]) {
+ expect(channelReorderRequestSchema.safeParse(request).success).toBe(false);
+ }
+});
diff --git a/src/shared/test/queries/community-dm-unread-count-sqlite.test.ts b/src/shared/test/queries/community-dm-unread-count-sqlite.test.ts
new file mode 100644
index 000000000..75c7957a0
--- /dev/null
+++ b/src/shared/test/queries/community-dm-unread-count-sqlite.test.ts
@@ -0,0 +1,42 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest"
+import { communityWriteDb } from "../helpers/community-write-db"
+import { createMessage } from "../../src/db/queries/community/message"
+import { listEligibleUnreadDms } from "../../src/db/queries/community/inbox"
+import { markReadToMessageBuilder } from "../../src/db/queries/community/read-state"
+
+describe("DM unread counts against real SQLite", () => {
+ let fixture: ReturnType<typeof communityWriteDb>
+ beforeEach(() => {
+ fixture = communityWriteDb()
+ fixture.sqlite.exec(`
+ ALTER TABLE user ADD COLUMN name TEXT NOT NULL DEFAULT 'Peer';
+ ALTER TABLE user ADD COLUMN discriminator TEXT NOT NULL DEFAULT '0042';
+ ALTER TABLE user ADD COLUMN image TEXT;
+ ALTER TABLE user ADD COLUMN avatarVersion INTEGER NOT NULL DEFAULT 0;
+ CREATE TABLE community_notification_setting (user_id TEXT, server_id TEXT, channel_id TEXT, level TEXT);
+ UPDATE community_channel SET type = 'dm' WHERE id = 'channel';
+ INSERT INTO community_channel_member VALUES
+ ('viewer', 'channel', 'author', 'access', 'added', NULL, 'now'),
+ ('peer', 'channel', 'peer', 'access', 'added', NULL, 'now');
+ `)
+ })
+ afterEach(() => fixture.sqlite.close())
+
+ it("counts existing unread messages across seq holes and shrinks with the read cursor", async () => {
+ const sent = []
+ for (let index = 0; index < 3; index++) {
+ sent.push((await createMessage(fixture.db, { channelId: "channel", authorId: "peer", authorKind: "human", content: `message ${index}` }))!)
+ }
+ fixture.sqlite.prepare("DELETE FROM community_message WHERE seq = 2").run()
+ await expect(listEligibleUnreadDms(fixture.db, "author")).resolves.toEqual([
+ expect.objectContaining({ channelId: "channel", lastUnreadSeq: 3, unreadCount: 2 }),
+ ])
+ ;(markReadToMessageBuilder(fixture.db, { userId: "author", channelId: "channel", message: sent[0]! }) as any).run()
+ await expect(listEligibleUnreadDms(fixture.db, "author")).resolves.toEqual([
+ expect.objectContaining({ lastUnreadSeq: 3, unreadCount: 1 }),
+ ])
+ ;(markReadToMessageBuilder(fixture.db, { userId: "author", channelId: "channel", message: sent[2]! }) as any).run()
+ await expect(listEligibleUnreadDms(fixture.db, "author")).resolves.toEqual([])
+ await expect(listEligibleUnreadDms(fixture.db, "outsider")).resolves.toEqual([])
+ })
+})
diff --git a/src/shared/test/queries/community-member-rail-cleanup.test.ts b/src/shared/test/queries/community-member-rail-cleanup.test.ts
index 521f43d00..c9d2d6a43 100644
--- a/src/shared/test/queries/community-member-rail-cleanup.test.ts
+++ b/src/shared/test/queries/community-member-rail-cleanup.test.ts
@@ -13,6 +13,7 @@ function createDatabase() {
sqlite.exec(`
PRAGMA foreign_keys = ON;
CREATE TABLE community_server (id TEXT PRIMARY KEY);
+ CREATE TABLE community_server_rail (user_id TEXT PRIMARY KEY, entries TEXT NOT NULL);
CREATE TABLE community_server_member (
id TEXT PRIMARY KEY,
server_id TEXT NOT NULL REFERENCES community_server(id) ON DELETE CASCADE,
@@ -126,7 +127,7 @@ describe("member removal server rail cleanup", () => {
db.batch = async (statements: any[]) => statements.map((statement) => statement.all());
const snapshot = await readServerRailSnapshot(db, "target");
- expect(snapshot).toEqual({ serverOrder: ["keep"], folderOrder: [], folders: {} });
+ expect(snapshot).toEqual({ serverIds: ["keep"], folderIds: [], folders: {}, topOrder: [{ kind: "server", id: "keep" }] });
const next = projectServerRailCommit(snapshot, {
commands: [{
kind: "create-folder",
diff --git a/src/shared/test/queries/community-notification-cursor-clear.test.ts b/src/shared/test/queries/community-notification-cursor-clear.test.ts
index f31e681fb..e9a761f3c 100644
--- a/src/shared/test/queries/community-notification-cursor-clear.test.ts
+++ b/src/shared/test/queries/community-notification-cursor-clear.test.ts
@@ -108,6 +108,9 @@ describe("notification setting read-state isolation contract", () => {
relation TEXT NOT NULL,
added_at TEXT NOT NULL
);
+ CREATE TABLE community_server_rail (user_id TEXT PRIMARY KEY, entries TEXT NOT NULL);
+ CREATE TABLE community_server_folder (id TEXT PRIMARY KEY, user_id TEXT, name TEXT);
+ CREATE TABLE community_server_folder_item (folder_id TEXT, server_id TEXT, position INTEGER);
CREATE TABLE community_server_member (
id TEXT PRIMARY KEY,
server_id TEXT NOT NULL,
diff --git a/src/shared/test/queries/community-server-rail-migration.test.ts b/src/shared/test/queries/community-server-rail-migration.test.ts
new file mode 100644
index 000000000..eabdbf9ea
--- /dev/null
+++ b/src/shared/test/queries/community-server-rail-migration.test.ts
@@ -0,0 +1,61 @@
+import { readFileSync } from "node:fs";
+import Sqlite from "better-sqlite3";
+import { expect, it } from "vitest";
+import { getTableConfig } from "drizzle-orm/sqlite-core";
+import { communityServerRail, communityServerMember, communityServerFolder } from "../../src/db/community-schema";
+
+it("migrates legacy order without replacing mixed order or folder contents", () => {
+ const db = new Sqlite(":memory:");
+ try {
+ db.exec(`
+ PRAGMA foreign_keys = ON;
+ CREATE TABLE user (id TEXT PRIMARY KEY);
+ CREATE TABLE community_server (id TEXT PRIMARY KEY);
+ CREATE TABLE community_server_member (id TEXT PRIMARY KEY, user_id TEXT REFERENCES user(id), server_id TEXT REFERENCES community_server(id), rail_order INTEGER, joined_at TEXT);
+ CREATE INDEX idx_server_member_user_rail_order ON community_server_member(user_id, rail_order);
+ CREATE TABLE community_server_folder (id TEXT PRIMARY KEY, user_id TEXT REFERENCES user(id), name TEXT, position INTEGER);
+ CREATE INDEX idx_server_folder_user_position ON community_server_folder(user_id, position);
+ CREATE TABLE community_server_folder_item (folder_id TEXT REFERENCES community_server_folder(id), server_id TEXT REFERENCES community_server(id), position INTEGER);
+ ${readFileSync(new URL("../../../web/migrations/0108_community_server_rail_order.sql", import.meta.url), "utf8")}
+ INSERT INTO user VALUES ('legacy'), ('mixed');
+ INSERT INTO community_server VALUES ('a'), ('b'), ('c'), ('d'), ('foreign');
+ INSERT INTO community_server_member VALUES
+ ('la','legacy','a',2,'2026-01-01'), ('lb','legacy','b',1,'2026-01-01'),
+ ('lc','legacy','c',0,'2026-01-01'), ('ld','legacy','d',0,'2026-01-01'),
+ ('ma','mixed','a',0,'2026-01-01'), ('mb','mixed','b',1,'2026-01-01');
+ INSERT INTO community_server_folder VALUES
+ ('later','legacy','Later',8), ('first','legacy','First',2),
+ ('empty','legacy','Empty',0), ('stale','legacy','Stale',0), ('mf','mixed','Mixed',0);
+ INSERT INTO community_server_folder_item VALUES ('later','c',6), ('first','d',3), ('stale','foreign',0), ('mf','b',0);
+ INSERT INTO community_server_rail VALUES ('mixed','[{"kind":"folder","id":"mf"},{"kind":"server","id":"a"}]');
+ `);
+ const items = db.prepare("SELECT * FROM community_server_folder_item").all();
+ const mixed = db.prepare("SELECT entries FROM community_server_rail WHERE user_id='mixed'").get();
+ db.exec(readFileSync(new URL("../../../web/migrations/0109_server_rail_single_order.sql", import.meta.url), "utf8"));
+ expect(JSON.parse((db.prepare("SELECT entries FROM community_server_rail WHERE user_id='legacy'").get() as { entries: string }).entries)).toEqual([
+ { kind: "server", id: "b" }, { kind: "server", id: "a" },
+ { kind: "folder", id: "first" }, { kind: "folder", id: "later" },
+ ]);
+ expect(db.prepare("SELECT entries FROM community_server_rail WHERE user_id='mixed'").get()).toEqual(mixed);
+ expect(db.prepare("SELECT * FROM community_server_folder_item").all()).toEqual(items);
+ expect(db.prepare("SELECT COUNT(*) AS count FROM community_server_member").get()).toEqual({ count: 6 });
+ expect(db.prepare("PRAGMA table_info(community_server_member)").all()).not.toEqual(expect.arrayContaining([expect.objectContaining({ name: "rail_order" })]));
+ expect(db.prepare("PRAGMA table_info(community_server_folder)").all()).not.toEqual(expect.arrayContaining([expect.objectContaining({ name: "position" })]));
+ expect(db.prepare("PRAGMA foreign_key_check").all()).toEqual([]);
+ db.exec("INSERT INTO user VALUES ('cascade-only'); INSERT INTO community_server_rail VALUES ('cascade-only', '[]'); DELETE FROM user WHERE id='cascade-only';");
+ expect(db.prepare("SELECT * FROM community_server_rail WHERE user_id='cascade-only'").get()).toBeUndefined();
+ expect(() => db.prepare("INSERT INTO community_server_rail VALUES ('missing-owner', '[]')").run()).toThrow();
+ } finally { db.close(); }
+});
+
+it("declares one account-owned order without legacy top-level columns", () => {
+ const rail = getTableConfig(communityServerRail);
+ expect(rail.columns.map((column) => column.name)).toEqual(["user_id", "entries"]);
+ const owner = rail.foreignKeys[0]!;
+ expect(owner.reference()).toMatchObject({ columns: [{ name: "user_id" }], foreignColumns: [{ name: "id" }] });
+ expect(owner.onDelete).toBe("cascade");
+ expect(getTableConfig(communityServerMember).columns.map((column) => column.name)).not.toContain("rail_order");
+ const folder = getTableConfig(communityServerFolder);
+ expect(folder.columns.map((column) => column.name)).not.toContain("position");
+ expect(folder.indexes.map((index) => index.config.name)).toContain("idx_server_folder_user");
+});
diff --git a/src/shared/test/queries/community-server-rail.test.ts b/src/shared/test/queries/community-server-rail.test.ts
index aed24b4e5..ea54f24d7 100644
--- a/src/shared/test/queries/community-server-rail.test.ts
+++ b/src/shared/test/queries/community-server-rail.test.ts
@@ -3,6 +3,7 @@ import { drizzle } from "drizzle-orm/better-sqlite3";
import { describe, expect, it } from "vitest";
import {
projectServerRailCommit,
+ serverRailTopOrder,
type ServerRailCommitRequest,
type ServerRailState,
} from "../../src/community-server-rail";
@@ -15,6 +16,7 @@ function createDatabase() {
const sqlite = new Sqlite(":memory:");
sqlite.exec(`
PRAGMA foreign_keys = ON;
+ CREATE TABLE community_server_rail (user_id TEXT PRIMARY KEY, entries TEXT NOT NULL);
CREATE TABLE community_server (
id TEXT PRIMARY KEY
);
@@ -23,7 +25,6 @@ function createDatabase() {
server_id TEXT NOT NULL REFERENCES community_server(id) ON DELETE CASCADE,
user_id TEXT NOT NULL,
role TEXT DEFAULT 'member',
- rail_order INTEGER DEFAULT 0,
joined_at TEXT NOT NULL
);
CREATE UNIQUE INDEX uq_server_member_server_user
@@ -31,8 +32,7 @@ function createDatabase() {
CREATE TABLE community_server_folder (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
- name TEXT NOT NULL,
- position INTEGER DEFAULT 0
+ name TEXT NOT NULL
);
CREATE TABLE community_server_folder_item (
folder_id TEXT NOT NULL REFERENCES community_server_folder(id) ON DELETE CASCADE,
@@ -64,21 +64,22 @@ function runProjection(
function seedMemberships(sqlite: Sqlite.Database, ids: string[]) {
const server = sqlite.prepare("INSERT INTO community_server (id) VALUES (?)");
const member = sqlite.prepare(`
- INSERT INTO community_server_member (id, server_id, user_id, rail_order, joined_at)
- VALUES (?, ?, 'u1', ?, ?)
+ INSERT INTO community_server_member (id, server_id, user_id, joined_at)
+ VALUES (?, ?, 'u1', ?)
`);
ids.forEach((id, index) => {
server.run(id);
- member.run(`member-${id}`, id, index, `2026-01-01T00:00:${String(index).padStart(2, "0")}.000Z`);
+ member.run(`member-${id}`, id, `2026-01-01T00:00:${String(index).padStart(2, "0")}.000Z`);
});
}
describe("community server rail D1 statements", () => {
- it("reads memberships, folders, and items in one consistent three-statement batch", async () => {
+ it("reads memberships, folders, and items in one consistent four-statement batch", async () => {
const statementRows = [
[{ serverId: "s1" }, { serverId: "s2" }],
[{ id: "f1", name: "One" }],
[{ folderId: "f1", serverId: "s2" }],
+ [],
];
const db: any = {
select: () => {
@@ -89,46 +90,37 @@ describe("community server rail D1 statements", () => {
return chain;
},
batch: async (statements: unknown[]) => {
- expect(statements).toHaveLength(3);
+ expect(statements).toHaveLength(4);
return statementRows;
},
};
await expect(readServerRailSnapshot(db, "u1")).resolves.toEqual({
- serverOrder: ["s1", "s2"],
- folderOrder: ["f1"],
+ serverIds: ["s1", "s2"],
+ folderIds: ["f1"],
folders: { f1: { id: "f1", name: "One", serverIds: ["s2"] } },
+ topOrder: [{ kind: "server", id: "s1" }, { kind: "folder", id: "f1" }],
});
});
- it("reorders 125 memberships with one JSON expansion and fixed bind count", () => {
+ it("persists 125 top-level entries with fixed bind count and no membership writes", () => {
const { sqlite, db } = createDatabase();
const ids = Array.from({ length: 125 }, (_, index) => `s${index}`);
seedMemberships(sqlite, ids);
- const state: ServerRailState = { serverOrder: ids, folderOrder: [], folders: {} };
- const { statements } = runProjection(sqlite, db, state, {
- commands: [{ kind: "reorder-servers", serverIds: [...ids].reverse() }],
- });
- expect(statements.length).toBeLessThanOrEqual(13);
- const reorder = statements.find((statement) => statement.toSQL().sql.includes(
- 'update "community_server_member"',
- ));
- expect(reorder).toBeDefined();
- const query = reorder!.toSQL();
- expect(query.sql).toContain("json_each");
- expect(query.params).toHaveLength(2);
- expect(query.params.every((param: unknown) => typeof param === "string")).toBe(true);
- const order = sqlite.prepare(`
- SELECT server_id AS id FROM community_server_member
- WHERE user_id = 'u1' ORDER BY rail_order, server_id
- `).all().map((row: any) => row.id);
- expect(order).toEqual([...ids].reverse());
+ const state: ServerRailState = { serverIds: ids, folderIds: [], folders: {} };
+ const entries = [...ids].reverse().map((id) => ({ kind: "server" as const, id }));
+ const { statements } = runProjection(sqlite, db, state, { commands: [{ kind: "reorder-top-level", entries }] });
+ expect(statements.length).toBeLessThanOrEqual(11);
+ expect(statements.some((statement) => statement.toSQL().sql.includes('update "community_server_member"'))).toBe(false);
+ const write = statements.find((statement) => statement.toSQL().sql.includes('insert into "community_server_rail"'))!;
+ expect(write.toSQL().params).toHaveLength(3);
+ expect(JSON.parse((sqlite.prepare("SELECT entries FROM community_server_rail WHERE user_id='u1'").get() as { entries: string }).entries)).toEqual(entries);
});
it("inserts 125 guarded folder items from one JSON statement", () => {
const { sqlite, db } = createDatabase();
const ids = Array.from({ length: 125 }, (_, index) => `s${index}`);
seedMemberships(sqlite, ids);
- const state: ServerRailState = { serverOrder: ids, folderOrder: [], folders: {} };
+ const state: ServerRailState = { serverIds: ids, folderIds: [], folders: {} };
const { statements } = runProjection(sqlite, db, state, {
commands: [{ kind: "create-folder", clientId: "tmp", name: "Group", serverIds: ids }],
});
@@ -154,7 +146,7 @@ describe("community server rail D1 statements", () => {
it("rolls back the whole write when membership disappears before guarded insert", () => {
const { sqlite, db } = createDatabase();
seedMemberships(sqlite, ["a", "b"]);
- const state: ServerRailState = { serverOrder: ["a", "b"], folderOrder: [], folders: {} };
+ const state: ServerRailState = { serverIds: ["a", "b"], folderIds: [], folders: {} };
const result = projectServerRailCommit(state, {
commands: [{ kind: "create-folder", clientId: "tmp", name: "Group", serverIds: ["a", "b"] }],
}, () => "created");
@@ -173,20 +165,20 @@ describe("community server rail D1 statements", () => {
const { sqlite, db } = createDatabase();
sqlite.exec(`
INSERT INTO community_server (id) VALUES ('a'), ('b'), ('x');
- INSERT INTO community_server_member (id, server_id, user_id, rail_order, joined_at)
+ INSERT INTO community_server_member (id, server_id, user_id, joined_at)
VALUES
- ('u1-a', 'a', 'u1', 0, '2026-01-01T00:00:00.000Z'),
- ('u1-b', 'b', 'u1', 1, '2026-01-01T00:00:01.000Z'),
- ('u2-x', 'x', 'u2', 0, '2026-01-01T00:00:00.000Z');
- INSERT INTO community_server_folder (id, user_id, name, position)
+ ('u1-a', 'a', 'u1', '2026-01-01T00:00:00.000Z'),
+ ('u1-b', 'b', 'u1', '2026-01-01T00:00:01.000Z'),
+ ('u2-x', 'x', 'u2', '2026-01-01T00:00:00.000Z');
+ INSERT INTO community_server_folder (id, user_id, name)
VALUES
- ('u1-empty', 'u1', 'Empty', 0),
- ('u1-a-locale-first', 'u1', 'Locale first', NULL),
- ('u1-Z-binary-first', 'u1', 'Binary first', 0),
- ('u1-dangling', 'u1', 'Dangling', 6),
- ('u2-empty', 'u2', 'Foreign empty', 0),
- ('u2-first', 'u2', 'Foreign first', 1),
- ('u2-second', 'u2', 'Foreign second', 2);
+ ('u1-empty', 'u1', 'Empty'),
+ ('u1-a-locale-first', 'u1', 'Locale first'),
+ ('u1-Z-binary-first', 'u1', 'Binary first'),
+ ('u1-dangling', 'u1', 'Dangling'),
+ ('u2-empty', 'u2', 'Foreign empty'),
+ ('u2-first', 'u2', 'Foreign first'),
+ ('u2-second', 'u2', 'Foreign second');
INSERT INTO community_server_folder_item (folder_id, server_id, position)
VALUES
('u1-a-locale-first', 'a', 7),
@@ -201,8 +193,9 @@ describe("community server rail D1 statements", () => {
const snapshot = await readServerRailSnapshot(d1Db, "u1");
expect(snapshot).toEqual({
- serverOrder: ["a", "b"],
- folderOrder: ["u1-Z-binary-first"],
+ serverIds: ["a", "b"],
+ folderIds: ["u1-Z-binary-first"],
+ topOrder: [{ kind: "server", id: "b" }, { kind: "folder", id: "u1-Z-binary-first" }],
folders: {
"u1-Z-binary-first": {
id: "u1-Z-binary-first",
@@ -212,7 +205,7 @@ describe("community server rail D1 statements", () => {
},
});
const projection = projectServerRailCommit(snapshot, {
- commands: [{ kind: "reorder-servers", serverIds: ["b", "a"] }],
+ commands: [{ kind: "reorder-top-level", entries: [...serverRailTopOrder(snapshot)].reverse() }],
}, () => "unused");
expect(projection.ok).toBe(true);
if (!projection.ok) throw new Error(projection.error);
@@ -221,18 +214,18 @@ describe("community server rail D1 statements", () => {
.not.toThrow();
expect(sqlite.prepare(`
- SELECT id, position FROM community_server_folder WHERE user_id = 'u1' ORDER BY id
- `).all()).toEqual([{ id: "u1-Z-binary-first", position: 0 }]);
+ SELECT id FROM community_server_folder WHERE user_id = 'u1' ORDER BY id
+ `).all()).toEqual([{ id: "u1-Z-binary-first" }]);
expect(sqlite.prepare(`
SELECT folder_id AS folderId, server_id AS serverId, position
FROM community_server_folder_item WHERE folder_id = 'u1-Z-binary-first'
`).all()).toEqual([{ folderId: "u1-Z-binary-first", serverId: "a", position: 0 }]);
expect(sqlite.prepare(`
- SELECT id, position FROM community_server_folder WHERE user_id = 'u2' ORDER BY id
+ SELECT id FROM community_server_folder WHERE user_id = 'u2' ORDER BY id
`).all()).toEqual([
- { id: "u2-empty", position: 0 },
- { id: "u2-first", position: 1 },
- { id: "u2-second", position: 2 },
+ { id: "u2-empty" },
+ { id: "u2-first" },
+ { id: "u2-second" },
]);
expect(sqlite.prepare(`
SELECT folder_id AS folderId, server_id AS serverId, position
@@ -251,9 +244,9 @@ describe("community server rail D1 statements", () => {
seedMemberships(sqlite, ids);
ids.forEach((serverId, index) => {
sqlite.prepare(`
- INSERT INTO community_server_folder (id, user_id, name, position)
- VALUES (?, 'u1', ?, ?)
- `).run(`f${index}`, `Folder ${index}`, index);
+ INSERT INTO community_server_folder (id, user_id, name)
+ VALUES (?, 'u1', ?)
+ `).run(`f${index}`, `Folder ${index}`);
sqlite.prepare(`
INSERT INTO community_server_folder_item (folder_id, server_id, position)
VALUES (?, ?, 0)
@@ -263,9 +256,9 @@ describe("community server rail D1 statements", () => {
batch: async (statements: any[]) => statements.map((statement) => statement.all()),
});
const overflow = await readServerRailSnapshot(d1Db, "u1");
- expect(overflow.folderOrder).toHaveLength(11);
+ expect(overflow.folderIds).toHaveLength(11);
expect(projectServerRailCommit(overflow, {
- commands: [{ kind: "reorder-servers", serverIds: [...ids].reverse() }],
+ commands: [{ kind: "reorder-top-level", entries: [...serverRailTopOrder(overflow)].reverse() }],
}, () => "unused")).toMatchObject({ ok: false });
const recovery = projectServerRailCommit(overflow, {
@@ -276,12 +269,12 @@ describe("community server rail D1 statements", () => {
const recoveryStatements = buildServerRailWriteStatements(db as any, "u1", recovery.value);
sqlite.transaction(() => recoveryStatements.forEach((statement) => statement.run()))();
expect(sqlite.prepare(`
- SELECT id, position FROM community_server_folder WHERE user_id = 'u1' ORDER BY position
- `).all()).toEqual(Array.from({ length: 10 }, (_, index) => ({ id: `f${index}`, position: index })));
+ SELECT id FROM community_server_folder WHERE user_id = 'u1' ORDER BY id
+ `).all()).toEqual(Array.from({ length: 10 }, (_, index) => ({ id: `f${index}` })));
const recovered = await readServerRailSnapshot(d1Db, "u1");
const next = projectServerRailCommit(recovered, {
- commands: [{ kind: "reorder-servers", serverIds: [...ids].reverse() }],
+ commands: [{ kind: "reorder-top-level", entries: [...serverRailTopOrder(recovered)].reverse() }],
}, () => "unused");
expect(next.ok).toBe(true);
if (!next.ok) throw new Error(next.error);
@@ -294,14 +287,14 @@ describe("community server rail D1 statements", () => {
const { sqlite, db } = createDatabase();
seedMemberships(sqlite, ["a", "b", "c"]);
sqlite.exec(`
- INSERT INTO community_server_folder (id, user_id, name, position)
- VALUES ('one', 'u1', 'One', 0), ('two', 'u1', 'Two', 1);
+ INSERT INTO community_server_folder (id, user_id, name)
+ VALUES ('one', 'u1', 'One'), ('two', 'u1', 'Two');
INSERT INTO community_server_folder_item (folder_id, server_id, position)
VALUES ('one', 'a', 0), ('one', 'b', 1), ('two', 'c', 0);
`);
const stale: ServerRailState = {
- serverOrder: ["a", "b", "c"],
- folderOrder: ["one", "two"],
+ serverIds: ["a", "b", "c"],
+ folderIds: ["one", "two"],
folders: {
one: { id: "one", name: "One", serverIds: ["a", "b"] },
two: { id: "two", name: "Two", serverIds: ["c"] },
@@ -339,7 +332,7 @@ describe("community server rail D1 statements", () => {
] as const)("removes the folder emptied by a concurrent same-server create: %s", async (_name, order) => {
const { sqlite, db } = createDatabase();
seedMemberships(sqlite, ["a", "b"]);
- const stale: ServerRailState = { serverOrder: ["a", "b"], folderOrder: [], folders: {} };
+ const stale: ServerRailState = { serverIds: ["a", "b"], folderIds: [], folders: {} };
const projections = Object.fromEntries(["x", "y"].map((id) => {
const result = projectServerRailCommit(stale, {
commands: [{ kind: "create-folder", clientId: id, name: id, serverIds: ["a"] }],
@@ -358,7 +351,7 @@ describe("community server rail D1 statements", () => {
batch: async (statements: any[]) => statements.map((statement) => statement.all()),
});
const snapshot = await readServerRailSnapshot(d1Db, "u1");
- expect(snapshot.folderOrder).toEqual([order[1]]);
+ expect(snapshot.folderIds).toEqual([order[1]]);
expect(snapshot.folders[order[1]]?.serverIds).toEqual(["a"]);
expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_server_folder").get())
.toEqual({ count: 1 });
@@ -378,8 +371,8 @@ describe("community server rail D1 statements", () => {
seedMemberships(sqlite, ids);
for (let index = 0; index < 9; index += 1) {
sqlite.prepare(`
- INSERT INTO community_server_folder (id, user_id, name, position) VALUES (?, 'u1', ?, ?)
- `).run(`f${index}`, `Folder ${index}`, index);
+ INSERT INTO community_server_folder (id, user_id, name) VALUES (?, 'u1', ?)
+ `).run(`f${index}`, `Folder ${index}`);
sqlite.prepare(`
INSERT INTO community_server_folder_item (folder_id, server_id, position) VALUES (?, ?, 0)
`).run(`f${index}`, `s${index}`);
@@ -407,7 +400,7 @@ describe("community server rail D1 statements", () => {
const finalSnapshot = await readServerRailSnapshot(d1Db, "u1");
const next = projectServerRailCommit(finalSnapshot, {
- commands: [{ kind: "reorder-servers", serverIds: [...finalSnapshot.serverOrder].reverse() }],
+ commands: [{ kind: "reorder-top-level", entries: [...serverRailTopOrder(finalSnapshot)].reverse() }],
}, () => "unused");
expect(next.ok).toBe(true);
if (!next.ok) throw new Error(next.error);
@@ -416,3 +409,34 @@ describe("community server rail D1 statements", () => {
.not.toThrow();
});
});
+
+it("persists one account mixed order without changing another account", () => {
+ const { sqlite, db } = createDatabase();
+ seedMemberships(sqlite, ["a", "b", "c"]);
+ sqlite.exec(`INSERT INTO community_server_folder VALUES ('f', 'u1', 'Folder'); INSERT INTO community_server_folder_item VALUES ('f', 'c', 0);`);
+ const other = JSON.stringify([{ kind: "server", id: "other" }]);
+ sqlite.prepare("INSERT INTO community_server_rail VALUES (?, ?)").run("u2", other);
+ const entries = [{ kind: "server" as const, id: "a" }, { kind: "folder" as const, id: "f" }, { kind: "server" as const, id: "b" }];
+ runProjection(sqlite, db, { serverIds: ["a", "b", "c"], folderIds: ["f"], folders: { f: { id: "f", name: "Folder", serverIds: ["c"] } } }, { commands: [{ kind: "reorder-top-level", entries }] });
+ expect(JSON.parse((sqlite.prepare("SELECT entries FROM community_server_rail WHERE user_id = 'u1'").get() as { entries: string }).entries)).toEqual(entries);
+ expect(sqlite.prepare("SELECT entries FROM community_server_rail WHERE user_id = 'u2'").get()).toEqual({ entries: other });
+});
+
+it("atomically replaces an emptied single-server folder at the ten-folder limit", () => {
+ const { sqlite, db } = createDatabase();
+ seedMemberships(sqlite, ["a", "b", ...Array.from({ length: 10 }, (_, i) => `s${i}`)]);
+ const folder = sqlite.prepare("INSERT INTO community_server_folder VALUES (?, 'u1', 'Folder')");
+ const item = sqlite.prepare("INSERT INTO community_server_folder_item VALUES (?, ?, 0)");
+ for (let i = 0; i < 10; i++) { folder.run(`f${i}`); item.run(`f${i}`, `s${i}`); }
+ const folderIds = Array.from({ length: 10 }, (_, i) => `f${i}`);
+ const state: ServerRailState = { serverIds: ["a", "b", ...Array.from({ length: 10 }, (_, i) => `s${i}`)], folderIds, folders: Object.fromEntries(folderIds.map((id, i) => [id, { id, name: "Folder", serverIds: [`s${i}`] }])) };
+ runProjection(sqlite, db, state, { commands: [
+ { kind: "delete-folder", folderId: "f1" },
+ { kind: "create-folder", clientId: "temp", name: "Group", serverIds: ["a", "s1"] },
+ { kind: "reorder-top-level", entries: [{ kind: "folder", id: "temp" }, { kind: "server", id: "b" }, ...folderIds.filter((id) => id !== "f1").map((id) => ({ kind: "folder" as const, id }))] },
+ ] });
+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_server_folder WHERE user_id = 'u1'").get()).toEqual({ count: 10 });
+ expect(sqlite.prepare("SELECT id FROM community_server_folder WHERE id = 'f1'").get()).toBeUndefined();
+ expect(sqlite.prepare("SELECT server_id AS id FROM community_server_folder_item WHERE folder_id = 'created' ORDER BY position").all()).toEqual([{ id: "a" }, { id: "s1" }]);
+ expect(JSON.parse((sqlite.prepare("SELECT entries FROM community_server_rail WHERE user_id = 'u1'").get() as { entries: string }).entries)[0]).toEqual({ kind: "folder", id: "created" });
+});
diff --git a/src/shared/test/queries/server.test.ts b/src/shared/test/queries/server.test.ts
index 4b4b58e2d..99774922c 100644
--- a/src/shared/test/queries/server.test.ts
+++ b/src/shared/test/queries/server.test.ts
@@ -265,13 +265,12 @@ describe("createServer", () => {
addedBy: ownerId,
});
- // 7) communityServerMember — exactly one owner row, railOrder=0
+ // 7) communityServerMember — exactly one owner row, no rail order
expect(insertCalls[6].table).toBe(communityServerMember);
expect(insertCalls[6].values).toMatchObject({
serverId,
userId: ownerId,
role: "owner",
- railOrder: 0,
});
// Member insert uses .returning({ id, userId, joinedAt })
expect(insertCalls[6].returningArg).toBeDefined();
@@ -385,6 +384,7 @@ function createListServersMock(finalRows: unknown[]) {
};
const db: any = {
+ batch: async () => [finalRows.map((row: any) => ({ serverId: row.id })), [], [], []],
select(fields: unknown) {
selectChains.push({
fields,
@@ -437,7 +437,7 @@ describe("listUserServers — mention aggregate for the rail badge", () => {
expect(outer.leftJoins[0].table).toMatchObject({ __subquery: "mention_counts" });
});
- it("orders rows by railOrder — rail sort must not regress", async () => {
+ it("orders newly joined rows deterministically before canonical projection", async () => {
const { db, selectChains } = createListServersMock([]);
await serverQueries.listUserServers(db, "u_1");
const outer = selectChains[1];
@@ -448,9 +448,9 @@ describe("listUserServers — mention aggregate for the rail badge", () => {
// Simulates: viewer has 2 unread mentions in srv_A, 1 in srv_B, none in
// srv_C (LEFT JOIN + COALESCE → 0).
const rows = [
- { id: "srv_A", name: "A", railOrder: 0, mentions: 2 },
- { id: "srv_B", name: "B", railOrder: 1, mentions: 1 },
- { id: "srv_C", name: "C", railOrder: 2, mentions: 0 },
+ { id: "srv_A", name: "A", mentions: 2 },
+ { id: "srv_B", name: "B", mentions: 1 },
+ { id: "srv_C", name: "C", mentions: 0 },
];
const { db } = createListServersMock(rows);
const result = await serverQueries.listUserServers(db, "u_1");
@@ -468,8 +468,8 @@ describe("listUserServers — mention aggregate for the rail badge", () => {
// With zero unread mentions, the subquery yields no rows and every
// LEFT JOIN produces NULL → COALESCE → 0.
const rows = [
- { id: "srv_A", name: "A", railOrder: 0, mentions: 0 },
- { id: "srv_B", name: "B", railOrder: 1, mentions: 0 },
+ { id: "srv_A", name: "A", mentions: 0 },
+ { id: "srv_B", name: "B", mentions: 0 },
];
const { db } = createListServersMock(rows);
const result = await serverQueries.listUserServers(db, "u_1");
diff --git a/src/web/migrations/0108_community_server_rail_order.sql b/src/web/migrations/0108_community_server_rail_order.sql
new file mode 100644
index 000000000..8c42134ae
--- /dev/null
+++ b/src/web/migrations/0108_community_server_rail_order.sql
@@ -0,0 +1,4 @@
+CREATE TABLE community_server_rail (
+ user_id TEXT PRIMARY KEY NOT NULL REFERENCES user(id) ON DELETE CASCADE,
+ entries TEXT NOT NULL
+);
diff --git a/src/web/migrations/0109_server_rail_single_order.sql b/src/web/migrations/0109_server_rail_single_order.sql
new file mode 100644
index 000000000..518b7750a
--- /dev/null
+++ b/src/web/migrations/0109_server_rail_single_order.sql
@@ -0,0 +1,36 @@
+INSERT INTO community_server_rail (user_id, entries)
+SELECT owner.user_id, (
+ SELECT json_group_array(json(entry))
+ FROM (
+ SELECT json_object('kind', 'server', 'id', member.server_id) AS entry,
+ 0 AS section, COALESCE(member.rail_order, 0) AS position,
+ member.joined_at AS joined_at, member.server_id AS id
+ FROM community_server_member AS member
+ WHERE member.user_id = owner.user_id
+ AND NOT EXISTS (
+ SELECT 1 FROM community_server_folder_item AS item
+ JOIN community_server_folder AS folder ON folder.id = item.folder_id
+ WHERE folder.user_id = owner.user_id AND item.server_id = member.server_id
+ )
+ UNION ALL
+ SELECT json_object('kind', 'folder', 'id', folder.id),
+ 1, COALESCE(folder.position, 0), '', folder.id
+ FROM community_server_folder AS folder
+ WHERE folder.user_id = owner.user_id
+ AND EXISTS (
+ SELECT 1 FROM community_server_folder_item AS item
+ JOIN community_server_member AS member ON member.server_id = item.server_id
+ AND member.user_id = owner.user_id
+ WHERE item.folder_id = folder.id
+ )
+ ORDER BY section, position, joined_at, id
+ )
+)
+FROM (SELECT DISTINCT user_id FROM community_server_member) AS owner
+WHERE NOT EXISTS (SELECT 1 FROM community_server_rail AS rail WHERE rail.user_id = owner.user_id);
+
+DROP INDEX idx_server_member_user_rail_order;
+ALTER TABLE community_server_member DROP COLUMN rail_order;
+DROP INDEX idx_server_folder_user_position;
+ALTER TABLE community_server_folder DROP COLUMN position;
+CREATE INDEX idx_server_folder_user ON community_server_folder(user_id);
diff --git a/src/web/package.json b/src/web/package.json
index f902f6745..b40ce1fc6 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -39,14 +39,7 @@
},
"dependencies": {
"@alook/shared": "workspace:*",
- "@atlaskit/pragmatic-drag-and-drop": "3.1.0",
- "@atlaskit/pragmatic-drag-and-drop-auto-scroll": "3.2.1",
- "@atlaskit/pragmatic-drag-and-drop-hitbox": "2.2.2",
- "@atlaskit/pragmatic-drag-and-drop-live-region": "2.1.0",
"@base-ui/react": "^1.9.0",
- "@dnd-kit/core": "^6.3.1",
- "@dnd-kit/sortable": "^10.0.0",
- "@dnd-kit/utilities": "^3.2.2",
"@emoji-mart/data": "^1.2.1",
"@emoji-mart/react": "^1.1.1",
"@grafana/faro-web-sdk": "2.12.1",
@@ -90,6 +83,7 @@
"better-auth": "1.7.11",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "dnd-multi-backend": "9.0.0",
"emoji-mart": "^5.6.0",
"gsap": "^3.15.0",
"html-to-image": "^1.11.13",
@@ -112,6 +106,10 @@
"next-themes": "^0.4.6",
"pdfjs-dist": "6.4.299",
"react": "19.3.1",
+ "react-dnd": "16.0.1",
+ "react-dnd-html5-backend": "16.0.1",
+ "react-dnd-scrolling": "1.3.10",
+ "react-dnd-touch-backend": "16.0.1",
"react-dom": "19.3.1",
"react-easy-crop": "^6.2.4",
"react-resizable-panels": "4.14.5",
@@ -162,6 +160,7 @@
"fake-indexeddb": "^6.2.5",
"jsdom": "29.1.1",
"knip": "^6.32.2",
+ "react-dnd-test-backend": "16.0.1",
"react-scan": "0.5.7",
"serwist": "9.5.13",
"sharp": "^0.35.5",
diff --git a/src/web/src/app/api/community/servers/[id]/channels/reorder/route.test.ts b/src/web/src/app/api/community/servers/[id]/channels/reorder/route.test.ts
index 35e2d5738..f9e5068e1 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/reorder/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/reorder/route.test.ts
@@ -1,114 +1,89 @@
-import { describe, it, expect, vi, beforeEach } from "vitest"
+import { beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
-const getMember = vi.fn()
-const getChannelsByIds = vi.fn()
-const reorderChannels = vi.fn()
-const fanOut = vi.fn()
-
-vi.mock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
-}))
-
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
-
-vi.mock("@alook/shared", async () => {
- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
- return {
- ...actual,
- queries: {
- communityMember: { getMember: (...a: unknown[]) => getMember(...a) },
- communityChannel: {
- getChannelsByIds: (...a: unknown[]) => getChannelsByIds(...a),
- reorderChannels: (...a: unknown[]) => reorderChannels(...a),
- },
- },
- }
-})
-
-vi.mock("@/lib/community/fanout", () => ({
- fanOutToServerMembers: (...a: unknown[]) => fanOut(...a),
+const mocks = vi.hoisted(() => ({ member: vi.fn(), roots: vi.fn(), categories: vi.fn(), reorder: vi.fn(), fanout: vi.fn(), primary: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: mocks.primary }))
+vi.mock("@alook/shared", async () => ({
+ ...await vi.importActual<typeof import("@alook/shared")>("@alook/shared"),
+ queries: {
+ communityMember: { getMember: mocks.member },
+ communityCategory: { listCategoriesByServer: mocks.categories },
+ communityChannel: { getServerRootChannelsByIds: mocks.roots, reorderChannels: mocks.reorder },
+ },
}))
-
-vi.mock("@/lib/middleware/auth", () => ({
- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params })
- }),
-}))
-
-vi.mock("@/lib/middleware/helpers", async () => {
- const { NextResponse } = require("next/server")
- return {
- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
- }
-})
-
+vi.mock("@/lib/community/fanout", () => ({ fanOutToServerMembers: mocks.fanout }))
+vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: any) => (req: any, ctx?: any) => handler(req, { env: { DB: "binding" }, userId: "u1", params: ctx?.params }) }))
import { PATCH } from "./route"
-
-function patchReq(body: unknown) {
- return new NextRequest("http://localhost/api/community/servers/s1/channels/reorder", {
- method: "PATCH",
- body: JSON.stringify(body),
- headers: { "Content-Type": "application/json" },
- })
-}
-
const ctx = { params: { id: "s1" } } as never
+const request = (body: unknown) => new NextRequest("http://localhost/api/community/servers/s1/channels/reorder", { method: "PATCH", body: JSON.stringify(body), headers: { "Content-Type": "application/json" } })
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.member.mockResolvedValue({ id: "m1", role: "admin" })
+ mocks.roots.mockResolvedValue([{ id: "c1", serverId: "s1", categoryId: "a" }, { id: "c2", serverId: "s1", categoryId: "b" }])
+ mocks.categories.mockResolvedValue([{ id: "a", private: 0 }, { id: "b", private: 0 }])
+ mocks.reorder.mockResolvedValue(undefined)
+ mocks.fanout.mockResolvedValue(undefined)
+})
-describe("PATCH /api/community/servers/[id]/channels/reorder", () => {
- beforeEach(() => {
- vi.clearAllMocks()
- getMember.mockResolvedValue({ id: "m1", role: "admin" })
- fanOut.mockResolvedValue(undefined)
- reorderChannels.mockResolvedValue(undefined)
+describe("server-scoped channel order", () => {
+ it("requires server administration before reading channel rows", async () => {
+ mocks.member.mockResolvedValue({ id: "member", role: "member" })
+ expect((await PATCH(request({ channelIds: ["c1"] }), ctx)).status).toBe(403)
+ expect(mocks.roots).not.toHaveBeenCalled()
+ expect(mocks.reorder).not.toHaveBeenCalled()
})
-
- it("403 when the caller is not an admin", async () => {
- getMember.mockResolvedValue({ id: "m1", role: "member" })
- const res = await PATCH(patchReq({ channelIds: ["c1", "c2"] }), ctx)
- expect(res.status).toBe(403)
- expect(reorderChannels).not.toHaveBeenCalled()
+ it.each([null, {}, { channelIds: [] }, { channelIds: ["c1", "c1"] }, { channelIds: [1] }, { channelIds: ["c1"], move: { channelId: "other", categoryId: "b" } }, { channelIds: ["c1"], move: { channelId: "c1", categoryId: 1 } }, { channelIds: ["c1"], unknown: true }])("rejects malformed commands before reading rows: %j", async (body) => {
+ expect((await PATCH(request(body), ctx)).status).toBe(400)
+ expect(mocks.roots).not.toHaveBeenCalled()
+ expect(mocks.reorder).not.toHaveBeenCalled()
+ expect(mocks.fanout).not.toHaveBeenCalled()
})
-
- it("400 when channelIds is empty", async () => {
- const res = await PATCH(patchReq({ channelIds: [] }), ctx)
- expect(res.status).toBe(400)
+ it.each(["foreign-server", "missing", "nested-thread"])("rejects a %s identity absent from the scoped root query", async () => {
+ mocks.roots.mockResolvedValue([{ id: "c1" }])
+ expect((await PATCH(request({ channelIds: ["c1", "unavailable"] }), ctx)).status).toBe(404)
+ expect(mocks.roots).toHaveBeenCalledExactlyOnceWith({}, "s1", ["c1", "unavailable"])
+ expect(mocks.reorder).not.toHaveBeenCalled()
+ expect(mocks.fanout).not.toHaveBeenCalled()
})
-
- it("400 when channelIds contains duplicates", async () => {
- const res = await PATCH(patchReq({ channelIds: ["c1", "c1"] }), ctx)
- expect(res.status).toBe(400)
- expect(reorderChannels).not.toHaveBeenCalled()
+ it("preserves the existing reorder contract and uses a primary session", async () => {
+ expect((await PATCH(request({ channelIds: ["c2", "c1"] }), ctx)).status).toBe(200)
+ expect(mocks.primary).toHaveBeenCalledExactlyOnceWith("binding")
+ expect(mocks.reorder).toHaveBeenCalledExactlyOnceWith({}, "s1", ["c2", "c1"], undefined)
+ expect(mocks.categories).not.toHaveBeenCalled()
+ expect(mocks.fanout).toHaveBeenCalledExactlyOnceWith("s1", { type: "community:channel.reorder", serverId: "s1", channels: [{ id: "c2", position: 0 }, { id: "c1", position: 1 }] })
})
-
- it("404 when one channel does not exist", async () => {
- getChannelsByIds.mockResolvedValue([{ id: "c1", serverId: "s1" }]) // missing c2
- const res = await PATCH(patchReq({ channelIds: ["c1", "c2"] }), ctx)
- expect(res.status).toBe(404)
- expect(reorderChannels).not.toHaveBeenCalled()
+ it.each([false, true])("commits a same-privacy category move and order together, private=%s", async (privateCategory) => {
+ mocks.categories.mockResolvedValue([{ id: "a", private: Number(privateCategory) }, { id: "b", private: Number(privateCategory) }])
+ const move = { channelId: "c1", categoryId: "b" }
+ expect((await PATCH(request({ channelIds: ["c2", "c1"], move }), ctx)).status).toBe(200)
+ expect(mocks.categories).toHaveBeenCalledExactlyOnceWith({}, "s1")
+ expect(mocks.reorder).toHaveBeenCalledExactlyOnceWith({}, "s1", ["c2", "c1"], move)
+ expect(mocks.reorder.mock.invocationCallOrder[0]).toBeLessThan(mocks.fanout.mock.invocationCallOrder[0]!)
})
-
- it("400 when a channel belongs to a DIFFERENT server (cross-server IDOR)", async () => {
- getChannelsByIds.mockResolvedValue([
- { id: "c1", serverId: "s1" },
- { id: "c2", serverId: "s_OTHER" }, // attacker-supplied foreign id
- ])
- const res = await PATCH(patchReq({ channelIds: ["c1", "c2"] }), ctx)
- expect(res.status).toBe(400)
- expect(await res.json()).toEqual({ error: "channel does not belong to this server" })
- expect(reorderChannels).not.toHaveBeenCalled()
+ it("moves a public channel to uncategorized in the same batch", async () => {
+ const move = { channelId: "c1", categoryId: null }
+ expect((await PATCH(request({ channelIds: ["c1", "c2"], move }), ctx)).status).toBe(200)
+ expect(mocks.reorder).toHaveBeenCalledWith({}, "s1", ["c1", "c2"], move)
})
-
- it("succeeds when every channel belongs to the target server", async () => {
- getChannelsByIds.mockResolvedValue([
- { id: "c1", serverId: "s1" },
- { id: "c2", serverId: "s1" },
- ])
- const res = await PATCH(patchReq({ channelIds: ["c1", "c2"] }), ctx)
- expect(res.status).toBe(200)
- expect(reorderChannels).toHaveBeenCalledWith({}, "s1", ["c1", "c2"])
- expect(fanOut).toHaveBeenCalled()
+ it.each(["b", null])("rejects a private channel entering public/root: %s", async (categoryId) => {
+ mocks.categories.mockResolvedValue([{ id: "a", private: 1 }, { id: "b", private: 0 }])
+ expect((await PATCH(request({ channelIds: ["c1", "c2"], move: { channelId: "c1", categoryId } }), ctx)).status).toBe(400)
+ expect(mocks.reorder).not.toHaveBeenCalled()
+ expect(mocks.fanout).not.toHaveBeenCalled()
+ })
+ it("rejects a public channel entering private", async () => {
+ mocks.categories.mockResolvedValue([{ id: "a", private: 0 }, { id: "b", private: 1 }])
+ expect((await PATCH(request({ channelIds: ["c1", "c2"], move: { channelId: "c1", categoryId: "b" } }), ctx)).status).toBe(400)
+ expect(mocks.reorder).not.toHaveBeenCalled()
+ })
+ it("rejects a target category outside the server", async () => {
+ expect((await PATCH(request({ channelIds: ["c1", "c2"], move: { channelId: "c1", categoryId: "foreign" } }), ctx)).status).toBe(404)
+ expect(mocks.reorder).not.toHaveBeenCalled()
+ })
+ it("sends no success event when the atomic write fails", async () => {
+ mocks.reorder.mockRejectedValue(new Error("batch rejected"))
+ await expect(PATCH(request({ channelIds: ["c1", "c2"], move: { channelId: "c1", categoryId: "b" } }), ctx)).rejects.toThrow("batch rejected")
+ expect(mocks.fanout).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/app/api/community/servers/[id]/channels/reorder/route.ts b/src/web/src/app/api/community/servers/[id]/channels/reorder/route.ts
index 20159e2cd..3d660fec8 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/reorder/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/reorder/route.ts
@@ -1,49 +1,36 @@
import { NextRequest } from "next/server"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
-import { getDb } from "@/lib/db"
-import { queries, WS_EVENTS } from "@alook/shared"
+import { getPrimaryDb } from "@/lib/db"
+import { channelReorderRequestSchema, queries, WS_EVENTS } from "@alook/shared"
import { fanOutToServerMembers } from "@/lib/community/fanout"
import { requireServerAdmin } from "@/lib/community/permissions"
export const PATCH = withAuth(async (req: NextRequest, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("missing server id", 400)
-
- const db = getDb(ctx.env.DB)
+ const db = getPrimaryDb(ctx.env.DB)
const auth = await requireServerAdmin(db, serverId, ctx.userId)
if (!auth.ok) return writeError(auth.error, auth.status)
-
- let body: { channelIds?: string[] }
- try {
- body = await req.json()
- } catch {
- return writeError("invalid request body", 400)
- }
-
- if (!Array.isArray(body.channelIds) || body.channelIds.length === 0) {
- return writeError("channelIds must be a non-empty array", 400)
- }
- const unique = new Set(body.channelIds)
- if (unique.size !== body.channelIds.length) {
- return writeError("channelIds must be unique", 400)
+ let body: unknown
+ try { body = await req.json() } catch { return writeError("invalid request body", 400) }
+ const parsed = channelReorderRequestSchema.safeParse(body)
+ if (!parsed.success) return writeError(parsed.error.issues[0]?.message ?? "invalid channel order", 400)
+ const { channelIds, move } = parsed.data
+ const channels = await queries.communityChannel.getServerRootChannelsByIds(db, serverId, channelIds)
+ if (channels.length !== channelIds.length) return writeError("one or more server channels not found", 404)
+ if (move) {
+ const categories = await queries.communityCategory.listCategoriesByServer(db, serverId)
+ const moving = channels.find((channel) => channel.id === move.channelId)!
+ const source = moving.categoryId ? categories.find((category) => category.id === moving.categoryId) : null
+ const target = move.categoryId ? categories.find((category) => category.id === move.categoryId) : null
+ if ((moving.categoryId && !source) || (move.categoryId && !target)) return writeError("category not found", 404)
+ if (!!source?.private !== !!target?.private) return writeError("Can't move a channel across a public/private boundary", 400)
}
-
- const channels = await queries.communityChannel.getChannelsByIds(db, body.channelIds)
- if (channels.length !== body.channelIds.length) {
- return writeError("one or more channels not found", 404)
- }
- if (channels.some((ch) => ch.serverId !== serverId)) {
- return writeError("channel does not belong to this server", 400)
- }
-
- await queries.communityChannel.reorderChannels(db, serverId, body.channelIds)
-
+ await queries.communityChannel.reorderChannels(db, serverId, channelIds, move)
await fanOutToServerMembers(serverId, {
- type: WS_EVENTS.CHANNEL_REORDER,
- serverId,
- channels: body.channelIds.map((id, i) => ({ id, position: i })),
+ type: WS_EVENTS.CHANNEL_REORDER, serverId,
+ channels: channelIds.map((id, position) => ({ id, position })),
})
-
return writeJSON({ ok: true })
})
diff --git a/src/web/src/app/api/community/servers/route.bot.test.ts b/src/web/src/app/api/community/servers/route.bot.test.ts
index 7bba03f3c..571437aaa 100644
--- a/src/web/src/app/api/community/servers/route.bot.test.ts
+++ b/src/web/src/app/api/community/servers/route.bot.test.ts
@@ -12,7 +12,7 @@ import { NextRequest } from "next/server"
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),
}))
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})), getPrimaryDb: vi.fn(() => ({})) }))
// No-`crk_` request falls through to the human withAuth path; mock Better-Auth
// to "no session" so a no-auth request yields the human-path 401 rather than a
diff --git a/src/web/src/app/api/community/servers/route.human.test.ts b/src/web/src/app/api/community/servers/route.human.test.ts
index 6b826f776..8f736d612 100644
--- a/src/web/src/app/api/community/servers/route.human.test.ts
+++ b/src/web/src/app/api/community/servers/route.human.test.ts
@@ -8,7 +8,7 @@ const mocks = vi.hoisted(() => ({
listUnreadMentionSources: vi.fn(),
}))
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({ kind: "db" })) }))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({ kind: "db" })), getPrimaryDb: vi.fn(() => ({ kind: "db" })) }))
vi.mock("@/lib/community/storage", () => ({
serverIconUrl: vi.fn((row: { icon?: string | null }) => row.icon ?? null),
}))
@@ -48,6 +48,7 @@ vi.mock("@alook/shared", async () => {
})
import { GET } from "./route"
+import { getDb, getPrimaryDb } from "@/lib/db"
describe("GET /api/community/servers — human unread seed", () => {
beforeEach(() => {
@@ -82,6 +83,8 @@ describe("GET /api/community/servers — human unread seed", () => {
const response = await GET(new NextRequest("http://localhost/api/community/servers"))
expect(response.status).toBe(200)
+ expect(getPrimaryDb).toHaveBeenCalledOnce()
+ expect(getDb).not.toHaveBeenCalled()
await expect(response.json()).resolves.toEqual({
servers: [
{
diff --git a/src/web/src/app/api/community/servers/route.test.ts b/src/web/src/app/api/community/servers/route.test.ts
index 0eadc3b21..2e536156f 100644
--- a/src/web/src/app/api/community/servers/route.test.ts
+++ b/src/web/src/app/api/community/servers/route.test.ts
@@ -8,7 +8,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
}))
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})), getPrimaryDb: vi.fn(() => ({})) }))
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
diff --git a/src/web/src/app/api/community/servers/route.ts b/src/web/src/app/api/community/servers/route.ts
index eed74e524..28eaaaeb2 100644
--- a/src/web/src/app/api/community/servers/route.ts
+++ b/src/web/src/app/api/community/servers/route.ts
@@ -1,6 +1,6 @@
import { NextRequest } from "next/server"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
-import { getDb } from "@/lib/db"
+import { getDb, getPrimaryDb } from "@/lib/db"
import {
queries,
MAX_SERVER_NAME_LENGTH,
@@ -15,7 +15,7 @@ import { fanOutToServerMembers } from "@/lib/community/fanout"
import { canonicalUserImage, serverIconUrl } from "@/lib/community/storage"
export const GET = withCommunityActor(async (_req, ctx) => {
- const db = getDb(ctx.env.DB)
+ const db = getPrimaryDb(ctx.env.DB)
const rows = await withD1Retry(
() => queries.communityServer.listUserServers(db, ctx.actor.userId),
{ route: "community/servers:list" },
diff --git a/src/web/src/app/api/community/users/me/attention/route.test.ts b/src/web/src/app/api/community/users/me/attention/route.test.ts
index 81c21a4dc..87d5c8d0d 100644
--- a/src/web/src/app/api/community/users/me/attention/route.test.ts
+++ b/src/web/src/app/api/community/users/me/attention/route.test.ts
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest"
+import { COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
const mocks = vi.hoisted(() => ({
snapshot: vi.fn(),
@@ -39,6 +40,20 @@ import { GET } from "./route"
describe("GET /api/community/users/me/attention", () => {
beforeEach(() => vi.clearAllMocks())
+ it.each([undefined, "1", "2", "3"])("exposes exact DM counts only for the resource contract: %s", async (contract) => {
+ mocks.snapshot.mockResolvedValue({
+ scopes: [{ scopeId: "dm1", channelId: "dm1", serverId: null, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 5, unreadCount: 2, lastAttentionSeq: null, attentionCount: 0 }],
+ items: [], limit: 100, truncated: false,
+ included: { servers: [], channels: [], dms: [{ id: "dm1", userId: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0, lastMessageAt: "2026-10-24T00:00:00Z", lastUnreadSeq: 5 }], profiles: [{ userId: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0 }], messages: [] },
+ })
+ const headers = new Headers()
+ if (contract) headers.set(COMMUNITY_CONTRACT_HEADER, contract)
+ const response = await GET(new Request("http://localhost/api/community/users/me/attention", { headers }) as any)
+ const body = await response.json()
+ expect(response.status).toBe(200)
+ expect(body.scopes[0].unreadCount).toBe(contract === "3" ? 2 : undefined)
+ })
+
it("uses the primary-authoritative session for the stateless snapshot", async () => {
mocks.snapshot.mockResolvedValue({
scopes: [],
diff --git a/src/web/src/app/api/community/users/me/attention/route.ts b/src/web/src/app/api/community/users/me/attention/route.ts
index 31bc7fb71..e58f56067 100644
--- a/src/web/src/app/api/community/users/me/attention/route.ts
+++ b/src/web/src/app/api/community/users/me/attention/route.ts
@@ -4,6 +4,7 @@ import {
MAX_INBOX_PAGE_SIZE,
queries,
readOrStale,
+ requestedCommunityContract,
} from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
import { avatarInitial } from "@/lib/community/avatar"
@@ -52,6 +53,9 @@ export const GET = withAuth(async (request, ctx) => {
)
const normalized = {
...value,
+ scopes: requestedCommunityContract(request.headers) === 3
+ ? value.scopes
+ : value.scopes.map(({ unreadCount: _unreadCount, ...scope }) => scope),
included: {
...value.included,
dms: value.included.dms.map(canonicalizeIncludedAvatar),
diff --git a/src/web/src/app/api/community/users/me/channel-directory/route.test.ts b/src/web/src/app/api/community/users/me/channel-directory/route.test.ts
index 8ecb9814e..ffda1317e 100644
--- a/src/web/src/app/api/community/users/me/channel-directory/route.test.ts
+++ b/src/web/src/app/api/community/users/me/channel-directory/route.test.ts
@@ -4,7 +4,7 @@ import { NextRequest } from "next/server"
const listChannelRefDirectoryForUser = vi.fn()
const db = { scoped: true }
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => db) }))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: vi.fn(() => db) }))
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
diff --git a/src/web/src/app/api/community/users/me/channel-directory/route.ts b/src/web/src/app/api/community/users/me/channel-directory/route.ts
index 12adca965..99c082055 100644
--- a/src/web/src/app/api/community/users/me/channel-directory/route.ts
+++ b/src/web/src/app/api/community/users/me/channel-directory/route.ts
@@ -1,10 +1,10 @@
import { queries } from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { getPrimaryDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
export const GET = withAuth(async (_req, ctx) => {
- const db = getDb(ctx.env.DB)
+ const db = getPrimaryDb(ctx.env.DB)
const directory = await queries.communityChannel.listChannelRefDirectoryForUser(
db,
ctx.userId,
diff --git a/src/web/src/app/api/community/users/me/server-folders/route.test.ts b/src/web/src/app/api/community/users/me/server-folders/route.test.ts
index 5c9d9a590..5119d64bf 100644
--- a/src/web/src/app/api/community/users/me/server-folders/route.test.ts
+++ b/src/web/src/app/api/community/users/me/server-folders/route.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
const { listFolders } = vi.hoisted(() => ({ listFolders: vi.fn() }))
-vi.mock("@/lib/db", () => ({ getDb: () => ({ id: "db" }) }))
+vi.mock("@/lib/db", () => ({ getDb: () => ({ id: "db" }), getPrimaryDb: () => ({ id: "db" }) }))
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
return { ...actual, queries: { communityServerFolder: { listFolders } } }
@@ -18,10 +18,17 @@ import { GET } from "./route"
describe("GET server folders", () => {
it("retains the current account-scoped folder list", async () => {
const folders = [{ id: "folder", name: "Group", position: 0, servers: [{ id: "server", name: "Server" }] }]
- listFolders.mockResolvedValue(folders)
+ listFolders.mockResolvedValue({ folders, topOrder: [] })
const response = await GET(new NextRequest("http://localhost/api/community/users/me/server-folders"), {} as any)
expect(response.status).toBe(200)
- expect(await response.json()).toEqual({ folders })
+ expect(await response.json()).toEqual({ folders, topOrder: [] })
expect(listFolders).toHaveBeenCalledWith({ id: "db" }, "viewer")
})
+
+ it("returns the same account's saved mixed order", async () => {
+ const topOrder = [{ kind: "folder", id: "folder" }, { kind: "server", id: "server" }]
+ listFolders.mockResolvedValue({ folders: [], topOrder })
+ const response = await GET(new NextRequest("http://localhost/api/community/users/me/server-folders"), {} as any)
+ expect(await response.json()).toEqual({ folders: [], topOrder })
+ })
})
diff --git a/src/web/src/app/api/community/users/me/server-folders/route.ts b/src/web/src/app/api/community/users/me/server-folders/route.ts
index b36d79799..bbeebc6b6 100644
--- a/src/web/src/app/api/community/users/me/server-folders/route.ts
+++ b/src/web/src/app/api/community/users/me/server-folders/route.ts
@@ -1,11 +1,10 @@
import { NextRequest } from "next/server"
import { queries } from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { getPrimaryDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
export const GET = withAuth(async (_req: NextRequest, ctx) => {
- const db = getDb(ctx.env.DB)
- const folders = await queries.communityServerFolder.listFolders(db, ctx.userId)
- return writeJSON({ folders })
+ const db = getPrimaryDb(ctx.env.DB)
+ return writeJSON(await queries.communityServerFolder.listFolders(db, ctx.userId))
})
diff --git a/src/web/src/app/api/community/users/me/server-rail/route.test.ts b/src/web/src/app/api/community/users/me/server-rail/route.test.ts
index 51146b43d..0c41391c7 100644
--- a/src/web/src/app/api/community/users/me/server-rail/route.test.ts
+++ b/src/web/src/app/api/community/users/me/server-rail/route.test.ts
@@ -8,8 +8,10 @@ vi.mock("@opennextjs/cloudflare", () => ({
const mockReadSnapshot = vi.fn()
const mockApplyProjection = vi.fn()
+const mockBroadcast = vi.fn()
+vi.mock("@/lib/community/fanout", () => ({ broadcastToUserSafe: (...args: unknown[]) => mockBroadcast(...args) }))
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({ id: "db" })) }))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({ id: "db" })), getPrimaryDb: vi.fn(() => ({ id: "db" })) }))
vi.mock("nanoid", async () => {
const actual = await vi.importActual<typeof import("nanoid")>("nanoid")
return { ...actual, nanoid: vi.fn(() => "folder_generated") }
@@ -38,8 +40,8 @@ vi.mock("@/lib/middleware/auth", () => ({
import { PATCH } from "./route"
const snapshot = {
- serverOrder: ["server_1", "server_2", "server_3"],
- folderOrder: ["folder_1"],
+ serverIds: ["server_1", "server_2", "server_3"],
+ folderIds: ["folder_1"],
folders: {
folder_1: { id: "folder_1", name: "Folder", serverIds: ["server_2"] },
},
@@ -57,6 +59,7 @@ describe("PATCH /api/community/users/me/server-rail", () => {
vi.clearAllMocks()
mockReadSnapshot.mockResolvedValue(snapshot)
mockApplyProjection.mockResolvedValue(undefined)
+ mockBroadcast.mockResolvedValue(undefined)
})
it("commits one validated projection and returns generated folder ids", async () => {
@@ -73,6 +76,8 @@ describe("PATCH /api/community/users/me/server-rail", () => {
await expect(response.json()).resolves.toEqual({
createdFolderIds: { temp_1: "folder_generated" },
})
+ expect(mockBroadcast).toHaveBeenCalledExactlyOnceWith("user_1", { type: "community:server_rail.changed" })
+ expect(mockApplyProjection.mock.invocationCallOrder[0]).toBeLessThan(mockBroadcast.mock.invocationCallOrder[0])
expect(mockReadSnapshot).toHaveBeenCalledWith({ id: "db" }, "user_1")
expect(mockApplyProjection).toHaveBeenCalledTimes(1)
expect(mockApplyProjection).toHaveBeenCalledWith(
@@ -88,15 +93,16 @@ describe("PATCH /api/community/users/me/server-rail", () => {
it.each([
["malformed JSON", "{"],
["empty commands", { commands: [] }],
- ["unknown fields", { commands: [{ kind: "reorder-servers", serverIds: snapshot.serverOrder, extra: true }] }],
- ["partial memberships", { commands: [{ kind: "reorder-servers", serverIds: ["server_1"] }] }],
- ["duplicate memberships", { commands: [{ kind: "reorder-servers", serverIds: ["server_1", "server_1", "server_3"] }] }],
+ ["unknown fields", { commands: [{ kind: "reorder-servers", serverIds: snapshot.serverIds, extra: true }] }],
+ ["partial root set", { commands: [{ kind: "reorder-top-level", entries: [{ kind: "server", id: "server_1" }] }] }],
+ ["duplicate root set", { commands: [{ kind: "reorder-top-level", entries: [{ kind: "server", id: "server_1" }, { kind: "server", id: "server_1" }] }] }],
["foreign folder", { commands: [{ kind: "delete-folder", folderId: "folder_foreign" }] }],
])("rejects %s without a write", async (_name, body) => {
const response = await PATCH(patchRequest(body), {} as any)
expect(response.status).toBeGreaterThanOrEqual(400)
expect(mockApplyProjection).not.toHaveBeenCalled()
+ expect(mockBroadcast).not.toHaveBeenCalled()
})
it("rejects an oversized UTF-8 body before reading a snapshot", async () => {
@@ -108,14 +114,15 @@ describe("PATCH /api/community/users/me/server-rail", () => {
expect(response.status).toBe(413)
expect(mockReadSnapshot).not.toHaveBeenCalled()
expect(mockApplyProjection).not.toHaveBeenCalled()
+ expect(mockBroadcast).not.toHaveBeenCalled()
})
it("accepts a complete 125-membership reorder without cardinality rejection", async () => {
- const serverOrder = Array.from({ length: 125 }, (_, index) => `server_${index}`)
- mockReadSnapshot.mockResolvedValue({ serverOrder, folderOrder: [], folders: {} })
+ const serverIds = Array.from({ length: 125 }, (_, index) => `server_${index}`)
+ mockReadSnapshot.mockResolvedValue({ serverIds, folderIds: [], folders: {} })
const response = await PATCH(patchRequest({
- commands: [{ kind: "reorder-servers", serverIds: [...serverOrder].reverse() }],
+ commands: [{ kind: "reorder-top-level", entries: [...serverIds].reverse().map((id) => ({ kind: "server", id })) }],
}), {} as any)
expect(response.status).toBe(200)
@@ -129,5 +136,12 @@ describe("PATCH /api/community/users/me/server-rail", () => {
expect(response.status).toBe(404)
expect(mockApplyProjection).not.toHaveBeenCalled()
+ expect(mockBroadcast).not.toHaveBeenCalled()
})
+ it("does not broadcast a failed atomic save", async () => {
+ mockApplyProjection.mockRejectedValue(new Error("D1 write failed"))
+ await expect(PATCH(patchRequest({ commands: [{ kind: "delete-folder", folderId: "folder_1" }] }), {} as any)).rejects.toThrow("D1 write failed")
+ expect(mockBroadcast).not.toHaveBeenCalled()
+ })
+
})
diff --git a/src/web/src/app/api/community/users/me/server-rail/route.ts b/src/web/src/app/api/community/users/me/server-rail/route.ts
index 6f55d5da2..1c99d0298 100644
--- a/src/web/src/app/api/community/users/me/server-rail/route.ts
+++ b/src/web/src/app/api/community/users/me/server-rail/route.ts
@@ -1,11 +1,13 @@
import { nanoid } from "nanoid"
import {
MAX_SERVER_RAIL_REQUEST_BYTES,
+ WS_EVENTS,
projectServerRailCommit,
queries,
serverRailCommitRequestSchema,
} from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { broadcastToUserSafe } from "@/lib/community/fanout"
+import { getPrimaryDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
@@ -25,7 +27,7 @@ export const PATCH = withAuth(async (req, ctx) => {
const request = serverRailCommitRequestSchema.safeParse(parsedBody)
if (!request.success) return writeError("invalid server rail commands", 400)
- const db = getDb(ctx.env.DB)
+ const db = getPrimaryDb(ctx.env.DB)
const snapshot = await queries.communityServerRail.readServerRailSnapshot(db, ctx.userId)
const projection = projectServerRailCommit(snapshot, request.data, () => nanoid())
if (!projection.ok) return writeError(projection.error, projection.status)
@@ -36,5 +38,7 @@ export const PATCH = withAuth(async (req, ctx) => {
projection.value,
)
+ await broadcastToUserSafe(ctx.userId, { type: WS_EVENTS.SERVER_RAIL_CHANGED })
+
return writeJSON({ createdFolderIds: projection.value.createdFolderIds })
})
diff --git a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts b/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
index 76b262d6b..8caeb55bb 100644
--- a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
+++ b/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
@@ -208,7 +208,6 @@ vi.mock("@/hooks/community/mutations", async () => {
useCreateChannel: mutation,
useRenameChannel: mutation,
useDeleteChannel: mutation,
- useMoveChannel: mutation,
useCreateCategory: mutation,
useUpdateCategory: mutation,
useDeleteCategory: mutation,
diff --git a/src/web/src/components/community/channels/channel-dnd.tsx b/src/web/src/components/community/channels/channel-dnd.tsx
new file mode 100644
index 000000000..38bb7485b
--- /dev/null
+++ b/src/web/src/components/community/channels/channel-dnd.tsx
@@ -0,0 +1,150 @@
+"use client"
+
+import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef, type ReactNode } from "react"
+import { useDrag, useDragDropManager, useDragLayer, useDrop, type DropTargetMonitor } from "react-dnd"
+import { useDndCancellation } from "../community-dnd"
+import { projectChannelTreeDrop, resolveChannelTreeDrop, type ChannelTree, type ChannelTreeDrop, type ChannelTreeEntity } from "./use-channel-tree"
+
+const CHANNEL_ITEM = "community/channel-tree"
+type Item = ChannelTreeEntity & { owner: object }
+type TargetId = ReturnType<DropTargetMonitor["getHandlerId"]>
+type Controller = {
+ owner: object
+ begin: (entity: ChannelTreeEntity) => Item
+ finish: (item?: Item, result?: ChannelTreeDrop | null) => void
+ resolve: (item: Item, result: ChannelTreeDrop) => ChannelTreeDrop | null
+ suppressClick: () => boolean
+ resumeClick: () => void
+}
+const ChannelDndContext = createContext<Controller | null>(null)
+
+export function ChannelDndScope({ tree, onDrop, enabled = true, children }: {
+ tree: ChannelTree
+ onDrop: (event: ChannelTreeDrop) => void
+ enabled?: boolean
+ children: ReactNode
+}) {
+ const latest = useRef({ tree, onDrop, enabled })
+ useLayoutEffect(() => { latest.current = { tree, onDrop, enabled } })
+ const manager = useDragDropManager()
+ const owner = useMemo(() => ({}), [])
+ const current = useRef<Item | null>(null)
+ const suppressed = useRef(false)
+ const finish = useCallback((item?: Item, result?: ChannelTreeDrop | null) => {
+ if (!current.current) return
+ current.current = null
+ suppressed.current = true
+ if (item?.owner === owner && result && latest.current.enabled && projectChannelTreeDrop(latest.current.tree, result)) latest.current.onDrop(result)
+ }, [owner])
+ useDndCancellation(useCallback(() => finish(), [finish]))
+ useLayoutEffect(() => () => {
+ current.current = null
+ if ((manager.getMonitor().getItem() as Item | null)?.owner === owner && manager.getMonitor().isDragging()) manager.getActions().endDrag()
+ }, [manager, owner])
+ const controller = useMemo<Controller>(() => ({
+ owner, finish,
+ begin: (entity) => { const item = { ...entity, owner }; current.current = item; suppressed.current = false; return item },
+ resolve: (item, result) => item.owner === owner && latest.current.enabled ? resolveChannelTreeDrop(latest.current.tree, result) : null,
+ suppressClick: () => !!current.current || suppressed.current,
+ resumeClick: () => { if (!current.current) suppressed.current = false },
+ }), [owner, finish])
+ return <ChannelDndContext.Provider value={controller}>{children}</ChannelDndContext.Provider>
+}
+
+export function useChannelDragActive() {
+ const controller = useContext(ChannelDndContext)
+ return useDragLayer((monitor) => {
+ const item = monitor.getItem<Item>()
+ return monitor.isDragging() && monitor.getItemType() === CHANNEL_ITEM && item?.owner === controller?.owner ? item : null
+ })
+}
+
+export function useChannelDndItem(id: string, kind: ChannelTreeEntity["kind"], canReorder: boolean) {
+ const controller = useContext(ChannelDndContext)
+ const nativeMonitor = useDragDropManager().getMonitor()
+ const element = useRef<HTMLElement | null>(null)
+ const header = useRef<HTMLElement | null>(null)
+ const instruction = useCallback((item: Item, point: { x: number; y: number } | null, append = false): ChannelTreeDrop | null => {
+ if (!controller || !canReorder || !point) return null
+ const rect = (append ? header.current : element.current)?.getBoundingClientRect()
+ if (!rect) return null
+ const result: ChannelTreeDrop = { active: { id: item.id, kind: item.kind }, over: { id, kind },
+ placement: append ? "append" : point.y < rect.top + rect.height / 2 ? "before" : "after" }
+ return controller.resolve(item, result)
+ }, [controller, canReorder, id, kind])
+ const [{ isDragging }, drag, preview] = useDrag<Item, ChannelTreeDrop, { isDragging: boolean }>(() => ({
+ type: CHANNEL_ITEM,
+ canDrag: () => canReorder && !!controller,
+ item: () => controller?.begin({ id, kind }) ?? null,
+ end: (item, monitor) => controller?.finish(item, monitor.didDrop() ? monitor.getDropResult() : null),
+ collect: (monitor) => ({ isDragging: monitor.isDragging() }),
+ }), [controller, id, kind, canReorder])
+ const [{ rowTargetId }, drop] = useDrop<Item, ChannelTreeDrop, { rowTargetId: TargetId }>(() => ({
+ accept: CHANNEL_ITEM,
+ canDrop: (item, monitor) => (kind === "channel" || item.kind === "category") && !!instruction(item, monitor.getClientOffset()),
+ drop: (item, monitor) => monitor.didDrop() ? undefined : instruction(item, monitor.getClientOffset()) ?? undefined,
+ collect: (monitor) => ({ rowTargetId: monitor.getHandlerId() }),
+ }), [instruction, kind])
+ const [{ headerTargetId }, headerDrop] = useDrop<Item, ChannelTreeDrop, { headerTargetId: TargetId }>(() => ({
+ accept: CHANNEL_ITEM,
+ canDrop: (item, monitor) => kind === "category" && item.kind === "channel" && !!instruction(item, monitor.getClientOffset(), true),
+ drop: (item, monitor) => monitor.didDrop() ? undefined : instruction(item, monitor.getClientOffset(), true) ?? undefined,
+ collect: (monitor) => ({ headerTargetId: monitor.getHandlerId() }),
+ }), [instruction, kind])
+ const latestTargets = useRef({ rowTargetId, headerTargetId, instruction, kind })
+ useLayoutEffect(() => { latestTargets.current = { rowTargetId, headerTargetId, instruction, kind } })
+ const feedback = useDragLayer((monitor) => {
+ const item = monitor.getItem<Item>()
+ const current = latestTargets.current
+ const headerOver = current.headerTargetId !== null && nativeMonitor.isOverTarget(current.headerTargetId, { shallow: true }) && nativeMonitor.canDropOnTarget(current.headerTargetId)
+ const rowOver = current.rowTargetId !== null && nativeMonitor.isOverTarget(current.rowTargetId, { shallow: current.kind !== "category" }) && nativeMonitor.canDropOnTarget(current.rowTargetId)
+ return item && (rowOver || headerOver) ? current.instruction(item, monitor.getClientOffset(), headerOver)?.placement ?? null : null
+ })
+ const setNodeRef = useCallback((node: HTMLElement | null) => {
+ element.current = node; drop(node); preview(node)
+ if (kind === "channel") drag(canReorder ? node : null)
+ }, [drop, preview, drag, kind, canReorder])
+ const setActivatorNodeRef = useCallback((node: HTMLElement | null) => {
+ header.current = node; headerDrop(node); drag(canReorder ? node : null)
+ }, [drag, headerDrop, canReorder])
+ return {
+ setNodeRef, setActivatorNodeRef, isDragging, isOver: feedback !== null,
+ placement: feedback, lineSide: feedback === "after" ? "bottom" as const : "top" as const,
+ dragActive: useChannelDragActive(),
+ suppressClick: () => controller?.suppressClick() ?? false,
+ resumeClick: () => controller?.resumeClick(),
+ }
+}
+
+export function ChannelDropContainer({ id, before = false, lastRowId }: { id: string; before?: boolean; lastRowId?: string }) {
+ const controller = useContext(ChannelDndContext)
+ const anchor = useRef<HTMLDivElement | null>(null)
+ const lastRow = useRef<HTMLElement | null>(null)
+ useLayoutEffect(() => {
+ lastRow.current = Array.from(anchor.current?.parentElement?.querySelectorAll<HTMLElement>("[data-channel-tree-row]") ?? []).find((node) => node.dataset.channelTreeRow === lastRowId) ?? null
+ })
+ const instruction = useCallback((item: Item | null, point: { x: number; y: number } | null): ChannelTreeDrop | null => {
+ const rect = anchor.current?.getBoundingClientRect()
+ if (!item || item.kind !== "channel" || !point || !rect) return null
+ const top = rect.top - (before ? 16 : 0)
+ const row = lastRow.current?.getBoundingClientRect()
+ const overLast = row && point.x >= row.left && point.x <= row.right && point.y >= row.top + row.height / 2 && point.y < row.bottom
+ const overEnd = point.x >= rect.left && point.x <= rect.right && point.y >= top && point.y < top + 16
+ if (!overLast && !overEnd) return null
+ const result: ChannelTreeDrop = { active: { id: item.id, kind: item.kind }, over: { id, kind: "category" }, placement: "append" }
+ return controller?.resolve(item, result) ?? null
+ }, [controller, id, before])
+ const [, drop] = useDrop<Item, ChannelTreeDrop>(() => ({
+ accept: CHANNEL_ITEM,
+ canDrop: (item, monitor) => !!instruction(item, monitor.getClientOffset()),
+ drop: (item, monitor) => monitor.didDrop() ? undefined : instruction(item, monitor.getClientOffset()) ?? undefined,
+ }), [instruction])
+ const setDropRef = useCallback((node: HTMLDivElement | null) => { drop(node) }, [drop])
+ const latestInstruction = useRef(instruction)
+ useLayoutEffect(() => { latestInstruction.current = instruction })
+ const visible = useDragLayer((monitor) => !!latestInstruction.current(monitor.getItem<Item>(), monitor.getClientOffset()))
+ return <div ref={anchor} data-channel-drop-anchor={id} aria-hidden="true" className="relative h-0">
+ <div ref={setDropRef} data-channel-drop-end={id} data-drop-visible={visible || undefined}
+ className={`absolute inset-x-0 ${before ? "bottom-0" : "top-0"} ${visible ? "h-4 rounded-md border border-dashed border-primary bg-primary/5" : "pointer-events-none h-0"}`} />
+ </div>
+}
diff --git a/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts b/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts
index e386cf530..b85eee553 100644
--- a/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts
+++ b/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts
@@ -15,12 +15,6 @@ const emptyTree = {
catPending: {},
catCreators: {},
toggleCat: vi.fn(),
- removeChannel: vi.fn(),
- renameChannel: vi.fn(),
- markRead: vi.fn(),
- renameCategory: vi.fn(),
- onDragOver: vi.fn(),
- onDragEnd: vi.fn(),
} as unknown as ChannelTree
const render = () =>
@@ -156,18 +150,18 @@ describe("ChannelSidebar header", () => {
expect(html).not.toContain("text-[13px]")
expect(html).toContain("First post")
expect(html).toContain("Second post")
- expect(html).toContain("bg-primary")
+ expect(html).toMatch(/data-slot="community-channel-unread-indicator" class="[^"]*rounded-full[^"]* h-1"/)
})
it("suppresses the child unread dot when its parent forum is muted", () => {
- expect(renderForum(true)).not.toContain("bg-primary")
+ expect(renderForum(true)).not.toMatch(/data-slot="community-channel-unread-indicator" class="[^"]* h-1"/)
})
it("uses the active child shape without treating route activation as read", () => {
const html = renderForum(false, "post_1")
expect(html).toContain('data-testid="community-forum-sidebar-thread-post_1"')
expect(html).toContain('aria-current="page"')
- expect(html).not.toContain("bg-primary")
+ expect(html).not.toMatch(/data-slot="community-channel-unread-indicator" class="[^"]* h-1"/)
})
it("keeps hint-only private categories inert until live actions are installed", () => {
diff --git a/src/web/src/components/community/channels/channel-sidebar.navigation.dom.test.tsx b/src/web/src/components/community/channels/channel-sidebar.navigation.dom.test.tsx
index f4ca678a7..9681cc039 100644
--- a/src/web/src/components/community/channels/channel-sidebar.navigation.dom.test.tsx
+++ b/src/web/src/components/community/channels/channel-sidebar.navigation.dom.test.tsx
@@ -6,43 +6,72 @@ import { useChannelTree } from "./use-channel-tree"
vi.mock("next/link", async () => ({ default: (await import("@/test/community-link-mock")).CommunityLinkMock }))
-function Sidebar({ onPick, isAdmin = true, grouped = false, onReorder, unread = false, muted = false }: {
+function Sidebar({ onPick, isAdmin = true, grouped = false, onReorder, unread = false, muted = false, actions = false }: {
unread?: boolean
muted?: boolean
onPick: (id: string) => void
isAdmin?: boolean
grouped?: boolean
onReorder?: (ids: string[]) => void
+ actions?: boolean
}) {
const tree = useChannelTree([{ id: grouped ? "group" : "none", name: grouped ? "Group" : "", channels: [
{ id: "one", name: "One", active: false, unread: false, type: "text" },
{ id: "two", name: unread ? "design-feedback-with-a-long-channel-name" : "Two", active: false, unread, muted, type: "forum" },
] }])
return <ChannelSidebar tree={tree} serverId="server" serverName="Server" activeChannel="one"
- setActiveChannel={onPick} onReorderChannels={onReorder} noHeader isAdmin={isAdmin} />
+ setActiveChannel={onPick} onReorderChannels={onReorder} noHeader isAdmin={isAdmin}
+ onCreateChannel={actions ? async () => "created" : undefined} />
}
describe("real sortable channel navigation surface", () => {
- it("reserves a non-shrinking dot beside a long unread channel name", () => {
+ it("does not collapse an empty category before its first channel arrives", async () => {
+ function EmptyCategory({ filled }: { filled: boolean }) {
+ const tree = useChannelTree([{ id: "empty", name: "Empty", channels: filled ? [{ id: "first", name: "First", active: false, unread: false }] : [] }])
+ return <ChannelSidebar tree={tree} serverName="Server" activeChannel="" setActiveChannel={() => {}} noHeader />
+ }
+ const view = render(<EmptyCategory filled={false} />)
+ const header = view.getByTestId(tid.categoryHeader("empty"))
+ expect(header).not.toHaveAttribute("aria-expanded")
+ expect(header.querySelector(".lucide-chevron-down")).toBeNull()
+ await setupUser().click(header)
+ view.rerender(<EmptyCategory filled />)
+ expect(header).toHaveAttribute("aria-expanded", "true")
+ expect(header.querySelector(".lucide-chevron-down")).not.toBeNull()
+ expect(view.getByTestId(tid.channelRow("first"))).toBeVisible()
+ })
+ it("keeps nested category action keys separate from disclosure keys", async () => {
+ const view = render(<Sidebar onPick={vi.fn()} grouped actions />)
+ const header = view.getByTestId(tid.categoryHeader("group"))
+ const user = setupUser()
+ act(() => header.focus())
+ await user.keyboard("{Enter}")
+ expect(header).toHaveAttribute("aria-expanded", "false")
+ act(() => view.getByRole("button", { name: "Create channel in Group" }).focus())
+ await user.keyboard(" ")
+ expect(await view.findByRole("dialog")).toBeVisible()
+ expect(header).toHaveAttribute("aria-expanded", "false")
+ })
+ it("keeps a left half-dot outside the long channel name layout", () => {
const view = render(<Sidebar onPick={vi.fn()} unread />)
const row = view.getByTestId(tid.channelRow("two"))
expect(row.querySelector(".truncate")).toHaveTextContent("design-feedback-with-a-long-channel-name")
- expect(row.querySelector(".rounded-full.bg-primary")).toHaveClass("size-2", "shrink-0")
+ expect(row.querySelector('[data-slot="community-channel-unread-indicator"]')).toHaveClass("absolute", "-left-2", "rounded-r-full", "h-2.5")
})
it("does not show an unread dot for a muted channel", () => {
const view = render(<Sidebar onPick={vi.fn()} unread muted />)
- expect(view.getByTestId(tid.channelRow("two")).querySelector(".rounded-full.bg-primary")).toBeNull()
+ expect(view.getByTestId(tid.channelRow("two")).querySelector('[data-slot="community-channel-unread-indicator"]')).toHaveClass("h-0")
})
- it("keeps href and sortable attributes on the anchor and Enter activates once", async () => {
+ it("keeps href and drag attributes on the anchor and Enter activates once", async () => {
const onPick = vi.fn()
const view = render(<Sidebar onPick={onPick} />)
const anchor = view.getByTestId(tid.channelRow("two"))
expect(anchor.tagName).toBe("A")
expect(anchor).toHaveAttribute("role", "link")
expect(anchor).toHaveAttribute("href", "/c/channels/server/two")
- expect(anchor).toHaveAttribute("aria-roledescription", "sortable")
+ expect(anchor).toHaveAttribute("aria-roledescription", "draggable")
fireEvent.focus(anchor)
expect(anchor).toHaveAttribute("data-prefetch", "true")
act(() => anchor.focus())
@@ -50,17 +79,17 @@ describe("real sortable channel navigation surface", () => {
expect(onPick.mock.calls).toEqual([["two"]])
})
- it("Space starts reorder and Tab ends it without navigating", async () => {
+ it("Space and Tab keep ordinary link navigation without keyboard sorting", async () => {
const onPick = vi.fn()
const view = render(<Sidebar onPick={onPick} />)
const anchor = view.getByTestId(tid.channelRow("two"))
act(() => anchor.focus())
const user = setupUser()
await user.keyboard(" ")
- expect(anchor).toHaveAttribute("aria-pressed", "true")
+ expect(anchor).not.toHaveAttribute("aria-pressed")
expect(onPick).not.toHaveBeenCalled()
await user.keyboard("{Tab}")
- expect(view.getByText(/was dropped/i)).toBeInTheDocument()
+ expect(view.queryByText(/was dropped/i)).not.toBeInTheDocument()
expect(onPick).not.toHaveBeenCalled()
})
diff --git a/src/web/src/components/community/channels/channel-sidebar.touch-dnd.contract.test.ts b/src/web/src/components/community/channels/channel-sidebar.touch-dnd.contract.test.ts
deleted file mode 100644
index 49023a79d..000000000
--- a/src/web/src/components/community/channels/channel-sidebar.touch-dnd.contract.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { readFileSync } from "node:fs"
-import { describe, expect, it } from "vitest"
-
-const readSource = (relativePath: string) =>
- readFileSync(new URL(relativePath, import.meta.url), "utf8")
-
-describe("channel sidebar touch drag contracts", () => {
- it("uses input-specific sensors with the agreed activation constraints", () => {
- const sidebar = readSource("./channel-sidebar.tsx")
-
- expect(sidebar).toContain(
- "useSensor(MouseSensor, { activationConstraint: { distance: 5 } })",
- )
- expect(sidebar).toContain(
- "useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } })",
- )
- expect(sidebar).toContain(
- "useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates, keyboardCodes: { start: [\"Space\"], cancel: [\"Escape\"], end: [\"Space\", \"Enter\", \"Tab\"] } })",
- )
- expect(sidebar).toContain("collisionDetection={channelSidebarCollisionDetection}")
- expect(sidebar).toContain('activeData?.kind !== "category"')
- expect(sidebar).toContain("containerId === containerId")
- expect(sidebar).toContain("catOrder.includes(activeStr)")
- expect(sidebar).not.toContain("PointerSensor")
- })
-
- it("keeps the whole channel row and category header draggable without blocking touch scroll", () => {
- const channel = readSource("./sortable-channel.tsx")
- const category = readSource("./sortable-category.tsx")
-
- expect(channel).toContain("onClick={onClick}")
- expect(channel).toContain("onActivate={onClick}")
- expect(category).toContain("onClick: onToggle")
- expect(category).toContain('data: { kind: "category" }')
- expect(category).toContain("ref: setActivatorNodeRef")
- expect(category).toContain("onTouchStartCapture: listeners?.onTouchStart")
- expect(category).not.toContain("useDroppable")
-
- for (const source of [channel, category]) {
- expect(source).toContain("...listeners")
- expect(source).toContain("touch-manipulation")
- expect(source).not.toContain("touch-none")
- }
- })
-})
diff --git a/src/web/src/components/community/channels/channel-sidebar.tsx b/src/web/src/components/community/channels/channel-sidebar.tsx
index a9d843980..bdd7a60d5 100644
--- a/src/web/src/components/community/channels/channel-sidebar.tsx
+++ b/src/web/src/components/community/channels/channel-sidebar.tsx
@@ -5,13 +5,10 @@ import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { OfficialServerBadge } from "../official-server-badge"
import { CommunityNavigationLink } from "../shell/community-navigation-link"
import { channelHref } from "@/lib/community/community-route"
-import { Fragment, memo, useEffect, useRef, type MouseEvent } from "react"
+import { Fragment, memo, useEffect, useRef, type ComponentProps, type MouseEvent } from "react"
import { Settings, Users, Link2, Bell, ChevronDown, UserPlus } from "lucide-react"
-import {
- DndContext, KeyboardSensor, MouseSensor, TouchSensor, closestCenter, useSensor, useSensors, useDndContext,
- type CollisionDetection,
-} from "@dnd-kit/core"
-import { SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from "@dnd-kit/sortable"
+import { CommunityDndProvider, useCommunityDndScrolling } from "../community-dnd"
+import { ChannelDndScope, ChannelDropContainer, useChannelDragActive } from "./channel-dnd"
import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem } from "@/components/ui/context-menu"
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"
import { Skeleton } from "@/components/ui/skeleton"
@@ -20,15 +17,16 @@ import { SortableChannel, PendingChannelRow } from "./sortable-channel"
import { CreateChannelDialog } from "../settings/create-channel-dialog"
import { CreateCategoryDialog } from "../settings/create-category-dialog"
import { CategorySettingsDialog } from "../settings/category-settings-dialog"
-import { catId, catOf, reorderChannelsWithin, type ChannelTree } from "./use-channel-tree"
+import { projectChannelTreeDrop, type ChannelCategoryMove, type ChannelTree, type ChannelTreeDrop } from "./use-channel-tree"
import { InviteDialog } from "../social/invite-dialog"
import { ChannelAddMembersDialog } from "../members/channel-add-members-dialog"
import type { Channel } from "@/lib/community/models/navigation"
import type { SettingsSection } from "@/components/community/settings/settings-types"
-import { UNCATEGORIZED_CATEGORY_ID, type ChannelType } from "@alook/shared"
+import type { ChannelType } from "@alook/shared"
import { tid } from "@/lib/community/testids"
import type { ForumSidebarThread } from "@/hooks/community/use-forum-sidebar-threads"
import { selectUnreadPresentation } from "@/hooks/community/unread-presentation"
+import { ChannelUnreadIndicator } from "./channel-unread-indicator"
type Dialog =
@@ -39,24 +37,6 @@ type Dialog =
| { kind: "manage-members"; channelId: string; channelName: string }
| null
-type SortableData = { kind?: "category" | "channel"; sortable?: { containerId?: string } }
-
-const channelSidebarCollisionDetection: CollisionDetection = (args) => {
- const activeData = args.active.data.current as SortableData | undefined
- if (args.pointerCoordinates && activeData?.kind !== "category") return closestCenter(args)
-
- const containerId = activeData?.sortable?.containerId
- if (!containerId) return closestCenter(args)
-
- const sameContainer = args.droppableContainers.filter((container) =>
- (container.data.current as SortableData | undefined)?.sortable?.containerId === containerId)
- return closestCenter({ ...args, droppableContainers: sameContainer })
-}
-
-// The channel sidebar (server view). Category/channel reorder + add/remove/rename live in
-// useChannelTree. The category gear/right-click opens settings; "+" (or empty-space
-// right-click) creates; channels right-click to edit/delete. A private category only
-// lets admins create channels — non-admins are blocked via onBlockedCreate.
export type ChannelSidebarProps = {
tree: ChannelTree
serverName: string
@@ -67,6 +47,7 @@ export type ChannelSidebarProps = {
noHeader?: boolean
onOpenSettings?: (section?: SettingsSection) => void
isAdmin?: boolean
+ reorderPending?: boolean
currentUserId?: string
onBlockedCreate?: () => void
mutedChannels?: Record<string, boolean>
@@ -77,9 +58,7 @@ export type ChannelSidebarProps = {
onUpdateCategory?: (categoryId: string, opts: { name?: string }) => void
onRenameChannel?: (channelId: string, name: string) => void
onReorderCategories?: (categoryIds: string[]) => void
- onReorderChannels?: (channelIds: string[]) => void
- onMoveChannel?: (channelId: string, categoryId: string | null) => void
- onBlockedMove?: () => void
+ onReorderChannels?: (channelIds: string[], move?: ChannelCategoryMove) => void
serverId?: string
invitePopoverOpen?: boolean
onInvitePopoverOpenChange?: (open: boolean) => void
@@ -88,16 +67,17 @@ export type ChannelSidebarProps = {
onSelectForumThread?: (parentId: string, id: string) => void
}
-export const ChannelSidebar = memo(function ChannelSidebar({
+function ChannelSidebarContent({
tree, serverName, official, activeChannel, setActiveChannel, noHeader, onOpenSettings,
- isAdmin = true, currentUserId, onBlockedCreate, mutedChannels,
+ isAdmin = true, reorderPending = false, currentUserId, onBlockedCreate, mutedChannels,
onCreateChannel, onCreateCategory, onDeleteChannel, onDeleteCategory,
onUpdateCategory, onRenameChannel, onReorderCategories, onReorderChannels,
- onMoveChannel, onBlockedMove,
serverId, invitePopoverOpen, onInvitePopoverOpenChange,
forumThreadsByParent = {}, activeThreadId, onSelectForumThread,
}: ChannelSidebarProps) {
- const { collapsed, catOrder, order, catNames, catPrivate, catPending, toggleCat, onDragOver, onDragEnd: treeDragEnd } = tree
+ const { collapsed, catOrder, order, catNames, catPrivate, catPending, toggleCat } = tree
+ const scrollRef = useRef<HTMLDivElement>(null)
+ useCommunityDndScrolling(scrollRef, "community/channel-tree")
const menuActionsRef = useRef<ContextMenuPrimitive.Root.Actions | null>(null)
useEffect(() => {
if (!isAdmin) {
@@ -105,78 +85,13 @@ export const ChannelSidebar = memo(function ChannelSidebar({
menuActionsRef.current?.unmount()
}
}, [isAdmin])
- // Category the dragged channel started in — captured at drag start, because
- // `onDragOver` mutates `order` mid-drag so by drop time it already reflects
- // the destination.
- const dragOriginCat = useRef<string | undefined>(undefined)
- const onDragStart = (e: { active: { id: string | number } }) => {
- const activeStr = String(e.active.id)
- dragOriginCat.current = catOrder.includes(activeStr) ? undefined : catOf(activeStr, order)
- }
- const onDragEnd = (e: Parameters<typeof treeDragEnd>[0]) => {
- const originCat = dragOriginCat.current
- dragOriginCat.current = undefined
- treeDragEnd(e)
- const { active, over } = e
- if (!over || active.id === over.id) return
- const activeStr = String(active.id)
- const overStr = String(over.id)
- const activeIsCategory = catOrder.includes(activeStr)
- const overIsCategory = catOrder.includes(overStr)
- if (activeIsCategory && overIsCategory) {
- const reordered = catOrder.indexOf(activeStr) !== -1 ? (() => {
- const from = catOrder.indexOf(activeStr)
- const to = catOrder.indexOf(overStr)
- if (from === -1 || to === -1) return null
- const next = [...catOrder]
- const [item] = next.splice(from, 1)
- next.splice(to, 0, item)
- return next
- })() : null
- // Never send an optimistic (pending) category id to the reorder endpoint.
- if (reordered) onReorderCategories?.(reordered.filter((cid) => !catPending[cid]))
- } else if (!activeIsCategory) {
- // The channel's category AFTER onDragOver settled the optimistic move.
- const destCat = catOf(activeStr, order)
- // A blocked public↔private move: the cursor landed in a different-privacy
- // category, so onDragOver refused to move it and destCat === originCat.
- // Detect the attempt from the drop target and warn.
- const dropTargetCat = overIsCategory ? overStr : catOf(overStr, order)
- if (
- originCat && dropTargetCat && dropTargetCat !== originCat &&
- destCat === originCat &&
- !!catPrivate[originCat] !== !!catPrivate[dropTargetCat]
- ) {
- onBlockedMove?.()
- return
- }
- // Persist a same-privacy cross-category move: write the new categoryId
- // (translating the synthetic uncategorized bucket to null), then reorder.
- //
- // `treeDragEnd(e)` above settles the drop via `setOrder(...)`, which only
- // applies on the NEXT render — so the `order` closure here is still the
- // PRE-drop order for a same-category reorder (`onDragOver` never touched
- // it in that case). Reading it directly would PATCH the old sequence and
- // the reorder wouldn't persist. Recompute the settled order synchronously
- // from the same pure helper `treeDragEnd` uses. Cross-category is already
- // settled by `onDragOver`, and re-settling within the destination is
- // idempotent — so this is correct for both paths.
- const settledOrder = reorderChannelsWithin(order, activeStr, overStr)
- const allChannelIds = catOrder.flatMap((cat) => (settledOrder[cat] ?? []).filter((c) => !c.pending).map((c) => c.id))
- if (destCat && originCat && destCat !== originCat) {
- // The uncategorized bucket (empty name, synthetic id) maps back to a
- // real `categoryId: null` for the PATCH.
- const isUncategorized = catNames[destCat] === "" || destCat === UNCATEGORIZED_CATEGORY_ID
- onMoveChannel?.(activeStr, isUncategorized ? null : destCat)
- }
- onReorderChannels?.(allChannelIds)
- }
+ const canReorder = isAdmin && !reorderPending
+ const onDragEnd = (event: ChannelTreeDrop) => {
+ const commit = projectChannelTreeDrop(tree, event)
+ if (!commit || !canReorder) return
+ if ("categoryIds" in commit) onReorderCategories?.(commit.categoryIds)
+ else onReorderChannels?.(commit.channelIds, commit.move)
}
- const sensors = useSensors(
- useSensor(MouseSensor, { activationConstraint: { distance: 5 } }),
- useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } }),
- useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates, keyboardCodes: { start: ["Space"], cancel: ["Escape"], end: ["Space", "Enter", "Tab"] } }),
- )
const [dialog, setDialog] = useAtom(useCreateAtom<Dialog>(null))
const withMute = (ch: Channel): Channel => mutedChannels && ch.id in mutedChannels ? { ...ch, muted: mutedChannels[ch.id] } : ch
const hasActiveSidebarThread = !!activeThreadId && Object.values(forumThreadsByParent)
@@ -242,13 +157,12 @@ export const ChannelSidebar = memo(function ChannelSidebar({
if (id) setActiveChannel(id)
}
- // one DndContext spans everything: categories sort among themselves, channels across categories
const channelTree = (
- <DndContext id="d-channels" sensors={sensors} collisionDetection={channelSidebarCollisionDetection} onDragStart={onDragStart} onDragOver={onDragOver} onDragEnd={onDragEnd}>
+ <ChannelDndScope tree={tree} onDrop={onDragEnd} enabled={canReorder}>
{/* uncategorized channels (empty-name category) render bare at the top — no header */}
- {noneCatId && order[noneCatId]?.length > 0 && (
- <SortableContext items={order[noneCatId].filter((c) => !c.pending).map((c) => c.id)} strategy={verticalListSortingStrategy}>
- <div className="mb-4 space-y-1">
+ {noneCatId && (
+ <div className={order[noneCatId].length > 0 ? "mb-4" : ""}>
+ <div className="space-y-1">
{order[noneCatId].map((ch) => ch.pending ? (
<PendingChannelRow key={ch.id} ch={ch} />
) : (
@@ -257,7 +171,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({
ch={withMute(ch)}
href={serverId ? channelHref(serverId, ch.id) : undefined}
active={ch.id === activeChannel && !hasActiveSidebarThread}
- canReorder={isAdmin}
+ canReorder={canReorder}
onClick={() => setActiveChannel(ch.id)}
onEdit={isAdmin ? () => setDialog({ kind: "edit-channel", id: ch.id, categoryId: noneCatId, name: ch.name, type: ch.type ?? "text" }) : undefined}
onDelete={isAdmin ? () => onDeleteChannel?.(ch.id) : undefined}
@@ -266,13 +180,14 @@ export const ChannelSidebar = memo(function ChannelSidebar({
</Fragment>
))}
</div>
- </SortableContext>
+ <ChannelDropContainer id={noneCatId} before={order[noneCatId].length === 0} lastRowId={order[noneCatId].filter((channel) => !channel.pending).at(-1)?.id} />
+ </div>
)}
- <SortableContext items={catOrder.filter((id) => catNames[id] !== "" && !catPending[id]).map((id) => catId(id))} strategy={verticalListSortingStrategy}>
+
{catOrder.filter((id) => catNames[id] !== "").map((id) => (
<SortableCategory
key={id}
- id={catId(id)}
+ id={id}
name={catNames[id] ?? id}
open={!collapsed.has(id)}
onToggle={() => toggleCat(id)}
@@ -280,11 +195,12 @@ export const ChannelSidebar = memo(function ChannelSidebar({
onSettings={!catPending[id] && isAdmin ? () => setDialog({ kind: "category-settings", categoryId: id }) : undefined}
onDelete={!catPending[id] && isAdmin ? () => onDeleteCategory?.(id) : undefined}
isPrivate={catPrivate[id]}
- canReorder={isAdmin && !catPending[id]}
+ canReorder={canReorder && !catPending[id]}
pending={catPending[id]}
+ hasChannels={(order[id]?.length ?? 0) > 0}
>
- <SortableContext items={(order[id] ?? []).filter((c) => !c.pending).map((c) => c.id)} strategy={verticalListSortingStrategy}>
- <div className="mt-1 min-h-2 space-y-1">
+ <div className={(order[id]?.length ?? 0) > 0 ? "mt-1" : ""}>
+ <div className="space-y-1">
{(order[id] ?? []).map((ch) => {
if (ch.pending) return <PendingChannelRow key={ch.id} ch={ch} />
// Manage/edit rights:
@@ -298,7 +214,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({
ch={withMute(ch)}
href={serverId ? channelHref(serverId, ch.id) : undefined}
active={ch.id === activeChannel && !hasActiveSidebarThread}
- canReorder={isAdmin}
+ canReorder={canReorder}
onClick={() => setActiveChannel(ch.id)}
onEdit={canManageChannel ? () => setDialog({ kind: "edit-channel", id: ch.id, categoryId: id, name: ch.name, type: ch.type ?? "text" }) : undefined}
onDelete={canManageChannel ? () => onDeleteChannel?.(ch.id) : undefined}
@@ -308,12 +224,12 @@ export const ChannelSidebar = memo(function ChannelSidebar({
</Fragment>
)
})}
+ </div>
+ <ChannelDropContainer id={id} lastRowId={order[id]?.filter((channel) => !channel.pending).at(-1)?.id} />
</div>
- </SortableContext>
</SortableCategory>
))}
- </SortableContext>
- </DndContext>
+ </ChannelDndScope>
)
return (
@@ -361,8 +277,10 @@ export const ChannelSidebar = memo(function ChannelSidebar({
)}
<ContextMenu disabled={!isAdmin} actionsRef={menuActionsRef}>
<ContextMenuTrigger
+ onTouchStart={(event) => { if (isAdmin) event.preventBaseUIHandler() }}
render={(
<div
+ ref={scrollRef}
data-testid={tid.channelSidebarScroll}
className="min-h-0 flex-1 overflow-y-auto px-2 py-4 thin-scrollbar scrollbar-none"
/>
@@ -420,6 +338,10 @@ export const ChannelSidebar = memo(function ChannelSidebar({
)}
</aside>
)
+}
+
+export const ChannelSidebar = memo(function ChannelSidebar(props: ComponentProps<typeof ChannelSidebarContent>) {
+ return <CommunityDndProvider><ChannelSidebarContent {...props} /></CommunityDndProvider>
})
function ForumSidebarThreadRow({
@@ -435,7 +357,7 @@ function ForumSidebarThreadRow({
muted: boolean
onClick: () => void
}) {
- const { active: dragActive } = useDndContext()
+ const dragActive = useChannelDragActive()
const unread = selectUnreadPresentation({
accountUnread: thread.unread,
active,
@@ -449,7 +371,7 @@ function ForumSidebarThreadRow({
event.stopPropagation()
},
className: [
- "ml-4 flex h-7 w-[calc(100%-1rem)] min-w-0 items-center rounded-md px-2 text-left text-xs font-medium focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
+ "relative ml-4 flex h-7 w-[calc(100%-1rem)] min-w-0 items-center rounded-md px-2 text-left text-xs font-medium focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
active
? "bg-sidebar-accent text-foreground"
: muted
@@ -461,7 +383,7 @@ function ForumSidebarThreadRow({
}
const content = (<>
<span className="truncate">{thread.title}</span>
- {unread.showDot && <span className="ml-auto size-2 shrink-0 rounded-full bg-primary" />}
+ <ChannelUnreadIndicator visible={unread.showDot} dot />
</>)
return (
<div className="relative h-7">
diff --git a/src/web/src/components/community/channels/channel-unread-indicator.tsx b/src/web/src/components/community/channels/channel-unread-indicator.tsx
new file mode 100644
index 000000000..f370262d5
--- /dev/null
+++ b/src/web/src/components/community/channels/channel-unread-indicator.tsx
@@ -0,0 +1,4 @@
+export function ChannelUnreadIndicator({ visible, hidden = false, dot = false }: { visible: boolean; hidden?: boolean; dot?: boolean }) {
+ return <span aria-hidden="true" data-slot="community-channel-unread-indicator"
+ className={`pointer-events-none absolute -left-2 top-1/2 w-1 -translate-y-1/2 ${dot ? "rounded-full" : "rounded-r-full"} bg-foreground transition-all duration-150 motion-reduce:transition-none ${visible && !hidden ? dot ? "h-1" : "h-2.5" : "h-0"}`} />
+}
diff --git a/src/web/src/components/community/channels/sortable-category.tsx b/src/web/src/components/community/channels/sortable-category.tsx
index fdc68a7c2..33f380bde 100644
--- a/src/web/src/components/community/channels/sortable-category.tsx
+++ b/src/web/src/components/community/channels/sortable-category.tsx
@@ -5,11 +5,11 @@ import { useEffect, useRef } from "react"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import type React from "react"
-import { ChevronDown, Plus, Settings, Lock, Trash2 } from "lucide-react"
-import { useSortable } from "@dnd-kit/sortable"
-import { CSS } from "@dnd-kit/utilities"
+import { ChevronDown, Plus, Settings, Folder, Lock, Trash2 } from "lucide-react"
+import { useChannelDndItem } from "./channel-dnd"
import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator } from "@/components/ui/context-menu"
import { ConfirmDialog } from "@/components/ui/confirm-dialog"
+import { tid } from "@/lib/community/testids"
import { DropLine } from "../drop-line"
export function hasCategoryMenu(h: { onAddChannel?: () => void; onSettings?: () => void; onDelete?: () => void }) {
@@ -20,7 +20,7 @@ export function hasCategoryMenu(h: { onAddChannel?: () => void; onSettings?: ()
// movement or a touch long-press distinguishes collapse from reorder. It is also a drop
// target so channels can be dropped onto it (including its empty space). Right-click
// (or the gear) opens Settings; the "+" creates a channel; a lock shows when private.
-export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChannel, onSettings, onDelete, isPrivate, canReorder = true, pending = false, children }: {
+export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChannel, onSettings, onDelete, isPrivate, canReorder = true, pending = false, hasChannels, children }: {
id: string
name: string
open: boolean
@@ -31,29 +31,30 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan
isPrivate?: boolean
canReorder?: boolean
pending?: boolean
+ hasChannels: boolean
children: React.ReactNode
}) {
const [confirmingDelete, setConfirmingDelete] = useAtom(useCreateAtom(false))
- const { attributes, listeners, setActivatorNodeRef, setNodeRef, transform, transition, isDragging, isOver, activeIndex, index } = useSortable({ id: catDndId, data: { kind: "category" }, disabled: !canReorder })
- const style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.4 : 1, zIndex: isDragging ? 10 : undefined }
- const showLine = isOver && !isDragging
- const lineSide: "top" | "bottom" = activeIndex !== -1 && activeIndex < index ? "bottom" : "top"
+ const { setActivatorNodeRef, setNodeRef, isDragging, isOver, placement, lineSide, suppressClick, resumeClick } = useChannelDndItem(catDndId, "category", canReorder)
+ const style = { opacity: isDragging ? 0.4 : 1, zIndex: isDragging ? 10 : undefined }
+ const showLine = isOver && !isDragging && placement !== "append"
const headerProps = {
ref: setActivatorNodeRef,
- ...(canReorder ? attributes : { role: "button", tabIndex: 0 }),
- ...listeners,
- onTouchStart: undefined,
- onTouchStartCapture: listeners?.onTouchStart
- ? (event: React.TouchEvent<HTMLDivElement>) => listeners.onTouchStart?.(event)
- : undefined,
- onClick: onToggle,
- className: `group flex w-full touch-manipulation items-center gap-1 rounded px-1 py-1 text-xs font-semibold text-muted-foreground/80 select-none hover:text-foreground ${canReorder ? "cursor-grab active:cursor-grabbing" : "cursor-pointer"}`,
+ "data-testid": tid.categoryHeader(catDndId),
+ "data-dragging": isDragging || undefined,
+ role: "button", tabIndex: 0,
+ "aria-label": name,
+ "aria-description": isPrivate ? "Private category" : "Public category",
+ "aria-expanded": hasChannels ? open : undefined,
+ onPointerDownCapture: resumeClick,
+ onKeyDownCapture: (event: React.KeyboardEvent) => { if (event.key === "Enter" || event.key === " ") resumeClick() },
+ onClick: () => { if (hasChannels && !suppressClick()) onToggle() },
+ onKeyDown: (event: React.KeyboardEvent) => { if (event.target === event.currentTarget && hasChannels && (event.key === "Enter" || event.key === " ")) { event.preventDefault(); if (!suppressClick()) onToggle() } },
+ className: `group flex w-full touch-manipulation items-center gap-1 rounded px-1 py-1 text-xs font-semibold text-muted-foreground/80 select-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none ${placement === "append" ? "bg-primary/5 ring-1 ring-primary" : ""} ${canReorder ? "cursor-grab active:cursor-grabbing" : "cursor-pointer"}`,
}
const headerInner = (
<>
- {/* Always reserve the lock's slot so public + private category names share
- the same left edge (private shows the Lock, public a same-size spacer). */}
- {isPrivate ? <Lock className="size-3 shrink-0" /> : <span className="size-3 shrink-0" aria-hidden="true" />}
+ {isPrivate ? <Lock className="size-3 shrink-0" aria-hidden="true" /> : <Folder className="size-3 shrink-0" aria-hidden="true" />}
<span className="flex-1 truncate text-left">{name}</span>
{onSettings && (
<button
@@ -75,7 +76,7 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan
<Plus className="size-3.5" />
</button>
)}
- <ChevronDown className={`size-3 shrink-0 transition-transform ${open ? "" : "-rotate-90"}`} />
+ {hasChannels && <ChevronDown className={`size-3 shrink-0 transition-transform ${open ? "" : "-rotate-90"}`} />}
</>
)
const hasMenu = hasCategoryMenu({ onAddChannel, onSettings, onDelete })
@@ -87,10 +88,10 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan
}
}, [hasMenu])
return (
- <div ref={setNodeRef} style={style} className={`relative mb-4 ${pending ? "opacity-60" : ""}`}>
+ <div ref={setNodeRef} data-channel-category={catDndId} style={style} className={`relative mb-4 ${pending ? "opacity-60" : ""}`}>
{showLine && <DropLine side={lineSide} />}
<ContextMenu disabled={!hasMenu} actionsRef={menuActionsRef}>
- <ContextMenuTrigger render={<div {...headerProps} />}>
+ <ContextMenuTrigger render={<div {...headerProps} />} onTouchStart={(event) => { if (canReorder) event.preventBaseUIHandler() }}>
{headerInner}
</ContextMenuTrigger>
{hasMenu && <ContextMenuContent className="w-48">
diff --git a/src/web/src/components/community/channels/sortable-channel.tsx b/src/web/src/components/community/channels/sortable-channel.tsx
index 9f9e174ea..83f2c5d67 100644
--- a/src/web/src/components/community/channels/sortable-channel.tsx
+++ b/src/web/src/components/community/channels/sortable-channel.tsx
@@ -7,14 +7,14 @@ import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { BellOff, Loader2, Pencil, Trash2, Users } from "lucide-react"
import { EntityIcon } from "../entity-icon"
-import { useSortable } from "@dnd-kit/sortable"
-import { CSS } from "@dnd-kit/utilities"
+import { useChannelDndItem } from "./channel-dnd"
import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator } from "@/components/ui/context-menu"
import { ConfirmDialog } from "@/components/ui/confirm-dialog"
import { DropLine } from "../drop-line"
import { tid } from "@/lib/community/testids"
import type { Channel } from "@/lib/community/models/navigation"
import { selectUnreadPresentation } from "@/hooks/community/unread-presentation"
+import { ChannelUnreadIndicator } from "./channel-unread-indicator"
export function hasChannelMenu(h: { onEdit?: () => void; onManageMembers?: () => void; onDelete?: () => void }) {
return !!(h.onEdit || h.onManageMembers || h.onDelete)
@@ -51,10 +51,10 @@ export function SortableChannel({ ch, href, active, onClick, onEdit, onDelete, o
canReorder?: boolean
}) {
const [confirmingDelete, setConfirmingDelete] = useAtom(useCreateAtom(false))
- const { attributes, listeners, setNodeRef, transform, transition, isDragging, isOver, activeIndex, index, active: dragActive } = useSortable({ id: ch.id, disabled: !canReorder })
- const style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.4 : 1, zIndex: isDragging ? 10 : undefined }
- const showLine = isOver && !isDragging
- const lineSide: "top" | "bottom" = activeIndex !== -1 && activeIndex < index ? "bottom" : "top"
+ const { setNodeRef, isDragging, isOver, placement, lineSide, dragActive, suppressClick, resumeClick } = useChannelDndItem(ch.id, "channel", canReorder)
+ const style = { opacity: isDragging ? 0.4 : 1, zIndex: isDragging ? 10 : undefined }
+ const showLine = isOver && !isDragging && placement !== "append"
+ const activate = () => { if (!suppressClick()) onClick() }
const unread = selectUnreadPresentation({
accountUnread: ch.unread,
active,
@@ -64,8 +64,13 @@ export function SortableChannel({ ch, href, active, onClick, onEdit, onDelete, o
ref: setNodeRef,
style,
"data-testid": tid.channelRow(ch.id),
- ...(canReorder ? attributes : { role: "button", tabIndex: 0 }),
- ...listeners,
+ "data-dragging": isDragging || undefined,
+ "data-channel-tree-row": ch.id,
+ "aria-roledescription": canReorder ? "draggable" : undefined,
+ role: "button", tabIndex: 0,
+ onPointerDownCapture: resumeClick,
+ onKeyDownCapture: (event: React.KeyboardEvent) => { if (event.key === "Enter" || event.key === " ") resumeClick() },
+ onClickCapture: (event: React.MouseEvent) => { if (suppressClick()) { event.preventDefault(); event.stopPropagation() } },
className: [
"group relative flex h-8 w-full cursor-pointer touch-manipulation items-center gap-2 rounded-md px-2 text-sm select-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
canReorder ? "active:cursor-grabbing" : "",
@@ -81,24 +86,23 @@ export function SortableChannel({ ch, href, active, onClick, onEdit, onDelete, o
const content = (
<>
{showLine && <DropLine side={lineSide} />}
+ <ChannelUnreadIndicator visible={unread.showDot} hidden={isDragging} />
<span className="grid size-5 shrink-0 place-items-center opacity-70">
<EntityIcon kind={ch.type} className="size-4" />
</span>
<span className="truncate font-semibold">{ch.name}</span>
{ch.muted ? (
<BellOff className="ml-auto size-4 shrink-0 opacity-70" />
- ) : unread.showDot ? (
- <span className="ml-auto size-2 shrink-0 rounded-full bg-primary" />
) : null}
</>
)
const row = href ? (
<CommunityNavigationLink {...rowProps} role="link" href={href} active={active}
- draggable={false} navigationDisabled={dragActive !== null} onActivate={onClick}>
+ navigationDisabled={dragActive !== null} onActivate={activate}>
{content}
</CommunityNavigationLink>
) : (
- <div {...rowProps} onClick={onClick}>{content}</div>
+ <div {...rowProps} onClick={activate}>{content}</div>
)
const hasMenu = hasChannelMenu({ onEdit, onManageMembers, onDelete })
const menuActionsRef = useRef<ContextMenuPrimitive.Root.Actions | null>(null)
@@ -111,7 +115,7 @@ export function SortableChannel({ ch, href, active, onClick, onEdit, onDelete, o
return (
<>
<ContextMenu disabled={!hasMenu} actionsRef={menuActionsRef}>
- <ContextMenuTrigger render={row} />
+ <ContextMenuTrigger render={row} onTouchStart={(event) => { if (canReorder) event.preventBaseUIHandler() }} />
{hasMenu && <ContextMenuContent className="w-48">
<div className="truncate px-2 py-2 text-xs font-semibold text-muted-foreground">/{ch.name}</div>
{onEdit && <ContextMenuItem onClick={onEdit}><Pencil className="size-4" /> Edit channel</ContextMenuItem>}
diff --git a/src/web/src/components/community/channels/use-channel-tree.dom.test.ts b/src/web/src/components/community/channels/use-channel-tree.dom.test.ts
index 55d35fc3a..26cd5c8a2 100644
--- a/src/web/src/components/community/channels/use-channel-tree.dom.test.ts
+++ b/src/web/src/components/community/channels/use-channel-tree.dom.test.ts
@@ -1,507 +1,112 @@
-import React from "react"
-import { act, render as rtlRender } from "@/test/react-dom-harness"
-import { describe, it, expect, vi } from "vitest"
+import { act, renderHook } from "@/test/react-dom-harness"
import { readFileSync } from "node:fs"
import { resolve } from "node:path"
-import {
- catId,
- catOf,
- moveChannelAcrossCategories,
- reorderChannelsWithin,
- reorderCategories,
- mergeChannelMetadata,
- useChannelTree,
- type ChannelOrder,
-} from "./use-channel-tree"
-import type { Channel, Category } from "@/lib/community/models/navigation"
-import type { DragEndEvent } from "@dnd-kit/core"
-
-const ch = (id: string): Channel => ({ id, name: id, active: false, unread: false })
-const category = (id: string, channels: Channel[]): Category => ({ id, name: id, channels })
-
-type Tree = ReturnType<typeof useChannelTree>
-
-function CaptureTree({ categories, onResult }: { categories: Category[]; onResult: (tree: Tree) => void }) {
- onResult(useChannelTree(categories))
- return null
-}
-
-function ReallocatedCaptureTree({ onResult }: { onResult: (tree: Tree) => void }) {
- const categories = [category("cat_A", [ch("a1"), ch("a2")])]
- onResult(useChannelTree(categories))
- return null
-}
-
-let nextOwnerId = 0
-
-function ScopedCaptureTree({
- scopeKey,
- categories,
- onResult,
-}: {
- scopeKey: string
- categories: Category[]
- onResult: (tree: Tree, ownerId: number) => void
-}) {
- return React.createElement(CaptureTreeOwner, {
- key: scopeKey,
- categories,
- onResult,
- })
-}
-
-function CaptureTreeOwner({
- categories,
- onResult,
-}: {
- categories: Category[]
- onResult: (tree: Tree, ownerId: number) => void
-}) {
- const [ownerId] = React.useState(() => ++nextOwnerId)
- onResult(useChannelTree(categories), ownerId)
- return null
-}
-
-async function renderTreeHook(categories: Category[]) {
- let current!: Tree
- await act(async () => {
- rtlRender(
- React.createElement(CaptureTree, { categories, onResult: (tree) => { current = tree } }),
- )
- })
- return {
- get current() {
- return current
- },
- async drag(callback: (tree: Tree) => void) {
- await act(async () => callback(current))
- },
- }
-}
-
-const dragEvent = (activeId: string, overId: string): DragEndEvent => ({
- active: { id: activeId },
- over: { id: overId },
-}) as DragEndEvent
-
-const order: ChannelOrder = {
- cat_A: [ch("a1"), ch("a2")],
- cat_B: [ch("b1"), ch("b2"), ch("b3")],
+import { describe, expect, it } from "vitest"
+import { UNCATEGORIZED_CATEGORY_ID } from "@alook/shared"
+import { catOf, projectChannelTreeDrop, resolveChannelTreeDrop, useChannelTree, type ChannelTreeDrop } from "./use-channel-tree"
+import type { Category, Channel } from "@/lib/community/models/navigation"
+
+const ch = (id: string, fields: Partial<Channel> = {}): Channel => ({ id, name: id, active: false, unread: false, ...fields })
+const categories: Category[] = [
+ { id: "opaque-a", name: "A", channels: [ch("text"), ch("forum", { type: "forum" }), ch("last")] },
+ { id: "opaque-b", name: "B", channels: [ch("b1"), ch("b2")] },
+ { id: "empty", name: "Empty", channels: [] },
+ { id: "private", name: "Private", private: true, channels: [ch("secret")] },
+ { id: "private2", name: "Private2", private: true, channels: [] },
+]
+const drop = (active: string, over: string, placement: ChannelTreeDrop["placement"], activeKind: "channel" | "category" = "channel", overKind: "channel" | "category" = "channel"): ChannelTreeDrop => ({ active: { id: active, kind: activeKind }, over: { id: over, kind: overKind }, placement })
+const treeFrom = (rows = categories) => renderHook(() => useChannelTree(rows)).result.current
+const channelIds = (tree: ReturnType<typeof useChannelTree>, event: ChannelTreeDrop) => {
+ const result = projectChannelTreeDrop(tree, event)
+ expect(result).not.toBeNull()
+ return result && "channelIds" in result ? result : null
}
-describe("id helpers", () => {
- it("keeps persisted category ids unchanged for dnd", () => {
- expect(catId("cat_A")).toBe("cat_A")
- expect(catId("5vg7bs")).toBe("5vg7bs")
- })
-})
-
-describe("catOf", () => {
- it("resolves the category holding a channel", () => {
- expect(catOf("a2", order)).toBe("cat_A")
- expect(catOf("b3", order)).toBe("cat_B")
- })
- it("resolves a category id to itself", () => {
- expect(catOf("cat_B", order)).toBe("cat_B")
- })
- it("resolves an opaque category id from the actual tree keys", () => {
- const opaqueOrder = { "5vg7bs": [ch("a1")] }
- expect(catOf("5vg7bs", opaqueOrder)).toBe("5vg7bs")
- })
- it("returns undefined for an unknown channel", () => {
- expect(catOf("zzz", order)).toBeUndefined()
- })
-})
-
-describe("moveChannelAcrossCategories", () => {
- it("relocates a channel into another category at the over index", () => {
- const next = moveChannelAcrossCategories(order, "a1", "b2")
- expect(next.cat_A.map((c) => c.id)).toEqual(["a2"])
- expect(next.cat_B.map((c) => c.id)).toEqual(["b1", "a1", "b2", "b3"])
- })
- it("is a no-op within the same category", () => {
- expect(moveChannelAcrossCategories(order, "a1", "a2")).toBe(order)
- })
- it("is a no-op for a missing channel", () => {
- expect(moveChannelAcrossCategories(order, "zzz", "b1")).toBe(order)
- })
-})
-
-describe("reorderChannelsWithin", () => {
- it("reorders channels inside one category", () => {
- const next = reorderChannelsWithin(order, "b1", "b3")
- expect(next.cat_B.map((c) => c.id)).toEqual(["b2", "b3", "b1"])
- })
- it("is a no-op when over is in a different category", () => {
- expect(reorderChannelsWithin(order, "a1", "b1")).toBe(order)
- })
-})
-
-// Regression: channel-sidebar's drop handler builds the reorder-PATCH payload
-// from the SETTLED order (reorderChannelsWithin applied synchronously), not the
-// stale pre-drop `order` closure. Same-category reorders previously PATCHed the
-// old sequence → positions rewritten unchanged → reorder didn't persist across
-// refresh. This pins that the payload derivation reflects the moved order.
-describe("reorder-PATCH payload derivation (channel-sidebar drop handler)", () => {
- const catOrder = ["cat_A", "cat_B"]
- const payloadFrom = (o: ChannelOrder) =>
- catOrder.flatMap((cat) => (o[cat] ?? []).map((c) => c.id))
-
- it("same-category drop: payload reflects the moved order, not the pre-drop order", () => {
- // Pre-drop order would yield b1,b2,b3 — the stale bug. Settled must move b1 past b3.
- const settled = reorderChannelsWithin(order, "b1", "b3")
- expect(payloadFrom(settled)).toEqual(["a1", "a2", "b2", "b3", "b1"])
- expect(payloadFrom(settled)).not.toEqual(payloadFrom(order))
- })
-
- it("re-settling an already-cross-category-settled order is idempotent for the payload", () => {
- // Cross-category is settled by onDragOver first; applying reorderChannelsWithin
- // to place it at the drop target within the destination must not corrupt it.
- const moved = moveChannelAcrossCategories(order, "a1", "b2") // a1 → cat_B before b2
- const settled = reorderChannelsWithin(moved, "a1", "b2")
- expect(payloadFrom(settled)).toContain("a1")
- // a1 left cat_A; cat_A now only a2.
- expect(settled.cat_A.map((c) => c.id)).toEqual(["a2"])
- })
-})
-
-describe("reorderCategories", () => {
- it("reorders the category id list", () => {
- expect(reorderCategories(["cat_A", "cat_B", "cat_C"], "cat_A", "cat_C")).toEqual(["cat_B", "cat_C", "cat_A"])
- })
- it("returns the input when a category is missing", () => {
- const cats = ["cat_A", "cat_B"]
- expect(reorderCategories(cats, "cat_Z", "cat_A")).toBe(cats)
- })
-})
-
-describe("useChannelTree opaque category drag callbacks", () => {
- const categories = [
- category("5vg7bs", [ch("a1"), ch("a2")]),
- category("9qsh2k", [ch("b1"), ch("b2")]),
- ]
-
- it("previews a same-privacy category move and settles the destination order", async () => {
- const moving = { ...ch("a1"), name: "Canonical channel", unread: true }
- const hook = await renderTreeHook([
- category("5vg7bs", [moving, ch("a2")]),
- category("9qsh2k", [ch("b1"), ch("b2")]),
- ])
-
- await hook.drag((tree) => tree.onDragOver(dragEvent("a1", "b2")))
-
- expect(hook.current.order["5vg7bs"].map((channel) => channel.id)).toEqual(["a2"])
- expect(hook.current.order["9qsh2k"].map((channel) => channel.id)).toEqual(["b1", "a1", "b2"])
- expect(hook.current.order["9qsh2k"][1]).toEqual(moving)
- const preview = hook.current.order
- await hook.drag((tree) => tree.onDragOver(dragEvent("a1", "b2")))
- expect(hook.current.order).toBe(preview)
-
- await hook.drag((tree) => tree.onDragEnd(dragEvent("a1", "b2")))
-
- expect(hook.current.order["5vg7bs"].map((channel) => channel.id)).toEqual(["a2"])
- expect(hook.current.order["9qsh2k"].map((channel) => channel.id)).toEqual(["b1", "b2", "a1"])
- expect(hook.current.order["9qsh2k"][2]).toEqual(moving)
- expect(hook.current.catOrder).toEqual(["5vg7bs", "9qsh2k"])
- })
-
- it("rejects a category move across the privacy boundary", async () => {
- const hook = await renderTreeHook([
- { ...category("5vg7bs", [ch("a1")]), private: true },
- category("9qsh2k", [ch("b1")]),
- ])
- const before = hook.current.order
-
- await hook.drag((tree) => tree.onDragOver(dragEvent("a1", "b1")))
-
- expect(hook.current.order).toBe(before)
- expect(hook.current.order["5vg7bs"].map((channel) => channel.id)).toEqual(["a1"])
- expect(hook.current.order["9qsh2k"].map((channel) => channel.id)).toEqual(["b1"])
- })
-
- it("ignores category drag-over instead of moving a channel", async () => {
- const hook = await renderTreeHook(categories)
- const before = hook.current.order
-
- await hook.drag((tree) => tree.onDragOver(dragEvent("5vg7bs", "b1")))
-
- expect(hook.current.order).toBe(before)
- expect(hook.current.order["5vg7bs"].map((channel) => channel.id)).toEqual(["a1", "a2"])
- expect(hook.current.order["9qsh2k"].map((channel) => channel.id)).toEqual(["b1", "b2"])
- })
-
- it("reorders opaque categories through the hook drop callback", async () => {
- const hook = await renderTreeHook(categories)
-
- await hook.drag((tree) => tree.onDragEnd(dragEvent("5vg7bs", "9qsh2k")))
-
- expect(hook.current.catOrder).toEqual(["9qsh2k", "5vg7bs"])
- })
-
- it("treats an opaque category dropped over a channel as a no-op", async () => {
- const hook = await renderTreeHook(categories)
- const beforeOrder = hook.current.order
- const beforeCatOrder = hook.current.catOrder
-
- await hook.drag((tree) => tree.onDragEnd(dragEvent("5vg7bs", "b1")))
-
- expect(hook.current.order).toBe(beforeOrder)
- expect(hook.current.catOrder).toBe(beforeCatOrder)
- })
-})
-
-describe("useChannelTree scope ownership", () => {
- const categoriesA: Category[] = [
- {
- id: "cat_A",
- name: "Alpha",
- private: true,
- pending: true,
- creatorId: "owner_A",
- channels: [ch("a1"), { ...ch("tmp_A"), pending: true }],
- },
- category("cat_A2", [ch("a2")]),
- ]
- const categoriesB: Category[] = [
- {
- id: "cat_B",
- name: "Beta",
- private: false,
- pending: false,
- creatorId: "owner_B",
- channels: [ch("b1"), ch("b2")],
- },
- ]
-
- it("preserves the seven state groups and callback owner under one stable key", async () => {
- nextOwnerId = 0
- let current!: Tree
- let ownerId = 0
- const onResult = (tree: Tree, id: number) => {
- current = tree
- ownerId = id
+describe("explicit channel tree instructions", () => {
+ it("uses one container append instruction for the final row's after edge", () => {
+ const tree = treeFrom()
+ expect(resolveChannelTreeDrop(tree, drop("text", "last", "after"))).toEqual(drop("text", "opaque-a", "append", "channel", "category"))
+ expect(resolveChannelTreeDrop(tree, drop("text", "b2", "after"))).toEqual(drop("text", "opaque-b", "append", "channel", "category"))
+ expect(resolveChannelTreeDrop(tree, drop("last", "text", "after"))).toEqual(drop("last", "text", "after"))
+ expect(resolveChannelTreeDrop(tree, drop("secret", "last", "after"))).toBeNull()
+ expect(resolveChannelTreeDrop(tree, drop("last", "opaque-a", "append", "channel", "category"))).toBeNull()
+ expect(resolveChannelTreeDrop(tree, drop("text", "missing", "after"))).toBeNull()
+ })
+ it("uses the pointer edge for mixed text/forum insertion in either direction", () => {
+ const tree = treeFrom()
+ expect(channelIds(tree, drop("text", "last", "before"))?.channelIds.slice(0, 3)).toEqual(["forum", "text", "last"])
+ expect(channelIds(tree, drop("text", "last", "after"))?.channelIds.slice(0, 3)).toEqual(["forum", "last", "text"])
+ expect(channelIds(tree, drop("last", "text", "before"))?.channelIds.slice(0, 3)).toEqual(["last", "text", "forum"])
+ expect(channelIds(tree, drop("last", "text", "after"))?.channelIds.slice(0, 3)).toEqual(["text", "last", "forum"])
+ expect(tree.order["opaque-a"].map((row) => row.id)).toEqual(["text", "forum", "last"])
+ })
+ it("projects category blocks before or after without persisting synthetic or pending categories", () => {
+ const tree = treeFrom([...categories, { id: "pending", name: "Pending", pending: true, channels: [] }])
+ expect(projectChannelTreeDrop(tree, drop("opaque-a", "private", "before", "category", "category"))).toEqual({ categoryIds: ["opaque-b", "empty", "opaque-a", "private", "private2"] })
+ expect(projectChannelTreeDrop(tree, drop("opaque-a", "private", "after", "category", "category"))).toEqual({ categoryIds: ["opaque-b", "empty", "private", "opaque-a", "private2"] })
+ expect(projectChannelTreeDrop(tree, drop("pending", "opaque-a", "before", "category", "category"))).toBeNull()
+ expect(projectChannelTreeDrop(tree, drop("opaque-a", UNCATEGORIZED_CATEGORY_ID, "before", "category", "category"))).toBeNull()
+ })
+ it("produces one category move plus the final order for an exact cross-category insertion", () => {
+ const tree = treeFrom()
+ expect(channelIds(tree, drop("text", "b1", "after"))).toEqual({ channelIds: ["forum", "last", "b1", "text", "b2", "secret"], move: { channelId: "text", categoryId: "opaque-b" } })
+ expect(channelIds(tree, drop("text", "opaque-b", "append", "channel", "category"))?.channelIds).toEqual(["forum", "last", "b1", "b2", "text", "secret"])
+ expect(channelIds(tree, drop("text", "empty", "append", "channel", "category"))?.move).toEqual({ channelId: "text", categoryId: "empty" })
+ })
+ it("supports an empty root bucket and private/private without crossing privacy", () => {
+ const tree = treeFrom()
+ expect(tree.order[UNCATEGORIZED_CATEGORY_ID]).toEqual([])
+ expect(channelIds(tree, drop("text", UNCATEGORIZED_CATEGORY_ID, "append", "channel", "category"))?.move).toEqual({ channelId: "text", categoryId: null })
+ expect(channelIds(tree, drop("secret", "private2", "append", "channel", "category"))?.move).toEqual({ channelId: "secret", categoryId: "private2" })
+ expect(projectChannelTreeDrop(tree, drop("text", "private2", "append", "channel", "category"))).toBeNull()
+ expect(projectChannelTreeDrop(tree, drop("secret", UNCATEGORIZED_CATEGORY_ID, "append", "channel", "category"))).toBeNull()
+ })
+ it("does not save an unchanged adjacency, unchanged append, self or malformed identity", () => {
+ const tree = treeFrom()
+ for (const event of [drop("text", "forum", "before"), drop("forum", "text", "after"), drop("last", "opaque-a", "append", "channel", "category"), drop("text", "text", "after"), drop("missing", "text", "after"), drop("opaque-a", "text", "after", "category"), drop("text", "opaque-b", "after", "category", "category"), drop("text", "b1", "append")]) {
+ expect(projectChannelTreeDrop(tree, event)).toBeNull()
}
- const renderer = rtlRender(React.createElement(ScopedCaptureTree, {
- scopeKey: "server:A",
- categories: categoriesA,
- onResult,
- }))
- const initialOwnerId = ownerId
- const initialToggle = current.toggleCat
-
- await act(async () => current.toggleCat("cat_A"))
- await act(async () => current.onDragOver(dragEvent("a2", "a1")))
- const movedOrder = current.order
-
- renderer.rerender(React.createElement(ScopedCaptureTree, {
- scopeKey: "server:A",
- categories: categoriesA,
- onResult,
- }))
-
- expect(ownerId).toBe(initialOwnerId)
- expect(current.collapsed).toEqual(new Set(["cat_A"]))
- expect(current.order).toBe(movedOrder)
- expect(current.catOrder).toEqual(["cat_A", "cat_A2"])
- expect(current.catNames).toMatchObject({ cat_A: "Alpha", cat_A2: "cat_A2" })
- expect(current.catPrivate.cat_A).toBe(true)
- expect(current.catPending.cat_A).toBe(true)
- expect(current.catCreators.cat_A).toBe("owner_A")
- expect(current.toggleCat).toBe(initialToggle)
})
-
- it("initializes the first render of a new key atomically from only that scope", async () => {
- nextOwnerId = 0
- const samples: Array<{ tree: Tree; ownerId: number }> = []
- const onResult = (tree: Tree, ownerId: number) => samples.push({ tree, ownerId })
- const renderer = rtlRender(React.createElement(ScopedCaptureTree, {
- scopeKey: "server:A",
- categories: categoriesA,
- onResult,
- }))
-
- const current = samples.at(-1)!.tree
- await act(async () => current.toggleCat("cat_A"))
- await act(async () => current.onDragOver(dragEvent("a2", "a1")))
- const ownerA = samples.at(-1)!.ownerId
- samples.length = 0
-
- renderer.rerender(React.createElement(ScopedCaptureTree, {
- scopeKey: "server:B",
- categories: categoriesB,
- onResult,
- }))
-
- const firstB = samples[0]
- expect(firstB.ownerId).not.toBe(ownerA)
- expect(firstB.tree.collapsed).toEqual(new Set())
- expect(firstB.tree.catOrder).toEqual(["cat_B"])
- expect(Object.keys(firstB.tree.order)).toEqual(["cat_B"])
- expect(firstB.tree.order.cat_B.map((channel) => channel.id)).toEqual(["b1", "b2"])
- expect(firstB.tree.catNames).toEqual({ cat_B: "Beta" })
- expect(firstB.tree.catPrivate).toEqual({ cat_B: false })
- expect(firstB.tree.catPending).toEqual({ cat_B: false })
- expect(firstB.tree.catCreators).toEqual({ cat_B: "owner_B" })
- expect(JSON.stringify(firstB.tree)).not.toContain("tmp_A")
-
- samples.length = 0
- renderer.rerender(React.createElement(ScopedCaptureTree, {
- scopeKey: "server:A",
- categories: categoriesA,
- onResult,
- }))
- expect(samples[0].ownerId).not.toBe(firstB.ownerId)
- expect(samples[0].tree.collapsed).toEqual(new Set())
- expect(samples[0].tree.order.cat_A.map((channel) => channel.id)).toEqual(["a1", "tmp_A"])
+ it("rejects pending source/target rows and categories before producing a command", () => {
+ const tree = treeFrom([{ id: "a", name: "A", channels: [ch("ready"), ch("pending", { pending: true })] }, { id: "pending-cat", name: "Pending", pending: true, channels: [ch("inside")] }])
+ for (const event of [drop("pending", "ready", "after"), drop("ready", "pending", "after"), drop("ready", "pending-cat", "append", "channel", "category"), drop("inside", "ready", "after")]) expect(projectChannelTreeDrop(tree, event)).toBeNull()
})
+})
- it("does not schedule an order update for equivalent categories with new references", async () => {
- let current!: Tree
+describe("canonical channel tree ownership", () => {
+ it("shows canonical optimistic order and its rollback without retaining a local order", () => {
+ const view = renderHook(({ rows }) => useChannelTree(rows), { initialProps: { rows: categories } })
+ act(() => view.result.current.toggleCat("opaque-b"))
+ const moved = categories.map((category) => category.id === "opaque-a" ? { ...category, channels: [ch("last"), ch("text"), ch("forum")] } : category)
+ view.rerender({ rows: moved })
+ expect(view.result.current.order["opaque-a"].map((row) => row.id)).toEqual(["last", "text", "forum"])
+ view.rerender({ rows: categories })
+ expect(view.result.current.order["opaque-a"].map((row) => row.id)).toEqual(["text", "forum", "last"])
+ expect(view.result.current.collapsed).toEqual(new Set(["opaque-b"]))
+ })
+ it("takes every field from the canonical row while keeping disclosure state", () => {
+ const view = renderHook(({ rows }) => useChannelTree(rows), { initialProps: { rows: categories } })
+ act(() => view.result.current.toggleCat("opaque-a"))
+ const changed = ch("text", { name: "renamed", unread: true, muted: true, type: "forum", pending: true, creatorId: "creator" })
+ view.rerender({ rows: categories.map((category) => category.id === "opaque-a" ? { ...category, channels: [changed] } : category) })
+ expect(view.result.current.order["opaque-a"][0]).toBe(changed)
+ expect(view.result.current.collapsed.has("opaque-a")).toBe(true)
+ expect(catOf("text", view.result.current.order)).toBe("opaque-a")
+ expect(catOf("missing", view.result.current.order)).toBeUndefined()
+ })
+ it("does not schedule state updates for equivalent reallocated category arrays", () => {
let renders = 0
- const onResult = (tree: Tree) => {
- current = tree
- renders += 1
- }
- const renderer = rtlRender(React.createElement(ReallocatedCaptureTree, { onResult }))
- const initialOrder = current.order
-
- await act(async () => current.toggleCat("cat_A"))
- expect(current.collapsed).toEqual(new Set(["cat_A"]))
- expect(current.order).toBe(initialOrder)
- expect(renders).toBe(2)
-
- renderer.rerender(React.createElement(ReallocatedCaptureTree, { onResult }))
+ const view = renderHook(() => { renders++; return useChannelTree(categories.map((category) => ({ ...category, channels: [...category.channels] }))) })
+ act(() => view.result.current.toggleCat("opaque-a"))
+ view.rerender()
expect(renders).toBe(3)
- expect(current.order).toBe(initialOrder)
+ expect(view.result.current.collapsed).toEqual(new Set(["opaque-a"]))
})
-
- it("reconciles category metadata without replacing drag order", async () => {
- let current!: Tree
- const onResult = (tree: Tree) => { current = tree }
- const renderer = rtlRender(React.createElement(CaptureTree, {
- categories: categoriesA,
- onResult,
- }))
- const initialOrder = current.order
-
- renderer.rerender(React.createElement(CaptureTree, {
- categories: categoriesA.map((item) => item.id === "cat_A" ? {
- ...item,
- name: "Renamed",
- private: false,
- pending: false,
- creatorId: "owner_B",
- } : item),
- onResult,
- }))
- await act(async () => { await Promise.resolve() })
-
- expect(current.order).toBe(initialOrder)
- expect(current.catNames.cat_A).toBe("Renamed")
- expect(current.catPrivate.cat_A).toBe(false)
- expect(current.catPending.cat_A).toBe(false)
- expect(current.catCreators.cat_A).toBe("owner_B")
- })
-
- it("reconciles channel interaction, permission, and type metadata for stable ids", async () => {
- let current!: Tree
- const onResult = (tree: Tree) => { current = tree }
- const initial: Category[] = [category("cat_A", [{
- ...ch("channel_1"),
- pending: true,
- creatorId: "owner_A",
- type: "text",
- }])]
- const renderer = rtlRender(React.createElement(CaptureTree, {
- categories: initial,
- onResult,
- }))
-
- renderer.rerender(React.createElement(CaptureTree, {
- categories: [category("cat_A", [{
- ...ch("channel_1"),
- pending: false,
- creatorId: "owner_B",
- type: "forum",
- }])],
- onResult,
- }))
- await act(async () => { await Promise.resolve() })
-
- expect(current.order.cat_A[0]).toMatchObject({
- pending: false,
- creatorId: "owner_B",
- type: "forum",
- })
- })
-})
-
-// Regression: the sync effect's id-set early-return must not swallow
-// metadata-only updates such as unread and name changes.
-describe("mergeChannelMetadata", () => {
- const cat = (id: string, channels: Channel[]): Category => ({ id, name: id, channels })
-
- it("flips an unread flag while ids are unchanged", () => {
- const result = mergeChannelMetadata(order, [
- cat("cat_A", [ch("a1"), { ...ch("a2"), unread: true }]),
- cat("cat_B", [ch("b1"), ch("b2"), ch("b3")]),
- ])
- expect(result.changed).toBe(true)
- expect(result.next.cat_A.find((c) => c.id === "a2")?.unread).toBe(true)
- // Untouched sibling channel keeps the same object reference.
- expect(result.next.cat_A.find((c) => c.id === "a1")).toBe(order.cat_A[0])
- })
-
- it("follows optimistic, normalized, and rollback names while ids and order stay unchanged", () => {
- const incoming = (name: string) => [
- cat("cat_A", [ch("a1"), { ...ch("a2"), name }]),
- cat("cat_B", [ch("b1"), ch("b2"), ch("b3")]),
- ]
- const optimistic = mergeChannelMetadata(order, incoming("General Chat"))
- const normalized = mergeChannelMetadata(optimistic.next, incoming("General-Chat"))
- const rolledBack = mergeChannelMetadata(optimistic.next, incoming("a2"))
-
- expect(optimistic.next.cat_A.find((c) => c.id === "a2")?.name).toBe("General Chat")
- expect(normalized.next.cat_A.find((c) => c.id === "a2")?.name).toBe("General-Chat")
- expect(rolledBack.next.cat_A.find((c) => c.id === "a2")?.name).toBe("a2")
- expect(normalized.next.cat_A.map((channel) => channel.id)).toEqual(["a1", "a2"])
- expect(normalized.next.cat_B.map((channel) => channel.id)).toEqual(["b1", "b2", "b3"])
- })
-
- it("preserves category/channel order — only rewrites the changed field", () => {
- const result = mergeChannelMetadata(order, [
- cat("cat_A", [ch("a1"), { ...ch("a2"), unread: true }]),
- cat("cat_B", [ch("b1"), ch("b2"), ch("b3")]),
- ])
- expect(Object.keys(result.next)).toEqual(Object.keys(order))
- expect(result.next.cat_B.map((c) => c.id)).toEqual(order.cat_B.map((c) => c.id))
- // Every field on the changed channel other than the diffed ones is preserved.
- expect(result.next.cat_A.find((c) => c.id === "a2")).toMatchObject({ id: "a2", active: false })
- })
-
- it("is a no-op (same reference, changed: false) when nothing differs", () => {
- const result = mergeChannelMetadata(order, [
- cat("cat_A", [ch("a1"), ch("a2")]),
- cat("cat_B", [ch("b1"), ch("b2"), ch("b3")]),
- ])
- expect(result.changed).toBe(false)
- expect(result.next).toBe(order)
- })
-
- // An optimistic pending row that survives an id-set-unchanged metadata merge
- // (e.g. a sibling WS unread patch) must keep its `pending` flag — the merge
- // spreads the existing row and only overwrites unread/name.
- it("preserves the pending flag when only unread changes underneath it", () => {
- const pendingOrder: ChannelOrder = {
- cat_A: [{ ...ch("tmp_ch_x"), pending: true }],
- }
- const result = mergeChannelMetadata(pendingOrder, [
- cat("cat_A", [{ ...ch("tmp_ch_x"), unread: true }]),
- ])
- expect(result.changed).toBe(true)
- const row = result.next.cat_A.find((c) => c.id === "tmp_ch_x")
- expect(row?.pending).toBe(true)
- expect(row?.unread).toBe(true)
+ it("does not duplicate a real uncategorized bucket", () => {
+ const root = { id: UNCATEGORIZED_CATEGORY_ID, name: "", channels: [ch("root")] }
+ const tree = treeFrom([root, ...categories])
+ expect(tree.catOrder.filter((id) => id === UNCATEGORIZED_CATEGORY_ID)).toHaveLength(1)
+ expect(tree.order[UNCATEGORIZED_CATEGORY_ID]).toBe(root.channels)
})
})
diff --git a/src/web/src/components/community/channels/use-channel-tree.ts b/src/web/src/components/community/channels/use-channel-tree.ts
index fad95b36b..edaf0dce6 100644
--- a/src/web/src/components/community/channels/use-channel-tree.ts
+++ b/src/web/src/components/community/channels/use-channel-tree.ts
@@ -1,153 +1,91 @@
"use client"
-
import { useAtom, useCreateAtom } from "@tanstack/react-store"
import { useCallback, useMemo } from "react"
-import { arrayMove } from "@dnd-kit/sortable"
-import type { DragEndEvent } from "@dnd-kit/core"
+import { UNCATEGORIZED_CATEGORY_ID, type ChannelCategoryMove } from "@alook/shared"
import type { Category, Channel } from "@/lib/community/models/navigation"
-// DnD keeps the persisted opaque IDs unchanged. Category identity comes from
-// membership in `catOrder` / `order`, never from an ID prefix.
-export const catId = (id: string) => id
-
export type ChannelOrder = Record<string, Channel[]>
+export type ChannelTreeEntity = { id: string; kind: "category" | "channel" }
+export type ChannelTreeDrop = {
+ active: ChannelTreeEntity
+ over: ChannelTreeEntity
+ placement: "before" | "after" | "append"
+}
+export type { ChannelCategoryMove } from "@alook/shared"
+export type ChannelTreeCommit = { categoryIds: string[] } | { channelIds: string[]; move?: ChannelCategoryMove }
-/** Which category currently holds a channel id (or the category itself if `id` is an order key). */
export function catOf(id: string, order: ChannelOrder): string | undefined {
if (Object.hasOwn(order, id)) return id
- return Object.keys(order).find((cat) => order[cat].some((c) => c.id === id))
-}
-
-/**
- * Live cross-category move while dragging a channel (channels can jump
- * categories). Returns a new order, or the input unchanged when the move doesn't
- * apply (same category, missing channel, etc.). Pure — exported for tests.
- */
-export function moveChannelAcrossCategories(order: ChannelOrder, activeId: string, overId: string): ChannelOrder {
- const fromCat = catOf(activeId, order)
- const toCat = catOf(overId, order)
- if (!fromCat || !toCat || fromCat === toCat) return order
- const moving = order[fromCat].find((c) => c.id === activeId)
- if (!moving) return order
- const overIdx = order[toCat].findIndex((c) => c.id === overId)
- const insertAt = overIdx === -1 ? order[toCat].length : overIdx
- const nextTo = [...order[toCat]]
- nextTo.splice(insertAt, 0, moving)
- return {
- ...order,
- [fromCat]: order[fromCat].filter((c) => c.id !== activeId),
- [toCat]: nextTo,
- }
+ return Object.keys(order).find((cat) => order[cat].some((channel) => channel.id === id))
}
-/** Settle channel order within the destination category on drop. Pure. */
-export function reorderChannelsWithin(order: ChannelOrder, activeId: string, overId: string): ChannelOrder {
- const cat = catOf(activeId, order)
- if (!cat || !order[cat].some((c) => c.id === overId)) return order
- const from = order[cat].findIndex((c) => c.id === activeId)
- const to = order[cat].findIndex((c) => c.id === overId)
- if (from === -1 || to === -1) return order
- return { ...order, [cat]: arrayMove(order[cat], from, to) }
+function insert<T>(rows: T[], value: T, target: T, placement: "before" | "after") {
+ const next = rows.filter((row) => row !== value)
+ const index = next.indexOf(target)
+ if (index === -1) return rows
+ next.splice(index + Number(placement === "after"), 0, value)
+ return next
}
+const sameIds = (a: string[], b: string[]) => a.length === b.length && a.every((id, index) => id === b[index])
-/**
- * Merge metadata-only field changes (`unread`, `name`) from the incoming
- * `categories` prop into the existing per-category `order` state, keyed by
- * channel id. Used by the sync effect when the channel/category *id set* is
- * unchanged but a field like `unread` still needs to reach the render tree —
- * preserves drag order/collapse state by only ever touching the matched
- * channel's fields, never reshuffling arrays. Pure — exported for tests.
- */
-export function mergeChannelMetadata(
- order: ChannelOrder,
- categories: Category[],
-): { next: ChannelOrder; changed: boolean } {
- const incoming = new Map<string, Channel>()
- for (const cat of categories) {
- for (const ch of cat.channels) incoming.set(ch.id, ch)
+export function projectChannelTreeDrop(tree: Pick<ChannelTree, "catOrder" | "order" | "catNames" | "catPrivate" | "catPending">, drop: ChannelTreeDrop): ChannelTreeCommit | null {
+ const { active, over, placement } = drop
+ const { catOrder, order, catNames, catPrivate, catPending } = tree
+ if (active.id === over.id) return null
+ const from = catOf(active.id, order), to = catOf(over.id, order)
+ if (!from || !to || catPending[from] || catPending[to]) return null
+ if (active.kind === "category") {
+ if (from !== active.id || to !== over.id || over.kind !== "category" || placement === "append" || !catNames[active.id] || !catNames[over.id]) return null
+ const categoryIds = catOrder.filter((id) => catNames[id] && !catPending[id])
+ const next = insert(categoryIds, active.id, over.id, placement)
+ return sameIds(next, categoryIds) ? null : { categoryIds: next }
}
- let changed = false
- const next: ChannelOrder = {}
- for (const [catId, channels] of Object.entries(order)) {
- next[catId] = channels.map((ch) => {
- const src = incoming.get(ch.id)
- if (!src) return ch
- const pending = src.pending === undefined ? ch.pending : src.pending
- if (
- src.unread === ch.unread &&
- src.name === ch.name &&
- Boolean(pending) === Boolean(ch.pending) &&
- (src.creatorId ?? null) === (ch.creatorId ?? null) &&
- (src.type ?? null) === (ch.type ?? null)
- ) return ch
- changed = true
- return {
- ...ch,
- unread: src.unread,
- name: src.name,
- pending,
- creatorId: src.creatorId,
- type: src.type,
- }
- })
+ const moving = order[from].find((channel) => channel.id === active.id)
+ if (!moving || moving.pending || catPrivate[from] !== catPrivate[to]) return null
+ if (over.kind === "category" ? placement !== "append" : placement === "append") return null
+ const target = over.kind === "channel" ? order[to].find((channel) => channel.id === over.id) : null
+ if (over.kind === "channel" && (!target || target.pending)) return null
+ const destination = order[to].filter((channel) => channel.id !== active.id)
+ const index = target ? destination.indexOf(target) + Number(placement === "after") : destination.length
+ destination.splice(index, 0, moving)
+ if (from === to && sameIds(destination.map((channel) => channel.id), order[from].map((channel) => channel.id))) return null
+ const settled = { ...order, [from]: order[from].filter((channel) => channel.id !== active.id), [to]: destination }
+ return {
+ channelIds: catOrder.flatMap((id) => (settled[id] ?? []).filter((channel) => !channel.pending).map((channel) => channel.id)),
+ ...(from === to ? {} : { move: { channelId: active.id, categoryId: catNames[to] === "" ? null : to } }),
}
- return { next: changed ? next : order, changed }
}
-/** Reorder the category list itself. `activeCatId`/`overCatId` are category IDs. Pure. */
-export function reorderCategories(catOrder: string[], activeCatId: string, overCatId: string): string[] {
- const from = catOrder.indexOf(activeCatId)
- const to = catOrder.indexOf(overCatId)
- if (from === -1 || to === -1) return catOrder
- return arrayMove(catOrder, from, to)
+export function resolveChannelTreeDrop(tree: ChannelTree, drop: ChannelTreeDrop): ChannelTreeDrop | null {
+ let result = drop
+ if (drop.active.kind === "channel" && drop.over.kind === "channel" && drop.placement === "after") {
+ const categoryId = catOf(drop.over.id, tree.order)
+ if (categoryId && tree.order[categoryId].filter((channel) => !channel.pending).at(-1)?.id === drop.over.id) result = { ...drop, over: { id: categoryId, kind: "category" }, placement: "append" }
+ }
+ return projectChannelTreeDrop(tree, result) ? result : null
}
-
-/**
- * Channel-sidebar dnd state: category order + per-category channel order, with
- * cross-category drag and collapse toggles. One DndContext drives both: categories
- * sort among themselves, channels sort across categories.
- */
export function useChannelTree(categories: Category[]) {
- const [collapsed, setCollapsed] = useAtom(useCreateAtom<Set<string>>(new Set<string>()));
- const layout = useCreateAtom<{ identity: string; categories: string[]; channels: Record<string, string[]> } | null>(null);
- const [preview, setPreview] = useAtom(layout);
- const identity = JSON.stringify(categories.map((category) => [category.id, category.channels.map((channel) => channel.id)]));
- const channelFacts = JSON.stringify(categories.flatMap((category) => category.channels));
- const canonicalChannels = useMemo(() => new Map((JSON.parse(channelFacts) as Channel[]).map((channel) => [channel.id, channel])), [channelFacts]);
- const baseOrder = useMemo(() => Object.fromEntries(JSON.parse(identity) as Array<[string, string[]]>), [identity]);
- const current = useMemo(() => preview?.identity === identity ? preview : { identity, categories: Object.keys(baseOrder), channels: baseOrder }, [preview, identity, baseOrder]);
- const catOrder = current.categories;
- const order = useMemo<ChannelOrder>(() => Object.fromEntries(Object.entries(current.channels).map(([id, ids]) => [id, ids.flatMap((channelId) => {
- const channel = canonicalChannels.get(channelId);
- return channel ? [channel] : [];
- })])), [current.channels, canonicalChannels]);
- const catNames = Object.fromEntries(categories.map((category) => [category.id, category.name]));
- const catPrivate = Object.fromEntries(categories.map((category) => [category.id, !!category.private]));
- const catPending = Object.fromEntries(categories.map((category) => [category.id, !!category.pending]));
- const catCreators = Object.fromEntries(categories.map((category) => [category.id, category.creatorId ?? null]));
- const toggleCat = useCallback((id: string) => setCollapsed((previous) => {
- const next = new Set(previous);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- return next;
- }), [setCollapsed]);
- const projectOrder = (next: ChannelOrder) => Object.fromEntries(Object.entries(next).map(([id, channels]) => [id, channels.map((channel) => channel.id)]));
- const onDragOver = ({ active, over }: DragEndEvent) => {
- if (!over || catOrder.includes(String(active.id))) return;
- const from = catOf(String(active.id), order), to = catOf(String(over.id), order);
- if (from && to && from !== to && catPrivate[from] !== catPrivate[to]) return;
- const next = moveChannelAcrossCategories(order, String(active.id), String(over.id));
- if (next !== order) setPreview({ ...current, channels: projectOrder(next) });
- };
- const onDragEnd = ({ active, over }: DragEndEvent) => {
- if (over && active.id !== over.id) {
- const activeId = String(active.id), overId = String(over.id);
- if (catOrder.includes(activeId) && catOrder.includes(overId)) setPreview({ ...current, categories: reorderCategories(catOrder, activeId, overId) });
- else if (!catOrder.includes(activeId)) setPreview({ ...current, channels: projectOrder(reorderChannelsWithin(order, activeId, overId)) });
+ const [collapsed, setCollapsed] = useAtom(useCreateAtom(new Set<string>()))
+ const structure = useMemo(() => {
+ const rows = categories.some((category) => category.name === "") ? categories
+ : [...categories, { id: UNCATEGORIZED_CATEGORY_ID, name: "", private: false, channels: [] }]
+ return {
+ catOrder: rows.map((category) => category.id),
+ order: Object.fromEntries(rows.map((category) => [category.id, category.channels])),
+ catNames: Object.fromEntries(rows.map((category) => [category.id, category.name])),
+ catPrivate: Object.fromEntries(rows.map((category) => [category.id, !!category.private])),
+ catPending: Object.fromEntries(rows.map((category) => [category.id, !!category.pending])),
+ catCreators: Object.fromEntries(rows.map((category) => [category.id, category.creatorId ?? null])),
}
- };
- return { collapsed, catOrder, order, catNames, catPrivate, catPending, catCreators, toggleCat, onDragOver, onDragEnd };
+ }, [categories])
+ const toggleCat = useCallback((id: string) => setCollapsed((previous) => {
+ const next = new Set(previous)
+ if (next.has(id)) next.delete(id)
+ else next.add(id)
+ return next
+ }), [setCollapsed])
+ return { ...structure, collapsed, toggleCat }
}
export type ChannelTree = ReturnType<typeof useChannelTree>
diff --git a/src/web/src/components/community/community-dnd.dom.test.tsx b/src/web/src/components/community/community-dnd.dom.test.tsx
new file mode 100644
index 000000000..9a83ba2af
--- /dev/null
+++ b/src/web/src/components/community/community-dnd.dom.test.tsx
@@ -0,0 +1,364 @@
+import { useLayoutEffect, useRef, useState, type ReactNode } from "react"
+import { DndProvider } from "react-dnd"
+import { TestBackend, type TestBackendImpl } from "react-dnd-test-backend"
+import { act, fireEvent, render } from "@/test/react-dom-harness"
+import { describe, expect, it, vi } from "vitest"
+import { CommunityDndProvider, communityDndOptions } from "./community-dnd"
+import { RailDndBinding, railInstructionAt, useServerRailDnd, type RailDndController } from "./shell/use-server-rail-dnd"
+import { ChannelDndScope, ChannelDropContainer, useChannelDndItem } from "./channels/channel-dnd"
+import { ChannelSidebar } from "./channels/channel-sidebar"
+import { tid } from "@/lib/community/testids"
+import { UNCATEGORIZED_CATEGORY_ID } from "@alook/shared"
+import { useChannelTree, type ChannelTreeDrop } from "./channels/use-channel-tree"
+import type { Category } from "@/lib/community/models/navigation"
+import type { RailInstruction, RailState } from "@/lib/community/server-rail-model"
+
+function setup(children: ReactNode) {
+ let backend!: TestBackendImpl
+ const sources = new Map<HTMLElement, string>()
+ const targets = new Map<HTMLElement, string>()
+ const view = render(<DndProvider context={{}} backend={(manager, context) => {
+ backend = TestBackend(manager, context) as TestBackendImpl
+ Object.assign(backend, {
+ connectDragSource: (id: string, node: HTMLElement) => { sources.set(node, id); return () => { sources.delete(node) } },
+ connectDropTarget: (id: string, node: HTMLElement) => { targets.set(node, id); return () => { targets.delete(node) } },
+ })
+ return backend
+ }}><CommunityDndProvider>{children}</CommunityDndProvider></DndProvider>)
+ const node = (id: string) => view.getByTestId(id)
+ const start = (id: string) => act(() => backend.simulateBeginDrag([sources.get(node(id))!], {
+ clientOffset: { x: 20, y: 20 }, getSourceClientOffset: () => ({ x: 0, y: 0 }),
+ }))
+ const hover = (id: string, y = 20) => act(() => backend.simulateHover([targets.get(node(id))!], { clientOffset: { x: 20, y } }))
+ const drop = () => act(() => { backend.simulateDrop(); backend.simulateEndDrag() })
+ const cancel = () => fireEvent.keyDown(window, { key: "Escape" })
+ return { ...view, node, start, hover, drop, cancel, backend, targets }
+}
+
+const state: RailState = { serverIds: ["a", "b", "c"], folderIds: ["f"], folders: { f: ["c"] }, expanded: [] }
+function RailFixture({ onDrop, onCancel = () => {}, onPreview = () => {}, onReady }: { onDrop: (instruction: RailInstruction) => void; onCancel?: () => void; onPreview?: (instruction: RailInstruction | null) => void; onReady?: (cancel: () => void, dnd: RailDndController) => void }) {
+ const dnd = useServerRailDnd({ getState: () => state, canStart: () => true, onDragStart: () => {}, onPreview, onDrop, onCancel })
+ useLayoutEffect(() => { onReady?.(dnd.cancel, dnd) }, [dnd, onReady])
+ return <>{["a", "b"].map((id) => <RailItem key={id} id={id} dnd={dnd} />)}<RailItem id="f" kind="folder" dnd={dnd} /></>
+}
+function RailItem({ id, kind = "server", dnd }: { id: string; kind?: "server" | "folder"; dnd: ReturnType<typeof useServerRailDnd> }) {
+ const ref = useRef<HTMLDivElement>(null)
+ return <div ref={ref} data-testid={`rail-${id}`}><RailDndBinding dnd={dnd} entity={{ kind, id }} element={ref} handle={ref} /></div>
+}
+
+const channel = (id: string) => ({ id, name: id, unread: false, active: false })
+const categories: Category[] = [
+ { id: "public", name: "Public", channels: [channel("text"), { ...channel("forum"), type: "forum" }] },
+ { id: "empty", name: "Empty", channels: [] },
+ { id: "private", name: "Private", private: true, channels: [channel("secret")] },
+ { id: "private2", name: "Private 2", private: true, channels: [] },
+]
+function TreeFixture({ onDrop, canReorder = true, rootBefore = true }: { onDrop: (event: ChannelTreeDrop) => void; canReorder?: boolean; rootBefore?: boolean }) {
+ const tree = useChannelTree(categories)
+ const settle = (event: ChannelTreeDrop) => { onDrop(event) }
+ return <ChannelDndScope tree={tree} onDrop={settle}>
+ <output data-testid="tree-order">{JSON.stringify({ cats: tree.catOrder, channels: Object.fromEntries(Object.entries(tree.order).map(([id, rows]) => [id, rows.map((row) => row.id)])) })}</output>
+ {tree.catOrder.map((id) => <TreeItem key={id} id={id} kind="category" canReorder={canReorder} />)}
+ {Object.values(tree.order).flat().map((row) => <TreeItem key={row.id} id={row.id} kind="channel" canReorder={canReorder} />)}
+ <ChannelDropContainer id="empty" />
+ <ChannelDropContainer id="public" lastRowId="forum" />
+ <ChannelDropContainer id={UNCATEGORIZED_CATEGORY_ID} before={rootBefore} />
+ </ChannelDndScope>
+}
+function TreeItem({ id, kind, canReorder }: { id: string; kind: "category" | "channel"; canReorder: boolean }) {
+ const { setNodeRef, setActivatorNodeRef, placement } = useChannelDndItem(id, kind, canReorder)
+ return <div ref={setNodeRef} data-testid={id} data-channel-tree-row={kind === "channel" ? id : undefined} data-placement={placement ?? undefined}>{kind === "category" ? <div ref={setActivatorNodeRef} data-testid={`${id}-handle`}>{id}</div> : id}</div>
+}
+
+function ActualSidebarFixture({ onReorder }: { onReorder: (ids: string[]) => void }) {
+ const tree = useChannelTree([
+ { id: UNCATEGORIZED_CATEGORY_ID, name: "", channels: [] },
+ ...categories,
+ { id: "pending", name: "Pending", pending: true, channels: [] },
+ ])
+ return <ChannelSidebar tree={tree} serverName="Fixture" activeChannel="" setActiveChannel={() => {}} onReorderCategories={onReorder} />
+}
+
+describe("React DnD community scopes", () => {
+ it("settles page-background release as cancellation, retaining only a visual return", () => {
+ vi.spyOn(window, "matchMedia").mockReturnValue({ matches: false } as MediaQueryList)
+ let dnd!: RailDndController
+ const onDrop = vi.fn(), onCancel = vi.fn(), onPreview = vi.fn()
+ const ui = setup(<RailFixture onDrop={onDrop} onCancel={onCancel} onPreview={onPreview} onReady={(_, value) => { dnd = value }} />)
+ ui.node("rail-b").getBoundingClientRect = () => ({ top: 100, height: 40 }) as DOMRect
+ ui.start("rail-a"); ui.hover("rail-b", 120)
+ act(() => ui.backend.simulateHover([ui.targets.get(document.body)!], { clientOffset: { x: 320, y: 220 } }))
+ expect(onPreview).toHaveBeenLastCalledWith(null)
+ ui.drop()
+ expect(onDrop).not.toHaveBeenCalled()
+ expect(onCancel).toHaveBeenCalledTimes(1)
+ const returning = dnd.returning.get()!
+ expect(returning).toMatchObject({ entity: { kind: "server", id: "a" }, offset: { x: 300, y: 200 } })
+ expect(returning.element).toBe(ui.node("rail-a"))
+ act(() => dnd.completeReturn(returning))
+ expect(dnd.returning.get()).toBeNull()
+ ui.start("rail-a"); ui.cancel()
+ expect(dnd.returning.get()).not.toBeNull()
+ ui.start("rail-a")
+ expect(dnd.returning.get()).toBeNull()
+ act(() => dnd.cancel())
+ expect(dnd.returning.get()).toBeNull()
+ })
+ it("preserves a valid nested drop instead of replacing it with background cancellation", () => {
+ let dnd!: RailDndController
+ const onDrop = vi.fn(), onCancel = vi.fn()
+ const ui = setup(<RailFixture onDrop={onDrop} onCancel={onCancel} onReady={(_, value) => { dnd = value }} />)
+ ui.node("rail-b").getBoundingClientRect = () => ({ top: 0, height: 40 }) as DOMRect
+ ui.start("rail-a")
+ act(() => ui.backend.simulateHover([ui.targets.get(document.body)!, ui.targets.get(ui.node("rail-b"))!], { clientOffset: { x: 20, y: 38 } }))
+ ui.drop()
+ expect(onDrop).toHaveBeenCalledExactlyOnceWith({ source: { kind: "server", id: "a" }, target: { kind: "server", id: "b" }, operation: "reorder-after" })
+ expect(onCancel).not.toHaveBeenCalled()
+ expect(dnd.returning.get()).toBeNull()
+ })
+ it("skips return motion for reduced motion and rejects channel items at the fallback target", () => {
+ const media = vi.spyOn(window, "matchMedia").mockReturnValue({ matches: true } as MediaQueryList)
+ try {
+ let dnd!: RailDndController
+ const onDrop = vi.fn(), onCancel = vi.fn(), treeDrop = vi.fn()
+ const ui = setup(<><RailFixture onDrop={onDrop} onCancel={onCancel} onReady={(_, value) => { dnd = value }} /><TreeFixture onDrop={treeDrop} /></>)
+ ui.start("rail-a"); ui.cancel()
+ expect(onCancel).toHaveBeenCalledTimes(1)
+ expect(dnd.returning.get()).toBeNull()
+ ui.start("text")
+ act(() => ui.backend.simulateHover([ui.targets.get(document.body)!], {}))
+ ui.drop()
+ expect(onDrop).not.toHaveBeenCalled()
+ expect(treeDrop).not.toHaveBeenCalled()
+ } finally { media.mockRestore() }
+ })
+ it("uses insertion feedback for nested rows, including a source from outside that folder", () => {
+ const nested: RailState = { serverIds: ["a", "b", "c"], folderIds: ["f"], folders: { f: ["b", "c"] }, expanded: ["f"] }
+ const source = { kind: "server", id: "a" } as const
+ const target = { kind: "server", id: "b" } as const
+ expect(railInstructionAt(nested, source, target, 0.4)).toMatchObject({ operation: "reorder-before" })
+ expect(railInstructionAt(nested, source, target, 0.6)).toMatchObject({ operation: "reorder-after" })
+ })
+ it("uses the container end instruction for the final row's after edge", () => {
+ const source = { kind: "server", id: "a" } as const
+ const nested: RailState = { serverIds: ["a", "b", "c"], folderIds: ["f"], folders: { f: ["b", "c"] }, expanded: ["f"] }
+ expect(railInstructionAt(nested, source, { kind: "server", id: "c" }, 0.8)).toEqual({ operation: "append", source, target: { kind: "folder-content", id: "f" } })
+ const root: RailState = { serverIds: ["a", "b", "c"], folderIds: [], folders: {}, expanded: [] }
+ expect(railInstructionAt(root, source, { kind: "server", id: "c" }, 0.9)).toEqual({ operation: "append", source, target: { kind: "root", id: "root" } })
+ expect(railInstructionAt(root, source, { kind: "server", id: "b" }, 0.9)).toEqual({ operation: "reorder-after", source, target: { kind: "server", id: "b" } })
+ expect(railInstructionAt(root, { kind: "server", id: "c" }, { kind: "server", id: "c" }, 0.9)).toBeNull()
+ })
+ it("updates center/combine and edge/insertion feedback while staying over the same target", () => {
+ const onPreview = vi.fn()
+ const ui = setup(<RailFixture onDrop={vi.fn()} onPreview={onPreview} />)
+ ui.node("rail-b").getBoundingClientRect = () => ({ top: 100, height: 40 }) as DOMRect
+ ui.start("rail-a"); ui.hover("rail-b", 120)
+ expect(onPreview).toHaveBeenLastCalledWith(expect.objectContaining({ operation: "combine" }))
+ ui.hover("rail-b", 138)
+ expect(onPreview).toHaveBeenLastCalledWith(expect.objectContaining({ operation: "reorder-after" }))
+ ui.hover("rail-b", 102)
+ expect(onPreview).toHaveBeenLastCalledWith(null)
+ ui.hover("rail-b", 120)
+ expect(onPreview).toHaveBeenLastCalledWith(expect.objectContaining({ operation: "combine" }))
+ ui.cancel()
+ })
+ it("ends a route-cancelled backend drag without a drop and allows the next drag", () => {
+ let cancel!: () => void
+ const onDrop = vi.fn(), onCancel = vi.fn(), onPreview = vi.fn()
+ const ui = setup(<RailFixture onDrop={onDrop} onCancel={onCancel} onPreview={onPreview} onReady={(next) => { cancel = next }} />)
+ ui.node("rail-b").getBoundingClientRect = () => ({ top: 0, height: 40 }) as DOMRect
+ ui.start("rail-a"); ui.hover("rail-b", 38)
+ act(() => cancel())
+ expect(onCancel).toHaveBeenCalledTimes(1)
+ expect(onPreview).toHaveBeenLastCalledWith(null)
+ expect(onDrop).not.toHaveBeenCalled()
+ ui.start("rail-a"); ui.hover("rail-b", 38); ui.drop()
+ expect(onDrop).toHaveBeenCalledExactlyOnceWith({ source: { kind: "server", id: "a" }, target: { kind: "server", id: "b" }, operation: "reorder-after" })
+ })
+ it("accepts the whole folder header without expansion or writes before drop", () => {
+ vi.useFakeTimers()
+ try {
+ const onDrop = vi.fn(), onPreview = vi.fn()
+ const ui = setup(<RailFixture onDrop={onDrop} onPreview={onPreview} />)
+ ui.node("rail-f").getBoundingClientRect = () => ({ top: 100, height: 40 }) as DOMRect
+ ui.start("rail-a"); ui.hover("rail-f", 102)
+ expect(onPreview).toHaveBeenLastCalledWith({ source: { kind: "server", id: "a" }, target: { kind: "folder", id: "f" }, operation: "combine" })
+ act(() => vi.advanceTimersByTime(500))
+ expect(state.expanded).toEqual([])
+ ui.hover("rail-f", 138)
+ expect(onPreview).toHaveBeenLastCalledWith(expect.objectContaining({ operation: "combine" }))
+ act(() => ui.backend.simulateHover([], {}))
+ expect(onPreview).toHaveBeenLastCalledWith(null)
+ ui.hover("rail-f", 120); ui.cancel()
+ act(() => vi.advanceTimersByTime(500))
+ expect(state.expanded).toEqual([])
+ expect(onDrop).not.toHaveBeenCalled()
+ } finally { vi.useRealTimers() }
+ })
+ it("rejects an eleventh-folder center drop without changing it to reorder", () => {
+ const folderIds = Array.from({ length: 10 }, (_, index) => `f${index}`)
+ const capped: RailState = {
+ serverIds: ["a", "b", ...folderIds.map((id) => `s${id}`)],
+ folderIds, folders: Object.fromEntries(folderIds.map((id) => [id, [`s${id}`]])), expanded: [],
+ }
+ const source = { kind: "server", id: "a" } as const
+ const target = { kind: "server", id: "b" } as const
+ expect(railInstructionAt(capped, source, target, 0.5)).toBeNull()
+ expect(railInstructionAt(capped, source, target, 0.9)).toMatchObject({ operation: "reorder-after" })
+ })
+ it("uses official touch activation settings and keeps a native HTML5 preview", () => {
+ expect(communityDndOptions.backends.map((entry) => entry.id)).toEqual(["html5", "touch"])
+ expect(communityDndOptions.backends[1].options).toMatchObject({ delayTouchStart: 650, touchSlop: 8 })
+ })
+ it("commits one rail instruction on drop; Escape commits nothing", () => {
+ const onDrop = vi.fn(), onCancel = vi.fn()
+ const ui = setup(<RailFixture onDrop={onDrop} onCancel={onCancel} />)
+ ui.node("rail-b").getBoundingClientRect = () => ({ top: 0, height: 40 }) as DOMRect
+ ui.start("rail-a"); ui.hover("rail-b", 38)
+ expect(onDrop).not.toHaveBeenCalled()
+ ui.drop()
+ expect(onDrop).toHaveBeenCalledExactlyOnceWith({ source: { kind: "server", id: "a" }, target: { kind: "server", id: "b" }, operation: "reorder-after" })
+ ui.start("rail-a"); ui.hover("rail-b", 20); ui.cancel()
+ expect(onDrop).toHaveBeenCalledTimes(1)
+ expect(onCancel).toHaveBeenCalledTimes(1)
+ })
+ it("keeps hover structural state unchanged and settles text/forum order on drop", () => {
+ const onDrop = vi.fn()
+ const ui = setup(<TreeFixture onDrop={onDrop} />)
+ const before = ui.node("tree-order").textContent
+ ui.start("text"); ui.hover("forum")
+ expect(ui.node("tree-order").textContent).toBe(before)
+ ui.drop()
+ expect(ui.node("tree-order").textContent).toBe(before)
+ expect(onDrop).toHaveBeenCalledWith({ active: { id: "text", kind: "channel" }, over: { id: "public", kind: "category" }, placement: "append" })
+ expect(onDrop).toHaveBeenCalledTimes(1)
+ })
+ it("accepts an empty category, rejects privacy changes, and allows private/private", () => {
+ const onDrop = vi.fn()
+ const ui = setup(<TreeFixture onDrop={onDrop} />)
+ ui.start("text"); ui.hover("empty-handle"); ui.drop()
+ expect(onDrop).toHaveBeenLastCalledWith({ active: { id: "text", kind: "channel" }, over: { id: "empty", kind: "category" }, placement: "append" })
+ ui.start("forum"); ui.hover("private"); ui.drop()
+ expect(onDrop).toHaveBeenCalledTimes(1)
+ ui.start("secret"); ui.hover("private2-handle"); ui.drop()
+ expect(onDrop).toHaveBeenLastCalledWith({ active: { id: "secret", kind: "channel" }, over: { id: "private2", kind: "category" }, placement: "append" })
+ expect(onDrop).toHaveBeenCalledTimes(2)
+ })
+ it("shows valid header feedback and updates row edges without stale hover snapshots", () => {
+ const ui = setup(<TreeFixture onDrop={vi.fn()} />)
+ ui.node("forum").getBoundingClientRect = () => ({ top: 100, bottom: 132, left: 0, right: 100, height: 32, width: 100 }) as DOMRect
+ ui.start("text"); ui.hover("empty-handle")
+ expect(ui.node("empty")).toHaveAttribute("data-placement", "append")
+ ui.hover("private-handle")
+ expect(ui.node("empty")).not.toHaveAttribute("data-placement")
+ expect(ui.node("private")).not.toHaveAttribute("data-placement")
+ ui.hover("forum", 130)
+ expect(ui.node("forum")).toHaveAttribute("data-placement", "append")
+ expect(ui.container.querySelector('[data-channel-drop-end="public"]')).toHaveAttribute("data-drop-visible", "true")
+ ui.hover("forum", 102)
+ expect(ui.node("forum")).not.toHaveAttribute("data-placement")
+ ui.cancel()
+ expect(ui.node("empty")).not.toHaveAttribute("data-placement")
+ })
+ it("keeps a nearby end target stable while its landing area opens and closes", () => {
+ const onDrop = vi.fn()
+ const ui = setup(<TreeFixture onDrop={onDrop} />)
+ const end = ui.container.querySelector<HTMLElement>('[data-channel-drop-end="empty"]')!
+ const anchor = end.parentElement!
+ anchor.getBoundingClientRect = () => ({ top: 100, bottom: 100, left: 0, right: 100, height: 0, width: 100 }) as DOMRect
+ ui.start("text")
+ act(() => ui.backend.simulateHover([], { clientOffset: { x: 20, y: 86 } }))
+ expect(end).not.toHaveAttribute("data-drop-visible")
+ act(() => ui.backend.simulateHover([ui.targets.get(end)!], { clientOffset: { x: 20, y: 108 } }))
+ expect(end).toHaveAttribute("data-drop-visible", "true")
+ expect(end).toHaveClass("absolute", "h-4")
+ expect(anchor).toHaveClass("h-0")
+ expect(anchor.getBoundingClientRect().top).toBe(100)
+ expect(onDrop).not.toHaveBeenCalled()
+ ui.drop()
+ expect(onDrop).toHaveBeenCalledExactlyOnceWith({ active: { id: "text", kind: "channel" }, over: { id: "empty", kind: "category" }, placement: "append" })
+ expect(end).not.toHaveAttribute("data-drop-visible")
+ ui.start("text")
+ act(() => ui.backend.simulateHover([], { clientOffset: { x: 20, y: 149 } }))
+ expect(end).not.toHaveAttribute("data-drop-visible")
+ ui.cancel()
+ expect(onDrop).toHaveBeenCalledTimes(1)
+ })
+ it("uses existing space before an empty root without capturing the first header", () => {
+ const onDrop = vi.fn()
+ const ui = setup(<TreeFixture onDrop={onDrop} />)
+ const end = ui.container.querySelector<HTMLElement>(`[data-channel-drop-end="${UNCATEGORIZED_CATEGORY_ID}"]`)!
+ end.parentElement!.getBoundingClientRect = () => ({ top: 100, bottom: 100, left: 0, right: 100, height: 0, width: 100 }) as DOMRect
+ ui.start("text")
+ act(() => ui.backend.simulateHover([ui.targets.get(end)!], { clientOffset: { x: 20, y: 92 } }))
+ expect(end).toHaveAttribute("data-drop-visible", "true")
+ expect(end).toHaveClass("absolute", "bottom-0", "h-4")
+ act(() => ui.backend.simulateHover([], { clientOffset: { x: 20, y: 100 } }))
+ expect(end).not.toHaveAttribute("data-drop-visible")
+ act(() => ui.backend.simulateHover([ui.targets.get(end)!], { clientOffset: { x: 20, y: 92 } }))
+ ui.drop()
+ expect(onDrop).toHaveBeenCalledExactlyOnceWith({ active: { id: "text", kind: "channel" }, over: { id: UNCATEGORIZED_CATEGORY_ID, kind: "category" }, placement: "append" })
+ })
+ it("uses the current root end geometry after a canonical update while idle", () => {
+ const onDrop = vi.fn()
+ function RootFixture() {
+ const [before, setBefore] = useState(true)
+ return <><button data-testid="root-filled" onClick={() => setBefore(false)}>Fill root</button><TreeFixture onDrop={onDrop} rootBefore={before} /></>
+ }
+ const ui = setup(<RootFixture />)
+ const end = ui.container.querySelector<HTMLElement>(`[data-channel-drop-end="${UNCATEGORIZED_CATEGORY_ID}"]`)!
+ end.parentElement!.getBoundingClientRect = () => ({ top: 100, bottom: 100, left: 0, right: 100, height: 0, width: 100 }) as DOMRect
+ fireEvent.click(ui.node("root-filled"))
+ expect(ui.container.querySelector(`[data-channel-drop-end="${UNCATEGORIZED_CATEGORY_ID}"]`)).toBe(end)
+ ui.start("text")
+ act(() => ui.backend.simulateHover([ui.targets.get(end)!], { clientOffset: { x: 20, y: 108 } }))
+ expect(end).toHaveClass("top-0", "h-4")
+ expect(end).toHaveAttribute("data-drop-visible", "true")
+ ui.drop()
+ expect(onDrop).toHaveBeenCalledTimes(1)
+ })
+ it("moves category blocks and cancels a channel without changing its owner", () => {
+ const onDrop = vi.fn()
+ const ui = setup(<TreeFixture onDrop={onDrop} />)
+ ui.start("public-handle"); ui.hover("empty"); ui.drop()
+ expect(onDrop).toHaveBeenCalledWith({ active: { id: "public", kind: "category" }, over: { id: "empty", kind: "category" }, placement: "after" })
+ const before = ui.node("tree-order").textContent
+ ui.start("text"); ui.hover("empty"); ui.cancel()
+ expect(ui.node("tree-order").textContent).toBe(before)
+ expect(onDrop).toHaveBeenCalledTimes(1)
+ })
+ it("persists only real non-pending categories from the actual sidebar", () => {
+ const onReorder = vi.fn()
+ const ui = setup(<ActualSidebarFixture onReorder={onReorder} />)
+ ui.start(tid.categoryHeader("public"))
+ const target = ui.node(tid.categoryHeader("empty")).closest<HTMLElement>("[data-channel-category]")!
+ act(() => ui.backend.simulateHover([ui.targets.get(target)!], { clientOffset: { x: 20, y: 20 } }))
+ ui.drop()
+ expect(onReorder).toHaveBeenCalledExactlyOnceWith(["empty", "public", "private", "private2"])
+ })
+ it("reserves touch hold for dragging without stopping native input or opening a menu", async () => {
+ vi.useFakeTimers()
+ const touchStarted = vi.fn()
+ document.addEventListener("touchstart", touchStarted)
+ try {
+ const ui = setup(<ActualSidebarFixture onReorder={() => {}} />)
+ const node = ui.node(tid.categoryHeader("public"))
+ fireEvent.touchStart(node, { touches: [{ identifier: 1, clientX: 20, clientY: 20, target: node }] })
+ await act(async () => { vi.advanceTimersByTime(700) })
+ expect(touchStarted).toHaveBeenCalledTimes(1)
+ expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ fireEvent.touchEnd(node, { touches: [] })
+ } finally {
+ document.removeEventListener("touchstart", touchStarted)
+ vi.useRealTimers()
+ }
+ })
+ it("does not let rail and channel items drop into the other scope", () => {
+ const railDrop = vi.fn(), treeDrop = vi.fn()
+ const ui = setup(<><RailFixture onDrop={railDrop} /><TreeFixture onDrop={treeDrop} /></>)
+ ui.start("rail-a"); ui.hover("empty"); ui.drop()
+ ui.start("text"); ui.hover("rail-b"); ui.drop()
+ expect(railDrop).not.toHaveBeenCalled()
+ expect(treeDrop).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/components/community/community-dnd.tsx b/src/web/src/components/community/community-dnd.tsx
new file mode 100644
index 000000000..fe94c5485
--- /dev/null
+++ b/src/web/src/components/community/community-dnd.tsx
@@ -0,0 +1,59 @@
+"use client"
+
+import { useContext, useEffect, useMemo, type ReactNode, type RefObject } from "react"
+import { DndContext, DndProvider, useDragDropManager } from "react-dnd"
+import { createVerticalStrength, useDndScrolling } from "react-dnd-scrolling"
+import { HTML5Backend } from "react-dnd-html5-backend"
+import { TouchBackend } from "react-dnd-touch-backend"
+import { MouseTransition, MultiBackend, TouchTransition } from "dnd-multi-backend"
+
+export const communityDndOptions = {
+ backends: [
+ { id: "html5", backend: HTML5Backend, transition: MouseTransition },
+ {
+ id: "touch", backend: TouchBackend, transition: TouchTransition,
+ options: { delayTouchStart: 650, touchSlop: 8, enableMouseEvents: false, enableKeyboardEvents: true, ignoreContextMenu: true },
+ },
+ ],
+}
+
+export function CommunityDndProvider({ children }: { children: ReactNode }) {
+ const { dragDropManager } = useContext(DndContext)
+ if (dragDropManager) return children
+ return <DndProvider backend={MultiBackend} options={communityDndOptions}>{children}</DndProvider>
+}
+
+export function useDndCancellation(onCancel: () => void) {
+ const manager = useDragDropManager()
+ useEffect(() => {
+ const cancel = () => {
+ if (!manager.getMonitor().isDragging()) return
+ onCancel()
+ manager.getActions().endDrag()
+ }
+ const key = (event: KeyboardEvent) => { if (event.key === "Escape") cancel() }
+ const visibility = () => { if (document.hidden) cancel() }
+ window.addEventListener("keydown", key, true)
+ window.addEventListener("blur", cancel)
+ window.addEventListener("touchcancel", cancel)
+ document.addEventListener("visibilitychange", visibility)
+ return () => {
+ window.removeEventListener("keydown", key, true)
+ window.removeEventListener("blur", cancel)
+ window.removeEventListener("touchcancel", cancel)
+ document.removeEventListener("visibilitychange", visibility)
+ }
+ }, [manager, onCancel])
+}
+
+export function useCommunityDndScrolling(ref: RefObject<HTMLElement | null>, itemType: string) {
+ const manager = useDragDropManager()
+ const options = useMemo(() => {
+ const strength = createVerticalStrength(80)
+ return {
+ horizontalStrength: () => 0,
+ verticalStrength: (box: Parameters<typeof strength>[0], point: Parameters<typeof strength>[1]) => manager.getMonitor().getItemType() === itemType ? strength(box, point) : 0,
+ }
+ }, [manager, itemType])
+ useDndScrolling(ref, options)
+}
diff --git a/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts b/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts
index 70647895e..8416ebdf0 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts
+++ b/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts
@@ -1,13 +1,21 @@
import React from "react"
-import { describe, expect, expectTypeOf, it, vi } from "vitest"
+import { beforeEach, describe, expect, expectTypeOf, it, vi } from "vitest"
import { fireEvent, render } from "@/test/react-dom-harness"
import { InboxPopover } from "./community-inbox-popover"
-import type { UnreadDm, UnreadServer } from "@/lib/community/models/inbox"
+import type { Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"
import { tid } from "@/lib/community/testids"
+import type { CommunityProfile } from "@/lib/community/models/people"
vi.mock("next/link", async () => ({ default: (await import("@/test/community-link-mock")).CommunityLinkMock }))
-const mocks = vi.hoisted(() => ({ tabs: vi.fn() }))
+const mocks = vi.hoisted(() => ({ tabs: vi.fn(), profiles: new Map<string, CommunityProfile>() }))
+
+vi.mock("@/lib/community-db/projections", async (importOriginal) => ({
+ ...await importOriginal<typeof import("@/lib/community-db/projections")>(),
+ useCanonicalProfilesByUserId: () => mocks.profiles,
+}))
+
+beforeEach(() => mocks.profiles.clear())
vi.mock("@/components/ui/tabs", () => ({
Tabs: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) => {
@@ -69,6 +77,29 @@ function popover(onOpenChannel: ReturnType<typeof vi.fn>, onOpenThread: ReturnTy
}
describe("InboxPopover thread opener rows", () => {
+ it.each([undefined, 0, 3])("shows a known positive DM unread count: %s", (unreadCount) => {
+ mocks.profiles.set("peer", { id: "peer", name: "Mika", discriminator: "0042" })
+ const dm: UnreadDm = { channelId: "dm1", otherUserId: "peer", otherUserName: "Mika", otherUserDiscriminator: "0042", otherUserAvatar: "M", otherUserAvatarVersion: 0, lastMessageAt: "2026-10-24T00:00:00Z", unreadCount }
+ const onOpenDm = vi.fn()
+ const renderer = render(React.createElement(InboxPopover, {
+ unreads: [], unreadDms: [dm], mentions: [], marked: [], hasProjectedUnreads: true, hasProjectedMentions: false, onOpenDm,
+ }))
+ const row = renderer.getByTestId(tid.inboxUnreadDm("dm1"))
+ expect(row.textContent).toBe(unreadCount ? "Mika#00423" : "Mika#0042")
+ expect(row.querySelector(".text-xs")?.textContent).toBe("#0042")
+ fireEvent.click(row)
+ expect(onOpenDm).toHaveBeenCalledExactlyOnceWith(dm)
+ })
+
+ it("shows the server identity and leaves unread navigation rows without chevrons", () => {
+ const renderer = render(popover(vi.fn(), vi.fn()))
+ const icon = renderer.getByRole("img", { name: "Server" })
+ expect(icon.style.width).toBe("14px")
+ expect(icon.style.height).toBe("14px")
+ const unreads = renderer.getByTestId(tid.inboxTabScroll("unreads"))
+ expect(unreads.querySelector(".lucide-chevron-right")).toBeNull()
+ })
+
it("accepts the generic thread callback used by opener-backed buttons", () => {
expectTypeOf<Parameters<typeof InboxPopover>[0]>().toExtend<{
onOpenThread?: (
@@ -215,6 +246,33 @@ describe("InboxPopover thread opener rows", () => {
})
})
+describe("InboxPopover mention rows", () => {
+ it("shows the full handle, location and content with a direct independent Remove button", () => {
+ mocks.profiles.set("author", { id: "author", name: "Alice", discriminator: "0042", avatar: "A" })
+ const onOpenMention = vi.fn()
+ const onDeleteMention = vi.fn()
+ const mention: Mention = { id: "mention-1", server: "Workshop", channel: "general", m: { id: "message-1", type: "chat", authorId: "author", content: "Hello there" } }
+ const renderer = render(React.createElement(InboxPopover, {
+ unreads: [], unreadDms: [], mentions: [mention], marked: [],
+ hasProjectedUnreads: false, hasProjectedMentions: true,
+ onOpenMention, onDeleteMention,
+ }))
+ const handle = renderer.getByText("Alice#0042")
+ const location = renderer.getByText(/Workshop ·/)
+ const content = renderer.getByText("Hello there")
+ expect(handle.parentElement?.nextElementSibling).toBe(location)
+ expect(location.nextElementSibling).toBe(content)
+ const remove = renderer.getByRole("button", { name: "Mark mention as read" })
+ expect(remove.querySelector(".lucide-check")).not.toBeNull()
+ expect(renderer.queryByRole("button", { name: "More" })).toBeNull()
+ fireEvent.click(remove)
+ expect(onDeleteMention).toHaveBeenCalledExactlyOnceWith("mention-1")
+ expect(onOpenMention).not.toHaveBeenCalled()
+ fireEvent.click(handle)
+ expect(onOpenMention).toHaveBeenCalledExactlyOnceWith(mention)
+ })
+})
+
describe("InboxPopover friend requests", () => {
const friendRequest = {
row: {
@@ -227,7 +285,26 @@ describe("InboxPopover friend requests", () => {
},
}
+ it.each([
+ { requests: true, dms: false, servers: false, separators: 0 },
+ { requests: false, dms: true, servers: false, separators: 0 },
+ { requests: false, dms: false, servers: true, separators: 0 },
+ { requests: true, dms: true, servers: false, separators: 1 },
+ { requests: true, dms: false, servers: true, separators: 1 },
+ { requests: false, dms: true, servers: true, separators: 1 },
+ { requests: true, dms: true, servers: true, separators: 2 },
+ ])("separates only nonempty sections: $requests/$dms/$servers", ({ requests, dms, servers, separators }) => {
+ const renderer = render(React.createElement(InboxPopover, {
+ friendRequests: requests ? [friendRequest] : [],
+ unreads: servers ? unreadFixture() : [],
+ unreadDms: dms ? [{ channelId: "dm1", otherUserId: "peer", otherUserName: "Peer", otherUserDiscriminator: "0042", otherUserAvatar: "P", otherUserAvatarVersion: 0, lastMessageAt: "2026-10-24T00:00:00Z" }] : [],
+ mentions: [], marked: [], hasProjectedUnreads: dms || servers, hasProjectedMentions: false,
+ }))
+ expect(renderer.getByTestId(tid.inboxTabScroll("unreads")).querySelectorAll('[data-slot="separator"]')).toHaveLength(separators)
+ })
+
it("renders requests before DMs and servers with sibling navigation/actions", () => {
+ mocks.profiles.set("u_friend", { id: "u_friend", name: "Ada", discriminator: "0001" })
const onOpenFriendRequests = vi.fn()
const onAcceptFriendRequest = vi.fn()
const renderer = render(React.createElement(InboxPopover, {
@@ -251,10 +328,13 @@ describe("InboxPopover friend requests", () => {
onOpenThread: vi.fn(),
}))
const text = renderer.container.textContent ?? ""
+ expect(text).not.toContain("sent you a friend request")
expect(text.indexOf("Friend requests — 1")).toBeLessThan(text.indexOf("Direct Messages"))
expect(text.indexOf("Direct Messages")).toBeLessThan(text.indexOf("Server"))
const open = renderer.getByTestId(tid.inboxFriendRequestOpen("fr_1"))
+ expect(open.textContent).toBe("Ada#0001")
+ expect(open.querySelector(".text-xs")?.textContent).toBe("#0001")
const accept = renderer.getByTestId(tid.inboxFriendRequestAccept("fr_1"))
expect(open.contains(accept)).toBe(false)
fireEvent.click(accept)
diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsx
index 7f74919a3..bfb65c17d 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.tsx
+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx
@@ -1,10 +1,12 @@
-import { Bookmark, Check, ChevronRight, Inbox, LoaderCircle, MoreHorizontal, Trash2, X } from "lucide-react"
-import { stripInlineMarkup } from "@alook/shared"
+import { Bookmark, Check, Inbox, LoaderCircle, MoreHorizontal, Trash2, X } from "lucide-react"
+import { formatHandle, stripInlineMarkup } from "@alook/shared"
import { EntityIcon } from "../entity-icon"
+import { ServerIcon } from "../server-icon"
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"
import { Skeleton } from "@/components/ui/skeleton"
+import { Separator } from "@/components/ui/separator"
import { Button } from "@/components/ui/button"
import { CommunityNavigationLink } from "./community-navigation-link"
import { Avatar } from "../avatar"
@@ -18,6 +20,7 @@ import { tid } from "@/lib/community/testids"
import type { CommunityProfile } from "@/lib/community/models/people"
import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { readCommunityProfile } from "@/lib/community/profile-read"
+import { avatarInitial } from "@/lib/community/avatar"
import {
useLayoutEffect,
useRef,
@@ -104,7 +107,7 @@ function InboxScrollBody({
)
}
-function MentionBadge({ count }: { count: number }) {
+function InboxCountBadge({ count }: { count: number }) {
if (count <= 0) return null
return (
<span className="grid h-5 min-w-5 place-items-center rounded-full bg-primary px-1 text-xs font-semibold text-primary-foreground">
@@ -174,7 +177,6 @@ function UnreadsTab({ friendRequests, servers, dms, loading, error, onRetry, onO
<Skeleton className="size-7 shrink-0 rounded-full" />
<div className="flex min-w-0 flex-1 flex-col gap-2">
<Skeleton className="h-3.5 w-28 rounded" />
- <Skeleton className="h-3 w-40 rounded" />
</div>
</div>
)
@@ -199,8 +201,7 @@ function UnreadsTab({ friendRequests, servers, dms, loading, error, onRetry, onO
>
<Avatar label={profile.avatar} seed={request.userId} size={28} />
<span className="min-w-0 flex-1">
- <span className="block truncate font-medium">{profile.name}</span>
- <span className="block truncate text-xs text-muted-foreground">sent you a friend request</span>
+ <span className="block truncate font-medium">{profile.name}{profile.discriminator && <span className="ml-1 text-xs font-normal tracking-wide text-muted-foreground">#{profile.discriminator}</span>}</span>
</span>
</button>
<div className="flex shrink-0 gap-1">
@@ -244,6 +245,8 @@ function UnreadsTab({ friendRequests, servers, dms, loading, error, onRetry, onO
</div>
)}
{visibleDms.length > 0 && (
+ <>
+ {friendRequests.length > 0 && <Separator className="mb-3" />}
<div className="mb-3">
<div className="px-2 pb-1 text-xs font-semibold text-muted-foreground">Direct Messages</div>
{visibleDms.map((d) => {
@@ -260,39 +263,42 @@ function UnreadsTab({ friendRequests, servers, dms, loading, error, onRetry, onO
className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-accent"
>
<Avatar label={profile.avatar} seed={d.otherUserId} size={24} />
- <span className="min-w-0 flex-1 truncate">{profile.name}</span>
- <ChevronRight className="size-4 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate">{profile.name}{profile.discriminator && <span className="ml-1 text-xs font-normal tracking-wide text-muted-foreground">#{profile.discriminator}</span>}</span>
+ <InboxCountBadge count={d.unreadCount ?? 0} />
</CommunityNavigationLink>
)
})}
</div>
+ </>
)}
+ {visibleServers.length > 0 && (friendRequests.length > 0 || visibleDms.length > 0) && <Separator className="mb-3" />}
{visibleServers.map(({ server, channels }) => (
<div key={server.serverId} className="mb-3">
- <div className="px-2 pb-1 text-xs font-semibold text-muted-foreground">{server.serverName}</div>
+ <div className="flex items-center gap-2 px-2 pb-1 text-sm font-semibold text-muted-foreground">
+ <ServerIcon id={server.serverId} name={server.serverName} initial={avatarInitial(server.serverName)} icon={server.serverIcon} size={14} className="shrink-0 rounded-sm" />
+ <span className="truncate">{server.serverName}</span>
+ </div>
{channels.map(({ channel, directVisible, children }) => (
<div key={channel.channelId}>
<button
data-testid={tid.inboxUnreadChannel(channel.channelId)}
onClick={() => onOpenChannel?.(server, channel, directVisible)}
- className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-accent"
+ className="flex w-full items-center gap-2 rounded-md py-2 pl-6 pr-2 text-left text-sm hover:bg-accent"
>
- <EntityIcon kind={channel.type} className="size-4 shrink-0 text-muted-foreground" />
+ <EntityIcon kind={channel.type} className="size-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate">{channel.channelName}</span>
- {directVisible && <MentionBadge count={channel.mentionCount} />}
- <ChevronRight className="size-4 shrink-0 text-muted-foreground" />
+ {directVisible && <InboxCountBadge count={channel.mentionCount} />}
</button>
{children.map((child) => (
<button
key={child.channelId}
data-testid={tid.inboxUnreadChild(child.channelId)}
onClick={() => onOpenThread(server, channel, child)}
- className="flex w-full items-center gap-2 rounded-md py-1.5 pl-8 pr-2 text-left text-sm hover:bg-accent"
+ className="flex w-full items-center gap-2 rounded-md py-1.5 pl-10 pr-2 text-left text-sm hover:bg-accent"
>
<EntityIcon kind={child.type} className="size-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate text-muted-foreground">{child.channelName}</span>
- <MentionBadge count={child.mentionCount} />
- <ChevronRight className="size-4 shrink-0 text-muted-foreground" />
+ <InboxCountBadge count={child.mentionCount} />
</button>
))}
</div>
@@ -328,6 +334,7 @@ function MentionsTab({ mentions, loading, error, onRetry, onOpenMention, onDelet
<div className="flex min-w-0 flex-1 flex-col gap-2">
<Skeleton className="h-3.5 w-2/5 rounded" />
<Skeleton className="h-3 w-3/4 rounded" />
+ <Skeleton className="h-3 w-full rounded" />
</div>
</div>
)
@@ -337,31 +344,23 @@ function MentionsTab({ mentions, loading, error, onRetry, onOpenMention, onDelet
mn.m.authorId ?? "",
)
return (
- <div key={mn.id} className="group flex w-full items-start gap-3 rounded-md p-2 text-left hover:bg-accent">
- <button onClick={() => onOpenMention?.(mn)} className="flex min-w-0 flex-1 items-start gap-3 text-left">
+ <div key={mn.id} className="grid w-full grid-cols-[minmax(0,1fr)_20px] items-start rounded-md p-2 text-left hover:bg-accent">
+ <button onClick={() => onOpenMention?.(mn)} className="col-span-2 col-start-1 row-start-1 flex min-w-0 items-start gap-3 text-left">
<Avatar label={author.avatar} seed={mn.m.authorId} size={36} />
<div className="min-w-0 flex-1">
- <div className="text-sm">
- <span className="font-medium">{author.name}</span>{" "}
- <span className="text-xs text-muted-foreground">
- {mn.kind === "reply" ? "replied to you" : "mentioned you"} in {mn.server} · <ChannelIcon className="inline h-[1em] w-auto align-[-0.1em]" />{mn.channel}
- </span>
+ <div className="flex h-5 items-center pr-7 text-sm font-medium leading-5">
+ <span className="truncate">{author.discriminator ? formatHandle(author.name, author.discriminator) : author.name}</span>
+ </div>
+ <div className="truncate text-[11px] leading-4 text-muted-foreground/75">
+ {mn.server} · <ChannelIcon className="inline h-[1em] w-auto align-[-0.1em]" />{mn.channel}
</div>
<div className="truncate text-sm text-muted-foreground">{stripInlineMarkup(mn.m.content ?? "")}</div>
</div>
</button>
{onDeleteMention && (
- <DropdownMenu>
- <DropdownMenuTrigger render={<button className="mt-1 grid size-6 shrink-0 place-items-center rounded-md text-muted-foreground opacity-0 hover:bg-accent hover:text-foreground group-hover:opacity-100" aria-label="More" />}>
- <MoreHorizontal className="size-4" />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" sideOffset={4} className="w-36">
- <DropdownMenuItem onClick={() => onDeleteMention(mn.id)}>
- <Trash2 className="size-4" />
- Remove
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ <Button variant="secondary" size="icon" onClick={() => onDeleteMention(mn.id)} aria-label="Mark mention as read" className="z-10 col-start-2 row-start-1 size-5 text-muted-foreground">
+ <Check className="size-3.5" />
+ </Button>
)}
</div>
)
diff --git a/src/web/src/components/community/shell/rail-folder.test.ts b/src/web/src/components/community/shell/rail-folder.test.ts
index 8a20ec370..3c13c75df 100644
--- a/src/web/src/components/community/shell/rail-folder.test.ts
+++ b/src/web/src/components/community/shell/rail-folder.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, it, vi } from "vitest"
-import { railFolderPropsEqual } from "./rail-folder"
+import { createElement } from "react"
+import { renderToStaticMarkup } from "react-dom/server"
+import { RailFolder, railFolderPropsEqual } from "./rail-folder"
const base = {
folderId: "folder",
@@ -12,6 +14,14 @@ const base = {
}
describe("RailFolder memo boundary", () => {
+ it("retracts the expanded folder bar and restores aggregate state only when collapsed", () => {
+ const expanded = renderToStaticMarkup(createElement(RailFolder, { ...base, open: true, active: true, unread: true }))
+ expect(expanded).toContain("h-0 opacity-0")
+ expect(expanded).not.toContain("group-hover:h-5")
+ const collapsed = renderToStaticMarkup(createElement(RailFolder, { ...base, active: true, unread: true }))
+ expect(collapsed).toContain("h-8")
+ expect(collapsed).not.toContain("opacity-0")
+ })
it("rerenders for aggregate unread/open/active but ignores callback identity", () => {
expect(railFolderPropsEqual(base, { ...base, onToggle: vi.fn() })).toBe(true)
expect(railFolderPropsEqual(base, { ...base, unread: true })).toBe(false)
diff --git a/src/web/src/components/community/shell/rail-folder.tsx b/src/web/src/components/community/shell/rail-folder.tsx
index b195c5cef..7a4f485eb 100644
--- a/src/web/src/components/community/shell/rail-folder.tsx
+++ b/src/web/src/components/community/shell/rail-folder.tsx
@@ -1,13 +1,14 @@
"use client"
import { memo, useEffect, useRef } from "react"
-import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem } from "@/components/ui/context-menu"
+import { useAtom, useCreateAtom } from "@tanstack/react-store"
+import { Folder } from "lucide-react"
import { RailIndicator } from "./rail-indicator"
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"
import { ServerIcon } from "@/components/community/server-icon"
import { tid } from "@/lib/community/testids"
import type { FolderServer } from "@/lib/community/models/navigation"
-import type { RailEntity, RailOperation } from "@/lib/community/server-rail-model"
+import { RailDndBinding, type RailDndController } from "./use-server-rail-dnd"
type RailFolderProps = {
folderId: string
@@ -17,122 +18,50 @@ type RailFolderProps = {
unread: boolean
onToggle: () => void
folderServers: FolderServer[]
- onUngroup?: () => void
dragging?: boolean
- preview?: RailOperation | null
- registerItem?: (
- entity: RailEntity,
- element: HTMLElement,
- dragHandle: HTMLElement,
- ) => () => void
+ dnd?: RailDndController
dragDescriptionId?: string
}
-function RailFolderImpl({
- folderId, name, open, active, unread, onToggle, folderServers, onUngroup, dragging: isDragActive,
- preview, registerItem, dragDescriptionId,
-}: RailFolderProps) {
+function RailFolderImpl({ folderId, name, open, active, unread, onToggle, folderServers, dragging, dnd, dragDescriptionId }: RailFolderProps) {
const rootRef = useRef<HTMLDivElement>(null)
const buttonRef = useRef<HTMLButtonElement>(null)
- useEffect(() => {
- if (!registerItem || !rootRef.current || !buttonRef.current) return
- return registerItem(
- { kind: "folder", id: folderId },
- rootRef.current,
- buttonRef.current,
- )
- }, [folderId, registerItem])
-
+ const [tooltipOpen, setTooltipOpen] = useAtom(useCreateAtom(false))
+ useEffect(() => { if (dragging) setTooltipOpen(false) }, [dragging, setTooltipOpen])
return (
- <Tooltip>
- <TooltipTrigger render={<span className="flex w-full justify-center" />}>
- <ContextMenu>
- <ContextMenuTrigger
- render={<div ref={rootRef} style={{ opacity: isDragActive ? 0.3 : 1 }} className="group relative flex w-full justify-center" />}
- >
- {(preview === "reorder-before" || preview === "reorder-after") && (
- <div
- data-testid={tid.serverRailInsertFolder(folderId)}
- className={`pointer-events-none absolute left-1/2 z-10 h-0.5 w-9 -translate-x-1/2 rounded-full bg-primary ${preview === "reorder-before" ? "-top-1" : "-bottom-1"}`}
- />
- )}
- <RailIndicator
- active={active}
- unread={unread}
- testId={tid.serverRailFolderIndicator(folderId)}
- />
- <button
- ref={buttonRef}
- data-testid={tid.serverRailFolder(folderId)}
- data-dragging={isDragActive || undefined}
- data-rail-preview={preview ?? undefined}
- aria-label={name}
- aria-describedby={dragDescriptionId}
- aria-keyshortcuts="Space ArrowUp ArrowDown Escape"
- onClick={onToggle}
- className="group/folder grid size-11 cursor-pointer place-items-center focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none active:cursor-grabbing [-webkit-touch-callout:none]"
- >
- <span data-rail-drag-preview className={[
- "pointer-events-none grid size-10 grid-cols-2 gap-1 p-2 transition-[border-radius,background-color] duration-150",
- open ? "rounded-xl bg-primary/15" : "rounded-[18px] bg-accent group-hover/folder:rounded-xl group-hover/folder:bg-primary/20",
- preview === "combine" ? "bg-primary/10 outline outline-2! outline-primary" : "",
- ].join(" ")}
- >
- {Array.from({ length: 4 }).map((_, i) => {
- const s = folderServers[i]
- return s ? (
- <ServerIcon
- key={s.id}
- id={s.id}
- name={s.name}
- initial={s.initial}
- icon={s.icon}
- size={10}
- fontSize={7}
- className={[
- "relative grid aspect-square place-items-center overflow-hidden rounded-sm text-[7px] font-semibold",
- s.icon ? "bg-card text-muted-foreground" : "text-white [text-shadow:0_1px_1px_rgb(0_0_0/0.35)]",
- ].join(" ")}
- />
- ) : (
- <span key={i} className="aspect-square rounded-sm bg-card/50" />
- )
- })}
- </span>
- </button>
- </ContextMenuTrigger>
- <ContextMenuContent className="w-52">
- <ContextMenuItem onClick={onUngroup}>Ungroup</ContextMenuItem>
- </ContextMenuContent>
- </ContextMenu>
+ <Tooltip open={!dragging && tooltipOpen} onOpenChange={setTooltipOpen}>
+ <TooltipTrigger render={<div ref={rootRef} className="group relative flex h-10 w-full justify-center" />}>
+ {dnd && <RailDndBinding dnd={dnd} entity={{ kind: "folder", id: folderId }} element={rootRef} handle={buttonRef} />}
+ <RailIndicator active={active} unread={unread} hidden={dragging || open} testId={tid.serverRailFolderIndicator(folderId)} />
+ <button ref={buttonRef} data-testid={tid.serverRailFolder(folderId)} aria-label={name} aria-expanded={open}
+ aria-describedby={dragDescriptionId} data-dragging={dragging || undefined}
+ onClick={onToggle} onContextMenu={(event) => event.preventDefault()} style={{ opacity: dragging ? 0.3 : 1 }}
+ className="absolute left-1/2 top-1/2 grid size-11 -translate-x-1/2 -translate-y-1/2 cursor-pointer place-items-center rounded-xl text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none active:cursor-grabbing [-webkit-touch-callout:none]">
+ <RailFolderIcon open={open} folderServers={folderServers} />
+ </button>
</TooltipTrigger>
<TooltipContent side="right" sideOffset={8}>{name}</TooltipContent>
</Tooltip>
)
}
-
+export function RailFolderIcon({ open, folderServers }: Pick<RailFolderProps, "open" | "folderServers">) {
+ return open ? <Folder className="pointer-events-none size-6" /> : (
+ <span className="pointer-events-none grid size-10 grid-cols-2 gap-1 p-2">
+ {Array.from({ length: 4 }).map((_, index) => {
+ const server = folderServers[index]
+ return server ? <ServerIcon key={server.id} id={server.id} name={server.name} initial={server.initial}
+ icon={server.icon} size={10} fontSize={7}
+ className={`relative grid aspect-square place-items-center overflow-hidden rounded-sm text-[7px] font-semibold ${server.icon ? "bg-card text-muted-foreground" : "text-white [text-shadow:0_1px_1px_rgb(0_0_0/0.35)]"}`} />
+ : <span key={index} className="aspect-square rounded-sm bg-card/50" />
+ })}
+ </span>
+ )
+}
export function railFolderPropsEqual(prev: RailFolderProps, next: RailFolderProps) {
- if (
- prev.folderId !== next.folderId ||
- prev.name !== next.name ||
- prev.open !== next.open ||
- prev.active !== next.active ||
- prev.unread !== next.unread ||
- prev.dragging !== next.dragging ||
- prev.preview !== next.preview ||
- !!prev.onUngroup !== !!next.onUngroup ||
- !!prev.registerItem !== !!next.registerItem ||
- prev.dragDescriptionId !== next.dragDescriptionId ||
- prev.folderServers.length !== next.folderServers.length
- ) return false
+ if (prev.folderId !== next.folderId || prev.name !== next.name || prev.open !== next.open || prev.active !== next.active || prev.unread !== next.unread || prev.dragging !== next.dragging || prev.dnd !== next.dnd || prev.dragDescriptionId !== next.dragDescriptionId || prev.folderServers.length !== next.folderServers.length) return false
return prev.folderServers.every((server, index) => {
const other = next.folderServers[index]
- return !!other &&
- server.id === other.id &&
- server.name === other.name &&
- server.initial === other.initial &&
- server.icon === other.icon
+ return !!other && server.id === other.id && server.initial === other.initial && server.name === other.name && server.icon === other.icon
})
}
-
export const RailFolder = memo(RailFolderImpl, railFolderPropsEqual)
diff --git a/src/web/src/components/community/shell/rail-indicator.test.ts b/src/web/src/components/community/shell/rail-indicator.test.ts
index bdae99206..fb1d99bf6 100644
--- a/src/web/src/components/community/shell/rail-indicator.test.ts
+++ b/src/web/src/components/community/shell/rail-indicator.test.ts
@@ -35,6 +35,14 @@ describe("RailIndicator", () => {
expect(markup({ testId: "indicator-id" })).toContain('data-testid="indicator-id"')
})
+ it("retracts a hidden source or expanded-folder bar despite active, unread, hover and focus", () => {
+ const html = markup({ active: true, unread: true, hidden: true })
+ expect(html).toContain("h-0 opacity-0")
+ expect(html).not.toContain("h-8")
+ expect(html).not.toContain("group-hover:h-5")
+ expect(html).not.toContain("group-has-[:focus-visible]:h-5")
+ })
+
it("builds the canonical server and folder indicator locators", () => {
expect(tid.serverRailIndicator("server-id")).toBe("community-server-rail-indicator-server-id")
expect(tid.serverRailFolderIndicator("folder-id")).toBe("community-server-rail-folder-indicator-folder-id")
diff --git a/src/web/src/components/community/shell/rail-indicator.tsx b/src/web/src/components/community/shell/rail-indicator.tsx
index bd4e6ea12..1433fb771 100644
--- a/src/web/src/components/community/shell/rail-indicator.tsx
+++ b/src/web/src/components/community/shell/rail-indicator.tsx
@@ -4,10 +4,12 @@ export function RailIndicator({
active,
unread,
testId,
+ hidden,
}: {
active?: boolean
unread?: boolean
testId?: string
+ hidden?: boolean
}) {
const presentation = selectUnreadPresentation({
accountUnread: unread === true,
@@ -19,7 +21,7 @@ export function RailIndicator({
data-testid={testId}
className={[
"absolute left-0 top-1/2 w-1 -translate-y-1/2 rounded-r-full bg-foreground transition-all duration-150",
- presentation.active
+ hidden ? "h-0 opacity-0" : presentation.active
? "h-8"
: `${presentation.showDot ? "h-2.5" : "h-0"} group-hover:h-5 group-has-[:focus-visible]:h-5`,
].join(" ")}
diff --git a/src/web/src/components/community/shell/rail-server-icon.tsx b/src/web/src/components/community/shell/rail-server-icon.tsx
new file mode 100644
index 000000000..a02324412
--- /dev/null
+++ b/src/web/src/components/community/shell/rail-server-icon.tsx
@@ -0,0 +1,17 @@
+import { OfficialServerBadge } from "../official-server-badge"
+import { ServerIcon } from "@/components/community/server-icon"
+import type { Server } from "@/lib/community/models/navigation"
+
+export function RailServerIcon({ server, active }: { server: Server; active?: boolean }) {
+ return <>
+ <ServerIcon data-rail-drag-preview id={server.id} name={server.name} initial={server.initial} icon={server.icon} size={40}
+ className={[
+ "pointer-events-none relative grid size-10 place-items-center overflow-hidden font-brand text-xl font-bold transition-all duration-150",
+ active ? "cursor-default rounded-xl" : "cursor-pointer rounded-[18px] group-hover/server:rounded-xl",
+ server.icon
+ ? active ? "bg-primary text-primary-foreground" : "bg-card group-hover/server:bg-primary group-hover/server:text-primary-foreground"
+ : "text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)] group-hover/server:brightness-110",
+ ].join(" ")} />
+ <OfficialServerBadge official={server.official} className="absolute -left-1 -top-1 z-2" />
+ </>
+}
diff --git a/src/web/src/components/community/shell/server-rail-brand.test.ts b/src/web/src/components/community/shell/server-rail-brand.test.ts
index 0994bb924..c3901d2c1 100644
--- a/src/web/src/components/community/shell/server-rail-brand.test.ts
+++ b/src/web/src/components/community/shell/server-rail-brand.test.ts
@@ -22,14 +22,14 @@ describe("ServerRail Home brand mark", () => {
const source = readFileSync(new URL("./server-rail.tsx", import.meta.url), "utf8")
const scrollViewport =
- 'className="min-h-0 w-full shrink overflow-y-auto overflow-x-clip py-2 thin-scrollbar scrollbar-none"'
+ 'className="min-h-0 w-full shrink overflow-y-auto overflow-x-clip pt-2 pb-1 thin-scrollbar scrollbar-none"'
const addRegion =
- 'className="flex w-full shrink-0 justify-center pb-[calc(var(--community-rail-bottom-inset)+var(--app-safe-area-bottom))] sm:pb-(--community-rail-bottom-inset)"'
+ 'className="flex w-full shrink-0 justify-center pt-2 pb-[calc(var(--community-rail-bottom-inset)+var(--app-safe-area-bottom)+0.5rem)] sm:pb-[calc(var(--community-rail-bottom-inset)+0.5rem)]"'
expect(source).toContain("data-testid={tid.serverRailScroll}")
expect(source).toContain(scrollViewport)
expect(source).toContain(addRegion)
- expect(source).toContain('"--community-rail-bottom-inset": `${bottomInset ?? 8}px`')
+ expect(source).toContain('"--community-rail-bottom-inset": `${bottomInset ?? 0}px`')
expect(source.indexOf(scrollViewport)).toBeLessThan(source.indexOf(addRegion))
expect(scrollViewport).toContain("shrink")
expect(scrollViewport).not.toContain("flex-1")
diff --git a/src/web/src/components/community/shell/server-rail-drag-preview.dom.test.tsx b/src/web/src/components/community/shell/server-rail-drag-preview.dom.test.tsx
new file mode 100644
index 000000000..930fd3ded
--- /dev/null
+++ b/src/web/src/components/community/shell/server-rail-drag-preview.dom.test.tsx
@@ -0,0 +1,95 @@
+import { render } from "@/test/react-dom-harness"
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { ServerRailDragPreview } from "./server-rail-drag-preview"
+import type { RailDndController, RailReturn } from "./use-server-rail-dnd"
+import type { RailEntity } from "@/lib/community/server-rail-model"
+
+const drag = vi.hoisted(() => ({ entity: null as RailEntity | null, offset: null as { x: number; y: number } | null, returning: null as RailReturn | null }))
+vi.mock("./use-server-rail-dnd", () => ({ useServerRailDrag: () => drag }))
+
+const props = {
+ dnd: {} as RailDndController,
+ servers: new Map([["a", { id: "a", name: "Alpha", initial: "A", active: false, unread: true, mentions: 2 }]]),
+ folderNames: new Map([["f", "Team"]]),
+ state: { serverIds: ["a"], folderIds: ["f"], folders: { f: ["a"] }, expanded: [] },
+ activeServerId: "a",
+}
+
+describe("server rail moving preview", () => {
+ const nativeAnimate = Object.getOwnPropertyDescriptor(Element.prototype, "animate")
+ afterEach(() => {
+ drag.returning = null
+ if (nativeAnimate) Object.defineProperty(Element.prototype, "animate", nativeAnimate)
+ else Reflect.deleteProperty(Element.prototype, "animate")
+ })
+ it("returns to the current source center with no stationary delay and removes the animation on cleanup", () => {
+ vi.spyOn(window, "matchMedia").mockReturnValue({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() } as unknown as MediaQueryList)
+ const source = document.createElement("div")
+ document.body.appendChild(source)
+ source.getBoundingClientRect = () => ({ left: 8, top: 72, width: 40, height: 40 }) as DOMRect
+ const animation = { onfinish: null as (() => void) | null, cancel: vi.fn() }
+ const animate = vi.fn(() => animation), completeReturn = vi.fn()
+ Object.defineProperty(Element.prototype, "animate", { configurable: true, value: animate })
+ drag.entity = { kind: "server", id: "a" }; drag.offset = { x: 300, y: 200 }
+ drag.returning = { entity: drag.entity, offset: drag.offset, element: source }
+ const result = render(<ServerRailDragPreview {...props} dnd={{ completeReturn } as unknown as RailDndController} />)
+ expect(document.querySelector('[data-rail-preview-phase="returning"]')).not.toBeNull()
+ expect(animate).toHaveBeenCalledExactlyOnceWith([
+ { transform: "translate(300px, 200px)" }, { transform: "translate(6px, 70px)" },
+ ], { duration: 150, easing: "cubic-bezier(0.2, 0.8, 0.2, 1)", fill: "forwards" })
+ animation.onfinish?.()
+ expect(completeReturn).toHaveBeenCalledExactlyOnceWith(drag.returning)
+ result.unmount()
+ expect(animation.cancel).toHaveBeenCalledTimes(1)
+ expect(animation.onfinish).toBeNull()
+ source.remove()
+ })
+ it.each(["reduced", "removed"])("restores immediately when the source is %s", (reason) => {
+ const source = document.createElement("div")
+ if (reason !== "removed") document.body.appendChild(source)
+ source.getBoundingClientRect = () => ({ left: 8, top: 72, width: 40, height: 40 }) as DOMRect
+ const media = vi.spyOn(window, "matchMedia").mockReturnValue({ matches: reason === "reduced" } as MediaQueryList)
+ const animate = vi.fn(), completeReturn = vi.fn()
+ Object.defineProperty(Element.prototype, "animate", { configurable: true, value: animate })
+ try {
+ drag.entity = { kind: "server", id: "a" }; drag.offset = { x: 300, y: 200 }
+ drag.returning = { entity: drag.entity, offset: drag.offset, element: source }
+ render(<ServerRailDragPreview {...props} dnd={{ completeReturn } as unknown as RailDndController} />)
+ expect(completeReturn).toHaveBeenCalledExactlyOnceWith(drag.returning)
+ expect(animate).not.toHaveBeenCalled()
+ } finally { source.remove(); media.mockRestore() }
+ })
+ it("moves the same icon and name bubble together, without an indicator, and removes both on release", () => {
+ drag.entity = { kind: "server", id: "a" }; drag.offset = { x: 100, y: 200 }
+ const result = render(<ServerRailDragPreview {...props} />)
+ const preview = document.querySelector('[data-rail-floating-preview="server"]')!
+ expect(preview).toHaveAttribute("aria-hidden", "true")
+ expect(preview.firstElementChild).toHaveStyle({ transform: "translate(100px, 200px)" })
+ expect(preview.querySelector('[data-slot="community-server-rail-drag-name"]')).toHaveTextContent("Alpha")
+ expect(preview.querySelector('[data-slot="community-server-rail-drag-glyph"]')).toHaveClass("opacity-50")
+ expect(preview.querySelector('[data-slot="community-server-rail-drag-name"]')?.parentElement).toBe(preview.firstElementChild)
+ expect(preview.querySelector('[data-rail-drag-preview]')).toHaveClass("size-10")
+ expect(preview.querySelector('[data-slot="community-server-rail-drag-mentions"]')).toHaveTextContent("2")
+ expect(preview.querySelector('[data-slot="community-server-rail-indicator"]')).toBeNull()
+ drag.offset = { x: 160, y: 320 }
+ result.rerender(<ServerRailDragPreview {...props} />)
+ expect(document.querySelector('[data-rail-floating-preview="server"]')).toBe(preview)
+ expect(preview.firstElementChild).toHaveStyle({ transform: "translate(160px, 320px)" })
+ drag.entity = null; drag.offset = null
+ result.rerender(<ServerRailDragPreview {...props} />)
+ expect(document.querySelector('[data-rail-floating-preview]')).toBeNull()
+ })
+
+ it("reuses folder collection thumbnails and its name without a base indicator", () => {
+ drag.entity = { kind: "folder", id: "f" }; drag.offset = { x: 20, y: 80 }
+ const view = render(<ServerRailDragPreview {...props} />)
+ const preview = document.querySelector('[data-rail-floating-preview="folder"]')!
+ expect(preview.querySelector('[data-slot="community-server-rail-drag-name"]')).toHaveTextContent("Team")
+ expect(preview.querySelector('[role="img"]')).toHaveAttribute("aria-label", "Alpha")
+ expect(preview.querySelector('[data-slot="community-server-rail-indicator"]')).toBeNull()
+ expect(preview.querySelector('[data-slot="community-server-rail-drag-folder"]')).toHaveClass("size-10", "rounded-xl")
+ expect(preview.firstElementChild).toHaveClass("size-11")
+ view.rerender(<ServerRailDragPreview {...props} activeServerId="other" />)
+ expect(preview.querySelector('[data-slot="community-server-rail-drag-folder"]')).toHaveClass("size-10", "rounded-[18px]")
+ })
+})
diff --git a/src/web/src/components/community/shell/server-rail-drag-preview.tsx b/src/web/src/components/community/shell/server-rail-drag-preview.tsx
new file mode 100644
index 000000000..fcccbf656
--- /dev/null
+++ b/src/web/src/components/community/shell/server-rail-drag-preview.tsx
@@ -0,0 +1,69 @@
+"use client"
+
+import { createPortal } from "react-dom"
+import { useLayoutEffect, useRef } from "react"
+import type { Server } from "@/lib/community/models/navigation"
+import { RailServerIcon } from "./rail-server-icon"
+import { RailFolderIcon } from "./rail-folder"
+import { useServerRailDrag, type RailDndController } from "./use-server-rail-dnd"
+import type { RailState } from "@/lib/community/server-rail-model"
+import { tid } from "@/lib/community/testids"
+
+export function ServerRailDragPreview({ dnd, servers, folderNames, state, activeServerId }: {
+ dnd: RailDndController
+ servers: ReadonlyMap<string, Server>
+ folderNames: ReadonlyMap<string, string>
+ state: RailState
+ activeServerId: string
+}) {
+ const { entity, offset, returning } = useServerRailDrag(dnd)
+ const anchor = useRef<HTMLDivElement>(null)
+ useLayoutEffect(() => {
+ if (!returning || !anchor.current) return
+ const media = window.matchMedia("(prefers-reduced-motion: reduce)")
+ const element = returning.element
+ const rect = element.getBoundingClientRect()
+ if (!element.isConnected || rect.width === 0 || rect.height === 0 || media.matches) {
+ dnd.completeReturn(returning)
+ return
+ }
+ const animation = anchor.current.animate([
+ { transform: `translate(${returning.offset.x}px, ${returning.offset.y}px)` },
+ { transform: `translate(${rect.left + (rect.width - 44) / 2}px, ${rect.top + (rect.height - 44) / 2}px)` },
+ ], { duration: 150, easing: "cubic-bezier(0.2, 0.8, 0.2, 1)", fill: "forwards" })
+ const complete = () => dnd.completeReturn(returning)
+ animation.onfinish = complete
+ const reduce = () => { if (media.matches) complete() }
+ media.addEventListener("change", reduce)
+ return () => {
+ animation.onfinish = null
+ animation.cancel()
+ media.removeEventListener("change", reduce)
+ }
+ }, [dnd, returning])
+ if (!entity || !offset) return null
+ const server = entity.kind === "server" ? servers.get(entity.id) : undefined
+ const name = server?.name ?? folderNames.get(entity.id) ?? "Group"
+ const children = (state.folders[entity.id] ?? []).flatMap((id) => {
+ const child = servers.get(id)
+ return child ? [child] : []
+ })
+ return createPortal(
+ <div aria-hidden="true" data-testid={tid.serverRailDragPreview} data-rail-floating-preview={entity.kind} data-rail-preview-phase={returning ? "returning" : "dragging"} className="pointer-events-none fixed inset-0 z-50">
+ <div ref={anchor} className="absolute left-0 top-0 grid size-11 place-items-center" style={{ transform: `translate(${offset.x}px, ${offset.y}px)` }}>
+ <span data-slot="community-server-rail-drag-glyph" className="relative grid size-11 place-items-center opacity-50">
+ {server ? <RailServerIcon server={server} active={activeServerId === server.id} /> : (
+ <span data-slot="community-server-rail-drag-folder" className={`grid size-10 shrink-0 place-items-center bg-accent/50 text-muted-foreground dark:bg-accent ${children.some((child) => child.id === activeServerId) ? "rounded-xl" : "rounded-[18px]"}`}>
+ <RailFolderIcon open={false} folderServers={children} />
+ </span>
+ )}
+ {server && server.mentions > 0 && <span data-slot="community-server-rail-drag-mentions" className="absolute -bottom-0.5 -right-0.5 z-2 grid h-5 min-w-5 place-items-center rounded-full bg-primary px-1 text-[11px] font-bold text-primary-foreground ring-2 ring-(--d-rail)">{server.mentions}</span>}
+ </span>
+ <span data-slot="community-server-rail-drag-name" data-testid={tid.serverRailDragName} className="absolute left-[calc(100%+8px)] top-1/2 inline-flex w-max max-w-xs -translate-y-1/2 items-center rounded-md bg-foreground px-3 py-2 text-xs text-background">
+ <span className="absolute -left-1 top-1/2 size-2 -translate-y-1/2 rotate-45 rounded-xs bg-foreground" />
+ <span className="truncate">{name}</span>
+ </span>
+ </div>
+ </div>, document.body,
+ )
+}
diff --git a/src/web/src/components/community/shell/server-rail-model.test.ts b/src/web/src/components/community/shell/server-rail-model.test.ts
index d81045e62..edb622959 100644
--- a/src/web/src/components/community/shell/server-rail-model.test.ts
+++ b/src/web/src/components/community/shell/server-rail-model.test.ts
@@ -4,6 +4,7 @@ import {
planRailPersistence,
railInstructionIsAvailable,
railOperationAvailability,
+ railTopLevel,
railStateFromData,
railStateErrors,
visibleTopLevelServers,
@@ -12,14 +13,45 @@ import {
function fixture(): RailState {
return {
- serverOrder: ["a", "b", "c", "d", "e", "f"],
- folderOrder: ["one", "two"],
+ serverIds: ["a", "b", "c", "d", "e", "f"],
+ folderIds: ["one", "two"],
folders: { one: ["c", "d"], two: ["e"] },
expanded: ["one"],
}
}
describe("server rail normalized reducer", () => {
+ it.each(["combine", "append", "reorder-after"] as const)("preserves an existing destination's disclosure after %s", (operation) => {
+ for (const open of [false, true]) {
+ const before = fixture()
+ if (open) before.expanded.push("two")
+ const source = { kind: "server", id: "a" } as const
+ const result = commitRailInstruction(before, operation === "append"
+ ? { operation, source, target: { kind: "folder-content", id: "two" } }
+ : { operation, source, target: operation === "combine" ? { kind: "folder", id: "two" } : { kind: "server", id: "e" } })
+ expect(result.applied).toBe(true)
+ if (result.applied) {
+ expect(result.state.expanded).toEqual(before.expanded)
+ expect(result.state.folders.two).toEqual(["e", "a"])
+ }
+ }
+ })
+ it("moves a folder's last member into its own root gap at the former folder position", () => {
+ const result = commitRailInstruction(fixture(), { operation: "reorder-before", source: { kind: "server", id: "e" }, target: { kind: "folder", id: "two" } })
+ expect(result.applied).toBe(true)
+ if (!result.applied) return
+ expect(result.state.folders.two).toBeUndefined()
+ expect(railTopLevel(result.state).map((entry) => entry.id)).toEqual(["a", "b", "f", "one", "e"])
+ expect(result.commands.map((command) => command.kind)).toEqual(["delete-folder", "reorder-top-level"])
+ })
+ it("appends an existing member on its own folder header and ignores an already-last member", () => {
+ const result = commitRailInstruction(fixture(), { operation: "combine", source: { kind: "server", id: "c" }, target: { kind: "folder", id: "one" } })
+ expect(result.applied).toBe(true)
+ if (!result.applied) return
+ expect(result.state.folders.one).toEqual(["d", "c"])
+ expect(result.commands).toEqual([{ kind: "replace-folder-items", folderId: "one", serverIds: ["d", "c"] }])
+ expect(commitRailInstruction(result.state, { operation: "combine", source: { kind: "server", id: "c" }, target: { kind: "folder", id: "one" } })).toMatchObject({ applied: false, reason: "instruction is a no-op" })
+ })
it("projects legacy dangling, empty, and duplicate folders with the server snapshot ordering", () => {
const folder = (id: string, position: number, serverIds: string[]) => ({
id,
@@ -34,8 +66,8 @@ describe("server rail normalized reducer", () => {
folder("dangling", 2, ["foreign"]),
folder("valid", 3, ["b"]),
], ["empty", "a-locale-first", "Z-binary-first", "valid"])).toEqual({
- serverOrder: ["a", "b"],
- folderOrder: ["Z-binary-first", "valid"],
+ serverIds: ["a", "b"],
+ folderIds: ["Z-binary-first", "valid"],
folders: { "Z-binary-first": ["a"], valid: ["b"] },
expanded: ["Z-binary-first", "valid"],
})
@@ -54,9 +86,10 @@ describe("server rail normalized reducer", () => {
})
expect(result).toMatchObject({ applied: true })
if (!result.applied) return
- expect(result.state.serverOrder).toEqual(["b", "a", "c", "d", "e", "f"])
+ expect(result.state.serverIds).toEqual(fixture().serverIds)
+ expect(railTopLevel(result.state).map((entry) => entry.id)).toEqual(["b", "a", "f", "one", "two"])
expect(result.commands).toEqual([
- { kind: "reorder-servers", serverIds: ["b", "a", "c", "d", "e", "f"] },
+ { kind: "reorder-top-level", entries: railTopLevel(result.state) },
])
})
@@ -83,8 +116,8 @@ describe("server rail normalized reducer", () => {
})
expect(result).toMatchObject({ applied: true })
if (!result.applied) return
- expect(result.state.folderOrder).toEqual(["one"])
- expect(result.commands).toEqual([{ kind: "delete-folder", folderId: "two" }])
+ expect(result.state.folderIds).toEqual(["one"])
+ expect(result.commands).toEqual([{ kind: "delete-folder", folderId: "two" }, { kind: "reorder-top-level", entries: railTopLevel(result.state) }])
})
it("creates one temporary folder command from two top-level servers", () => {
@@ -100,15 +133,15 @@ describe("server rail normalized reducer", () => {
kind: "create-folder",
clientId: "temp_one",
name: "Group",
- serverIds: ["a", "b"],
- }])
+ serverIds: ["b", "a"],
+ }, { kind: "reorder-top-level", entries: railTopLevel(result.state) }])
})
it("plans folder reorder separately and treats no-op as zero-write", () => {
const before = fixture()
- const after = { ...fixture(), folderOrder: ["two", "one"] }
+ const after = { ...fixture(), folderIds: ["two", "one"] }
expect(planRailPersistence(before, after)).toEqual([
- { kind: "reorder-folders", folderIds: ["two", "one"] },
+ { kind: "reorder-top-level", entries: railTopLevel(after) },
])
expect(commitRailInstruction(before, {
operation: "reorder-before",
@@ -117,12 +150,12 @@ describe("server rail normalized reducer", () => {
})).toMatchObject({ applied: false })
})
- it("rejects cross-kind reorder and duplicate-folder membership", () => {
+ it("allows mixed reorder and rejects duplicate-folder membership", () => {
expect(commitRailInstruction(fixture(), {
operation: "reorder-before",
source: { kind: "server", id: "a" },
target: { kind: "folder", id: "one" },
- })).toMatchObject({ applied: false, reason: "server and folder orders cannot interleave" })
+ })).toMatchObject({ applied: true })
const invalid = fixture()
invalid.folders.two.push("c")
expect(railStateErrors(invalid)).toContain("server c belongs to multiple folders")
@@ -138,12 +171,12 @@ describe("server rail normalized reducer", () => {
fixture(),
{ kind: "server", id: "c" },
{ kind: "folder", id: "one" },
- )).toEqual({ "reorder-before": false, "reorder-after": false, combine: false })
+ )).toEqual({ "reorder-before": true, "reorder-after": true, combine: true })
expect(railOperationAvailability(
fixture(),
{ kind: "server", id: "a" },
{ kind: "folder", id: "one" },
- )).toEqual({ "reorder-before": false, "reorder-after": false, combine: true })
+ )).toEqual({ "reorder-before": true, "reorder-after": true, combine: true })
expect(railInstructionIsAvailable(fixture(), {
operation: "combine",
source: { kind: "server", id: "a" },
@@ -158,7 +191,7 @@ describe("server rail normalized reducer", () => {
it("allocates a collision-free temporary id for server-combine previews", () => {
const state = fixture()
- state.folderOrder.push("__rail_preview_folder__")
+ state.folderIds.push("__rail_preview_folder__")
state.folders.__rail_preview_folder__ = ["f"]
expect(railInstructionIsAvailable(state, {
@@ -168,3 +201,39 @@ describe("server rail normalized reducer", () => {
})).toBe(true)
})
})
+
+it("creates directly from a nested server within the bounded command batch", () => {
+ const result = commitRailInstruction(fixture(), { operation: "combine", source: { kind: "server", id: "c" }, target: { kind: "server", id: "a" }, newFolderId: "new" })
+ expect(result.applied).toBe(true)
+ if (!result.applied) return
+ expect(result.state.folders.one).toEqual(["d"])
+ expect(result.state.folders.new).toEqual(["a", "c"])
+ expect(result.commands.map((command) => command.kind)).toEqual(["replace-folder-items", "create-folder", "reorder-top-level"])
+ expect(railTopLevel(result.state)[0]).toEqual({ kind: "folder", id: "new" })
+})
+it("appends a nested server to root and deletes only the emptied folder", () => {
+ const result = commitRailInstruction(fixture(), { operation: "append", source: { kind: "server", id: "e" }, target: { kind: "root", id: "root" } })
+ expect(result.applied).toBe(true)
+ if (!result.applied) return
+ expect(result.state.folders.two).toBeUndefined()
+ expect(result.state.folders.one).toEqual(["c", "d"])
+ expect(railTopLevel(result.state).at(-1)).toEqual({ kind: "server", id: "e" })
+ expect(result.commands).toHaveLength(2)
+})
+it("keeps ten folders usable and refuses only a net eleventh folder", () => {
+ const state: RailState = { serverIds: ["a", "b", ...Array.from({ length: 11 }, (_, i) => `s${i}`)], folderIds: Array.from({ length: 10 }, (_, i) => `f${i}`), folders: Object.fromEntries(Array.from({ length: 10 }, (_, i) => [`f${i}`, i === 0 ? ["s0", "s10"] : [`s${i}`]])), expanded: [] }
+ expect(commitRailInstruction(state, { operation: "combine", source: { kind: "server", id: "a" }, target: { kind: "server", id: "b" }, newFolderId: "extra" })).toMatchObject({ applied: false, reason: "folder limit reached" })
+ const join = commitRailInstruction(state, { operation: "append", source: { kind: "server", id: "a" }, target: { kind: "folder-content", id: "f0" } })
+ expect(join.applied).toBe(true)
+ const replace = commitRailInstruction(state, { operation: "combine", source: { kind: "server", id: "s1" }, target: { kind: "server", id: "a" }, newFolderId: "replacement" })
+ expect(replace.applied).toBe(true)
+ if (replace.applied) expect(replace.state.folderIds).toHaveLength(10)
+})
+it("reorders folders between servers while preserving their contents", () => {
+ const result = commitRailInstruction(fixture(), { operation: "reorder-after", source: { kind: "folder", id: "one" }, target: { kind: "server", id: "a" } })
+ expect(result.applied).toBe(true)
+ if (!result.applied) return
+ expect(railTopLevel(result.state).map((entry) => entry.id)).toEqual(["a", "one", "b", "f", "two"])
+ expect(result.state.folders).toEqual(fixture().folders)
+ expect(result.commands.map((command) => command.kind)).toEqual(["reorder-top-level"])
+})
diff --git a/src/web/src/components/community/shell/server-rail-pdd-contract.test.ts b/src/web/src/components/community/shell/server-rail-pdd-contract.test.ts
deleted file mode 100644
index 3627f1bec..000000000
--- a/src/web/src/components/community/shell/server-rail-pdd-contract.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { readFileSync } from "node:fs"
-import { describe, expect, it } from "vitest"
-
-const read = (name: string) => readFileSync(new URL(name, import.meta.url), "utf8")
-
-describe("server rail PDD component contract", () => {
- it("uses Pragmatic Drag and Drop only in the server rail", () => {
- const rail = read("./server-rail.tsx")
- const adapter = read("./use-server-rail-pdd.ts")
- const channelTree = read("../channels/use-channel-tree.ts")
- expect(rail).toContain('from "./use-server-rail-pdd"')
- expect(adapter).toContain("@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter")
- expect(adapter).toContain("getIsSticky: () => false")
- expect(rail).not.toContain("@dnd-kit")
- expect(channelTree).toContain("@dnd-kit")
- })
-
- it("pins one inset indicator, one combine outline, and the 500ms expansion", () => {
- const server = read("./sortable-server.tsx")
- const folder = read("./rail-folder.tsx")
- const adapter = read("./use-server-rail-pdd.ts")
- for (const source of [server, folder]) {
- expect(source).toContain("h-0.5 w-9")
- expect(source).toContain("bg-primary/10 outline outline-2! outline-primary")
- expect(source).not.toContain("ring-2 ring-primary")
- }
- expect(folder).toContain("transition-[border-radius,background-color]")
- expect(server).toContain("transition-[border-radius,background-color,border-color,opacity,transform]")
- expect(adapter).toContain("}, 500)")
- })
-
- it("uses drag as the only spatial model and retains only Ungroup", () => {
- const server = read("./sortable-server.tsx")
- const folder = read("./rail-folder.tsx")
- const rail = read("./server-rail.tsx")
- expect(server).not.toContain("Move…")
- expect(server).not.toContain("Create group")
- expect(folder).not.toContain("Move…")
- expect(folder).toContain("Ungroup")
- expect(rail).not.toContain("ServerRailMoveMenu")
- })
-
- it("separates touch scroll intent and exposes keyboard drag instructions", () => {
- const adapter = read("./use-server-rail-pdd.ts")
- const rail = read("./server-rail.tsx")
- const server = read("./sortable-server.tsx")
- const folder = read("./rail-folder.tsx")
- expect(adapter).toContain("SERVER_RAIL_TOUCH_HOLD_MS = 650")
- expect(adapter).toContain("SERVER_RAIL_TOUCH_DRAG_PX = 8")
- expect(adapter).toContain("SERVER_RAIL_TOUCH_DRIFT_PX = 10")
- const touchStart = adapter.slice(
- adapter.indexOf("const onTouchStart"),
- adapter.indexOf("const onTouchMove"),
- )
- const preArmScroll = adapter.slice(
- adapter.indexOf('if (exactIntent === "scroll")'),
- adapter.indexOf('if (exactIntent === "wait")'),
- )
- expect(touchStart).not.toContain("preventDefault")
- expect(preArmScroll).toContain("clearTouch()")
- expect(preArmScroll).not.toContain("preventDefault")
- expect(adapter).toContain('addEventListener("touchstart", onTouchStart, { passive: true })')
- expect(adapter).toContain('element.addEventListener("touchstart", suppressTouchMenu, { passive: true })')
- expect(adapter).toContain('dragHandle.addEventListener("touchstart", suppressTouchMenu, { passive: true })')
- expect(adapter).toContain("event.stopPropagation()")
- expect(adapter).toContain("event.preventDefault()")
- expect(adapter).toContain('addEventListener("touchmove", onTouchMove, { passive: false })')
- expect(adapter).toContain('addEventListener("touchend", onTouchEnd, { passive: false })')
- expect(adapter).not.toContain("scroll.scrollTop -=")
- expect(adapter).not.toContain("pending.scrolling")
- expect(adapter).toContain('addEventListener("scroll", cancelPendingTouchForNativeScroll')
- expect(server).not.toContain("touch-none")
- expect(folder).not.toContain("touch-none")
- expect(server).toContain("[-webkit-touch-callout:none]")
- expect(folder).toContain("[-webkit-touch-callout:none]")
- expect(server).toContain("data-rail-drag-preview")
- expect(folder).toContain("data-rail-drag-preview")
- expect(adapter).toContain("data-rail-floating-preview")
- expect(adapter).toContain("positionTouchDragPreview")
- expect(adapter).toContain("document.body.appendChild(element)")
- expect(adapter).toContain("requestAnimationFrame(runTouchFrame)")
- expect(adapter).toContain('!begin(entity, "touch")')
- expect(adapter).not.toContain('new MouseEvent("contextmenu"')
- expect(adapter).not.toContain("matchMedia")
- expect(rail).toContain("Press Space to pick up a server or group")
- expect(rail).toContain("onAnnounce: announce")
- })
-})
diff --git a/src/web/src/components/community/shell/server-rail.pending.dom.test.ts b/src/web/src/components/community/shell/server-rail.pending.dom.test.ts
index 163e24c67..03e073325 100644
--- a/src/web/src/components/community/shell/server-rail.pending.dom.test.ts
+++ b/src/web/src/components/community/shell/server-rail.pending.dom.test.ts
@@ -11,23 +11,22 @@ const mocks = vi.hoisted(() => ({
mutate: vi.fn(),
pending: false,
announce: vi.fn(),
- capturePddOptions: vi.fn(),
+ captureDndOptions: vi.fn(),
querySelector: vi.fn(),
sortableProps: vi.fn(),
railFolderProps: vi.fn(),
}))
-vi.mock("@atlaskit/pragmatic-drag-and-drop-live-region", () => ({
- announce: mocks.announce,
- cleanup: vi.fn(),
-}))
vi.mock("@/hooks/community/mutations", () => ({
useServerRailCommit: () => ({ mutate: mocks.mutate, isPending: mocks.pending, isCommandPending: () => mocks.pending }),
}))
-vi.mock("./use-server-rail-pdd", () => ({
- useServerRailPdd: (options: unknown) => {
- mocks.capturePddOptions(options)
- return { registerItem: vi.fn() }
+vi.mock("./use-server-rail-dnd", () => ({
+ RailEndDropTarget: () => null,
+ RailFolderGapDropTarget: () => null,
+ useServerRailDrag: () => ({ entity: null, offset: null }),
+ useServerRailDnd: (options: unknown) => {
+ mocks.captureDndOptions(options)
+ return { cancel: () => {} }
},
}))
vi.mock("./sortable-server", () => ({
@@ -127,7 +126,7 @@ function latestMutation() {
}
function drop(instruction: RailInstruction) {
- const options = mocks.capturePddOptions.mock.calls.at(-1)![0] as {
+ const options = mocks.captureDndOptions.mock.calls.at(-1)![0] as {
onDrop: (instruction: RailInstruction) => void
}
options.onDrop(instruction)
@@ -413,39 +412,17 @@ describe("ServerRail one-in-flight structural guard", () => {
expect((latestSortableProps("b").server as { unread: boolean }).unread).toBe(true)
})
- it.each(["drop-first", "ungroup-first"] as const)(
- "allows one PATCH when drag-drop and ungroup callbacks race: %s",
- async (order) => {
- renderRail()
- const ungroup = latestFolderProps().onUngroup as () => void
- const instruction = {
- operation: "reorder-after",
- source: { kind: "server", id: "a" },
- target: { kind: "server", id: "c" },
- } satisfies RailInstruction
-
- await act(async () => {
- if (order === "drop-first") {
- drop(instruction)
- ungroup()
- } else {
- ungroup()
- drop(instruction)
- }
- })
-
- expect(mocks.mutate).toHaveBeenCalledTimes(1)
- expect(mocks.announce).toHaveBeenCalledWith("A server rail move is already being saved")
-
- const options = mocks.mutate.mock.calls[0]![1]
- await act(async () => { options.onSettled() })
- await act(async () => {
- if (order === "drop-first") ungroup()
- else drop(instruction)
- })
- expect(mocks.mutate).toHaveBeenCalledTimes(2)
- },
- )
+ it.each([false, true])("allows one PATCH when two drop callbacks race, reverse=%s", async (reverse) => {
+ const view = renderRail()
+ const first: RailInstruction = { operation: "reorder-after", source: { kind: "server", id: "a" }, target: { kind: "server", id: "c" } }
+ const second: RailInstruction = { operation: "reorder-before", source: { kind: "server", id: "c" }, target: { kind: "server", id: "a" } }
+ await act(async () => { drop(reverse ? second : first); drop(reverse ? first : second) })
+ expect(mocks.mutate).toHaveBeenCalledTimes(1)
+ expect(view.container.querySelector('[role="status"]')?.textContent).toBe("A server rail move is already being saved")
+ await act(async () => { mocks.mutate.mock.calls[0]![1].onSettled() })
+ await act(async () => drop(reverse ? first : second))
+ expect(mocks.mutate).toHaveBeenCalledTimes(2)
+ })
it("keeps immediate rejected-operation focus on one animation frame", async () => {
const focus = vi.fn()
@@ -592,32 +569,34 @@ describe("ServerRail one-in-flight structural guard", () => {
expect(latestFolderProps("created").open).toBe(true)
})
- it.each(["success", "error"] as const)(
- "returns Ungroup focus after settle to a surviving entity: %s",
- async (outcome) => {
- const focus = vi.fn()
- mocks.querySelector.mockReturnValue({ focus })
- renderRail()
- const ungroup = latestFolderProps().onUngroup as () => void
- await act(async () => ungroup())
- const { callbacks } = latestMutation()
+ it("has no Ungroup callback and keeps the same folder backdrop across toggle", async () => {
+ const view = renderRail()
+ expect(latestFolderProps().onUngroup).toBeUndefined()
+ const background = view.container.querySelector('[data-slot="community-rail-folder-backdrop"]')
+ expect(background).toHaveClass("size-10", "rounded-[18px]", "group-hover/folder:rounded-xl")
+ await act(async () => (latestFolderProps().onToggle as () => void)())
+ expect(view.container.querySelector('[data-slot="community-rail-folder-backdrop"]')).toBe(background)
+ expect(background).toHaveClass("inset-x-1", "inset-y-0", "rounded-[12px]")
+ expect(background).not.toHaveClass("size-10")
+ await act(async () => (latestFolderProps().onToggle as () => void)())
+ view.rerender(railElement([{ ...folders[0]!, servers: [{ id: "a", name: "A", initial: "A" }] }]))
+ expect(latestFolderProps().active).toBe(true)
+ expect(background).toHaveClass("size-10", "rounded-xl")
+ expect(background).not.toHaveClass("rounded-[18px]")
+ expect(mocks.mutate).not.toHaveBeenCalled()
+ })
- await act(async () => {
- if (outcome === "success") callbacks.onSuccess({ createdFolderIds: {} })
- else callbacks.onError()
- })
- expect(focus).not.toHaveBeenCalled()
+ it("keeps folder expansion unchanged while hovering and cancelling without a mutation", async () => {
+ renderRail()
+ const options = mocks.captureDndOptions.mock.calls.at(-1)![0] as { onDragStart: (source: { kind: "server"; id: string }) => void; onPreview: (instruction: RailInstruction) => void; onCancel: () => void }
+ await act(async () => options.onDragStart({ kind: "server", id: "a" }))
+ await act(async () => options.onPreview({ source: { kind: "server", id: "a" }, target: { kind: "folder", id: "one" }, operation: "combine" }))
+ expect(latestFolderProps().open).toBe(false)
+ await act(async () => options.onCancel())
+ expect(latestFolderProps().open).toBe(false)
+ expect(mocks.mutate).not.toHaveBeenCalled()
+ })
- await act(async () => callbacks.onSettled(
- undefined,
- outcome === "error" ? new Error("failed") : null,
- ))
- await expectReconciledFocus(
- outcome === "success" ? tid.serverIcon("b") : tid.serverRailFolder("one"),
- focus,
- )
- },
- )
})
vi.mock("next/link", async () => ({ default: (await import("@/test/community-link-mock")).CommunityLinkMock }))
diff --git a/src/web/src/components/community/shell/server-rail.tsx b/src/web/src/components/community/shell/server-rail.tsx
index ae741c048..8dd997dc8 100644
--- a/src/web/src/components/community/shell/server-rail.tsx
+++ b/src/web/src/components/community/shell/server-rail.tsx
@@ -10,12 +10,14 @@ import {
useLayoutEffect,
useMemo,
useRef,
+ type ComponentProps,
type CSSProperties,
type ReactNode,
type Ref,
} from "react"
+import type { ServerRailEntry } from "@alook/shared"
import { Plus } from "lucide-react"
-import { announce, cleanup as cleanupLiveRegion } from "@atlaskit/pragmatic-drag-and-drop-live-region"
+import { CommunityDndProvider, useCommunityDndScrolling } from "../community-dnd"
import { RailIcon } from "./rail-icon"
import { AnimatedAlookLogo } from "./animated-alook-logo"
import { tid } from "@/lib/community/testids"
@@ -25,20 +27,20 @@ import { CommunityNavigationLink } from "./community-navigation-link"
import { serverRootHref } from "@/lib/community/community-route"
import { SortableServer } from "./sortable-server"
import { RailFolder } from "./rail-folder"
+import { ServerRailDragPreview } from "./server-rail-drag-preview"
import { RailIndicator } from "./rail-indicator"
import { CreateServerDialog } from "../settings/create-server-dialog"
import {
cloneRailState,
commitRailInstruction,
- planRailPersistence,
railMoveAnnouncement,
railStateFromData,
- visibleTopLevelServers,
+ railTopLevel,
type RailEntity,
type RailInstruction,
type RailState,
} from "@/lib/community/server-rail-model"
-import { useServerRailPdd } from "./use-server-rail-pdd"
+import { RailEndDropTarget, RailFolderGapDropTarget, useServerRailDnd } from "./use-server-rail-dnd"
import { useServerRailCommit } from "@/hooks/community/mutations"
import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"
import type { Server, CommunityFolder } from "@/lib/community/models/navigation"
@@ -87,7 +89,7 @@ function ServerRailFrame({
<div
ref={scrollRef}
data-testid={tid.serverRailScroll}
- className="min-h-0 w-full shrink overflow-y-auto overflow-x-clip py-2 thin-scrollbar scrollbar-none"
+ className="min-h-0 w-full shrink overflow-y-auto overflow-x-clip pt-2 pb-1 thin-scrollbar scrollbar-none"
>
{items}
</div>
@@ -95,9 +97,9 @@ function ServerRailFrame({
{add && (
<div
data-slot="community-server-rail-add"
- className="flex w-full shrink-0 justify-center pb-[calc(var(--community-rail-bottom-inset)+var(--app-safe-area-bottom))] sm:pb-(--community-rail-bottom-inset)"
+ className="flex w-full shrink-0 justify-center pt-2 pb-[calc(var(--community-rail-bottom-inset)+var(--app-safe-area-bottom)+0.5rem)] sm:pb-[calc(var(--community-rail-bottom-inset)+0.5rem)]"
style={{
- "--community-rail-bottom-inset": `${bottomInset ?? 8}px`,
+ "--community-rail-bottom-inset": `${bottomInset ?? 0}px`,
} as CSSProperties}
>
{add}
@@ -109,11 +111,13 @@ function ServerRailFrame({
)
}
-export const ServerRail = memo(function ServerRail({
+function ServerRailContent({
servers,
homeHref = "/c/me",
serverHrefs = {},
folders,
+ topOrder,
+ navigationKey,
activeServerId: activeServerIdProp,
serversLoading,
view,
@@ -130,6 +134,8 @@ export const ServerRail = memo(function ServerRail({
homeHref?: string
serverHrefs?: Readonly<Record<string, string>>
folders: CommunityFolder[]
+ topOrder?: ServerRailEntry[]
+ navigationKey?: string
activeServerId?: string
serversLoading?: boolean
view: View
@@ -142,15 +148,17 @@ export const ServerRail = memo(function ServerRail({
onOpenSettings?: (serverId: string) => void
onOpenInvitePopover?: (serverId: string) => void
}) {
+ const [announcement, announce] = useAtom(useCreateAtom(""))
const isPreview = useCommunityPreviewNavigation()
const expandedAtom = useCreateAtom<string[]>([])
const [expanded, setExpanded] = useAtom(expandedAtom)
- const collapsedAtom = useCreateAtom(new Set<string>())
+ const expansionOverrides = useCreateAtom(new Map<string, boolean>())
const dragSnapshotAtom = useCreateAtom<RailState | null>(null)
const [preview, setPreview] = useAtom(useCreateAtom<RailInstruction | null>(null))
const [dragSource, setDragSource] = useAtom(useCreateAtom<RailEntity | null>(null))
const [createOpen, setCreateOpen] = useAtom(useCreateAtom(false))
const scrollRef = useRef<HTMLDivElement>(null)
+ useCommunityDndScrolling(scrollRef, "community/server-rail")
const serverActivationRef = useRef({ onServer, onServerNavigate, onOpenSettings, onOpenInvitePopover })
const railMutation = useServerRailCommit()
const communityRuntime = useCommunityRuntime()
@@ -169,15 +177,15 @@ export const ServerRail = memo(function ServerRail({
}
}, [registry, viewLifecycle])
const storageKey = `alook:community:${registry?.accountId ?? "anon"}:rail-open-folders`
- const renderState = useMemo(() => railStateFromData(servers.map((server) => server.id), folders, expanded), [servers, folders, expanded])
+ const renderState = useMemo(() => railStateFromData(servers.map((server) => server.id), folders, expanded, topOrder), [servers, folders, expanded, topOrder])
const claimMutation = useCallback(() => {
if (railMutation.isCommandPending()) {
announce("A server rail move is already being saved")
return false
}
return true
- }, [railMutation])
- const releaseMutation = useCallback(() => collapsedAtom.set(() => new Set()), [collapsedAtom])
+ }, [announce, railMutation])
+ const releaseMutation = useCallback(() => expansionOverrides.set(() => new Map()), [expansionOverrides])
useEffect(() => {
try {
if (isPreview) return
@@ -194,7 +202,6 @@ export const ServerRail = memo(function ServerRail({
sessionStorage.setItem(storageKey, JSON.stringify(expanded))
}, [isPreview, expanded, storageKey])
- useEffect(() => () => cleanupLiveRegion(), [])
const activeFromProps = activeServerIdProp ?? servers.find((server) => server.active)?.id ?? ""
const [localActiveId, setLocalActiveId] = useAtom(useCreateAtom(activeFromProps))
@@ -269,13 +276,13 @@ export const ServerRail = memo(function ServerRail({
const assertUI = captureUI()
setExpanded(result.state.expanded)
railMutation.mutate(
- { before, after: result.state, commands: result.commands, assertUI },
+ { commands: result.commands, assertUI },
{
onSuccess: (response) => {
try { assertUI() } catch { return }
setExpanded((current) => {
const next = new Set(current.map((id) => response.createdFolderIds[id] ?? id))
- for (const [clientId, id] of Object.entries(response.createdFolderIds)) if (!collapsedAtom.get().has(clientId) && !collapsedAtom.get().has(id)) next.add(id)
+ for (const [clientId, id] of Object.entries(response.createdFolderIds)) if (expansionOverrides.get().get(clientId) !== false && expansionOverrides.get().get(id) !== false) next.add(id)
return [...next]
})
announce(label)
@@ -283,7 +290,11 @@ export const ServerRail = memo(function ServerRail({
onError: () => {
try { assertUI() } catch { return }
const created = new Set(result.commands.flatMap((command) => command.kind === "create-folder" ? [command.clientId] : []))
- setExpanded((current) => current.filter((id) => !created.has(id)))
+ setExpanded(() => {
+ const restored = new Set(before.expanded)
+ for (const [id, open] of expansionOverrides.get()) { if (open) restored.add(id); else restored.delete(id) }
+ return [...restored].filter((id) => !created.has(id))
+ })
announce(`${label} failed and was rolled back`)
},
onSettled: () => {
@@ -293,52 +304,18 @@ export const ServerRail = memo(function ServerRail({
},
},
)
- }, [isPreview, captureUI, claimMutation, collapsedAtom, focusEntity, folderNames, railMutation, releaseMutation, serverNames, setExpanded])
+ }, [announce, isPreview, captureUI, claimMutation, expansionOverrides, focusEntity, folderNames, railMutation, releaseMutation, serverNames, setExpanded])
- const ungroupFolder = useCallback((folderId: string) => {
- const before = cloneRailState(renderState)
- const after = cloneRailState(renderState)
- const firstServerId = before.folders[folderId]?.[0]
- delete after.folders[folderId]
- after.folderOrder = after.folderOrder.filter((id) => id !== folderId)
- after.expanded = after.expanded.filter((id) => id !== folderId)
- const commands = planRailPersistence(before, after)
- if (commands.length !== 1) return
- if (!claimMutation()) return
- const assertUI = captureUI()
- setExpanded(after.expanded)
- railMutation.mutate(
- { before, after, commands, assertUI },
- {
- onSuccess: () => { try { assertUI() } catch { return }; announce("Group removed") },
- onError: () => {
- try { assertUI() } catch { return }
- if (before.expanded.includes(folderId)) setExpanded((current) => [...new Set([...current, folderId])])
- announce("Removing group failed and was rolled back")
- },
- onSettled: (_data, error) => {
- try { assertUI() } catch { return }
- releaseMutation()
- focusEntity(error || !firstServerId
- ? { kind: "folder", id: folderId }
- : { kind: "server", id: firstServerId }, { afterReconcile: true }, assertUI)
- },
- },
- )
- }, [captureUI, claimMutation, focusEntity, railMutation, releaseMutation, renderState, setExpanded])
-
- const { registerItem } = useServerRailPdd({
- scrollRef,
+ const dnd = useServerRailDnd({
getState: () => renderState,
canStart: () => !isPreview && !railMutation.isCommandPending(),
- getEntityLabel: (entity) => entity.kind === "server"
- ? serverNames.get(entity.id) ?? "Server"
- : folderNames.get(entity.id) ?? "Group",
onDragStart: (source) => {
dragSnapshotAtom.set(() => cloneRailState(renderState))
setDragSource(source)
},
- onPreview: setPreview,
+ onPreview: (instruction) => {
+ setPreview(instruction)
+ },
onDrop: (instruction) => {
const before = dragSnapshotAtom.get() ?? cloneRailState(renderState)
dragSnapshotAtom.set(() => null)
@@ -349,16 +326,9 @@ export const ServerRail = memo(function ServerRail({
dragSnapshotAtom.set(() => null)
setDragSource(null)
},
- onHoverExpand: (folderId) => {
- setExpanded((current) => current.includes(folderId) ? current : [...current, folderId])
- },
- onAnnounce: announce,
})
+ useLayoutEffect(() => { dnd.cancel() }, [dnd, navigationKey, activeFromProps, view, registry?.accountId])
- const previewFor = (entity: RailEntity) => preview?.target.kind === entity.kind
- && preview.target.id === entity.id
- ? preview.operation
- : null
const dragging = (entity: RailEntity) => dragSource?.kind === entity.kind
&& dragSource.id === entity.id
const folderServers = (folderId: string): Server[] => (renderState.folders[folderId] ?? [])
@@ -385,85 +355,63 @@ export const ServerRail = memo(function ServerRail({
</Tooltip>
)
const serverListPending = serversLoading && servers.length === 0 && folders.length === 0
- const items = serverListPending ? (
- <ServerRailSkeleton />
- ) : (
+ const serverItem = (server: Server, inFolder = false) => (
+ <SortableServer key={server.id} server={server}
+ href={serverHrefs[server.id] ?? serverRootHref(server.id)}
+ navigationDisabled={dragSource !== null}
+ active={view !== "dm" && activeId === server.id}
+ onClick={() => pickServer(server.id)}
+ onLeave={inFolder ? undefined : () => onLeaveServer?.(server.id)}
+ onOpenSettings={() => serverActivationRef.current.onOpenSettings?.(server.id)}
+ onOpenInvitePopover={onOpenInvitePopover ? () => serverActivationRef.current.onOpenInvitePopover?.(server.id) : undefined}
+ inFolder={inFolder} dragging={dragging({ kind: "server", id: server.id })}
+ preview={preview?.target.kind === "server" && preview.target.id === server.id && preview.operation !== "append" ? preview.operation : null}
+ combineWith={preview?.operation === "combine" && preview.target.kind === "server" && preview.target.id === server.id && preview.source.kind === "server" ? serverById.get(preview.source.id) : undefined}
+ dnd={dnd} dragDescriptionId={DRAG_INSTRUCTIONS_ID}
+ />
+ )
+ const items = serverListPending ? <ServerRailSkeleton /> : (
<div className="flex w-full flex-col items-center gap-2">
- {visibleTopLevelServers(renderState).map((serverId) => {
- const server = serverById.get(serverId)
- if (!server) return null
+ {railTopLevel(renderState).map((entry, index, entries) => {
+ if (entry.kind === "server") {
+ const server = serverById.get(entry.id)
+ return server ? serverItem(server) : null
+ }
+ const folderId = entry.id
+ const children = folderServers(folderId)
+ const open = renderState.expanded.includes(folderId) && !dragging(entry)
+ const active = children.some((server) => server.id === activeId)
+ const operation = preview?.target.kind === "folder" && preview.target.id === folderId && preview.operation !== "append" ? preview.operation : null
return (
- <SortableServer
- key={serverId}
- server={server}
- href={serverHrefs[serverId] ?? serverRootHref(serverId)}
- navigationDisabled={dragSource !== null}
- active={view !== "dm" && activeId === serverId}
- onClick={() => pickServer(serverId)}
- onLeave={() => onLeaveServer?.(serverId)}
- onOpenSettings={() => serverActivationRef.current.onOpenSettings?.(serverId)}
- onOpenInvitePopover={onOpenInvitePopover ? () => serverActivationRef.current.onOpenInvitePopover?.(serverId) : undefined}
- dragging={dragging({ kind: "server", id: serverId })}
- preview={previewFor({ kind: "server", id: serverId })}
- registerItem={registerItem}
- dragDescriptionId={DRAG_INSTRUCTIONS_ID}
- />
- )
- })}
- {renderState.folderOrder.map((folderId) => {
- const serversInFolder = folderServers(folderId)
- const open = renderState.expanded.includes(folderId)
- && !(dragSource?.kind === "folder" && dragSource.id === folderId)
- return (
- <div key={folderId} className="flex w-full flex-col items-center gap-2">
- <RailFolder
- folderId={folderId}
- name={folderNames.get(folderId) ?? "Group"}
- open={open}
- active={!open && serversInFolder.some((server) => server.id === activeId)}
- unread={!open && serversInFolder.some((server) => server.unread)}
+ <div key={`folder:${folderId}`} data-slot="community-rail-folder-surface" data-folder-id={folderId}
+ data-rail-preview={operation || undefined}
+ className="group/folder relative w-full py-1">
+ <RailFolderGapDropTarget dnd={dnd} folderId={folderId} operation="reorder-before" testId={tid.serverRailFolderBefore(folderId)} />
+ {index < entries.length - 1 && <RailFolderGapDropTarget dnd={dnd} folderId={folderId} operation="reorder-after" testId={tid.serverRailFolderAfter(folderId)} />}
+ <div data-slot="community-rail-folder-backdrop" className={`pointer-events-none absolute bg-accent/50 dark:bg-accent ${open ? "inset-x-1 inset-y-0 rounded-[12px]" : `left-1/2 top-1 size-10 -translate-x-1/2 transition-[border-radius] duration-150 ${active ? "rounded-xl" : "rounded-[18px] group-hover/folder:rounded-xl"}`} ${operation === "combine" ? "ring-2 ring-primary" : ""}`} />
+ {operation && operation !== "combine" && <span data-slot="community-server-rail-insert" className={`pointer-events-none absolute inset-x-2 z-10 h-0.5 rounded-full bg-primary ${operation === "reorder-before" ? "-top-1 -translate-y-1/2" : "-bottom-1 translate-y-1/2"}`} />}
+ <RailFolder folderId={folderId} name={folderNames.get(folderId) ?? "Group"} open={open}
+ active={!open && active}
+ unread={!open && children.some((server) => server.unread)}
onToggle={() => setExpanded((current) => {
- const collapsing = current.includes(folderId)
- if (railMutation.isCommandPending()) collapsedAtom.set((values) => {
- const next = new Set(values)
- if (collapsing) next.add(folderId)
- else next.delete(folderId)
- return next
- })
- return collapsing ? current.filter((id) => id !== folderId) : [...current, folderId]
+ const expanding = !current.includes(folderId)
+ if (railMutation.isCommandPending()) expansionOverrides.set((previous) => new Map(previous).set(folderId, expanding))
+ return expanding ? [...current, folderId] : current.filter((id) => id !== folderId)
})}
- folderServers={serversInFolder}
- onUngroup={() => ungroupFolder(folderId)}
- dragging={dragging({ kind: "folder", id: folderId })}
- preview={previewFor({ kind: "folder", id: folderId })}
- registerItem={registerItem}
- dragDescriptionId={DRAG_INSTRUCTIONS_ID}
+ folderServers={children} dragging={dragging(entry)} dnd={dnd} dragDescriptionId={DRAG_INSTRUCTIONS_ID}
/>
- {open && serversInFolder.length > 0 && (
- <div className="relative flex w-full flex-col items-center gap-2 py-1">
- <span className="pointer-events-none absolute inset-y-0 left-1/2 w-12 -translate-x-1/2 rounded-[20px] bg-primary/10" />
- {serversInFolder.map((server) => (
- <SortableServer
- key={server.id}
- server={server}
- href={serverHrefs[server.id] ?? serverRootHref(server.id)}
- navigationDisabled={dragSource !== null}
- active={view !== "dm" && activeId === server.id}
- onClick={() => pickServer(server.id)}
- onOpenSettings={() => serverActivationRef.current.onOpenSettings?.(server.id)}
- onOpenInvitePopover={onOpenInvitePopover ? () => serverActivationRef.current.onOpenInvitePopover?.(server.id) : undefined}
- inFolder
- dragging={dragging({ kind: "server", id: server.id })}
- preview={previewFor({ kind: "server", id: server.id })}
- registerItem={registerItem}
- dragDescriptionId={DRAG_INSTRUCTIONS_ID}
- />
- ))}
+ <div className={`relative grid transition-[grid-template-rows] duration-150 ease-out motion-reduce:transition-none ${open ? "grid-rows-[1fr]" : "grid-rows-[0fr]"}`} inert={!open}>
+ <div className="min-h-0 overflow-hidden">
+ <div className="flex w-full flex-col items-center gap-2 pt-2">
+ {children.map((server) => serverItem(server, true))}
+ <RailEndDropTarget dnd={dnd} target={{ kind: "folder-content", id: folderId }} testId={tid.serverRailFolderEnd(folderId)} active={preview?.operation === "append" && preview.target.kind === "folder-content" && preview.target.id === folderId} />
+ </div>
</div>
- )}
+ </div>
</div>
)
})}
+ <RailEndDropTarget dnd={dnd} target={{ kind: "root", id: "root" }} testId={tid.serverRailEnd} active={preview?.operation === "append" && preview.target.kind === "root"} />
</div>
)
@@ -490,10 +438,11 @@ export const ServerRail = memo(function ServerRail({
/>
)}
>
+ <ServerRailDragPreview dnd={dnd} servers={serverById} folderNames={folderNames} state={renderState} activeServerId={view === "dm" ? "" : activeId} />
<span id={DRAG_INSTRUCTIONS_ID} className="sr-only">
- Press Space to pick up a server or group. Use the arrow keys to choose a position,
- Space or Enter to drop, and Escape to cancel.
+ Drag to move a server or group. On touch screens, hold before moving. Escape cancels.
</span>
+ <span className="sr-only" role="status" aria-live="polite">{announcement}</span>
{createOpen && (
<CreateServerDialog
onClose={() => setCreateOpen(false)}
@@ -502,6 +451,10 @@ export const ServerRail = memo(function ServerRail({
)}
</ServerRailFrame>
)
+}
+
+export const ServerRail = memo(function ServerRail(props: ComponentProps<typeof ServerRailContent>) {
+ return <CommunityDndProvider><ServerRailContent {...props} /></CommunityDndProvider>
})
export function ServerRailPending({ bottomInset }: { bottomInset?: number }) {
diff --git a/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx b/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx
index ea370b7a1..aa116bb78 100644
--- a/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx
+++ b/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx
@@ -58,7 +58,7 @@ it.each([false, true])("keeps real same-server list, row and category nodes thro
const view = render(node("/c/channels/target", 0))
const scroll = await view.findByTestId(tid.channelSidebarScroll)
const row = view.getByTestId(tid.channelRow("channel"))
- expect(row).toHaveAttribute("aria-roledescription", "sortable")
+ expect(row).toHaveAttribute("aria-roledescription", "draggable")
const header = grouped ? view.getByText("Group") : null
scroll.scrollTop = 37
row.setAttribute("data-retained-row", "original")
@@ -88,11 +88,11 @@ it.each([false, true])("keeps real same-server list, row and category nodes thro
await act(async () => { view.rerender(node(mocks.pathname, 2)) })
await waitFor(() => expect(view.getByTestId("pending")).toHaveTextContent("false"))
assertNodes()
- expect(row).toHaveAttribute("aria-roledescription", "sortable")
+ expect(row).toHaveAttribute("aria-roledescription", "draggable")
const user = setupUser()
act(() => row.focus())
await user.keyboard(" ")
- expect(row).toHaveAttribute("aria-pressed", "true")
+ expect(row).not.toHaveAttribute("aria-pressed")
await user.keyboard("{Escape}")
assertNodes()
if (header) {
diff --git a/src/web/src/components/community/shell/server-sidebar-slot.tsx b/src/web/src/components/community/shell/server-sidebar-slot.tsx
index cd14ede34..1eef72d5d 100644
--- a/src/web/src/components/community/shell/server-sidebar-slot.tsx
+++ b/src/web/src/components/community/shell/server-sidebar-slot.tsx
@@ -1,4 +1,5 @@
"use client"
+import { readCommunityServerRailServers } from "@/lib/community-db/server-rail"
import { useAtom, useCreateAtom, useSelector } from "@tanstack/react-store";
import { getCommunityRuntime } from "@/stores/community/runtime"
@@ -62,7 +63,6 @@ import {
useCreateChannel,
useRenameChannel,
useDeleteChannel,
- useMoveChannel,
useCreateCategory,
useUpdateCategory,
useDeleteCategory,
@@ -204,7 +204,6 @@ function ServerSidebar({ serverId, href, routeCommitted }: { serverId: string; h
const createChannelMut = useCreateChannel()
const renameChannelMut = useRenameChannel()
const deleteChannelMut = useDeleteChannel()
- const moveChannelMut = useMoveChannel()
const createCategoryMut = useCreateCategory()
const updateCategoryMut = useUpdateCategory()
const deleteCategoryMut = useDeleteCategory()
@@ -217,8 +216,7 @@ function ServerSidebar({ serverId, href, routeCommitted }: { serverId: string; h
clearLastChannel(deletedServerId)
if (!needsNavigation || !ownerDeleteRouteToken) return
void (async () => {
- const allowed = new Set([...communityDb!.collections.serverMemberships.values()].filter((row) => row.viewer && row.userId === currentUser.id).map((row) => row.serverId))
- const survivor = [...communityDb!.collections.servers.values()].filter((server) => allowed.has(server.id)).sort((a, b) => (a.position ?? 0) - (b.position ?? 0)).find((server) => server.id !== deletedServerId)
+ const survivor = readCommunityServerRailServers(communityDb!).find((server) => server.id !== deletedServerId)
const destination = survivor
? await serverDestination(survivor.id)
: "/c/me"
@@ -441,22 +439,16 @@ function ServerSidebar({ serverId, href, routeCommitted }: { serverId: string; h
const onReorderCategoriesInSidebar = useCallback((categoryIds: string[]) => {
reorderCategoriesMut.mutate({ serverId, categoryIds }, { onError: (e) => toastApiError(e, "Failed to save category order") })
}, [reorderCategoriesMut, serverId])
- const onReorderChannelsInSidebar = useCallback((channelIds: string[]) => {
- reorderChannelsMut.mutate({ serverId, channelIds }, { onError: (e) => toastApiError(e, "Failed to save channel order") })
+ const onReorderChannelsInSidebar = useCallback((channelIds: string[], move?: Parameters<typeof reorderChannelsMut.mutate>[0]["move"]) => {
+ reorderChannelsMut.mutate({ serverId, channelIds, move }, { onError: (e) => toastApiError(e, "Failed to save channel order") })
}, [reorderChannelsMut, serverId])
- const onMoveChannelInSidebar = useCallback((channelId: string, categoryId: string | null) => {
- moveChannelMut.mutate({ serverId, channelId, categoryId }, { onError: (e) => toastApiError(e, "Failed to move channel") })
- }, [moveChannelMut, serverId])
- const onBlockedMove = useCallback(() => {
- toast("Can't move a channel between public and private categories")
- }, [])
-
const channelProps = useMemo(() => ({
serverName: currentServer?.name ?? "",
serverIcon: currentServer?.icon ?? null,
official: currentServer?.official ?? false,
activeChannel: currentChannelMeta?.parentChannelId ?? currentChannelId ?? "",
isAdmin,
+ reorderPending: reorderCategoriesMut.isPending || reorderChannelsMut.isPending,
currentUserId: currentUser.id,
setActiveChannel,
forumThreadsByParent,
@@ -473,12 +465,10 @@ function ServerSidebar({ serverId, href, routeCommitted }: { serverId: string; h
onUpdateCategory: sidebarHintOnly ? undefined : onUpdateCategoryInSidebar,
onReorderCategories: sidebarHintOnly ? undefined : onReorderCategoriesInSidebar,
onReorderChannels: sidebarHintOnly ? undefined : onReorderChannelsInSidebar,
- onMoveChannel: sidebarHintOnly ? undefined : onMoveChannelInSidebar,
- onBlockedMove,
serverId,
invitePopoverOpen,
onInvitePopoverOpenChange: sidebarHintOnly ? undefined : setInvitePopoverOpen,
- }), [currentServer?.name, currentServer?.icon, currentServer?.official, currentChannelMeta?.parentChannelId, currentChannelId, isAdmin, currentUser.id, setActiveChannel, forumThreadsByParent, activeForumThreadId, setActiveForumThread, sidebarHintOnly, onSidebarOpenSettings, onBlockedCreate, mutedChannels, onCreateChannelInSidebar, onCreateCategoryInSidebar, onRenameChannel, onDeleteChannelInSidebar, onDeleteCategoryInSidebar, onUpdateCategoryInSidebar, onReorderCategoriesInSidebar, onReorderChannelsInSidebar, onMoveChannelInSidebar, onBlockedMove, serverId, invitePopoverOpen, setInvitePopoverOpen])
+ }), [reorderCategoriesMut.isPending, reorderChannelsMut.isPending, currentServer?.name, currentServer?.icon, currentServer?.official, currentChannelMeta?.parentChannelId, currentChannelId, isAdmin, currentUser.id, setActiveChannel, forumThreadsByParent, activeForumThreadId, setActiveForumThread, sidebarHintOnly, onSidebarOpenSettings, onBlockedCreate, mutedChannels, onCreateChannelInSidebar, onCreateCategoryInSidebar, onRenameChannel, onDeleteChannelInSidebar, onDeleteCategoryInSidebar, onUpdateCategoryInSidebar, onReorderCategoriesInSidebar, onReorderChannelsInSidebar, serverId, invitePopoverOpen, setInvitePopoverOpen])
const openProfile = (name: string, e: React.MouseEvent, discriminator?: string, userId?: string) => {
// Delegate to the shell's registered openProfile via the community store.
diff --git a/src/web/src/components/community/shell/sortable-server.focus.dom.test.ts b/src/web/src/components/community/shell/sortable-server.focus.dom.test.ts
index 9b36aa519..d2f3d3c86 100644
--- a/src/web/src/components/community/shell/sortable-server.focus.dom.test.ts
+++ b/src/web/src/components/community/shell/sortable-server.focus.dom.test.ts
@@ -4,6 +4,8 @@ import { SortableServer } from "./sortable-server"
import { tid } from "@/lib/community/testids"
import { act, fireEvent, render, setupUser } from "@/test/react-dom-harness"
+const feedback = vi.hoisted(() => ({ tooltip: vi.fn() }))
+
vi.mock("@/components/ui/context-menu", () => ({
ContextMenu: ({ children }: { children: ReactNode }) => createElement(Fragment, null, children),
ContextMenuTrigger: ({ render }: { render: ReactNode }) =>
@@ -15,11 +17,10 @@ vi.mock("@/components/ui/context-menu", () => ({
ContextMenuSeparator: () => null,
}))
vi.mock("@/components/ui/tooltip", () => ({
- Tooltip: ({ children }: { children: ReactNode }) => createElement(Fragment, null, children),
+ Tooltip: ({ children, ...props }: { children: ReactNode }) => { feedback.tooltip(props); return createElement(Fragment, null, children) },
TooltipTrigger: ({ children }: { children: ReactNode }) => children,
TooltipContent: () => null,
}))
-vi.mock("./rail-indicator", () => ({ RailIndicator: () => null }))
vi.mock("@/components/ui/confirm-dialog", () => ({ ConfirmDialog: () => null }))
vi.mock("@/components/ui/number-ticker", () => ({ NumberTicker: () => null }))
vi.mock("@/components/avatar", () => ({ SeededBackdrop: () => null }))
@@ -53,11 +54,43 @@ function renderServer(
describe("SortableServer stable menu trigger", () => {
afterEach(() => vi.restoreAllMocks())
- it("updates href on the same registered anchor with the committed activation dispatcher", async () => {
- const registerItem = vi.fn(() => vi.fn())
+ it("previews the final target/source folder thumbnails and restores the same target anchor", () => {
+ const props = { server: { ...server, unread: true, mentions: 3 }, active: true, onClick: vi.fn() }
+ const source = { ...server, id: "b", name: "Bee", initial: "B", unread: false }
+ const result = render(createElement(SortableServer, { ...props, preview: "combine", combineWith: source }))
+ const anchor = result.getByTestId(tid.serverIcon("a"))
+ const preview = result.container.querySelector('[data-slot="community-server-rail-combine-preview"]')!
+ expect([...preview.querySelectorAll('[role="img"]')].map((node) => node.getAttribute("aria-label"))).toEqual(["A", "Bee"])
+ expect(preview).toHaveClass("size-12", "ring-primary")
+ expect(result.container.querySelector(`[data-testid="${tid.railUnreadBadge("a")}"]`)).toBeNull()
+ result.rerender(createElement(SortableServer, props))
+ expect(result.getByTestId(tid.serverIcon("a"))).toBe(anchor)
+ expect(result.container.querySelector('[data-slot="community-server-rail-combine-preview"]')).toBeNull()
+ expect(result.container.querySelectorAll('[role="img"]')).toHaveLength(1)
+ expect(result.getByTestId(tid.railUnreadBadge("a"))).toBeInTheDocument()
+ })
+
+ it("hides the dragged base tooltip and bar, and changes target feedback on the same anchor", () => {
+ const props = { server: { ...server, unread: true }, active: true, onClick: vi.fn() }
+ const result = render(createElement(SortableServer, { ...props, dragging: true, preview: "combine" }))
+ const anchor = result.getByTestId(tid.serverIcon("a"))
+ expect(feedback.tooltip).toHaveBeenLastCalledWith(expect.objectContaining({ open: false }))
+ expect(result.getByTestId(tid.serverRailIndicator("a"))).toHaveClass("h-0", "opacity-0")
+ expect(result.container.querySelector('[data-rail-preview="combine"] .ring-primary')).not.toBeNull()
+ result.rerender(createElement(SortableServer, { ...props, dragging: false, preview: "reorder-after" }))
+ expect(result.getByTestId(tid.serverIcon("a"))).toBe(anchor)
+ expect(result.getByTestId(tid.serverRailIndicator("a"))).toHaveClass("h-8")
+ expect(result.container.querySelector('[data-slot="community-server-rail-insert"]')).toHaveClass("-bottom-1")
+ result.rerender(createElement(SortableServer, props))
+ expect(result.container.querySelector('[data-rail-preview]')).toBeNull()
+ expect(result.container.querySelector('[data-slot="community-server-rail-insert"]')).toBeNull()
+ expect(feedback.tooltip).toHaveBeenLastCalledWith(expect.objectContaining({ open: false }))
+ })
+
+ it("updates href on the same anchor with the committed activation dispatcher", async () => {
const current = { activate: vi.fn() }
const dispatch = () => current.activate()
- const props = { server, onClick: dispatch, registerItem, href: "/c/channels/a/first" }
+ const props = { server, onClick: dispatch, href: "/c/channels/a/first" }
const result = render(createElement(SortableServer, props))
const anchor = result.getByTestId(tid.serverIcon("a"))
const originalActivate = current.activate
@@ -65,8 +98,6 @@ describe("SortableServer stable menu trigger", () => {
result.rerender(createElement(SortableServer, { ...props, href: "/c/channels/a/latest" }))
expect(result.getByTestId(tid.serverIcon("a"))).toBe(anchor)
expect(anchor).toHaveAttribute("href", "/c/channels/a/latest")
- expect(registerItem).toHaveBeenCalledTimes(1)
- expect(registerItem).toHaveBeenCalledWith({ kind: "server", id: "a" }, expect.any(HTMLElement), anchor)
await setupUser().click(anchor)
expect(originalActivate).not.toHaveBeenCalled()
expect(current.activate).toHaveBeenCalledTimes(1)
@@ -93,23 +124,19 @@ describe("SortableServer stable menu trigger", () => {
expect(result.container.querySelectorAll("context-menu-content")).toHaveLength(1)
})
- it("keeps the same button and drag registration when pointer hover activates the menu", () => {
+ it("keeps the same button when pointer hover activates the menu", () => {
const focus = vi.spyOn(HTMLElement.prototype, "focus")
- const dispose = vi.fn()
- const registerItem = vi.fn(() => dispose)
const onClick = vi.fn()
- const result = renderServer(false, 0, false, { registerItem, onClick })
+ const result = renderServer(false, 0, false, { onClick })
const originalButton = result.button()
fireEvent.pointerEnter(result.activationRoot())
expect(result.button()).toBe(originalButton)
- expect(registerItem).toHaveBeenCalledTimes(1)
expect(onClick).not.toHaveBeenCalled()
expect(result.container.querySelectorAll("context-menu-trigger")).toHaveLength(1)
expect(result.container.querySelectorAll("context-menu-content")).toHaveLength(1)
expect(focus).not.toHaveBeenCalled()
- expect(dispose).not.toHaveBeenCalled()
})
it("keeps the same button for first touch-like pointer activation", () => {
@@ -123,11 +150,11 @@ describe("SortableServer stable menu trigger", () => {
expect(result.container.querySelectorAll("context-menu-content")).toHaveLength(1)
})
- it("exposes keyboard drag help without positional menu shortcuts", () => {
+ it("keeps drag help without advertising keyboard sorting", () => {
const result = renderServer()
const button = result.button()
expect(button).toHaveAttribute("aria-describedby", "rail-help")
- expect(button).toHaveAttribute("aria-keyshortcuts", expect.stringContaining("Space"))
+ expect(button).not.toHaveAttribute("aria-keyshortcuts")
fireEvent.keyDown(button, { key: "F10", shiftKey: true })
expect(result.container.querySelectorAll("context-menu-content")).toHaveLength(1)
const menuText = result.container.textContent
diff --git a/src/web/src/components/community/shell/sortable-server.tsx b/src/web/src/components/community/shell/sortable-server.tsx
index cda3354e8..8ff56b391 100644
--- a/src/web/src/components/community/shell/sortable-server.tsx
+++ b/src/web/src/components/community/shell/sortable-server.tsx
@@ -1,9 +1,8 @@
"use client";
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { OfficialServerBadge } from "../official-server-badge";
-import { memo, useLayoutEffect, useRef } from "react";
+import { memo, useEffect, useRef } from "react";
import {
ContextMenu,
ContextMenuTrigger,
@@ -19,10 +18,12 @@ import {
} from "@/components/ui/tooltip";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { NumberTicker } from "@/components/ui/number-ticker";
-import { ServerIcon } from "@/components/community/server-icon";
+import { RailServerIcon } from "./rail-server-icon"
+import { RailFolderIcon } from "./rail-folder"
import { tid } from "@/lib/community/testids";
import type { Server } from "@/lib/community/models/navigation"
-import type { RailEntity, RailOperation } from "@/lib/community/server-rail-model"
+import type { RailOperation } from "@/lib/community/server-rail-model"
+import { RailDndBinding, type RailDndController } from "./use-server-rail-dnd"
import { CommunityNavigationLink } from "./community-navigation-link"
import { serverRootHref } from "@/lib/community/community-route"
@@ -39,11 +40,8 @@ type SortableServerProps = {
inFolder?: boolean;
dragging?: boolean;
preview?: RailOperation | null;
- registerItem?: (
- entity: RailEntity,
- element: HTMLElement,
- dragHandle: HTMLElement,
- ) => () => void;
+ combineWith?: Server;
+ dnd?: RailDndController;
dragDescriptionId?: string;
};
@@ -59,27 +57,24 @@ function SortableServerImpl({
inFolder,
dragging: isDragActive,
preview,
- registerItem,
+ combineWith,
+ dnd,
dragDescriptionId,
}: SortableServerProps) {
const rootRef = useRef<HTMLDivElement>(null)
const linkRef = useRef<HTMLAnchorElement>(null)
const [confirmLeave, setConfirmLeave] = useAtom(useCreateAtom(false));
const [activated, setActivated] = useAtom(useCreateAtom(false));
- useLayoutEffect(() => {
- if (!registerItem || !rootRef.current || !linkRef.current) return
- return registerItem(
- { kind: "server", id: server.id },
- rootRef.current,
- linkRef.current,
- )
- }, [registerItem, server.id])
+ const [tooltipOpen, setTooltipOpen] = useAtom(useCreateAtom(false));
+ useEffect(() => { if (isDragActive) setTooltipOpen(false) }, [isDragActive, setTooltipOpen])
+
const activate = activated ? undefined : () => setActivated(true);
const icon = (
<div
ref={rootRef}
style={{ opacity: isDragActive ? 0.3 : 1 }}
+ data-rail-preview={preview || undefined}
className="group relative flex w-full justify-center"
onPointerEnter={activate}
onPointerDownCapture={activate}
@@ -87,22 +82,18 @@ function SortableServerImpl({
onKeyDownCapture={activate}
onContextMenuCapture={activate}
>
- {(preview === "reorder-before" || preview === "reorder-after") && (
- <div
- data-testid={tid.serverRailInsert(server.id)}
- className={`pointer-events-none absolute left-1/2 z-10 h-0.5 w-9 -translate-x-1/2 rounded-full bg-primary ${preview === "reorder-before" ? "-top-1" : "-bottom-1"}`}
- />
- )}
+ {dnd && <RailDndBinding dnd={dnd} entity={{ kind: "server", id: server.id }} element={rootRef} handle={linkRef} />}
<RailIndicator
active={active}
unread={server.unread}
testId={tid.serverRailIndicator(server.id)}
+ hidden={isDragActive}
/>
+ {preview && preview !== "combine" && <span data-slot="community-server-rail-insert" className={`pointer-events-none absolute inset-x-2 z-10 h-0.5 rounded-full bg-primary ${preview === "reorder-before" ? "-top-1 -translate-y-1/2" : "-bottom-1 translate-y-1/2"}`} />}
<div
className={[
"relative size-10 transition-[border-radius,background-color,border-color,opacity,transform] duration-150",
- preview === "combine" ? "rounded-xl bg-primary/10 outline outline-2! outline-primary" : "",
- isDragActive ? "rounded-xl border-2 border-dashed border-muted-foreground/40" : "",
+ preview === "combine" && !combineWith ? "rounded-xl ring-2 ring-primary ring-offset-2 ring-offset-(--d-rail)" : "",
].join(" ")}
>
<CommunityNavigationLink
@@ -113,38 +104,21 @@ function SortableServerImpl({
ref={linkRef}
data-testid={tid.serverIcon(server.id)}
data-dragging={isDragActive || undefined}
- data-rail-preview={preview ?? undefined}
aria-label={server.official ? `${server.name}, Official server` : server.name}
aria-describedby={dragDescriptionId}
- aria-keyshortcuts="Space ArrowUp ArrowDown ArrowLeft ArrowRight Escape"
onActivate={() => { if (!active) onClick() }}
className={[
"group/server absolute left-1/2 top-1/2 z-1 grid size-11 -translate-x-1/2 -translate-y-1/2 place-items-center focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none active:cursor-grabbing [-webkit-touch-callout:none]",
active ? "cursor-default" : "cursor-pointer",
].join(" ")}
>
- <ServerIcon
- data-rail-drag-preview
- id={server.id}
- name={server.name}
- initial={server.initial}
- icon={server.icon}
- size={40}
- className={[
- "pointer-events-none relative grid size-10 place-items-center overflow-hidden font-brand text-xl font-bold transition-all duration-150",
- active
- ? "cursor-default rounded-xl"
- : "cursor-pointer rounded-[18px] group-hover/server:rounded-xl",
- server.icon
- ? active
- ? "bg-primary text-primary-foreground"
- : "bg-card group-hover/server:bg-primary group-hover/server:text-primary-foreground"
- : "text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)] group-hover/server:brightness-110",
- ].join(" ")}
- />
- <OfficialServerBadge official={server.official} className="absolute -left-1 -top-1 z-2" />
+ {preview === "combine" && combineWith ? (
+ <span data-slot="community-server-rail-combine-preview" className="pointer-events-none absolute -inset-0.5 grid size-12 place-items-center rounded-[12px] bg-accent/50 text-muted-foreground ring-2 ring-primary dark:bg-accent">
+ <RailFolderIcon open={false} folderServers={[server, combineWith]} />
+ </span>
+ ) : <RailServerIcon server={server} active={active} />}
</CommunityNavigationLink>
- {server.mentions > 0 && (
+ {server.mentions > 0 && !(preview === "combine" && combineWith) && (
<span
data-testid={tid.railUnreadBadge(server.id)}
className="pointer-events-none absolute -bottom-1 -right-1 z-2 grid h-5 min-w-5 place-items-center rounded-full bg-primary px-1 text-[11px] font-bold text-primary-foreground ring-2 ring-(--d-rail)"
@@ -158,7 +132,7 @@ function SortableServerImpl({
const withMenu = (
<ContextMenu>
- <ContextMenuTrigger render={icon} />
+ <ContextMenuTrigger render={icon} onTouchStart={(event) => { if (dnd?.latest.current.canStart()) event.preventBaseUIHandler() }} />
{activated && (
<ContextMenuContent className="w-52">
<div className="truncate px-2 py-1 text-xs font-semibold text-muted-foreground">
@@ -190,7 +164,7 @@ function SortableServerImpl({
return (
<>
- <Tooltip>
+ <Tooltip open={!isDragActive && tooltipOpen} onOpenChange={setTooltipOpen}>
<TooltipTrigger
render={<span className="flex w-full justify-center" />}
>
@@ -247,6 +221,10 @@ export function serverPropsEqual(prev: SortableServerProps, next: SortableServer
prev.inFolder === next.inFolder &&
prev.dragging === next.dragging &&
prev.preview === next.preview &&
+ prev.combineWith?.id === next.combineWith?.id &&
+ prev.combineWith?.name === next.combineWith?.name &&
+ prev.combineWith?.initial === next.combineWith?.initial &&
+ prev.combineWith?.icon === next.combineWith?.icon &&
// The presence of an optional handler flips menu items on/off, so compare
// definedness (not identity) — a menu row appears/disappears with it.
!!prev.onLeave === !!next.onLeave &&
diff --git a/src/web/src/components/community/shell/use-server-rail-dnd.tsx b/src/web/src/components/community/shell/use-server-rail-dnd.tsx
new file mode 100644
index 000000000..588038453
--- /dev/null
+++ b/src/web/src/components/community/shell/use-server-rail-dnd.tsx
@@ -0,0 +1,224 @@
+"use client"
+
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, type RefObject } from "react"
+import { useDrag, useDragLayer, useDragDropManager, useDrop } from "react-dnd"
+import { getEmptyImage } from "react-dnd-html5-backend"
+import { useAtom, useCreateAtom } from "@tanstack/react-store"
+import { useDndCancellation } from "../community-dnd"
+import { railTopLevel, railOperationAvailability, railInstructionIsAvailable, type RailContainer, type RailEntity, type RailInstruction, type RailState } from "@/lib/community/server-rail-model"
+
+const RAIL_ITEM = "community/server-rail"
+type RailDrag = { entity: RailEntity; owner: object }
+type RailDrop = { instruction: RailInstruction } | { cancelled: true }
+export type RailReturn = { entity: RailEntity; offset: { x: number; y: number }; element: HTMLElement }
+type Options = {
+ getState: () => RailState
+ canStart: () => boolean
+ onDragStart: (source: RailEntity) => void
+ onPreview: (instruction: RailInstruction | null) => void
+ onDrop: (instruction: RailInstruction) => void
+ onCancel: () => void
+}
+
+export function railInstructionAt(state: RailState, source: RailEntity, target: RailEntity, ratio: number): RailInstruction | null {
+ const available = railOperationAvailability(state, source, target)
+ const folderId = target.kind === "server" ? state.folderIds.find((id) => state.folders[id]?.includes(target.id)) : undefined
+ const operation = source.kind === "server" && target.kind === "folder" ? "combine"
+ : folderId ? ratio < 0.5 ? "reorder-before" : "reorder-after"
+ : ratio < 0.25 ? "reorder-before" : ratio > 0.75 ? "reorder-after"
+ : source.kind === "server" ? "combine" : ratio < 0.5 ? "reorder-before" : "reorder-after"
+ if (operation === "reorder-after") {
+ const last = folderId ? state.folders[folderId]?.at(-1) === target.id : railTopLevel(state).at(-1)?.id === target.id
+ if (last) {
+ const append: RailInstruction = { operation: "append", source, target: folderId ? { kind: "folder-content", id: folderId } : { kind: "root", id: "root" } }
+ return railInstructionIsAvailable(state, append) ? append : null
+ }
+ }
+ return available[operation] ? { source, target, operation } : null
+}
+
+export function useServerRailDnd(options: Options) {
+ const latest = useRef(options)
+ useLayoutEffect(() => { latest.current = options })
+ const owner = useMemo(() => ({}), [])
+ const manager = useDragDropManager()
+ const returning = useCreateAtom<RailReturn | null>(null)
+ const source = useRef<{ entity: RailEntity; element: HTMLElement | null } | null>(null)
+ const lastOffset = useRef<{ x: number; y: number } | null>(null)
+ const active = useRef(false)
+ const preview = useRef<RailInstruction | null>(null)
+ const suppressNextClick = useRef(false)
+ const updatePreview = useCallback((next: RailInstruction | null) => {
+ if (next && !active.current) return
+ const previous = preview.current
+ if (previous?.operation === next?.operation && previous?.target.kind === next?.target.kind && previous?.target.id === next?.target.id) return
+ preview.current = next
+ latest.current.onPreview(next)
+ }, [])
+ const finish = useCallback((result?: RailDrop | null, animate = true) => {
+ if (!active.current) return
+ active.current = false
+ suppressNextClick.current = true
+ updatePreview(null)
+ if (result && "instruction" in result) latest.current.onDrop(result.instruction)
+ else {
+ const offset = manager.getMonitor().getSourceClientOffset() ?? lastOffset.current
+ const origin = source.current
+ if (animate && origin?.element?.isConnected && offset && !window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
+ const value: RailReturn = { entity: origin.entity, element: origin.element, offset }
+ returning.set(() => value)
+ }
+ latest.current.onCancel()
+ }
+ source.current = null
+ }, [manager, returning, updatePreview])
+ const cancel = useCallback(() => finish(), [finish])
+ useDndCancellation(cancel)
+ const [{ background }, cancelDrop] = useDrop<RailDrag, RailDrop, { background: boolean }>(() => ({
+ accept: RAIL_ITEM,
+ canDrop: (item) => item.owner === owner && active.current,
+ drop: (_item, monitor) => monitor.didDrop() ? undefined : { cancelled: true },
+ collect: (monitor) => ({ background: monitor.isOver({ shallow: true }) }),
+ }), [owner])
+ useLayoutEffect(() => { if (background) updatePreview(null) }, [background, updatePreview])
+ useEffect(() => {
+ cancelDrop(document.body)
+ return () => { cancelDrop(null) }
+ }, [cancelDrop])
+ useLayoutEffect(() => manager.getMonitor().subscribeToStateChange(() => {
+ if (active.current && manager.getMonitor().getTargetIds().length === 0) updatePreview(null)
+ }), [manager, updatePreview])
+ useLayoutEffect(() => manager.getMonitor().subscribeToOffsetChange(() => {
+ const offset = manager.getMonitor().getSourceClientOffset()
+ if (active.current && offset) lastOffset.current = offset
+ }), [manager])
+ useLayoutEffect(() => () => { finish(null, false); returning.set(() => null) }, [finish, returning])
+ return useMemo(() => ({
+ owner, latest, updatePreview, finish, returning,
+ completeReturn: (value: RailReturn) => { if (returning.get() === value) returning.set(() => null) },
+ begin: (entity: RailEntity, element: HTMLElement | null = null): RailDrag | null => {
+ if (!latest.current.canStart()) return null
+ returning.set(() => null)
+ lastOffset.current = null
+ source.current = { entity, element }
+ active.current = true
+ latest.current.onDragStart(entity)
+ return { entity, owner }
+ },
+ suppressClick: () => active.current || suppressNextClick.current,
+ resumeClick: () => { if (!active.current) suppressNextClick.current = false },
+ cancel: () => {
+ returning.set(() => null)
+ if (!active.current) return
+ finish(null, false)
+ if (manager.getMonitor().isDragging()) manager.getActions().endDrag()
+ },
+ }), [owner, updatePreview, finish, manager, returning])
+}
+export type RailDndController = ReturnType<typeof useServerRailDnd>
+
+export function useServerRailDrag(dnd: RailDndController) {
+ const [returning] = useAtom(dnd.returning)
+ const drag = useDragLayer((monitor) => {
+ const item = monitor.isDragging() && monitor.getItemType() === RAIL_ITEM ? monitor.getItem<RailDrag>() : null
+ return { entity: item?.owner === dnd.owner ? item.entity : null, offset: monitor.getSourceClientOffset() }
+ })
+ return returning ? { entity: returning.entity, offset: returning.offset, returning } : { ...drag, returning: null }
+}
+
+export function RailDndBinding({ dnd, entity, element, handle }: {
+ dnd: RailDndController
+ entity: RailEntity
+ element: RefObject<HTMLElement | null>
+ handle: RefObject<HTMLElement | null>
+}) {
+ const { kind, id } = entity
+ const manager = useDragDropManager()
+ const [, drag, preview] = useDrag<RailDrag, RailDrop>(() => ({
+ type: RAIL_ITEM,
+ canDrag: () => dnd.latest.current.canStart(),
+ item: () => dnd.begin(entity, handle.current),
+ end: (_item, monitor) => dnd.finish(monitor.didDrop() ? monitor.getDropResult() : null),
+ }), [dnd, entity.kind, entity.id])
+ const instruction = useCallback((item: RailDrag, y: number | undefined) => {
+ if (item.owner !== dnd.owner || y === undefined || !element.current) return null
+ const rect = element.current.getBoundingClientRect()
+ return railInstructionAt(dnd.latest.current.getState(), item.entity, { kind, id }, (y - rect.top) / rect.height)
+ }, [dnd, element, kind, id])
+ const [{ over, handlerId }, drop] = useDrop<RailDrag, RailDrop, { over: boolean; handlerId: string | symbol | null }>(() => ({
+ accept: RAIL_ITEM,
+ canDrop: (item, monitor) => !!instruction(item, monitor.getClientOffset()?.y),
+ drop: (item, monitor) => {
+ if (monitor.didDrop()) return
+ const next = instruction(item, monitor.getClientOffset()?.y)
+ return next ? { instruction: next } : undefined
+ },
+ collect: (monitor) => {
+ const over = monitor.isOver({ shallow: true })
+ return { over, handlerId: monitor.getHandlerId() }
+ },
+ }), [instruction])
+ useLayoutEffect(() => {
+ const monitor = manager.getMonitor()
+ if (over && monitor.getTargetIds().at(-1) === handlerId) dnd.updatePreview(instruction(monitor.getItem(), monitor.getClientOffset()?.y))
+ }, [dnd, manager, over, handlerId, instruction])
+ useLayoutEffect(() => manager.getMonitor().subscribeToOffsetChange(() => {
+ const monitor = manager.getMonitor()
+ if (monitor.getTargetIds().at(-1) !== handlerId) return
+ const item = monitor.getItem() as RailDrag | null
+ if (item) dnd.updatePreview(instruction(item, monitor.getClientOffset()?.y))
+ }), [manager, handlerId, dnd, instruction])
+ useEffect(() => {
+ drag(handle)
+ preview(getEmptyImage(), { captureDraggingState: true })
+ drop(element)
+ const node = handle.current
+ const suppress = (event: Event) => {
+ if (dnd.suppressClick()) { event.preventDefault(); event.stopPropagation() }
+ }
+ const resume = () => dnd.resumeClick()
+ node?.addEventListener("pointerdown", resume, true)
+ node?.addEventListener("click", suppress, true)
+ node?.addEventListener("contextmenu", suppress, true)
+ return () => {
+ drag(null); preview(null); drop(null)
+ node?.removeEventListener("pointerdown", resume, true)
+ node?.removeEventListener("click", suppress, true)
+ node?.removeEventListener("contextmenu", suppress, true)
+ }
+ }, [drag, preview, drop, dnd, element, handle])
+ return null
+}
+
+export function RailEndDropTarget({ dnd, target, testId, active = false }: { dnd: RailDndController; target: RailContainer; testId: string; active?: boolean }) {
+ const item = useDragLayer((monitor) => monitor.isDragging() && monitor.getItemType() === RAIL_ITEM ? monitor.getItem<RailDrag>() : null)
+ const { kind, id } = target
+ const instruction = useCallback((drag: RailDrag): RailInstruction => ({ operation: "append", source: drag.entity, target: kind === "root" ? { kind, id: "root" } : { kind, id } }), [kind, id])
+ const valid = !!item && item.owner === dnd.owner && railInstructionIsAvailable(dnd.latest.current.getState(), instruction(item))
+ const [{ over }, drop] = useDrop<RailDrag, RailDrop, { over: boolean }>(() => ({
+ accept: RAIL_ITEM,
+ canDrop: (drag) => drag.owner === dnd.owner && railInstructionIsAvailable(dnd.latest.current.getState(), instruction(drag)),
+ drop: (drag, monitor) => monitor.didDrop() ? undefined : { instruction: instruction(drag) },
+ collect: (monitor) => ({ over: monitor.isOver({ shallow: true }) && monitor.canDrop() }),
+ }), [dnd, instruction])
+ useLayoutEffect(() => { if (over && item) dnd.updatePreview(instruction(item)) }, [dnd, over, item, instruction])
+ return <div ref={(node) => { drop(node) }} data-testid={testId} aria-hidden="true"
+ className={`relative z-20 -mt-2 w-full shrink-0 ${valid && (over || active) ? "h-10" : "h-0"}`}>
+ {valid && <span className={`absolute left-1/2 h-2 w-12 -translate-x-1/2 ${kind === "root" ? "-top-1" : "-top-2"}`} />}
+ {valid && (over || active) && <span data-slot="community-server-rail-end-region" className="pointer-events-none absolute inset-x-1 inset-y-0 rounded-[12px] border-2 border-dashed border-primary bg-primary/5" />}
+ </div>
+}
+
+export function RailFolderGapDropTarget({ dnd, folderId, operation, testId }: { dnd: RailDndController; folderId: string; operation: "reorder-before" | "reorder-after"; testId: string }) {
+ const instruction = useCallback((drag: RailDrag): RailInstruction => ({ operation, source: drag.entity, target: { kind: "folder", id: folderId } }), [folderId, operation])
+ const [{ over, item }, drop] = useDrop<RailDrag, RailDrop, { over: boolean; item: RailDrag | null }>(() => ({
+ accept: RAIL_ITEM,
+ canDrop: (drag) => drag.owner === dnd.owner && railInstructionIsAvailable(dnd.latest.current.getState(), instruction(drag)),
+ drop: (drag, monitor) => monitor.didDrop() ? undefined : { instruction: instruction(drag) },
+ collect: (monitor) => ({ over: monitor.isOver({ shallow: true }) && monitor.canDrop(), item: monitor.getItem() }),
+ }), [dnd, instruction])
+ const valid = !!item && item.owner === dnd.owner && railInstructionIsAvailable(dnd.latest.current.getState(), instruction(item))
+ useLayoutEffect(() => { if (over && item) dnd.updatePreview(instruction(item)) }, [dnd, over, item, instruction])
+ if (!valid) return null
+ return <div ref={(node) => { drop(node) }} data-testid={testId} aria-hidden="true" className={`absolute inset-x-0 z-10 h-2 ${operation === "reorder-before" ? "-top-2" : "-bottom-2"}`} />
+}
diff --git a/src/web/src/components/community/shell/use-server-rail-pdd.behavior.dom.test.ts b/src/web/src/components/community/shell/use-server-rail-pdd.behavior.dom.test.ts
deleted file mode 100644
index c298b1719..000000000
--- a/src/web/src/components/community/shell/use-server-rail-pdd.behavior.dom.test.ts
+++ /dev/null
@@ -1,793 +0,0 @@
-import { createElement, type RefObject } from "react"
-import { act, render as rtlRender } from "@/test/react-dom-harness"
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-
-const adapters = vi.hoisted(() => ({
- draggables: [] as unknown[],
- targets: [] as unknown[],
- monitor: null as unknown,
- autoScroll: null as unknown,
- cleanupDraggable: vi.fn(),
- cleanupTarget: vi.fn(),
- cleanupMonitor: vi.fn(),
- cleanupAutoScroll: vi.fn(),
-}))
-
-vi.mock("@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter", () => ({
- draggable: (options: unknown) => {
- adapters.draggables.push(options)
- return adapters.cleanupDraggable
- },
- dropTargetForElements: (options: unknown) => {
- adapters.targets.push(options)
- return adapters.cleanupTarget
- },
- monitorForElements: (options: unknown) => {
- adapters.monitor = options
- return adapters.cleanupMonitor
- },
-}))
-
-vi.mock("@atlaskit/pragmatic-drag-and-drop-auto-scroll/element", () => ({
- autoScrollForElements: (options: unknown) => {
- adapters.autoScroll = options
- return adapters.cleanupAutoScroll
- },
-}))
-
-import type { RailEntity, RailState } from "@/lib/community/server-rail-model"
-import {
- SERVER_RAIL_TOUCH_HOLD_MS,
- useServerRailPdd,
-} from "./use-server-rail-pdd"
-
-type TestEvent = {
- type: string
- defaultPrevented: boolean
- propagationStopped: boolean
- preventDefault: () => void
- stopPropagation: () => void
- [key: string]: unknown
-}
-
-function testEvent(type: string, fields: Record<string, unknown> = {}): TestEvent {
- return {
- type,
- defaultPrevented: false,
- propagationStopped: false,
- preventDefault() { this.defaultPrevented = true },
- stopPropagation() { this.propagationStopped = true },
- ...fields,
- }
-}
-
-class FakeEventTarget {
- private readonly listeners = new Map<string, Set<(event: TestEvent) => void>>()
-
- addEventListener(type: string, listener: (event: TestEvent) => void) {
- const listeners = this.listeners.get(type) ?? new Set()
- listeners.add(listener)
- this.listeners.set(type, listeners)
- }
-
- removeEventListener(type: string, listener: (event: TestEvent) => void) {
- this.listeners.get(type)?.delete(listener)
- }
-
- dispatch(type: string, event = testEvent(type)): TestEvent {
- for (const listener of this.listeners.get(type) ?? []) listener(event)
- return event
- }
-
- dispatchEvent(event: TestEvent): boolean {
- this.dispatch(event.type, event)
- return !event.defaultPrevented
- }
-}
-
-class FakeMouseEvent implements TestEvent {
- [key: string]: unknown
- readonly type: string
- readonly clientX: number
- readonly clientY: number
- defaultPrevented = false
- propagationStopped = false
-
- constructor(type: string, init: { clientX?: number; clientY?: number } = {}) {
- this.type = type
- this.clientX = init.clientX ?? 0
- this.clientY = init.clientY ?? 0
- }
-
- preventDefault() { this.defaultPrevented = true }
- stopPropagation() { this.propagationStopped = true }
-}
-
-type Rect = { top: number; bottom: number; left: number; right: number; height: number; width: number }
-
-function rect(top: number, bottom: number, left = 0, right = 40): Rect {
- return { top, bottom, left, right, height: bottom - top, width: right - left }
-}
-
-class FakeElement extends FakeEventTarget {
- scrollTop = 0
- scrollLeft = 0
- isConnected = true
- clickCount = 0
- lastClickEvent: FakeMouseEvent | null = null
- dragPreview: FakeElement | null = null
- cloneCount = 0
- removed = false
- readonly style: Record<string, string> = {}
- readonly attributes = new Map<string, string>()
- readonly focus = vi.fn()
-
- constructor(public bounds: Rect) {
- super()
- }
-
- getBoundingClientRect() { return this.bounds }
-
- querySelector(selector: string) {
- return selector === "[data-rail-drag-preview]" ? this.dragPreview : null
- }
-
- cloneNode() {
- this.cloneCount += 1
- const clone = new FakeElement({ ...this.bounds })
- for (const [name, value] of this.attributes) clone.attributes.set(name, value)
- return clone
- }
-
- setAttribute(name: string, value: string) { this.attributes.set(name, value) }
- removeAttribute(name: string) { this.attributes.delete(name) }
- remove() { this.removed = true }
-
- click() {
- this.clickCount += 1
- this.lastClickEvent = new FakeMouseEvent("click")
- this.dispatchEvent(this.lastClickEvent)
- }
-}
-
-class FakeDocument extends FakeEventTarget {
- visibilityState: "visible" | "hidden" = "visible"
- points: FakeElement[] = []
- readonly documentElement = { style: { userSelect: "text" } }
- readonly removeAllRanges = vi.fn()
- readonly body: {
- children: FakeElement[]
- appendChild: ReturnType<typeof vi.fn>
- }
-
- constructor() {
- super()
- const children: FakeElement[] = []
- this.body = {
- children,
- appendChild: vi.fn((element: FakeElement) => {
- children.push(element)
- return element
- }),
- }
- }
-
- elementsFromPoint() { return this.points }
- getSelection() { return { removeAllRanges: this.removeAllRanges } }
-}
-
-type HookOptions = Parameters<typeof useServerRailPdd>[0]
-type HookApi = ReturnType<typeof useServerRailPdd>
-
-type DraggableOptions = {
- canDrag: () => boolean
- getInitialData: () => Record<string, unknown>
-}
-
-type TargetOptions = {
- canDrop: (args: { source: { data: Record<string, unknown> } }) => boolean
- getIsSticky: () => boolean
- getData: (args: {
- input: { clientX: number; clientY: number }
- element: HTMLElement
- source: { data: Record<string, unknown> }
- }) => Record<string, unknown>
-}
-
-type MonitorOptions = {
- canMonitor: (args: { source: { data: Record<string, unknown> } }) => boolean
- onDragStart: (args: { source: { data: Record<string, unknown> } }) => void
- onDrag: (args: MonitorLocation) => void
- onDropTargetChange: (args: MonitorLocation) => void
- onDrop: (args: MonitorLocation) => void
-}
-
-type MonitorLocation = {
- source: { data: Record<string, unknown> }
- location: { current: { dropTargets: Array<{ data: Record<string, unknown> }> } }
-}
-
-type AutoScrollOptions = {
- getAllowedAxis: () => string
- getConfiguration: () => { maxScrollSpeed: string }
-}
-
-const renderers: ReturnType<typeof rtlRender>[] = []
-const rtlContainer = document.createElement("div")
-let fakeDocument: FakeDocument
-let fakeWindow: FakeEventTarget
-let animationFrames: Map<number, FrameRequestCallback>
-let nextFrameId: number
-
-function stateFixture(): RailState {
- return {
- serverOrder: ["a", "b", "c", "d"],
- folderOrder: ["f", "g"],
- folders: { f: ["c"], g: ["d"] },
- expanded: [],
- }
-}
-
-function Capture({ options, onResult }: { options: HookOptions; onResult: (api: HookApi) => void }) {
- onResult(useServerRailPdd(options))
- return null
-}
-
-async function renderHook(overrides: Partial<HookOptions> = {}) {
- const scroll = new FakeElement(rect(0, 300, 0, 56))
- const callbacks = {
- getState: vi.fn(() => stateFixture()),
- canStart: vi.fn(() => true),
- getEntityLabel: vi.fn((entity: RailEntity) => entity.id.toUpperCase()),
- onDragStart: vi.fn(),
- onPreview: vi.fn(),
- onDrop: vi.fn(),
- onCancel: vi.fn(),
- onHoverExpand: vi.fn(),
- onAnnounce: vi.fn(),
- }
- let options: HookOptions = {
- scrollRef: { current: scroll as unknown as HTMLElement },
- ...callbacks,
- ...overrides,
- }
- let current!: HookApi
- let renderer!: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(createElement(Capture, {
- options,
- onResult: (api) => { current = api },
- }), { container: rtlContainer, baseElement: rtlContainer })
- })
- renderers.push(renderer)
- return {
- callbacks,
- scroll,
- get current() { return current },
- async rerender(next: Partial<HookOptions>) {
- options = { ...options, ...next }
- await act(async () => renderer.rerender(createElement(Capture, {
- options,
- onResult: (api) => { current = api },
- })))
- },
- }
-}
-
-function register(
- api: HookApi,
- entity: RailEntity,
- bounds: Rect,
-) {
- const element = new FakeElement(bounds)
- const handle = new FakeElement(bounds)
- const dragPreview = new FakeElement(rect(0, 40, 0, 40))
- dragPreview.setAttribute("data-rail-drag-preview", "")
- handle.dragPreview = dragPreview
- const dispose = api.registerItem(
- entity,
- element as unknown as HTMLElement,
- handle as unknown as HTMLElement,
- )
- return { entity, element, handle, dragPreview, dispose }
-}
-
-function point(identifier: number, clientX: number, clientY: number) {
- return { identifier, clientX, clientY }
-}
-
-function touch(
- handle: FakeElement,
- type: "touchstart" | "touchmove" | "touchend" | "touchcancel",
- touches: ReturnType<typeof point>[],
- changedTouches = touches,
-) {
- return handle.dispatch(type, testEvent(type, { touches, changedTouches }))
-}
-
-function key(target: FakeEventTarget, value: string) {
- return target.dispatch("keydown", testEvent("keydown", { key: value }))
-}
-
-function flushAnimationFrame() {
- const first = animationFrames.entries().next().value as [number, FrameRequestCallback] | undefined
- if (!first) return
- animationFrames.delete(first[0])
- first[1](0)
-}
-
-function monitorLocation(
- source: RailEntity,
- records: Array<{ data: Record<string, unknown> }>,
-): MonitorLocation {
- return {
- source: { data: { railKind: source.kind, railId: source.id } },
- location: { current: { dropTargets: records } },
- }
-}
-
-function targetRecord(
- index: number,
- target: FakeElement,
- source: RailEntity,
- clientY: number,
-) {
- const options = adapters.targets[index] as TargetOptions
- return {
- data: options.getData({
- input: { clientX: 20, clientY },
- element: target as unknown as HTMLElement,
- source: { data: { railKind: source.kind, railId: source.id } },
- }),
- }
-}
-
-beforeEach(() => {
- vi.useFakeTimers()
- adapters.draggables.length = 0
- adapters.targets.length = 0
- adapters.monitor = null
- adapters.autoScroll = null
- adapters.cleanupDraggable.mockReset()
- adapters.cleanupTarget.mockReset()
- adapters.cleanupMonitor.mockReset()
- adapters.cleanupAutoScroll.mockReset()
- fakeDocument = new FakeDocument()
- fakeWindow = new FakeEventTarget()
- animationFrames = new Map()
- nextFrameId = 1
- vi.stubGlobal("document", fakeDocument)
- vi.stubGlobal("window", fakeWindow)
- vi.stubGlobal("MouseEvent", FakeMouseEvent)
- vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
- const id = nextFrameId++
- animationFrames.set(id, callback)
- return id
- })
- vi.stubGlobal("cancelAnimationFrame", (id: number) => animationFrames.delete(id))
-})
-
-afterEach(async () => {
- await act(async () => {
- for (const renderer of renderers.splice(0)) renderer.unmount()
- })
- vi.useRealTimers()
- vi.unstubAllGlobals()
-})
-
-describe("useServerRailPdd behavior", () => {
- it("adapts native PDD availability, previews, hover expansion, and drop", async () => {
- const hook = await renderHook()
- const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40))
- const b = register(hook.current, { kind: "server", id: "b" }, rect(80, 120))
- const folder = register(hook.current, { kind: "folder", id: "f" }, rect(160, 200))
- register(hook.current, { kind: "folder", id: "g" }, rect(240, 280))
-
- const draggable = adapters.draggables[0] as DraggableOptions
- expect(draggable.canDrag()).toBe(true)
- expect(draggable.getInitialData()).toEqual({ railKind: "server", railId: "a" })
- const bTarget = adapters.targets[1] as TargetOptions
- expect(bTarget.canDrop({ source: { data: draggable.getInitialData() } })).toBe(true)
- expect(bTarget.canDrop({ source: { data: { railKind: "server", railId: "b" } } })).toBe(false)
- expect(bTarget.getIsSticky()).toBe(false)
- bTarget.getData({
- input: { clientX: 20, clientY: 100 },
- element: b.element as unknown as HTMLElement,
- source: { data: { railKind: "invalid", railId: "x" } },
- })
-
- const monitor = adapters.monitor as MonitorOptions
- expect(monitor.canMonitor({ source: { data: draggable.getInitialData() } })).toBe(true)
- expect(monitor.canMonitor({ source: { data: {} } })).toBe(false)
- monitor.onDragStart({ source: { data: {} } })
- monitor.onDragStart({ source: { data: draggable.getInitialData() } })
- expect(draggable.canDrag()).toBe(false)
-
- const afterB = targetRecord(1, b.element, a.entity, 115)
- monitor.onDrag(monitorLocation(a.entity, [afterB]))
- expect(hook.callbacks.onPreview).toHaveBeenLastCalledWith(expect.objectContaining({
- operation: "reorder-after",
- }))
-
- const intoFolder = targetRecord(2, folder.element, a.entity, 180)
- monitor.onDropTargetChange(monitorLocation(a.entity, [intoFolder]))
- const sameFolderNewSource = targetRecord(2, folder.element, b.entity, 180)
- monitor.onDrag(monitorLocation(b.entity, [sameFolderNewSource]))
- await act(async () => vi.advanceTimersByTime(500))
- expect(hook.callbacks.onHoverExpand).toHaveBeenCalledWith("f")
-
- monitor.onDrop(monitorLocation(a.entity, [afterB]))
- expect(hook.callbacks.onDrop).toHaveBeenCalledWith(expect.objectContaining({
- operation: "reorder-after",
- }))
- monitor.onDrag(monitorLocation(a.entity, [afterB]))
- monitor.onDropTargetChange(monitorLocation(a.entity, [afterB]))
- monitor.onDrop(monitorLocation(a.entity, [afterB]))
- const autoScroll = adapters.autoScroll as AutoScrollOptions
- expect(autoScroll.getAllowedAxis()).toBe("vertical")
- expect(autoScroll.getConfiguration()).toEqual({ maxScrollSpeed: "fast" })
- })
-
- it("supports keyboard pickup, spatial changes, drop, cancellation, and pending lock", async () => {
- const hook = await renderHook()
- const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40, 10, 50))
- const b = register(hook.current, { kind: "server", id: "b" }, rect(80, 120, 0, 40))
- register(hook.current, { kind: "folder", id: "f" }, rect(160, 200))
-
- expect(key(a.handle, "x").defaultPrevented).toBe(false)
- expect(key(a.handle, " ").defaultPrevented).toBe(true)
- expect(hook.callbacks.onAnnounce).toHaveBeenCalledWith(expect.stringContaining("A picked up"))
- flushAnimationFrame()
- expect(a.handle.focus).toHaveBeenCalledWith({ preventScroll: true })
-
- const replacement = register(hook.current, a.entity, rect(0, 40))
- expect(replacement.handle.focus).toHaveBeenCalledWith({ preventScroll: true })
- expect(key(a.handle, "ArrowDown").defaultPrevented).toBe(true)
- expect(hook.callbacks.onAnnounce).toHaveBeenCalledWith("A will move after B")
- expect(key(a.handle, "ArrowRight").defaultPrevented).toBe(true)
- expect(hook.callbacks.onAnnounce).toHaveBeenCalledWith("A will move into B")
- expect(key(a.handle, "ArrowLeft").defaultPrevented).toBe(true)
- expect(key(a.handle, "ArrowDown").defaultPrevented).toBe(true)
- expect(hook.callbacks.onAnnounce).toHaveBeenCalledWith("A will move into F")
- expect(key(a.handle, "Enter").defaultPrevented).toBe(true)
- expect(hook.callbacks.onDrop).toHaveBeenCalled()
-
- key(b.handle, " ")
- expect(key(b.handle, "ArrowUp").defaultPrevented).toBe(true)
- key(b.handle, " ")
- expect(hook.callbacks.onDrop).toHaveBeenCalledWith(expect.objectContaining({
- operation: "reorder-before",
- }))
-
- const folderHandle = (adapters.draggables[2] as DraggableOptions)
- expect(folderHandle.getInitialData()).toEqual({ railKind: "folder", railId: "f" })
- const registeredFolder = register(hook.current, { kind: "folder", id: "g" }, rect(240, 280))
- key(registeredFolder.handle, " ")
- expect(key(registeredFolder.handle, "ArrowDown").defaultPrevented).toBe(true)
- key(registeredFolder.handle, "Escape")
-
- key(a.handle, " ")
- const escape = key(fakeDocument, "Escape")
- expect(escape.propagationStopped).toBe(true)
- expect(hook.callbacks.onAnnounce).toHaveBeenCalledWith("A move cancelled")
-
- key(a.handle, " ")
- fakeWindow.dispatch("blur")
- key(a.handle, " ")
- fakeDocument.visibilityState = "hidden"
- fakeDocument.dispatch("visibilitychange")
- fakeDocument.visibilityState = "visible"
-
- key(a.handle, " ")
- await hook.rerender({ canStart: () => false })
- expect(hook.callbacks.onCancel).toHaveBeenCalled()
- const locked = key(a.handle, " ")
- expect(locked.defaultPrevented).toBe(false)
- expect(hook.callbacks.onAnnounce).toHaveBeenCalledWith(
- "A server rail move is already being saved",
- )
- })
-
- it("falls back across keyboard combine and relative-order availability", async () => {
- const hook = await renderHook()
- const b = register(hook.current, { kind: "server", id: "b" }, rect(0, 40))
- register(hook.current, { kind: "server", id: "a" }, rect(80, 120))
-
- expect(key(b.handle, " ").defaultPrevented).toBe(true)
- expect(key(b.handle, "ArrowDown").defaultPrevented).toBe(true)
- expect(hook.callbacks.onAnnounce).toHaveBeenLastCalledWith("B will move into A")
-
- expect(key(b.handle, "ArrowLeft").defaultPrevented).toBe(true)
- expect(hook.callbacks.onAnnounce).toHaveBeenLastCalledWith("B will move before A")
-
- hook.callbacks.getState.mockReturnValue({
- serverOrder: ["c", "d"],
- folderOrder: [],
- folders: {},
- expanded: [],
- })
- expect(key(b.handle, "ArrowLeft").defaultPrevented).toBe(false)
- expect(key(b.handle, "Escape").defaultPrevented).toBe(true)
-
- hook.callbacks.getState.mockReturnValue({
- serverOrder: ["a", "b"],
- folderOrder: ["f"],
- folders: { f: ["a", "b"] },
- expanded: ["f"],
- })
- expect(key(b.handle, " ").defaultPrevented).toBe(true)
- const noOpAnnouncementCount = hook.callbacks.onAnnounce.mock.calls.length
- expect(key(b.handle, "ArrowDown").defaultPrevented).toBe(true)
- expect(hook.callbacks.onAnnounce).toHaveBeenCalledTimes(noOpAnnouncementCount)
- expect(key(b.handle, "Escape").defaultPrevented).toBe(true)
- })
-
- it("separates taps, scroll, context menu, multi-touch, and cancellation", async () => {
- const hook = await renderHook()
- const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40))
- register(hook.current, { kind: "server", id: "b" }, rect(80, 120))
- const desktopContext = a.handle.dispatch("contextmenu", testEvent("contextmenu"))
- expect(desktopContext.defaultPrevented).toBe(false)
- expect(desktopContext.propagationStopped).toBe(false)
-
- const tapStart = touch(a.handle, "touchstart", [point(1, 10, 10)])
- expect(tapStart.defaultPrevented).toBe(false)
- expect(tapStart.propagationStopped).toBe(true)
- const tapEnd = touch(a.handle, "touchend", [], [point(1, 10, 10)])
- expect(tapEnd.defaultPrevented).toBe(true)
- expect(a.handle.clickCount).toBe(1)
-
- touch(a.handle, "touchstart", [point(2, 10, 10)])
- const scrollMove = touch(a.handle, "touchmove", [point(2, 10, 30)])
- expect(scrollMove.defaultPrevented).toBe(false)
-
- touch(a.handle, "touchstart", [point(3, 10, 10)])
- hook.scroll.scrollTop += 1
- hook.scroll.dispatch("scroll")
- touch(a.handle, "touchmove", [point(3, 10, 30)])
- expect(hook.callbacks.onDragStart).not.toHaveBeenCalled()
-
- touch(a.handle, "touchstart", [point(4, 10, 10)])
- touch(a.handle, "touchstart", [point(4, 10, 10), point(5, 12, 12)])
- expect(hook.callbacks.onCancel).toHaveBeenCalled()
-
- touch(a.handle, "touchstart", [point(40, 10, 10)])
- touch(a.handle, "touchmove", [point(40, 10, 20), point(41, 12, 22)])
-
- touch(a.handle, "touchstart", [point(6, 10, 10)])
- touch(a.handle, "touchmove", [point(7, 10, 30)])
- touch(a.handle, "touchstart", [point(8, 10, 10)])
- touch(a.handle, "touchcancel", [])
-
- const dragStartCount = hook.callbacks.onDragStart.mock.calls.length
- const longClickCount = a.handle.clickCount
- touch(a.handle, "touchstart", [point(9, 10, 10)])
- await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS - 1))
- expect(hook.callbacks.onDragStart).toHaveBeenCalledTimes(dragStartCount)
- expect(fakeDocument.body.children).toHaveLength(0)
- const context = a.handle.dispatch("contextmenu", testEvent("contextmenu"))
- expect(context.defaultPrevented).toBe(true)
- expect(context.propagationStopped).toBe(true)
- await act(async () => vi.advanceTimersByTime(1))
- expect(hook.callbacks.onDragStart).toHaveBeenCalledTimes(dragStartCount)
- expect(fakeDocument.body.children).toHaveLength(0)
- expect(fakeDocument.documentElement.style.userSelect).toBe("text")
- touch(a.handle, "touchend", [], [point(9, 10, 10)])
- expect(a.handle.clickCount).toBe(longClickCount + 1)
-
- touch(a.handle, "touchstart", [point(91, 10, 10)])
- await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS - 1))
- const preArmMove = touch(a.handle, "touchmove", [point(91, 17, 10)])
- expect(preArmMove.defaultPrevented).toBe(false)
- await act(async () => vi.advanceTimersByTime(1))
- const sevenPixelMove = touch(a.handle, "touchmove", [point(91, 24, 10)])
- expect(sevenPixelMove.defaultPrevented).toBe(false)
- expect(hook.callbacks.onDragStart).toHaveBeenCalledTimes(dragStartCount)
- expect(fakeDocument.body.children).toHaveLength(0)
- const eightPixelMove = touch(a.handle, "touchmove", [point(91, 25, 10)])
- expect(eightPixelMove.defaultPrevented).toBe(true)
- expect(hook.callbacks.onDragStart).toHaveBeenCalledTimes(dragStartCount + 1)
- expect(hook.callbacks.onDragStart).toHaveBeenLastCalledWith(a.entity)
- expect(fakeDocument.documentElement.style.userSelect).toBe("none")
- const floating = fakeDocument.body.children.at(-1)!
- expect(a.dragPreview.cloneCount).toBe(1)
- expect(floating.attributes.get("data-rail-floating-preview")).toBe("server")
- expect(floating.attributes.get("aria-hidden")).toBe("true")
- expect(floating.attributes.has("data-rail-drag-preview")).toBe(false)
- expect(floating.style.width).toBe("40px")
- expect(floating.style.height).toBe("40px")
- expect(floating.style.pointerEvents).toBe("none")
- expect(floating.style.transform).toBe("translate3d(5px, -10px, 0)")
- const dragMove = touch(a.handle, "touchmove", [point(91, 30, 50)])
- expect(dragMove.defaultPrevented).toBe(true)
- expect(floating.style.transform).toBe("translate3d(10px, 30px, 0)")
- const clickCount = a.handle.clickCount
- touch(a.handle, "touchend", [], [point(91, 30, 50)])
- expect(a.handle.clickCount).toBe(clickCount)
- expect(floating.removed).toBe(true)
- expect(fakeDocument.documentElement.style.userSelect).toBe("text")
- a.handle.click()
- expect(a.handle.lastClickEvent?.defaultPrevented).toBe(true)
- expect(a.handle.lastClickEvent?.propagationStopped).toBe(true)
-
- const triggerTouch = a.element.dispatch(
- "touchstart",
- testEvent("touchstart", { touches: [point(90, 10, 10)] }),
- )
- expect(triggerTouch.defaultPrevented).toBe(false)
- expect(triggerTouch.propagationStopped).toBe(true)
-
- hook.callbacks.canStart.mockReturnValueOnce(true)
- touch(a.handle, "touchstart", [point(10, 10, 10)])
- hook.callbacks.canStart.mockReturnValue(false)
- await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
- touch(a.handle, "touchmove", [point(10, 18, 10)])
- expect(hook.callbacks.onAnnounce).toHaveBeenCalledWith(
- "A server rail move is already being saved",
- )
- })
-
- it("does not arm touch drag when the source has no legal registered target", async () => {
- const hook = await renderHook({
- getState: () => ({
- serverOrder: ["a"],
- folderOrder: [],
- folders: {},
- expanded: [],
- }),
- })
- const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40))
-
- touch(a.handle, "touchstart", [point(1, 10, 10)])
- await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
- const move = touch(a.handle, "touchmove", [point(1, 30, 10)])
- const end = touch(a.handle, "touchend", [], [point(1, 30, 10)])
- expect(move.defaultPrevented).toBe(false)
- expect(end.defaultPrevented).toBe(false)
- expect(hook.callbacks.onDragStart).not.toHaveBeenCalled()
- expect(fakeDocument.body.children).toHaveLength(0)
-
- a.handle.click()
- expect(a.handle.clickCount).toBe(1)
- expect(a.handle.lastClickEvent?.defaultPrevented).toBe(false)
- })
-
- it("keeps a stationary hold when a prior scroll notification arrives after touchstart", async () => {
- const hook = await renderHook()
- const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40))
- const b = register(hook.current, { kind: "server", id: "b" }, rect(80, 120))
- hook.scroll.scrollTop = 349
- touch(a.handle, "touchstart", [point(1, 20, 10)])
- hook.scroll.dispatch("scroll")
- await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
- fakeDocument.points = [b.element]
- const move = touch(a.handle, "touchmove", [point(1, 20, 100)])
- expect(move.defaultPrevented).toBe(true)
- expect(hook.callbacks.onDragStart).toHaveBeenCalledWith(a.entity)
- expect(fakeDocument.body.children.filter((element) => !element.removed)).toHaveLength(1)
- touch(a.handle, "touchend", [], [point(1, 20, 100)])
- expect(hook.callbacks.onDrop).toHaveBeenCalled()
- })
-
- it.each(["scrollTop", "scrollLeft"] as const)("cancels a hold when %s changes after touchstart", async (offset) => {
- const hook = await renderHook()
- const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40))
- register(hook.current, { kind: "server", id: "b" }, rect(80, 120))
- hook.scroll[offset] = 349
- touch(a.handle, "touchstart", [point(1, 20, 10)])
- hook.scroll[offset] += 1
- hook.scroll.dispatch("scroll")
- await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
- const move = touch(a.handle, "touchmove", [point(1, 20, 100)])
- expect(move.defaultPrevented).toBe(false)
- expect(hook.callbacks.onDragStart).not.toHaveBeenCalled()
- expect(fakeDocument.body.children).toHaveLength(0)
- })
-
- it("drags by touch through every hit region and owns edge scroll only after hold", async () => {
- const hook = await renderHook()
- hook.scroll.bounds = rect(0, 100, 0, 56)
- hook.scroll.scrollTop = 20
- const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40))
- const b = register(hook.current, { kind: "server", id: "b" }, rect(80, 120))
- const f = register(hook.current, { kind: "folder", id: "f" }, rect(160, 200))
- const g = register(hook.current, { kind: "folder", id: "g" }, rect(240, 280))
-
- async function drag(
- source: typeof a,
- target: typeof a,
- identifier: number,
- startY: number,
- endY: number,
- includeChangedTouch = true,
- ) {
- touch(source.handle, "touchstart", [point(identifier, 20, startY)])
- await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
- expect(fakeDocument.body.children.filter((element) => !element.removed)).toHaveLength(0)
- fakeDocument.points = [target.element]
- const move = touch(source.handle, "touchmove", [point(identifier, 20, endY)])
- expect(move.defaultPrevented).toBe(true)
- const floating = fakeDocument.body.children.at(-1)!
- expect(floating.attributes.get("data-rail-floating-preview")).toBe(source.entity.kind)
- expect(floating.style.width).toBe("40px")
- expect(floating.style.height).toBe("40px")
- expect(floating.style.transform).toBe(`translate3d(0px, ${endY - 20}px, 0)`)
- touch(source.handle, "touchmove", [point(identifier, 20, endY)])
- flushAnimationFrame()
- touch(
- source.handle,
- "touchend",
- [],
- includeChangedTouch ? [point(identifier, 20, endY)] : [],
- )
- expect(floating.removed).toBe(true)
- }
-
- await drag(b, a, 1, 100, 5)
- await drag(a, b, 2, 10, 115, false)
-
- touch(a.handle, "touchstart", [point(3, 20, 10)])
- await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
- fakeDocument.points = [f.element]
- touch(a.handle, "touchmove", [point(3, 20, 180)])
- const context = a.handle.dispatch("contextmenu", testEvent("contextmenu"))
- expect(context.defaultPrevented).toBe(true)
- touch(a.handle, "touchend", [], [point(3, 20, 180)])
-
- await drag(g, f, 4, 260, 176)
- await drag(f, g, 5, 180, 264)
- expect(hook.callbacks.onDrop.mock.calls.map(([instruction]) => instruction.operation))
- .toEqual(expect.arrayContaining([
- "reorder-before",
- "reorder-after",
- "combine",
- ]))
- expect(hook.scroll.scrollTop).not.toBe(20)
- expect(fakeDocument.removeAllRanges).toHaveBeenCalled()
- expect(fakeDocument.documentElement.style.userSelect).toBe("text")
-
- touch(a.handle, "touchstart", [point(6, 20, 10)])
- await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
- fakeDocument.points = [a.element]
- touch(a.handle, "touchmove", [point(6, 20, 35)])
- touch(a.handle, "touchend", [], [])
- expect(hook.callbacks.onCancel).toHaveBeenCalled()
- })
-
- it("cancels when an active source leaves, but survives same-entity reconciliation", async () => {
- const hook = await renderHook()
- const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40))
- key(a.handle, " ")
- a.dispose()
- const replacement = register(hook.current, a.entity, rect(0, 40))
- await act(async () => Promise.resolve())
- expect(hook.callbacks.onCancel).not.toHaveBeenCalled()
- replacement.dispose()
- await act(async () => Promise.resolve())
- expect(hook.callbacks.onCancel).toHaveBeenCalledTimes(1)
- expect(adapters.cleanupTarget).toHaveBeenCalledTimes(2)
- expect(adapters.cleanupDraggable).toHaveBeenCalledTimes(2)
- })
-
- it("cleans armed touch state on cancellation and source unmount", async () => {
- const hook = await renderHook()
- const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40))
- register(hook.current, { kind: "server", id: "b" }, rect(80, 120))
-
- touch(a.handle, "touchstart", [point(1, 10, 10)])
- await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
- expect(hook.callbacks.onDragStart).not.toHaveBeenCalled()
- expect(fakeDocument.body.children).toHaveLength(0)
- touch(a.handle, "touchcancel", [])
- expect(hook.callbacks.onCancel).toHaveBeenCalledTimes(1)
-
- touch(a.handle, "touchstart", [point(2, 10, 10)])
- await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
- a.dispose()
- await act(async () => Promise.resolve())
- touch(a.handle, "touchmove", [point(2, 18, 10)])
- expect(hook.callbacks.onCancel).toHaveBeenCalledTimes(2)
- expect(hook.callbacks.onDragStart).not.toHaveBeenCalled()
- expect(fakeDocument.body.children).toHaveLength(0)
- })
-})
diff --git a/src/web/src/components/community/shell/use-server-rail-pdd.test.ts b/src/web/src/components/community/shell/use-server-rail-pdd.test.ts
deleted file mode 100644
index 13b0d5933..000000000
--- a/src/web/src/components/community/shell/use-server-rail-pdd.test.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-import { describe, expect, it } from "vitest"
-import { attachInstruction } from "@atlaskit/pragmatic-drag-and-drop-hitbox/list-item"
-import {
- railEntityHasAvailableTarget,
- railEntityFromData,
- railInstructionFromRecords,
- railTouchMoveIntent,
- SERVER_RAIL_TOUCH_DRAG_PX,
- SERVER_RAIL_TOUCH_DRIFT_PX,
- SERVER_RAIL_TOUCH_HOLD_MS,
-} from "./use-server-rail-pdd"
-
-describe("server rail PDD record adapter", () => {
- it("reads only typed rail entities", () => {
- expect(railEntityFromData({ railKind: "server", railId: "one" })).toEqual({
- kind: "server",
- id: "one",
- })
- expect(railEntityFromData({ railKind: "channel", railId: "one" })).toBeNull()
- })
-
- it("extracts one before/after/combine instruction from the foremost target", () => {
- const targetData = attachInstruction(
- { railKind: "folder", railId: "group" },
- {
- input: { clientX: 20, clientY: 20 } as any,
- element: {
- getBoundingClientRect: () => ({ top: 0, bottom: 40, height: 40 }),
- } as HTMLElement,
- axis: "vertical",
- operations: {
- "reorder-before": "not-available",
- "reorder-after": "not-available",
- combine: "available",
- },
- },
- )
- expect(railInstructionFromRecords(
- { railKind: "server", railId: "one" },
- [{ data: targetData }],
- )).toEqual({
- operation: "combine",
- source: { kind: "server", id: "one" },
- target: { kind: "folder", id: "group" },
- })
- })
-
- it("rejects self and missing targets", () => {
- expect(railInstructionFromRecords({ railKind: "server", railId: "one" }, [])).toBeNull()
- })
-
- it("requires the 650ms arm before the 8px drag threshold", () => {
- expect(SERVER_RAIL_TOUCH_HOLD_MS).toBe(650)
- expect(SERVER_RAIL_TOUCH_DRAG_PX).toBe(8)
- expect(SERVER_RAIL_TOUCH_DRIFT_PX).toBe(10)
- expect(railTouchMoveIntent({
- armed: false,
- dragging: false,
- distance: 10,
- touchCount: 1,
- })).toBe("wait")
- expect(railTouchMoveIntent({
- armed: false,
- dragging: false,
- distance: 10.1,
- touchCount: 1,
- })).toBe("scroll")
- expect(railTouchMoveIntent({
- armed: true,
- dragging: false,
- distance: 7,
- touchCount: 1,
- })).toBe("wait")
- expect(railTouchMoveIntent({
- armed: true,
- dragging: false,
- distance: 8,
- touchCount: 1,
- })).toBe("drag")
- expect(railTouchMoveIntent({
- armed: true,
- dragging: true,
- distance: 30,
- touchCount: 1,
- })).toBe("drag")
- expect(railTouchMoveIntent({
- armed: true,
- dragging: true,
- distance: 30,
- touchCount: 2,
- })).toBe("cancel")
- })
-
- it("arms touch only when the source has a legal registered target", () => {
- expect(railEntityHasAvailableTarget({
- serverOrder: ["a"],
- folderOrder: [],
- folders: {},
- expanded: [],
- }, { kind: "server", id: "a" }, [
- { kind: "server", id: "a" },
- ])).toBe(false)
-
- expect(railEntityHasAvailableTarget({
- serverOrder: ["a", "b"],
- folderOrder: [],
- folders: {},
- expanded: [],
- }, { kind: "server", id: "a" }, [
- { kind: "server", id: "a" },
- { kind: "server", id: "b" },
- ])).toBe(true)
-
- expect(railEntityHasAvailableTarget({
- serverOrder: ["a", "b"],
- folderOrder: ["f"],
- folders: { f: ["a"] },
- expanded: ["f"],
- }, { kind: "server", id: "a" }, [
- { kind: "server", id: "a" },
- { kind: "server", id: "b" },
- ])).toBe(true)
-
- expect(railEntityHasAvailableTarget({
- serverOrder: ["a"],
- folderOrder: ["f"],
- folders: { f: ["a"] },
- expanded: ["f"],
- }, { kind: "folder", id: "f" }, [
- { kind: "folder", id: "f" },
- { kind: "server", id: "a" },
- ])).toBe(false)
- })
-})
diff --git a/src/web/src/components/community/shell/use-server-rail-pdd.ts b/src/web/src/components/community/shell/use-server-rail-pdd.ts
deleted file mode 100644
index 99ab8006e..000000000
--- a/src/web/src/components/community/shell/use-server-rail-pdd.ts
+++ /dev/null
@@ -1,719 +0,0 @@
-"use client"
-
-import { useCallback, useEffect, useRef, type RefObject } from "react"
-import { autoScrollForElements } from "@atlaskit/pragmatic-drag-and-drop-auto-scroll/element"
-import {
- attachInstruction,
- extractInstruction,
- type Availability,
-} from "@atlaskit/pragmatic-drag-and-drop-hitbox/list-item"
-import {
- draggable,
- dropTargetForElements,
- monitorForElements,
-} from "@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter"
-import {
- railInstructionIsAvailable,
- railOperationAvailability,
- type RailEntity,
- type RailInstruction,
- type RailOperation,
- type RailState,
-} from "@/lib/community/server-rail-model"
-
-type RailData = Record<string | symbol, unknown>
-
-export const SERVER_RAIL_TOUCH_HOLD_MS = 650
-export const SERVER_RAIL_TOUCH_DRAG_PX = 8
-export const SERVER_RAIL_TOUCH_DRIFT_PX = 10
-const TOUCH_DRAG_PREVIEW_SELECTOR = "[data-rail-drag-preview]"
-
-type TouchDragPreview = {
- element: HTMLElement
- width: number
- height: number
-}
-
-function positionTouchDragPreview(
- preview: TouchDragPreview,
- clientX: number,
- clientY: number,
-) {
- preview.element.style.transform = `translate3d(${clientX - preview.width / 2}px, ${clientY - preview.height / 2}px, 0)`
-}
-
-function createTouchDragPreview(
- dragHandle: HTMLElement,
- entity: RailEntity,
- clientX: number,
- clientY: number,
-): TouchDragPreview | null {
- const source = dragHandle.querySelector<HTMLElement>(TOUCH_DRAG_PREVIEW_SELECTOR)
- if (!source) return null
- const rect = source.getBoundingClientRect()
- const element = source.cloneNode(true) as HTMLElement
- element.removeAttribute("data-rail-drag-preview")
- element.setAttribute("data-rail-floating-preview", entity.kind)
- element.setAttribute("aria-hidden", "true")
- Object.assign(element.style, {
- position: "fixed",
- left: "0",
- top: "0",
- zIndex: "100",
- width: `${rect.width}px`,
- height: `${rect.height}px`,
- margin: "0",
- pointerEvents: "none",
- transition: "none",
- willChange: "transform",
- })
- const preview = { element, width: rect.width, height: rect.height }
- positionTouchDragPreview(preview, clientX, clientY)
- document.body.appendChild(element)
- return preview
-}
-
-export function railTouchMoveIntent({
- armed,
- dragging,
- distance,
- touchCount,
-}: {
- armed: boolean
- dragging: boolean
- distance: number
- touchCount: number
-}): "wait" | "scroll" | "drag" | "cancel" {
- if (touchCount !== 1) return "cancel"
- if (dragging) return "drag"
- if (armed) return distance >= SERVER_RAIL_TOUCH_DRAG_PX ? "drag" : "wait"
- return distance > SERVER_RAIL_TOUCH_DRIFT_PX ? "scroll" : "wait"
-}
-
-function sameEntity(left: RailEntity | null, right: RailEntity | null): boolean {
- return left?.kind === right?.kind && left?.id === right?.id
-}
-
-export function railEntityHasAvailableTarget(
- state: RailState,
- source: RailEntity,
- targets: readonly RailEntity[],
-): boolean {
- return targets.some((target) => {
- if (sameEntity(source, target)) return false
- const availability = railOperationAvailability(state, source, target)
- return availability["reorder-before"] || availability["reorder-after"] || availability.combine
- })
-}
-
-export function railEntityFromData(data: RailData): RailEntity | null {
- const kind = data.railKind
- const id = data.railId
- if ((kind !== "server" && kind !== "folder") || typeof id !== "string") return null
- return { kind, id }
-}
-
-export function railInstructionFromRecords(
- sourceData: RailData,
- targets: readonly { data: RailData }[],
-): RailInstruction | null {
- const source = railEntityFromData(sourceData)
- const targetRecord = targets[0]
- if (!source || !targetRecord) return null
- const target = railEntityFromData(targetRecord.data)
- const instruction = extractInstruction(targetRecord.data)
- if (!target || !instruction || instruction.blocked || sameEntity(source, target)) return null
- return { operation: instruction.operation, source, target }
-}
-
-function pddAvailability(state: RailState, source: RailEntity | null, target: RailEntity): {
- "reorder-before": Availability
- "reorder-after": Availability
- combine: Availability
-} {
- const available = railOperationAvailability(state, source, target)
- return {
- "reorder-before": available["reorder-before"] ? "available" : "not-available",
- "reorder-after": available["reorder-after"] ? "available" : "not-available",
- combine: available.combine ? "available" : "not-available",
- }
-}
-
-function sameInstruction(left: RailInstruction | null, right: RailInstruction | null): boolean {
- return left?.operation === right?.operation
- && sameEntity(left?.source ?? null, right?.source ?? null)
- && sameEntity(left?.target ?? null, right?.target ?? null)
-}
-
-export function useServerRailPdd({
- scrollRef,
- getState,
- canStart,
- getEntityLabel,
- onDragStart,
- onPreview,
- onDrop,
- onCancel,
- onHoverExpand,
- onAnnounce,
-}: {
- scrollRef: RefObject<HTMLElement | null>
- getState: () => RailState
- canStart: () => boolean
- getEntityLabel: (entity: RailEntity) => string
- onDragStart: (source: RailEntity) => void
- onPreview: (instruction: RailInstruction | null) => void
- onDrop: (instruction: RailInstruction) => void
- onCancel: () => void
- onHoverExpand: (folderId: string) => void
- onAnnounce: (message: string) => void
-}) {
- const handlersRef = useRef({
- getState,
- canStart,
- getEntityLabel,
- onDragStart,
- onPreview,
- onDrop,
- onCancel,
- onHoverExpand,
- onAnnounce,
- })
- useEffect(() => {
- handlersRef.current = {
- getState,
- canStart,
- getEntityLabel,
- onDragStart,
- onPreview,
- onDrop,
- onCancel,
- onHoverExpand,
- onAnnounce,
- }
- }, [canStart, getEntityLabel, getState, onAnnounce, onCancel, onDragStart, onDrop, onHoverExpand, onPreview])
- const previewRef = useRef<RailInstruction | null>(null)
- const hoverTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
- const hoverFolderRef = useRef<string | null>(null)
- const itemsRef = useRef(new Map<HTMLElement, { entity: RailEntity; handle: HTMLElement }>())
- const activeRef = useRef<{ sensor: "native" | "touch" | "keyboard"; source: RailEntity } | null>(null)
- const suppressClickUntilRef = useRef(0)
- const selectionStyleRef = useRef<string | null>(null)
- const touchRef = useRef<{
- entity: RailEntity
- identifier: number
- startX: number
- startY: number
- startScrollTop: number
- startScrollLeft: number
- clientX: number
- clientY: number
- armX: number
- armY: number
- armed: boolean
- dragging: boolean
- timer: ReturnType<typeof setTimeout> | null
- frame: number | null
- preview: TouchDragPreview | null
- } | null>(null)
-
- const clearHover = useCallback(() => {
- if (hoverTimerRef.current) clearTimeout(hoverTimerRef.current)
- hoverTimerRef.current = null
- hoverFolderRef.current = null
- }, [])
-
- const updatePreview = useCallback((instruction: RailInstruction | null) => {
- if (sameInstruction(previewRef.current, instruction)) return
- previewRef.current = instruction
- handlersRef.current.onPreview(instruction)
- const folderId = instruction?.operation === "combine" && instruction.target.kind === "folder"
- ? instruction.target.id
- : null
- if (!folderId) {
- clearHover()
- return
- }
- if (hoverFolderRef.current === folderId && hoverTimerRef.current) return
- clearHover()
- hoverFolderRef.current = folderId
- hoverTimerRef.current = setTimeout(() => {
- handlersRef.current.onHoverExpand(folderId)
- hoverTimerRef.current = null
- }, 500)
- }, [clearHover])
-
- const restoreSelection = useCallback(() => {
- if (selectionStyleRef.current === null) return
- document.documentElement.style.userSelect = selectionStyleRef.current
- selectionStyleRef.current = null
- }, [])
-
- const clearTouch = useCallback(() => {
- const touch = touchRef.current
- if (touch?.timer) clearTimeout(touch.timer)
- if (touch?.frame !== null && touch?.frame !== undefined) cancelAnimationFrame(touch.frame)
- touch?.preview?.element.remove()
- touchRef.current = null
- restoreSelection()
- }, [restoreSelection])
-
- const cancelActive = useCallback((announcement?: string) => {
- if (!activeRef.current && !touchRef.current) return
- activeRef.current = null
- clearTouch()
- clearHover()
- updatePreview(null)
- handlersRef.current.onCancel()
- if (announcement) handlersRef.current.onAnnounce(announcement)
- }, [clearHover, clearTouch, updatePreview])
-
- const begin = useCallback((source: RailEntity, sensor: "native" | "touch" | "keyboard") => {
- if (activeRef.current || !handlersRef.current.canStart()) {
- handlersRef.current.onAnnounce("A server rail move is already being saved")
- return false
- }
- activeRef.current = { sensor, source }
- handlersRef.current.onDragStart(source)
- if (sensor === "keyboard") {
- handlersRef.current.onAnnounce(
- `${handlersRef.current.getEntityLabel(source)} picked up. Use arrow keys to choose a position, Space or Enter to drop, and Escape to cancel.`,
- )
- }
- return true
- }, [])
-
- const describePreview = useCallback((instruction: RailInstruction) => {
- const source = handlersRef.current.getEntityLabel(instruction.source)
- const target = handlersRef.current.getEntityLabel(instruction.target)
- if (instruction.operation === "combine") return `${source} will move into ${target}`
- return `${source} will move ${instruction.operation === "reorder-before" ? "before" : "after"} ${target}`
- }, [])
-
- const setPreview = useCallback((instruction: RailInstruction | null, announcePreview = false) => {
- const valid = instruction && railInstructionIsAvailable(
- handlersRef.current.getState(),
- instruction,
- ) ? instruction : null
- const changed = !sameInstruction(previewRef.current, valid)
- updatePreview(valid)
- if (changed && valid && announcePreview) {
- handlersRef.current.onAnnounce(describePreview(valid))
- }
- }, [describePreview, updatePreview])
-
- const finishDrop = useCallback((instruction: RailInstruction | null) => {
- const valid = instruction && railInstructionIsAvailable(
- handlersRef.current.getState(),
- instruction,
- ) ? instruction : null
- activeRef.current = null
- clearTouch()
- clearHover()
- updatePreview(null)
- if (valid) handlersRef.current.onDrop(valid)
- else handlersRef.current.onCancel()
- }, [clearHover, clearTouch, updatePreview])
-
- const itemAtPoint = useCallback((source: RailEntity, clientX: number, clientY: number) => {
- const targetElement = document.elementsFromPoint(clientX, clientY)
- .find((element) => itemsRef.current.has(element as HTMLElement)) as HTMLElement | undefined
- if (!targetElement) return null
- const target = itemsRef.current.get(targetElement)!.entity
- if (sameEntity(source, target)) return null
- const availability = railOperationAvailability(handlersRef.current.getState(), source, target)
- const rect = targetElement.getBoundingClientRect()
- const ratio = rect.height > 0 ? (clientY - rect.top) / rect.height : 0.5
- let operation: RailOperation | null = null
- if (ratio < 0.25 && availability["reorder-before"]) operation = "reorder-before"
- else if (ratio > 0.75 && availability["reorder-after"]) operation = "reorder-after"
- else if (availability.combine) operation = "combine"
- else if (ratio < 0.5 && availability["reorder-before"]) operation = "reorder-before"
- else if (availability["reorder-after"]) operation = "reorder-after"
- return operation ? { operation, source, target } satisfies RailInstruction : null
- }, [])
-
- const runTouchFrame = useCallback(function frame() {
- const touch = touchRef.current
- const scroll = scrollRef.current
- if (!touch?.dragging || !scroll) return
- const rect = scroll.getBoundingClientRect()
- const edge = 32
- let delta = 0
- if (touch.clientY < rect.top + edge) {
- delta = -Math.ceil(12 * (1 - Math.max(0, touch.clientY - rect.top) / edge))
- } else if (touch.clientY > rect.bottom - edge) {
- delta = Math.ceil(12 * (1 - Math.max(0, rect.bottom - touch.clientY) / edge))
- }
- if (delta !== 0) {
- scroll.scrollTop += delta
- setPreview(itemAtPoint(touch.entity, touch.clientX, touch.clientY))
- }
- touch.frame = requestAnimationFrame(frame)
- }, [itemAtPoint, scrollRef, setPreview])
-
- const orderedItems = useCallback(() => [...itemsRef.current.values()].sort((left, right) => {
- const leftRect = left.handle.getBoundingClientRect()
- const rightRect = right.handle.getBoundingClientRect()
- return leftRect.top - rightRect.top || leftRect.left - rightRect.left
- }), [])
-
- const keyboardInstruction = useCallback((source: RailEntity, direction: -1 | 1) => {
- const items = orderedItems()
- const currentTarget = previewRef.current?.target ?? source
- const currentIndex = items.findIndex(({ entity }) => sameEntity(entity, currentTarget))
- for (
- let index = currentIndex + direction;
- index >= 0 && index < items.length;
- index += direction
- ) {
- const target = items[index]!.entity
- if (sameEntity(source, target)) continue
- const availability = railOperationAvailability(handlersRef.current.getState(), source, target)
- const operation = target.kind === "folder" && availability.combine
- ? "combine"
- : direction < 0 && availability["reorder-before"]
- ? "reorder-before"
- : direction > 0 && availability["reorder-after"]
- ? "reorder-after"
- : availability.combine
- ? "combine"
- : null
- if (operation) return { operation, source, target } satisfies RailInstruction
- }
- return null
- }, [orderedItems])
-
- const handleKeyboardCommand = useCallback((event: KeyboardEvent, source: RailEntity) => {
- if (event.key === "Escape") {
- event.preventDefault()
- cancelActive(`${handlersRef.current.getEntityLabel(source)} move cancelled`)
- return true
- }
- if (event.key === " " || event.key === "Enter") {
- event.preventDefault()
- finishDrop(previewRef.current)
- return true
- }
- if (event.key === "ArrowUp" || event.key === "ArrowDown") {
- event.preventDefault()
- setPreview(keyboardInstruction(source, event.key === "ArrowUp" ? -1 : 1), true)
- return true
- }
- const current = previewRef.current
- if (!current || current.target.kind !== "server" || source.kind !== "server") return false
- const availability = railOperationAvailability(
- handlersRef.current.getState(),
- source,
- current.target,
- )
- if (event.key === "ArrowRight" && availability.combine) {
- event.preventDefault()
- setPreview({ ...current, operation: "combine" }, true)
- return true
- }
- if (event.key !== "ArrowLeft") return false
- const operation = availability["reorder-before"]
- ? "reorder-before"
- : availability["reorder-after"]
- ? "reorder-after"
- : null
- if (!operation) return false
- event.preventDefault()
- setPreview({ ...current, operation }, true)
- return true
- }, [cancelActive, finishDrop, keyboardInstruction, setPreview])
-
- const registerItem = useCallback((
- entity: RailEntity,
- element: HTMLElement,
- dragHandle: HTMLElement,
- ) => {
- itemsRef.current.set(element, { entity, handle: dragHandle })
- if (
- activeRef.current?.sensor === "keyboard"
- && sameEntity(activeRef.current.source, entity)
- ) dragHandle.focus({ preventScroll: true })
- const cleanupDraggable = draggable({
- element,
- dragHandle,
- canDrag: () => !touchRef.current && !activeRef.current && handlersRef.current.canStart(),
- getInitialData: () => ({ railKind: entity.kind, railId: entity.id }),
- })
- const cleanupTarget = dropTargetForElements({
- element,
- canDrop: ({ source }) => !sameEntity(railEntityFromData(source.data), entity),
- getIsSticky: () => false,
- getData: ({ input, element: targetElement, source }) => attachInstruction(
- { railKind: entity.kind, railId: entity.id },
- {
- input,
- element: targetElement,
- axis: "vertical",
- operations: pddAvailability(
- handlersRef.current.getState(),
- railEntityFromData(source.data),
- entity,
- ),
- },
- ),
- })
-
- const suppressTouchMenu = (event: TouchEvent) => {
- // Base UI owns a separate 500 ms touch timer on ContextMenuTrigger.
- // Keep the event native (and therefore scrollable), but do not let it
- // reach that trigger: the rail owns its 650 ms touch intent timer.
- event.stopPropagation()
- }
- const onTouchStart = (event: TouchEvent) => {
- if (event.touches.length !== 1) {
- if (touchRef.current || activeRef.current?.sensor === "touch") cancelActive()
- return
- }
- if (touchRef.current || activeRef.current) return
- suppressClickUntilRef.current = 0
- if (!handlersRef.current.canStart()) return
- const targets = [...itemsRef.current.values()].map((item) => item.entity)
- if (!railEntityHasAvailableTarget(handlersRef.current.getState(), entity, targets)) return
- const touch = event.touches[0]!
- const pending = {
- entity,
- identifier: touch.identifier,
- startX: touch.clientX,
- startY: touch.clientY,
- startScrollTop: scrollRef.current?.scrollTop ?? 0,
- startScrollLeft: scrollRef.current?.scrollLeft ?? 0,
- clientX: touch.clientX,
- clientY: touch.clientY,
- armX: touch.clientX,
- armY: touch.clientY,
- armed: false,
- dragging: false,
- timer: null as ReturnType<typeof setTimeout> | null,
- frame: null as number | null,
- preview: null as TouchDragPreview | null,
- }
- pending.timer = setTimeout(() => {
- if (touchRef.current !== pending) return
- pending.timer = null
- pending.armX = pending.clientX
- pending.armY = pending.clientY
- pending.armed = true
- }, SERVER_RAIL_TOUCH_HOLD_MS)
- touchRef.current = pending
- }
- const onTouchMove = (event: TouchEvent) => {
- const pending = touchRef.current
- if (!pending || !sameEntity(pending.entity, entity)) return
- if (event.touches.length !== 1) {
- cancelActive()
- return
- }
- const touch = [...event.touches].find((candidate) => candidate.identifier === pending.identifier)
- if (!touch) {
- cancelActive()
- return
- }
- pending.clientX = touch.clientX
- pending.clientY = touch.clientY
- if (pending.preview) {
- positionTouchDragPreview(pending.preview, touch.clientX, touch.clientY)
- }
- const originX = pending.armed ? pending.armX : pending.startX
- const originY = pending.armed ? pending.armY : pending.startY
- const exactDistance = Math.hypot(touch.clientX - originX, touch.clientY - originY)
- const exactIntent = railTouchMoveIntent({
- armed: pending.armed,
- dragging: pending.dragging,
- distance: exactDistance,
- touchCount: event.touches.length,
- })
- if (exactIntent === "scroll") {
- clearTouch()
- return
- }
- if (exactIntent === "wait") return
- if (!pending.dragging) {
- const targets = [...itemsRef.current.values()].map((item) => item.entity)
- if (
- !railEntityHasAvailableTarget(handlersRef.current.getState(), entity, targets)
- || !begin(entity, "touch")
- ) {
- clearTouch()
- return
- }
- pending.dragging = true
- pending.preview = createTouchDragPreview(
- dragHandle,
- entity,
- pending.clientX,
- pending.clientY,
- )
- selectionStyleRef.current = document.documentElement.style.userSelect
- document.documentElement.style.userSelect = "none"
- document.getSelection()?.removeAllRanges()
- pending.frame = requestAnimationFrame(runTouchFrame)
- }
- event.preventDefault()
- setPreview(itemAtPoint(entity, touch.clientX, touch.clientY))
- }
- const onTouchEnd = (event: TouchEvent) => {
- const pending = touchRef.current
- if (!pending || !sameEntity(pending.entity, entity)) return
- const touch = [...event.changedTouches].find((candidate) => candidate.identifier === pending.identifier)
- if (pending.dragging) {
- const clientX = touch?.clientX ?? pending.clientX
- const clientY = touch?.clientY ?? pending.clientY
- setPreview(itemAtPoint(entity, clientX, clientY))
- suppressClickUntilRef.current = Date.now() + 800
- finishDrop(itemAtPoint(entity, clientX, clientY))
- } else {
- event.preventDefault()
- clearTouch()
- dragHandle.click()
- }
- }
- const onTouchCancel = () => cancelActive()
- const onContextMenu = (event: MouseEvent) => {
- const pending = touchRef.current
- const pendingMatches = !!pending && sameEntity(pending.entity, entity)
- const draggingMatches = activeRef.current?.sensor === "touch"
- && sameEntity(activeRef.current.source, entity)
- const clickSuppressed = Date.now() < suppressClickUntilRef.current
- if (
- pendingMatches
- || draggingMatches
- || clickSuppressed
- ) {
- event.preventDefault()
- event.stopPropagation()
- if (draggingMatches || clickSuppressed) {
- suppressClickUntilRef.current = Date.now() + 800
- }
- }
- }
- const onClickCapture = (event: MouseEvent) => {
- if (Date.now() >= suppressClickUntilRef.current) return
- event.preventDefault()
- event.stopPropagation()
- }
- const onKeyDown = (event: KeyboardEvent) => {
- const active = activeRef.current
- if (!active) {
- if (event.key !== " " || !begin(entity, "keyboard")) return
- event.preventDefault()
- requestAnimationFrame(() => {
- const registered = [...itemsRef.current.values()]
- .find((item) => item.handle.isConnected && sameEntity(item.entity, entity))
- registered?.handle.focus({ preventScroll: true })
- })
- return
- }
- if (active.sensor !== "keyboard" || !sameEntity(active.source, entity)) return
- handleKeyboardCommand(event, entity)
- }
- element.addEventListener("touchstart", suppressTouchMenu, { passive: true })
- dragHandle.addEventListener("touchstart", suppressTouchMenu, { passive: true })
- dragHandle.addEventListener("touchstart", onTouchStart, { passive: true })
- dragHandle.addEventListener("touchmove", onTouchMove, { passive: false })
- dragHandle.addEventListener("touchend", onTouchEnd, { passive: false })
- dragHandle.addEventListener("touchcancel", onTouchCancel, { passive: true })
- dragHandle.addEventListener("contextmenu", onContextMenu)
- dragHandle.addEventListener("click", onClickCapture, true)
- dragHandle.addEventListener("keydown", onKeyDown)
- return () => {
- element.removeEventListener("touchstart", suppressTouchMenu)
- dragHandle.removeEventListener("touchstart", suppressTouchMenu)
- dragHandle.removeEventListener("touchstart", onTouchStart)
- dragHandle.removeEventListener("touchmove", onTouchMove)
- dragHandle.removeEventListener("touchend", onTouchEnd)
- dragHandle.removeEventListener("touchcancel", onTouchCancel)
- dragHandle.removeEventListener("contextmenu", onContextMenu)
- dragHandle.removeEventListener("click", onClickCapture, true)
- dragHandle.removeEventListener("keydown", onKeyDown)
- itemsRef.current.delete(element)
- // Reconciliation may replace a registered element without removing its
- // entity, so defer cancellation until a same-entity registration can land.
- queueMicrotask(() => {
- const stillRegistered = [...itemsRef.current.values()]
- .some((item) => sameEntity(item.entity, entity))
- if (!stillRegistered && (
- sameEntity(touchRef.current?.entity ?? null, entity)
- || sameEntity(activeRef.current?.source ?? null, entity)
- )) cancelActive()
- })
- cleanupTarget()
- cleanupDraggable()
- }
- }, [begin, cancelActive, clearTouch, finishDrop, handleKeyboardCommand, itemAtPoint, runTouchFrame, scrollRef, setPreview])
-
- useEffect(() => monitorForElements({
- canMonitor: ({ source }) => railEntityFromData(source.data) !== null,
- onDragStart: ({ source }) => {
- const entity = railEntityFromData(source.data)
- if (entity) begin(entity, "native")
- },
- onDrag: ({ source, location }) => {
- if (activeRef.current?.sensor !== "native") return
- setPreview(railInstructionFromRecords(source.data, location.current.dropTargets))
- },
- onDropTargetChange: ({ source, location }) => {
- if (activeRef.current?.sensor !== "native") return
- setPreview(railInstructionFromRecords(source.data, location.current.dropTargets))
- },
- onDrop: ({ source, location }) => {
- if (activeRef.current?.sensor !== "native") return
- const instruction = railInstructionFromRecords(source.data, location.current.dropTargets)
- finishDrop(instruction)
- },
- }), [begin, finishDrop, setPreview])
-
- useEffect(() => {
- const element = scrollRef.current
- if (!element) return
- const cancelPendingTouchForNativeScroll = () => {
- const pending = touchRef.current
- if (pending && !pending.dragging && (
- element.scrollTop !== pending.startScrollTop
- || element.scrollLeft !== pending.startScrollLeft
- )) clearTouch()
- }
- element.addEventListener("scroll", cancelPendingTouchForNativeScroll, { passive: true })
- const cleanupAutoScroll = autoScrollForElements({
- element,
- getAllowedAxis: () => "vertical",
- getConfiguration: () => ({ maxScrollSpeed: "fast" }),
- })
- return () => {
- element.removeEventListener("scroll", cancelPendingTouchForNativeScroll)
- cleanupAutoScroll()
- }
- }, [clearTouch, scrollRef])
-
- useEffect(() => {
- const cancel = () => cancelActive()
- const cancelWhenHidden = () => {
- if (document.visibilityState === "hidden") cancelActive()
- }
- const handleActiveKeyboardDrag = (event: KeyboardEvent) => {
- const active = activeRef.current
- if (active?.sensor !== "keyboard") return
- if (handleKeyboardCommand(event, active.source)) event.stopPropagation()
- }
- window.addEventListener("blur", cancel)
- document.addEventListener("visibilitychange", cancelWhenHidden)
- document.addEventListener("keydown", handleActiveKeyboardDrag, true)
- return () => {
- window.removeEventListener("blur", cancel)
- document.removeEventListener("visibilitychange", cancelWhenHidden)
- document.removeEventListener("keydown", handleActiveKeyboardDrag, true)
- cancelActive()
- }
- }, [cancelActive, handleKeyboardCommand])
-
- useEffect(() => {
- if (!canStart()) cancelActive()
- }, [canStart, cancelActive])
-
- return { registerItem }
-}
diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx b/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
index 973e07f21..595640af7 100644
--- a/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
+++ b/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
@@ -6,6 +6,7 @@ import { beforeEach, afterEach, describe, expect, it, vi } from "vitest"
import { act, fireEvent, render, waitFor, within } from "@/test/react-dom-harness"
import { QueryProvider } from "@/app/c/QueryProvider"
import { clearAllPersistedCaches } from "@/lib/query-persister"
+import { captureCommunityLiveSnapshotToken, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { useShellRailController } from "./use-shell-rail-controller"
import { useCommunityNavigationController, type CommunityNavigationController } from "./use-community-navigation-controller"
@@ -63,7 +64,7 @@ function Probe({ sidebar = false }: { sidebar?: boolean }) {
return sidebar ? <CommunityRouteContext value={{ breakpoint: "desktop", frame, navigation: currentNavigation, ownerDeleteRouteScope }}><ServerRail {...current.railProps} bottomInset={60} /><ServerSidebarSlot serverId={serverId} /></CommunityRouteContext> : null
}
function Root({ visible = true, sidebar = false }: { visible?: boolean; sidebar?: boolean }) { return <QueryProvider userId="A">{visible && <Probe sidebar={sidebar} />}</QueryProvider> }
-async function mount(sidebar = false) {
+async function mount(sidebar = false, extraServer = false) {
let resolve!: (value: unknown) => void, reject!: (error: Error) => void
const held = new Promise<unknown>((done, fail) => { resolve = done; reject = fail })
const seen = new Set<string>()
@@ -72,10 +73,10 @@ async function mount(sidebar = false) {
if (options.method === "POST") return held
if (seen.has(path)) return new Promise((_, fail) => options.signal?.addEventListener("abort", () => fail(new DOMException("cancelled", "AbortError")), { once: true }))
seen.add(path)
- return Promise.resolve(path.endsWith("server-folders") ? { folders: [] } : { servers: [{ id: "s1", name: "One", discriminator: "0001", icon: null, ownerId: sidebar ? "other-owner" : "A", role: sidebar ? "member" : "owner" }, ...(sidebar ? [{ id: "s2", name: "Two", discriminator: "0002", icon: null, ownerId: "other-owner", role: "member" }] : [])] })
+ return Promise.resolve(path.endsWith("server-folders") ? { folders: [] } : { servers: [{ id: "s1", name: "One", discriminator: "0001", icon: null, ownerId: sidebar ? "other-owner" : "A", role: sidebar ? "member" : "owner" }, ...((sidebar || extraServer) ? [{ id: "s2", name: "Two", discriminator: "0002", icon: null, ownerId: "other-owner", role: "member" }] : []), ...(extraServer ? [{ id: "s3", name: "Three", discriminator: "0003", icon: null, ownerId: "other-owner", role: "member" }] : [])] })
})
const view = render(<Root sidebar={sidebar} />)
- await waitFor(() => expect(controller.railProps.servers).toHaveLength(sidebar ? 2 : 1))
+ await waitFor(() => expect(controller.railProps.servers).toHaveLength(extraServer ? 3 : sidebar ? 2 : 1))
return { view, resolve, reject, original: client }
}
beforeEach(async () => {
@@ -145,6 +146,26 @@ describe("actual native Rail controller continuation", () => {
await act(async () => resolve(undefined))
await waitFor(() => expect(ui.replace).toHaveBeenCalledWith("/c/me"))
})
+ it("leaves into canonical folder order while server/folder refresh stays held", async () => {
+ const { resolve, original } = await mount(false, true)
+ const registry = getCommunityDbRegistry(original)!
+ act(() => {
+ publishCommunityLiveSnapshot(original, {
+ snapshot: { kind: "folders", data: {
+ folders: [{ id: "f", name: "Group", servers: [{ id: "s3", name: "Three", initial: "T" }, { id: "s2", name: "Two", initial: "T" }] }],
+ topOrder: [{ kind: "folder", id: "f" }, { kind: "server", id: "s1" }],
+ } },
+ proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(original), signal: undefined },
+ })
+ })
+ await waitFor(() => expect(controller.railProps.servers.map((server) => server.id)).toEqual(["s3", "s2", "s1"]))
+ act(() => controller.railProps.onLeaveServer!("s1"))
+ await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
+ await act(async () => resolve(undefined))
+ await waitFor(() => expect(ui.replace).toHaveBeenCalledWith("/c/channels/s3"))
+ expect(registry.collections.servers.get("s2")?.position).toBe(1)
+ expect(registry.collections.servers.get("s3")?.position).toBe(2)
+ })
it("confirmed leave does not redirect a newer navigation intent", async () => {
const { view, resolve } = await mount()
act(() => controller.railProps.onLeaveServer!("s1"))
diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.ts b/src/web/src/components/community/shell/use-shell-rail-controller.ts
index a99457722..0d4533428 100644
--- a/src/web/src/components/community/shell/use-shell-rail-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-rail-controller.ts
@@ -1,5 +1,7 @@
"use client"
+import { readCommunityServerRailServers } from "@/lib/community-db/server-rail"
+
import { useCallback, useMemo, useLayoutEffect } from "react"
import { toast } from "sonner"
import { toastApiError } from "@/lib/api/client"
@@ -149,8 +151,7 @@ export function useShellRailController({
if (currentNavigation && communityServerId(currentNavigation.navigationPending
? currentNavigation.pendingHref ?? ""
: currentNavigation.publishedHref) === id) {
- const allowed = new Set([...communityDb!.collections.serverMemberships.values()].filter((row) => row.viewer && row.userId === communityDb!.accountId).map((row) => row.serverId))
- const remaining = [...communityDb!.collections.servers.values()].filter((row) => allowed.has(row.id)).sort((a, b) => (a.position ?? 0) - (b.position ?? 0))
+ const remaining = readCommunityServerRailServers(communityDb!)
currentNavigation.replace(pickPostEjectDestination(remaining, id))
}
},
@@ -197,6 +198,8 @@ export function useShellRailController({
homeHref,
serverHrefs,
folders,
+ topOrder: foldersQuery.topOrder,
+ navigationKey: navigation.navigationPending ? navigation.pendingHref ?? navigation.publishedHref : navigation.publishedHref,
activeServerId: projectedActiveServerId,
serversLoading: serversQuery.isPending && servers.length === 0,
view: projectedView,
diff --git a/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts b/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts
index 26fcf5539..425cf1f2f 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts
@@ -974,18 +974,35 @@ describe("membership metadata and access lifetime", () => {
expect(capturedQueryClient.getQueryData(key)).toMatchObject({ pages: [{ messages: [] }] })
})
- it.each([403, 404, 500])("keeps unknown legacy content retired when the access recheck returns %s", async (status) => {
+ it("restores a newly mentioned forum participant and refreshes the mounted sidebar after legacy metadata recovery", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const api = getCommunityApiFetchMock()
+ const base = communityKeys.forumSidebarThreads("server")
+ capturedQueryClient.setQueryData(base, { threads: [], serverNow: "2026-10-01T00:00:00Z", verifiedEpoch: 0, serverClockOffsetMs: 0 })
+ const unread = getAccountUnreadProjection(capturedQueryClient, "u_me")
+ unread.recordArrival({ channelId: "child", serverId: "server", railChannelId: "forum", seq: 1, isMention: true })
+ api.mockResolvedValue(conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 1, creatorId: "peer", createdAt: "2026-10-01T00:00:00Z", lastMessageAt: "2026-10-01T00:00:01Z", id: "child", serverId: "server", type: "thread", parentChannelId: "forum", parentMessageId: "opener", name: "New post", archived: false }, "u_me"))
+ capturedOnMessage!({ type: "community:channel.member_add", channelId: "child", serverId: "server", userId: "u_me" })
+ await vi.waitFor(() => expect(capturedQueryClient.getQueryData(entryKey("server", "child"))).toMatchObject({ channelId: "child", proof: expect.any(Object) }))
+ await vi.waitFor(() => expect(hasCanonicalChannelNotify("child", "u_me")).toBe(true))
+ await vi.waitFor(() => expect(capturedQueryClient.getQueryState(base)?.isInvalidated).toBe(true))
+ expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "server")).toBe(false)
+ expect(unread.projectUnread("servers", "child", false)).toBe(true)
+ })
+
+ it.each([403, 404, 500].flatMap((status) => (["community:channel.member_add", "community:channel.member_remove"] as const).map((type) => ({ status, type }))))("keeps unknown legacy content retired after $type when the access recheck returns $status", async ({ status, type }) => {
await mountHook({ viewerUserId: "u_me" })
const { ApiError } = await import("@/lib/errors")
const { useCommunityWsStore } = await import("@/stores/community/ws")
getCommunityApiFetchMock().mockRejectedValue(new ApiError("lookup failed", status))
const key = communityKeys.channelMessages("child")
capturedQueryClient.setQueryData(key, { pages: [] })
- capturedOnMessage!({ type: "community:channel.member_remove", channelId: "child", serverId: "server", userId: "u_me" })
+ capturedOnMessage!({ type, channelId: "child", serverId: "server", userId: "u_me" })
await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith("/api/community/channels/child/messages?entry=1", expect.anything()))
await vi.waitFor(() => expect(capturedQueryClient.getQueryState(entryKey("server", "child"))?.fetchStatus ?? "idle").toBe("idle"))
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child")).toBe(true)
expect(capturedQueryClient.getQueryData(key) === undefined).toBe(true)
+ expect(hasCanonicalChannelNotify("child", "u_me")).toBe(false)
})
it("discards a slow removal after a newer add and a slow metadata result after server leave", async () => {
diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.ts
index 6f6db756f..109aeda42 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.ts
@@ -55,7 +55,7 @@ function retireChannelAccess(event: { serverId: string | null; channelId: string
if (registry) retireCommunityChannelReading(registry, event.channelId, { reason: "read-denied", serverId: event.serverId })
}
-function refreshChannelAccess(event: { serverId: string | null; channelId: string }, context: MembershipEventContext) {
+function refreshChannelAccess(event: { serverId: string | null; channelId: string }, context: MembershipEventContext, legacyEvent?: ChannelMemberEvent) {
const { queryClient } = context
const token = captureChannelMetadataToken(queryClient, event.channelId)
const options = channelMetadataOptions(queryClient, event.serverId, event.channelId)
@@ -68,8 +68,15 @@ function refreshChannelAccess(event: { serverId: string | null; channelId: strin
if (!isChannelMetadataTokenCurrent(token)) return
const channel = getCanonicalCommunityChannels(queryClient).find((row) => row.id === event.channelId && row.serverId === event.serverId)
if (channel?.archived) runCommunityWsProjectionTransaction(queryClient, (projection) => retireChannelAccess(event, { ...context, projection }))
- else if (channel) getAccountUnreadProjection(queryClient, context.viewerUserIdRef.current!).grantAccessScope({ kind: "channel", channelId: event.channelId })
- } catch {}
+ else if (channel) {
+ getAccountUnreadProjection(queryClient, context.viewerUserIdRef.current!).grantAccessScope({ kind: "channel", channelId: event.channelId })
+ if (legacyEvent && channel.type === "thread") runCommunityWsProjectionTransaction(queryClient, (projection) => {
+ handleChannelMembershipChange({ ...legacyEvent, type: "community:channel.membership.change", relation: "notify", present: legacyEvent.type === "community:channel.member_add" }, { ...context, projection })
+ })
+ }
+ } catch {
+ if (legacyEvent?.type === "community:channel.member_add" && isChannelMetadataTokenCurrent(token)) runCommunityWsProjectionTransaction(queryClient, (projection) => retireChannelAccess(event, { ...context, projection }))
+ }
})()
}
@@ -113,8 +120,8 @@ export function handleChannelMemberEvent(event: ChannelMemberEvent, context: Mem
return
}
if (event.userId === context.viewerUserIdRef.current) {
- retireChannelAccess(event, context)
- refreshChannelAccess(event, context)
+ if (event.type === "community:channel.member_remove") retireChannelAccess(event, context)
+ refreshChannelAccess(event, context, event)
} else invalidateChannelRoster(context.projection, event.channelId)
}
diff --git a/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts b/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts
index d14b79790..0ff39ea13 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts
@@ -512,7 +512,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
await capturedOnReconnect!({ reconnectDurationMs: 250 })
- expect(directoryFetches).toBe(1)
+ expect(directoryFetches).toBe(2)
expect(capturedQueryClient.getQueryState(communityKeys.channelRefDirectory())?.isInvalidated).toBe(false)
const calls = spy.mock.calls.map(([filters]) => filters)
for (const serverId of ["srv_a", "srv_b"]) {
@@ -543,7 +543,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
expect(capturedQueryClient.getQueryData(scopeOnlyMetadata)).toEqual({ id: "scope-only" })
expect(calls.some(({ queryKey }) => queryKey?.includes("__none__"))).toBe(false)
expect(calls.some(({ queryKey }) => queryKey?.includes("__pending__"))).toBe(false)
- expect(calls.some(({ queryKey }) => queryKey?.includes("channel-ref-directory"))).toBe(false)
+ expect(calls.some(({ queryKey }) => queryKey?.includes("channel-ref-directory"))).toBe(true)
expect(calls.some(({ queryKey }) => queryKey?.includes("srv_ghost"))).toBe(false)
for (const queryKey of invalidDerivedTuples) {
expect(capturedQueryClient.getQueryData(queryKey)).toEqual({ sentinel: true })
@@ -569,8 +569,8 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
const summary = await reconcileCommunityWsReconnect(capturedQueryClient, 900)
expect(summary).toMatchObject({
- policyCount: 15,
- successCount: 14,
+ policyCount: 16,
+ successCount: 15,
failureCount: 1,
reconnectDurationMs: 900,
})
@@ -629,7 +629,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
const summary = await reconcileCommunityWsReconnect(capturedQueryClient, 10)
vi.spyOn(getCapturedRuntime().ws.actions, "setPresence").mockImplementation(originalSetPresence)
- expect(summary).toMatchObject({ policyCount: 15, successCount: 14, failureCount: 1 })
+ expect(summary).toMatchObject({ policyCount: 16, successCount: 15, failureCount: 1 })
expect(telemetry.failure).toHaveBeenCalledWith({
policy: "presence-overlay",
reason: "async-rejection",
@@ -650,7 +650,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
expect(keys).not.toContain(JSON.stringify(communityKeys.dms()))
expect(keys).toContain(JSON.stringify(communityKeys.friends()))
expect(keys).toContain(JSON.stringify(communityKeys.servers()))
- expect(summary).toMatchObject({ policyCount: 14, successCount: 14, failureCount: 0 })
+ expect(summary).toMatchObject({ policyCount: 15, successCount: 15, failureCount: 0 })
})
it("actively refetches cached Friends and canonical attention after a socket gap", async () => {
diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.ts
index 2c6d63102..45c071859 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.ts
@@ -1,3 +1,4 @@
+import { reconcileCommunityServerRail } from "./server-rail-reconciliation"
import { getCommunityRuntime, readCurrentCommunityChannelMeta } from "@/stores/community/runtime"
import type { QueryClient, QueryKey } from "@tanstack/react-query"
@@ -233,6 +234,7 @@ function policyExecutors(
"cached-read-state": async () => {
await reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
},
+ "server-rail": () => reconcileCommunityServerRail(queryClient),
"all-cached-servers": async () => {
const serverIds = cachedServerIds(queryClient, queryKeys)
const settled = await Promise.allSettled([
diff --git a/src/web/src/hooks/community/community-ws/registry.test.ts b/src/web/src/hooks/community/community-ws/registry.test.ts
index b0238389b..8322037f6 100644
--- a/src/web/src/hooks/community/community-ws/registry.test.ts
+++ b/src/web/src/hooks/community/community-ws/registry.test.ts
@@ -21,6 +21,8 @@ const handlers = vi.hoisted(() => new Proxy({} as Record<string, ReturnType<type
},
}))
+vi.mock("./server-rail-reconciliation", () => ({ handleServerRailChanged: handlers.handleServerRailChanged }))
+
vi.mock("./message-events", () => ({
handleMessageCreate: handlers.handleMessageCreate,
handleMessageEdited: handlers.handleMessageEdited,
@@ -88,7 +90,7 @@ describe("community WebSocket registry", () => {
it("has exactly one entry for each runtime event type", () => {
const eventTypes = Object.values(WS_EVENTS).sort()
const registryTypes = Object.keys(communityWsRegistry).sort()
- expect(eventTypes).toHaveLength(47)
+ expect(eventTypes).toHaveLength(48)
expect(registryTypes).toEqual(eventTypes)
})
@@ -100,8 +102,8 @@ describe("community WebSocket registry", () => {
})
it("deduplicates the complete policy set", () => {
- expect(communityWsReconnectPolicies).toHaveLength(15)
- expect(new Set(communityWsReconnectPolicies).size).toBe(15)
+ expect(communityWsReconnectPolicies).toHaveLength(16)
+ expect(new Set(communityWsReconnectPolicies).size).toBe(16)
})
it.each([
@@ -131,6 +133,7 @@ describe("community WebSocket registry", () => {
["community:message.create", "handleMessageCreate"],
["community:typing.start", "handleTypingStart"],
["community:server.update", "handleServerUpdate"],
+ ["community:server_rail.changed", "handleServerRailChanged"],
["community:member.join", "handleMemberJoin"],
["community:friend.accept", "handleFriendEvent"],
["community:presence.update", "handlePresenceUpdate"],
diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.ts
index 691e2a73e..04faa17e3 100644
--- a/src/web/src/hooks/community/community-ws/registry.ts
+++ b/src/web/src/hooks/community/community-ws/registry.ts
@@ -1,3 +1,4 @@
+import { handleServerRailChanged } from "./server-rail-reconciliation"
import { getCommunityRuntime } from "@/stores/community/runtime"
import { telemetryId, currentPageObservation, startPageOperation, finishPageOperation, pageOperationAttributes, type PageOperation } from "@/lib/observability/context"
@@ -78,6 +79,7 @@ export const communityWsRegistry = {
"community:typing.stop": { handler: handleTypingStop, reconnectPolicies: ["ephemeral-typing"] },
"community:channel.child_create": { handler: handleChildChannelCreate, reconnectPolicies: ["focused-threads", "all-cached-servers"] },
"community:channel.child_update": { handler: handleChildChannelUpdate, reconnectPolicies: ["focused-threads", "all-cached-servers"] },
+ "community:server_rail.changed": { handler: handleServerRailChanged, reconnectPolicies: ["server-rail"] },
"community:server.update": { handler: handleServerUpdate, reconnectPolicies: ["all-cached-servers"] },
"community:server.delete": { handler: handleServerDelete, reconnectPolicies: ["all-cached-servers"] },
"community:channel.create": { handler: handleChannelEvent, reconnectPolicies: ["all-cached-servers"] },
diff --git a/src/web/src/hooks/community/community-ws/server-rail-reconciliation.test.ts b/src/web/src/hooks/community/community-ws/server-rail-reconciliation.test.ts
new file mode 100644
index 000000000..d894d5553
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/server-rail-reconciliation.test.ts
@@ -0,0 +1,120 @@
+import { afterEach, expect, it, vi } from "vitest"
+import { QueryClient, QueryObserver } from "@tanstack/react-query"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { communityKeys } from "@/lib/query-keys"
+import { serverRailMutationKey } from "@/lib/community-db/server-rail"
+import { dispatchCommunityWsEvent, communityWsReconnectPolicies } from "./registry"
+import { reconcileCommunityWsReconnect } from "./reconnect"
+import { reconcileCommunityServerRail } from "./server-rail-reconciliation"
+
+const subscriptions: Array<() => void> = []
+afterEach(() => subscriptions.splice(0).forEach((unsubscribe) => unsubscribe()))
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((done) => { resolve = done })
+ return { promise, resolve }
+}
+function observe(client: QueryClient, key: readonly unknown[], queryFn = vi.fn(async () => ["fresh"])) {
+ const observer = new QueryObserver(client, { queryKey: key, queryFn, initialData: ["old"], staleTime: Infinity })
+ subscriptions.push(observer.subscribe(() => {}))
+ return { observer, queryFn }
+}
+
+it("refreshes only the account rail and reference directory, keeping inactive queries stale", async () => {
+ const { client, runtime } = await createCommunityQueryOwner()
+ const { client: other } = await createCommunityQueryOwner("other")
+ const servers = observe(client, communityKeys.servers())
+ const folders = observe(client, communityKeys.folders())
+ const detail = observe(client, communityKeys.server("unrelated"))
+ const foreign = observe(other, communityKeys.folders())
+ client.setQueryData(communityKeys.channelRefDirectory(), ["old"])
+ await dispatchCommunityWsEvent({ type: "community:server_rail.changed" }, {
+ queryClient: client, communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, deliveryMode: "single",
+ viewerUserIdRef: { current: "viewer" }, matchesFocus: () => false, scheduleInboxInvalidate: vi.fn(),
+ })
+ expect(servers.queryFn).toHaveBeenCalledTimes(1)
+ expect(folders.queryFn).toHaveBeenCalledTimes(1)
+ expect(detail.queryFn).not.toHaveBeenCalled()
+ expect(foreign.queryFn).not.toHaveBeenCalled()
+ expect(client.getQueryState(communityKeys.channelRefDirectory())?.isInvalidated).toBe(true)
+})
+
+it("cancels a pre-event GET so its late response cannot restore the old order", async () => {
+ const { client } = await createCommunityQueryOwner()
+ const old = deferred<string[]>()
+ let signal: AbortSignal | undefined
+ const queryFn = vi.fn().mockImplementationOnce((context) => { signal = context.signal; return old.promise }).mockResolvedValue(["new-order"])
+ const { observer } = observe(client, communityKeys.folders(), queryFn)
+ const pending = observer.refetch()
+ await vi.waitFor(() => expect(queryFn).toHaveBeenCalledTimes(1))
+ await reconcileCommunityServerRail(client)
+ expect(signal?.aborted).toBe(true)
+ old.resolve(["obsolete"])
+ await pending
+ expect(client.getQueryData(communityKeys.folders())).toEqual(["new-order"])
+})
+
+it("waits for native save confirmation and coalesces simultaneous hints", async () => {
+ const { client } = await createCommunityQueryOwner()
+ const folders = observe(client, communityKeys.folders())
+ const commit = deferred<void>()
+ const mutation = client.getMutationCache().build(client, { mutationKey: serverRailMutationKey, mutationFn: () => commit.promise })
+ const saving = mutation.execute(undefined)
+ await vi.waitFor(() => expect(client.isMutating()).toBe(1))
+ const hints = Promise.all([reconcileCommunityServerRail(client), reconcileCommunityServerRail(client)])
+ await Promise.resolve()
+ expect(folders.queryFn).not.toHaveBeenCalled()
+ commit.resolve()
+ await saving
+ await hints
+ expect(folders.queryFn).toHaveBeenCalledTimes(1)
+ expect(client.getQueryData(communityKeys.folders())).toEqual(["fresh"])
+})
+
+it.each(["retired", "new-generation"])("ignores a %s account after its pending save completes", async (change) => {
+ const { client, registry } = await createCommunityQueryOwner()
+ const folders = observe(client, communityKeys.folders())
+ const commit = deferred<void>()
+ const mutation = client.getMutationCache().build(client, { mutationKey: serverRailMutationKey, mutationFn: () => commit.promise })
+ const saving = mutation.execute(undefined)
+ await vi.waitFor(() => expect(client.isMutating()).toBe(1))
+ const refresh = reconcileCommunityServerRail(client)
+ if (change === "retired") await registry.cleanup()
+ else registry.runtime.lifecycle.setState((state) => ({ ...state, generation: state.generation + 1 }))
+ commit.resolve()
+ await saving
+ await refresh
+ expect(folders.queryFn).not.toHaveBeenCalled()
+})
+
+it("does not refresh a replacement query registered during cancellation", async () => {
+ const { client } = await createCommunityQueryOwner()
+ observe(client, communityKeys.folders())
+ const cancel = client.cancelQueries.bind(client)
+ const replacement = vi.fn(async () => ["replacement"])
+ vi.spyOn(client, "cancelQueries").mockImplementationOnce(async (filters) => {
+ await cancel(filters)
+ client.removeQueries({ queryKey: communityKeys.folders(), exact: true })
+ observe(client, communityKeys.folders(), replacement)
+ })
+ await reconcileCommunityServerRail(client)
+ expect(replacement).not.toHaveBeenCalled()
+})
+
+it("requires a live native account registry", async () => {
+ const client = new QueryClient()
+ const invalidate = vi.spyOn(client, "invalidateQueries")
+ await reconcileCommunityServerRail(client)
+ expect(invalidate).not.toHaveBeenCalled()
+ client.clear()
+})
+
+it("reconciles missed rail hints on reconnect without unrelated server-detail work", async () => {
+ const { client } = await createCommunityQueryOwner()
+ const folders = observe(client, communityKeys.folders())
+ const detail = observe(client, communityKeys.server("unrelated"))
+ const summary = await reconcileCommunityWsReconnect(client, 10, { excludePolicies: communityWsReconnectPolicies.filter((policy) => policy !== "server-rail") })
+ expect(summary).toMatchObject({ policyCount: 1, successCount: 1, failureCount: 0 })
+ expect(folders.queryFn).toHaveBeenCalledTimes(1)
+ expect(detail.queryFn).not.toHaveBeenCalled()
+})
diff --git a/src/web/src/hooks/community/community-ws/server-rail-reconciliation.ts b/src/web/src/hooks/community/community-ws/server-rail-reconciliation.ts
new file mode 100644
index 000000000..97f6f9cde
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/server-rail-reconciliation.ts
@@ -0,0 +1,33 @@
+import type { QueryClient } from "@tanstack/react-query"
+import type { CommunityServerRailChanged } from "@alook/shared"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import { serverRailMutationKey } from "@/lib/community-db/server-rail"
+import { communityKeys } from "@/lib/query-keys"
+import type { StructureTreeEventContext } from "./handler-context"
+
+export async function reconcileCommunityServerRail(queryClient: QueryClient) {
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry?.runtime.lifecycle.get().active) return
+ const generation = registry.runtime.lifecycle.get().generation
+ const current = () => getCommunityDbRegistry(queryClient) === registry
+ && registry.runtime.lifecycle.get().active && registry.runtime.lifecycle.get().generation === generation
+ const pending = () => queryClient.isMutating({ mutationKey: serverRailMutationKey, exact: true }) > 0
+ if (pending()) {
+ await new Promise<void>((resolve) => {
+ const unsubscribe = queryClient.getMutationCache().subscribe(() => {
+ if (!pending()) { unsubscribe(); resolve() }
+ })
+ })
+ }
+ if (!current()) return
+ const queries = [communityKeys.servers(), communityKeys.folders(), communityKeys.channelRefDirectory()]
+ .flatMap((queryKey) => queryClient.getQueryCache().findAll({ queryKey, exact: true }))
+ await Promise.all(queries.map((query) => queryClient.cancelQueries({ queryKey: query.queryKey, exact: true, predicate: (candidate) => candidate === query })))
+ if (!current()) return
+ await Promise.all(queries.filter((query) => queryClient.getQueryCache().get(query.queryHash) === query)
+ .map((query) => queryClient.invalidateQueries({ queryKey: query.queryKey, exact: true, predicate: (candidate) => candidate === query }, { cancelRefetch: false })))
+}
+
+export function handleServerRailChanged(_event: CommunityServerRailChanged, { queryClient }: StructureTreeEventContext) {
+ return reconcileCommunityServerRail(queryClient)
+}
diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.ts
index b450e93db..543590016 100644
--- a/src/web/src/hooks/community/community-ws/social-events.ts
+++ b/src/web/src/hooks/community/community-ws/social-events.ts
@@ -87,7 +87,7 @@ export function handleUnreadBump(
const viewerId = viewerUserIdRef.current
if (event.userId === viewerId && viewerId) {
const evidence = unreadBumpEvidence?.get(event)
- scheduleAccountAttentionReconcile(queryClient)
+ scheduleAccountAttentionReconcile(queryClient, { channelId: event.channelId, messageId: evidence?.messageId })
getAccountUnreadProjection(queryClient, viewerId).recordArrival({
channelId: event.channelId,
railChannelId: event.railChannelId,
@@ -151,7 +151,7 @@ export function handleMentionCreate(
) {
const viewerId = viewerUserIdRef.current
if (!viewerId || event.userId !== viewerId) return
- scheduleAccountAttentionReconcile(queryClient)
+ scheduleAccountAttentionReconcile(queryClient, { channelId: event.channelId, messageId: event.messageId })
if (event.channelId) {
const candidate = messageEvidenceByChannel?.get(event.channelId)
const evidence = candidate?.messageId === event.messageId ? candidate : undefined
diff --git a/src/web/src/hooks/community/mutations/channels.dom.test.ts b/src/web/src/hooks/community/mutations/channels.dom.test.ts
index 7d556245d..6e733df2d 100644
--- a/src/web/src/hooks/community/mutations/channels.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/channels.dom.test.ts
@@ -9,6 +9,7 @@ import { communityKeys } from "@/lib/query-keys"
import { UNCATEGORIZED_CATEGORY_ID } from "@alook/shared"
import { getActiveAccountUnreadProjection } from "../account-unread-projection"
import * as commands from "./channels"
+import { useChannelTree } from "@/components/community/channels/use-channel-tree"
import type { ServerDetail } from "../use-servers"
const api = vi.fn()
@@ -36,7 +37,7 @@ function seed(cats = categories) {
client.setQueryData(communityKeys.server("s1"), "s1")
client.setQueryData(communityKeys.channelRefDirectory(), { serverIds: ["s1", "s2"] })
}
-function mount<T>(hook: () => T) { return renderHook(() => ({ command: hook(), tree: useServerTreeProjection("s1"), directory: useChannelRefDirectoryProjection() }), { wrapper: Owner }) }
+function mount<T>(hook: () => T) { return renderHook(() => { const command = hook(), tree = useServerTreeProjection("s1"), directory = useChannelRefDirectoryProjection(), sidebar = useChannelTree(tree?.categories ?? []); return { command, tree, directory, sidebar } }, { wrapper: Owner }) }
function deferred() {
let resolve!: (value: unknown) => void, reject!: (error: Error) => void
const promise = new Promise((done, fail) => { resolve = done; reject = fail })
@@ -93,14 +94,30 @@ describe("canonical channel rename", () => {
})
describe("canonical channel move and create", () => {
- it.each(["cat_2", null])("PATCHes categoryId %s and invalidates the original tree and directory", async (categoryId) => {
+ it.each(["cat_2", null])("saves categoryId %s and final positions in one request", async (categoryId) => {
seed(); api.mockResolvedValueOnce(undefined)
- const rendered = mount(commands.useMoveChannel)
- await act(async () => { await rendered.result.current.command.mutateAsync({ serverId: "s1", channelId: "c1", categoryId }) })
- expect(api).toHaveBeenCalledWith("/api/community/channels/c1", expect.objectContaining({ method: "PATCH", body: JSON.stringify({ categoryId }) }))
- expect(registry.collections.channels.get("c1")?.categoryId).toBe(categoryId)
+ const rendered = mount(commands.useReorderChannels)
+ const args = { serverId: "s1", channelIds: ["c2", "c1"], move: { channelId: "c1", categoryId } }
+ await act(async () => { await rendered.result.current.command.mutateAsync(args) })
+ expect(api).toHaveBeenCalledExactlyOnceWith("/api/community/servers/s1/channels/reorder", expect.objectContaining({ method: "PATCH", body: JSON.stringify({ channelIds: args.channelIds, move: args.move }) }))
+ expect(registry.collections.channels.get("c1")).toMatchObject({ categoryId, position: 1 })
+ expect(registry.collections.channels.get("c2")?.position).toBe(0)
+ expect(registry.collections.channels.get("c3")?.serverId).toBe("s2")
for (const key of [communityKeys.server("s1"), communityKeys.channelRefDirectory()]) expect(client.getQueryState(key)?.isInvalidated).toBe(true)
})
+ it("rolls back category and ordering in the actual sidebar projection on one failed save", async () => {
+ seed(); const held = deferred(), rendered = mount(commands.useReorderChannels)
+ const args = { serverId: "s1", channelIds: ["c2", "c1"], move: { channelId: "c1", categoryId: "cat_2" } }
+ const pending = start(rendered.result.current.command, args)
+ await waitFor(() => expect(rendered.result.current.sidebar.order.cat_2.map((row) => row.id)).toEqual(["c1"]))
+ expect(rendered.result.current.sidebar.order.cat_1.map((row) => row.id)).toEqual(["c2"])
+ await act(async () => { held.reject(new Error("atomic write failed")); expect(await pending).toMatchObject({ message: "atomic write failed" }) })
+ await waitFor(() => expect(rendered.result.current.sidebar.order.cat_1.map((row) => row.id)).toEqual(["c1", "c2"]))
+ expect(rendered.result.current.sidebar.order.cat_2).toEqual([])
+ expect(registry.collections.channels.get("c1")).toMatchObject({ categoryId: "cat_1", position: 0 })
+ expect(registry.collections.channels.get("c2")?.position).toBe(1)
+ expect(api).toHaveBeenCalledTimes(1)
+ })
it("inserts a pending channel into the matching category", async () => {
seed(); const held = deferred(), rendered = mount(commands.useCreateChannel), pending = start(rendered.result.current.command, create)
await waitFor(() => expect(treeChannels(rendered.result.current.tree).find((row) => row.pending)).toMatchObject({ name: "hi", type: "text" }))
diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.ts
index c911a100c..79f4ebe98 100644
--- a/src/web/src/hooks/community/mutations/channels.ts
+++ b/src/web/src/hooks/community/mutations/channels.ts
@@ -15,7 +15,7 @@ import {
import { communityKeys } from "@/lib/query-keys"
import { isAbortError } from "@/lib/errors"
import type { ChannelRow, CategoryRow } from "@/lib/community-db/schema"
-import { UNCATEGORIZED_CATEGORY_ID, type ChannelType } from "@alook/shared"
+import { UNCATEGORIZED_CATEGORY_ID, type ChannelCategoryMove, type ChannelType } from "@alook/shared"
import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
// Prefix marks an optimistic row so every consumer can tell it from a real
@@ -116,12 +116,6 @@ export function useCreateChannel() {
})
}
-export type MoveChannelArgs = {
- serverId: string
- channelId: string
- categoryId: string | null
-}
-
export type RenameChannelArgs = {
serverId: string
channelId: string
@@ -178,28 +172,6 @@ export function useRenameChannel() {
})
}
-/**
- * Move a channel to another category (or to uncategorized with `null`). The
- * backend (`channels/[id]` PATCH) is admin-only and rejects a move that would
- * cross a public↔private boundary — the sidebar blocks that before it gets
- * here, this mutation covers the same-privacy case. Invalidates the tree so
- * positions/category resettle from the server.
- */
-export function useMoveChannel() {
- const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()
- return useCommunityCommandMutation<void, Error, MoveChannelArgs>(origin, { meta: { observabilityAction: "channel.move" },
- scope: { id: "community-tree-commands" },
- mutationFn: (args) => persistTreeChange(origin, queryClient, args, (db) => {
- if (db.collections.channels.has(args.channelId)) db.collections.channels.update(args.channelId, (row) => { row.categoryId = args.categoryId })
- }, async (proof, options) => {
- await apiFetch(`/api/community/channels/${args.channelId}`, { method: "PATCH", body: JSON.stringify({ categoryId: args.categoryId }), ...options })
- origin.assert(proof.token)
- publishCommunityChannelFields(queryClient, args.channelId, { categoryId: args.categoryId }, proof)
- }),
- onSettled: (_data, error, args) => settleTree(origin, queryClient, args, error),
- })
-}
-
export type DeleteChannelArgs = { serverId: string; channelId: string }
export function useDeleteChannel() {
@@ -308,18 +280,18 @@ export function useReorderCategories() {
})
}
-export type ReorderChannelsArgs = { serverId: string; channelIds: string[] }
+export type ReorderChannelsArgs = { serverId: string; channelIds: string[]; move?: ChannelCategoryMove }
export function useReorderChannels() {
const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()
return useCommunityCommandMutation<void, Error, ReorderChannelsArgs>(origin, { meta: { observabilityAction: "channel.reorder" },
scope: { id: "community-tree-commands" },
mutationFn: (args) => persistTreeChange(origin, queryClient, args, (db) => {
- args.channelIds.forEach((id, position) => { if (db.collections.channels.get(id)?.serverId === args.serverId) db.collections.channels.update(id, (row) => { row.position = position }) })
+ args.channelIds.forEach((id, position) => { if (db.collections.channels.get(id)?.serverId === args.serverId) db.collections.channels.update(id, (row) => { row.position = position; if (args.move?.channelId === id) row.categoryId = args.move.categoryId }) })
}, async (proof, options) => {
- await apiFetch(`/api/community/servers/${args.serverId}/channels/reorder`, { method: "PATCH", body: JSON.stringify({ channelIds: args.channelIds }), ...options })
+ await apiFetch(`/api/community/servers/${args.serverId}/channels/reorder`, { method: "PATCH", body: JSON.stringify({ channelIds: args.channelIds, ...(args.move ? { move: args.move } : {}) }), ...options })
origin.assert(proof.token)
- args.channelIds.forEach((id, position) => publishCommunityChannelFields(queryClient, id, { position }, proof))
+ args.channelIds.forEach((id, position) => publishCommunityChannelFields(queryClient, id, { position, ...(args.move?.channelId === id ? { categoryId: args.move.categoryId } : {}) }, proof))
}),
onSettled: (_data, error, args) => settleTree(origin, queryClient, args, error),
})
diff --git a/src/web/src/hooks/community/mutations/server-rail-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/server-rail-owner.dom.test.tsx
index 54978b7b6..bad18fa87 100644
--- a/src/web/src/hooks/community/mutations/server-rail-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/server-rail-owner.dom.test.tsx
@@ -22,18 +22,18 @@ vi.mock("@/lib/api/client", () => ({ apiFetch: api }))
vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => sdk.session }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn(), replace: vi.fn() }) }))
vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))
-vi.mock("@atlaskit/pragmatic-drag-and-drop-live-region", () => ({ announce: ui.announce, cleanup: vi.fn() }))
-vi.mock("@/components/community/shell/use-server-rail-pdd", () => ({ useServerRailPdd: (options: typeof ui.options) => { ui.options = options; return { registerItem: vi.fn() } } }))
+vi.mock("@/components/community/shell/use-server-rail-dnd", () => ({ RailEndDropTarget: () => null, RailFolderGapDropTarget: () => null, useServerRailDrag: () => ({ entity: null, offset: null }), useServerRailDnd: (options: typeof ui.options) => { ui.options = options; return { cancel: () => {} } } }))
vi.mock("@/components/community/shell/sortable-server", () => ({ SortableServer: ({ server }: { server: { id: string; name: string } }) => <button data-testid={tid.serverIcon(server.id)}>{server.name}</button> }))
-vi.mock("@/components/community/shell/rail-folder", () => ({ RailFolder: ({ folderId, open, onToggle, onUngroup }: { folderId: string; open: boolean; onToggle: () => void; onUngroup: () => void }) => <><button data-testid={tid.serverRailFolder(folderId)} aria-expanded={open} onClick={onToggle}>{folderId}</button><button onClick={onUngroup}>Ungroup {folderId}</button></> }))
+vi.mock("@/components/community/shell/rail-folder", () => ({ RailFolder: ({ folderId, open, onToggle }: { folderId: string; open: boolean; onToggle: () => void }) => <button data-testid={tid.serverRailFolder(folderId)} aria-expanded={open} onClick={onToggle}>{folderId}</button> }))
vi.mock("@/components/community/shell/animated-alook-logo", () => ({ AnimatedAlookLogo: () => null }))
vi.mock("@/components/community/settings/create-server-dialog", () => ({ CreateServerDialog: () => null }))
vi.mock("@/components/ui/tooltip", () => ({ Tooltip: ({ children }: { children: React.ReactNode }) => children, TooltipTrigger: ({ children }: { children: React.ReactNode }) => children, TooltipContent: () => null }))
const servers = ["a", "b", "c"].map((id) => ({ id, name: id.toUpperCase(), discriminator: "0001", ownerId: "A", role: "member", icon: null }))
const folders = [{ id: "one", name: "One", position: 0, servers: [{ id: "c", name: "C", icon: null }] }]
-const before = { serverOrder: ["a", "b", "c"], folderOrder: ["one"], folders: { one: ["c"] }, expanded: [] }
-const after = { serverOrder: ["b", "a", "c"], folderOrder: ["one", "temp"], folders: { one: ["c"], temp: ["a", "b"] }, expanded: ["temp"] }
-const commands = [{ kind: "reorder-servers" as const, serverIds: after.serverOrder }, { kind: "create-folder" as const, clientId: "temp", name: "Group", serverIds: ["a", "b"] }]
+const commands = [
+ { kind: "reorder-top-level" as const, entries: [{ kind: "folder" as const, id: "temp" }, { kind: "folder" as const, id: "one" }] },
+ { kind: "create-folder" as const, clientId: "temp", name: "Group", serverIds: ["b", "a"] },
+]
let mutation: ReturnType<typeof useServerRailCommit>, qc: QueryClient
const clients: QueryClient[] = []
function Probe({ rail = false }: { rail?: boolean }) { const list = useServers(), groups = useFolders(); const command = useServerRailCommit(), client = useQueryClient(); useLayoutEffect(() => { mutation = command; qc = client; if (!clients.includes(client)) clients.push(client) }); return <><output data-testid="order">{list.servers.map((row) => row.id).join(",")}</output><output data-testid="names">{list.servers.map((row) => `${row.id}:${row.name}`).join(",")}</output><output data-testid="groups">{groups.folders.map((row) => `${row.id}:${row.servers.map((server) => server.id).join(",")}`).join("|")}</output>{rail && <ServerRail servers={list.servers} folders={groups.folders} view="server" onHome={vi.fn()} />}</> }
@@ -53,7 +53,7 @@ async function mount(rail = false) {
await getCommunityDbRegistry(qc)!.ready
return { view, resolve, reject, original: qc }
}
-function commit() { return mutation.mutateAsync({ before, after, commands }).catch((error: unknown) => error) }
+function commit() { return mutation.mutateAsync({ commands }).catch((error: unknown) => error) }
beforeEach(async () => { await clearAllPersistedCaches(); sdk.session = { data: { user: { id: "A" } }, isPending: false, error: null }; ui.frames.length = 0; ui.announce.mockReset(); sessionStorage.clear(); vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { ui.frames.push(callback); return ui.frames.length }) })
afterEach(async () => {
await act(async () => {
@@ -66,7 +66,7 @@ describe("native canonical rail command owner", () => {
expect(original.getQueryData(communityKeys.folders())).toEqual(["one"])
const cancel = vi.spyOn(original, "cancelQueries")
let result!: Promise<unknown>; act(() => { result = commit() })
- await waitFor(() => { expect(screen.getByTestId("order").textContent).toBe("b,a,c"); expect(screen.getByTestId("groups").textContent).toBe("one:c|temp:a,b") })
+ await waitFor(() => { expect(screen.getByTestId("order").textContent).toBe("b,a,c"); expect(screen.getByTestId("groups").textContent).toBe("temp:b,a|one:c") })
const replacement = new QueryClient()
for (const key of [communityKeys.servers(), communityKeys.folders()]) {
const resource = original.getQueryCache().find({ queryKey: key, exact: true })!
@@ -80,7 +80,7 @@ describe("native canonical rail command owner", () => {
expect(patches).toHaveLength(1)
expect(patches[0]).toEqual(["/api/community/users/me/server-rail", expect.objectContaining({ method: "PATCH", body: JSON.stringify({ commands }), authenticationAccount: "A" })])
await act(async () => { resolve({ createdFolderIds: { temp: "real" } }); await result })
- await waitFor(() => expect(screen.getByTestId("groups").textContent).toBe("one:c|real:a,b"))
+ await waitFor(() => expect(screen.getByTestId("groups").textContent).toBe("real:b,a|one:c"))
const registry = getCommunityDbRegistry(original)!
expect(registry.collections.folders.has("temp")).toBe(false); expect(registry.collections.folders.has("real")).toBe(true)
expect([...registry.collections.folderItems.values()].some((row) => row.folderId === "temp")).toBe(false)
@@ -110,13 +110,13 @@ describe("native canonical rail command owner", () => {
expect(screen.getByTestId("order").textContent).toBe("b,a,c")
expect(screen.getByTestId("names").textContent).toBe("b:B,a:newer,c:C")
const registry = getCommunityDbRegistry(original)!
- expect(registry.collections.servers.get("a")).toMatchObject({ name: "newer", position: 1 })
- expect(registry.collections.servers.get("b")?.position).toBe(0)
+ expect(registry.collections.servers.get("a")).toMatchObject({ name: "newer", position: 0 })
+ expect(registry.collections.servers.get("b")?.position).toBe(1)
expect(registry.collections.servers.get("c")?.position).toBe(2)
const committed = original.getQueryData<Array<{ id: string; position: number; name: string }>>(
communityKeys.communityDbCollection(registry.scopeId, "servers"),
)
- expect(committed).toEqual(expect.arrayContaining([expect.objectContaining({ id: "a", name: "newer", position: 1 })]))
+ expect(committed).toEqual(expect.arrayContaining([expect.objectContaining({ id: "a", name: "newer", position: 0 })]))
})
it("old successful account response cannot resurrect transport data or touch the new account", async () => {
const { view, resolve, original } = await mount()
@@ -149,7 +149,7 @@ describe("native canonical rail command owner", () => {
await waitFor(() => expect(api.mock.calls.some(([, options]) => options.method === "PATCH")).toBe(true))
act(() => view.rerender(<Root />)); ui.announce.mockClear(); ui.frames.length = 0
await act(async () => resolve({ createdFolderIds: { temp: "real" } }))
- await waitFor(() => expect(screen.getByTestId("groups").textContent).toBe("one:c|real:a,b"))
+ await waitFor(() => expect(screen.getByTestId("groups").textContent).toBe("real:b,a|one:c"))
expect(ui.announce).not.toHaveBeenCalled(); expect(ui.frames).toHaveLength(0)
})
it("a queued original focus callback cannot focus the replacement account", async () => {
@@ -165,3 +165,20 @@ describe("native canonical rail command owner", () => {
expect(query).not.toHaveBeenCalled(); query.mockRestore()
})
})
+
+it.each(["success", "error"] as const)("keeps mixed rail metadata in the native transaction through %s", async (outcome) => {
+ const { resolve, reject, original } = await mount();
+ const entries = [{ kind: "folder" as const, id: "one" }, { kind: "server" as const, id: "b" }, { kind: "server" as const, id: "a" }];
+ let result!: Promise<unknown>;
+ act(() => { result = mutation.mutateAsync({ commands: [{ kind: "reorder-top-level", entries }] }).catch((error: unknown) => error) });
+ const registry = getCommunityDbRegistry(original)!;
+ await waitFor(() => expect(registry.collections.serverRail.get("account")?.entries).toEqual(entries));
+ act(() => projectCommunityWsEventToDb(original, { type: "community:server.update", serverId: "a", changes: { name: "newer" } }));
+ await act(async () => {
+ if (outcome === "success") resolve({ createdFolderIds: {} }); else reject(new Error("denied"));
+ await result;
+ });
+ if (outcome === "success") expect(registry.collections.serverRail.get("account")?.entries).toEqual(entries);
+ else expect(registry.collections.serverRail.get("account")).toBeUndefined();
+ expect(registry.collections.servers.get("a")?.name).toBe("newer");
+});
diff --git a/src/web/src/hooks/community/mutations/server-rail.ts b/src/web/src/hooks/community/mutations/server-rail.ts
index 6465d276e..df02a2748 100644
--- a/src/web/src/hooks/community/mutations/server-rail.ts
+++ b/src/web/src/hooks/community/mutations/server-rail.ts
@@ -8,12 +8,11 @@ import { projectServerRailCommit, type ServerRailCommand, type ServerRailCommitR
import { apiFetch } from "@/lib/api/client"
import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
import { communityKeys } from "@/lib/query-keys"
-import { mutateCommunityServerRail, readCommunityServerRail } from "@/lib/community-db/server-rail"
+import { serverRailMutationKey, mutateCommunityServerRail, readCommunityServerRail } from "@/lib/community-db/server-rail"
import { publishCommunityServerRailCommit } from "@/lib/community-db/sync"
-import type { RailState } from "@/lib/community/server-rail-model"
-export type ServerRailCommitArgs = { before: RailState; after: RailState; commands: ServerRailCommand[]; assertUI?: () => void }
-const mutationKey = ["community", "server-rail", "change"] as const
+export type ServerRailCommitArgs = { commands: ServerRailCommand[]; assertUI?: () => void }
+const mutationKey = serverRailMutationKey
export function useServerRailCommit() {
const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()
const pending = useIsMutating({ mutationKey, exact: true }) > 0
@@ -66,6 +65,7 @@ export function useServerRailCommit() {
if ((error instanceof Error && error.name === "AbortError") || !origin.registry?.runtime.lifecycle.get().active) return
void queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true, predicate: (query) => args.resources.includes(query) })
void queryClient.invalidateQueries({ queryKey: communityKeys.folders(), exact: true, predicate: (query) => args.resources.includes(query) })
+ void queryClient.invalidateQueries({ queryKey: communityKeys.channelRefDirectory(), exact: true, predicate: (query) => args.resources.includes(query) })
},
})
return { ...mutation, isPending: pending, isCommandPending: () => queryClient.isMutating({ mutationKey, exact: true }) > 0 }
diff --git a/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx
index f2eb80cfa..644fc8054 100644
--- a/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx
@@ -15,7 +15,7 @@ import { createOwnerServerDeleteRouteToken, cancelOwnerServerDelete, observeOwne
import { flushOwnerServerDeleteRouteCommit } from "../community-ws/scope-eviction"
import { dispatchCommunityWsEvent } from "../community-ws/registry"
import { getCommunityRuntime } from "@/stores/community/runtime"
-import { useCreateChannel, useCreateCategory, useDeleteCategory, useMoveChannel, useReorderChannels, useUpdateCategory, useReorderCategories, useDeleteChannel } from "./channels"
+import { useCreateChannel, useCreateCategory, useDeleteCategory, useReorderChannels, useUpdateCategory, useReorderCategories, useDeleteChannel } from "./channels"
import { getActiveAccountUnreadProjection } from "../account-unread-projection"
const api = vi.hoisted(() => vi.fn())
const sdk = vi.hoisted(() => ({ id: "A" }))
@@ -29,15 +29,15 @@ let leave: ReturnType<typeof useLeaveServer>
let remove: ReturnType<typeof useDeleteServer>
let icon: ReturnType<typeof useUploadServerIcon>, updateCategory: ReturnType<typeof useUpdateCategory>, reorderCategories: ReturnType<typeof useReorderCategories>, deleteChannel: ReturnType<typeof useDeleteChannel>
let deleteCallbacks = { onSuccess: vi.fn(), onError: vi.fn() }
-let createChannel: ReturnType<typeof useCreateChannel>, createCategory: ReturnType<typeof useCreateCategory>, deleteCategory: ReturnType<typeof useDeleteCategory>, moveChannel: ReturnType<typeof useMoveChannel>, reorderChannels: ReturnType<typeof useReorderChannels>
+let createChannel: ReturnType<typeof useCreateChannel>, createCategory: ReturnType<typeof useCreateCategory>, deleteCategory: ReturnType<typeof useDeleteCategory>, reorderChannels: ReturnType<typeof useReorderChannels>
function Probe() {
const currentClient = useQueryClient()
const list = useServers(), detail = useServer("s1")
const routeToken = useMemo(() => createOwnerServerDeleteRouteToken(currentClient), [currentClient])
const currentUpdate = useUpdateServer(), currentLeave = useLeaveServer(), currentRemove = useDeleteServer({ ...deleteCallbacks, routeToken })
const currentIcon = useUploadServerIcon(), currentUpdateCategory = useUpdateCategory(), currentReorderCategories = useReorderCategories(), currentDeleteChannel = useDeleteChannel()
- const currentCreateChannel = useCreateChannel(), currentCreateCategory = useCreateCategory(), currentDeleteCategory = useDeleteCategory(), currentMoveChannel = useMoveChannel(), currentReorderChannels = useReorderChannels()
- useLayoutEffect(() => { client = currentClient; update = currentUpdate; leave = currentLeave; remove = currentRemove; icon = currentIcon; updateCategory = currentUpdateCategory; reorderCategories = currentReorderCategories; deleteChannel = currentDeleteChannel; createChannel = currentCreateChannel; createCategory = currentCreateCategory; deleteCategory = currentDeleteCategory; moveChannel = currentMoveChannel; reorderChannels = currentReorderChannels })
+ const currentCreateChannel = useCreateChannel(), currentCreateCategory = useCreateCategory(), currentDeleteCategory = useDeleteCategory(), currentReorderChannels = useReorderChannels()
+ useLayoutEffect(() => { client = currentClient; update = currentUpdate; leave = currentLeave; remove = currentRemove; icon = currentIcon; updateCategory = currentUpdateCategory; reorderCategories = currentReorderCategories; deleteChannel = currentDeleteChannel; createChannel = currentCreateChannel; createCategory = currentCreateCategory; deleteCategory = currentDeleteCategory; reorderChannels = currentReorderChannels })
return <><output data-testid="server-list">{list.servers.map((s) => s.name).join(",")}</output><output data-testid="server-detail">{detail.server ? `${detail.server.name}|${detail.server.description}` : "missing"}</output><output data-testid="tree">{detail.server?.categories.map((c) => `${c.id}:${c.name}:${c.channels.map((ch) => `${ch.id}=${ch.name}`).join(",")}`).join("|")}</output></>
}
function Root({ id = sdk.id }: { id?: string }) { return <QueryProvider userId={id}><Probe /></QueryProvider> }
@@ -156,7 +156,7 @@ describe("actual canonical server and tree command owner", () => {
})
it("confirms a move without losing the newer WS channel name", async () => {
const { resolve, original } = await mount()
- let result!: Promise<unknown>; act(() => { result = moveChannel.mutateAsync({ serverId: "s1", channelId: "c1", categoryId: "cat2" }).catch((error) => error) })
+ let result!: Promise<unknown>; act(() => { result = reorderChannels.mutateAsync({ serverId: "s1", channelIds: ["c1"], move: { channelId: "c1", categoryId: "cat2" } }).catch((error) => error) })
await waitFor(() => expect(screen.getByTestId("tree").textContent).toContain("cat2:Elsewhere:c1=general"))
act(() => projectCommunityWsEventToDb(original, { type: "community:channel.update", serverId: "s1", channelId: "c1", changes: { name: "newer-room" } }))
await act(async () => { resolve({ id: "c1", categoryId: "cat2" }); await result })
diff --git a/src/web/src/hooks/community/use-account-attention.dom.test.ts b/src/web/src/hooks/community/use-account-attention.dom.test.ts
new file mode 100644
index 000000000..36533986b
--- /dev/null
+++ b/src/web/src/hooks/community/use-account-attention.dom.test.ts
@@ -0,0 +1,126 @@
+import { createElement, type PropsWithChildren } from "react"
+import { QueryClientProvider } from "@tanstack/react-query"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { COMMUNITY_CONTRACT_HEADER, type AccountAttentionSnapshot } from "@alook/shared"
+import { renderHook, waitFor } from "@/test/react-dom-harness"
+import { CommunityDbProvider } from "@/lib/community-db/projections"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { scheduleAccountAttentionReconcile, useAccountAttention } from "./use-account-attention"
+
+const apiFetchMock = vi.fn()
+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetchMock(...args) }))
+beforeEach(() => { apiFetchMock.mockReset() })
+
+const message = { id: "message", channelId: "channel", type: "chat", seq: 4, authorId: "peer", authorName: "Peer", authorAvatar: null, authorAvatarVersion: 0, content: "background message", createdAt: "2026-10-24T00:00:00Z", replyToId: null, clientNonce: null, attachments: [], embeds: [], reactions: [], resourceComplete: true }
+function snapshot(lastUnreadSeq = 4): AccountAttentionSnapshot {
+ return {
+ scopes: [{ scopeId: "channel", channelId: "channel", serverId: "server", parentChannelId: null, ordinaryUnread: true, lastUnreadSeq, lastAttentionSeq: null, attentionCount: 0 }],
+ items: [], limit: 100, truncated: false,
+ included: {
+ servers: [{ id: "server", name: "Server", discriminator: "0001" }],
+ channels: [{ id: "channel", serverId: "server", name: "general", type: "text", parentChannelId: null, parentMessageId: null, creatorId: null, archived: false, lastMessageAt: message.createdAt }],
+ dms: [], profiles: [], messages: [],
+ },
+ }
+}
+
+async function mountOwner(value: AccountAttentionSnapshot) {
+ const owner = await createCommunityQueryOwner()
+ apiFetchMock.mockImplementation(async (path) => {
+ if (path === "/api/community/users/me/attention") return value
+ if (path === "/api/community/channels/channel/messages?limit=1") return { messages: [message] }
+ if (path === "/api/community/messages/message") return message
+ throw new Error(`Unexpected content read ${path}`)
+ })
+ function Wrapper({ children }: PropsWithChildren) {
+ return createElement(QueryClientProvider, { client: owner.client }, createElement(CommunityDbProvider, { registry: owner.registry }, children))
+ }
+ const hook = renderHook(() => useAccountAttention(), { wrapper: Wrapper })
+ await waitFor(() => {
+ if (hook.result.current.error) throw hook.result.current.error
+ expect(hook.result.current.data).toEqual({ loaded: true })
+ })
+ return { ...owner, hook }
+}
+
+describe("closed-Inbox account attention message hydration", () => {
+ it("hydrates an ID-bearing mention without any Inbox component or message window", async () => {
+ const owner = await mountOwner(snapshot())
+ const attentionCall = apiFetchMock.mock.calls.find(([path]) => path.endsWith("/attention"))!
+ expect(new Headers(attentionCall[1].headers).get(COMMUNITY_CONTRACT_HEADER)).toBe("3")
+ scheduleAccountAttentionReconcile(owner.client, { messageId: message.id, channelId: "channel" })
+ await waitFor(() => expect(owner.registry.collections.messages.get(message.id)?.resourceComplete).toBe(true))
+ expect(owner.registry.collections.messages.get(message.id)?.content).toBe(message.content)
+ expect(apiFetchMock.mock.calls.filter(([path]) => path.includes("/seq/"))).toHaveLength(0)
+ expect(apiFetchMock.mock.calls.every(([path]) => !path.endsWith("/read"))).toBe(true)
+ owner.hook.unmount()
+ })
+
+ it("hydrates a hint-only unread while its account index reconciliation is still held", async () => {
+ const owner = await mountOwner(snapshot())
+ expect(owner.registry.collections.messages.get(message.id)).toBeUndefined()
+ let release!: (value: AccountAttentionSnapshot) => void
+ apiFetchMock.mockImplementation(async (path) => {
+ if (path.endsWith("/attention")) return new Promise((resolve) => { release = resolve })
+ if (path === "/api/community/channels/channel/messages?limit=1") return { messages: [message] }
+ throw new Error(`Unexpected content read ${path}`)
+ })
+ scheduleAccountAttentionReconcile(owner.client, { channelId: "channel" })
+ await waitFor(() => expect(owner.registry.collections.messages.get(message.id)?.resourceComplete).toBe(true))
+ await waitFor(() => expect(release).toBeTypeOf("function"))
+ expect(owner.hook.result.current.isFetching).toBe(true)
+ expect(apiFetchMock.mock.calls.filter(([path]) => path.includes("/seq/"))).toHaveLength(0)
+ release(snapshot())
+ await waitFor(() => expect(owner.hook.result.current.isFetching).toBe(false))
+ owner.hook.unmount()
+ })
+
+ it("hydrates both channels when a later hint cancels an earlier account-index read", async () => {
+ const owner = await mountOwner(snapshot())
+ const other = { ...message, id: "other", channelId: "other-channel" }
+ const reads: Array<{ signal: AbortSignal; release: (value: AccountAttentionSnapshot) => void }> = []
+ apiFetchMock.mockImplementation(async (path, options) => {
+ if (path.endsWith("/attention")) return new Promise((resolve) => { reads.push({ signal: options.signal, release: resolve }) })
+ if (path === "/api/community/channels/channel/messages?limit=1") return { messages: [message] }
+ if (path === "/api/community/channels/other-channel/messages?limit=1") return { messages: [other] }
+ throw new Error(`Unexpected content read ${path}`)
+ })
+ scheduleAccountAttentionReconcile(owner.client, { channelId: "channel" })
+ await waitFor(() => expect(reads).toHaveLength(1))
+ scheduleAccountAttentionReconcile(owner.client, { channelId: other.channelId })
+ await waitFor(() => expect(reads).toHaveLength(2))
+ expect(reads[0].signal.aborted).toBe(true)
+ reads[0].release(snapshot())
+ reads[1].release(snapshot())
+ await waitFor(() => {
+ expect(owner.registry.collections.messages.get(message.id)?.resourceComplete).toBe(true)
+ expect(owner.registry.collections.messages.get(other.id)?.resourceComplete).toBe(true)
+ expect(owner.hook.result.current.isFetching).toBe(false)
+ })
+ expect(apiFetchMock.mock.calls.filter(([path]) => path.includes("messages?limit=1"))).toHaveLength(2)
+ expect(apiFetchMock.mock.calls.every(([path]) => !path.endsWith("/read"))).toBe(true)
+ owner.hook.unmount()
+ })
+
+ it.each(["missing-scope", "empty-scope"])("hydrates without depending on a potentially lagging index: %s", async (mode) => {
+ const value = snapshot(0)
+ if (mode === "missing-scope") value.scopes = []
+ const owner = await mountOwner(value)
+ scheduleAccountAttentionReconcile(owner.client, { channelId: "channel" })
+ await waitFor(() => expect(owner.registry.collections.messages.get(message.id)?.resourceComplete).toBe(true))
+ expect(apiFetchMock.mock.calls.every(([path]) => !path.endsWith("/read"))).toBe(true)
+ owner.hook.unmount()
+ })
+
+ it.each(["no-hint", "inactive"])("does not hydrate an unrelated or retired scope: %s", async (mode) => {
+ const owner = await mountOwner(snapshot())
+ if (mode === "inactive") owner.runtime.lifecycle.setState((state) => ({ active: false, generation: state.generation + 1 }))
+ scheduleAccountAttentionReconcile(owner.client, mode === "no-hint" ? undefined : { channelId: "channel" })
+ if (mode !== "inactive") {
+ await waitFor(() => expect(apiFetchMock.mock.calls.filter(([path]) => path.endsWith("/attention"))).toHaveLength(2))
+ await waitFor(() => expect(owner.hook.result.current.isFetching).toBe(false))
+ }
+ expect(apiFetchMock.mock.calls.filter(([path]) => path.includes("/messages"))).toHaveLength(0)
+ owner.hook.unmount()
+ })
+})
diff --git a/src/web/src/hooks/community/use-account-attention.ts b/src/web/src/hooks/community/use-account-attention.ts
index 48e6d0d90..f5afa4c51 100644
--- a/src/web/src/hooks/community/use-account-attention.ts
+++ b/src/web/src/hooks/community/use-account-attention.ts
@@ -4,6 +4,8 @@ import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle
import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"
import {
AccountAttentionSnapshotSchema,
+ COMMUNITY_CONTRACT_HEADER,
+ COMMUNITY_RESOURCE_CONTRACT_VERSION,
type AccountAttentionSnapshot,
} from "@alook/shared"
import { apiFetch, type ApiRequestOptions } from "@/lib/api/client"
@@ -21,6 +23,7 @@ import {
getCommunityDbRegistry,
type CommunityDbRegistry,
} from "@/lib/community-db/collections"
+import { prefetchCommunityMessage, prefetchCommunityLatestMessage } from "./use-message"
class StaleAttentionReadError extends Error {
constructor() {
@@ -30,9 +33,11 @@ class StaleAttentionReadError extends Error {
}
async function fetchAccountAttention(options: ApiRequestOptions): Promise<AccountAttentionSnapshot> {
+ const headers = new Headers(options.headers)
+ headers.set(COMMUNITY_CONTRACT_HEADER, String(COMMUNITY_RESOURCE_CONTRACT_VERSION))
const response = await apiFetch<AccountAttentionSnapshot & { stale?: boolean }>(
"/api/community/users/me/attention",
- options,
+ { ...options, headers },
)
if (response.stale) throw new StaleAttentionReadError()
return AccountAttentionSnapshotSchema.parse(response)
@@ -90,10 +95,15 @@ export async function reconcileAccountAttention(
return snapshot
}
-export function scheduleAccountAttentionReconcile(queryClient: QueryClient) {
+export function scheduleAccountAttentionReconcile(queryClient: QueryClient, message?: { channelId?: string; messageId?: string }) {
const registry = getCommunityDbRegistry(queryClient)
if (!registry?.runtime.lifecycle.get().active) return
const token = captureCommunityLiveSnapshotToken(queryClient)
+ if (message?.messageId) {
+ void prefetchCommunityMessage(queryClient, message.messageId, { channelId: message.channelId }).catch(() => undefined)
+ } else if (message?.channelId) {
+ void prefetchCommunityLatestMessage(queryClient, message.channelId).catch(() => undefined)
+ }
void queryClient.cancelQueries({ queryKey: communityKeys.accountAttention(), exact: true }).then(() => {
assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)
return queryClient.invalidateQueries({ queryKey: communityKeys.accountAttention(), exact: true, refetchType: "active" }, { cancelRefetch: false })
diff --git a/src/web/src/hooks/community/use-folders.test.ts b/src/web/src/hooks/community/use-folders.test.ts
index d264d5d19..a08de87f9 100644
--- a/src/web/src/hooks/community/use-folders.test.ts
+++ b/src/web/src/hooks/community/use-folders.test.ts
@@ -29,7 +29,6 @@ describe("useFolders / foldersQueryFn", () => {
{
id: "fld_1",
name: "Group",
- position: 2,
servers: [{ id: "srv_1", name: "Alook", icon: null }],
},
],
@@ -38,7 +37,7 @@ describe("useFolders / foldersQueryFn", () => {
const data = await foldersQueryFn(context())
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/me/server-folders", expect.objectContaining({ authenticationAccount: "viewer", signal: expect.any(AbortSignal) }))
expect(data.folders[0].servers[0].initial).toBe("A")
- expect(data.folders[0].position).toBe(2)
+ expect(data.folders[0]).not.toHaveProperty("position")
})
it("populates queryClient at communityKeys.folders()", async () => {
diff --git a/src/web/src/hooks/community/use-folders.ts b/src/web/src/hooks/community/use-folders.ts
index e0f57ceee..307ca2e61 100644
--- a/src/web/src/hooks/community/use-folders.ts
+++ b/src/web/src/hooks/community/use-folders.ts
@@ -10,6 +10,7 @@ import {
} from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
+import type { ServerRailEntry } from "@alook/shared"
import { avatarInitial } from "@/lib/community/avatar"
import type { CommunityFolder } from "@/lib/community/models/navigation"
import {
@@ -30,11 +31,10 @@ import {
type RawFolder = {
id: string
name: string
- position: number
servers: Array<{ id: string; name: string; icon?: string | null }>
}
-export type FoldersResponse = { folders: CommunityFolder[] }
+export type FoldersResponse = { folders: CommunityFolder[]; topOrder?: ServerRailEntry[] | null }
// Frozen empty fallback — see `use-servers.ts` for the rationale.
const EMPTY_FOLDERS: readonly CommunityFolder[] = Object.freeze([])
@@ -43,11 +43,10 @@ export const foldersQueryFn = async (
context: QueryFunctionContext = {} as QueryFunctionContext,
): Promise<FoldersResponse> => {
const token = captureCommunityLiveSnapshotToken(context.client)
- const data = await apiFetch<{ folders: RawFolder[] }>("/api/community/users/me/server-folders", communityRequestOptions(context.client, token, context.signal))
+ const data = await apiFetch<{ folders: RawFolder[]; topOrder?: ServerRailEntry[] | null }>("/api/community/users/me/server-folders", communityRequestOptions(context.client, token, context.signal))
const folders: CommunityFolder[] = data.folders.map((f) => ({
id: f.id,
name: f.name,
- position: f.position ?? 0,
servers: f.servers.map((s) => ({
id: s.id,
name: s.name,
@@ -55,7 +54,7 @@ export const foldersQueryFn = async (
icon: s.icon ?? null,
})),
}))
- return { folders }
+ return { folders, ...(Object.hasOwn(data, "topOrder") ? { topOrder: data.topOrder } : {}) }
}
export const foldersProjectedQueryFn = (
@@ -72,6 +71,7 @@ export const foldersProjectedQueryFn = (
export function useFolders(): UseQueryResult<string[]> & {
folders: CommunityFolder[]
+ topOrder?: ServerRailEntry[]
} {
const dbRail = useServerRailProjection()
const queryClient = useQueryClient()
@@ -82,6 +82,7 @@ export function useFolders(): UseQueryResult<string[]> & {
})
return {
...query,
+ topOrder: dbRail?.topOrder,
folders: dbRail?.folders ?? (EMPTY_FOLDERS as CommunityFolder[]),
}
}
diff --git a/src/web/src/hooks/community/use-inbox.dom.test.ts b/src/web/src/hooks/community/use-inbox.dom.test.ts
index 1a5d1b2aa..3d93cddcc 100644
--- a/src/web/src/hooks/community/use-inbox.dom.test.ts
+++ b/src/web/src/hooks/community/use-inbox.dom.test.ts
@@ -14,6 +14,7 @@ import {
import {
clearAttentionScopeOptimistically,
ingestAttentionSnapshot,
+ ingestServers,
} from "@/lib/community-db/sync"
import { useCommunityWsStore } from "@/stores/community/ws"
import { CommunityPreviewProfileOwner } from "@/stores/community/profile-preview"
@@ -189,6 +190,7 @@ function dmSnapshot({ mention = false }: { mention?: boolean } = {}): AccountAtt
parentChannelId: null,
ordinaryUnread: !mention,
lastUnreadSeq: 9,
+ unreadCount: 3,
lastAttentionSeq: mention ? 9 : null,
attentionCount: mention ? 1 : 0,
}],
@@ -390,6 +392,28 @@ beforeEach(() => {
})
describe("useInboxAttention", () => {
+ it("keeps unread server identity aligned with its canonical owner", async () => {
+ const harness = await createHarness()
+ try {
+ const server = { id: "server", name: "Server", discriminator: "0001", initial: "S", active: false, unread: true, mentions: 0, icon: "/first-server-icon.png" }
+ act(() => {
+ ingestServers(harness.registry, { servers: [server] })
+ ingestAttentionSnapshot(harness.registry, forumSnapshot())
+ })
+ await waitFor(() => expect(harness.latest.servers[0]).toMatchObject({
+ serverName: "Server",
+ serverIcon: "/first-server-icon.png",
+ }))
+ act(() => ingestServers(harness.registry, { servers: [{ ...server, name: "Renamed", icon: null }] }))
+ await waitFor(() => expect(harness.latest.servers[0]).toMatchObject({
+ serverName: "Renamed",
+ serverIcon: null,
+ }))
+ } finally {
+ harness.dispose()
+ }
+ })
+
it("rejects stale marked and message-mark responses instead of publishing empty success", async () => {
const wrapperFor = (queryClient: QueryClient) => function Wrapper({
children,
@@ -428,6 +452,7 @@ describe("useInboxAttention", () => {
channelId: "dm",
otherUserName: "Peer",
lastUnreadSeq: 9,
+ unreadCount: 3,
})]))
const profileKey = communityKeys.communityDbCollection("viewer", "profiles")
diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.ts
index 56110009f..edc443aa8 100644
--- a/src/web/src/hooks/community/use-inbox.ts
+++ b/src/web/src/hooks/community/use-inbox.ts
@@ -91,6 +91,7 @@ export function useInboxAttention() {
otherUserAvatarVersion: dm.avatarVersion,
lastMessageAt: channel.lastMessageAt ?? "",
lastUnreadSeq: scope.lastUnreadSeq,
+ unreadCount: scope.unreadCount,
})
continue
}
@@ -194,7 +195,7 @@ export function useInboxAttention() {
.sort((left, right) => right.lastMessageAt.localeCompare(left.lastMessageAt)),
}))
.sort((left, right) => right.lastMessageAt.localeCompare(left.lastMessageAt))
- return [{ serverId, serverName: server.name, channels }]
+ return [{ serverId, serverName: server.name, serverIcon: server.icon, channels }]
})
dms.sort((left, right) => right.lastMessageAt.localeCompare(left.lastMessageAt))
diff --git a/src/web/src/hooks/community/use-message.test.ts b/src/web/src/hooks/community/use-message.test.ts
index e45918b30..6f061c4d7 100644
--- a/src/web/src/hooks/community/use-message.test.ts
+++ b/src/web/src/hooks/community/use-message.test.ts
@@ -1,8 +1,10 @@
import { beforeEach, describe, expect, it, vi } from "vitest"
+import { COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { communityKeys } from "@/lib/query-keys"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
-import { ingestMessages } from "@/lib/community-db/sync"
-import { findCachedMessage, messageQueryFn } from "./use-message"
+import { ingestMessages, retireCommunityChannelReading } from "@/lib/community-db/sync"
+import { findCachedMessage, messageQueryFn, prefetchCommunityMessage, prefetchCommunityLatestMessage } from "./use-message"
+import { getActiveAccountUnreadProjection } from "./account-unread-projection"
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetchMock(...args) }))
@@ -14,6 +16,127 @@ const payload = {
createdAt: "2026-07-03T00:00:00.000Z",
}
+const completePayload = { ...payload, resourceComplete: true as const, seq: 4, replyToId: null, clientNonce: null, attachments: [], embeds: [], reactions: [] }
+
+describe("background canonical message hydration", () => {
+ it("deduplicates concurrent reads and shares the exact message cache without opening a window", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ let release!: (value: typeof completePayload) => void
+ apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
+ const first = prefetchCommunityMessage(client, payload.id, { channelId: payload.channelId })
+ const second = prefetchCommunityMessage(client, payload.id, { channelId: payload.channelId })
+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(1))
+ release(completePayload)
+ await Promise.all([first, second])
+ expect(registry.collections.messages.get(payload.id)).toMatchObject({ resourceComplete: true, content: payload.content, seq: 4 })
+ expect(client.getQueryData(communityKeys.message(payload.id))).toBe(payload.id)
+ expect(client.getQueryData(communityKeys.channelMessages(payload.channelId))).toBeUndefined()
+ await prefetchCommunityMessage(client, payload.id, { channelId: payload.channelId })
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ it("reads a hint-only channel's latest full resource without creating a conversation window", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ apiFetchMock.mockResolvedValue({ messages: [completePayload] })
+ await Promise.all([
+ prefetchCommunityLatestMessage(client, payload.channelId),
+ prefetchCommunityLatestMessage(client, payload.channelId),
+ ])
+ expect(apiFetchMock.mock.calls.map(([path]) => path)).toEqual(["/api/community/channels/channel-1/messages?limit=1"])
+ expect(new Headers(apiFetchMock.mock.calls[0][1].headers).get(COMMUNITY_CONTRACT_HEADER)).toBe("3")
+ expect(registry.collections.messages.get(payload.id)?.resourceComplete).toBe(true)
+ expect(client.getQueryData(communityKeys.channelLatestMessage(payload.channelId))).toBe(payload.id)
+ expect(client.getQueryData(communityKeys.channelMessages(payload.channelId))).toBeUndefined()
+ })
+
+ it("hydrates a partial canonical message through the existing exact-ID reader", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ ingestMessages(registry, payload.channelId, [{ ...payload, seq: 4 }])
+ apiFetchMock.mockResolvedValueOnce(completePayload)
+ await prefetchCommunityMessage(client, payload.id, { channelId: payload.channelId })
+ expect(apiFetchMock.mock.calls.map(([path]) => path)).toEqual(["/api/community/messages/m_1"])
+ expect(registry.collections.messages.get(payload.id)?.resourceComplete).toBe(true)
+ })
+
+ it("does not fetch for retired access or an inactive owner", async () => {
+ const owner = await createCommunityQueryOwner()
+ getActiveAccountUnreadProjection(owner.client).retireAccessScope({ kind: "channel", channelId: payload.channelId })
+ await prefetchCommunityMessage(owner.client, payload.id, { channelId: payload.channelId })
+ await prefetchCommunityLatestMessage(owner.client, payload.channelId)
+ owner.runtime.lifecycle.setState((state) => ({ active: false, generation: state.generation + 1 }))
+ await prefetchCommunityMessage(owner.client, payload.id, {})
+ await prefetchCommunityLatestMessage(owner.client, payload.channelId)
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ })
+
+ it("does not publish a latest resource after its account owner retires", async () => {
+ const owner = await createCommunityQueryOwner()
+ let release!: (value: { messages: typeof completePayload[] }) => void
+ apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
+ const result = prefetchCommunityLatestMessage(owner.client, payload.channelId).catch((error) => error)
+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(1))
+ owner.runtime.lifecycle.setState((state) => ({ active: false, generation: state.generation + 1 }))
+ release({ messages: [completePayload] })
+ expect(await result).toMatchObject({ name: "AbortError" })
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ expect(owner.registry.collections.messages.get(payload.id)).toBeUndefined()
+ })
+
+ it("keeps different channel reads independent and cancels an older same-channel read", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ const next = { ...completePayload, id: "new", seq: 5, content: "newest" }
+ const other = { ...completePayload, id: "other", channelId: "channel-2" }
+ let releaseOld!: (value: { messages: typeof completePayload[] }) => void
+ let releaseOther!: (value: { messages: typeof completePayload[] }) => void
+ apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { releaseOld = resolve }))
+ .mockImplementationOnce(() => new Promise((resolve) => { releaseOther = resolve }))
+ .mockResolvedValueOnce({ messages: [next] })
+ const old = prefetchCommunityLatestMessage(client, payload.channelId).catch((error) => error)
+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(1))
+ const secondChannel = prefetchCommunityLatestMessage(client, other.channelId)
+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(2))
+ await prefetchCommunityLatestMessage(client, payload.channelId)
+ expect(apiFetchMock.mock.calls[0][1].signal.aborted).toBe(true)
+ expect(apiFetchMock.mock.calls[1][1].signal.aborted).toBe(false)
+ releaseOld({ messages: [completePayload] })
+ releaseOther({ messages: [other] })
+ await Promise.all([old, secondChannel])
+ expect(registry.collections.messages.get(payload.id)).toBeUndefined()
+ expect(registry.collections.messages.get(next.id)?.content).toBe("newest")
+ expect(registry.collections.messages.get(other.id)?.resourceComplete).toBe(true)
+ expect(client.getQueryData(communityKeys.channelLatestMessage(payload.channelId))).toBe(next.id)
+ expect(client.getQueryData(communityKeys.channelLatestMessage(other.channelId))).toBe(other.id)
+ })
+
+ it("stores null for an empty latest page and rejects a late revoked-scope resource", async () => {
+ const owner = await createCommunityQueryOwner()
+ apiFetchMock.mockResolvedValueOnce({ messages: [] })
+ await prefetchCommunityLatestMessage(owner.client, payload.channelId)
+ expect(owner.client.getQueryData(communityKeys.channelLatestMessage(payload.channelId))).toBeNull()
+ let release!: (value: { messages: typeof completePayload[] }) => void
+ apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
+ const result = prefetchCommunityLatestMessage(owner.client, payload.channelId).catch((error) => error)
+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(2))
+ retireCommunityChannelReading(owner.registry, payload.channelId, { reason: "read-denied" })
+ release({ messages: [completePayload] })
+ await result
+ expect(owner.registry.collections.messages.get(payload.id)).toBeUndefined()
+ expect(owner.client.getQueryData(communityKeys.channelLatestMessage(payload.channelId))).toBeUndefined()
+ })
+
+ it("does not publish a full message response after channel access is revoked", async () => {
+ const owner = await createCommunityQueryOwner()
+ let release!: (value: typeof completePayload) => void
+ apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
+ const result = prefetchCommunityMessage(owner.client, payload.id, { channelId: payload.channelId }).catch((error) => error)
+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(1))
+ owner.runtime.ws.actions.revokeChannelAccess(null, payload.channelId)
+ release(completePayload)
+ expect(await result).toMatchObject({ name: "AbortError" })
+ expect(owner.registry.collections.messages.get(payload.id)).toBeUndefined()
+ })
+})
+
describe("useMessage / messageQueryFn", () => {
it("clears absent rich fields from a fresh complete exact response", async () => {
const { client, registry } = await createCommunityQueryOwner()
diff --git a/src/web/src/hooks/community/use-message.ts b/src/web/src/hooks/community/use-message.ts
index 523b97383..75597ace6 100644
--- a/src/web/src/hooks/community/use-message.ts
+++ b/src/web/src/hooks/community/use-message.ts
@@ -6,13 +6,16 @@ import { useEffect, useMemo } from "react"
import {
useQuery,
useQueryClient,
+ queryOptions,
type QueryClient,
type QueryFunctionContext,
type UseQueryResult,
} from "@tanstack/react-query"
import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"
+import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { communityKeys } from "@/lib/query-keys"
-import type { MessageInput, Msg } from "@/lib/community/models/message"
+import type { MessageInput, MessagesPage, Msg } from "@/lib/community/models/message"
import { presentCanonicalMessage } from "@/lib/community/message-wire"
import {
useCanonicalMessagesById,
@@ -26,6 +29,7 @@ import { accountUnreadAllowsAccess, getActiveAccountUnreadProjection } from "./a
import { conversationReadRetryPolicy, withConversationReadDeadline } from "@/lib/community/conversation-read"
import {
captureCommunityLiveSnapshotToken,
+ assertCommunityLiveSnapshotTokenCurrent,
publishCommunityMessages,
getCanonicalCommunityMessages,
} from "@/lib/community-db/sync"
@@ -55,7 +59,7 @@ export const messageQueryFn = (
const token = captureCommunityLiveSnapshotToken(queryClient, channelId)
const message = await apiFetchCommunity<MessageInput>(
`/api/community/messages/${messageId}`,
- { signal: readSignal }, token,
+ { signal: readSignal, headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_RESOURCE_CONTRACT_VERSION) } }, token,
)
const publishChannelId = message.channelId ?? channelId
if (publishChannelId) {
@@ -68,6 +72,51 @@ export const messageQueryFn = (
return message.id
})
+function messageQueryOptions(queryClient: QueryClient, messageId: string, channelId?: string) {
+ return queryOptions({
+ queryKey: communityKeys.message(messageId),
+ queryFn: messageQueryFn(messageId, queryClient, channelId),
+ staleTime: 30_000,
+ retry: conversationReadRetryPolicy(queryClient.defaultQueryOptions({ queryKey: communityKeys.message(messageId) }).retry),
+ networkMode: "always",
+ })
+}
+
+export async function prefetchCommunityMessage(queryClient: QueryClient, messageId: string, scope: MessageAccessScope) {
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry?.runtime.lifecycle.get().active
+ || !accountUnreadAllowsAccess(getActiveAccountUnreadProjection(queryClient).state.get(), scope)) return
+ rememberMessageAccessScope(queryClient, messageId, scope)
+ if (registry.collections.messages.get(messageId)?.resourceComplete) return
+ await queryClient.query({ ...messageQueryOptions(queryClient, messageId, scope.channelId), staleTime: 0, select: undefined })
+}
+
+export async function prefetchCommunityLatestMessage(queryClient: QueryClient, channelId: string) {
+ const token = captureCommunityLiveSnapshotToken(queryClient, channelId)
+ const registry = token.registry
+ if (!registry?.runtime.lifecycle.get().active) return
+ const scope = { channelId, serverId: registry.collections.channels.get(channelId)?.serverId }
+ if (!accountUnreadAllowsAccess(getActiveAccountUnreadProjection(queryClient).state.get(), scope)) return
+ const queryKey = communityKeys.channelLatestMessage(channelId)
+ await queryClient.cancelQueries({ queryKey, exact: true })
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)
+ await queryClient.query({
+ queryKey,
+ staleTime: 0,
+ retry: conversationReadRetryPolicy(queryClient.defaultQueryOptions({ queryKey }).retry),
+ networkMode: "always",
+ queryFn: ({ signal }) => withConversationReadDeadline(signal, async (readSignal) => {
+ const page = await apiFetchCommunity<MessagesPage>(
+ `/api/community/channels/${channelId}/messages?limit=1`,
+ { signal: readSignal, headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_RESOURCE_CONTRACT_VERSION) } }, token,
+ )
+ publishCommunityMessages(queryClient, { channelId, messages: page.messages, proof: { token, signal: readSignal } })
+ return page.messages[0]?.id ?? null
+ }),
+ select: undefined,
+ })
+}
+
export function findCachedMessage(
queryClient: QueryClient,
messageId: string,
@@ -110,17 +159,12 @@ export function useMessage(
[accessAllowed, messageId, queryClient],
)
const query = useQuery({
- queryKey: enabled ? communityKeys.message(messageId!) : communityKeys.message("__none__"),
+ ...messageQueryOptions(queryClient, enabled ? messageId! : "__none__", accessScope?.channelId),
queryFn: enabled
? messageQueryFn(messageId!, queryClient, accessScope?.channelId)
: (() => Promise.reject(new Error("disabled"))),
enabled,
placeholderData,
- // Quick tab-switches shouldn't hammer the endpoint; 30s window is plenty
- // for the "opener stays live via mutation invalidation" contract.
- staleTime: 30_000,
- retry: conversationReadRetryPolicy(queryClient.defaultQueryOptions({ queryKey: communityKeys.message(messageId ?? "__none__") }).retry),
- networkMode: "always",
})
const canonical = messageId ? canonicalMessages?.get(messageId) : undefined
return {
diff --git a/src/web/src/lib/analytics.ts b/src/web/src/lib/analytics.ts
index 06823ee6b..c18aac76f 100644
--- a/src/web/src/lib/analytics.ts
+++ b/src/web/src/lib/analytics.ts
@@ -220,6 +220,7 @@ export type CommunityWsReconcilePolicy =
| "inbox-dms"
| "cached-read-state"
| "all-cached-servers"
+ | "server-rail"
| "friends"
| "presence-overlay"
| "status-overlay"
diff --git a/src/web/src/lib/community-db/collections.ts b/src/web/src/lib/community-db/collections.ts
index 578ff50dc..d48cc537a 100644
--- a/src/web/src/lib/community-db/collections.ts
+++ b/src/web/src/lib/community-db/collections.ts
@@ -23,6 +23,7 @@ import {
channelSchema,
folderItemSchema,
folderSchema,
+ serverRailSchema,
messageSchema,
friendshipSchema,
notificationSettingSchema,
@@ -85,6 +86,7 @@ function buildCommunityDbRegistry(
const readStateClock = collectionFor("readStateClock", readStateClockSchema, (row) => row.id)
const attentionScopes = collectionFor("attentionScopes", AttentionScopeSchema, (row) => row.scopeId)
const attentionItems = collectionFor("attentionItems", AttentionItemSchema, (row) => row.id)
+ const serverRail = collectionFor("serverRail", serverRailSchema, (row) => row.id)
const folders = collectionFor("folders", folderSchema, (row) => row.id)
const folderItems = collectionFor("folderItems", folderItemSchema, (row) => row.id)
const notificationSettings = collectionFor("notificationSettings", notificationSettingSchema, (row) => row.id)
@@ -103,6 +105,7 @@ function buildCommunityDbRegistry(
readStateClock,
attentionScopes,
attentionItems,
+ serverRail,
folders,
folderItems,
notificationSettings,
diff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.ts
index e128d85db..850f2b160 100644
--- a/src/web/src/lib/community-db/projections.ts
+++ b/src/web/src/lib/community-db/projections.ts
@@ -5,7 +5,7 @@ import { ApplicationOwnerProvider, createApplicationOwner } from "@/lib/applicat
import { DbProvider, and, eq, inArray, useLiveQuery as useNativeLiveQuery, type WhereCallback, type ContextFromSource } from "@tanstack/react-db"
import { createStore, useSelector } from "@tanstack/react-store"
import { CommunityRuntimeProvider } from "@/stores/community/runtime"
-import { notifLevelDisplay } from "@alook/shared"
+import { serverRailTopOrder, sortServerRailRows, notifLevelDisplay } from "@alook/shared"
import { projectForumSidebar } from "@/lib/community/forum-sidebar"
import { avatarInitial } from "@/lib/community/avatar"
import { readCommunityProfile } from "@/lib/community/profile-read"
@@ -135,6 +135,7 @@ export function useServerRailProjection() {
registry: useOptionalCommunityDbRegistry(),
servers: useServerRows(),
serverMemberships: useServerMembershipRows(),
+ serverRail: useCollectionRows("serverRail"),
folders: useFolderRows(),
folderItems: useFolderItemRows(),
}
@@ -175,12 +176,9 @@ export function useServerRailProjection() {
itemsByFolder.set(item.folderId, items)
}
const folders: CommunityFolder[] = (rows.folders ?? [])
- .slice()
- .sort((a, b) => a.position - b.position)
.map((folder) => ({
id: folder.id,
name: folder.name,
- position: folder.position,
servers: (itemsByFolder.get(folder.id) ?? [])
.slice()
.sort((a, b) => a.position - b.position)
@@ -194,8 +192,16 @@ export function useServerRailProjection() {
}] : []
}),
}))
- return { servers, folders }
- }, [rows.registry, rows.servers, rows.serverMemberships, rows.folders, rows.folderItems])
+ const state = {
+ serverIds: servers.map((server) => server.id),
+ folderIds: folders.map((folder) => folder.id),
+ folders: Object.fromEntries(folders.map((folder) => [folder.id, { id: folder.id, name: folder.name, serverIds: folder.servers.map((server) => server.id) }])),
+ topOrder: rows.serverRail?.find((row) => row.id === "account")?.entries,
+ }
+ const topOrder = serverRailTopOrder(state)
+ const byFolder = new Map(folders.map((folder) => [folder.id, folder]))
+ return { servers: sortServerRailRows(state, servers), folders: topOrder.flatMap((entry) => entry.kind === "folder" ? [byFolder.get(entry.id)!] : []), topOrder }
+ }, [rows.registry, rows.servers, rows.serverMemberships, rows.folders, rows.folderItems, rows.serverRail])
}
export function useServerTreeProjection(serverId: string | null) {
diff --git a/src/web/src/lib/community-db/schema.test.ts b/src/web/src/lib/community-db/schema.test.ts
index 7b2babcab..43afe8766 100644
--- a/src/web/src/lib/community-db/schema.test.ts
+++ b/src/web/src/lib/community-db/schema.test.ts
@@ -51,6 +51,7 @@ describe("community DB schemas", () => {
"readStateClock",
"attentionScopes",
"attentionItems",
+ "serverRail",
"folders",
"folderItems",
"notificationSettings",
diff --git a/src/web/src/lib/community-db/schema.ts b/src/web/src/lib/community-db/schema.ts
index 23f925843..912b11cd2 100644
--- a/src/web/src/lib/community-db/schema.ts
+++ b/src/web/src/lib/community-db/schema.ts
@@ -1,6 +1,6 @@
import { z } from "zod"
import { PARTICIPANT_SOURCE } from "@alook/shared/constants/community"
-import { AttentionScopeSchema, AttentionItemSchema, CommunityChannelResourceSchema, CommunityMessageResourceSchema, CommunityMessagePreviewSchema, CommunityReadStateResourceSchema, CommunityMemberRelationSchema, CommunityResourceProfileSchema } from "@alook/shared"
+import { serverRailEntrySchema, AttentionScopeSchema, AttentionItemSchema, CommunityChannelResourceSchema, CommunityMessageResourceSchema, CommunityMessagePreviewSchema, CommunityReadStateResourceSchema, CommunityMemberRelationSchema, CommunityResourceProfileSchema } from "@alook/shared"
const nullableString = z.string().nullable()
const optionalNullableString = nullableString.optional()
@@ -116,7 +116,11 @@ export const readStateClockSchema = z.object({
export const folderSchema = z.object({
id: z.string().min(1),
name: z.string(),
- position: z.number(),
+})
+
+export const serverRailSchema = z.object({
+ id: z.literal("account"),
+ entries: z.array(serverRailEntrySchema),
})
export const folderItemSchema = z.object({
@@ -153,6 +157,7 @@ export const communityCollectionSchemas = {
readStateClock: readStateClockSchema,
attentionScopes: AttentionScopeSchema,
attentionItems: AttentionItemSchema,
+ serverRail: serverRailSchema,
folders: folderSchema,
folderItems: folderItemSchema,
notificationSettings: notificationSettingSchema,
diff --git a/src/web/src/lib/community-db/server-rail.ts b/src/web/src/lib/community-db/server-rail.ts
index f073b07b7..c76148355 100644
--- a/src/web/src/lib/community-db/server-rail.ts
+++ b/src/web/src/lib/community-db/server-rail.ts
@@ -1,26 +1,38 @@
-import type { ServerRailProjection, ServerRailState } from "@alook/shared"
+import { sortServerRailRows, serverRailTopOrder, type ServerRailProjection, type ServerRailState } from "@alook/shared"
import type { CommunityDbRegistry } from "./collections"
import { folderItemKey } from "./schema"
+export const serverRailMutationKey = ["community", "server-rail", "change"] as const
+
export function readCommunityServerRail(registry: CommunityDbRegistry): ServerRailState {
const allowed = new Set([...registry.collections.serverMemberships.values()].filter((row) => row.viewer && row.userId === registry.accountId).map((row) => row.serverId))
- const serverOrder = [...registry.collections.servers.values()].filter((row) => allowed.has(row.id)).sort((a, b) => (a.position ?? 0) - (b.position ?? 0)).map((row) => row.id)
- const folders = [...registry.collections.folders.values()].sort((a, b) => a.position - b.position)
+ const serverIds = [...registry.collections.servers.values()].filter((row) => allowed.has(row.id)).sort((a, b) => (a.position ?? 0) - (b.position ?? 0)).map((row) => row.id)
+ const folders = [...registry.collections.folders.values()]
const items = [...registry.collections.folderItems.values()].filter((row) => allowed.has(row.serverId)).sort((a, b) => a.position - b.position)
return {
- serverOrder,
- folderOrder: folders.map((row) => row.id),
+ ...(registry.collections.serverRail.get("account") ? { topOrder: registry.collections.serverRail.get("account")!.entries } : {}),
+ serverIds,
+ folderIds: folders.map((row) => row.id),
folders: Object.fromEntries(folders.map((row) => [row.id, { id: row.id, name: row.name, serverIds: items.filter((item) => item.folderId === row.id).map((item) => item.serverId) }])),
}
}
+export function readCommunityServerRailServers(registry: CommunityDbRegistry) {
+ const state = readCommunityServerRail(registry)
+ const allowed = new Set(state.serverIds)
+ return sortServerRailRows(state, [...registry.collections.servers.values()].filter((row) => allowed.has(row.id)))
+}
+
export function mutateCommunityServerRail(registry: CommunityDbRegistry, projection: ServerRailProjection) {
- if (projection.reorderServers) projection.after.serverOrder.forEach((id, position) => registry.collections.servers.update(id, (row) => { row.position = position }))
+ if (projection.reorderTopLevel) {
+ const entries = serverRailTopOrder(projection.after);
+ if (registry.collections.serverRail.has("account")) registry.collections.serverRail.update("account", (row) => { row.entries = entries });
+ else registry.collections.serverRail.insert({ id: "account", entries });
+ }
for (const id of projection.deletedFolderIds) {
registry.collections.folders.delete(id)
}
- for (const folder of projection.createdFolders) registry.collections.folders.insert({ id: folder.id, name: folder.name, position: projection.after.folderOrder.indexOf(folder.id) })
- if (projection.reorderFolders) projection.after.folderOrder.forEach((id, position) => registry.collections.folders.update(id, (row) => { row.position = position }))
+ for (const folder of projection.createdFolders) registry.collections.folders.insert({ id: folder.id, name: folder.name })
const affected = new Set([...projection.affectedFolderIds, ...projection.createdFolders.map((row) => row.id)])
const items = [...affected].flatMap((id) => projection.after.folders[id]?.serverIds.map((serverId, position) => ({ id: folderItemKey(id, serverId), folderId: id, serverId, position })) ?? [])
const desired = new Map(items.map((row) => [row.id, row]))
diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.ts
index 199ec4a96..a23716351 100644
--- a/src/web/src/lib/community-db/sync.ts
+++ b/src/web/src/lib/community-db/sync.ts
@@ -1,3 +1,4 @@
+import { serverRailTopOrder } from "@alook/shared"
import type { Transaction } from "@tanstack/react-db"
import { communityRequestOptions as qualifiedCommunityRequestOptions } from "@/lib/community/account-cache-lifecycle"
import { isAbortError } from "@/lib/errors"
@@ -1006,7 +1007,6 @@ function ingestFolders(
const folders: FolderRow[] = response.folders.map((folder) => ({
id: folder.id,
name: folder.name,
- position: folder.position,
}))
const items: FolderItemRow[] = response.folders.flatMap((folder) => (
folder.servers.map((server, position) => ({
@@ -1017,6 +1017,7 @@ function ingestFolders(
}))
))
notifyManager.batch(() => {
+ if (Object.hasOwn(response, "topOrder")) replaceRows(registry, "serverRail", response.topOrder ? [{ id: "account", entries: response.topOrder }] : [], () => true)
replaceRows(registry, "folders", folders, () => true)
replaceRows(registry, "folderItems", items, () => true)
})
@@ -1024,14 +1025,9 @@ function ingestFolders(
export function publishCommunityServerRailCommit(queryClient: QueryClient, projection: ServerRailProjection, proof: CommunityFreshQueryProof) {
return withCommunityQueryProof(queryClient, proof, (registry) => {
- if (projection.reorderServers) {
- const positions = new Map(projection.after.serverOrder.map((id, position) => [id, position]))
- withCanonicalWriteContext(queryClient, { kind: "event" }, () => {
- patchRows(registry, "servers", (row) => ({ ...row, position: positions.get(row.id)! }), (row) => positions.has(row.id), undefined, ["position"])
- })
- }
- const affected = new Set([...projection.affectedFolderIds, ...projection.createdFolders.map((row) => row.id), ...(projection.reorderFolders ? projection.after.folderOrder : [])])
- const folders = projection.after.folderOrder.filter((id) => affected.has(id)).map((id) => ({ id, name: projection.after.folders[id]!.name, position: projection.after.folderOrder.indexOf(id) }))
+ if (projection.reorderTopLevel) replaceRows(registry, "serverRail", [{ id: "account", entries: serverRailTopOrder(projection.after) }], () => true)
+ const affected = new Set([...projection.affectedFolderIds, ...projection.createdFolders.map((row) => row.id)])
+ const folders = projection.after.folderIds.filter((id) => affected.has(id)).map((id) => ({ id, name: projection.after.folders[id]!.name }))
const knownServers = new Set(collectionRows(registry, "servers").map((row) => row.id))
const allowed = new Set(collectionRows(registry, "serverMemberships").filter((row) => row.viewer && row.userId === registry.accountId && knownServers.has(row.serverId)).map((row) => row.serverId))
const items = folders.flatMap((folder) => projection.after.folders[folder.id]!.serverIds.filter((serverId) => allowed.has(serverId)).map((serverId, position) => ({ id: folderItemKey(folder.id, serverId), folderId: folder.id, serverId, position })))
diff --git a/src/web/src/lib/community/eject-server.ts b/src/web/src/lib/community/eject-server.ts
index a7ab255b7..dafd7992e 100644
--- a/src/web/src/lib/community/eject-server.ts
+++ b/src/web/src/lib/community/eject-server.ts
@@ -191,7 +191,7 @@ export function isDefinitiveChildMetaFailure(error: unknown): boolean {
}
// Pure destination picker for the post-eject redirect. When the viewer
-// has any other servers, the first (railOrder-sorted from the API) wins.
+// has any other servers, the first in the canonical rail sequence wins.
// Otherwise the DM home is the only safe landing spot.
export function pickPostEjectDestination(
servers: readonly Pick<Server, "id">[],
diff --git a/src/web/src/lib/community/models/inbox.ts b/src/web/src/lib/community/models/inbox.ts
index 173d76b04..0a71d1751 100644
--- a/src/web/src/lib/community/models/inbox.ts
+++ b/src/web/src/lib/community/models/inbox.ts
@@ -67,6 +67,7 @@ type UnreadChild = {
export type UnreadServer = {
serverId: string
serverName: string
+ serverIcon?: string | null
channels: Array<{
channelId: string
channelName: string
@@ -84,6 +85,7 @@ export type UnreadServer = {
// "Unreads" — DMs with unread messages, rendered as a flat sibling section
// under the same Unreads tab as channels.
export type UnreadDm = {
+ unreadCount?: number
// The DM's channel id (a DM is a channel now). Kept as the row's stable key
// and the value passed to `onOpenDm` / the `/c/me/:id` route.
channelId: string
diff --git a/src/web/src/lib/community/models/navigation.ts b/src/web/src/lib/community/models/navigation.ts
index 84f5967da..51b6e4bd0 100644
--- a/src/web/src/lib/community/models/navigation.ts
+++ b/src/web/src/lib/community/models/navigation.ts
@@ -34,7 +34,6 @@ export type FolderServer = {
export type CommunityFolder = {
id: string
name: string
- position: number
servers: FolderServer[]
}
diff --git a/src/web/src/lib/community/server-rail-model.ts b/src/web/src/lib/community/server-rail-model.ts
index 9d96e8fd5..f212fa972 100644
--- a/src/web/src/lib/community/server-rail-model.ts
+++ b/src/web/src/lib/community/server-rail-model.ts
@@ -1,364 +1,236 @@
-import { MAX_SERVER_RAIL_FOLDERS, type ServerRailCommand } from "@alook/shared"
-
+import { MAX_SERVER_RAIL_FOLDERS, serverRailTopOrder, type ServerRailCommand, type ServerRailEntry } from "@alook/shared"
import type { CommunityFolder } from "@/lib/community/models/navigation"
-export type RailEntity =
- | { kind: "server"; id: string }
- | { kind: "folder"; id: string }
-
+export type RailEntity = ServerRailEntry
+export type RailContainer = { kind: "root"; id: "root" } | { kind: "folder-content"; id: string }
export type RailOperation = "reorder-before" | "reorder-after" | "combine"
-
export type RailOperationAvailability = Record<RailOperation, boolean>
-
export type RailInstruction = {
operation: RailOperation
source: RailEntity
target: RailEntity
newFolderId?: string
+} | {
+ operation: "append"
+ source: RailEntity
+ target: RailContainer
+ newFolderId?: never
}
-
export type RailState = {
- serverOrder: string[]
- folderOrder: string[]
+ serverIds: string[]
+ folderIds: string[]
folders: Record<string, string[]>
expanded: string[]
+ topOrder?: RailEntity[]
}
-
export type RailCommitResult =
| { applied: true; state: RailState; commands: ServerRailCommand[] }
| { applied: false; state: RailState; reason: string }
-function unique(values: readonly string[]): string[] {
- return [...new Set(values)]
-}
+const key = (entity: RailEntity) => `${entity.kind}:${entity.id}`
+const sameArray = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((value, index) => value === b[index])
+const unique = (values: string[]) => [...new Set(values)]
-function sameArray(left: readonly string[], right: readonly string[]): boolean {
- return left.length === right.length && left.every((value, index) => value === right[index])
+export function railTopLevel(state: RailState): RailEntity[] {
+ return serverRailTopOrder({ ...state, folders: Object.fromEntries(Object.entries(state.folders).map(([id, serverIds]) => [id, { id, name: "", serverIds }])) })
}
-export function railStateFromData(
- serverIds: readonly string[],
- folders: readonly CommunityFolder[],
- expanded: readonly string[],
-): RailState {
- const membershipIds = new Set(serverIds)
- const claimedServerIds = new Set<string>()
- const projectedFolders = [...folders]
- .sort((left, right) => left.position - right.position
- || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0))
- .map((folder) => ({
- id: folder.id,
- serverIds: folder.servers
- .map((server) => server.id)
- .filter((serverId) => {
- if (!membershipIds.has(serverId) || claimedServerIds.has(serverId)) return false
- claimedServerIds.add(serverId)
- return true
- }),
- }))
- .filter((folder) => folder.serverIds.length > 0)
- return {
- serverOrder: [...serverIds],
- folderOrder: projectedFolders.map((folder) => folder.id),
- folders: Object.fromEntries(
- projectedFolders.map((folder) => [folder.id, folder.serverIds]),
- ),
- expanded: expanded.filter((folderId) => projectedFolders.some((folder) => folder.id === folderId)),
+export function railStateFromData(serverIds: readonly string[], folders: readonly CommunityFolder[], expanded: readonly string[], topOrder?: RailEntity[]): RailState {
+ const membership = new Set(serverIds), claimed = new Set<string>()
+ const projected = [...folders].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0).map((folder) => ({
+ id: folder.id,
+ ids: folder.servers.flatMap((server) => {
+ if (!membership.has(server.id) || claimed.has(server.id)) return []
+ claimed.add(server.id)
+ return [server.id]
+ }),
+ })).filter((folder) => folder.ids.length > 0)
+ const state: RailState = {
+ serverIds: [...serverIds], folderIds: projected.map((folder) => folder.id),
+ folders: Object.fromEntries(projected.map((folder) => [folder.id, folder.ids])),
+ expanded: expanded.filter((id) => projected.some((folder) => folder.id === id)),
+ ...(topOrder ? { topOrder } : {}),
}
+ if (topOrder) state.topOrder = railTopLevel(state)
+ return state
}
export function cloneRailState(state: RailState): RailState {
return {
- serverOrder: [...state.serverOrder],
- folderOrder: [...state.folderOrder],
- folders: Object.fromEntries(
- Object.entries(state.folders).map(([folderId, serverIds]) => [folderId, [...serverIds]]),
- ),
+ serverIds: [...state.serverIds], folderIds: [...state.folderIds],
+ folders: Object.fromEntries(Object.entries(state.folders).map(([id, ids]) => [id, [...ids]])),
expanded: [...state.expanded],
+ ...(state.topOrder ? { topOrder: state.topOrder.map((entry) => ({ ...entry })) } : {}),
}
}
-function folderForServer(state: RailState, serverId: string): string | null {
- for (const folderId of state.folderOrder) {
- if (state.folders[folderId]?.includes(serverId)) return folderId
- }
- return null
+function folderForServer(state: RailState, id: string): string | null {
+ return state.folderIds.find((folderId) => state.folders[folderId]?.includes(id)) ?? null
}
-
export function visibleTopLevelServers(state: RailState): string[] {
- const claimed = new Set(Object.values(state.folders).flat())
- return state.serverOrder.filter((serverId) => !claimed.has(serverId))
+ return railTopLevel(state).flatMap((entry) => entry.kind === "server" ? [entry.id] : [])
}
-
export function railStateErrors(state: RailState): string[] {
const errors: string[] = []
- const serverIds = new Set(state.serverOrder)
- if (serverIds.size !== state.serverOrder.length) errors.push("server order contains duplicates")
- if (new Set(state.folderOrder).size !== state.folderOrder.length) errors.push("folder order contains duplicates")
- if (state.folderOrder.length > MAX_SERVER_RAIL_FOLDERS) errors.push("folder limit reached")
- const claimed = new Set<string>()
- for (const folderId of state.folderOrder) {
- const items = state.folders[folderId]
- if (!items) {
- errors.push(`folder ${folderId} is missing`)
- continue
- }
- if (items.length === 0) errors.push(`folder ${folderId} is empty`)
- if (new Set(items).size !== items.length) errors.push(`folder ${folderId} contains duplicates`)
+ const servers = new Set(state.serverIds), claimed = new Set<string>()
+ if (servers.size !== state.serverIds.length) errors.push("server order contains duplicates")
+ if (new Set(state.folderIds).size !== state.folderIds.length) errors.push("folder order contains duplicates")
+ if (state.folderIds.length > MAX_SERVER_RAIL_FOLDERS) errors.push("folder limit reached")
+ for (const id of state.folderIds) {
+ const items = state.folders[id]
+ if (!items) { errors.push(`folder ${id} is missing`); continue }
+ if (!items.length) errors.push(`folder ${id} is empty`)
+ if (new Set(items).size !== items.length) errors.push(`folder ${id} contains duplicates`)
for (const serverId of items) {
- if (!state.serverOrder.includes(serverId)) errors.push(`folder ${folderId} contains unknown server`)
+ if (!servers.has(serverId)) errors.push(`folder ${id} contains unknown server`)
if (claimed.has(serverId)) errors.push(`server ${serverId} belongs to multiple folders`)
claimed.add(serverId)
}
}
- for (const folderId of Object.keys(state.folders)) {
- if (!state.folderOrder.includes(folderId)) errors.push(`folder ${folderId} is unordered`)
- }
+ for (const id of Object.keys(state.folders)) if (!state.folderIds.includes(id)) errors.push(`folder ${id} is unordered`)
return errors
}
-
-function samePersistedState(left: RailState, right: RailState): boolean {
- return sameArray(left.serverOrder, right.serverOrder)
- && sameArray(left.folderOrder, right.folderOrder)
- && left.folderOrder.every((folderId) =>
- sameArray(left.folders[folderId] ?? [], right.folders[folderId] ?? []),
- )
-}
-
-function moveRelative(
- list: readonly string[],
- sourceId: string,
- targetId: string,
- after: boolean,
-): string[] {
- const next = list.filter((id) => id !== sourceId)
- const targetIndex = next.indexOf(targetId)
- if (targetIndex === -1) return [...list]
- next.splice(targetIndex + (after ? 1 : 0), 0, sourceId)
- return next
-}
-
-function removeServerFromFolder(state: RailState, serverId: string): void {
- const folderId = folderForServer(state, serverId)
+function removeServerFromFolder(state: RailState, id: string) {
+ const folderId = folderForServer(state, id)
if (!folderId) return
- state.folders[folderId] = state.folders[folderId]!.filter((id) => id !== serverId)
- if (state.folders[folderId]!.length > 0) return
+ state.folders[folderId] = state.folders[folderId]!.filter((serverId) => serverId !== id)
+ if (state.folders[folderId]!.length) return
delete state.folders[folderId]
- state.folderOrder = state.folderOrder.filter((id) => id !== folderId)
- state.expanded = state.expanded.filter((id) => id !== folderId)
+ state.folderIds = state.folderIds.filter((value) => value !== folderId)
+ state.expanded = state.expanded.filter((value) => value !== folderId)
+}
+function moveRelative(list: string[], source: string, target: string, after: boolean) {
+ const next = list.filter((id) => id !== source)
+ const index = next.indexOf(target)
+ if (index < 0) return list
+ next.splice(index + (after ? 1 : 0), 0, source)
+ return next
}
-
-function moveServerRelative(
- state: RailState,
- sourceId: string,
- targetId: string,
- after: boolean,
-): boolean {
- const sourceFolder = folderForServer(state, sourceId)
- const targetFolder = folderForServer(state, targetId)
- if (sourceFolder === targetFolder) {
- if (sourceFolder) {
- state.folders[sourceFolder] = moveRelative(
- state.folders[sourceFolder]!,
- sourceId,
- targetId,
- after,
- )
- } else {
- state.serverOrder = moveRelative(state.serverOrder, sourceId, targetId, after)
- }
- return true
- }
- removeServerFromFolder(state, sourceId)
- if (targetFolder) {
- state.folders[targetFolder] = moveRelative(
- [...state.folders[targetFolder]!, sourceId],
- sourceId,
- targetId,
- after,
- )
- state.expanded = unique([...state.expanded, targetFolder])
- return true
- }
- state.serverOrder = moveRelative(state.serverOrder, sourceId, targetId, after)
+function moveTopRelative(state: RailState, source: RailEntity, target: RailEntity, after: boolean) {
+ const entries = railTopLevel(state).filter((entry) => key(entry) !== key(source))
+ const index = entries.findIndex((entry) => key(entry) === key(target))
+ if (index < 0) return false
+ entries.splice(index + (after ? 1 : 0), 0, source)
+ state.topOrder = entries
return true
}
-function applyCombine(state: RailState, instruction: RailInstruction): string | null {
+function combine(state: RailState, instruction: Extract<RailInstruction, { operation: RailOperation }>): string | null {
if (instruction.source.kind !== "server") return "folders cannot combine"
- const sourceId = instruction.source.id
- const sourceFolder = folderForServer(state, sourceId)
- if (instruction.target.kind === "folder") {
- const targetItems = state.folders[instruction.target.id]
- if (!targetItems) return "target folder is missing"
- if (sourceFolder === instruction.target.id) return "server is already in target folder"
- removeServerFromFolder(state, sourceId)
- state.folders[instruction.target.id] = [...targetItems, sourceId]
- state.expanded = unique([...state.expanded, instruction.target.id])
- return null
- }
-
- const targetId = instruction.target.id
- const targetFolder = folderForServer(state, targetId)
+ const source = instruction.source.id
+ const sourceFolder = folderForServer(state, source)
+ const targetFolder = instruction.target.kind === "folder" ? instruction.target.id : folderForServer(state, instruction.target.id)
if (targetFolder) {
- if (sourceFolder === targetFolder) return "servers already share a folder"
- removeServerFromFolder(state, sourceId)
- const targetItems = state.folders[targetFolder]!
- const targetIndex = targetItems.indexOf(targetId)
- state.folders[targetFolder] = [...targetItems]
- state.folders[targetFolder]!.splice(targetIndex + 1, 0, sourceId)
- state.expanded = unique([...state.expanded, targetFolder])
+ if (!state.folders[targetFolder]) return "target folder is missing"
+ if (sourceFolder === targetFolder) {
+ if (instruction.target.kind !== "folder") return "server is already in target folder"
+ state.folders[targetFolder] = [...state.folders[targetFolder]!.filter((id) => id !== source), source]
+ return null
+ }
+ removeServerFromFolder(state, source)
+ const items = state.folders[targetFolder]!
+ const index = instruction.target.kind === "server" ? items.indexOf(instruction.target.id) + 1 : items.length
+ items.splice(index, 0, source)
return null
}
- if (sourceFolder) return "creating a folder requires two top-level servers"
- if (state.folderOrder.length >= MAX_SERVER_RAIL_FOLDERS) return "folder limit reached"
- if (!instruction.newFolderId || state.folders[instruction.newFolderId]) {
- return "new folder id is required"
- }
- state.folderOrder.push(instruction.newFolderId)
- state.folders[instruction.newFolderId] = [sourceId, targetId]
- state.expanded = unique([...state.expanded, instruction.newFolderId])
+ if (instruction.target.kind !== "server") return "target folder is missing"
+ removeServerFromFolder(state, source)
+ if (state.folderIds.length >= MAX_SERVER_RAIL_FOLDERS) return "folder limit reached"
+ const id = instruction.newFolderId
+ if (!id || state.folders[id]) return "new folder id is required"
+ const entries = railTopLevel(state).filter((entry) => !(entry.kind === "server" && entry.id === source))
+ const index = entries.findIndex((entry) => entry.kind === "server" && entry.id === instruction.target.id)
+ if (index < 0) return "target server is missing"
+ entries.splice(index, 1, { kind: "folder", id })
+ state.topOrder = entries
+ state.folderIds.push(id)
+ state.folders[id] = [instruction.target.id, source]
+ state.expanded = unique([...state.expanded, id])
return null
}
export function planRailPersistence(before: RailState, after: RailState): ServerRailCommand[] {
- if (samePersistedState(before, after)) return []
const commands: ServerRailCommand[] = []
- if (!sameArray(before.serverOrder, after.serverOrder)) {
- commands.push({ kind: "reorder-servers", serverIds: [...after.serverOrder] })
- }
- const added = after.folderOrder.filter((folderId) => !before.folderOrder.includes(folderId))
- for (const folderId of before.folderOrder) {
- const afterItems = after.folders[folderId]
- if (!afterItems) commands.push({ kind: "delete-folder", folderId })
- else if (!sameArray(before.folders[folderId] ?? [], afterItems)) {
- commands.push({ kind: "replace-folder-items", folderId, serverIds: [...afterItems] })
- }
- }
- if (added.length === 1) {
- const clientId = added[0]!
- commands.push({
- kind: "create-folder",
- clientId,
- name: "Group",
- serverIds: [...after.folders[clientId]!],
- })
- }
- const sameFolderSet = before.folderOrder.length === after.folderOrder.length
- && before.folderOrder.every((folderId) => after.folderOrder.includes(folderId))
- if (sameFolderSet && !sameArray(before.folderOrder, after.folderOrder)) {
- commands.push({ kind: "reorder-folders", folderIds: [...after.folderOrder] })
+ for (const id of before.folderIds) {
+ if (!after.folders[id]) commands.push({ kind: "delete-folder", folderId: id })
+ else if (!sameArray(before.folders[id] ?? [], after.folders[id]!)) commands.push({ kind: "replace-folder-items", folderId: id, serverIds: [...after.folders[id]!] })
}
+ for (const id of after.folderIds.filter((folderId) => !before.folders[folderId])) commands.push({ kind: "create-folder", clientId: id, name: "Group", serverIds: [...after.folders[id]!] })
+ const topOrder = railTopLevel(after)
+ if (!sameArray(railTopLevel(before).map(key), topOrder.map(key))) commands.push({ kind: "reorder-top-level", entries: topOrder })
return commands
}
-export function commitRailInstruction(
- before: RailState,
- instruction: RailInstruction,
-): RailCommitResult {
- if (railStateErrors(before).length > 0) {
- return { applied: false, state: before, reason: "invalid start state" }
- }
- if (
- instruction.source.kind === instruction.target.kind
- && instruction.source.id === instruction.target.id
- ) {
- return { applied: false, state: before, reason: "source equals target" }
- }
+export function commitRailInstruction(before: RailState, instruction: RailInstruction): RailCommitResult {
+ if (railStateErrors(before).length) return { applied: false, state: before, reason: "invalid start state" }
+ const { source, target } = instruction
+ if (source.kind === target.kind && source.id === target.id) return { applied: false, state: before, reason: "source equals target" }
+ const exists = source.kind === "server" ? before.serverIds.includes(source.id) : before.folderIds.includes(source.id)
+ if (!exists) return { applied: false, state: before, reason: "source is missing" }
const next = cloneRailState(before)
+ next.topOrder = railTopLevel(before)
let error: string | null = null
- if (instruction.operation === "combine") {
- error = applyCombine(next, instruction)
- } else if (instruction.source.kind === "folder" || instruction.target.kind === "folder") {
- if (instruction.source.kind !== "folder" || instruction.target.kind !== "folder") {
- error = "server and folder orders cannot interleave"
- } else if (!next.folderOrder.includes(instruction.source.id)
- || !next.folderOrder.includes(instruction.target.id)) {
- error = "folder is missing"
+ if (instruction.operation === "append") {
+ if (instruction.target.kind === "root") {
+ if (source.kind === "server") removeServerFromFolder(next, source.id)
+ next.topOrder = [...railTopLevel(next).filter((entry) => key(entry) !== key(source)), source]
+ } else if (source.kind !== "server") error = "folders cannot nest"
+ else if (!next.folders[instruction.target.id]) error = "target folder is missing"
+ else {
+ const id = instruction.target.id
+ if (folderForServer(next, source.id) === id) next.folders[id] = [...next.folders[id]!.filter((value) => value !== source.id), source.id]
+ else { removeServerFromFolder(next, source.id); next.folders[id]!.push(source.id) }
+ }
+ } else if (instruction.operation === "combine") error = combine(next, instruction)
+ else {
+ const targetFolder = instruction.target.kind === "server" ? folderForServer(next, target.id) : null
+ if (targetFolder) {
+ if (source.kind !== "server") error = "folders cannot nest"
+ else {
+ if (folderForServer(next, source.id) !== targetFolder) {
+ removeServerFromFolder(next, source.id)
+ next.folders[targetFolder]!.push(source.id)
+ }
+ next.folders[targetFolder] = moveRelative(next.folders[targetFolder]!, source.id, target.id, instruction.operation === "reorder-after")
+ }
} else {
- next.folderOrder = moveRelative(
- next.folderOrder,
- instruction.source.id,
- instruction.target.id,
- instruction.operation === "reorder-after",
- )
+ const targetIndex = railTopLevel(next).findIndex((entry) => key(entry) === key(instruction.target))
+ if (source.kind === "server") removeServerFromFolder(next, source.id)
+ if (targetIndex >= 0 && instruction.target.kind === "folder" && !next.folders[instruction.target.id]) {
+ const entries = railTopLevel(next).filter((entry) => key(entry) !== key(source))
+ entries.splice(targetIndex, 0, source)
+ next.topOrder = entries
+ } else if (!moveTopRelative(next, source, instruction.target, instruction.operation === "reorder-after")) error = "target is missing"
}
- } else if (!next.serverOrder.includes(instruction.source.id)
- || !next.serverOrder.includes(instruction.target.id)) {
- error = "server is missing"
- } else {
- moveServerRelative(
- next,
- instruction.source.id,
- instruction.target.id,
- instruction.operation === "reorder-after",
- )
}
if (error) return { applied: false, state: before, reason: error }
+ next.topOrder = railTopLevel(next)
const stateError = railStateErrors(next)[0]
if (stateError) return { applied: false, state: before, reason: stateError }
const commands = planRailPersistence(before, next)
- if (commands.length === 0) return { applied: false, state: before, reason: "instruction is a no-op" }
+ if (!commands.length) return { applied: false, state: before, reason: "instruction is a no-op" }
if (commands.length > 3) return { applied: false, state: before, reason: "instruction exceeds command budget" }
return { applied: true, state: next, commands }
}
-function previewInstruction(instruction: RailInstruction, state: RailState): RailInstruction {
- if (
- instruction.operation !== "combine"
- || instruction.source.kind !== "server"
- || instruction.target.kind !== "server"
- || instruction.newFolderId
- ) return instruction
- let suffix = 0
- let newFolderId = "__rail_preview_folder__"
- while (state.folders[newFolderId]) {
- suffix += 1
- newFolderId = `__rail_preview_folder_${suffix}__`
- }
- return { ...instruction, newFolderId }
-}
-
-export function railInstructionIsAvailable(
- state: RailState,
- instruction: RailInstruction,
-): boolean {
- return commitRailInstruction(state, previewInstruction(instruction, state)).applied
+export function railInstructionIsAvailable(state: RailState, instruction: RailInstruction) {
+ let id = "__rail_preview_folder__", suffix = 0
+ while (state.folders[id]) id = `__rail_preview_folder_${++suffix}__`
+ const preview = instruction.operation === "combine" && instruction.source.kind === "server" && instruction.target.kind === "server" && !instruction.newFolderId
+ ? { ...instruction, newFolderId: id }
+ : instruction
+ return commitRailInstruction(state, preview).applied
}
-
-export function railOperationAvailability(
- state: RailState,
- source: RailEntity | null,
- target: RailEntity,
-): RailOperationAvailability {
- if (!source) {
- return { "reorder-before": false, "reorder-after": false, combine: false }
- }
+export function railOperationAvailability(state: RailState, source: RailEntity | null, target: RailEntity): RailOperationAvailability {
return {
- "reorder-before": railInstructionIsAvailable(state, {
- operation: "reorder-before",
- source,
- target,
- }),
- "reorder-after": railInstructionIsAvailable(state, {
- operation: "reorder-after",
- source,
- target,
- }),
- combine: railInstructionIsAvailable(state, { operation: "combine", source, target }),
+ "reorder-before": !!source && railInstructionIsAvailable(state, { operation: "reorder-before", source, target }),
+ "reorder-after": !!source && railInstructionIsAvailable(state, { operation: "reorder-after", source, target }),
+ combine: !!source && railInstructionIsAvailable(state, { operation: "combine", source, target }),
}
}
-
-export function railMoveAnnouncement(
- instruction: RailInstruction,
- names: { servers: ReadonlyMap<string, string>; folders: ReadonlyMap<string, string> },
-): string {
- const source = instruction.source.kind === "server"
- ? names.servers.get(instruction.source.id) ?? "Server"
- : names.folders.get(instruction.source.id) ?? "Group"
- const target = instruction.target.kind === "server"
- ? names.servers.get(instruction.target.id) ?? "server"
- : names.folders.get(instruction.target.id) ?? "group"
- if (instruction.operation === "combine") return `${source} moved into ${target}`
- return `${source} moved ${instruction.operation === "reorder-before" ? "before" : "after"} ${target}`
+export function railMoveAnnouncement(instruction: RailInstruction, names: { servers: ReadonlyMap<string, string>; folders: ReadonlyMap<string, string> }): string {
+ const source = instruction.source.kind === "server" ? names.servers.get(instruction.source.id) ?? "Server" : names.folders.get(instruction.source.id) ?? "Group"
+ if (instruction.operation === "append") return `${source} moved to the end of ${instruction.target.kind === "root" ? "the server list" : names.folders.get(instruction.target.id) ?? "group"}`
+ const target = instruction.target.kind === "server" ? names.servers.get(instruction.target.id) ?? "server" : names.folders.get(instruction.target.id) ?? "group"
+ return instruction.operation === "combine" ? `${source} moved into ${target}` : `${source} moved ${instruction.operation === "reorder-before" ? "before" : "after"} ${target}`
}
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 8841edec3..045207a5f 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -23,12 +23,19 @@ export const tid = {
conversationResolutionPending: "community-conversation-resolution-pending",
messageRouteAlert: (messageId: string) => `community-message-route-alert-${messageId}`,
serverAdd: "community-server-add",
+ serverRailEnd: "community-server-rail-end",
+ serverRailDragPreview: "community-server-rail-drag-preview",
+ serverRailDragName: "community-server-rail-drag-name",
+ serverRailFolderEnd: (id: string) => `community-server-folder-end-${id}`,
+ serverRailFolderBefore: (id: string) => `community-server-folder-before-${id}`,
+ serverRailFolderAfter: (id: string) => `community-server-folder-after-${id}`,
serverRailScroll: "community-server-rail-scroll",
serverRailFolder: (id: string) => `community-server-folder-${id}`,
serverRailIndicator: (id: string) => `community-server-rail-indicator-${id}`,
serverRailFolderIndicator: (id: string) => `community-server-rail-folder-indicator-${id}`,
serverRailInsert: (id: string) => `community-server-rail-insert-${id}`,
serverRailInsertFolder: (id: string) => `community-server-rail-insert-folder-${id}`,
+ categoryHeader: (id: string) => `community-category-header-${id}`,
channelSidebarScroll: "community-channel-sidebar-scroll",
channelSidebarPending: (serverId: string) => `community-channel-sidebar-pending-${serverId}`,
messageHeaderLeadingLoading: "community-message-header-leading-loading",
diff --git a/src/web/src/lib/observability/coverage.test.ts b/src/web/src/lib/observability/coverage.test.ts
index 306839f9e..e7246279c 100644
--- a/src/web/src/lib/observability/coverage.test.ts
+++ b/src/web/src/lib/observability/coverage.test.ts
@@ -275,11 +275,6 @@ const facadeCoverage = [
"owner": "useRenameChannel",
"action": "channel.rename"
},
- {
- "file": "src/web/src/hooks/community/mutations/channels.ts",
- "owner": "useMoveChannel",
- "action": "channel.move"
- },
{
"file": "src/web/src/hooks/community/mutations/channels.ts",
"owner": "useDeleteChannel",
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index 75a1c323b..8497bc4c3 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -64,6 +64,8 @@ export const communityKeys = {
// ── Channel-scoped resources ────────────────────────────────────────────
channelMessages: (channelId: string) =>
[...communityKeys.all, "channel", channelId, "messages"] as const,
+ channelLatestMessage: (channelId: string) =>
+ [...communityKeys.all, "channel", channelId, "latest-message"] as const,
channelMessagesWindow: (channelId: string, initial: Extract<MessagesPageParam, { mode: "newest" | "anchor" | "since" }>, tag?: string | null) =>
initial.mode === "newest" && !tag ? communityKeys.channelMessages(channelId)
: [...communityKeys.channelMessages(channelId), "window", { ...initial, tag: tag ?? null }] as const,
diff --git a/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts b/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts
index ee68920ed..e648bafea 100644
--- a/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts
+++ b/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts
@@ -136,6 +136,7 @@ test("real bot avatars become unreadable after single delete and authenticated m
await route.continue()
})
await alice.page.reload({ waitUntil: "commit" })
+ await expect(alice.page.getByText(botName, { exact: true })).toHaveCount(1)
await expect(alice.page.getByText(botName, { exact: true })).toBeVisible()
const avatar = alice.page.locator(`img[src="${upload.url}"]`)
await expect(avatar).toHaveAttribute("data-remote-image-state", "pending")
@@ -154,6 +155,7 @@ test("real bot avatars become unreadable after single delete and authenticated m
failAvatar = false
const requestsBeforeReload = avatarRequests
await alice.page.reload({ waitUntil: "commit" })
+ await expect(alice.page.getByText(botName, { exact: true })).toHaveCount(1)
await expect(alice.page.getByText(botName, { exact: true })).toBeVisible()
await expect.poll(() => avatarRequests).toBeGreaterThan(requestsBeforeReload)
await expect(avatar).toHaveCount(1)
@@ -198,6 +200,7 @@ test("real bot avatars become unreadable after single delete and authenticated m
const cascadeUpload = await uploadAvatar(alice.page, cascadeBotId)
expect(cascadeUpload.status).toBe(200)
await alice.page.reload()
+ await expect(alice.page.getByText(cascadeBotName, { exact: true })).toHaveCount(1)
await expect(alice.page.getByText(cascadeBotName, { exact: true })).toBeVisible()
expect(await alice.page.evaluate(async (path) => (
await fetch(`${path}?before-cascade=${crypto.randomUUID()}`, { cache: "no-store" })
diff --git a/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts b/src/web/src/test/e2e-ui/37-server-rail-dnd.spec.ts
similarity index 85%
rename from src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts
rename to src/web/src/test/e2e-ui/37-server-rail-dnd.spec.ts
index 140fa26b9..ad88d2bcf 100644
--- a/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts
+++ b/src/web/src/test/e2e-ui/37-server-rail-dnd.spec.ts
@@ -93,11 +93,7 @@ async function dispatchTouchGesture(
await page.waitForTimeout(20)
if (holdMs > 0) await page.waitForTimeout(holdMs)
let sawDragging = false
- let sawPreview = false
- let sawFloatingPreview = false
- let sawFloatingPreviewFollowTouch = false
- let floatingPreviewKind: string | null = null
- let floatingPreviewSize: { width: number; height: number } | null = null
+ let sawFeedback = false
let capturedPreview = false
let currentEnd = end
for (let step = 1; step <= 8; step += 1) {
@@ -117,23 +113,10 @@ async function dispatchTouchGesture(
}
await dispatch("touchmove", currentPoint)
await page.waitForTimeout(20)
- const floatingPreview = page.locator("[data-rail-floating-preview]")
- if (await floatingPreview.count() === 1) {
- sawFloatingPreview = true
- floatingPreviewKind = await floatingPreview.getAttribute("data-rail-floating-preview")
- const box = await floatingPreview.boundingBox()
- if (box) {
- floatingPreviewSize = { width: box.width, height: box.height }
- sawFloatingPreviewFollowTouch ||= (
- Math.abs(box.x + box.width / 2 - currentPoint.x) <= 0.5
- && Math.abs(box.y + box.height / 2 - currentPoint.y) <= 0.5
- )
- }
- }
if (probe) {
sawDragging ||= await probe.source.getAttribute("data-dragging") === "true"
- sawPreview ||= await probe.target.getAttribute("data-rail-preview") !== null
- if (sawPreview && previewScreenshotPath && !capturedPreview) {
+ sawFeedback ||= await probe.target.evaluate((element) => !!element.closest("[data-rail-preview]"))
+ if (sawFeedback && previewScreenshotPath && !capturedPreview) {
capturedPreview = true
await page.screenshot({ path: previewScreenshotPath })
}
@@ -145,11 +128,7 @@ async function dispatchTouchGesture(
return {
events: await page.evaluate(() => Reflect.get(window, "__railTouchEvents") as string[]),
sawDragging,
- sawPreview,
- sawFloatingPreview,
- sawFloatingPreviewFollowTouch,
- floatingPreviewKind,
- floatingPreviewSize,
+ sawFeedback,
}
}
@@ -230,13 +209,7 @@ async function touchDrag(
targetRatio,
previewScreenshotPath,
)
- const expectedPreviewKind = sourceTestId?.startsWith(tid.serverRailFolder(""))
- ? "folder"
- : "server"
- expect(result.sawFloatingPreview).toBe(true)
- expect(result.sawFloatingPreviewFollowTouch).toBe(true)
- expect(result.floatingPreviewKind).toBe(expectedPreviewKind)
- expect(result.floatingPreviewSize).toEqual({ width: 40, height: 40 })
+ expect(result.sawDragging).toBe(true)
return { ...result, sourceTestId }
}
@@ -244,29 +217,21 @@ async function startStationaryTouch(page: Page, origin: Locator) {
const box = await origin.boundingBox()
if (!box) throw new Error("touch target is outside the viewport")
const point = { x: box.x + box.width / 2, y: box.y + box.height / 2 }
- const dispatch = (type: "touchstart" | "touchend") => origin.evaluate((element, args) => {
- const touch = new Touch({
- identifier: 2,
- target: element,
- clientX: args.point.x,
- clientY: args.point.y,
- screenX: args.point.x,
- screenY: args.point.y,
+ const session = await page.context().newCDPSession(page)
+ try {
+ await session.send("Input.dispatchTouchEvent", {
+ type: "touchStart",
+ touchPoints: [{ ...point, radiusX: 1, radiusY: 1, force: 1, id: 2 }],
})
- const allowed = element.dispatchEvent(new TouchEvent(args.type, {
- bubbles: true,
- cancelable: true,
- composed: true,
- touches: args.type === "touchend" ? [] : [touch],
- targetTouches: args.type === "touchend" ? [] : [touch],
- changedTouches: [touch],
- }))
- // Synthetic TouchEvents do not synthesize the browser's trailing click.
- // Mirror that default only when the production handler did not cancel it.
- if (args.type === "touchend" && allowed) (element as HTMLElement).click()
- }, { type, point })
- await dispatch("touchstart")
- return () => dispatch("touchend")
+ } catch (error) {
+ await session.detach()
+ throw error
+ }
+ return async () => {
+ try {
+ await session.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] })
+ } finally { await session.detach() }
+ }
}
async function expectTouchPatch(
@@ -287,6 +252,7 @@ async function expectTouchPatch(
expect((await response).status()).toBe(200)
expect((await reconcile).every((candidate) => candidate.status() === 200)).toBe(true)
if (sourceTestId) await expect(page.getByTestId(sourceTestId)).toBeFocused()
+ return (await response).json() as Promise<{ createdFolderIds: Record<string, string> }>
}
async function dragUntilNativeDrop(
@@ -426,7 +392,7 @@ test("first native Server tap is one root push with a stable handle and zero rai
await expectFirstNativeServerTap(warm.page, serverId, warmPatches)
})
-test("server rail keeps scroll separate from native, touch, and keyboard drag", async ({ caseActors, caseResources }, testInfo) => {
+test("server rail keeps scroll separate from React DnD native and touch drag", async ({ caseActors, caseResources }, testInfo) => {
test.setTimeout(150_000)
const actors = await caseActors(["alice"])
@@ -476,8 +442,8 @@ test("server rail keeps scroll separate from native, touch, and keyboard drag",
document.addEventListener(type, () => events.push(type), { capture: true })
}
})
- const sourceDraggable = source.locator("xpath=ancestor::*[@draggable='true'][1]")
- const targetDraggable = target.locator("xpath=ancestor::*[@draggable='true'][1]")
+ const sourceDraggable = source.locator("xpath=ancestor-or-self::*[@draggable='true'][1]")
+ const targetDraggable = target.locator("xpath=ancestor-or-self::*[@draggable='true'][1]")
await expect(sourceDraggable).toHaveCount(1)
await expect(targetDraggable).toHaveCount(1)
await dragUntilNativeDrop(page, sourceDraggable, targetDraggable, () => railRequests.length > 0)
@@ -487,7 +453,7 @@ test("server rail keeps scroll separate from native, touch, and keyboard drag",
await expect.poll(() => railRequests.length, { timeout: 10_000 }).toBe(1)
expect(railRequests).toHaveLength(1)
expect(railRequests[0]?.body).toMatchObject({
- commands: [{ kind: "reorder-servers" }],
+ commands: [{ kind: "reorder-top-level" }],
})
await expect.poll(() => railRequests[0]?.status).toBe(200)
@@ -566,7 +532,8 @@ test("server rail keeps scroll separate from native, touch, and keyboard drag",
expect(firstTouch.events).toContain("touchend")
expect(firstTouch.events).not.toContain("contextmenu")
expect(firstTouch.sawDragging).toBe(true)
- expect(firstTouch.sawPreview).toBe(true)
+ expect(firstTouch.sawFeedback).toBe(true)
+ await expect(page.locator("[data-rail-preview]")).toHaveCount(0)
const createResponse = await createResponsePromise
expect(createResponse.status()).toBe(200)
expect((await createReconcilePromise).every((response) => response.status() === 200)).toBe(true)
@@ -575,17 +542,20 @@ test("server rail keeps scroll separate from native, touch, and keyboard drag",
}
expect(railRequests).toHaveLength(2)
expect(railRequests[1]?.body).toMatchObject({
- commands: [{ kind: "create-folder", name: "Group", serverIds: [tail, swipeServer] }],
+ commands: [
+ { kind: "create-folder", name: "Group", serverIds: [swipeServer, tail] },
+ { kind: "reorder-top-level" },
+ ],
})
- const folderSelector = `[data-testid^="${tid.serverRailFolder("")}"]`
- const firstFolder = page.locator(folderSelector).first()
+ const createdFirst = await createResponse.json() as { createdFolderIds: Record<string, string> }
+ const firstFolder = page.getByTestId(tid.serverRailFolder(Object.values(createdFirst.createdFolderIds)[0]!))
await expect(firstFolder).toBeVisible()
await expectTouchPatch(page, () => touchDrag(
page,
page.getByTestId(tid.serverIcon(tail)),
page.getByTestId(tid.serverIcon(swipeServer)),
- 0.85,
+ 0.15,
))
expect(railRequests[2]?.body).toMatchObject({
commands: [{ kind: "replace-folder-items" }],
@@ -600,8 +570,8 @@ test("server rail keeps scroll separate from native, touch, and keyboard drag",
))
expect(railRequests[3]?.body).toMatchObject({
commands: [
- { kind: "reorder-servers" },
{ kind: "replace-folder-items" },
+ { kind: "reorder-top-level" },
],
})
@@ -611,19 +581,19 @@ test("server rail keeps scroll separate from native, touch, and keyboard drag",
firstFolder,
))
expect(railRequests[4]?.body).toMatchObject({
- commands: [{ kind: "replace-folder-items" }],
+ commands: [{ kind: "replace-folder-items" }, { kind: "reorder-top-level" }],
})
const secondGroupSource = overflowServers.at(-4)!
- await expectTouchPatch(page, () => touchDrag(
+ const createdSecond = await expectTouchPatch(page, () => touchDrag(
page,
page.getByTestId(tid.serverIcon(secondGroupSource)),
page.getByTestId(tid.serverIcon(nearbyTopLevel)),
))
expect(railRequests[5]?.body).toMatchObject({
- commands: [{ kind: "create-folder" }],
+ commands: [{ kind: "create-folder" }, { kind: "reorder-top-level" }],
})
- const secondFolder = page.locator(folderSelector).nth(1)
+ const secondFolder = page.getByTestId(tid.serverRailFolder(Object.values(createdSecond.createdFolderIds)[0]!))
await expect(secondFolder).toBeVisible()
await expectTouchPatch(page, () => touchDrag(
@@ -638,9 +608,19 @@ test("server rail keeps scroll separate from native, touch, and keyboard drag",
],
})
- await expectTouchPatch(page, () => touchDrag(page, secondFolder, firstFolder, 0.15))
+ const readFolderIds = async () => {
+ const response = await page.request.get("/api/community/users/me/server-folders")
+ expect(response.status()).toBe(200)
+ const body = await response.json() as { topOrder: Array<{ kind: "server" | "folder"; id: string }> }
+ return body.topOrder.filter((entry) => entry.kind === "folder").map((entry) => entry.id)
+ }
+ const firstFolderId = Object.values(createdFirst.createdFolderIds)[0]!
+ const secondFolderId = Object.values(createdSecond.createdFolderIds)[0]!
+ expect(await readFolderIds()).toEqual([secondFolderId, firstFolderId])
+ await expectTouchPatch(page, () => touchDrag(page, secondFolder, firstFolder, 0.85))
+ expect(await readFolderIds()).toEqual([firstFolderId, secondFolderId])
expect(railRequests[7]?.body).toMatchObject({
- commands: [{ kind: "reorder-folders" }],
+ commands: [{ kind: "reorder-top-level" }],
})
await expect(page.getByTestId(tid.serverIcon(tail))).toBeVisible()
await expect(page.getByTestId(tid.serverIcon(first))).toBeVisible()
@@ -658,14 +638,15 @@ test("server rail keeps scroll separate from native, touch, and keyboard drag",
})
})
const endLongPress = await startStationaryTouch(page, firstFolder)
- await page.waitForTimeout(700)
- await expect(firstFolder).not.toHaveAttribute("data-dragging", "true")
const stationaryFolderPreview = page.locator('[data-rail-floating-preview="folder"]')
- await expect(stationaryFolderPreview).toHaveCount(0)
- await expect(page.getByRole("menuitem", { name: "Ungroup" })).toHaveCount(0)
- await expect(page.getByRole("menuitem", { name: "Move…" })).toHaveCount(0)
- await expect(page.getByRole("menuitem", { name: "Create group" })).toHaveCount(0)
- await endLongPress()
+ try {
+ await page.waitForTimeout(700)
+ await expect(firstFolder).not.toHaveAttribute("data-dragging", "true")
+ await expect(stationaryFolderPreview).toHaveCount(0)
+ await expect(page.getByRole("menuitem", { name: "Ungroup" })).toHaveCount(0)
+ await expect(page.getByRole("menuitem", { name: "Move…" })).toHaveCount(0)
+ await expect(page.getByRole("menuitem", { name: "Create group" })).toHaveCount(0)
+ } finally { await endLongPress() }
await expect(stationaryFolderPreview).toHaveCount(0)
await expect.poll(() => page.evaluate(() => Reflect.get(window, "__railStationaryClicks")))
.toBe(1)
@@ -689,17 +670,15 @@ test("server rail keeps scroll separate from native, touch, and keyboard drag",
await expect(desktopComposer).toBeVisible()
await waitForElementMotion(desktopComposer)
await expect(firstFolder).toBeFocused()
- const darkKeyboardSource = page.getByTestId(tid.serverIcon(first))
- await darkKeyboardSource.focus()
+ const darkSource = page.getByTestId(tid.serverIcon(first))
+ await darkSource.focus()
+ const beforeKeyboard = railRequests.length
await page.keyboard.press("Space")
- await expect(darkKeyboardSource).toBeFocused()
- await expect(darkKeyboardSource).toHaveAttribute("data-dragging", "true")
- await page.keyboard.press("ArrowDown")
- const keyboardInsert = page.locator(`[data-testid^="${tid.serverRailInsert("")}"]`).first()
- await expect(keyboardInsert).toBeVisible()
- await page.screenshot({ path: testInfo.outputPath("server-rail-keyboard-preview-1280-dark.png") })
+ await expect(darkSource).not.toHaveAttribute("data-dragging", "true")
+ await expect(darkSource).not.toHaveAttribute("aria-keyshortcuts")
await page.keyboard.press("Escape")
- await expect(keyboardInsert).toHaveCount(0)
+ expect(railRequests).toHaveLength(beforeKeyboard)
+ await page.screenshot({ path: testInfo.outputPath("server-rail-native-1280-dark.png") })
await page.emulateMedia({ colorScheme: "light" })
await expect(page.locator("html")).not.toHaveClass(/dark/)
let releaseCommit!: () => void
@@ -717,27 +696,26 @@ test("server rail keeps scroll separate from native, touch, and keyboard drag",
response.request().method() === "PATCH" && new URL(response.url()).pathname === RAIL_ENDPOINT,
)
try {
- const keyboardSource = page.getByTestId(tid.serverIcon(first))
- await keyboardSource.focus()
- await page.keyboard.press("Space")
- await page.keyboard.press("ArrowDown")
- await expect(page.locator(`[data-testid^="${tid.serverRailInsert("")}"]`).first()).toBeVisible()
- await page.keyboard.press("Enter")
- await expect.poll(() => railRequests.length).toBe(9)
+ const beforePending = railRequests.length
+ expect(await readFolderIds()).toEqual([firstFolderId, secondFolderId])
+ await secondFolder.dragTo(firstFolder, { targetPosition: { x: 22, y: 4 } })
+ await expect.poll(() => railRequests.length).toBe(beforePending + 1)
const existingFolder = page.locator(`[data-testid^="${tid.serverRailFolder("")}"]`).first()
await existingFolder.click({ button: "right" })
await expect(page.getByRole("menuitem", { name: "Move…" })).toHaveCount(0)
await expect(page.getByRole("menuitem", { name: "Create group" })).toHaveCount(0)
- await page.getByRole("menuitem", { name: "Ungroup" }).click()
+ await expect(page.getByRole("menuitem", { name: "Ungroup" })).toHaveCount(0)
+ await firstFolder.dragTo(secondFolder, { targetPosition: { x: 22, y: 4 } })
await page.waitForTimeout(250)
- expect(railRequests).toHaveLength(9)
+ expect(railRequests).toHaveLength(beforePending + 1)
} finally {
releaseCommit()
}
expect((await pendingResponse).status()).toBe(200)
+ expect(await readFolderIds()).toEqual([secondFolderId, firstFolderId])
await page.unroute(`**${RAIL_ENDPOINT}`)
- await page.screenshot({ path: testInfo.outputPath("server-rail-keyboard-1280.png") })
+ await page.screenshot({ path: testInfo.outputPath("server-rail-native-1280.png") })
})
test("short server rail keeps Add adjacent and desktop geometry stable", async ({ caseActors }) => {
@@ -794,10 +772,11 @@ test("short server rail keeps Add adjacent and desktop geometry stable", async (
})
const endLongPress = await startStationaryTouch(page, onlyServer)
- await page.waitForTimeout(700)
- await expect(onlyServer).not.toHaveAttribute("data-dragging", "true")
- await expect(page.locator("[data-rail-floating-preview]")).toHaveCount(0)
- await endLongPress()
+ try {
+ await page.waitForTimeout(700)
+ await expect(onlyServer).not.toHaveAttribute("data-dragging", "true")
+ await expect(page.locator("[data-rail-floating-preview]")).toHaveCount(0)
+ } finally { await endLongPress() }
await expect.poll(() => page.evaluate(() => Reflect.get(window, "__railOnlyServerClicks")))
.toBe(1)
expect(new URL(page.url()).pathname).toBe(`/c/channels/${serverId}`)
diff --git a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
index d82df6664..2dc206e39 100644
--- a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
+++ b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
@@ -96,7 +96,7 @@ function expectStableScroller(before: ScrollerGeometry, after: ScrollerGeometry)
async function clickAuthoritativeOwnerChannelRow(page: Page, channelId: string): Promise<void> {
const row = page.getByTestId(tid.channelRow(channelId))
- await expect(row).toHaveAttribute("aria-disabled", "false", { timeout: 20_000 })
+ await expect(row).toBeEnabled({ timeout: 20_000 })
await row.evaluate((element) => (element as HTMLElement).click())
}
diff --git a/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
index 9cb33d2d9..2f19bd17a 100644
--- a/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
+++ b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
@@ -21,11 +21,9 @@ async function combineServers(page: Page, sourceId: string, targetId: string) {
await sourceButton.focus()
await targetButton.focus()
const source = sourceButton
- .locator("xpath=ancestor::*[@draggable='true'][1]")
const target = targetButton
- .locator("xpath=ancestor::*[@draggable='true'][1]")
- await expect(source).toHaveCount(1)
- await expect(target).toHaveCount(1)
+ await expect(source).toHaveAttribute("draggable", "true")
+ await expect(target).toHaveAttribute("draggable", "true")
const targetBox = await target.boundingBox()
if (!targetBox) throw new Error("server rail drag target is outside the viewport")
let responseStatus: number | null = null
@@ -136,7 +134,8 @@ test("server unread owns exact rail geometry, folder aggregation, read clear, an
await page.getByTestId(tid.serverIcon(foregroundServer)).focus()
await expectIndicatorHeight(backgroundIndicator, 10)
await folder.click()
- await expect(page.getByTestId(tid.serverIcon(backgroundServer))).toHaveCount(0)
+ await expect(folder).toHaveAttribute("aria-expanded", "false")
+ await expect(backgroundIcon).not.toBeInViewport()
await page.mouse.move(300, 300)
await page.getByTestId(tid.serverIcon(foregroundServer)).focus()
await expectIndicatorHeight(folderIndicator, 10)
@@ -149,7 +148,8 @@ test("server unread owns exact rail geometry, folder aggregation, read clear, an
await backgroundIcon.click()
await expectIndicatorHeight(backgroundIndicator, 32)
await folder.click()
- await expect(page.getByTestId(tid.serverIcon(backgroundServer))).toHaveCount(0)
+ await expect(folder).toHaveAttribute("aria-expanded", "false")
+ await expect(backgroundIcon).not.toBeInViewport()
await expectIndicatorHeight(folderIndicator, 32)
await folder.click()
await expect(backgroundIcon).toBeVisible()
@@ -172,7 +172,7 @@ test("server unread owns exact rail geometry, folder aggregation, read clear, an
await page.setViewportSize({ width: 390, height: 844 })
await page.getByRole("banner").getByRole("button", { name: "Back" }).click()
await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${foregroundServer}`)
- if (await backgroundIcon.count() === 0) {
+ if (await folder.getAttribute("aria-expanded") !== "true") {
await folder.click()
await expect(backgroundIcon).toBeVisible()
}
@@ -359,13 +359,14 @@ test("server unread owns exact rail geometry, folder aggregation, read clear, an
const beforeFolder = await flow.elementHandle()
expect(beforeFolder).not.toBeNull()
await folder.click()
- await expect(backgroundIcon).toHaveCount(0)
+ await expect(folder).toHaveAttribute("aria-expanded", "false")
+ await expect(backgroundIcon).not.toBeInViewport()
await sendMention(`Server folder update ${stamp}`)
- await expectPrimaryCount("folder-unmounted", 2)
- await capture("folder-unmounted", 2)
+ await expectPrimaryCount("folder-hidden", 2)
+ await capture("folder-hidden", 2)
await folder.click()
- await expectVisibleDigits("folder-remount", 2)
- expect(await flow.evaluate((element, prior) => element === prior, beforeFolder)).toBe(false)
+ await expectVisibleDigits("folder-reopen", 2)
+ expect(await flow.evaluate((element, prior) => element === prior, beforeFolder)).toBe(true)
})
diff --git a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
index de2d5d7fa..bf5027b88 100644
--- a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
+++ b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
@@ -89,13 +89,13 @@ function hasCorrelatedBundle(
})
}
-async function expectUnreadDot(row: ReturnType<Page["getByTestId"]>) {
+async function expectUnreadDot(row: ReturnType<Page["getByTestId"]>, height = "10px") {
await expect(row).toBeVisible({ timeout: 30_000 })
- await expect(row.locator("span.rounded-full.bg-primary")).toHaveCount(1)
+ await expect(row.locator('[data-slot="community-channel-unread-indicator"]')).toHaveCSS("height", height)
}
async function expectNoUnreadDot(row: ReturnType<Page["getByTestId"]>) {
- await expect(row.locator("span.rounded-full.bg-primary")).toHaveCount(0)
+ await expect(row.locator('[data-slot="community-channel-unread-indicator"]')).toHaveCSS("height", "0px")
}
async function readSeq(page: Page, channelId: string): Promise<number> {
@@ -370,7 +370,7 @@ test.setTimeout(180_000)
await gotoAfterUserWsAuth(page, `/c/channels/${backgroundServer}/${forumId}`)
await expect(page).toHaveURL(`/c/channels/${backgroundServer}/${forumId}`)
- await expectUnreadDot(page.getByTestId(tid.forumSidebarThread(forumChild)))
+ await expectUnreadDot(page.getByTestId(tid.forumSidebarThread(forumChild)), "4px")
await page.getByRole("button", { name: "Inbox", exact: true }).click()
await expect(page.getByTestId(tid.inboxUnreadChannel(unreadChannel))).toBeVisible()
await expect(page.getByTestId(tid.inboxUnreadChild(forumChild))).toBeVisible()
diff --git a/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts b/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts
index f68b2bff3..221f136b0 100644
--- a/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts
+++ b/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts
@@ -751,11 +751,11 @@ test.describe("desktop default User Bar width", () => {
)
const rowButton = activeBody.getByRole("button", { name: new RegExp(content) })
const row = rowButton.locator("..")
- const more = row.getByRole("button", { name: "More", exact: true })
+ const action = row.getByRole("button", { name: tab === "Mentions" ? "Mark mention as read" : "More", exact: true })
await expect(row).toHaveCount(1)
- await expect(more).toHaveCount(1)
+ await expect(action).toHaveCount(1)
await row.hover()
- await expect(more).toBeVisible()
+ await expect(action).toBeVisible()
}
const sample = await extension.evaluate((element, ids) => {
diff --git a/src/web/test-runtime/d1-bind-community.runtime.test.ts b/src/web/test-runtime/d1-bind-community.runtime.test.ts
index e69b1db62..1bc0b54c8 100644
--- a/src/web/test-runtime/d1-bind-community.runtime.test.ts
+++ b/src/web/test-runtime/d1-bind-community.runtime.test.ts
@@ -74,8 +74,8 @@ describe("community high-cardinality D1 queries", () => {
"INSERT INTO community_server (id, name, discriminator, owner_id, created_at) VALUES (?, ?, ?, ?, ?)",
).bind(serverId, `${prefix}-server-${index}`, String(index).padStart(4, "0"), userId, now),
runtimeEnv.DB.prepare(
- "INSERT INTO community_server_member (id, server_id, user_id, role, rail_order, joined_at) VALUES (?, ?, ?, 'owner', ?, ?)",
- ).bind(`${prefix}_member_${index}`, serverId, userId, index, now),
+ "INSERT INTO community_server_member (id, server_id, user_id, role, joined_at) VALUES (?, ?, ?, 'owner', ?)",
+ ).bind(`${prefix}_member_${index}`, serverId, userId, now),
runtimeEnv.DB.prepare(
"INSERT INTO community_channel (id, server_id, name, type, position, created_at) VALUES (?, ?, ?, 'text', 0, ?)",
).bind(`${prefix}_channel_${index}`, serverId, `general-${index}`, now),
@@ -114,8 +114,8 @@ describe("community high-cardinality D1 queries", () => {
"INSERT INTO user (id, email, name, discriminator) VALUES (?, ?, ?, ?)",
).bind(userId, `${userId}@example.com`, `Member ${index}`, String(2000 + index)),
runtimeEnv.DB.prepare(
- "INSERT INTO community_server_member (id, server_id, user_id, role, rail_order, joined_at) VALUES (?, ?, ?, 'member', ?, ?)",
- ).bind(`${prefix}_member_${index}`, serverId, userId, index, now),
+ "INSERT INTO community_server_member (id, server_id, user_id, role, joined_at) VALUES (?, ?, ?, 'member', ?)",
+ ).bind(`${prefix}_member_${index}`, serverId, userId, now),
runtimeEnv.DB.prepare(
"INSERT INTO community_category (id, server_id, name, position, private) VALUES (?, ?, ?, ?, 0)",
).bind(categoryIds[index], serverId, `Category ${index}`, index),
diff --git a/src/web/test-runtime/d1-sql-correctness.runtime.test.ts b/src/web/test-runtime/d1-sql-correctness.runtime.test.ts
index d0002d35e..0cc444ef6 100644
--- a/src/web/test-runtime/d1-sql-correctness.runtime.test.ts
+++ b/src/web/test-runtime/d1-sql-correctness.runtime.test.ts
@@ -279,7 +279,7 @@ describe("whole-statement SQL correctness on native D1", () => {
expect(result.ownerMember).toMatchObject({ userId: owner, userName: owner, userImage: null, userAvatarVersion: 0, userDiscriminator: "1710" });
expect(await graph(prefix)).toEqual([{ servers: 1, categories: 2, channels: 2, access: 1, members: 1 }]);
expect(await rows("SELECT c.name, k.name AS category, k.private FROM community_channel c JOIN community_category k ON k.id = c.category_id WHERE c.server_id = ? ORDER BY k.position", result.server.id)).toEqual([{ name: "all", category: "Public", private: 0 }, { name: "room", category: "Private", private: 1 }]);
- expect(await rows("SELECT role, rail_order FROM community_server_member WHERE server_id = ?", result.server.id)).toEqual([{ role: "owner", rail_order: 0 }]);
+ expect(await rows("SELECT role FROM community_server_member WHERE server_id = ?", result.server.id)).toEqual([{ role: "owner" }]);
});
it.each([2, 3, 4, 5, 6, 7])("rolls back every graph row after a native failure at seed step %i", async (step) => {
@@ -340,3 +340,59 @@ describe("whole-statement SQL correctness on native D1", () => {
expect(await graph(name)).toEqual([{ servers: 0, categories: 0, channels: 0, access: 0, members: 0 }]);
});
});
+
+async function seedChannelOrder(label: string) {
+ const f = await seedCommunity(label, 3);
+ const source = `${f.prefix}_source`, target = `${f.prefix}_target`;
+ await run("INSERT INTO community_category (id, server_id, name, private) VALUES (?, ?, 'Source', 1), (?, ?, 'Target', 1)", source, f.server, target, f.server);
+ for (const [position, id] of f.channels.entries()) await run("UPDATE community_channel SET category_id = ?, position = ? WHERE id = ?", position === 0 ? source : target, position, id);
+ await run("INSERT INTO community_channel_member (id, channel_id, user_id, relation, source, added_at) VALUES (?, ?, ?, 'access', 'added', ?)", `${f.prefix}_roster`, f.channels[0], f.viewer, baseline);
+ return { ...f, source, target };
+}
+
+async function channelOrderRows(serverId: string) {
+ return rows<{ id: string; categoryId: string | null; position: number }>("SELECT id, category_id AS categoryId, position FROM community_channel WHERE server_id = ? ORDER BY id", serverId);
+}
+
+describe("atomic channel category and order", () => {
+ it("persists exact insertion and category in one native batch without changing private rosters", async () => {
+ const f = await seedChannelOrder("order_atomic");
+ const before = await rows("SELECT * FROM community_channel_member WHERE user_id = ?", f.viewer);
+ const { db, record } = recordedDb("channel-order-atomic");
+ const order = [f.channels[1], f.channels[0], f.channels[2]];
+ await queries.communityChannel.reorderChannels(db, f.server, order, { channelId: f.channels[0], categoryId: f.target });
+ expect(record.batches).toEqual([3]);
+ const after = await channelOrderRows(f.server);
+ expect([...after].sort((a, b) => a.position - b.position).map((channel) => channel.id)).toEqual(order);
+ expect(after.every((channel) => channel.categoryId === f.target)).toBe(true);
+ expect(await rows("SELECT * FROM community_channel_member WHERE user_id = ?", f.viewer)).toEqual(before);
+ });
+
+ it("rolls back category and every position when a later statement fails", async () => {
+ const f = await seedChannelOrder("order_rollback");
+ const before = await channelOrderRows(f.server);
+ const roster = await rows("SELECT * FROM community_channel_member WHERE user_id = ?", f.viewer);
+ const trigger = `${f.prefix}_trigger`;
+ triggers.push(trigger);
+ await run(`CREATE TRIGGER ${trigger} BEFORE UPDATE OF position ON community_channel WHEN OLD.id = '${f.channels[2]}' BEGIN SELECT RAISE(ABORT, 'order rejected'); END`);
+ const { db, record } = recordedDb("channel-order-rollback");
+ await expect(queries.communityChannel.reorderChannels(db, f.server, [f.channels[1], f.channels[0], f.channels[2]], { channelId: f.channels[0], categoryId: f.target })).rejects.toThrow("order rejected");
+ expect(record.batches).toEqual([3]);
+ expect(await channelOrderRows(f.server)).toEqual(before);
+ expect(await rows("SELECT * FROM community_channel_member WHERE user_id = ?", f.viewer)).toEqual(roster);
+ });
+
+ it("scopes root reads and writes before accepting opaque channel identities", async () => {
+ const f = await seedCommunity("order_scope", 125), other = await seedCommunity("order_foreign", 1);
+ const child = `${f.prefix}_child`;
+ await run("INSERT INTO community_channel (id, server_id, name, type, parent_channel_id, position, created_at) VALUES (?, ?, 'child', 'thread', ?, 10, ?)", child, f.server, f.channels[0], baseline);
+ const { db } = recordedDb("channel-order-scope");
+ const actual = await queries.communityChannel.getServerRootChannelsByIds(db, f.server, [...f.channels, other.channels[0], child]);
+ expect(actual.map((channel) => channel.id).sort()).toEqual([...f.channels].sort());
+ const foreignBefore = await channelOrderRows(other.server);
+ await queries.communityChannel.reorderChannels(db, f.server, [other.channels[0], f.channels[0], child]);
+ expect(await channelOrderRows(other.server)).toEqual(foreignBefore);
+ expect((await channelOrderRows(f.server)).find((channel) => channel.id === child)?.position).toBe(10);
+ expect((await channelOrderRows(f.server)).find((channel) => channel.id === f.channels[0])?.position).toBe(1);
+ });
+});
diff --git a/src/ws-do/src/community-browser-event-ingress.test.ts b/src/ws-do/src/community-browser-event-ingress.test.ts
index 74b19b9fd..ede330568 100644
--- a/src/ws-do/src/community-browser-event-ingress.test.ts
+++ b/src/ws-do/src/community-browser-event-ingress.test.ts
@@ -69,9 +69,9 @@ function worstEscapingTarget(index: number) {
}
describe("community browser event ingress", () => {
- it("normalizes all 47 current fixtures without a contract version field", () => {
+ it("normalizes all 48 current fixtures without a contract version field", () => {
const fixtures = Object.values(communityWsEventFixtures)
- expect(fixtures).toHaveLength(47)
+ expect(fixtures).toHaveLength(48)
for (const fixture of fixtures) {
const normalized = normalizeCommunityBrowserEvent(fixture)
expect(normalized).toMatchObject({ ok: true, event: fixture, envelope: fixture })
@@ -83,8 +83,9 @@ describe("community browser event ingress", () => {
it("rejects every required-field corruption and representative invalid families", () => {
for (const [type, fixture] of Object.entries(communityWsEventFixtures)) {
+ const path = requiredFixturePaths[type as CommunityWsEvent["type"]]
expect(normalizeCommunityBrowserEvent(
- corruptRequiredField(fixture, requiredFixturePaths[type as CommunityWsEvent["type"]]),
+ path.length ? corruptRequiredField(fixture, path) : { ...fixture, entries: [] },
)).toMatchObject({ ok: false, reason: "invalid-payload" })
}
expect(normalizeCommunityBrowserEvent({ type: "task.updated" })).toMatchObject({ reason: "wrong-family" })
diff --git a/src/ws-do/src/community-content-access.ts b/src/ws-do/src/community-content-access.ts
index 5b1af59b8..b148fb667 100644
--- a/src/ws-do/src/community-content-access.ts
+++ b/src/ws-do/src/community-content-access.ts
@@ -26,6 +26,7 @@ export const communityContentAccessKinds = {
"community:channel.membership.change": "control",
"community:member.join": "control",
"community:server.update": "control",
+ "community:server_rail.changed": "control",
"community:channel.reorder": "control",
"community:category.create": "control",
"community:category.update": "control",