Compare commits

..

26 Commits

Author SHA1 Message Date
Kevin Puig
f18d192e5b 30000 2025-09-28 10:57:25 -04:00
Kevin Puig
8fcc775c66 refactor refetch and stale time 2025-09-28 10:47:29 -04:00
Kevin Puig
ac5f6ed680 payload formatted 2025-09-28 10:26:04 -04:00
Kevin Puig
e1a7257137 qwertyu 2025-09-28 10:08:43 -04:00
bdc448c193 voip: initial test run of store for managing socket connections 2025-09-28 10:05:11 -04:00
a2fb529911 Merge pull request #11 from k-puig/feature/events
socket set up
2025-09-28 08:37:50 -04:00
67d041e287 Merge branch 'main' of https://github.com/k-puig/shellhacks-2025 2025-09-28 08:34:47 -04:00
Kevin Puig
4cc6f4841c Merge pull request #10 from k-puig/feature/webrtc-voice
Feature/webrtc voice
2025-09-28 08:33:23 -04:00
Kevin Puig
afd2454674 rtc works 2025-09-28 08:24:26 -04:00
83e813a950 socket set up 2025-09-28 08:02:47 -04:00
a5e7fa4bc6 sad 2025-09-28 07:46:11 -04:00
Kevin Puig
5a5afcec32 skeletons of fun 2025-09-28 06:14:22 -04:00
Kevin Puig
d55049dfc4 sdfgh 2025-09-28 06:06:44 -04:00
af8371ed84 halfway commit to allow collaboration 2025-09-28 05:58:29 -04:00
Kevin Puig
7c5d0a4bad Handle disconnect (willful and otherwise) 2025-09-28 05:58:06 -04:00
Kevin Puig
226ee3f998 Join voice channel with sockets 2025-09-28 05:39:05 -04:00
Kevin Puig
69b03ecc61 Merge pull request #8 from k-puig/feature/websockets
Feature/websockets
2025-09-28 03:19:43 -04:00
Kevin Puig
b3e24f4493 pretty + socket separation 2025-09-28 03:18:11 -04:00
Kevin Puig
460991f2ae socket.io work!!! 2025-09-28 03:11:34 -04:00
PrimarchPaul
4adcf81004 nuked all realtime code 2025-09-28 02:10:41 -04:00
b79d3ac2cf auth: update server authentication 2025-09-28 01:58:59 -04:00
Kevin Puig
3bffb87d90 Merge pull request #7 from k-puig/feature/websockets
feat: completed messagetochannel endpoint
2025-09-28 01:49:36 -04:00
PrimarchPaul
de827ad441 oops, forgot to mount the routes 2025-09-28 01:49:24 -04:00
PrimarchPaul
6ef53fd964 feat: completed messagetochannel endpoint 2025-09-28 01:45:43 -04:00
Paul R
36a04de084 Merge pull request #6 from k-puig/feature/websockets
feat: send message to channel event
2025-09-28 00:44:02 -04:00
PrimarchPaul
db9a9a5d13 feat: send message to channel event 2025-09-28 00:41:42 -04:00
57 changed files with 5542 additions and 1762 deletions

1
.gitignore vendored
View File

@@ -137,3 +137,4 @@ dist
# Vite logs files
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
**/.helix

View File

@@ -18,6 +18,7 @@
"@tailwindcss/vite": "^4.1.13",
"@tanstack/react-query": "^5.90.2",
"@tanstack/react-query-devtools": "^5.90.2",
"bcrypt": "^6.0.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
@@ -28,15 +29,19 @@
"react-markdown": "^10.1.0",
"react-router": "^7.9.3",
"react-syntax-highlighter": "^15.6.6",
"socket.io-client": "^4.8.1",
"sonner": "^2.0.7",
"tailwind-merge": "^3.3.1",
"tailwindcss": "^4.1.13",
"zustand": "^5.0.8",
},
"devDependencies": {
"@types/bcrypt": "^6.0.0",
"@types/bun": "^1.2.22",
"@types/react": "^18.2.64",
"@types/react-dom": "^18.2.21",
"@types/react-syntax-highlighter": "^15.5.13",
"@types/socket.io-client": "^3.0.0",
"@typescript-eslint/eslint-plugin": "^7.1.1",
"@typescript-eslint/parser": "^7.1.1",
"@vitejs/plugin-react": "^4.2.1",
@@ -328,6 +333,8 @@
"@sindresorhus/is": ["@sindresorhus/is@4.6.0", "", {}, "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw=="],
"@socket.io/component-emitter": ["@socket.io/component-emitter@3.1.2", "", {}, "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA=="],
"@szmarczak/http-timer": ["@szmarczak/http-timer@4.0.6", "", { "dependencies": { "defer-to-connect": "^2.0.0" } }, "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w=="],
"@tailwindcss/node": ["@tailwindcss/node@4.1.13", "", { "dependencies": { "@jridgewell/remapping": "^2.3.4", "enhanced-resolve": "^5.18.3", "jiti": "^2.5.1", "lightningcss": "1.30.1", "magic-string": "^0.30.18", "source-map-js": "^1.2.1", "tailwindcss": "4.1.13" } }, "sha512-eq3ouolC1oEFOAvOMOBAmfCIqZBJuvWvvYWh5h5iOYfe1HFC6+GZ6EIL0JdM3/niGRJmnrOc+8gl9/HGUaaptw=="],
@@ -378,6 +385,10 @@
"@types/babel__traverse": ["@types/babel__traverse@7.28.0", "", { "dependencies": { "@babel/types": "^7.28.2" } }, "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q=="],
"@types/bcrypt": ["@types/bcrypt@6.0.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-/oJGukuH3D2+D+3H4JWLaAsJ/ji86dhRidzZ/Od7H/i8g+aCmvkeCc6Ni/f9uxGLSQVCRZkX2/lqEFG2BvWtlQ=="],
"@types/bun": ["@types/bun@1.2.22", "", { "dependencies": { "bun-types": "1.2.22" } }, "sha512-5A/KrKos2ZcN0c6ljRSOa1fYIyCKhZfIVYeuyb4snnvomnpFqC0tTsEkdqNxbAgExV384OETQ//WAjl3XbYqQA=="],
"@types/cacheable-request": ["@types/cacheable-request@6.0.3", "", { "dependencies": { "@types/http-cache-semantics": "*", "@types/keyv": "^3.1.4", "@types/node": "*", "@types/responselike": "^1.0.0" } }, "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw=="],
"@types/debug": ["@types/debug@4.1.12", "", { "dependencies": { "@types/ms": "*" } }, "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ=="],
@@ -412,6 +423,8 @@
"@types/responselike": ["@types/responselike@1.0.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw=="],
"@types/socket.io-client": ["@types/socket.io-client@3.0.0", "", { "dependencies": { "socket.io-client": "*" } }, "sha512-s+IPvFoEIjKA3RdJz/Z2dGR4gLgysKi8owcnrVwNjgvc01Lk68LJDDsG2GRqegFITcxmvCMYM7bhMpwEMlHmDg=="],
"@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="],
"@types/verror": ["@types/verror@1.10.11", "", {}, "sha512-RlDm9K7+o5stv0Co8i8ZRGxDbrTxhJtgjqjFyVh/tXQyl/rYtTKlnTvZ88oSTeYREWurwx20Js4kTuKCsFkUtg=="],
@@ -488,6 +501,8 @@
"baseline-browser-mapping": ["baseline-browser-mapping@2.8.7", "", { "bin": { "baseline-browser-mapping": "dist/cli.js" } }, "sha512-bxxN2M3a4d1CRoQC//IqsR5XrLh0IJ8TCv2x6Y9N0nckNz/rTjZB3//GGscZziZOxmjP55rzxg/ze7usFI9FqQ=="],
"bcrypt": ["bcrypt@6.0.0", "", { "dependencies": { "node-addon-api": "^8.3.0", "node-gyp-build": "^4.8.4" } }, "sha512-cU8v/EGSrnH+HnxV2z0J7/blxH8gq7Xh2JFT6Aroax7UohdmiJJlxApMxtKfuI7z68NvvVcmR78k2LbT6efhRg=="],
"bl": ["bl@4.1.0", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
"bluebird": ["bluebird@3.7.2", "", {}, "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg=="],
@@ -514,6 +529,8 @@
"builder-util-runtime": ["builder-util-runtime@9.2.4", "", { "dependencies": { "debug": "^4.3.4", "sax": "^1.2.4" } }, "sha512-upp+biKpN/XZMLim7aguUyW8s0FUpDvOtK6sbanMFDAMBzpHDqdhgVYm6zc9HJ6nWo7u2Lxk60i2M6Jd3aiNrA=="],
"bun-types": ["bun-types@1.2.22", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-hwaAu8tct/Zn6Zft4U9BsZcXkYomzpHJX28ofvx7k0Zz2HNz54n1n+tDgxoWFGB4PcFvJXJQloPhaV2eP3Q6EA=="],
"cacheable-lookup": ["cacheable-lookup@5.0.4", "", {}, "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA=="],
"cacheable-request": ["cacheable-request@7.0.4", "", { "dependencies": { "clone-response": "^1.0.2", "get-stream": "^5.1.0", "http-cache-semantics": "^4.0.0", "keyv": "^4.0.0", "lowercase-keys": "^2.0.0", "normalize-url": "^6.0.1", "responselike": "^2.0.0" } }, "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg=="],
@@ -648,6 +665,10 @@
"end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
"engine.io-client": ["engine.io-client@6.6.3", "", { "dependencies": { "@socket.io/component-emitter": "~3.1.0", "debug": "~4.3.1", "engine.io-parser": "~5.2.1", "ws": "~8.17.1", "xmlhttprequest-ssl": "~2.1.1" } }, "sha512-T0iLjnyNWahNyv/lcjS2y4oE358tVS/SYQNxYXGAJ9/GLgH4VCvOQ/mhTjqU88mLZCQgiG8RIegFHYCdVC+j5w=="],
"engine.io-parser": ["engine.io-parser@5.2.3", "", {}, "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q=="],
"enhanced-resolve": ["enhanced-resolve@5.18.3", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.2.0" } }, "sha512-d4lC8xfavMeBjzGr2vECC3fsGXziXZQyJxD868h2M/mBI3PwAuODxAkLkq5HYuvrPYcUtiLzsTo8U3PgX3Ocww=="],
"env-paths": ["env-paths@2.2.1", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="],
@@ -1030,7 +1051,9 @@
"next-themes": ["next-themes@0.4.6", "", { "peerDependencies": { "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" } }, "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA=="],
"node-addon-api": ["node-addon-api@1.7.2", "", {}, "sha512-ibPK3iA+vaY1eEjESkQkM0BbCqFOaZMiXRTtdB0u7b4djtY6JnsjvPdUHVMg6xQt3B8fpTTWHI9A+ADjM9frzg=="],
"node-addon-api": ["node-addon-api@8.5.0", "", {}, "sha512-/bRZty2mXUIFY/xU5HLvveNHlswNJej+RnxBjOMkidWfwZzgTbPG1E3K5TOxRLOR+5hX7bSofy8yf1hZevMS8A=="],
"node-gyp-build": ["node-gyp-build@4.8.4", "", { "bin": { "node-gyp-build": "bin.js", "node-gyp-build-optional": "optional.js", "node-gyp-build-test": "build-test.js" } }, "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ=="],
"node-releases": ["node-releases@2.0.21", "", {}, "sha512-5b0pgg78U3hwXkCM8Z9b2FJdPZlr9Psr9V2gQPESdGHqbntyFJKFW4r5TeWGFzafGY3hzs1JC62VEQMbl1JFkw=="],
@@ -1178,6 +1201,10 @@
"smart-buffer": ["smart-buffer@4.2.0", "", {}, "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg=="],
"socket.io-client": ["socket.io-client@4.8.1", "", { "dependencies": { "@socket.io/component-emitter": "~3.1.0", "debug": "~4.3.2", "engine.io-client": "~6.6.1", "socket.io-parser": "~4.2.4" } }, "sha512-hJVXfu3E28NmzGk8o1sHhN3om52tRvwYeidbj7xKy2eIIse5IoKX3USlS6Tqt3BHAtflLIkCQBkzVrEEfWUyYQ=="],
"socket.io-parser": ["socket.io-parser@4.2.4", "", { "dependencies": { "@socket.io/component-emitter": "~3.1.0", "debug": "~4.3.1" } }, "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew=="],
"sonner": ["sonner@2.0.7", "", { "peerDependencies": { "react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc", "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc" } }, "sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w=="],
"source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
@@ -1304,8 +1331,12 @@
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
"ws": ["ws@8.17.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ=="],
"xmlbuilder": ["xmlbuilder@15.1.1", "", {}, "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg=="],
"xmlhttprequest-ssl": ["xmlhttprequest-ssl@2.1.2", "", {}, "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ=="],
"xtend": ["xtend@4.0.2", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="],
"y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
@@ -1378,6 +1409,8 @@
"decode-named-character-reference/character-entities": ["character-entities@2.0.2", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="],
"engine.io-client/debug": ["debug@4.3.7", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ=="],
"fast-glob/glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
"filelist/minimatch": ["minimatch@5.1.6", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g=="],
@@ -1398,6 +1431,8 @@
"hosted-git-info/lru-cache": ["lru-cache@6.0.0", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA=="],
"iconv-corefoundation/node-addon-api": ["node-addon-api@1.7.2", "", {}, "sha512-ibPK3iA+vaY1eEjESkQkM0BbCqFOaZMiXRTtdB0u7b4djtY6JnsjvPdUHVMg6xQt3B8fpTTWHI9A+ADjM9frzg=="],
"lazystream/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"lru-cache/yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
@@ -1418,6 +1453,10 @@
"serialize-error/type-fest": ["type-fest@0.13.1", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
"socket.io-client/debug": ["debug@4.3.7", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ=="],
"socket.io-parser/debug": ["debug@4.3.7", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ=="],
"string_decoder/safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
"stringify-entities/character-entities-legacy": ["character-entities-legacy@3.0.0", "", {}, "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ=="],

View File

@@ -24,6 +24,7 @@
"@tailwindcss/vite": "^4.1.13",
"@tanstack/react-query": "^5.90.2",
"@tanstack/react-query-devtools": "^5.90.2",
"bcrypt": "^6.0.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
@@ -34,15 +35,19 @@
"react-markdown": "^10.1.0",
"react-router": "^7.9.3",
"react-syntax-highlighter": "^15.6.6",
"socket.io-client": "^4.8.1",
"sonner": "^2.0.7",
"tailwind-merge": "^3.3.1",
"tailwindcss": "^4.1.13",
"zustand": "^5.0.8"
},
"devDependencies": {
"@types/bcrypt": "^6.0.0",
"@types/bun": "^1.2.22",
"@types/react": "^18.2.64",
"@types/react-dom": "^18.2.21",
"@types/react-syntax-highlighter": "^15.5.13",
"@types/socket.io-client": "^3.0.0",
"@typescript-eslint/eslint-plugin": "^7.1.1",
"@typescript-eslint/parser": "^7.1.1",
"@vitejs/plugin-react": "^4.2.1",

View File

@@ -1,6 +1,6 @@
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import React, { useEffect, useRef, useState } from "react";
import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router";
import { QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { Toaster } from "@/components/ui/sonner";
@@ -10,34 +10,25 @@ import LoginPage from "@/pages/LoginPage";
import ChatPage from "@/pages/ChatPage";
import SettingsPage from "@/pages/SettingsPage";
import NotFoundPage from "@/pages/NotFoundPage";
import { useVoiceStore } from "@/stores/voiceStore";
// import { useAuthStore } from "@/stores/authStore";
// import { useUiStore } from "@/stores/uiStore";
import { queryClient } from "@/lib/api-client";
import { useAuthStore } from "@/stores/authStore";
import ErrorBoundary from "@/components/common/ErrorBoundary";
import { Home } from "lucide-react";
// Create a client
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60 * 5, // 5 minutes
refetchOnWindowFocus: false,
retry: (failureCount, error: any) => {
if (error?.status === 401) return false;
return failureCount < 3;
},
},
},
});
import { Socket } from "socket.io-client";
// Protected Route wrapper
const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
// const { isAuthenticated } = useAuthStore();
// if (!isAuthenticated) {
// return <Navigate to="/login" replace />;
// }
const { isAuthenticated } = useAuthStore();
// Enable this when you want to enforce authentication
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return <>{children}</>;
};
@@ -61,7 +52,16 @@ const HomePage: React.FC = () => {
);
};
function App() {
function App(props: { socket: Socket }) {
const initVoiceStore = useVoiceStore((state) => state.init);
useEffect(() => {
initVoiceStore(props.socket);
return () => {
useVoiceStore.getState().cleanup();
};
}, [props.socket, initVoiceStore]);
return (
<ErrorBoundary>
<QueryClientProvider client={queryClient}>

View File

@@ -0,0 +1,108 @@
import React from "react";
import { Hash, Volume2 } from "lucide-react";
import { useNavigate, useParams } from "react-router";
import { Channel } from "@/lib/api-client";
import { useVoiceStore } from "@/stores/voiceStore";
import { useInstanceMembers } from "@/hooks/useServers";
import { useAuthStore } from "@/stores/authStore";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
interface ChannelItemProps {
channel: Channel;
}
const ChannelItem: React.FC<ChannelItemProps> = ({ channel }) => {
const { instanceId, channelId: activeChannelId } = useParams();
const navigate = useNavigate();
// Voice store hooks
const {
joinChannel,
leaveChannel,
activeVoiceChannelId,
remoteStreams,
localStream,
} = useVoiceStore();
// Data hooks
const { data: members } = useInstanceMembers(instanceId);
const { user: currentUser, token } = useAuthStore(); // Get token from auth store
const isConnectedToThisChannel = activeVoiceChannelId === channel.id;
const isActive = activeChannelId === channel.id;
const handleChannelClick = () => {
if (channel.type === "text") {
navigate(`/channels/${instanceId}/${channel.id}`);
} else if (channel.type === "voice") {
if (isConnectedToThisChannel) {
leaveChannel();
} else if (currentUser && token) {
console.log({
channelId: channel.id,
currentUser: currentUser.id,
token: token,
});
joinChannel(channel.id, currentUser.id, token);
}
}
};
const Icon = channel.type === "voice" ? Volume2 : Hash;
const connectedUserIds = Array.from(remoteStreams.keys());
return (
<div>
<button
onClick={handleChannelClick}
className={`w-full flex items-center p-1.5 rounded-md text-left transition-colors ${
isActive || isConnectedToThisChannel
? "bg-concord-secondary text-concord-primary"
: "text-concord-secondary hover:bg-concord-secondary/50 hover:text-concord-primary"
}`}
>
<Icon className="w-5 h-5 mr-2 flex-shrink-0" />
<span className="truncate flex-1">{channel.name}</span>
</button>
{/* Render connected users for this voice channel */}
{isConnectedToThisChannel && (
<div className="pl-4 mt-1 space-y-1">
{/* Current User */}
{localStream && currentUser && (
<div className="flex items-center p-1">
<Avatar className="h-6 w-6">
<AvatarImage src={currentUser.picture || ""} />
<AvatarFallback>
{currentUser.username.slice(0, 2)}
</AvatarFallback>
</Avatar>
<span className="ml-2 text-sm text-concord-primary">
{currentUser.nickname || currentUser.username}
</span>
</div>
)}
{/* Remote Users */}
{connectedUserIds.map((userId) => {
const member = members?.find((m) => m.id === userId);
if (!member) return null;
return (
<div key={userId} className="flex items-center p-1">
<Avatar className="h-6 w-6">
<AvatarImage src={member.picture || ""} />
<AvatarFallback>{member.username.slice(0, 2)}</AvatarFallback>
</Avatar>
<span className="ml-2 text-sm text-concord-primary">
{member.nickname || member.username}
</span>
</div>
);
})}
</div>
)}
</div>
);
};
export default ChannelItem;

View File

@@ -1,13 +1,6 @@
import React, { useState } from "react";
import { useNavigate, useParams } from "react-router";
import {
Hash,
Volume2,
ChevronDown,
ChevronRight,
Plus,
Edit,
} from "lucide-react";
import { ChevronDown, ChevronRight, Plus, Edit } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@@ -18,35 +11,7 @@ import {
} from "@/components/ui/dropdown-menu";
import { CategoryWithChannels } from "@/types/api";
import { Channel } from "@/types/database";
interface ChannelItemProps {
channel: Channel;
isActive: boolean;
onClick: () => void;
}
const ChannelItem: React.FC<ChannelItemProps> = ({
channel,
isActive,
onClick,
}) => {
const Icon = channel.type === "voice" ? Volume2 : Hash;
return (
<Button
variant="ghost"
className={`w-full justify-start px-2 py-2 h-8 text-left font-medium p-3 rounded-lg transition-all ${
isActive
? "border-primary bg-primary/10 border-2 "
: "hover:border-primary/50"
}`}
onClick={onClick}
>
<Icon size={16} className="mr-2 flex-shrink-0" />
<span className="truncate">{channel.name}</span>
</Button>
);
};
import ChannelItem from "@/components/channel/ChannelItem";
interface CategoryHeaderProps {
category: CategoryWithChannels;
@@ -110,18 +75,11 @@ interface ChannelListProps {
}
const ChannelList: React.FC<ChannelListProps> = ({ categories }) => {
const navigate = useNavigate();
const { instanceId, channelId } = useParams();
// Track expanded categories
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(
new Set(categories.map((cat) => cat.id)), // Start with all expanded
);
const handleChannelClick = (channel: Channel) => {
navigate(`/channels/${instanceId}/${channel.id}`);
};
const toggleCategory = (categoryId: string) => {
setExpandedCategories((prev) => {
const newSet = new Set(prev);
@@ -164,12 +122,7 @@ const ChannelList: React.FC<ChannelListProps> = ({ categories }) => {
{category.channels
.sort((a, b) => a.position - b.position)
.map((channel) => (
<ChannelItem
key={channel.id}
channel={channel}
isActive={channelId === channel.id}
onClick={() => handleChannelClick(channel)}
/>
<ChannelItem key={channel.id} channel={channel} />
))}
</div>
)}

View File

@@ -0,0 +1,276 @@
import * as React from "react";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
// Basic dropdown styles
const dropdownStyles = {
content: `
min-w-[220px]
bg-white dark:bg-gray-800
border border-gray-200 dark:border-gray-700
rounded-md
p-1
shadow-lg
z-50
animate-in
fade-in-80
data-[state=open]:animate-in
data-[state=closed]:animate-out
data-[state=closed]:fade-out-0
data-[state=open]:fade-in-0
data-[state=closed]:zoom-out-95
data-[state=open]:zoom-in-95
data-[side=bottom]:slide-in-from-top-2
data-[side=left]:slide-in-from-right-2
data-[side=right]:slide-in-from-left-2
data-[side=top]:slide-in-from-bottom-2
`,
item: `
relative
flex
cursor-pointer
select-none
items-center
rounded-sm
px-2
py-1.5
text-sm
outline-none
transition-colors
hover:bg-gray-100 dark:hover:bg-gray-700
focus:bg-gray-100 dark:focus:bg-gray-700
data-[disabled]:pointer-events-none
data-[disabled]:opacity-50
`,
separator: `
-mx-1
my-1
h-px
bg-gray-200 dark:bg-gray-700
`,
label: `
px-2
py-1.5
text-sm
font-semibold
text-gray-500 dark:text-gray-400
`,
destructive: `
text-red-600 dark:text-red-400
hover:bg-red-50 dark:hover:bg-red-900/20
focus:bg-red-50 dark:focus:bg-red-900/20
`,
};
// Utility to combine class names
const cn = (...classes: (string | undefined | false)[]) => {
return classes.filter(Boolean).join(" ");
};
// Root dropdown menu
export const DirectDropdownMenu = DropdownMenu.Root;
export const DirectDropdownMenuTrigger = DropdownMenu.Trigger;
// Content component with styling
interface DirectDropdownMenuContentProps
extends React.ComponentProps<typeof DropdownMenu.Content> {
className?: string;
sideOffset?: number;
}
export const DirectDropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenu.Content>,
DirectDropdownMenuContentProps
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenu.Portal>
<DropdownMenu.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
dropdownStyles.content.replace(/\s+/g, " ").trim(),
className,
)}
{...props}
/>
</DropdownMenu.Portal>
));
DirectDropdownMenuContent.displayName = "DirectDropdownMenuContent";
// Menu item component
interface DirectDropdownMenuItemProps
extends React.ComponentProps<typeof DropdownMenu.Item> {
className?: string;
destructive?: boolean;
}
export const DirectDropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenu.Item>,
DirectDropdownMenuItemProps
>(({ className, destructive, ...props }, ref) => (
<DropdownMenu.Item
ref={ref}
className={cn(
dropdownStyles.item.replace(/\s+/g, " ").trim(),
destructive && dropdownStyles.destructive.replace(/\s+/g, " ").trim(),
className,
)}
{...props}
/>
));
DirectDropdownMenuItem.displayName = "DirectDropdownMenuItem";
// Separator component
interface DirectDropdownMenuSeparatorProps
extends React.ComponentProps<typeof DropdownMenu.Separator> {
className?: string;
}
export const DirectDropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenu.Separator>,
DirectDropdownMenuSeparatorProps
>(({ className, ...props }, ref) => (
<DropdownMenu.Separator
ref={ref}
className={cn(
dropdownStyles.separator.replace(/\s+/g, " ").trim(),
className,
)}
{...props}
/>
));
DirectDropdownMenuSeparator.displayName = "DirectDropdownMenuSeparator";
// Label component
interface DirectDropdownMenuLabelProps
extends React.ComponentProps<typeof DropdownMenu.Label> {
className?: string;
}
export const DirectDropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenu.Label>,
DirectDropdownMenuLabelProps
>(({ className, ...props }, ref) => (
<DropdownMenu.Label
ref={ref}
className={cn(dropdownStyles.label.replace(/\s+/g, " ").trim(), className)}
{...props}
/>
));
DirectDropdownMenuLabel.displayName = "DirectDropdownMenuLabel";
// Checkbox item component
interface DirectDropdownMenuCheckboxItemProps
extends React.ComponentProps<typeof DropdownMenu.CheckboxItem> {
className?: string;
children: React.ReactNode;
}
export const DirectDropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenu.CheckboxItem>,
DirectDropdownMenuCheckboxItemProps
>(({ className, children, ...props }, ref) => (
<DropdownMenu.CheckboxItem
ref={ref}
className={cn(
dropdownStyles.item.replace(/\s+/g, " ").trim(),
"pl-8",
className,
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenu.ItemIndicator>
<CheckIcon className="h-4 w-4" />
</DropdownMenu.ItemIndicator>
</span>
{children}
</DropdownMenu.CheckboxItem>
));
DirectDropdownMenuCheckboxItem.displayName = "DirectDropdownMenuCheckboxItem";
// Sub menu components
export const DirectDropdownMenuSub = DropdownMenu.Sub;
interface DirectDropdownMenuSubTriggerProps
extends React.ComponentProps<typeof DropdownMenu.SubTrigger> {
className?: string;
children: React.ReactNode;
}
export const DirectDropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenu.SubTrigger>,
DirectDropdownMenuSubTriggerProps
>(({ className, children, ...props }, ref) => (
<DropdownMenu.SubTrigger
ref={ref}
className={cn(dropdownStyles.item.replace(/\s+/g, " ").trim(), className)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto h-4 w-4" />
</DropdownMenu.SubTrigger>
));
DirectDropdownMenuSubTrigger.displayName = "DirectDropdownMenuSubTrigger";
interface DirectDropdownMenuSubContentProps
extends React.ComponentProps<typeof DropdownMenu.SubContent> {
className?: string;
}
export const DirectDropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenu.SubContent>,
DirectDropdownMenuSubContentProps
>(({ className, ...props }, ref) => (
<DropdownMenu.SubContent
ref={ref}
className={cn(
dropdownStyles.content.replace(/\s+/g, " ").trim(),
className,
)}
{...props}
/>
));
DirectDropdownMenuSubContent.displayName = "DirectDropdownMenuSubContent";
// Example usage component to test the dropdown
export const DirectDropdownExample: React.FC = () => {
const [isOpen, setIsOpen] = React.useState(false);
return (
<div className="p-4">
<DirectDropdownMenu open={isOpen} onOpenChange={setIsOpen}>
<DirectDropdownMenuTrigger asChild>
<button className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
Open Menu
</button>
</DirectDropdownMenuTrigger>
<DirectDropdownMenuContent align="end" className="w-56">
<DirectDropdownMenuLabel>My Account</DirectDropdownMenuLabel>
<DirectDropdownMenuSeparator />
<DirectDropdownMenuItem
onClick={() => console.log("Profile clicked")}
>
<span>Profile</span>
</DirectDropdownMenuItem>
<DirectDropdownMenuItem
onClick={() => console.log("Settings clicked")}
>
<span>Settings</span>
</DirectDropdownMenuItem>
<DirectDropdownMenuSeparator />
<DirectDropdownMenuItem
destructive
onClick={() => console.log("Logout clicked")}
>
<span>Log out</span>
</DirectDropdownMenuItem>
</DirectDropdownMenuContent>
</DirectDropdownMenu>
</div>
);
};

View File

@@ -8,6 +8,7 @@ import ChannelSidebar from "@/components/layout/ChannelSidebar";
import UserPanel from "@/components/layout/UserPanel";
import MemberList from "@/components/layout/MemberList";
import LoadingSpinner from "@/components/common/LoadingSpinner";
import VoiceConnectionManager from "@/components/voice/VoiceConnectionManager";
const AppLayout: React.FC = () => {
const { isLoading } = useAuthStore();
@@ -32,22 +33,15 @@ const AppLayout: React.FC = () => {
);
}
// Uncomment if auth is required
// if (!user) {
// return (
// <div className="h-screen w-screen flex items-center justify-center bg-concord-primary">
// <div className="text-red-400">Authentication required</div>
// </div>
// );
// }
return (
<div className="flex h-screen overflow-hidden bg-concord-primary text-concord-primary">
{/* This component handles playing audio from remote users */}
<VoiceConnectionManager />
{/* Server List Sidebar - Always visible on desktop, overlay on mobile */}
<div className="relative w-[72px] sidebar-primary flex-shrink-0">
<ServerSidebar />
</div>
{/* Channel Sidebar - Only shown when in a server context and not collapsed */}
{shouldShowChannelSidebar && (
<div
@@ -64,7 +58,6 @@ const AppLayout: React.FC = () => {
</div>
</div>
)}
{/* Main Content Area */}
<div
className={`flex-1 flex flex-col min-w-0 ${
@@ -73,7 +66,6 @@ const AppLayout: React.FC = () => {
>
<Outlet />
</div>
{/* Member List - Only shown when in a channel and member list is enabled */}
{showMemberList && shouldShowChannelSidebar && (
<div className="flex-0 sidebar-secondary order-l border-sidebar">

View File

@@ -6,6 +6,7 @@ import { ScrollArea } from "@/components/ui/scroll-area";
import { useInstanceDetails } from "@/hooks/useServers";
import { useUiStore } from "@/stores/uiStore";
import ChannelList from "@/components/channel/ChannelList";
import { CreateCategoryModal, CreateChannelModal } from "../server/ServerIcon";
const ChannelSidebar: React.FC = () => {
const { instanceId } = useParams();
@@ -94,6 +95,8 @@ const ChannelSidebar: React.FC = () => {
</div>
</div>
</ScrollArea>
<CreateChannelModal />
<CreateCategoryModal />
</div>
);
};

View File

@@ -1,10 +1,13 @@
import React from "react";
// src/components/layout/MemberList.tsx - Enhanced with role management
import React, { useState } from "react";
import { useParams } from "react-router";
import { Crown, Shield, UserIcon } from "lucide-react";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Role } from "@/types/database";
import { useInstanceMembers } from "@/hooks/useServers";
import { useAuthStore } from "@/stores/authStore";
import { User } from "@/types/database";
// Status color utility
@@ -23,6 +26,7 @@ const getStatusColor = (status: string) => {
interface MemberItemProps {
member: User;
instanceId: string;
isOwner?: boolean;
}
@@ -43,61 +47,83 @@ const getRoleInfo = (role: string) => {
}
};
const MemberItem: React.FC<MemberItemProps> = ({ member, isOwner = false }) => {
const { instanceId } = useParams();
const MemberItem: React.FC<MemberItemProps> = ({
member,
instanceId,
isOwner = false,
}) => {
const userRole = getUserRoleForInstance(member.roles, instanceId || "");
const roleInfo = getRoleInfo(userRole);
return (
<div className="panel-button">
<div className="relative">
<Avatar className="h-8 w-8">
<AvatarImage
src={member.picture || undefined}
alt={member.username}
/>
<AvatarFallback className="text-xs bg-primary text-primary-foreground">
{member.username.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
{/* Status indicator */}
<div
className={`absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-sidebar ${getStatusColor(member.status)}`}
/>
</div>
<div className="ml-3 flex-1 min-w-0">
<div className="flex items-center gap-1">
{isOwner && (
<Crown size={12} className="text-yellow-500 flex-shrink-0" />
)}
{!isOwner && userRole !== "member" && (
<Shield
size={12}
className="flex-shrink-0"
style={{ color: roleInfo.color || "var(--background)" }}
<>
<Button
variant="ghost"
className="w-full justify-start p-2 h-auto hover:bg-concord-tertiary/50"
disabled={member.admin}
>
<div className="flex items-center gap-3 w-full">
<div className="relative">
<Avatar className="h-8 w-8">
<AvatarImage
src={member.picture || undefined}
alt={member.username}
/>
<AvatarFallback className="text-xs bg-primary text-primary-foreground">
{member.username.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
{/* Status indicator */}
<div
className={`absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-sidebar ${getStatusColor(member.status)}`}
/>
)}
<span
className="text-sm font-medium truncate"
style={{ color: roleInfo.color || "var(--color-text-primary)" }}
>
{member.nickname || member.username}
</span>
</div>
{member.bio && (
<div className="text-xs text-concord-secondary truncate">
{member.bio}
</div>
)}
</div>
</div>
<div className="flex-1 min-w-0 text-left">
<div className="flex items-center gap-1">
{isOwner && (
<Crown size={12} className="text-yellow-500 flex-shrink-0" />
)}
{!isOwner && userRole !== "member" && (
<Shield
size={12}
className="flex-shrink-0"
style={{ color: roleInfo.color || "var(--background)" }}
/>
)}
<span
className="text-sm font-medium truncate"
style={{ color: roleInfo.color || "var(--color-text-primary)" }}
>
{member.nickname || member.username}
</span>
</div>
{member.bio && (
<div className="text-xs text-concord-secondary truncate">
{member.bio}
</div>
)}
</div>
</div>
</Button>
</>
);
};
const MemberList: React.FC = () => {
const { instanceId } = useParams();
const { data: members, isLoading } = useInstanceMembers(instanceId);
const { user: currentUser } = useAuthStore();
const currentUserRole = React.useMemo(() => {
if (!currentUser || !instanceId) return "member";
if (currentUser.admin) return "admin";
const userRole = currentUser.roles.find(
(role) => role.instanceId === instanceId,
);
return userRole?.role || "member";
}, [currentUser, instanceId]);
if (!instanceId) {
return null;
@@ -149,12 +175,9 @@ const MemberList: React.FC = () => {
{/* Header */}
<div className="px-4 py-3 border-b border-concord-primary flex items-center justify-between">
<UserIcon size={20} className="text-concord-primary h-8" />
<div className="h-8 flex flex-col justify-center">
<h3 className="text-sm font-semibold text-concord-secondary tracking-wide">
Members: {members.length} Online:{" "}
{members.filter((m) => m.status === "online").length}
</h3>
</div>
<p className="text-sm font-semibold text-concord-secondary tracking-wide">
{members.length} Members
</p>
</div>
{/* Member List */}
@@ -177,6 +200,8 @@ const MemberList: React.FC = () => {
<MemberItem
key={member.id}
member={member}
instanceId={instanceId}
currentUserRole={currentUserRole}
isOwner={false}
/>
))}

View File

@@ -10,32 +10,44 @@ import {
} from "@/components/ui/tooltip";
import { useServers } from "@/hooks/useServers";
import { useUiStore } from "@/stores/uiStore";
import { useAuthStore } from "@/stores/authStore";
import ServerIcon from "@/components/server/ServerIcon";
import { getAccessibleInstances, isGlobalAdmin } from "@/utils/permissions";
import { CreateServerModal } from "../modals/CreateServerModal";
const ServerSidebar: React.FC = () => {
const navigate = useNavigate();
const { instanceId } = useParams();
const { data: servers, isLoading } = useServers();
const { data: allServers = [], isLoading } = useServers();
const { openCreateServer, setActiveInstance, getSelectedChannelForInstance } =
useUiStore();
const { user: currentUser } = useAuthStore();
// Filter servers based on user permissions
const accessibleServers = getAccessibleInstances(currentUser, allServers);
const canCreateServer = isGlobalAdmin(currentUser);
const handleServerClick = (serverId: string) => {
setActiveInstance(serverId);
const lastChannelId = getSelectedChannelForInstance(serverId);
console.log(servers);
if (lastChannelId) {
navigate(`/channels/${serverId}/${lastChannelId}`);
} else {
// Fallback: navigate to the server, let the page component handle finding a channel
// A better UX would be to find and navigate to the first channel here.
navigate(`/channels/${serverId}`);
}
};
const handleHomeClick = () => {
setActiveInstance(null);
navigate("/channels/@me");
navigate("/");
};
const handleCreateServer = () => {
if (canCreateServer) {
openCreateServer();
}
};
return (
@@ -47,8 +59,10 @@ const ServerSidebar: React.FC = () => {
<Button
variant="ghost"
size="icon"
className={` w-12 h-12 ml-0 ${
!instanceId || instanceId === "@me" ? "active" : ""
className={`w-12 h-12 ml-0 rounded-2xl hover:rounded-xl transition-all duration-200 ${
!instanceId || instanceId === "@me"
? "bg-primary text-primary-foreground rounded-xl"
: "hover:bg-primary/10"
}`}
onClick={handleHomeClick}
>
@@ -56,7 +70,7 @@ const ServerSidebar: React.FC = () => {
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Direct Messages</p>
<p>{isGlobalAdmin(currentUser) ? "Admin Dashboard" : "Home"}</p>
</TooltipContent>
</Tooltip>
@@ -69,8 +83,8 @@ const ServerSidebar: React.FC = () => {
<div className="flex items-center justify-center py-4">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
</div>
) : (
servers?.map((server) => (
) : accessibleServers.length > 0 ? (
accessibleServers.map((server) => (
<Tooltip key={server.id}>
<TooltipTrigger asChild>
<div>
@@ -86,25 +100,43 @@ const ServerSidebar: React.FC = () => {
</TooltipContent>
</Tooltip>
))
)}
) : currentUser ? (
<div className="text-center py-4 px-2">
<div className="text-xs text-concord-secondary mb-2">
No servers available
</div>
{canCreateServer && (
<Button
variant="outline"
size="sm"
className="text-xs"
onClick={handleCreateServer}
>
Create One
</Button>
)}
</div>
) : null}
</div>
{/* Add Server Button */}
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="w-12 h-12 ml-3 rounded-2xl hover:rounded-xl bg-concord-secondary hover:bg-green-600 text-green-500 hover:text-white transition-all duration-200"
onClick={openCreateServer}
>
<Plus size={24} />
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Add a Server</p>
</TooltipContent>
</Tooltip>
{/* Add Server Button - Only show if user can create servers */}
{canCreateServer && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="w-12 h-12 ml-3 rounded-2xl hover:rounded-xl bg-concord-secondary hover:bg-green-600 text-green-500 hover:text-white transition-all duration-200"
onClick={handleCreateServer}
>
<Plus size={24} />
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Add a Server</p>
</TooltipContent>
</Tooltip>
)}
</div>
</TooltipProvider>
);

View File

@@ -18,7 +18,8 @@ import {
import { useAuthStore } from "@/stores/authStore";
import { useUiStore } from "@/stores/uiStore";
import { SAMPLE_USERS } from "@/hooks/useServers";
import { useLogout } from "@/hooks/useAuth";
import { useVoiceStore } from "@/stores/voiceStore";
// Status color utility
const getStatusColor = (status: string) => {
@@ -46,6 +47,8 @@ const UserStatusDropdown: React.FC<UserStatusDropdownProps> = ({
onStatusChange,
children,
}) => {
const { mutate: logout } = useLogout();
const statusOptions = [
{ value: "online", label: "Online", color: "bg-status-online" },
{ value: "away", label: "Away", color: "bg-status-away" },
@@ -79,7 +82,7 @@ const UserStatusDropdown: React.FC<UserStatusDropdownProps> = ({
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => useAuthStore.getState().logout()}
onClick={() => logout()}
className="text-destructive focus:text-destructive"
>
Log Out
@@ -209,64 +212,46 @@ const UserPanel: React.FC = () => {
const { user } = useAuthStore();
const { openUserSettings } = useUiStore();
const [isMuted, setIsMuted] = useState(false);
const [isDeafened, setIsDeafened] = useState(false);
const displayUser = user || SAMPLE_USERS.find((u) => u.id === "current");
if (!displayUser) {
return (
<div className="flex-shrink-0 p-2 bg-concord-tertiary">
<div className="text-concord-secondary text-sm">No user data</div>
</div>
);
}
const { isConnected, isMuted, isDeafened, toggleMute, toggleDeafen } =
useVoiceStore();
const handleStatusChange = (newStatus: string) => {
console.log("Status change to:", newStatus);
// TODO: Implement API call to update user status
};
const handleMuteToggle = () => setIsMuted(!isMuted);
const handleDeafenToggle = () => {
const newDeafenState = !isDeafened;
setIsDeafened(newDeafenState);
if (newDeafenState) {
setIsMuted(true); // Deafening also mutes
}
};
return (
<div className="user-panel flex items-center p-2 bg-concord-tertiary border-t border-sidebar">
{/* User Info with Dropdown */}
<UserStatusDropdown
currentStatus={displayUser.status}
currentStatus={user?.status as string}
onStatusChange={handleStatusChange}
>
<Button
variant="ghost"
className="flex-1 flex items-center h-auto p-1 rounded-md hover:bg-concord-secondary"
>
<UserAvatar user={displayUser} size="md" />
<UserAvatar user={user} size="md" />
<div className="ml-2 flex-1 min-w-0 text-left">
<div className="text-sm font-medium text-concord-primary truncate">
{displayUser.nickname || displayUser.username}
{user?.nickname || user?.username}
</div>
<div className="text-xs text-concord-secondary truncate capitalize">
{displayUser.status}
{user?.status}
</div>
</div>
</Button>
</UserStatusDropdown>
{/* Voice Controls */}
<VoiceControls
isMuted={isMuted}
isDeafened={isDeafened}
onMuteToggle={handleMuteToggle}
onDeafenToggle={handleDeafenToggle}
onSettingsClick={openUserSettings}
/>
{isConnected && (
<VoiceControls
isMuted={isMuted}
isDeafened={isDeafened}
onMuteToggle={toggleMute}
onDeafenToggle={toggleDeafen}
onSettingsClick={openUserSettings}
/>
)}
</div>
);
};

View File

@@ -0,0 +1,223 @@
import React, { useState, useEffect } from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Hash, Volume2, Loader2 } from "lucide-react";
import { useCreateChannel } from "@/hooks/useServers";
import { useCategoriesByInstance } from "@/hooks/useCategories"; // New hook
import { CategoryWithChannels } from "@/types/api";
interface CreateChannelModalProps {
isOpen: boolean;
onClose: () => void;
instanceId: string; // Changed to use instanceId instead of categories prop
defaultCategoryId?: string;
}
export const CreateChannelModal: React.FC<CreateChannelModalProps> = ({
isOpen,
onClose,
instanceId,
defaultCategoryId,
}) => {
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [type, setType] = useState<"text" | "voice">("text");
const [categoryId, setCategoryId] = useState(defaultCategoryId || "");
// Fetch categories using the new API
const {
data: categories,
isLoading: categoriesLoading,
error: categoriesError,
} = useCategoriesByInstance(instanceId);
const createChannelMutation = useCreateChannel();
// Update categoryId when defaultCategoryId changes or categories load
useEffect(() => {
if (defaultCategoryId) {
setCategoryId(defaultCategoryId);
} else if (categories && categories.length > 0 && !categoryId) {
// Auto-select first category if none selected
setCategoryId(categories[0].id);
}
}, [defaultCategoryId, categories, categoryId]);
// Reset form when modal opens/closes
useEffect(() => {
if (!isOpen) {
setName("");
setDescription("");
setType("text");
setCategoryId(defaultCategoryId || "");
}
}, [isOpen, defaultCategoryId]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim() || !categoryId) return;
try {
await createChannelMutation.mutateAsync({
name: name.trim(),
description: description.trim(),
type,
categoryId,
});
// Reset form
setName("");
setDescription("");
setType("text");
setCategoryId(defaultCategoryId || "");
onClose();
} catch (error) {
console.error("Failed to create channel:", error);
}
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-[400px]">
<DialogHeader>
<DialogTitle>Create Channel</DialogTitle>
</DialogHeader>
{categoriesError && (
<div className="p-3 text-sm text-destructive bg-destructive/10 rounded-md">
Failed to load categories. Please try again.
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label>Channel Type</Label>
<div className="flex gap-2">
<Button
type="button"
variant={type === "text" ? "default" : "outline"}
onClick={() => setType("text")}
className="flex-1"
>
<Hash className="h-4 w-4 mr-2" />
Text
</Button>
<Button
type="button"
variant={type === "voice" ? "default" : "outline"}
onClick={() => setType("voice")}
className="flex-1"
>
<Volume2 className="h-4 w-4 mr-2" />
Voice
</Button>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="channel-name">Channel Name</Label>
<Input
id="channel-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="awesome-channel"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="channel-description">Description</Label>
<Textarea
id="channel-description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="What's this channel about?"
rows={3}
/>
</div>
<div className="space-y-2">
<Label>Category</Label>
<Select
value={categoryId}
onValueChange={setCategoryId}
required
disabled={categoriesLoading}
>
<SelectTrigger>
<SelectValue
placeholder={
categoriesLoading
? "Loading categories..."
: "Select a category"
}
/>
</SelectTrigger>
<SelectContent>
{categoriesLoading ? (
<SelectItem value="loading" disabled>
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
Loading...
</div>
</SelectItem>
) : categories && categories.length > 0 ? (
categories.map((category) => (
<SelectItem key={category.id} value={category.id}>
{category.name}
</SelectItem>
))
) : (
<SelectItem value="no-categories" disabled>
No categories available
</SelectItem>
)}
</SelectContent>
</Select>
</div>
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button
type="submit"
disabled={
!name.trim() ||
!categoryId ||
createChannelMutation.isPending ||
categoriesLoading ||
categoryId === "loading" ||
categoryId === "no-categories"
}
>
{createChannelMutation.isPending ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
Creating...
</div>
) : (
"Create Channel"
)}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
};

View File

@@ -0,0 +1,92 @@
import React, { useState } from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useCreateInstance } from "@/hooks/useServers";
interface CreateServerModalProps {
isOpen: boolean;
onClose: () => void;
}
export const CreateServerModal: React.FC<CreateServerModalProps> = ({
isOpen,
onClose,
}) => {
const [name, setName] = useState("");
const [icon, setIcon] = useState("");
const createInstanceMutation = useCreateInstance();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim()) return;
try {
await createInstanceMutation.mutateAsync({
name: name.trim(),
icon: icon.trim() || undefined,
});
// Reset form
setName("");
setIcon("");
onClose();
} catch (error) {
console.error("Failed to create server:", error);
}
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-[400px]">
<DialogHeader>
<DialogTitle>Create Server</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="server-name">Server Name</Label>
<Input
id="server-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="My Awesome Server"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="server-icon">Server Icon URL (optional)</Label>
<Input
id="server-icon"
value={icon}
onChange={(e) => setIcon(e.target.value)}
placeholder="https://example.com/icon.png"
type="url"
/>
</div>
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button
type="submit"
disabled={!name.trim() || createInstanceMutation.isPending}
>
{createInstanceMutation.isPending
? "Creating..."
: "Create Server"}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
};

View File

@@ -0,0 +1,61 @@
import React from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Copy, Reply } from "lucide-react";
import { Message } from "@/lib/api-client";
interface MessageActionsModalProps {
isOpen: boolean;
onClose: () => void;
message: Message;
isOwnMessage: boolean;
onReply?: (messageId: string) => void;
}
export const MessageActionsModal: React.FC<MessageActionsModalProps> = ({
isOpen,
onClose,
message,
onReply,
}) => {
const handleAction = (action: () => void) => {
action();
onClose();
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-[300px]">
<DialogHeader>
<DialogTitle>Message Actions</DialogTitle>
</DialogHeader>
<div className="space-y-2">
<Button
variant="ghost"
className="w-full justify-start"
onClick={() => handleAction(() => onReply?.(message.id))}
>
<Reply className="h-4 w-4 mr-2" />
Reply
</Button>
<Button
variant="ghost"
className="w-full justify-start"
onClick={() =>
handleAction(() => navigator.clipboard.writeText(message.text))
}
>
<Copy className="h-4 w-4 mr-2" />
Copy Text
</Button>
</div>
</DialogContent>
</Dialog>
);
};

View File

@@ -1,6 +1,30 @@
import React from "react";
import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Instance } from "@/types/database";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
} from "../ui/dialog";
import { DialogDescription, DialogTitle } from "@radix-ui/react-dialog";
import { Label } from "../ui/label";
import { Input } from "../ui/input";
import { Textarea } from "../ui/textarea";
import { Category } from "@/types";
import { useUiStore } from "@/stores/uiStore";
import {
useCreateCategory,
useCreateChannel,
useCreateInstance,
} from "@/hooks/useServers";
import {
Select,
SelectContent,
SelectTrigger,
SelectItem,
SelectValue,
} from "../ui/select";
interface ServerIconProps {
server: Instance;
@@ -44,7 +68,7 @@ const ServerIcon: React.FC<ServerIconProps> = ({
<img
src={server.icon}
alt={server.name}
className="w-full h-full object-cover rounded-inherit"
className={`w-full h-full object-cover ${isActive ? "rounded-xl" : "rounded-2xl"}`}
/>
) : (
<span className="font-semibold text-sm">
@@ -56,4 +80,308 @@ const ServerIcon: React.FC<ServerIconProps> = ({
);
};
// Create Server Modal
export const CreateServerModal: React.FC = () => {
const { showCreateServer, closeCreateServer } = useUiStore();
const { mutate: createInstance, isPending } = useCreateInstance();
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [icon, setIcon] = useState("");
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (name.trim()) {
createInstance(
{
name: name.trim(),
icon: icon.trim() || undefined,
description: description.trim() || undefined,
},
{
onSuccess: () => {
setName("");
setDescription("");
setIcon("");
closeCreateServer();
},
onError: (error) => {
console.error("Failed to create server:", error);
},
},
);
}
};
const handleClose = () => {
setName("");
setDescription("");
setIcon("");
closeCreateServer();
};
return (
<Dialog open={showCreateServer} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Create a Server</DialogTitle>
<DialogDescription>
Create a new server to chat with friends and communities.
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="server-name">Server Name</Label>
<Input
id="server-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter server name"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="server-description">Description (Optional)</Label>
<Textarea
id="server-description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="What's this server about?"
rows={3}
/>
</div>
<div className="space-y-2">
<Label htmlFor="server-icon">Server Icon URL (Optional)</Label>
<Input
id="server-icon"
type="url"
value={icon}
onChange={(e) => setIcon(e.target.value)}
placeholder="https://example.com/icon.png"
/>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button type="submit" disabled={isPending || !name.trim()}>
{isPending ? "Creating..." : "Create Server"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
};
// Create Channel Modal
export const CreateChannelModal: React.FC = () => {
const { showCreateChannel, closeCreateChannel } = useUiStore();
const { mutate: createChannel, isPending } = useCreateChannel();
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [type, setType] = useState<"text" | "voice">("text");
const [categoryId, setCategoryId] = useState("");
// You'd need to get categories for the current instance
// This is a simplified version
const categories: Category[] = []; // Get from context or props
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (name.trim() && categoryId) {
createChannel(
{
name: name.trim(),
description: description.trim(),
type,
categoryId,
},
{
onSuccess: () => {
setName("");
setDescription("");
setType("text");
setCategoryId("");
closeCreateChannel();
},
onError: (error) => {
console.error("Failed to create channel:", error);
},
},
);
}
};
const handleClose = () => {
setName("");
setDescription("");
setType("text");
setCategoryId("");
closeCreateChannel();
};
return (
<Dialog open={showCreateChannel} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Create a Channel</DialogTitle>
<DialogDescription>
Create a new text or voice channel in this server.
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="channel-type">Channel Type</Label>
<Select
value={type}
onValueChange={(value: "text" | "voice") => setType(value)}
>
<SelectTrigger>
<SelectValue placeholder="Select channel type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="text">Text Channel</SelectItem>
<SelectItem value="voice">Voice Channel</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="channel-category">Category</Label>
<Select value={categoryId} onValueChange={setCategoryId}>
<SelectTrigger>
<SelectValue placeholder="Select a category" />
</SelectTrigger>
<SelectContent>
{categories.map((category) => (
<SelectItem key={category.id} value={category.id}>
{category.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="channel-name">Channel Name</Label>
<Input
id="channel-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter channel name"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="channel-description">Description (Optional)</Label>
<Textarea
id="channel-description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="What's this channel for?"
rows={3}
/>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button type="submit" disabled={isPending || !name.trim()}>
{isPending ? "Creating..." : "Create Channel"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
};
// Create Category Modal
export const CreateCategoryModal: React.FC = () => {
const [open, setOpen] = useState(false);
const { mutate: createCategory, isPending } = useCreateCategory();
const [name, setName] = useState("");
const [instanceId, setInstanceId] = useState("");
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (name.trim() && instanceId) {
createCategory(
{
name: name.trim(),
instanceId,
position: 0,
},
{
onSuccess: () => {
setName("");
setInstanceId("");
setOpen(false);
},
onError: (error) => {
console.error("Failed to create category:", error);
},
},
);
}
};
const handleClose = () => {
setName("");
setInstanceId("");
setOpen(false);
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Create a Category</DialogTitle>
<DialogDescription>
Create a new category to organize your channels.
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="category-name">Category Name</Label>
<Input
id="category-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter category name"
required
/>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button type="submit" disabled={isPending || !name.trim()}>
{isPending ? "Creating..." : "Create Category"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
};
export const AdminModals: React.FC = () => {
return (
<>
<CreateServerModal />
<CreateChannelModal />
<CreateCategoryModal />
</>
);
};
export default ServerIcon;

View File

@@ -1,15 +1,14 @@
import React, { useState } from "react";
import { Moon, Sun, Monitor, Palette, Plus, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
DropdownMenuLabel,
DropdownMenuGroup,
} from "@/components/ui/dropdown-menu";
Moon,
Sun,
Monitor,
Palette,
Plus,
Trash2,
Settings,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
@@ -17,6 +16,7 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@@ -29,6 +29,8 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import {
useTheme,
ThemeDefinition,
@@ -132,101 +134,107 @@ const CreateThemeModal: React.FC<{
</DialogDescription>
</DialogHeader>
<div className="space-y-6">
{/* Basic Info */}
<div className="space-y-4">
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="theme-name" className="text-right">
Name
</Label>
<Input
id="theme-name"
value={name}
onChange={(e) => setName(e.target.value)}
className="col-span-3"
placeholder="My Custom Theme"
/>
<ScrollArea className="max-h-96">
<div className="space-y-6 pr-4">
{/* Basic Info */}
<div className="space-y-4">
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="theme-name" className="text-right">
Name
</Label>
<Input
id="theme-name"
value={name}
onChange={(e) => setName(e.target.value)}
className="col-span-3"
placeholder="My Custom Theme"
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="theme-description" className="text-right">
Description
</Label>
<Textarea
id="theme-description"
value={description}
onChange={(e) => setDescription(e.target.value)}
className="col-span-3"
placeholder="Optional description"
rows={2}
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="theme-mode" className="text-right">
Mode
</Label>
<Select
value={mode}
onValueChange={(v: "light" | "dark") => setMode(v)}
>
<SelectTrigger className="col-span-3">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="light">Light</SelectItem>
<SelectItem value="dark">Dark</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="theme-description" className="text-right">
Description
</Label>
<Textarea
id="theme-description"
value={description}
onChange={(e) => setDescription(e.target.value)}
className="col-span-3"
placeholder="Optional description"
rows={2}
/>
</div>
<Separator />
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="theme-mode" className="text-right">
Mode
</Label>
<Select
value={mode}
onValueChange={(v: "light" | "dark") => setMode(v)}
>
<SelectTrigger className="col-span-3">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="light">Light</SelectItem>
<SelectItem value="dark">Dark</SelectItem>
</SelectContent>
</Select>
{/* Color sections */}
<div className="space-y-4">
<h4 className="font-medium">Basic Colors</h4>
<div className="space-y-3">
<ColorInput
label="Background"
value={colors.background}
onChange={(v) => updateColor("background", v)}
/>
<ColorInput
label="Foreground"
value={colors.foreground}
onChange={(v) => updateColor("foreground", v)}
/>
<ColorInput
label="Primary"
value={colors.primary}
onChange={(v) => updateColor("primary", v)}
/>
<ColorInput
label="Secondary"
value={colors.secondary}
onChange={(v) => updateColor("secondary", v)}
/>
</div>
<Separator />
<h4 className="font-medium">Sidebar Colors</h4>
<div className="space-y-3">
<ColorInput
label="Sidebar"
value={colors.sidebar}
onChange={(v) => updateColor("sidebar", v)}
/>
<ColorInput
label="Sidebar Primary"
value={colors.sidebarPrimary}
onChange={(v) => updateColor("sidebarPrimary", v)}
/>
<ColorInput
label="Sidebar Accent"
value={colors.sidebarAccent}
onChange={(v) => updateColor("sidebarAccent", v)}
/>
</div>
</div>
</div>
{/* Color sections */}
<div className="space-y-4">
<h4 className="font-medium">Basic Colors</h4>
<div className="space-y-3">
<ColorInput
label="Background"
value={colors.background}
onChange={(v) => updateColor("background", v)}
/>
<ColorInput
label="Foreground"
value={colors.foreground}
onChange={(v) => updateColor("foreground", v)}
/>
<ColorInput
label="Primary"
value={colors.primary}
onChange={(v) => updateColor("primary", v)}
/>
<ColorInput
label="Secondary"
value={colors.secondary}
onChange={(v) => updateColor("secondary", v)}
/>
</div>
<h4 className="font-medium">Sidebar Colors</h4>
<div className="space-y-3">
<ColorInput
label="Sidebar"
value={colors.sidebar}
onChange={(v) => updateColor("sidebar", v)}
/>
<ColorInput
label="Sidebar Primary"
value={colors.sidebarPrimary}
onChange={(v) => updateColor("sidebarPrimary", v)}
/>
<ColorInput
label="Sidebar Accent"
value={colors.sidebarAccent}
onChange={(v) => updateColor("sidebarAccent", v)}
/>
</div>
</div>
</div>
</ScrollArea>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
@@ -241,12 +249,11 @@ const CreateThemeModal: React.FC<{
);
};
// Main theme selector component
// Main theme selector component as modal
export function ThemeSelector() {
const {
mode,
currentTheme,
// themes,
setMode,
setTheme,
addCustomTheme,
@@ -254,6 +261,7 @@ export function ThemeSelector() {
getThemesForMode,
} = useTheme();
const [isMainModalOpen, setIsMainModalOpen] = useState(false);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
const lightThemes = getThemesForMode("light");
@@ -272,142 +280,200 @@ export function ThemeSelector() {
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Dialog open={isMainModalOpen} onOpenChange={setIsMainModalOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm">
{getCurrentModeIcon()}
<span className="ml-2">{currentTheme.name}</span>
<Settings className="h-4 w-4 mr-2" />
Theme
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuLabel>Appearance</DropdownMenuLabel>
<DropdownMenuSeparator />
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
{getCurrentModeIcon()}
Appearance Settings
</DialogTitle>
<DialogDescription>
Choose your preferred theme and color scheme
</DialogDescription>
</DialogHeader>
{/* Mode Selection */}
<DropdownMenuGroup>
<DropdownMenuLabel className="text-xs">Mode</DropdownMenuLabel>
<DropdownMenuItem onClick={() => setMode("light")}>
<Sun className="mr-2 h-4 w-4" />
<span>Light</span>
{mode === "light" && (
<Badge variant="secondary" className="ml-auto">
Active
</Badge>
)}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setMode("dark")}>
<Moon className="mr-2 h-4 w-4" />
<span>Dark</span>
{mode === "dark" && (
<Badge variant="secondary" className="ml-auto">
Active
</Badge>
)}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setMode("system")}>
<Monitor className="mr-2 h-4 w-4" />
<span>System</span>
{mode === "system" && (
<Badge variant="secondary" className="ml-auto">
Active
</Badge>
)}
</DropdownMenuItem>
</DropdownMenuGroup>
<div className="space-y-6">
{/* Current Theme Display */}
<div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
<div>
<p className="font-medium">{currentTheme.name}</p>
{currentTheme.description && (
<p className="text-sm text-muted-foreground">
{currentTheme.description}
</p>
)}
</div>
<Badge variant="secondary">Active</Badge>
</div>
<DropdownMenuSeparator />
{/* Light Themes */}
{lightThemes.length > 0 && (
<DropdownMenuGroup>
<DropdownMenuLabel className="text-xs">
Light Themes
</DropdownMenuLabel>
{lightThemes.map((theme) => (
<DropdownMenuItem
key={theme.id}
onClick={() => setTheme(theme.id)}
className="justify-between"
{/* Mode Selection */}
<div className="space-y-3">
<Label className="text-sm font-medium">Display Mode</Label>
<div className="grid grid-cols-3 gap-2">
<Button
variant={mode === "light" ? "default" : "outline"}
size="sm"
onClick={() => setMode("light")}
className="flex flex-col gap-1 h-auto py-3"
>
<div className="flex items-center">
<Palette className="mr-2 h-4 w-4" />
<span>{theme.name}</span>
</div>
<div className="flex items-center gap-2">
{currentTheme.id === theme.id && (
<Badge variant="secondary">Active</Badge>
)}
{theme.isCustom && (
<Button
variant="ghost"
size="sm"
className="h-auto p-1 hover:text-destructive"
onClick={(e) => {
e.stopPropagation();
removeCustomTheme(theme.id);
}}
>
<Trash2 className="h-3 w-3" />
</Button>
)}
</div>
</DropdownMenuItem>
))}
</DropdownMenuGroup>
)}
{lightThemes.length > 0 && darkThemes.length > 0 && (
<DropdownMenuSeparator />
)}
{/* Dark Themes */}
{darkThemes.length > 0 && (
<DropdownMenuGroup>
<DropdownMenuLabel className="text-xs">
Dark Themes
</DropdownMenuLabel>
{darkThemes.map((theme) => (
<DropdownMenuItem
key={theme.id}
onClick={() => setTheme(theme.id)}
className="justify-between"
<Sun className="h-4 w-4" />
<span className="text-xs">Light</span>
</Button>
<Button
variant={mode === "dark" ? "default" : "outline"}
size="sm"
onClick={() => setMode("dark")}
className="flex flex-col gap-1 h-auto py-3"
>
<div className="flex items-center">
<Palette className="mr-2 h-4 w-4" />
<span>{theme.name}</span>
</div>
<div className="flex items-center gap-2">
{currentTheme.id === theme.id && (
<Badge variant="secondary">Active</Badge>
)}
{theme.isCustom && (
<Button
variant="ghost"
size="sm"
className="h-auto p-1 hover:text-destructive"
onClick={(e) => {
e.stopPropagation();
removeCustomTheme(theme.id);
}}
>
<Trash2 className="h-3 w-3" />
</Button>
)}
</div>
</DropdownMenuItem>
))}
</DropdownMenuGroup>
)}
<Moon className="h-4 w-4" />
<span className="text-xs">Dark</span>
</Button>
<Button
variant={mode === "system" ? "default" : "outline"}
size="sm"
onClick={() => setMode("system")}
className="flex flex-col gap-1 h-auto py-3"
>
<Monitor className="h-4 w-4" />
<span className="text-xs">System</span>
</Button>
</div>
</div>
<DropdownMenuSeparator />
{/* Theme Selection */}
<div className="space-y-4">
<div className="flex items-center justify-between">
<Label className="text-sm font-medium">Themes</Label>
<Button
variant="ghost"
size="sm"
onClick={() => setIsCreateModalOpen(true)}
>
<Plus className="h-4 w-4 mr-1" />
Create
</Button>
</div>
{/* Add Custom Theme */}
<DropdownMenuItem onClick={() => setIsCreateModalOpen(true)}>
<Plus className="mr-2 h-4 w-4" />
<span>Create Theme</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<ScrollArea className="max-h-64">
<div className="space-y-3">
{/* Light Themes */}
{lightThemes.length > 0 && (
<div className="space-y-2">
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
Light Themes
</p>
{lightThemes.map((theme) => (
<div
key={theme.id}
className="flex items-center justify-between p-2 rounded-md hover:bg-muted/50 cursor-pointer"
onClick={() => setTheme(theme.id)}
>
<div className="flex items-center gap-3">
<Palette className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">
{theme.name}
</p>
{theme.description && (
<p className="text-xs text-muted-foreground">
{theme.description}
</p>
)}
</div>
</div>
<div className="flex items-center gap-2">
{currentTheme.id === theme.id && (
<Badge variant="secondary" className="text-xs">
Active
</Badge>
)}
{theme.isCustom && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 hover:text-destructive"
onClick={(e) => {
e.stopPropagation();
removeCustomTheme(theme.id);
}}
>
<Trash2 className="h-3 w-3" />
</Button>
)}
</div>
</div>
))}
</div>
)}
{/* Dark Themes */}
{darkThemes.length > 0 && (
<div className="space-y-2">
{lightThemes.length > 0 && <Separator />}
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
Dark Themes
</p>
{darkThemes.map((theme) => (
<div
key={theme.id}
className="flex items-center justify-between p-2 rounded-md hover:bg-muted/50 cursor-pointer"
onClick={() => setTheme(theme.id)}
>
<div className="flex items-center gap-3">
<Palette className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">
{theme.name}
</p>
{theme.description && (
<p className="text-xs text-muted-foreground">
{theme.description}
</p>
)}
</div>
</div>
<div className="flex items-center gap-2">
{currentTheme.id === theme.id && (
<Badge variant="secondary" className="text-xs">
Active
</Badge>
)}
{theme.isCustom && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 hover:text-destructive"
onClick={(e) => {
e.stopPropagation();
removeCustomTheme(theme.id);
}}
>
<Trash2 className="h-3 w-3" />
</Button>
)}
</div>
</div>
))}
</div>
)}
</div>
</ScrollArea>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsMainModalOpen(false)}>
Close
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<CreateThemeModal
isOpen={isCreateModalOpen}

View File

@@ -1,13 +1,13 @@
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import * as React from "react";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
}
function DropdownMenuPortal({
@@ -15,7 +15,7 @@ function DropdownMenuPortal({
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
)
);
}
function DropdownMenuTrigger({
@@ -26,7 +26,7 @@ function DropdownMenuTrigger({
data-slot="dropdown-menu-trigger"
{...props}
/>
)
);
}
function DropdownMenuContent({
@@ -41,12 +41,12 @@ function DropdownMenuContent({
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className
className,
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
);
}
function DropdownMenuGroup({
@@ -54,7 +54,7 @@ function DropdownMenuGroup({
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
)
);
}
function DropdownMenuItem({
@@ -63,8 +63,8 @@ function DropdownMenuItem({
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
inset?: boolean;
variant?: "default" | "destructive";
}) {
return (
<DropdownMenuPrimitive.Item
@@ -73,11 +73,11 @@ function DropdownMenuItem({
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
/>
)
);
}
function DropdownMenuCheckboxItem({
@@ -91,7 +91,7 @@ function DropdownMenuCheckboxItem({
data-slot="dropdown-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
checked={checked}
{...props}
@@ -103,7 +103,7 @@ function DropdownMenuCheckboxItem({
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
)
);
}
function DropdownMenuRadioGroup({
@@ -114,7 +114,7 @@ function DropdownMenuRadioGroup({
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
);
}
function DropdownMenuRadioItem({
@@ -127,7 +127,7 @@ function DropdownMenuRadioItem({
data-slot="dropdown-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
>
@@ -138,7 +138,7 @@ function DropdownMenuRadioItem({
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
)
);
}
function DropdownMenuLabel({
@@ -146,7 +146,7 @@ function DropdownMenuLabel({
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
inset?: boolean;
}) {
return (
<DropdownMenuPrimitive.Label
@@ -154,11 +154,11 @@ function DropdownMenuLabel({
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className
className,
)}
{...props}
/>
)
);
}
function DropdownMenuSeparator({
@@ -171,7 +171,7 @@ function DropdownMenuSeparator({
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
)
);
}
function DropdownMenuShortcut({
@@ -183,17 +183,17 @@ function DropdownMenuShortcut({
data-slot="dropdown-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
className,
)}
{...props}
/>
)
);
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
}
function DropdownMenuSubTrigger({
@@ -202,7 +202,7 @@ function DropdownMenuSubTrigger({
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
inset?: boolean;
}) {
return (
<DropdownMenuPrimitive.SubTrigger
@@ -210,14 +210,14 @@ function DropdownMenuSubTrigger({
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
className
className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
)
);
}
function DropdownMenuSubContent({
@@ -229,11 +229,11 @@ function DropdownMenuSubContent({
data-slot="dropdown-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className
className,
)}
{...props}
/>
)
);
}
export {
@@ -252,4 +252,4 @@ export {
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}
};

View File

@@ -0,0 +1,39 @@
import React, { useEffect, useRef } from "react";
import { useVoiceStore } from "@/stores/voiceStore";
interface AudioPlayerProps {
stream: MediaStream;
isDeafened: boolean;
}
const AudioPlayer: React.FC<AudioPlayerProps> = ({ stream, isDeafened }) => {
const audioRef = useRef<HTMLAudioElement>(null);
useEffect(() => {
if (audioRef.current) {
audioRef.current.srcObject = stream;
audioRef.current.volume = isDeafened ? 0 : 1;
}
}, [stream, isDeafened]);
return <audio ref={audioRef} autoPlay playsInline />;
};
const VoiceConnectionManager: React.FC = () => {
const remoteStreams = useVoiceStore((state) => state.remoteStreams);
const isDeafened = useVoiceStore((state) => state.isDeafened);
if (remoteStreams.size === 0) {
return null;
}
return (
<div style={{ display: "none" }}>
{Array.from(remoteStreams.entries()).map(([userId, stream]) => (
<AudioPlayer key={userId} stream={stream} isDeafened={isDeafened} />
))}
</div>
);
};
export default VoiceConnectionManager;

View File

@@ -0,0 +1,212 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuthStore } from "@/stores/authStore";
import {
authClient,
LoginCredentials,
RegisterData,
AuthResponse,
} from "@/lib/auth-client";
import { BackendUser } from "@/lib/api-client";
import { Role, UserStatus } from "@/types/database";
// Frontend User type
interface FrontendUser {
id: string;
username: string;
nickname?: string | null;
bio?: string | null;
picture?: string | null;
banner?: string | null;
hashPassword: string;
admin: boolean;
status: UserStatus;
createdAt: string;
updatedAt: string;
roles: Role[];
}
// Transform backend user to frontend user format
function transformBackendUser(backendUser: BackendUser): FrontendUser {
return {
id: backendUser.id,
username: backendUser.userName,
nickname: backendUser.nickName,
bio: backendUser.bio,
picture: backendUser.picture,
banner: backendUser.banner,
hashPassword: "", // Don't store password
admin: backendUser.admin,
status: transformStatusToFrontend(backendUser.status),
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
roles: backendUser.role.map((r) => ({
instanceId: r.instanceId || "",
role: r.role || "member",
})) as Role[],
};
}
// Transform status from backend to frontend format
function transformStatusToFrontend(
backendStatus: "online" | "offline" | "dnd" | "idle" | "invis",
): UserStatus {
switch (backendStatus) {
case "dnd":
return "busy";
case "idle":
return "away";
case "invis":
return "offline";
default:
return "online";
}
}
// Transform status from frontend to backend format
export function transformStatusToBackend(
frontendStatus: UserStatus,
): "online" | "offline" | "dnd" | "idle" | "invis" {
switch (frontendStatus) {
case "busy":
return "dnd";
case "away":
return "idle";
case "offline":
return "invis";
default:
return "online";
}
}
// Hook for login
export const useLogin = () => {
const { setAuth, setLoading } = useAuthStore();
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (
credentials: LoginCredentials,
): Promise<AuthResponse> => {
setLoading(true);
return authClient.login(credentials);
},
onSuccess: (data: AuthResponse) => {
const frontendUser = transformBackendUser(data.user);
setAuth(frontendUser, data.token, data.token); // Use token as refresh token for now
queryClient.clear();
},
onError: (error: Error) => {
console.error("Login failed:", error);
setLoading(false);
},
onSettled: () => {
setLoading(false);
},
});
};
// Hook for registration (requires admin)
export const useRegister = () => {
const { setAuth, setLoading, user, token } = useAuthStore();
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (userData: RegisterData): Promise<AuthResponse> => {
setLoading(true);
if (!user || !token || !user.admin) {
throw new Error("Admin privileges required for user creation");
}
return authClient.register(userData, { id: user.id, token });
},
onSuccess: (data: AuthResponse) => {
const frontendUser = transformBackendUser(data.user);
setAuth(frontendUser, data.token, data.token);
queryClient.clear();
},
onError: (error: Error) => {
console.error("Registration failed:", error);
setLoading(false);
},
onSettled: () => {
setLoading(false);
},
});
};
// Hook for logout
export const useLogout = () => {
const { logout, user } = useAuthStore();
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (): Promise<void> => {
if (user) {
try {
await authClient.logout(user.id);
} catch (error) {
console.warn("Logout endpoint failed:", error);
}
}
},
onSuccess: () => {
logout();
queryClient.clear();
},
onError: (error: Error) => {
console.error("Logout failed:", error);
// Still logout locally even if server request fails
logout();
queryClient.clear();
},
});
};
// Hook for token validation
export const useValidateToken = () => {
const { token, user, setAuth, logout } = useAuthStore();
return useMutation({
mutationFn: async (): Promise<{ valid: boolean; user?: BackendUser }> => {
if (!token || !user) {
throw new Error("No token to validate");
}
return authClient.validateToken(token, user.id);
},
onSuccess: (data) => {
if (!data.valid) {
logout();
} else if (data.user) {
const frontendUser = transformBackendUser(data.user);
setAuth(frontendUser, token!, useAuthStore.getState().refreshToken!);
}
},
onError: (error: Error) => {
console.error("Token validation failed:", error);
logout();
},
});
};
// Hook for token refresh
export const useRefreshToken = () => {
const { refreshToken, user, setAuth, logout } = useAuthStore();
return useMutation({
mutationFn: async (): Promise<AuthResponse> => {
if (!refreshToken || !user) {
throw new Error("No refresh token available");
}
return authClient.refreshToken(refreshToken, user.id);
},
onSuccess: (data: AuthResponse) => {
const frontendUser = transformBackendUser(data.user);
setAuth(frontendUser, data.token, data.token);
},
onError: (error: Error) => {
console.error("Token refresh failed:", error);
logout();
},
});
};

View File

@@ -0,0 +1,139 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { categoryApi } from "@/lib/api-client";
// Get categories by instance ID
export const useCategoriesByInstance = (instanceId: string | undefined) => {
return useQuery({
queryKey: ["categories", instanceId],
queryFn: () =>
instanceId
? categoryApi.getCategoriesByInstance(instanceId)
: Promise.resolve([]),
enabled: !!instanceId,
staleTime: 500 * 1, // 5 minutes
});
};
// Get single category by ID
export const useCategoryById = (categoryId: string | undefined) => {
return useQuery({
queryKey: ["category", categoryId],
queryFn: () =>
categoryId
? categoryApi.getCategoryById(categoryId)
: Promise.resolve(null),
enabled: !!categoryId,
staleTime: 500 * 1,
});
};
// Create category mutation
export const useCreateCategory = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: categoryApi.createCategory,
onSuccess: (data, variables) => {
// Invalidate categories for the instance
queryClient.invalidateQueries({
queryKey: ["categories", variables.instanceId],
});
// Also invalidate instance details to refresh the sidebar
queryClient.invalidateQueries({
queryKey: ["instance", variables.instanceId],
});
},
onError: (error) => {
console.error("Failed to create category:", error);
},
});
};
// Update category mutation
export const useUpdateCategory = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
categoryId,
...data
}: {
categoryId: string;
id: string;
name?: string;
description?: string;
position?: number;
userId: string;
}) => categoryApi.updateCategory(categoryId, data),
onSuccess: (data, variables) => {
// Update the specific category in cache
queryClient.invalidateQueries({
queryKey: ["category", variables.categoryId],
});
// Invalidate categories list
queryClient.invalidateQueries({ queryKey: ["categories"] });
// Invalidate instance details
queryClient.invalidateQueries({ queryKey: ["instance"] });
},
onError: (error) => {
console.error("Failed to update category:", error);
},
});
};
// Delete category mutation
export const useDeleteCategory = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
categoryId,
userId,
}: {
categoryId: string;
userId: string;
}) => categoryApi.deleteCategory(categoryId, userId),
onSuccess: (data, variables) => {
// Remove the category from cache
queryClient.removeQueries({
queryKey: ["category", variables.categoryId],
});
// Invalidate categories list
queryClient.invalidateQueries({ queryKey: ["categories"] });
// Invalidate instance details
queryClient.invalidateQueries({ queryKey: ["instance"] });
},
onError: (error) => {
console.error("Failed to delete category:", error);
},
});
};
// Delete all categories by instance mutation
export const useDeleteAllCategoriesByInstance = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
instanceId,
userId,
}: {
instanceId: string;
userId: string;
}) => categoryApi.deleteAllCategoriesByInstance(instanceId, userId),
onSuccess: (data, variables) => {
// Remove all categories for this instance from cache
queryClient.removeQueries({
queryKey: ["categories", variables.instanceId],
});
queryClient.removeQueries({ queryKey: ["category"] });
// Invalidate instance details
queryClient.invalidateQueries({
queryKey: ["instance", variables.instanceId],
});
},
onError: (error) => {
console.error("Failed to delete all categories:", error);
},
});
};

View File

@@ -1,86 +0,0 @@
import { Message } from "@/types/database";
import { useQuery } from "@tanstack/react-query";
// Sample messages data
export const SAMPLE_MESSAGES = [
{
id: "1",
content: "Hey everyone! Just finished the new theme system. Check it out!",
channelId: "1", // general channel
userId: "1",
edited: false,
createdAt: new Date(Date.now() - 5 * 60 * 1000).toISOString(),
updatedAt: new Date(Date.now() - 5 * 60 * 1000).toISOString(),
},
{
id: "2",
content:
"Looking great! The dark mode especially feels much better on the eyes 👀",
channelId: "1",
userId: "2",
edited: false,
createdAt: new Date(Date.now() - 4 * 60 * 1000).toISOString(),
updatedAt: new Date(Date.now() - 4 * 60 * 1000).toISOString(),
},
{
id: "3",
content: "Can we add a **high contrast mode** for accessibility?",
channelId: "1",
userId: "3",
edited: false,
createdAt: new Date(Date.now() - 3 * 60 * 1000).toISOString(),
updatedAt: new Date(Date.now() - 3 * 60 * 1000).toISOString(),
},
{
id: "4",
content:
"```typescript\nconst theme = {\n primary: 'oklch(0.6 0.2 240)',\n secondary: 'oklch(0.8 0.1 60)'\n};\n```\nHere's how the new color system works!",
channelId: "1",
userId: "3",
edited: false,
createdAt: new Date(Date.now() - 2 * 60 * 1000).toISOString(),
updatedAt: new Date(Date.now() - 2 * 60 * 1000).toISOString(),
},
{
id: "5",
content:
"Perfect timing! I was just about to ask about the color format. _OKLCH_ is so much better than HSL for this.",
channelId: "1",
userId: "1",
edited: false,
createdAt: new Date(Date.now() - 1 * 60 * 1000).toISOString(),
updatedAt: new Date(Date.now() - 1 * 60 * 1000).toISOString(),
},
// Messages for random channel
{
id: "6",
content: "Anyone up for a game tonight?",
channelId: "2", // random channel
userId: "2",
edited: false,
createdAt: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
updatedAt: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
},
{
id: "7",
content: "I'm in! What are we playing?",
channelId: "2",
userId: "1",
edited: false,
createdAt: new Date(Date.now() - 25 * 60 * 1000).toISOString(),
updatedAt: new Date(Date.now() - 25 * 60 * 1000).toISOString(),
},
];
export const useChannelMessages = (channelId?: string) => {
return useQuery({
queryKey: ["messages", channelId],
queryFn: async (): Promise<Message[]> => {
if (!channelId) return [];
await new Promise((resolve) => setTimeout(resolve, 100));
return SAMPLE_MESSAGES.filter((msg) => msg.channelId === channelId);
},
enabled: !!channelId,
staleTime: 1000 * 60 * 1,
});
};

View File

@@ -0,0 +1,313 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiClient, Message } from "@/lib/api-client";
import { useAuthStore } from "@/stores/authStore";
// Hook for getting messages in a channel with pagination
export const useChannelMessages = (channelId?: string, limit = 50) => {
return useQuery({
queryKey: ["messages", channelId, limit],
queryFn: async (): Promise<Message[]> => {
if (!channelId) return [];
try {
const date = new Date();
const messages = await apiClient.getMessages({
date: date.toISOString(),
channelId: channelId,
});
return messages || [];
} catch (error) {
console.error("Failed to fetch messages:", error);
return [];
}
},
enabled: !!channelId,
staleTime: 500 * 1,
refetchInterval: 500 * 1,
});
};
// Hook for getting older messages (pagination)
export const useChannelMessagesPaginated = (
channelId?: string,
beforeDate?: Date,
limit = 50,
) => {
return useQuery({
queryKey: [
"messages",
channelId,
"paginated",
beforeDate?.toISOString(),
limit,
],
queryFn: async (): Promise<Message[]> => {
if (!channelId || !beforeDate) return [];
try {
const messages = await apiClient.getMessages({
date: beforeDate.toISOString(),
channelId: channelId,
});
return messages || [];
} catch (error) {
console.error("Failed to fetch paginated messages:", error);
return [];
}
},
enabled: !!channelId && !!beforeDate,
staleTime: 500 * 1,
});
};
// Hook for sending messages
export const useSendMessage = () => {
const queryClient = useQueryClient();
const { user, token } = useAuthStore();
return useMutation({
mutationFn: async (data: {
channelId: string;
content: string;
repliedMessageId?: string | null;
}) => {
if (!user || !token) {
throw new Error("Authentication required");
}
const requestData = {
channelId: data.channelId,
userId: user.id,
content: data.content,
token: token,
repliedMessageId: data.repliedMessageId,
};
try {
const message = await apiClient.sendMessage(requestData);
return message;
} catch (error) {
console.error("Failed to send message:", error);
throw new Error("Failed to send message");
}
},
onSuccess: (_, variables) => {
queryClient.invalidateQueries({
queryKey: ["messages", variables.channelId],
});
},
onError: (error) => {
console.error("Send message failed:", error);
},
});
};
// Hook for deleting messages
export const useDeleteMessage = () => {
const queryClient = useQueryClient();
const { user, token } = useAuthStore();
return useMutation({
mutationFn: async (data: { messageId: string; channelId: string }) => {
if (!user || !token) {
throw new Error("Authentication required");
}
// TODO: Replace with actual API call when available
return { success: true, messageId: data.messageId };
},
onSuccess: (result, variables) => {
// Update the cache to mark message as deleted
queryClient.setQueryData(
["messages", variables.channelId],
(oldData: Message[] | undefined) => {
if (!oldData) return oldData;
return oldData.map((msg) =>
msg.id === result.messageId
? { ...msg, content: "[Message deleted]", deleted: true }
: msg,
);
},
);
},
onError: (error) => {
console.error("Delete message failed:", error);
},
});
};
// Hook for editing messages
export const useEditMessage = () => {
const queryClient = useQueryClient();
const { user, token } = useAuthStore();
return useMutation({
mutationFn: async (data: {
messageId: string;
content: string;
channelId: string;
}) => {
if (!user || !token) {
throw new Error("Authentication required");
}
// TODO: Replace with actual API call when available
console.log(
"Editing message:",
data.messageId,
"New content:",
data.content,
);
return {
success: true,
messageId: data.messageId,
content: data.content,
edited: true,
};
},
onSuccess: (result, variables) => {
// Update the cache with edited message
queryClient.setQueryData(
["messages", variables.channelId],
(oldData: Message[] | undefined) => {
if (!oldData) return oldData;
return oldData.map((msg) =>
msg.id === result.messageId
? { ...msg, content: result.content, edited: result.edited }
: msg,
);
},
);
},
onError: (error) => {
console.error("Edit message failed:", error);
},
});
};
// Hook for pinning/unpinning messages
export const usePinMessage = () => {
const queryClient = useQueryClient();
const { user, token } = useAuthStore();
return useMutation({
mutationFn: async (data: {
messageId: string;
channelId: string;
pinned: boolean;
}) => {
if (!user || !token) {
throw new Error("Authentication required");
}
// TODO: Replace with actual API call when available
console.log(
`${data.pinned ? "Pinning" : "Unpinning"} message:`,
data.messageId,
);
return {
success: true,
messageId: data.messageId,
pinned: data.pinned,
};
},
onSuccess: (result, variables) => {
// Update the cache with pinned status
queryClient.setQueryData(
["messages", variables.channelId],
(oldData: Message[] | undefined) => {
if (!oldData) return oldData;
return oldData.map((msg) =>
msg.id === result.messageId
? { ...msg, pinned: result.pinned }
: msg,
);
},
);
// Also invalidate pinned messages query if it exists
queryClient.invalidateQueries({
queryKey: ["pinned-messages", variables.channelId],
});
},
onError: (error) => {
console.error("Pin message failed:", error);
},
});
};
// Hook for getting pinned messages
export const usePinnedMessages = (channelId?: string) => {
return useQuery({
queryKey: ["pinned-messages", channelId],
queryFn: async (): Promise<Message[]> => {
if (!channelId) return [];
try {
// TODO: Replace with actual API call when available
// For now, return empty array
return [];
} catch (error) {
console.error("Failed to fetch pinned messages:", error);
return [];
}
},
enabled: !!channelId,
staleTime: 500 * 1,
});
};
// Hook for loading more messages (infinite scroll)
export const useLoadMoreMessages = (channelId?: string) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (data: { beforeDate: Date }) => {
if (!channelId) return [];
try {
const messages = await apiClient.getMessages({
date: data.beforeDate.toISOString(),
channelId: channelId,
});
return messages || [];
} catch (error) {
console.error("Failed to load more messages:", error);
return [];
}
},
onSuccess: (newMessages) => {
if (newMessages.length > 0) {
// Prepend new messages to existing messages
queryClient.setQueryData(
["messages", channelId],
(oldData: Message[] | undefined) => {
if (!oldData) return newMessages;
// Remove duplicates and sort by creation date
const combined = [...newMessages, ...oldData];
const unique = combined.filter(
(msg, index, arr) =>
arr.findIndex((m) => m.id === msg.id) === index,
);
return unique.sort(
(a, b) =>
new Date(a.createdAt).getTime() -
new Date(b.createdAt).getTime(),
);
},
);
}
},
});
};

View File

@@ -1,337 +1,119 @@
import { useQuery } from "@tanstack/react-query";
import { Instance, User } from "@/types/database";
import { InstanceWithDetails } from "@/types/api";
import { CategoryWithChannels } from "@/types/api";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
apiClient,
Instance,
Category,
Channel,
BackendUser,
} from "@/lib/api-client";
import { useAuthStore } from "@/stores/authStore";
// Sample users data with proper Role structure
export const SAMPLE_USERS: User[] = [
{
id: "1",
username: "alice_dev",
nickname: "Alice",
bio: "Frontend developer who loves React",
picture: null,
banner: null,
status: "online" as const,
// Extended types with relations for frontend use
export interface CategoryWithChannels extends Category {
channels: Channel[];
}
export interface InstanceWithDetails extends Instance {
categories: CategoryWithChannels[];
}
// Transform backend user to frontend user format for compatibility
function transformBackendUserToFrontend(backendUser: BackendUser) {
return {
id: backendUser.id,
username: backendUser.userName,
nickname: backendUser.nickName,
bio: backendUser.bio,
picture: backendUser.picture,
banner: backendUser.banner,
hashPassword: "",
admin: false,
admin: backendUser.admin,
status:
backendUser.status === "dnd"
? "busy"
: backendUser.status === "idle"
? "away"
: backendUser.status === "invis"
? "offline"
: backendUser.status,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
roles: [], // Will be populated per instance
},
{
id: "2",
username: "bob_designer",
nickname: "Bob",
bio: "UI/UX Designer & Coffee Enthusiast",
picture:
"https://media.istockphoto.com/id/1682296067/photo/happy-studio-portrait-or-professional-man-real-estate-agent-or-asian-businessman-smile-for.jpg?s=612x612&w=0&k=20&c=9zbG2-9fl741fbTWw5fNgcEEe4ll-JegrGlQQ6m54rg=",
banner: null,
status: "away" as const,
hashPassword: "",
admin: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
roles: [],
},
{
id: "3",
username: "charlie_backend",
nickname: "Charlie",
bio: "Backend wizard, scaling systems since 2018",
picture: null,
banner: null,
status: "busy" as const,
hashPassword: "",
admin: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
roles: [],
},
{
id: "current",
username: "you",
nickname: "You",
bio: "That's you!",
picture: null,
banner: null,
status: "online" as const,
hashPassword: "",
admin: true,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
roles: [],
},
];
roles: backendUser.role.map((r) => ({
instanceId: r.instanceId || "",
role: r.role || "member",
})),
};
}
// Sample servers data
const SAMPLE_SERVERS: Instance[] = [
{
id: "1",
name: "Dev Team",
icon: null,
description: "Our development team server",
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
{
id: "2",
name: "Gaming Squad",
icon: null,
description: "Gaming and fun times",
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
{
id: "3",
name: "Book Club",
icon: null,
description: "Monthly book discussions",
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
];
// Sample messages data
export const SAMPLE_MESSAGES = [
{
id: "1",
content: "Hey everyone! Just finished the new theme system. Check it out!",
channelId: "1", // general channel
userId: "1",
edited: false,
createdAt: new Date(Date.now() - 5 * 60 * 1000).toISOString(),
updatedAt: new Date(Date.now() - 5 * 60 * 1000).toISOString(),
},
{
id: "2",
content:
"Looking great! The dark mode especially feels much better on the eyes 👀",
channelId: "1",
userId: "2",
edited: false,
createdAt: new Date(Date.now() - 4 * 60 * 1000).toISOString(),
updatedAt: new Date(Date.now() - 4 * 60 * 1000).toISOString(),
},
{
id: "3",
content: "Can we add a **high contrast mode** for accessibility?",
channelId: "1",
userId: "3",
edited: false,
createdAt: new Date(Date.now() - 3 * 60 * 1000).toISOString(),
updatedAt: new Date(Date.now() - 3 * 60 * 1000).toISOString(),
},
{
id: "4",
content:
"```typescript\nconst theme = {\n primary: 'oklch(0.6 0.2 240)',\n secondary: 'oklch(0.8 0.1 60)'\n};\n```\nHere's how the new color system works!",
channelId: "1",
userId: "3",
edited: false,
createdAt: new Date(Date.now() - 2 * 60 * 1000).toISOString(),
updatedAt: new Date(Date.now() - 2 * 60 * 1000).toISOString(),
},
{
id: "5",
content:
"Perfect timing! I was just about to ask about the color format. _OKLCH_ is so much better than HSL for this.",
channelId: "1",
userId: "1",
edited: false,
createdAt: new Date(Date.now() - 1 * 60 * 1000).toISOString(),
updatedAt: new Date(Date.now() - 1 * 60 * 1000).toISOString(),
},
// Messages for random channel
{
id: "6",
content: "Anyone up for a game tonight?",
channelId: "2", // random channel
userId: "2",
edited: false,
createdAt: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
updatedAt: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
},
{
id: "7",
content: "I'm in! What are we playing?",
channelId: "2",
userId: "1",
edited: false,
createdAt: new Date(Date.now() - 25 * 60 * 1000).toISOString(),
updatedAt: new Date(Date.now() - 25 * 60 * 1000).toISOString(),
},
];
// Sample categories with channels
const createSampleCategories = (instanceId: string): CategoryWithChannels[] => [
{
id: "1",
name: "Text Channels",
instanceId: instanceId,
position: 0,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
channels: [
{
id: "1",
name: "general",
type: "text",
categoryId: "1",
instanceId: instanceId,
position: 0,
description: "General discussion about development and projects",
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
{
id: "2",
name: "random",
type: "text",
categoryId: "1",
instanceId: instanceId,
position: 1,
description: "Random chat and off-topic discussions",
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
{
id: "3",
name: "announcements",
type: "text",
categoryId: "1",
instanceId: instanceId,
position: 2,
description: "Important announcements and updates",
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
],
},
{
id: "2",
name: "Voice Channels",
instanceId: instanceId,
position: 1,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
channels: [
{
id: "4",
name: "General",
type: "voice",
categoryId: "2",
instanceId: instanceId,
position: 0,
description: "",
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
{
id: "5",
name: "Focus Room",
type: "voice",
categoryId: "2",
instanceId: instanceId,
position: 1,
description: "",
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
],
},
{
id: "3",
name: "Project Channels",
instanceId: instanceId,
position: 2,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
channels: [
{
id: "6",
name: "frontend",
type: "text",
categoryId: "3",
instanceId: instanceId,
position: 0,
description: "Frontend development discussions",
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
{
id: "7",
name: "backend",
type: "text",
categoryId: "3",
instanceId: instanceId,
position: 1,
description: "Backend and API development",
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
],
},
];
// Placeholder hook for channels by instance
export const useChannels = (instanceId?: string) => {
return useQuery({
queryKey: ["channels", instanceId],
queryFn: async (): Promise<CategoryWithChannels[]> => {
if (!instanceId) return [];
return createSampleCategories(instanceId);
},
enabled: !!instanceId,
staleTime: 1000 * 60 * 5, // 5 minutes
});
};
// Hook for getting messages in a channel
export const useChannelMessages = (channelId?: string) => {
return useQuery({
queryKey: ["messages", channelId],
queryFn: async () => {
if (!channelId) return [];
// Return messages for this channel
return SAMPLE_MESSAGES.filter((msg) => msg.channelId === channelId);
},
enabled: !!channelId,
staleTime: 1000 * 60 * 1, // 1 minute (messages are more dynamic)
});
};
// Placeholder hook for servers/instances
// Hook for getting all servers/instances
export const useServers = () => {
return useQuery({
queryKey: ["servers"],
queryFn: async (): Promise<Instance[]> => {
await new Promise((resolve) => setTimeout(resolve, 100));
return SAMPLE_SERVERS;
try {
const instances = await apiClient.getInstances();
return instances;
} catch (error) {
console.error("Failed to fetch servers:", error);
throw new Error("Failed to fetch servers");
}
},
staleTime: 1000 * 60 * 5,
staleTime: 500 * 1,
});
};
// Hook for getting detailed instance info with categories and channels
export const useInstanceDetails = (instanceId?: string) => {
return useQuery({
queryKey: ["instance", instanceId],
queryFn: async (): Promise<InstanceWithDetails | null> => {
if (!instanceId) return null;
await new Promise((resolve) => setTimeout(resolve, 100));
const server = SAMPLE_SERVERS.find((s) => s.id === instanceId);
if (!server) return null;
try {
// Get instance basic info
const instances = await apiClient.getInstances();
const instance = instances.find((s) => s.id === instanceId);
if (!instance) return null;
return {
...server,
categories: createSampleCategories(instanceId),
};
// Get categories for this instance
const categories = await apiClient.getCategoriesByInstance(instanceId);
// For each category, get its channels
const categoriesWithChannels: CategoryWithChannels[] =
await Promise.all(
categories.map(async (category): Promise<CategoryWithChannels> => {
try {
const channels = await apiClient.getChannelsByCategory(
category.id,
);
return {
...category,
channels: channels || [],
};
} catch (error) {
console.warn(
`Failed to fetch channels for category ${category.id}:`,
error,
);
return {
...category,
channels: [],
};
}
}),
);
return {
...instance,
categories: categoriesWithChannels,
};
} catch (error) {
console.error("Failed to fetch instance details:", error);
throw new Error("Failed to fetch instance details");
}
},
enabled: !!instanceId,
staleTime: 1000 * 60 * 5,
staleTime: 500 * 1,
});
};
@@ -339,21 +121,149 @@ export const useInstanceDetails = (instanceId?: string) => {
export const useInstanceMembers = (instanceId?: string) => {
return useQuery({
queryKey: ["instance", instanceId, "members"],
queryFn: async (): Promise<User[]> => {
queryFn: async () => {
if (!instanceId) return [];
await new Promise((resolve) => setTimeout(resolve, 100));
return SAMPLE_USERS.map((user, index) => ({
...user,
roles: [
{
instanceId: instanceId,
role: index === 0 ? "admin" : index === 1 ? "mod" : "member",
},
],
}));
try {
const backendUsers = await apiClient.getUsersByInstance(instanceId);
// Transform backend users to frontend format for compatibility
return backendUsers.map(transformBackendUserToFrontend);
} catch (error) {
console.error("Failed to fetch instance members:", error);
throw new Error("Failed to fetch instance members");
}
},
enabled: !!instanceId,
staleTime: 1000 * 60 * 2,
staleTime: 500 * 1,
});
};
// Hook for creating a new server/instance
export const useCreateInstance = () => {
const queryClient = useQueryClient();
const { user, token } = useAuthStore();
return useMutation({
mutationFn: async (data: { name: string; icon?: string }) => {
if (!user || !token) {
throw new Error("Authentication required");
}
const requestData = {
...data,
requestingUserId: user.id,
requestingUserToken: token,
};
try {
const instance = await apiClient.createInstance(requestData);
return instance;
} catch (error) {
console.error("Failed to create instance:", error);
throw new Error("Failed to create instance");
}
},
onSuccess: () => {
// Invalidate servers list to refetch
queryClient.invalidateQueries({ queryKey: ["servers"] });
},
});
};
// Hook for creating a new category
export const useCreateCategory = () => {
const queryClient = useQueryClient();
const { user, token } = useAuthStore();
return useMutation({
mutationFn: async (data: {
name: string;
instanceId?: string;
position: number;
}) => {
if (!user || !token) {
throw new Error("Authentication required");
}
const requestData = {
...data,
admin: user.admin,
requestingUserId: user.id,
requestingUserToken: token,
};
try {
const category = await apiClient.createCategory(requestData);
return category;
} catch (error) {
console.error("Failed to create category:", error);
throw new Error("Failed to create category");
}
},
onSuccess: (_, variables) => {
// Invalidate instance details to refetch categories
if (variables.instanceId) {
queryClient.invalidateQueries({
queryKey: ["instance", variables.instanceId],
});
}
},
});
};
// Hook for creating a new channel
export const useCreateChannel = () => {
const queryClient = useQueryClient();
const { user, token } = useAuthStore();
return useMutation({
mutationFn: async (data: {
type: "text" | "voice";
name: string;
description: string;
categoryId?: string;
}) => {
if (!user || !token) {
throw new Error("Authentication required");
}
const requestData = {
...data,
admin: user.admin,
requestingUserId: user.id,
requestingUserToken: token,
};
try {
const channel = await apiClient.createChannel(requestData);
return channel;
} catch (error) {
console.error("Failed to create channel:", error);
throw new Error("Failed to create channel");
}
},
onSuccess: (_, variables) => {
// Invalidate related queries
if (variables.categoryId) {
// Find the instance this category belongs to and invalidate it
queryClient.invalidateQueries({
queryKey: ["instance"],
});
}
},
});
};
// Placeholder hook for channels by instance (for backward compatibility)
export const useChannels = (instanceId?: string) => {
const { data: instance } = useInstanceDetails(instanceId);
return useQuery({
queryKey: ["channels", instanceId],
queryFn: async (): Promise<CategoryWithChannels[]> => {
return instance?.categories || [];
},
enabled: !!instanceId && !!instance,
staleTime: 500 * 1,
});
};

View File

@@ -0,0 +1,357 @@
import { QueryClient } from "@tanstack/react-query";
// Base API configuration
export const API_BASE_URL =
import.meta.env.VITE_API_URL || "http://localhost:3000";
// Enhanced QueryClient with error handling
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 500 * 1, // 1 minute
refetchOnWindowFocus: true,
retry: (failureCount, error: any) => {
// Don't retry on auth errors
if (error?.status === 401 || error?.status === 403) return false;
return failureCount < 3;
},
},
mutations: {
retry: (failureCount, error: any) => {
if (error?.status === 401 || error?.status === 403) return false;
return failureCount < 2;
},
},
},
});
// API Response types based on your backend
export interface ApiResponse<T> {
success?: boolean;
data?: T;
error?: string;
}
// Specific response types for your backend
export interface Instance {
id: string;
name: string;
icon?: string | null;
description?: string;
createdAt: string;
updatedAt: string;
}
export interface Category {
id: string;
name: string;
instanceId: string;
position: number;
createdAt: string;
updatedAt: string;
}
export interface Channel {
id: string;
name: string;
type: "text" | "voice";
categoryId: string;
instanceId: string;
position: number;
description?: string;
createdAt: string;
updatedAt: string;
}
export interface BackendUser {
id: string;
userName: string;
nickName: string | null;
bio: string | null;
picture: string | null;
banner: string | null;
admin: boolean;
status: "online" | "offline" | "dnd" | "idle" | "invis";
role: Array<{
userId: string;
instanceId: string;
role?: string;
}>;
}
export interface Message {
id: string;
text: string;
channelId: string;
userId: string;
edited: boolean;
createdAt: string;
deleted: boolean;
updatedAt: string;
replies: MessageReply;
user?: BackendUser;
}
export interface MessageReply {
id: string;
repliesToId: string;
repliesToText: string;
}
// Enhanced fetch wrapper with auth and error handling
export class ApiClient {
private baseUrl: string;
constructor(baseUrl: string = API_BASE_URL) {
this.baseUrl = baseUrl;
}
private async getAuthHeaders(): Promise<Record<string, string>> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
return headers;
}
private async request<T>(
endpoint: string,
options: RequestInit = {},
): Promise<T> {
const url = `${this.baseUrl}${endpoint}`;
const headers = await this.getAuthHeaders();
const config: RequestInit = {
...options,
headers: {
...headers,
...options.headers,
},
};
try {
const response = await fetch(url, config);
if (!response.ok) {
if (response.status === 401) {
// Handle auth error - logout user
const authStore = await import("@/stores/authStore");
authStore.useAuthStore.getState().logout();
throw new Error("Authentication required");
}
const errorData = await response
.json()
.catch(() => ({ error: "Unknown error" }));
throw new Error(errorData.error || `HTTP ${response.status}`);
}
const data = await response.json();
return data as T;
} catch (error) {
console.error(`API request failed: ${endpoint}`, error);
throw error;
}
}
// Instance/Server methods
async getInstances(): Promise<Instance[]> {
const response = await this.request<
{ success: boolean; data: Instance[] } | Instance[]
>("/api/instance");
// Handle both wrapped and direct responses
if (Array.isArray(response)) {
return response;
}
if ("data" in response && Array.isArray(response.data)) {
return response.data;
}
return [];
}
async createInstance(data: {
name: string;
icon?: string;
requestingUserId: string;
requestingUserToken: string;
}): Promise<Instance> {
return this.request<Instance>("/api/instance", {
method: "POST",
body: JSON.stringify(data),
});
}
// Categories methods
async getCategoriesByInstance(instanceId: string): Promise<Category[]> {
try {
const response = await this.request<Category[] | { data: Category[] }>(
`/api/category/instance/${instanceId}`,
);
if (Array.isArray(response)) {
return response;
}
if ("data" in response && Array.isArray(response.data)) {
return response.data;
}
return [];
} catch (error) {
console.warn(
`Categories endpoint not available for instance ${instanceId}`,
error,
);
return [];
}
}
async createCategory(data: {
name: string;
position: number;
instanceId?: string;
admin: boolean;
requestingUserId: string;
requestingUserToken: string;
}): Promise<Category> {
return this.request<Category>("/api/category", {
method: "POST",
body: JSON.stringify(data),
});
}
// Channel methods
async getChannelsByCategory(categoryId: string): Promise<Channel[]> {
try {
const response = await this.request<Channel[] | { data: Channel[] }>(
`/api/channel/category/${categoryId}`,
);
if (Array.isArray(response)) {
return response;
}
if ("data" in response && Array.isArray(response.data)) {
return response.data;
}
return [];
} catch (error) {
console.warn(
`Channels endpoint not available for category ${categoryId}`,
error,
);
return [];
}
}
async createChannel(data: {
type: "text" | "voice";
name: string;
description: string;
categoryId?: string;
admin: boolean;
requestingUserId: string;
requestingUserToken: string;
}): Promise<Channel> {
return this.request<Channel>("/api/channel", {
method: "POST",
body: JSON.stringify(data),
});
}
// Message methods
async getMessages(params: {
date: string;
channelId: string;
}): Promise<Message[]> {
const query = new URLSearchParams(params);
const response = await this.request<Message[] | { data: Message[] }>(
`/api/message?${query}`,
);
if (Array.isArray(response)) {
return response;
}
if ("data" in response && Array.isArray(response.data)) {
return response.data;
}
return [];
}
async sendMessage(data: {
channelId: string;
userId: string;
content: string;
token: string;
repliedMessageId?: string | null;
}): Promise<Message> {
return this.request<Message>("/api/message", {
method: "POST",
body: JSON.stringify(data),
});
}
// User methods
async getUsersByInstance(instanceId: string): Promise<BackendUser[]> {
const query = new URLSearchParams({ instanceId });
const response = await this.request<
BackendUser[] | { data: BackendUser[] }
>(`/api/user?${query}`);
if (Array.isArray(response)) {
return response;
}
if ("data" in response && Array.isArray(response.data)) {
return response.data;
}
return [];
}
async getUser(id: string): Promise<BackendUser> {
const response = await this.request<BackendUser | { data: BackendUser }>(
`/api/user/${id}`,
);
if ("data" in response) {
return response.data;
}
return response as BackendUser;
}
async createUser(data: {
username: string;
nickname?: string;
bio?: string;
picture?: string;
banner?: string;
status?: "online" | "offline" | "dnd" | "idle" | "invis";
admin?: boolean;
requestingUserId: string;
requestingUserToken: string;
passwordhash: string;
}): Promise<{ success: boolean; data?: BackendUser; error?: string }> {
try {
const response = await this.request<BackendUser>("/api/user", {
method: "POST",
body: JSON.stringify(data),
});
return { success: true, data: response };
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : "Unknown error",
};
}
}
}
// Create singleton instance
export const apiClient = new ApiClient();

View File

@@ -0,0 +1,175 @@
import { apiClient, BackendUser } from "./api-client";
export interface LoginCredentials {
username: string;
password: string;
}
export interface RegisterData {
username: string;
password: string;
nickname?: string;
bio?: string;
picture?: string;
banner?: string;
}
export interface AuthResponse {
user: BackendUser;
token: string;
}
class AuthClient {
private baseUrl: string;
constructor(
baseUrl: string = import.meta.env.VITE_API_URL || "http://localhost:3000",
) {
this.baseUrl = baseUrl;
}
async login(credentials: LoginCredentials): Promise<AuthResponse> {
try {
const response = await fetch(`${this.baseUrl}/api/auth/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username: credentials.username,
password: credentials.password,
}),
});
if (!response.ok) {
const errorData = await response
.json()
.catch(() => ({ error: "Login failed" }));
throw new Error(errorData.error || "Login failed");
}
const data: AuthResponse = await response.json();
return data;
} catch (error) {
console.error("Login failed:", error);
throw error instanceof Error ? error : new Error("Login failed");
}
}
async register(
data: RegisterData,
adminUser: { id: string; token: string },
): Promise<AuthResponse> {
try {
const createUserData = {
username: data.username,
nickname: data.nickname,
bio: data.bio,
picture: data.picture,
banner: data.banner,
status: "online" as const,
admin: false,
requestingUserId: adminUser.id,
requestingUserToken: adminUser.token,
passwordhash: data.password,
};
const response = await apiClient.createUser(createUserData);
if (!response.success || !response.data) {
throw new Error(response.error || "Registration failed");
}
try {
const loginResponse = await this.login({
username: data.username,
password: data.password,
});
return loginResponse;
} catch (loginError) {
throw new Error(
"Registration successful, but auto-login failed. Please login manually.",
);
}
} catch (error) {
console.error("Registration failed:", error);
throw error instanceof Error ? error : new Error("Registration failed");
}
}
async validateToken(
token: string,
userId: string,
): Promise<{ valid: boolean; user?: BackendUser }> {
try {
const response = await fetch(`${this.baseUrl}/api/auth/validate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ token, userId }),
});
if (!response.ok) {
return { valid: false };
}
const data: { valid: boolean; user?: BackendUser } =
await response.json();
return data;
} catch (error) {
console.error("Token validation failed:", error);
return { valid: false };
}
}
async refreshToken(oldToken: string, userId: string): Promise<AuthResponse> {
try {
const response = await fetch(`${this.baseUrl}/api/auth/refresh`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ userId, oldToken }),
});
if (!response.ok) {
const errorData = await response
.json()
.catch(() => ({ error: "Token refresh failed" }));
throw new Error(errorData.error || "Token refresh failed");
}
const data: AuthResponse = await response.json();
return data;
} catch (error) {
console.error("Token refresh failed:", error);
throw error instanceof Error ? error : new Error("Token refresh failed");
}
}
async logout(userId: string): Promise<{ success: boolean }> {
try {
const response = await fetch(`${this.baseUrl}/api/auth/logout`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ userId }),
});
if (!response.ok) {
console.warn(
"Logout endpoint failed, but continuing with local logout",
);
}
const data = await response.json().catch(() => ({ success: true }));
return data;
} catch (error) {
console.warn("Logout request failed:", error);
return { success: true }; // Always succeed locally
}
}
}
export const authClient = new AuthClient();

View File

@@ -1,15 +1,33 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.tsx";
import { io } from "socket.io-client";
import "./index.css";
ReactDOM.createRoot(document.getElementById('root')!).render(
function printPayload(data: unknown) {
console.log(data);
}
const socket = io("http://localhost:3000");
socket.on("connect", () => {
console.log("connected!");
socket.emit("ping", "world");
});
socket.on("pong", () => {
console.log("pong");
});
socket.on("joined-voicechannel", printPayload);
socket.on("user-joined-voicechannel", printPayload);
socket.on("error-voicechannel", printPayload);
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
<App socket={socket} />
</React.StrictMode>,
)
);
// Use contextBridge
window.ipcRenderer.on('main-process-message', (_event, message) => {
console.log(message)
})
window.ipcRenderer.on("main-process-message", (_event, message) => {
console.log(message);
});

View File

@@ -1,26 +1,20 @@
import React, { useState, useEffect, useRef } from "react";
import { useNavigate, useParams } from "react-router";
import ReactMarkdown from "react-markdown";
import { Hash, Volume2, Users, Pin } from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import {
Hash,
Volume2,
Users,
Pin,
MoreHorizontal,
Reply,
Plus,
} from "lucide-react";
import { formatDistanceToNow, isValid, parseISO } from "date-fns";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Copy, Edit, Trash2, Reply, MoreHorizontal } from "lucide-react";
import { useInstanceDetails, useInstanceMembers } from "@/hooks/useServers";
import { useChannelMessages } from "@/hooks/useChannel";
import { useUiStore } from "@/stores/uiStore";
import { useAuthStore } from "@/stores/authStore";
import { Message, User } from "@/types/database";
import { MessageProps } from "@/components/message/Message";
import SyntaxHighlighter from "react-syntax-highlighter";
import {
dark,
@@ -28,217 +22,294 @@ import {
} from "react-syntax-highlighter/dist/esm/styles/hljs";
import { useTheme } from "@/components/theme-provider";
// Updated imports for API integration
import { useInstanceDetails, useInstanceMembers } from "@/hooks/useServers";
import {
useChannelMessages,
useLoadMoreMessages,
useSendMessage,
} from "@/hooks/useMessages";
import { useUiStore } from "@/stores/uiStore";
import { useAuthStore } from "@/stores/authStore";
import { Message } from "@/lib/api-client";
// Modal imports
import { MessageActionsModal } from "@/components/modals/MessageActionsModal";
// User type for message component
interface MessageUser {
id: string;
username?: string;
userName?: string;
nickname?: string | null;
nickName?: string | null;
picture?: string | null;
}
// Message Props interface
interface MessageProps {
message: Message;
user: MessageUser;
currentUser: any;
replyTo?: Message;
replyToUser?: MessageUser;
onReply?: (messageId: string) => void;
}
const MessageComponent: React.FC<MessageProps> = ({
message,
user,
currentUser,
replyTo,
onEdit,
onDelete,
replyToUser,
onReply,
isGrouped,
}) => {
const [isHovered, setIsHovered] = useState(false);
const [showActionsModal, setShowActionsModal] = useState(false);
const formatTimestamp = (timestamp: string) => {
return formatDistanceToNow(new Date(timestamp), { addSuffix: true });
};
try {
// First try parsing as ISO string
let date = parseISO(timestamp);
// If that fails, try regular Date constructor
if (!isValid(date)) {
date = new Date(timestamp);
}
// Final check if date is valid
if (!isValid(date)) {
console.error("Invalid timestamp:", timestamp);
return "Invalid date";
}
return formatDistanceToNow(date, { addSuffix: true });
} catch (error) {
console.error("Error formatting timestamp:", timestamp, error);
return "Invalid date";
}
};
const isOwnMessage = currentUser?.id === message.userId;
const { mode } = useTheme();
// Get username with fallback
const username = user.username || user.userName || "Unknown User";
const displayName = user.nickname || user.nickName || username;
const isDeleted = message.deleted;
if (isDeleted) {
return (
<div className="px-4 py-2 opacity-50">
<div className="flex gap-3">
<div className="w-10 flex-shrink-0" />
<div className="flex-1 min-w-0">
<div className="text-sm text-concord-secondary italic border border-border rounded px-3 py-2 bg-concord-tertiary/50">
This message has been deleted
</div>
</div>
</div>
</div>
);
}
return (
<div
className={`group relative px-4 hover:bg-concord-secondary/50 transition-colors ${
isGrouped ? "mt-0 py-0" : "mt-4"
}`}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
<div className="flex gap-3">
{/* Avatar - only show if not grouped */}
<div className="w-10 flex-shrink-0">
{!isGrouped && (
<>
<div
className="group relative px-4 py-2 hover:bg-concord-secondary/50 transition-colors"
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
<div className="flex gap-3">
{/* Avatar - always show */}
<div className="w-10 flex-shrink-0">
<Avatar className="h-10 w-10">
<AvatarImage
src={user.picture || undefined}
alt={user.username}
/>
<AvatarImage src={user.picture || undefined} alt={username} />
<AvatarFallback className="text-sm bg-primary text-primary-foreground">
{user.username.slice(0, 2).toUpperCase()}
{username.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
)}
</div>
{/* Message content */}
<div className="flex-1 min-w-0">
{/* Reply line and reference */}
{replyTo && (
<div className="flex items-center gap-2 mb-2 text-xs text-concord-secondary">
<div className="w-6 h-3 border-l-2 border-t-2 border-concord-secondary/50 rounded-tl-md ml-2" />
<span className="font-medium text-concord-primary">
{replyTo?.user?.nickname || replyTo?.user?.username}
</span>
<span className="truncate max-w-xs opacity-75">
{replyTo.content.replace(/```[\s\S]*?```/g, "[code]")}
</span>
</div>
)}
{/* Header - only show if not grouped */}
{!isGrouped && (
</div>
{/* Message content */}
<div className="flex-1 min-w-0">
{/* Reply line and reference */}
{replyTo && replyToUser && (
<div className="flex items-center gap-2 mb-2 text-xs text-concord-secondary">
<div className="w-6 h-3 border-l-2 border-t-2 border-concord-secondary/50 rounded-tl-md ml-2" />
<span className="font-medium text-concord-primary">
{replyToUser.nickname ||
replyToUser.nickName ||
replyToUser.username ||
replyToUser.userName}
</span>
<span className="truncate max-w-xs opacity-75">
{replyTo.text.replace(/```[\s\S]*?```/g, "[code]")}
</span>
</div>
)}
{/* Reply line and reference */}
{replyTo && replyToUser && (
<div className="flex items-center gap-2 mb-2 text-xs text-concord-secondary">
<div className="w-6 h-3 border-l-2 border-t-2 border-concord-secondary/50 rounded-tl-md ml-2" />
<span className="font-medium text-concord-primary">
{replyToUser.nickname ||
replyToUser.nickName ||
replyToUser.username ||
replyToUser.userName}
</span>
<span className="truncate max-w-xs opacity-75">
{replyTo.text.replace(/```[\s\S]*?```/g, "[code]")}
</span>
</div>
)}
{/* Header - always show */}
<div className="flex items-baseline gap-2 mb-1">
<span className="font-semibold text-concord-primary">
{user.nickname || user.username}
{displayName}
</span>
<span className="text-xs text-concord-secondary">
{formatTimestamp(message.createdAt)}
</span>
{message.edited && (
<span className="text-xs text-concord-secondary opacity-60">
(edited)
</span>
)}
{(message as any).pinned && (
<Pin className="h-3 w-3 text-yellow-500" />
)}
</div>
{/* Message content with markdown */}
<div className="text-concord-primary leading-relaxed prose prose-sm max-w-none dark:prose-invert">
<ReactMarkdown
components={{
code: ({ node, className, children, ...props }) => {
const match = /language-(\w+)/.exec(className || "");
return match ? (
<div className="flex flex-row flex-1 max-w-2/3 flex-wrap !bg-transparent">
<SyntaxHighlighter
PreTag="div"
children={String(children).replace(/\n$/, "")}
language={match[1]}
style={mode === "light" ? solarizedLight : dark}
className="!bg-concord-secondary p-2 border-2 concord-border rounded-xl"
/>
</div>
) : (
<code className={className}>{children}</code>
);
},
blockquote: ({ children }) => (
<blockquote className="border-l-4 border-primary pl-4 my-2 italic text-concord-secondary bg-concord-secondary/30 py-2 rounded-r">
{children}
</blockquote>
),
p: ({ children }) => (
<p className="my-1 text-concord-primary">{children}</p>
),
strong: ({ children }) => (
<strong className="font-semibold text-concord-primary">
{children}
</strong>
),
em: ({ children }) => (
<em className="italic text-concord-primary">{children}</em>
),
ul: ({ children }) => (
<ul className="list-disc list-inside my-2 text-concord-primary">
{children}
</ul>
),
ol: ({ children }) => (
<ol className="list-decimal list-inside my-2 text-concord-primary">
{children}
</ol>
),
h1: ({ children }) => (
<h1 className="text-xl font-bold my-2 text-concord-primary">
{children}
</h1>
),
h2: ({ children }) => (
<h2 className="text-lg font-bold my-2 text-concord-primary">
{children}
</h2>
),
h3: ({ children }) => (
<h3 className="text-base font-bold my-2 text-concord-primary">
{children}
</h3>
),
a: ({ children, href }) => (
<a
href={href}
className="text-primary hover:underline"
target="_blank"
rel="noopener noreferrer"
>
{children}
</a>
),
}}
>
{message.text}
</ReactMarkdown>
</div>
</div>
{/* Message actions */}
{isHovered && (
<div className="absolute top-0 right-4 bg-concord-secondary border border-border rounded-md shadow-md flex">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 interactive-hover"
onClick={() => onReply?.(message.id)}
>
<Reply className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 interactive-hover"
onClick={() => setShowActionsModal(true)}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</div>
)}
{/* Message content with markdown */}
<div className="text-concord-primary leading-relaxed prose prose-sm max-w-none dark:prose-invert">
<ReactMarkdown
components={{
code: ({ node, className, children, ...props }) => {
const match = /language-(\w+)/.exec(className || "");
return match ? (
<div className="flex flex-row flex-1 max-w-2/3 flex-wrap !bg-transparent">
<SyntaxHighlighter
PreTag="div"
children={String(children).replace(/\n$/, "")}
language={match[1]}
style={mode === "light" ? solarizedLight : dark}
className="!bg-concord-secondary p-2 border-2 concord-border rounded-xl"
/>
</div>
) : (
<code className={className}>{children}</code>
);
},
blockquote: ({ children }) => (
<blockquote className="border-l-4 border-primary pl-4 my-2 italic text-concord-secondary bg-concord-secondary/30 py-2 rounded-r">
{children}
</blockquote>
),
p: ({ children }) => (
<p className="my-1 text-concord-primary">{children}</p>
),
strong: ({ children }) => (
<strong className="font-semibold text-concord-primary">
{children}
</strong>
),
em: ({ children }) => (
<em className="italic text-concord-primary">{children}</em>
),
ul: ({ children }) => (
<ul className="list-disc list-inside my-2 text-concord-primary">
{children}
</ul>
),
ol: ({ children }) => (
<ol className="list-decimal list-inside my-2 text-concord-primary">
{children}
</ol>
),
h1: ({ children }) => (
<h1 className="text-xl font-bold my-2 text-concord-primary">
{children}
</h1>
),
h2: ({ children }) => (
<h2 className="text-lg font-bold my-2 text-concord-primary">
{children}
</h2>
),
h3: ({ children }) => (
<h3 className="text-base font-bold my-2 text-concord-primary">
{children}
</h3>
),
a: ({ children, href }) => (
<a
href={href}
className="text-primary hover:underline"
target="_blank"
rel="noopener noreferrer"
>
{children}
</a>
),
}}
>
{message.content}
</ReactMarkdown>
</div>
</div>
{/* Message actions */}
{isHovered && (
<div className="absolute top-0 right-4 bg-concord-secondary border border-border rounded-md shadow-md flex">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 interactive-hover"
onClick={() => onReply?.(message.id)}
>
<Reply className="h-4 w-4" />
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 interactive-hover"
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem
onClick={() => navigator.clipboard.writeText(message.content)}
>
<Copy className="h-4 w-4 mr-2" />
Copy Text
</DropdownMenuItem>
{isOwnMessage && (
<>
<DropdownMenuItem onClick={() => onEdit?.(message.id)}>
<Edit className="h-4 w-4 mr-2" />
Edit Message
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => onDelete?.(message.id)}
className="text-destructive focus:text-destructive"
>
<Trash2 className="h-4 w-4 mr-2" />
Delete Message
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
)}
</div>
</div>
{/* Message Actions Modal */}
<MessageActionsModal
isOpen={showActionsModal}
onClose={() => setShowActionsModal(false)}
message={message}
isOwnMessage={isOwnMessage}
onReply={onReply}
/>
</>
);
};
// Message Input Component
interface MessageInputProps {
channelId: string;
channelName?: string;
onSendMessage: (content: string) => void;
replyingTo?: Message | null;
onCancelReply?: () => void;
replyingToUser: User | null;
replyingToUser: MessageUser | null;
}
const MessageInput: React.FC<MessageInputProps> = ({
channelId,
channelName,
onSendMessage,
replyingTo,
onCancelReply,
replyingToUser,
@@ -247,6 +318,9 @@ const MessageInput: React.FC<MessageInputProps> = ({
const textareaRef = useRef<HTMLTextAreaElement>(null);
const formRef = useRef<HTMLFormElement>(null);
// Use the API hook for sending messages
const sendMessageMutation = useSendMessage();
// Auto-resize textarea
useEffect(() => {
if (textareaRef.current) {
@@ -255,18 +329,27 @@ const MessageInput: React.FC<MessageInputProps> = ({
}
}, [content]);
const handleSubmit = (e: React.FormEvent) => {
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (content.trim()) {
onSendMessage(content.trim());
setContent("");
if (content.trim() && !sendMessageMutation.isPending) {
try {
await sendMessageMutation.mutateAsync({
channelId,
content: content.trim(),
repliedMessageId: replyingTo?.id || null,
});
setContent("");
onCancelReply?.();
} catch (error) {
console.error("Failed to send message:", error);
}
}
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
formRef.current?.requestSubmit(); // <-- Programmatically submit form
formRef.current?.requestSubmit();
}
};
@@ -278,7 +361,10 @@ const MessageInput: React.FC<MessageInputProps> = ({
<div className="flex items-center gap-2">
<div className="w-6 h-4 border-l-2 border-t-2 border-concord-secondary/50 rounded-tl-md ml-2" />
<span className="font-medium text-concord-primary">
{replyingToUser.nickname || replyingToUser.username}
{replyingToUser.nickname ||
replyingToUser.nickName ||
replyingToUser.username ||
replyingToUser.userName}
</span>
</div>
<Button
@@ -291,7 +377,7 @@ const MessageInput: React.FC<MessageInputProps> = ({
</Button>
</div>
<div className="text-sm text-concord-primary truncate pl-2">
{replyingTo.content.replace(/```[\s\S]*?```/g, "[code]")}
{replyingTo.text.replace(/```[\s\S]*?```/g, "[code]")}
</div>
</div>
)}
@@ -304,14 +390,17 @@ const MessageInput: React.FC<MessageInputProps> = ({
onChange={(e) => setContent(e.target.value)}
onKeyDown={handleKeyDown}
placeholder={`Message #${channelName || "channel"}`}
className="w-full bg-concord-tertiary border border-border rounded-lg px-4 py-3 text-concord-primary placeholder-concord-muted resize-none focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
disabled={sendMessageMutation.isPending}
className="w-full bg-concord-tertiary border border-border rounded-lg px-4 py-3 text-concord-primary placeholder-concord-muted resize-none focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent disabled:opacity-50"
style={{
minHeight: "44px",
maxHeight: "200px",
}}
/>
<div className="absolute right-3 bottom-3 text-xs text-concord-secondary">
Press Enter to send Shift+Enter for new line
{sendMessageMutation.isPending
? "Sending..."
: "Press Enter to send • Shift+Enter for new line"}
</div>
</div>
</form>
@@ -321,40 +410,140 @@ const MessageInput: React.FC<MessageInputProps> = ({
const ChatPage: React.FC = () => {
const { instanceId, channelId } = useParams();
const { data: instance } = useInstanceDetails(instanceId);
const categories = instance?.categories;
const { data: channelMessages } = useChannelMessages(channelId);
const { toggleMemberList, showMemberList } = useUiStore();
const { user: currentUser } = useAuthStore();
const { data: users } = useInstanceMembers(instanceId);
// State for messages and interactions
const [messages, setMessages] = useState<Message[]>([]);
const [replyingTo, setReplyingTo] = useState<Message | null>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const navigate = useNavigate();
// Use sample current user if none exists
const displayCurrentUser =
currentUser || users?.find((u) => u.id === "current");
// ALL HOOKS MUST BE CALLED BEFORE ANY CONDITIONAL LOGIC
// API hooks - called unconditionally
const {
data: instance,
isLoading: instanceLoading,
error: instanceError,
} = useInstanceDetails(instanceId);
const {
data: channelMessages,
isLoading: messagesLoading,
error: messagesError,
} = useChannelMessages(channelId);
const { data: users, isLoading: usersLoading } =
useInstanceMembers(instanceId);
// Find current channel
const currentChannel = categories
?.flatMap((cat) => cat.channels)
?.find((ch) => ch.id === channelId);
// UI state hooks - called unconditionally
const { toggleMemberList, showMemberList } = useUiStore();
const { user: currentUser } = useAuthStore();
// Update messages when channel messages load
useEffect(() => {
if (channelMessages) {
setMessages(channelMessages.map((msg) => ({ ...msg, replyToId: null })));
}
// Local state hooks - called unconditionally
const [replyingTo, setReplyingTo] = useState<Message | null>(null);
const [isLoadingMore, setIsLoadingMore] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null);
const messagesStartRef = useRef<HTMLDivElement>(null);
// API mutation hooks - called unconditionally
const loadMoreMessagesMutation = useLoadMoreMessages(channelId);
// Memoized values - called unconditionally
const categories = instance?.categories;
const currentChannel = React.useMemo(() => {
return categories
?.flatMap((cat) => cat.channels)
?.find((ch) => ch.id === channelId);
}, [categories, channelId]);
const userHasAccess = React.useMemo(() => {
if (!currentUser || !instanceId) return false;
if (currentUser.admin) return true;
return currentUser.roles.some((role) => role.instanceId === instanceId);
}, [currentUser, instanceId]);
const sortedMessages = React.useMemo(() => {
if (!channelMessages) return [];
// Sort messages by createdAt timestamp (oldest first, newest last)
return [...channelMessages].sort((a, b) => {
const dateA = new Date(a.createdAt).getTime();
const dateB = new Date(b.createdAt).getTime();
return dateA - dateB; // ascending order (oldest to newest)
});
}, [channelMessages]);
// Scroll to bottom when messages change
// Effects - called unconditionally
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages]);
}, [channelMessages]);
// Event handlers
const handleLoadMore = React.useCallback(async () => {
if (!channelMessages || channelMessages.length === 0 || isLoadingMore)
return;
setIsLoadingMore(true);
try {
const oldestMessage = channelMessages[0];
await loadMoreMessagesMutation.mutateAsync({
beforeDate: new Date(oldestMessage.createdAt),
});
} catch (error) {
console.error("Failed to load more messages:", error);
} finally {
setIsLoadingMore(false);
}
}, [channelMessages, isLoadingMore, loadMoreMessagesMutation]);
const handleReply = React.useCallback(
(messageId: string) => {
const message = channelMessages?.find((m) => m.id === messageId);
if (message) {
setReplyingTo(message);
}
},
[channelMessages],
);
// Handle loading states
if (instanceLoading || messagesLoading || usersLoading) {
return (
<div className="flex-1 flex items-center justify-center bg-concord-primary">
<div className="text-center text-concord-secondary">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
<p>Loading chat...</p>
</div>
</div>
);
}
// Handle errors and permissions
if (!userHasAccess) {
return (
<div className="flex-1 flex items-center justify-center bg-concord-primary">
<div className="text-center text-concord-secondary">
<h2 className="text-xl font-semibold mb-2 text-destructive">
Access Denied
</h2>
<p className="mb-4">You don't have permission to view this server.</p>
<Button onClick={() => navigate("/")}>Go Home</Button>
</div>
</div>
);
}
if (instanceError || messagesError) {
return (
<div className="flex-1 flex items-center justify-center bg-concord-primary">
<div className="text-center text-concord-secondary">
<h2 className="text-xl font-semibold mb-2 text-destructive">
Error Loading Chat
</h2>
<p className="mb-4">
{instanceError?.message ||
messagesError?.message ||
"Something went wrong"}
</p>
<Button onClick={() => window.location.reload()}>Retry</Button>
</div>
</div>
);
}
// Require both instanceId and channelId for chat
if (!instanceId) {
@@ -362,9 +551,9 @@ const ChatPage: React.FC = () => {
<div className="flex-1 flex items-center justify-center bg-concord-primary">
<div className="text-center text-concord-secondary">
<h2 className="text-xl font-semibold mb-2 text-concord-primary">
No Channel Selected
No Server Selected
</h2>
<p>Select a channel from the sidebar to start chatting.</p>
<p>Select a server from the sidebar to start chatting.</p>
</div>
</div>
);
@@ -373,9 +562,10 @@ const ChatPage: React.FC = () => {
?.flatMap((cat) => cat.channels)
?.find((channel) => channel.position === 0)?.id;
if (existingChannelId)
if (existingChannelId) {
navigate(`/channels/${instanceId}/${existingChannelId}`);
else
return null;
} else {
return (
<div className="flex-1 flex items-center justify-center bg-concord-primary">
<div className="text-center text-concord-secondary">
@@ -386,59 +576,10 @@ const ChatPage: React.FC = () => {
</div>
</div>
);
}
const ChannelIcon = currentChannel?.type === "voice" ? Volume2 : Hash;
// Message handlers
const handleSendMessage = (content: string) => {
if (!displayCurrentUser) return;
const newMessage: Message = {
id: Date.now().toString(),
content,
channelId: channelId || "",
userId: displayCurrentUser.id,
edited: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
replyTo: replyingTo || null,
};
setMessages((prev) => [...prev, newMessage]);
setReplyingTo(null);
};
const handleReply = (messageId: string) => {
const message = messages.find((m) => m.id === messageId);
if (message) {
setReplyingTo(message);
}
};
}
const handleEdit = (messageId: string) => {
// TODO: Implement edit functionality
console.log("Edit message:", messageId);
};
const handleDelete = (messageId: string) => {
setMessages((prev) => prev.filter((m) => m.id !== messageId));
};
// Group messages by user and time
const groupedMessages = messages.reduce((acc, message, index) => {
const prevMessage = index > 0 ? messages[index - 1] : null;
const isGrouped =
prevMessage &&
prevMessage.userId === message.userId &&
!message.replyTo && // Don't group replies
!prevMessage.replyTo && // Don't group if previous was a reply
new Date(message.createdAt).getTime() -
new Date(prevMessage.createdAt).getTime() <
5 * 60 * 1000; // 5 minutes
acc.push({ ...message, isGrouped });
return acc;
}, [] as Message[]);
const ChannelIcon = currentChannel?.type === "voice" ? Volume2 : Hash;
return (
<div className="flex flex-col flex-shrink h-full bg-concord-primary">
@@ -460,13 +601,6 @@ const ChatPage: React.FC = () => {
</div>
<div className="flex items-center space-x-2">
<Button
variant="ghost"
size="icon"
className="h-8 w-8 interactive-hover"
>
<Pin size={16} />
</Button>
<Button
variant="ghost"
size="icon"
@@ -488,6 +622,28 @@ const ChatPage: React.FC = () => {
<div className="flex-1 flex flex-col overflow-hidden">
{/* Messages Area */}
<ScrollArea className="flex-1 min-h-0">
{/* Load More Button */}
{channelMessages && channelMessages.length > 0 && (
<div className="flex justify-center py-2">
<Button
variant="ghost"
size="sm"
onClick={handleLoadMore}
disabled={isLoadingMore}
className="text-xs"
>
{isLoadingMore ? (
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary mr-2"></div>
) : (
<Plus className="h-4 w-4 mr-2" />
)}
{isLoadingMore ? "Loading..." : "Load older messages"}
</Button>
</div>
)}
<div ref={messagesStartRef} />
{/* Welcome Message */}
<div className="px-4 py-6 border-b border-concord/50 flex-shrink-0">
<div className="flex items-center space-x-3 mb-3">
@@ -509,28 +665,29 @@ const ChatPage: React.FC = () => {
<div className="pb-4">
{/* Messages */}
{groupedMessages.length > 0 ? (
{sortedMessages && sortedMessages.length > 0 ? (
<div>
{groupedMessages.map((message) => {
{sortedMessages.map((message) => {
console.log(message);
const user = users?.find((u) => u.id === message.userId);
const replyToMessage = messages.find(
(m) => m.id === message.replyTo?.id,
const replyToMessage = channelMessages?.find(
(m) => m.id === (message as any).repliedMessageId,
);
const replyToUser = replyToMessage?.user;
const replyToUser = replyToMessage
? users?.find((u) => u.id === replyToMessage.userId)
: undefined;
if (!user) return null;
return (
<MessageComponent
key={message.id}
message={message}
user={user}
currentUser={displayCurrentUser}
currentUser={currentUser}
replyTo={replyToMessage}
onEdit={handleEdit}
onDelete={handleDelete}
onReply={handleReply}
replyToUser={replyToUser}
isGrouped={message.isGrouped}
/>
);
})}
@@ -548,19 +705,21 @@ const ChatPage: React.FC = () => {
</ScrollArea>
{/* Message Input */}
<div className="flex-shrink-0">
<MessageInput
channelName={currentChannel?.name}
onSendMessage={handleSendMessage}
replyingTo={replyingTo}
onCancelReply={() => setReplyingTo(null)}
replyingToUser={
replyingTo
? users?.find((u) => u.id === replyingTo.userId) || null
: null
}
/>
</div>
{currentUser && (
<div className="flex-shrink-0">
<MessageInput
channelId={channelId}
channelName={currentChannel?.name}
replyingTo={replyingTo}
onCancelReply={() => setReplyingTo(null)}
replyingToUser={
replyingTo
? users?.find((u) => u.id === replyingTo.userId) || null
: null
}
/>
</div>
)}
</div>
</div>
);

View File

@@ -10,50 +10,31 @@ import {
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { useAuthStore } from "@/stores/authStore";
import { useLogin } from "@/hooks/useAuth";
const LoginPage: React.FC = () => {
const { isAuthenticated, setAuth } = useAuthStore();
const { isAuthenticated } = useAuthStore();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [isLoading, setIsLoading] = useState(false);
// Use the real login hook
const { mutate: login, isPending, error } = useLogin();
// Redirect if already authenticated
if (isAuthenticated) {
return <Navigate to="/channels/@me" replace />;
return <Navigate to="/" replace />;
}
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
setIsLoading(true);
try {
// TODO: Replace with actual login API call
setTimeout(() => {
setAuth(
{
id: "1",
username,
nickname: username,
bio: "Test user",
picture: "",
banner: "",
hashPassword: "",
admin: false,
status: "online",
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
roles: [],
},
"fake-token",
"fake-refresh-token",
);
setIsLoading(false);
}, 1000);
} catch (error) {
console.error("Login failed:", error);
setIsLoading(false);
if (!username.trim() || !password.trim()) {
return;
}
login({ username: username.trim(), password });
};
return (
@@ -69,6 +50,16 @@ const LoginPage: React.FC = () => {
</CardHeader>
<CardContent>
<form onSubmit={handleLogin} className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>
{error instanceof Error
? error.message
: "Login failed. Please try again."}
</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="username" className="text-concord-primary">
Username
@@ -80,9 +71,11 @@ const LoginPage: React.FC = () => {
onChange={(e) => setUsername(e.target.value)}
className="bg-concord-tertiary border-concord text-concord-primary"
placeholder="Enter your username"
disabled={isPending}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="password" className="text-concord-primary">
Password
@@ -94,11 +87,17 @@ const LoginPage: React.FC = () => {
onChange={(e) => setPassword(e.target.value)}
className="bg-concord-tertiary border-concord text-concord-primary"
placeholder="Enter your password"
disabled={isPending}
required
/>
</div>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? "Logging in..." : "Log In"}
<Button
type="submit"
className="w-full"
disabled={isPending || !username.trim() || !password.trim()}
>
{isPending ? "Logging in..." : "Log In"}
</Button>
</form>
</CardContent>

View File

@@ -7,7 +7,7 @@ const NotFoundPage: React.FC = () => {
<h1 className="text-4xl font-bold mb-4 text-concord-primary">404</h1>
<p className="text-xl mb-6">Page not found</p>
<Button asChild>
<a href="/channels/@me">Go Home</a>
<a href="/">Go Home</a>
</Button>
</div>
</div>

View File

@@ -5,12 +5,13 @@ import {
User,
Shield,
Mic,
Eye,
Settings,
ChevronRight,
Eye,
Moon,
Sun,
Monitor,
Lock,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -25,6 +26,7 @@ import {
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { ThemeSelector } from "@/components/theme-selector";
import { useTheme } from "@/components/theme-provider";
import { useAuthStore } from "@/stores/authStore";
@@ -44,6 +46,12 @@ const SETTINGS_SECTIONS: SettingsSection[] = [
icon: User,
description: "Profile, privacy, and account settings",
},
// {
// id: "security",
// title: "Security",
// icon: Lock,
// description: "Password and security settings",
// },
{
id: "appearance",
title: "Appearance",
@@ -58,6 +66,389 @@ const SETTINGS_SECTIONS: SettingsSection[] = [
},
];
const SecuritySettings: React.FC = () => {
const { user } = useAuthStore();
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [isChangingPassword, setIsChangingPassword] = useState(false);
const [passwordError, setPasswordError] = useState("");
const [passwordSuccess, setPasswordSuccess] = useState("");
const [twoFactorEnabled, setTwoFactorEnabled] = useState(false);
const handlePasswordChange = async (e: React.FormEvent) => {
e.preventDefault();
setPasswordError("");
setPasswordSuccess("");
if (!currentPassword || !newPassword || !confirmPassword) {
setPasswordError("All password fields are required");
return;
}
if (newPassword !== confirmPassword) {
setPasswordError("New passwords do not match");
return;
}
if (newPassword.length < 8) {
setPasswordError("New password must be at least 8 characters long");
return;
}
setIsChangingPassword(true);
try {
// TODO: Implement actual password change API call
await new Promise((resolve) => setTimeout(resolve, 1000)); // Simulate API call
console.log("Changing password for user:", user?.id);
// const result = await authClient.changePassword({
// userId: user.id,
// currentPassword,
// newPassword,
// token: authStore.token
// });
setPasswordSuccess("Password changed successfully");
setCurrentPassword("");
setNewPassword("");
setConfirmPassword("");
} catch (error) {
setPasswordError(
"Failed to change password. Please check your current password.",
);
} finally {
setIsChangingPassword(false);
}
};
return (
<div className="space-y-6 flex flex-col justify-center self-center items-stretch w-2/3">
<Card className="w-full p-6">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Lock className="h-5 w-5" />
Change Password
</CardTitle>
<CardDescription>
Update your password to keep your account secure.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{passwordError && (
<Alert variant="destructive">
<AlertDescription>{passwordError}</AlertDescription>
</Alert>
)}
{passwordSuccess && (
<Alert>
<AlertDescription>{passwordSuccess}</AlertDescription>
</Alert>
)}
<form onSubmit={handlePasswordChange} className="space-y-4">
<div className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="current-password">Current Password</Label>
<Input
id="current-password"
type="password"
value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
className="max-w-sm"
required
/>
</div>
<div className="grid gap-2">
<Label htmlFor="new-password">New Password</Label>
<Input
id="new-password"
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
className="max-w-sm"
minLength={8}
required
/>
<p className="text-xs text-muted-foreground">
Must be at least 8 characters long
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="confirm-password">Confirm New Password</Label>
<Input
id="confirm-password"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="max-w-sm"
required
/>
</div>
</div>
<div className="mt-6">
<Button
type="submit"
disabled={
isChangingPassword ||
!currentPassword ||
!newPassword ||
!confirmPassword
}
>
{isChangingPassword
? "Changing Password..."
: "Change Password"}
</Button>
</div>
</form>
</CardContent>
</Card>
<Card className="w-full p-6">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Shield className="h-5 w-5" />
Security Options
</CardTitle>
<CardDescription>
Additional security features for your account.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<div>
<Label className="text-base font-medium">
Two-Factor Authentication
</Label>
<p className="text-sm text-muted-foreground">
Add an extra layer of security to your account
</p>
</div>
<Switch
checked={twoFactorEnabled}
onCheckedChange={setTwoFactorEnabled}
/>
</div>
<Separator />
<div className="space-y-2">
<Label className="text-base font-medium">Active Sessions</Label>
<p className="text-sm text-muted-foreground mb-4">
Manage devices that are currently logged into your account
</p>
<Button variant="outline" size="sm">
View Active Sessions
</Button>
</div>
<Separator />
<div className="space-y-2">
<Label className="text-base font-medium">Account Backup</Label>
<p className="text-sm text-muted-foreground mb-4">
Download a copy of your account data
</p>
<Button variant="outline" size="sm">
Request Data Export
</Button>
</div>
</CardContent>
</Card>
</div>
);
};
const AccountSettings: React.FC = () => {
const { user, updateUser } = useAuthStore();
const [username, setUsername] = useState(user?.username || "");
const [nickname, setNickname] = useState(user?.nickname || "");
const [bio, setBio] = useState(user?.bio || "");
const [isChanged, setIsChanged] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [saveError, setSaveError] = useState("");
const [saveSuccess, setSaveSuccess] = useState("");
const handleSave = async () => {
setSaveError("");
setSaveSuccess("");
setIsSaving(true);
try {
// TODO: Implement actual profile update API call
await new Promise((resolve) => setTimeout(resolve, 1000)); // Simulate API call
console.log("Updating profile:", { username, nickname, bio });
// const updatedUser = await userClient.updateProfile({
// userId: user.id,
// username: username.trim(),
// nickname: nickname.trim() || null,
// bio: bio.trim() || null,
// token: authStore.token
// });
// Update local state
updateUser({
username: username.trim(),
nickname: nickname.trim() || null,
bio: bio.trim() || null,
});
setSaveSuccess("Profile updated successfully");
setIsChanged(false);
} catch (error) {
setSaveError("Failed to update profile. Please try again.");
} finally {
setIsSaving(false);
}
};
const handleChange = () => {
setIsChanged(true);
setSaveError("");
setSaveSuccess("");
};
return (
<div className="space-y-6 flex flex-col justify-center self-center items-stretch w-2/3">
<Card className="w-full p-6">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<User className="h-5 w-5" />
Profile
</CardTitle>
<CardDescription>
Update your profile information and display settings.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{saveError && (
<Alert variant="destructive">
<AlertDescription>{saveError}</AlertDescription>
</Alert>
)}
{saveSuccess && (
<Alert>
<AlertDescription>{saveSuccess}</AlertDescription>
</Alert>
)}
<div className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="username">Username</Label>
<Input
id="username"
value={username}
onChange={(e) => {
setUsername(e.target.value);
handleChange();
}}
className="max-w-sm"
/>
</div>
<div className="grid gap-2">
<Label htmlFor="nickname">Display Name</Label>
<Input
id="nickname"
value={nickname}
onChange={(e) => {
setNickname(e.target.value);
handleChange();
}}
className="max-w-sm"
placeholder="How others see your name"
/>
</div>
<div className="grid gap-2">
<Label htmlFor="bio">Bio</Label>
<Input
id="bio"
value={bio}
onChange={(e) => {
setBio(e.target.value);
handleChange();
}}
className="max-w-sm"
placeholder="Tell others about yourself"
/>
</div>
</div>
<div className="mt-6 flex gap-2">
<Button onClick={handleSave} disabled={!isChanged || isSaving}>
{isSaving ? "Saving..." : "Save Changes"}
</Button>
{isChanged && (
<Button
variant="outline"
onClick={() => {
setUsername(user?.username || "");
setNickname(user?.nickname || "");
setBio(user?.bio || "");
setIsChanged(false);
setSaveError("");
setSaveSuccess("");
}}
>
Reset
</Button>
)}
</div>
</CardContent>
</Card>
<Card className="w-full p-6">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Shield className="h-5 w-5" />
Privacy
</CardTitle>
<CardDescription>
Control who can contact you and see your information.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<div>
<Label className="text-base font-medium">
Allow Direct Messages
</Label>
<p className="text-sm text-muted-foreground">
Let other users send you direct messages
</p>
</div>
<Switch defaultChecked />
</div>
<Separator />
<div className="flex items-center justify-between">
<div>
<Label className="text-base font-medium">
Show Online Status
</Label>
<p className="text-sm text-muted-foreground">
Display when you're online to other users
</p>
</div>
<Switch defaultChecked />
</div>
</CardContent>
</Card>
</div>
);
};
// Appearance Settings Component (keeping existing implementation)
const AppearanceSettings: React.FC = () => {
const {
currentLightTheme,
@@ -67,12 +458,6 @@ const AppearanceSettings: React.FC = () => {
setMode,
setTheme,
} = useTheme();
const [compactMode, setCompactMode] = useState(false);
const [showTimestamps, setShowTimestamps] = useState(true);
const [animationsEnabled, setAnimationsEnabled] = useState(true);
const [reduceMotion, setReduceMotion] = useState(false);
const [highContrast, setHighContrast] = useState(false);
const lightThemes = getThemesForMode("light");
const darkThemes = getThemesForMode("dark");
@@ -339,250 +724,11 @@ const AppearanceSettings: React.FC = () => {
</div>
</CardContent>
</Card>
{/* Display Settings */}
<Card className="w-full p-6">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Eye className="h-5 w-5" />
Display Settings
</CardTitle>
<CardDescription>
Customize how content is displayed in the app.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<div>
<Label className="text-base font-medium">Compact Mode</Label>
<p className="text-sm text-muted-foreground">
Use less space between messages and interface elements
</p>
</div>
<Switch checked={compactMode} onCheckedChange={setCompactMode} />
</div>
<Separator />
<div className="flex items-center justify-between">
<div>
<Label className="text-base font-medium">
Show Message Timestamps
</Label>
<p className="text-sm text-muted-foreground">
Display timestamps next to messages
</p>
</div>
<Switch
checked={showTimestamps}
onCheckedChange={setShowTimestamps}
/>
</div>
<Separator />
<div className="flex items-center justify-between">
<div>
<Label className="text-base font-medium">Enable Animations</Label>
<p className="text-sm text-muted-foreground">
Play animations throughout the interface
</p>
</div>
<Switch
checked={animationsEnabled}
onCheckedChange={setAnimationsEnabled}
/>
</div>
</CardContent>
</Card>
{/* Accessibility */}
<Card className="w-full p-6">
<CardHeader>
<CardTitle>Accessibility</CardTitle>
<CardDescription>
Settings to improve accessibility and usability.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<div>
<Label className="text-base font-medium">Reduce Motion</Label>
<p className="text-sm text-muted-foreground">
Reduce motion and animations for users with vestibular disorders
</p>
</div>
<Switch checked={reduceMotion} onCheckedChange={setReduceMotion} />
</div>
<Separator />
<div className="flex items-center justify-between">
<div>
<Label className="text-base font-medium">High Contrast</Label>
<p className="text-sm text-muted-foreground">
Increase contrast for better visibility
</p>
</div>
<Switch checked={highContrast} onCheckedChange={setHighContrast} />
</div>
</CardContent>
</Card>
</div>
);
};
const AccountSettings: React.FC = () => {
const { user } = useAuthStore();
const [username, setUsername] = useState(user?.username || "");
const [nickname, setNickname] = useState(user?.nickname || "");
const [bio, setBio] = useState(user?.bio || "");
const [email, setEmail] = useState("user@example.com");
const [isChanged, setIsChanged] = useState(false);
const handleSave = () => {
console.log("Saving profile changes:", { username, nickname, bio, email });
setIsChanged(false);
};
const handleChange = () => {
setIsChanged(true);
};
return (
<div className="space-y-6 flex flex-col justify-center self-center items-stretch w-2/3">
<Card className="w-full p-6">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<User className="h-5 w-5" />
Profile
</CardTitle>
<CardDescription>
Update your profile information and display settings.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
value={email}
onChange={(e) => {
setEmail(e.target.value);
handleChange();
}}
className="max-w-sm"
/>
</div>
<div className="grid gap-2">
<Label htmlFor="username">Username</Label>
<Input
id="username"
value={username}
onChange={(e) => {
setUsername(e.target.value);
handleChange();
}}
className="max-w-sm"
/>
</div>
<div className="grid gap-2">
<Label htmlFor="nickname">Display Name</Label>
<Input
id="nickname"
value={nickname}
onChange={(e) => {
setNickname(e.target.value);
handleChange();
}}
className="max-w-sm"
placeholder="How others see your name"
/>
</div>
<div className="grid gap-2">
<Label htmlFor="bio">Bio</Label>
<Input
id="bio"
value={bio}
onChange={(e) => {
setBio(e.target.value);
handleChange();
}}
className="max-w-sm"
placeholder="Tell others about yourself"
/>
</div>
</div>
<div className="mt-6 flex gap-2">
<Button onClick={handleSave} disabled={!isChanged}>
Save Changes
</Button>
{isChanged && (
<Button
variant="outline"
onClick={() => {
setUsername(user?.username || "");
setNickname(user?.nickname || "");
setBio(user?.bio || "");
setEmail("user@example.com");
setIsChanged(false);
}}
>
Reset
</Button>
)}
</div>
</CardContent>
</Card>
<Card className="w-full p-6">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Shield className="h-5 w-5" />
Privacy
</CardTitle>
<CardDescription>
Control who can contact you and see your information.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<div>
<Label className="text-base font-medium">
Allow Direct Messages
</Label>
<p className="text-sm text-muted-foreground">
Let other users send you direct messages
</p>
</div>
<Switch defaultChecked />
</div>
<Separator />
<div className="flex items-center justify-between">
<div>
<Label className="text-base font-medium">
Show Online Status
</Label>
<p className="text-sm text-muted-foreground">
Display when you're online to other users
</p>
</div>
<Switch defaultChecked />
</div>
</CardContent>
</Card>
</div>
);
};
// Voice Settings Component
const VoiceSettings: React.FC = () => {
const [inputVolume, setInputVolume] = useState(75);
const [outputVolume, setOutputVolume] = useState(100);
@@ -700,18 +846,20 @@ const VoiceSettings: React.FC = () => {
const SettingsPage: React.FC = () => {
const { section } = useParams();
const currentSection = section || "appearance";
const currentSection = section || "account";
const renderSettingsContent = () => {
switch (currentSection) {
case "account":
return <AccountSettings />;
case "security":
return <SecuritySettings />;
case "appearance":
return <AppearanceSettings />;
case "voice":
return <VoiceSettings />;
default:
return <AppearanceSettings />;
return <AccountSettings />;
}
};

View File

@@ -0,0 +1,341 @@
import { create } from "zustand";
import { Socket } from "socket.io-client";
// --- TYPE DEFINITIONS ---
interface IceServerConfig {
urls: string | string[];
username?: string;
credential?: string;
}
// The state managed by the store
interface VoiceState {
socket: Socket | null;
localStream: MediaStream | null;
remoteStreams: Map<string, MediaStream>;
peerConnections: Map<string, RTCPeerConnection>;
iceServers: IceServerConfig[];
isConnected: boolean;
isConnecting: boolean;
activeVoiceChannelId: string | null;
isDeafened: boolean;
isMuted: boolean;
}
// Actions that can be performed on the store
interface VoiceActions {
init: (socket: Socket) => void;
joinChannel: (
channelId: string,
userId: string,
token: string,
) => Promise<void>;
leaveChannel: () => void;
cleanup: () => void;
toggleMute: () => void;
toggleDeafen: () => void;
}
// --- ZUSTAND STORE IMPLEMENTATION ---
export const useVoiceStore = create<VoiceState & VoiceActions>((set, get) => {
// --- INTERNAL HELPERS (not exposed in the store's public interface) ---
/**
* Safely closes and removes a single peer connection.
* @param userId The ID of the user whose connection to clean up.
*/
const cleanupPeerConnection = (userId: string) => {
const { peerConnections } = get();
const peerConnection = peerConnections.get(userId);
if (peerConnection) {
peerConnection.close();
peerConnections.delete(userId);
}
set((state) => {
const newStreams = new Map(state.remoteStreams);
newStreams.delete(userId);
return {
remoteStreams: newStreams,
peerConnections: new Map(peerConnections),
};
});
};
/**
* Creates a new RTCPeerConnection for a target user and configures it.
* @param targetUserId The user to connect to.
* @returns The configured RTCPeerConnection instance.
*/
const createPeerConnection = (targetUserId: string): RTCPeerConnection => {
console.log(`Creating peer connection for: ${targetUserId}`);
const { iceServers, localStream, socket, peerConnections } = get();
const peerConnection = new RTCPeerConnection({ iceServers });
// Add local stream tracks to the new connection
if (localStream) {
localStream
.getTracks()
.forEach((track) => peerConnection.addTrack(track, localStream));
}
// Handle ICE candidates
peerConnection.onicecandidate = (event) => {
if (event.candidate && socket) {
socket.emit("webrtc-ice-candidate", {
targetUserId,
candidate: event.candidate,
});
}
};
// Handle incoming remote tracks
peerConnection.ontrack = (event) => {
console.log(`Received remote track from: ${targetUserId}`);
set((state) => {
const newStreams = new Map(state.remoteStreams);
newStreams.set(targetUserId, event.streams[0]);
return { remoteStreams: newStreams };
});
};
// For debugging connection state
peerConnection.onconnectionstatechange = () => {
console.log(
`Connection state change for ${targetUserId}: ${peerConnection.connectionState}`,
);
if (
peerConnection.connectionState === "disconnected" ||
peerConnection.connectionState === "failed"
) {
cleanupPeerConnection(targetUserId);
}
};
peerConnections.set(targetUserId, peerConnection);
set({ peerConnections: new Map(peerConnections) });
return peerConnection;
};
// --- SOCKET EVENT HANDLERS ---
// These are defined once and can be reused by the join/leave actions.
const onJoinedVoiceChannel = async (data: {
connectedUserIds: string[];
iceServers: IceServerConfig[];
}) => {
console.log(
"Successfully joined voice channel. Users:",
data.connectedUserIds,
);
set({
iceServers: data.iceServers,
isConnecting: false,
isConnected: true,
});
for (const userId of data.connectedUserIds) {
const peerConnection = createPeerConnection(userId);
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
get().socket?.emit("webrtc-offer", {
targetUserId: userId,
sdp: peerConnection.localDescription,
});
}
};
const onUserLeft = (data: { userId: string }) => {
console.log(`User ${data.userId} left the channel.`);
cleanupPeerConnection(data.userId);
};
const onWebRTCOffer = async (data: {
senderUserId: string;
sdp: RTCSessionDescriptionInit;
}) => {
console.log("Received WebRTC offer from:", data.senderUserId);
const peerConnection = createPeerConnection(data.senderUserId);
await peerConnection.setRemoteDescription(
new RTCSessionDescription(data.sdp),
);
const answer = await peerConnection.createAnswer();
await peerConnection.setLocalDescription(answer);
get().socket?.emit("webrtc-answer", {
targetUserId: data.senderUserId,
sdp: peerConnection.localDescription,
});
};
const onWebRTCAnswer = async (data: {
senderUserId: string;
sdp: RTCSessionDescriptionInit;
}) => {
console.log("Received WebRTC answer from:", data.senderUserId);
const peerConnection = get().peerConnections.get(data.senderUserId);
if (peerConnection) {
await peerConnection.setRemoteDescription(
new RTCSessionDescription(data.sdp),
);
}
};
const onICECandidate = async (data: {
senderUserId: string;
candidate: RTCIceCandidateInit;
}) => {
const peerConnection = get().peerConnections.get(data.senderUserId);
if (peerConnection && data.candidate) {
try {
await peerConnection.addIceCandidate(
new RTCIceCandidate(data.candidate),
);
} catch (e) {
console.error("Error adding received ICE candidate", e);
}
}
};
const onError = (error: { message: string }) => {
console.error("Voice channel error:", error.message);
get().leaveChannel(); // Disconnect on error
};
// --- STORE DEFINITION (STATE & ACTIONS) ---
return {
// Initial State
socket: null,
localStream: null,
remoteStreams: new Map(),
peerConnections: new Map(),
iceServers: [],
isConnected: false,
isConnecting: false,
activeVoiceChannelId: null,
isMuted: false,
isDeafened: false,
// Actions
init: (socketInstance) => {
set({ socket: socketInstance });
},
joinChannel: async (channelId: string, userId: string, token: string) => {
const { socket, activeVoiceChannelId, leaveChannel, isConnecting } =
get();
if (!socket || isConnecting || activeVoiceChannelId === channelId) return;
if (!userId || !token) {
console.error("Join channel requires user and token.");
return;
}
if (activeVoiceChannelId) {
leaveChannel();
}
set({ isConnecting: true, activeVoiceChannelId: channelId });
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: true,
video: false,
});
set({ localStream: stream });
} catch (error) {
console.error("Could not get user media:", error);
set({ isConnecting: false, activeVoiceChannelId: null });
return;
}
// Attach all necessary listeners for a voice session
socket.on("joined-voicechannel", onJoinedVoiceChannel);
socket.on("user-left-voicechannel", onUserLeft);
socket.on("webrtc-offer", onWebRTCOffer);
socket.on("webrtc-answer", onWebRTCAnswer);
socket.on("webrtc-ice-candidate", onICECandidate);
socket.on("error-voicechannel", onError);
// *** THE FIX: Send user credentials with the join request ***
socket.emit("join-voicechannel", {
userId: userId,
userToken: token,
voiceChannelId: channelId,
});
},
leaveChannel: () => {
const { socket, peerConnections, localStream, activeVoiceChannelId } =
get();
if (!socket || !activeVoiceChannelId) return;
console.log(`Leaving voice channel: ${activeVoiceChannelId}`);
socket.emit("leave-voicechannel", { channelId: activeVoiceChannelId });
// Clean up all event listeners
socket.off("joined-voicechannel");
socket.off("user-left-voicechannel");
socket.off("webrtc-offer");
socket.off("webrtc-answer");
socket.off("webrtc-ice-candidate");
socket.off("error-voicechannel");
// Close all peer connections
peerConnections.forEach((pc) => pc.close());
// Stop local media tracks
localStream?.getTracks().forEach((track) => track.stop());
// Reset state to initial values
set({
localStream: null,
remoteStreams: new Map(),
peerConnections: new Map(),
isConnected: false,
isConnecting: false,
activeVoiceChannelId: null,
iceServers: [],
});
},
toggleMute: () => {
set((state) => {
const newMutedState = !state.isMuted;
if (state.localStream) {
state.localStream.getAudioTracks().forEach((track) => {
track.enabled = !newMutedState;
});
}
// Cannot be deafened and unmuted
if (state.isDeafened && !newMutedState) {
return { isMuted: newMutedState, isDeafened: false };
}
return { isMuted: newMutedState };
});
},
toggleDeafen: () => {
set((state) => {
const newDeafenedState = !state.isDeafened;
// When deafening, you are also muted
if (newDeafenedState && !state.isMuted) {
// Manually mute logic without toggling deafen state again
if (state.localStream) {
state.localStream.getAudioTracks().forEach((track) => {
track.enabled = false;
});
}
return { isDeafened: newDeafenedState, isMuted: true };
}
return { isDeafened: newDeafenedState };
});
},
cleanup: () => {
get().leaveChannel();
set({ socket: null });
},
};
});

View File

@@ -28,14 +28,15 @@ export interface Channel {
updatedAt: string;
}
export type UserStatus = "online" | "away" | "busy" | "offline";
export interface User {
id: string;
username: string;
nickname?: string;
bio?: string;
nickname?: string | null;
bio?: string | null;
picture?: string | null;
banner?: string | null;
hashPassword: string; // Won't be sent to client
hashPassword: string;
admin: boolean;
status: "online" | "away" | "busy" | "offline";
createdAt: string;

View File

@@ -0,0 +1,46 @@
import { BackendUser } from "@/lib/api-client";
import { Message } from "./database";
// API types
export type {
ApiResponse,
Instance,
Category,
Channel,
BackendUser,
Message,
} from "@/lib/api-client";
// Auth types
export type {
LoginCredentials,
RegisterData,
AuthResponse,
} from "@/lib/auth-client";
// Hook types
export type { CategoryWithChannels, InstanceWithDetails } from "@/types/api";
// Frontend User type (for compatibility with existing components)
export interface User {
id: string;
username: string;
nickname?: string | null;
bio?: string | null;
picture?: string | null;
banner?: string | null;
hashPassword: string;
admin: boolean;
status: string;
createdAt: string;
updatedAt: string;
roles: Array<{
instanceId: string;
role: string;
}>;
}
// Message with user for chat components
export interface MessageWithUser extends Message {
user?: User | BackendUser;
}

View File

@@ -0,0 +1,198 @@
import { User, Role } from "@/types/database";
export type UserPermission =
| "view_instance"
| "create_channel"
| "delete_channel"
| "create_category"
| "delete_category"
| "manage_instance"
| "delete_messages"
| "pin_messages"
| "manage_users"
| "create_instance"
| "manage_roles";
export type UserRole = "admin" | "mod" | "member";
// Check if user has a specific role in an instance
export function hasInstanceRole(
user: User | null,
instanceId: string,
role: UserRole,
): boolean {
if (!user) return false;
// Global admins have all permissions
if (user.admin) return true;
const userRole = user.roles.find((r) => r.instanceId === instanceId);
if (!userRole) return false;
switch (role) {
case "admin":
return userRole.role === "admin";
case "mod":
return userRole.role === "admin" || userRole.role === "mod";
case "member":
return (
userRole.role === "admin" ||
userRole.role === "mod" ||
userRole.role === "member"
);
default:
return false;
}
}
// Check if user has access to view an instance
export function canViewInstance(
user: User | null,
instanceId: string,
): boolean {
if (!user) return false;
// Global admins can view all instances
if (user.admin) return true;
// Check if user has any role in this instance
return user.roles.some((role) => role.instanceId === instanceId);
}
// Check if user has a specific permission in an instance
export function hasPermission(
user: User | null,
instanceId: string,
permission: UserPermission,
): boolean {
if (!user) return false;
// Global admins have all permissions everywhere
if (user.admin) return true;
const userRole = user.roles.find((r) => r.instanceId === instanceId);
if (!userRole) return false;
switch (permission) {
case "view_instance":
return hasInstanceRole(user, instanceId, "member");
case "create_channel":
case "delete_channel":
case "create_category":
case "delete_category":
case "manage_instance":
case "manage_users":
case "manage_roles":
return hasInstanceRole(user, instanceId, "admin");
case "delete_messages":
case "pin_messages":
return hasInstanceRole(user, instanceId, "mod");
case "create_instance":
return user.admin; // Only global admins can create instances
default:
return false;
}
}
// Get user's role in a specific instance
export function getUserRole(
user: User | null,
instanceId: string,
): UserRole | null {
if (!user) return null;
// Global admins are always admins
if (user.admin) return "admin";
const userRole = user.roles.find((r) => r.instanceId === instanceId);
return userRole ? (userRole.role as UserRole) : null;
}
// Filter instances that user can access
export function getAccessibleInstances(
user: User | null,
instances: any[],
): any[] {
if (!user) return [];
// Global admins can see all instances
if (user.admin) return instances;
// Filter instances where user has a role
const userInstanceIds = new Set(user.roles.map((role) => role.instanceId));
return instances.filter((instance) => userInstanceIds.has(instance.id));
}
// Check if user can delete a specific message
export function canDeleteMessage(
user: User | null,
instanceId: string,
messageUserId: string,
): boolean {
if (!user) return false;
// Users can always delete their own messages
if (user.id === messageUserId) return true;
// Mods and admins can delete any message
return hasPermission(user, instanceId, "delete_messages");
}
// Check if user can edit a specific message
export function canEditMessage(
user: User | null,
messageUserId: string,
): boolean {
if (!user) return false;
// Users can only edit their own messages
return user.id === messageUserId;
}
// Check if user can pin messages
export function canPinMessage(user: User | null, instanceId: string): boolean {
return hasPermission(user, instanceId, "pin_messages");
}
// Check if user is global admin
export function isGlobalAdmin(user: User | null): boolean {
return user?.admin === true;
}
// Helper to get role display info
export function getRoleDisplayInfo(role: UserRole) {
switch (role) {
case "admin":
return {
name: "Admin",
color: "#ff6b6b",
priority: 3,
description: "Full server permissions",
};
case "mod":
return {
name: "Moderator",
color: "#4ecdc4",
priority: 2,
description: "Can moderate messages and users",
};
case "member":
return {
name: "Member",
color: null,
priority: 1,
description: "Basic server access",
};
default:
return {
name: "Unknown",
color: null,
priority: 0,
description: "Unknown role",
};
}
}

View File

@@ -0,0 +1,8 @@
/*
Warnings:
- You are about to alter the column `text` on the `Message` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(2000)`.
*/
-- AlterTable
ALTER TABLE "public"."Message" ALTER COLUMN "text" SET DATA TYPE VARCHAR(2000);

View File

@@ -1,3 +0,0 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"

View File

@@ -104,7 +104,7 @@ model Message {
User User @relation(fields: [userId], references: [id])
userId String
deleted Boolean
text String
text String @db.VarChar(2000)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
replies Reply? @relation("MessageToReply")

View File

@@ -1,8 +1,10 @@
import {
editMessage,
getMessageInformation,
getMessagesBefore,
sendMessageToChannel,
} from "../services/messageService";
import { PutMessage } from "../validators/messageValidator";
export async function fetchMessageData(id: string) {
return await getMessageInformation(id);
@@ -27,3 +29,7 @@ export async function sendMessage(
repliedMessageId,
);
}
export async function putMessage(data: PutMessage) {
return await editMessage(data);
}

View File

@@ -1,126 +0,0 @@
import { Context } from "hono";
import {
sendMessageToChannel,
removeMessageFromChannel,
} from "../services/realtime.js";
import { success } from "zod";
export async function postMessageToChannel(io: any, c: Context) {
try {
io = c.get("io");
const instanceId = c.req.param("instanceId");
const categoryId = c.req.param("categoryId");
const channelId = c.req.param("channelId");
const message = await c.req.json();
const result = await sendMessageToChannel(
instanceId,
categoryId,
channelId,
message,
"new_channel_message",
io,
);
if (result === "Event not implemented") {
console.log(
"controller::realtime::postMessageToChannel - Failed to send message",
);
return c.json({
success: false,
message: "Event not implemented or recognized",
status: 400,
});
}
if (result === "no acknowledgment") {
console.log(
"controller::realtime::postMessageToChannel - No acknowledgment received from client",
);
return c.json({
success: false,
message: "No acknowledgment received from client",
status: 500,
});
}
if (!result) {
throw new Error("failed to send message");
}
return c.json({
success: true,
message: "Message sent successfully",
status: 200,
});
} catch (err) {
const errMessage = err as Error;
console.log("controller::realtime::postMessageToChannel - ", errMessage);
return c.json({
success: false,
message: errMessage.message,
status: 500,
});
}
}
export async function deleteMessageFromChannel(io: any, c: Context) {
try {
io = c.get("io");
const instanceId = c.req.param("instanceId");
const categoryId = c.req.param("categoryId");
const channelId = c.req.param("channelId");
const messageId = c.req.param("messageId");
const result = await removeMessageFromChannel(
instanceId,
categoryId,
channelId,
messageId,
"delete_channel_message",
io,
);
if (result === "event not implemented") {
console.log(
"controller::realtime::deleteMessageFromChannel - Event not implemented",
);
return c.json({
success: false,
message: "Event not implemented or recognized",
status: 400,
});
}
if (result === "no acknowledgment") {
console.log(
"controller::realtime::deleteMessageFromChannel - No acknowledgment received from client",
);
return c.json({
success: false,
message: "No acknowledgment received from client",
status: 500,
});
}
if (!result) {
throw new Error("failed to delete message");
}
c.json({
success: true,
message: "Message deleted successfully",
status: 200,
});
} catch (err) {
const errMessage = err as Error;
console.log("services::realtime::deleteMessageFromChannel - ", errMessage);
return c.json({
success: false,
message: errMessage.message,
status: 500,
});
}
}

View File

@@ -2,6 +2,7 @@ import {
getAllUsersFrom,
getUserInformation,
createUser,
getUserId,
} from "../services/userService";
import { CreateUserInput } from "../validators/userValidator";
@@ -16,3 +17,7 @@ export async function fetchAllUsers(instanceId: string) {
export async function createNewUser(data: CreateUserInput) {
return await createUser(data);
}
export async function fetchUserId(username: string) {
return await getUserId(username);
}

View File

@@ -5,46 +5,20 @@ import { Server } from "socket.io";
import routes from "./routes/index";
import { Scalar } from "@scalar/hono-api-reference";
import { openAPIRouteHandler } from "hono-openapi";
import { registerSocketHandlers } from "./sockets";
//initialize socket.io server
const io = new Server();
//initialize bun engine
//then bind to socket.io server
const engine = new Engine();
io.bind(engine);
io.on("connection", (socket) => {
//get userId and clientId from query params
const userId = socket.handshake.query.userId;
const clientId = socket.handshake.query.clientId;
if (!userId || Array.isArray(userId)) {
socket.disconnect();
throw new Error("Invalid user ID");
}
if (!clientId || Array.isArray(clientId)) {
socket.disconnect();
throw new Error("Invalid client ID");
}
socket.join(userId);
console.log(
`User ${userId} connected. Client ID ${clientId} on socket ${socket.id}`,
);
socket.on("disconnect", () => {
console.log(`User ${userId} disconnected from socket ${socket.id}`);
});
});
// Routes
const app = new Hono();
app.use(
"*",
cors({
origin: "http://localhost:5173",
allowHeaders: ["Content-Type", "Authorization"],
origin: ["http://localhost:5173", "https://concord.kpuig.net", "http://localhost:3000"],
allowHeaders: [
"Content-Type",
"Authorization",
"Access-Control-Allow-Origin",
],
allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
credentials: true,
}),
@@ -68,4 +42,44 @@ app.get(
app.get("/scalar", Scalar({ url: "/openapi" }));
export default app;
// initialize socket.io server
const io = new Server({
cors: {
origin: ["http://localhost:5173", "https://concord.kpuig.net", "http://localhost:3000"],
credentials: true,
},
});
const engine = new Engine();
io.bind(engine);
// Register socket.io events
registerSocketHandlers(io);
const { websocket } = engine.handler();
export default {
port: 3000,
idleTimeout: 30, // must be greater than the "pingInterval" option of the engine, which defaults to 25 seconds
async fetch(req: Request, server: Bun.Server) {
const url = new URL(req.url);
if (url.pathname === "/socket.io/") {
const response = await engine.handleRequest(req, server);
// Add CORS headers explicitly
const origin = req.headers.get("Origin");
if (
origin &&
["http://localhost:5173", "https://concord.kpuig.net", "http://localhost:3000"].includes(origin)
) {
response.headers.set("Access-Control-Allow-Origin", origin);
}
response.headers.set("Access-Control-Allow-Credentials", "true");
return response;
} else {
return app.fetch(req, server);
}
},
websocket,
};

View File

@@ -0,0 +1,239 @@
import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { describeRoute, resolver } from "hono-openapi";
import {
getUserCredentials,
getUserId,
getUserInformation,
} from "../services/userService";
import shaHash from "../helper/hashing";
import { PrismaClient } from "@prisma/client";
import {
loginSchema,
validateTokenSchema,
refreshTokenSchema,
logoutSchema,
authResponseSchema,
validationResponseSchema,
errorResponseSchema,
successResponseSchema,
} from "../validators/authValidator";
const prisma = new PrismaClient();
const authRoutes = new Hono();
// Login endpoint
authRoutes.post(
"/login",
describeRoute({
description: "User login",
responses: {
200: {
description: "Login successful",
content: {
"application/json": { schema: resolver(authResponseSchema) },
},
},
401: {
description: "Invalid credentials",
content: {
"application/json": { schema: resolver(errorResponseSchema) },
},
},
},
}),
zValidator("json", loginSchema),
async (c) => {
try {
const { username, password } = await c.req.json();
console.log(c.req.json);
// Find user by username
const user = await prisma.user.findFirst({
where: { username: username },
});
if (!user) {
return c.json({ error: "Invalid username or password" }, 401);
}
// get userId
const userIdResult = await getUserId(username);
if (!userIdResult) {
return c.json({ error: "Invalid username or password" }, 401);
}
const userId = userIdResult.userId;
// get user creds
const userCredentials = await getUserCredentials(userId);
if (!userCredentials) {
return c.json({ error: "Invalid username or password" }, 401);
}
// hash the provided password with user ID as salt
const hashedPassword = shaHash(password, userId);
// verify password
if (hashedPassword !== userCredentials.password) {
return c.json({ error: "Invalid username or password" }, 401);
}
// generate new token
const token = crypto.randomUUID();
// Update user's token in database
await prisma.userAuth.update({
where: { userId: user.id },
data: { token: token },
});
// get full user information
const userInfo = await getUserInformation(user.id);
if (!userInfo) {
return c.json({ error: "Failed to get user information" }, 500);
}
return c.json({
user: userInfo,
token: token,
});
} catch (error) {
console.error("Login error:", error);
return c.json({ error: "Internal server error" }, 500);
}
},
);
// Token validation endpoint
authRoutes.post(
"/validate",
describeRoute({
description: "Validate user token",
responses: {
200: {
description: "Token validation result",
content: {
"application/json": { schema: resolver(validationResponseSchema) },
},
},
},
}),
zValidator("json", validateTokenSchema),
async (c) => {
try {
const { token, userId } = await c.req.json();
// Get user credentials
const userCredentials = await getUserCredentials(userId);
if (!userCredentials || userCredentials.token !== token) {
return c.json({ valid: false });
}
// Get user information
const userInfo = await getUserInformation(userId);
if (!userInfo) {
return c.json({ valid: false });
}
return c.json({
valid: true,
user: userInfo,
});
} catch (error) {
return c.json({ valid: false });
}
},
);
// Token refresh endpoint
authRoutes.post(
"/refresh",
describeRoute({
description: "Refresh user token",
responses: {
200: {
description: "Token refreshed successfully",
content: {
"application/json": { schema: resolver(authResponseSchema) },
},
},
401: {
description: "Invalid token",
content: {
"application/json": { schema: resolver(errorResponseSchema) },
},
},
},
}),
zValidator("json", refreshTokenSchema),
async (c) => {
try {
const { userId, oldToken } = await c.req.json();
// Verify old token
const userCredentials = await getUserCredentials(userId);
if (!userCredentials || userCredentials.token !== oldToken) {
return c.json({ error: "Invalid token" }, 401);
}
// Generate new token
const newToken = crypto.randomUUID();
// Update token in database
await prisma.userAuth.update({
where: { userId: userId },
data: { token: newToken },
});
// Get user information
const userInfo = await getUserInformation(userId);
if (!userInfo) {
return c.json({ error: "Failed to get user information" }, 500);
}
return c.json({
user: userInfo,
token: newToken,
});
} catch (error) {
console.error("Token refresh error:", error);
return c.json({ error: "Internal server error" }, 500);
}
},
);
// Logout endpoint (invalidate token)
authRoutes.post(
"/logout",
describeRoute({
description: "User logout",
responses: {
200: {
description: "Logout successful",
content: {
"application/json": { schema: resolver(successResponseSchema) },
},
},
},
}),
zValidator("json", logoutSchema),
async (c) => {
try {
const { userId } = await c.req.json();
// Clear token in database
await prisma.userAuth.update({
where: { userId: userId },
data: { token: null },
});
return c.json({ success: true });
} catch (error) {
console.error("Logout error:", error);
return c.json({ error: "Internal server error" }, 500);
}
},
);
export default authRoutes;

View File

@@ -5,6 +5,7 @@ import messageRoutes from "./messageRoutes";
import { channelRoutes } from "./channelRoutes";
import instanceRoutes from "./instanceRoutes";
import { categoryRoutes } from "./categoryRoutes";
import authRoutes from "./authRoutes";
const routes = new Hono();
@@ -13,5 +14,6 @@ routes.route("/message", messageRoutes);
routes.route("/channel", channelRoutes);
routes.route("/instance", instanceRoutes);
routes.route("/category", categoryRoutes);
routes.route("/auth", authRoutes);
export default routes;

View File

@@ -81,6 +81,28 @@ messageRoutes.get(
},
);
messageRoutes.put(
"/:id",
describeRoute({
description: "Edit message fields",
responses: {
200: {
description: "Success"
},
404: {
description: "Message not found"
},
500: {
description: "Bad request"
}
}
}),
zValidator("json", sendMessageSchema),
async (c) => {
}
)
messageRoutes.post(
"",
describeRoute({

View File

@@ -1,29 +0,0 @@
import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { describeRoute, resolver } from "hono-openapi";
import {
postMessageToChannel,
deleteMessageFromChannel,
} from "../controller/realtime";
const app = new Hono();
app.post(
"message/",
zValidator({
body: z.object({
content: z.string().min(1).max(500),
}),
}),
async (c) => {
const { instanceId, categoryId, channelId } = c.req.params;
const { content } = c.req.body;
return postMessageToChannel(c.get("io"), {
instanceId,
categoryId,
channelId,
content,
});
},
);

View File

@@ -3,16 +3,49 @@ import {
fetchAllUsers,
fetchUserData,
createNewUser,
fetchUserId,
} from "../controller/userController";
import {
createUserSchema,
queryAllUsersByInstanceId,
queryUserByIdSchema,
queryUserByUsernameSchema,
} from "../validators/userValidator";
import { zValidator } from "@hono/zod-validator";
import { describeRoute, resolver } from "hono-openapi";
const userRoutes = new Hono();
userRoutes.get(
"/username/:username",
describeRoute({
description: "Get userId by username",
responses: {
200: {
description: "Success getting userId",
content: {
"application/json": { schema: resolver(queryUserByUsernameSchema) },
},
},
404: {
description: "userId not found",
content: {
"application/json": { schema: resolver(queryUserByUsernameSchema) },
},
},
},
}),
zValidator("param", queryUserByUsernameSchema),
async (c) => {
const username = c.req.param("username");
const userId = await fetchUserId(username);
if (userId) {
return c.json(userId);
} else {
return c.json({ error: "User not found" }, 404);
}
},
);
userRoutes.get(
"/:id",
describeRoute({

View File

@@ -57,3 +57,64 @@ export async function getAllInstances() {
};
}
}
export async function getInstanceByChannelId(id: string) {
try {
const instance = await prisma.instance.findFirst({
where: {
Category: {
some: {
Channel: {
some: {
id: id
}
}
}
}
},
});
if (!instance) {
return null;
}
return instance;
} catch (error) {
console.error("Error fetching instance by channel ID:", error);
return null;
}
}
export async function getInstancesByUserId(id: string) {
try {
const user = await getUserInformation(id);
if (user && user.admin) {
const adminInstances = await getAllInstances();
if (adminInstances && adminInstances.success) {
return adminInstances.data;
}
}
const instance = await prisma.instance.findMany({
where: {
Role: {
some: {
User: {
id: id
}
}
}
}
});
if (!instance) {
return null;
}
return instance;
} catch (error) {
console.error("Error fetching instance by channel ID:", error);
return null;
}
}

View File

@@ -1,5 +1,6 @@
import { PrismaClient } from "@prisma/client";
import { getUserCredentials } from "./userService";
import { PutMessage } from "../validators/messageValidator";
const prisma = new PrismaClient();
@@ -126,6 +127,7 @@ export async function getMessagesBefore(date: string, channelId: string) {
userId: message.userId!,
text: message.text,
deleted: message.deleted,
createdAt: message.createdAt,
replies: originalMessage
? {
messageId: message.id,
@@ -155,6 +157,38 @@ export async function getMessagesBefore(date: string, channelId: string) {
}
}
export async function editMessage(data: PutMessage) {
try {
const userCreds = await getUserCredentials(data.id);
if (
!userCreds ||
userCreds.token == null ||
userCreds.token != data.token
) {
return null;
}
const updatedMessage = await prisma.message.update({
where: {
id: data.id,
},
data: {
text: data.content,
deleted: data.deleted,
},
});
if (!updatedMessage) {
return null;
}
return updatedMessage;
} catch (error) {
console.error("Error editing message:", error);
return null;
}
}
export async function sendMessageToChannel(
channelId: string,
userId: string,

View File

@@ -1,90 +0,0 @@
import { readonly } from "zod";
const EVENTS = {
NEW_CHANNEL_MESSAGE: "new_channel_message",
DELETE_CHANNEL_MESSAGE: "delete_channel_message",
};
export async function sendMessageToChannel(
instanceId: string,
categoryId: string,
channelId: string,
message: any,
event: string,
io: any,
): Promise<string | boolean> {
try {
//TODO: implement middleware to replace this
if (EVENTS.NEW_CHANNEL_MESSAGE === event) {
throw new Error("Event not implemented");
}
//TODO: add prisma to save channel message to DB
return new Promise((resolve) => {
io.to(instanceId).emit(event, message, (ack: any) => {
if (ack && ack.status === "received") {
console.log(`Message ${ack.messageId} acknowledged by client.`);
resolve(true);
} else {
console.log(
"services::realtime::sendMessageToChannel No acknowledgment received from client.",
);
resolve("no acknowledgment");
}
});
});
} catch (err) {
const errMessage = err as Error;
if (errMessage.message === "Event not implemented") {
console.log(
`services::realtime::sendMessageToChannel - Event not implemented. Attempted event: ${event}`,
);
return "event not implemented";
}
console.log("services::realtime::sendMessageToChannel - ", errMessage);
return false;
}
}
export async function removeMessageFromChannel(
instanceId: string,
categoryId: string,
channelId: string,
messageId: string,
event: string,
io: any,
): Promise<string | boolean> {
try {
//TODO: implement middleware to replace this
if (EVENTS.DELETE_CHANNEL_MESSAGE === event) {
throw new Error("event not implemented");
}
//TODO: add prisma to flag a channel message as deleted
return new Promise((resolve) => {
io.to(instanceId).emit(event, { messageId }, (ack: any) => {
if (ack && ack.status === "received") {
console.log(`Message ${ack.messageId} acknowledged by client.`);
resolve(true);
} else {
console.log(
"services::realtime::deleteMessageFromChannel No acknowledgment received from client.",
);
resolve("no acknowledgment");
}
});
});
} catch (err) {
const errMessage = err as Error;
if (errMessage.message === "Event not implemented") {
console.log(
`services::realtime::deleteMessageFromChannel - Event not implemented. Attempted event: ${event}`,
);
return false;
}
console.log("services::realtime::deleteMessageFromChannel - ", errMessage);
return false;
}
}

View File

@@ -64,6 +64,39 @@ export async function createUser(data: CreateUserInput): Promise<{
return userData;
}
export async function getUserId(
username: string,
): Promise<{ userId: string } | null> {
try {
if (!username) throw new Error("missing username");
const user = await prisma.user.findFirst({
where: {
username: username,
},
});
if (!user) throw new Error("could not find user");
return {
userId: user.id,
};
} catch (err) {
const errMessage = err as Error;
if (errMessage.message === "missing username") {
console.log("services::actions::getUserId - no username given");
return null;
}
if (errMessage.message === "could not find user") {
console.log("services::actions::getUserId - unable to find user");
return null;
}
console.log("services::actions::getUserId - unknown error");
return null;
}
}
export async function getUserCredentials(userId: string): Promise<{
userId: string;
password: string;

View File

@@ -0,0 +1,16 @@
import { Server } from "socket.io";
import { registerVoiceHandlers } from "./voiceHandler";
export function registerSocketHandlers(io: Server) {
// bad practice
io.on("connection", (socket) => {
console.log("connected");
socket.on("ping", (c) => {
console.log(c);
socket.emit("pong", c);
});
});
// good practice
registerVoiceHandlers(io);
}

View File

@@ -0,0 +1,309 @@
import { Server, Socket } from "socket.io";
import { getUserCredentials, getUserInformation } from "../services/userService";
import { getAllInstances, getInstanceByChannelId, getInstancesByUserId } from "../services/instanceService";
import { getCategoriesByInstance, getCategory, getChannel } from "../services/channelService";
// Change to Map of voiceChannelId to Map of userId to socket
const voiceChannelMembers = new Map<string, Map<string, Socket>>();
// Types for WebRTC messages
interface WebRTCOffer {
targetUserId: string;
sdp: RTCSessionDescriptionInit;
}
interface WebRTCAnswer {
targetUserId: string;
sdp: RTCSessionDescriptionInit;
}
interface WebRTCIceCandidate {
targetUserId: string;
candidate: RTCIceCandidateInit;
}
// Future ICE server configuration
// This can be expanded later to include TURN servers
interface IceServerConfig {
urls: string | string[];
username?: string;
credential?: string;
}
export function registerVoiceHandlers(io: Server) {
io.on("connection", (socket: Socket) => {
// Join voice channel
socket.on("join-voicechannel", async (data) => {
const payload = data as {
userId: string
userToken: string,
voiceChannelId: string,
};
if (!payload) {
socket.emit("error-voicechannel", "no payload in voice conn")
return;
}
// Initialize map for channel if not present
if (!voiceChannelMembers.has(payload.voiceChannelId)) {
voiceChannelMembers.set(payload.voiceChannelId, new Map());
}
const channelMembers = voiceChannelMembers.get(payload.voiceChannelId)!;
// Remove user if already present in this channel
if (channelMembers.has(payload.userId)) {
channelMembers.delete(payload.userId);
}
// authenticate user
const userCreds = await getUserCredentials(payload.userId);
if (!userCreds || !userCreds.token || userCreds.token != payload.userToken) {
socket.emit("error-voicechannel", "bad user creds in voice conn");
return;
}
// determine if channel is voice channel
const channel = await getChannel(payload.voiceChannelId);
if (!channel || channel.type !== "voice" || !channel.categoryId) {
socket.emit("error-voicechannel", "bad channel or channel type in voice conn");
return;
}
// authorize user using role
const user = await getUserInformation(payload.userId);
const instance = await getInstanceByChannelId(payload.voiceChannelId);
const instances = await getInstancesByUserId(payload.userId);
if (!user || !instance || !instances || !instances.find(e => e.id === instance.id)) {
socket.emit("error-voicechannel", "user not authorized for channel in voice conn");
return;
}
// add to map
channelMembers.set(payload.userId, socket);
socket.join(payload.voiceChannelId);
socket.emit("joined-voicechannel", {
voiceChannelId: payload.voiceChannelId,
connectedUserIds: Array.from(channelMembers.keys()).filter(e => e !== payload.userId),
iceServers: getIceServers() // Send ICE server config to client
});
socket.to(payload.voiceChannelId).emit("user-joined-voicechannel", { userId: payload.userId });
// Store userId in socket.data for easier access later
socket.data.userId = payload.userId;
socket.data.currentVoiceChannelId = payload.voiceChannelId;
});
// Leave voice channel
socket.on("leave-voicechannel", async (data) => {
const payload = data as {
userId: string,
userToken: string,
voiceChannelId: string,
};
if (!payload) {
socket.emit("error-voicechannel", "no payload in leave voice request");
return;
}
const channelMembers = voiceChannelMembers.get(payload.voiceChannelId);
if (!channelMembers) {
socket.emit("error-voicechannel", "voice channel not found");
return;
}
// authenticate user
const userCreds = await getUserCredentials(payload.userId);
if (!userCreds || !userCreds.token || userCreds.token != payload.userToken) {
socket.emit("error-voicechannel", "bad user creds in leave voice request");
return;
}
// Remove user from channel
if (channelMembers.has(payload.userId)) {
channelMembers.delete(payload.userId);
// Leave the socket.io room
socket.leave(payload.voiceChannelId);
// Notify other users in the channel
io.to(payload.voiceChannelId).emit("user-left-voicechannel", {
userId: payload.userId,
voiceChannelId: payload.voiceChannelId
});
// Clean up empty channels
if (channelMembers.size === 0) {
voiceChannelMembers.delete(payload.voiceChannelId);
}
// Confirm to the user that they've left
socket.emit("left-voicechannel", {
voiceChannelId: payload.voiceChannelId
});
// Clear socket data
socket.data.currentVoiceChannelId = undefined;
} else {
socket.emit("error-voicechannel", "user not in voice channel");
}
});
// Handle disconnection
socket.on("disconnect", () => {
// Get the user ID and current voice channel from socket data
const userId = socket.data.userId;
const voiceChannelId = socket.data.currentVoiceChannelId;
// If we have the channel ID stored, use it directly
if (userId && voiceChannelId) {
const channelMembers = voiceChannelMembers.get(voiceChannelId);
if (channelMembers && channelMembers.has(userId)) {
// Remove the user from the channel
channelMembers.delete(userId);
// Notify other members
io.to(voiceChannelId).emit("user-left-voicechannel", {
userId,
voiceChannelId,
reason: "disconnected"
});
// Clean up empty channels
if (channelMembers.size === 0) {
voiceChannelMembers.delete(voiceChannelId);
}
}
} else {
// If we don't have the info stored, search through all channels
voiceChannelMembers.forEach((members, channelId) => {
// Use Array.from to convert Map entries to array for iteration
Array.from(members.entries()).forEach(([memberId, memberSocket]) => {
if (memberSocket.id === socket.id) {
// Found the user in this channel
members.delete(memberId);
// Notify other members
io.to(channelId).emit("user-left-voicechannel", {
userId: memberId,
voiceChannelId: channelId,
reason: "disconnected"
});
// Clean up empty channels
if (members.size === 0) {
voiceChannelMembers.delete(channelId);
}
}
});
});
}
});
// Handle WebRTC Offer
socket.on("webrtc-offer", async (data) => {
const payload = data as { targetUserId: string; sdp: any };
const senderUserId = socket.data.userId;
const voiceChannelId = socket.data.currentVoiceChannelId;
if (!payload || !senderUserId || !voiceChannelId) {
socket.emit("error-voicechannel", "Invalid WebRTC offer payload or sender not in voice channel");
return;
}
const channelMembers = voiceChannelMembers.get(voiceChannelId);
const targetSocket = channelMembers?.get(payload.targetUserId);
if (targetSocket) {
targetSocket.emit("webrtc-offer", {
senderUserId: senderUserId,
sdp: payload.sdp
});
} else {
socket.emit("error-voicechannel", "Target user not found in voice channel");
}
});
// Handle WebRTC Answer
socket.on("webrtc-answer", (data: WebRTCAnswer) => {
const senderUserId = socket.data.userId;
const voiceChannelId = socket.data.currentVoiceChannelId;
if (!data || !senderUserId || !voiceChannelId) {
socket.emit("error-voicechannel", "Invalid WebRTC answer data");
return;
}
// Forward the answer to the target user
const channelMembers = voiceChannelMembers.get(voiceChannelId);
const targetSocket = channelMembers?.get(data.targetUserId);
if (targetSocket) {
targetSocket.emit("webrtc-answer", {
senderUserId: senderUserId,
sdp: data.sdp
});
} else {
socket.emit("error-voicechannel", "Target user not found in voice channel");
}
});
// Handle ICE Candidates
socket.on("webrtc-ice-candidate", (data: WebRTCIceCandidate) => {
const senderUserId = socket.data.userId;
const voiceChannelId = socket.data.currentVoiceChannelId;
if (!data || !senderUserId || !voiceChannelId) {
socket.emit("error-voicechannel", "Invalid ICE candidate data");
return;
}
// Forward the ICE candidate to the target user
const channelMembers = voiceChannelMembers.get(voiceChannelId);
const targetSocket = channelMembers?.get(data.targetUserId);
if (targetSocket) {
targetSocket.emit("webrtc-ice-candidate", {
senderUserId: senderUserId,
candidate: data.candidate
});
} else {
socket.emit("error-voicechannel", "Target user not found in voice channel");
}
});
});
}
/**
* Get the current ICE server configuration.
* This function returns STUN servers and includes TURN server credentials
* if they are available in the environment variables.
*/
function getIceServers(): IceServerConfig[] {
const iceServers: IceServerConfig[] = [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' },
];
// Add own STUN server if configured
const stunServerUrl = process.env.STUN_SERVER_URL;
if (stunServerUrl) {
iceServers.push({ urls: stunServerUrl });
}
// Add TURN server if configured in environment variables
const turnServerUrl = process.env.TURN_SERVER_URL;
const turnUsername = process.env.TURN_SERVER_USERNAME;
const turnCredential = process.env.TURN_SERVER_CREDENTIAL;
if (turnServerUrl && turnUsername && turnCredential) {
iceServers.push({
urls: turnServerUrl,
username: turnUsername,
credential: turnCredential,
});
}
return iceServers;
}

View File

@@ -0,0 +1,57 @@
import { z } from "zod";
export const loginSchema = z.object({
username: z.string().min(3).max(30),
password: z.string().min(1),
});
export const validateTokenSchema = z.object({
token: z.string(),
userId: z.uuidv7(),
});
export const refreshTokenSchema = z.object({
userId: z.uuidv7(),
oldToken: z.string(),
});
export const logoutSchema = z.object({
userId: z.uuidv7(),
});
// Response schemas for OpenAPI documentation
export const authResponseSchema = z.object({
user: z.object({
id: z.string(),
userName: z.string(),
nickName: z.string().nullable(),
bio: z.string().nullable(),
picture: z.string().nullable(),
banner: z.string().nullable(),
admin: z.boolean(),
status: z.enum(["online", "offline", "dnd", "idle", "invis"]),
role: z.array(z.any()),
}),
token: z.string(),
});
export const validationResponseSchema = z.object({
valid: z.boolean(),
user: z.any().optional(),
});
export const errorResponseSchema = z.object({
error: z.string(),
});
export const successResponseSchema = z.object({
success: z.boolean(),
});
// Type exports
export type LoginInput = z.infer<typeof loginSchema>;
export type ValidateTokenInput = z.infer<typeof validateTokenSchema>;
export type RefreshTokenInput = z.infer<typeof refreshTokenSchema>;
export type LogoutInput = z.infer<typeof logoutSchema>;
export type AuthResponse = z.infer<typeof authResponseSchema>;
export type ValidationResponse = z.infer<typeof validationResponseSchema>;

View File

@@ -18,3 +18,12 @@ export const sendMessageSchema = z.object({
token: z.string(),
repliedMessageId: z.uuidv7().nullable().optional(),
});
export const putMessageSchema = z.object({
id: z.uuidv7(),
content: z.string().optional(),
deleted: z.boolean().optional(),
token: z.string(),
});
export type PutMessage = z.infer<typeof putMessageSchema>;

View File

@@ -0,0 +1,18 @@
import { z } from "zod";
export const postMessageToChannelSchema = z.object({
instanceId: z.uuidv7(),
categoryId: z.uuidv7(),
channelId: z.uuidv7(),
userId: z.uuidv7(),
content: z.string().min(1).max(2000),
repliedMessageId: z.uuidv7().optional(),
token: z.string(),
});
//TODO: add more realtime related validators as needed
export type PostMessageToChannelInput = z.infer<
typeof postMessageToChannelSchema
>;
//TODO: create more input schemas for other realtime actions

View File

@@ -4,10 +4,14 @@ export const queryUserByIdSchema = z.object({
id: z.uuidv7(),
});
export const queryUserByUsernameSchema = z.object({
username: z.string().min(3).max(30),
});
export const queryAllUsersByInstanceId = z.object({
instanceId: z.uuidv7(),
});
import { is } from "zod/v4/locales";
export const createUserSchema = z.object({
username: z.string().min(3).max(30),
nickname: z.string().min(1).max(30).optional(),