.
This commit is contained in:
3
app/.prettierrc
Normal file
3
app/.prettierrc
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"tabWidth": 4
|
||||
}
|
||||
346
app/app.css
346
app/app.css
@@ -4,194 +4,204 @@
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme {
|
||||
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif,
|
||||
"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
||||
--font-sans:
|
||||
"Inter", ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji",
|
||||
"Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
||||
}
|
||||
|
||||
:root {
|
||||
--background: oklch(1.00 0 0);
|
||||
--foreground: oklch(0.32 0 0);
|
||||
--card: oklch(1.00 0 0);
|
||||
--card-foreground: oklch(0.32 0 0);
|
||||
--popover: oklch(1.00 0 0);
|
||||
--popover-foreground: oklch(0.32 0 0);
|
||||
--primary: oklch(0.62 0.19 259.81);
|
||||
--primary-foreground: oklch(1.00 0 0);
|
||||
--secondary: oklch(0.97 0.00 264.54);
|
||||
--secondary-foreground: oklch(0.45 0.03 256.80);
|
||||
--muted: oklch(0.98 0.00 247.84);
|
||||
--muted-foreground: oklch(0.55 0.02 264.36);
|
||||
--accent: oklch(0.95 0.03 236.82);
|
||||
--accent-foreground: oklch(0.38 0.14 265.52);
|
||||
--destructive: oklch(0.64 0.21 25.33);
|
||||
--destructive-foreground: oklch(1.00 0 0);
|
||||
--border: oklch(0.93 0.01 264.53);
|
||||
--input: oklch(0.93 0.01 264.53);
|
||||
--ring: oklch(0.62 0.19 259.81);
|
||||
--chart-1: oklch(0.62 0.19 259.81);
|
||||
--chart-2: oklch(0.55 0.22 262.88);
|
||||
--chart-3: oklch(0.49 0.22 264.38);
|
||||
--chart-4: oklch(0.42 0.18 265.64);
|
||||
--chart-5: oklch(0.38 0.14 265.52);
|
||||
--sidebar: oklch(0.98 0.00 247.84);
|
||||
--sidebar-foreground: oklch(0.32 0 0);
|
||||
--sidebar-primary: oklch(0.62 0.19 259.81);
|
||||
--sidebar-primary-foreground: oklch(1.00 0 0);
|
||||
--sidebar-accent: oklch(0.95 0.03 236.82);
|
||||
--sidebar-accent-foreground: oklch(0.38 0.14 265.52);
|
||||
--sidebar-border: oklch(0.93 0.01 264.53);
|
||||
--sidebar-ring: oklch(0.62 0.19 259.81);
|
||||
--font-sans: Inter, sans-serif;
|
||||
--font-serif: Source Serif 4, serif;
|
||||
--font-mono: JetBrains Mono, monospace;
|
||||
--radius: 0.375rem;
|
||||
--shadow-2xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05);
|
||||
--shadow-xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05);
|
||||
--shadow-sm: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 1px 2px -1px hsl(0 0% 0% / 0.10);
|
||||
--shadow: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 1px 2px -1px hsl(0 0% 0% / 0.10);
|
||||
--shadow-md: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 2px 4px -1px hsl(0 0% 0% / 0.10);
|
||||
--shadow-lg: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 4px 6px -1px hsl(0 0% 0% / 0.10);
|
||||
--shadow-xl: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 8px 10px -1px hsl(0 0% 0% / 0.10);
|
||||
--shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / 0.25);
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.32 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.32 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.32 0 0);
|
||||
--primary: oklch(0.62 0.19 259.81);
|
||||
--primary-foreground: oklch(1 0 0);
|
||||
--secondary: oklch(0.97 0 264.54);
|
||||
--secondary-foreground: oklch(0.45 0.03 256.8);
|
||||
--muted: oklch(0.98 0 247.84);
|
||||
--muted-foreground: oklch(0.55 0.02 264.36);
|
||||
--accent: oklch(0.95 0.03 236.82);
|
||||
--accent-foreground: oklch(0.38 0.14 265.52);
|
||||
--destructive: oklch(0.64 0.21 25.33);
|
||||
--destructive-foreground: oklch(1 0 0);
|
||||
--border: oklch(0.93 0.01 264.53);
|
||||
--input: oklch(0.93 0.01 264.53);
|
||||
--ring: oklch(0.62 0.19 259.81);
|
||||
--chart-1: oklch(0.62 0.19 259.81);
|
||||
--chart-2: oklch(0.55 0.22 262.88);
|
||||
--chart-3: oklch(0.49 0.22 264.38);
|
||||
--chart-4: oklch(0.42 0.18 265.64);
|
||||
--chart-5: oklch(0.38 0.14 265.52);
|
||||
--sidebar: oklch(0.98 0 247.84);
|
||||
--sidebar-foreground: oklch(0.32 0 0);
|
||||
--sidebar-primary: oklch(0.62 0.19 259.81);
|
||||
--sidebar-primary-foreground: oklch(1 0 0);
|
||||
--sidebar-accent: oklch(0.95 0.03 236.82);
|
||||
--sidebar-accent-foreground: oklch(0.38 0.14 265.52);
|
||||
--sidebar-border: oklch(0.93 0.01 264.53);
|
||||
--sidebar-ring: oklch(0.62 0.19 259.81);
|
||||
--font-sans: Inter, sans-serif;
|
||||
--font-serif: Source Serif 4, serif;
|
||||
--font-mono: JetBrains Mono, monospace;
|
||||
--radius: 0.375rem;
|
||||
--shadow-2xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05);
|
||||
--shadow-xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05);
|
||||
--shadow-sm:
|
||||
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1);
|
||||
--shadow:
|
||||
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1);
|
||||
--shadow-md:
|
||||
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 2px 4px -1px hsl(0 0% 0% / 0.1);
|
||||
--shadow-lg:
|
||||
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 4px 6px -1px hsl(0 0% 0% / 0.1);
|
||||
--shadow-xl:
|
||||
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 8px 10px -1px hsl(0 0% 0% / 0.1);
|
||||
--shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / 0.25);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.20 0 0);
|
||||
--foreground: oklch(0.92 0 0);
|
||||
--card: oklch(0.27 0 0);
|
||||
--card-foreground: oklch(0.92 0 0);
|
||||
--popover: oklch(0.27 0 0);
|
||||
--popover-foreground: oklch(0.92 0 0);
|
||||
--primary: oklch(0.62 0.19 259.81);
|
||||
--primary-foreground: oklch(1.00 0 0);
|
||||
--secondary: oklch(0.27 0 0);
|
||||
--secondary-foreground: oklch(0.92 0 0);
|
||||
--muted: oklch(0.27 0 0);
|
||||
--muted-foreground: oklch(0.72 0 0);
|
||||
--accent: oklch(0.38 0.14 265.52);
|
||||
--accent-foreground: oklch(0.88 0.06 254.13);
|
||||
--destructive: oklch(0.64 0.21 25.33);
|
||||
--destructive-foreground: oklch(1.00 0 0);
|
||||
--border: oklch(0.37 0 0);
|
||||
--input: oklch(0.37 0 0);
|
||||
--ring: oklch(0.62 0.19 259.81);
|
||||
--chart-1: oklch(0.71 0.14 254.62);
|
||||
--chart-2: oklch(0.62 0.19 259.81);
|
||||
--chart-3: oklch(0.55 0.22 262.88);
|
||||
--chart-4: oklch(0.49 0.22 264.38);
|
||||
--chart-5: oklch(0.42 0.18 265.64);
|
||||
--sidebar: oklch(0.20 0 0);
|
||||
--sidebar-foreground: oklch(0.92 0 0);
|
||||
--sidebar-primary: oklch(0.62 0.19 259.81);
|
||||
--sidebar-primary-foreground: oklch(1.00 0 0);
|
||||
--sidebar-accent: oklch(0.38 0.14 265.52);
|
||||
--sidebar-accent-foreground: oklch(0.88 0.06 254.13);
|
||||
--sidebar-border: oklch(0.37 0 0);
|
||||
--sidebar-ring: oklch(0.62 0.19 259.81);
|
||||
--font-sans: Inter, sans-serif;
|
||||
--font-serif: Source Serif 4, serif;
|
||||
--font-mono: JetBrains Mono, monospace;
|
||||
--radius: 0.375rem;
|
||||
--shadow-2xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05);
|
||||
--shadow-xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05);
|
||||
--shadow-sm: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 1px 2px -1px hsl(0 0% 0% / 0.10);
|
||||
--shadow: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 1px 2px -1px hsl(0 0% 0% / 0.10);
|
||||
--shadow-md: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 2px 4px -1px hsl(0 0% 0% / 0.10);
|
||||
--shadow-lg: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 4px 6px -1px hsl(0 0% 0% / 0.10);
|
||||
--shadow-xl: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 8px 10px -1px hsl(0 0% 0% / 0.10);
|
||||
--shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / 0.25);
|
||||
--background: oklch(0.2 0 0);
|
||||
--foreground: oklch(0.92 0 0);
|
||||
--card: oklch(0.27 0 0);
|
||||
--card-foreground: oklch(0.92 0 0);
|
||||
--popover: oklch(0.27 0 0);
|
||||
--popover-foreground: oklch(0.92 0 0);
|
||||
--primary: oklch(0.62 0.19 259.81);
|
||||
--primary-foreground: oklch(1 0 0);
|
||||
--secondary: oklch(0.27 0 0);
|
||||
--secondary-foreground: oklch(0.92 0 0);
|
||||
--muted: oklch(0.27 0 0);
|
||||
--muted-foreground: oklch(0.72 0 0);
|
||||
--accent: oklch(0.38 0.14 265.52);
|
||||
--accent-foreground: oklch(0.88 0.06 254.13);
|
||||
--destructive: oklch(0.64 0.21 25.33);
|
||||
--destructive-foreground: oklch(1 0 0);
|
||||
--border: oklch(0.37 0 0);
|
||||
--input: oklch(0.37 0 0);
|
||||
--ring: oklch(0.62 0.19 259.81);
|
||||
--chart-1: oklch(0.71 0.14 254.62);
|
||||
--chart-2: oklch(0.62 0.19 259.81);
|
||||
--chart-3: oklch(0.55 0.22 262.88);
|
||||
--chart-4: oklch(0.49 0.22 264.38);
|
||||
--chart-5: oklch(0.42 0.18 265.64);
|
||||
--sidebar: oklch(0.2 0 0);
|
||||
--sidebar-foreground: oklch(0.92 0 0);
|
||||
--sidebar-primary: oklch(0.62 0.19 259.81);
|
||||
--sidebar-primary-foreground: oklch(1 0 0);
|
||||
--sidebar-accent: oklch(0.38 0.14 265.52);
|
||||
--sidebar-accent-foreground: oklch(0.88 0.06 254.13);
|
||||
--sidebar-border: oklch(0.37 0 0);
|
||||
--sidebar-ring: oklch(0.62 0.19 259.81);
|
||||
--font-sans: Inter, sans-serif;
|
||||
--font-serif: Source Serif 4, serif;
|
||||
--font-mono: JetBrains Mono, monospace;
|
||||
--radius: 0.375rem;
|
||||
--shadow-2xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05);
|
||||
--shadow-xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05);
|
||||
--shadow-sm:
|
||||
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1);
|
||||
--shadow:
|
||||
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1);
|
||||
--shadow-md:
|
||||
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 2px 4px -1px hsl(0 0% 0% / 0.1);
|
||||
--shadow-lg:
|
||||
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 4px 6px -1px hsl(0 0% 0% / 0.1);
|
||||
--shadow-xl:
|
||||
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 8px 10px -1px hsl(0 0% 0% / 0.1);
|
||||
--shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / 0.25);
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
|
||||
--font-sans: var(--font-sans);
|
||||
--font-mono: var(--font-mono);
|
||||
--font-serif: var(--font-serif);
|
||||
--font-sans: var(--font-sans);
|
||||
--font-mono: var(--font-mono);
|
||||
--font-serif: var(--font-serif);
|
||||
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
|
||||
--shadow-2xs: var(--shadow-2xs);
|
||||
--shadow-xs: var(--shadow-xs);
|
||||
--shadow-sm: var(--shadow-sm);
|
||||
--shadow: var(--shadow);
|
||||
--shadow-md: var(--shadow-md);
|
||||
--shadow-lg: var(--shadow-lg);
|
||||
--shadow-xl: var(--shadow-xl);
|
||||
--shadow-2xl: var(--shadow-2xl);
|
||||
--shadow-2xs: var(--shadow-2xs);
|
||||
--shadow-xs: var(--shadow-xs);
|
||||
--shadow-sm: var(--shadow-sm);
|
||||
--shadow: var(--shadow);
|
||||
--shadow-md: var(--shadow-md);
|
||||
--shadow-lg: var(--shadow-lg);
|
||||
--shadow-xl: var(--shadow-xl);
|
||||
--shadow-2xl: var(--shadow-2xl);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
/* width */
|
||||
::-webkit-scrollbar {
|
||||
@apply w-1
|
||||
}
|
||||
/* width */
|
||||
::-webkit-scrollbar {
|
||||
@apply w-1;
|
||||
}
|
||||
|
||||
/* Handle */
|
||||
::-webkit-scrollbar-thumb {
|
||||
@apply bg-border rounded-full mr-0.5
|
||||
}
|
||||
/* Handle */
|
||||
::-webkit-scrollbar-thumb {
|
||||
@apply bg-border rounded-full mr-0.5;
|
||||
}
|
||||
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
|
||||
button,
|
||||
[role="button"] {
|
||||
cursor: pointer;
|
||||
}
|
||||
button,
|
||||
[role="button"] {
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
/* Hide scrollbar for Chrome, Safari and Opera */
|
||||
.no-scrollbar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Hide scrollbar for Chrome, Safari and Opera */
|
||||
.no-scrollbar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Hide scrollbar for IE, Edge and Firefox */
|
||||
.no-scrollbar {
|
||||
/* IE and Edge */
|
||||
-ms-overflow-style: none;
|
||||
/* Firefox */
|
||||
scrollbar-width: none;
|
||||
}
|
||||
}
|
||||
/* Hide scrollbar for IE, Edge and Firefox */
|
||||
.no-scrollbar {
|
||||
/* IE and Edge */
|
||||
-ms-overflow-style: none;
|
||||
/* Firefox */
|
||||
scrollbar-width: none;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,31 +14,45 @@ interface AppLayoutProps {
|
||||
}
|
||||
|
||||
export default function AppLayout({ children }: AppLayoutProps) {
|
||||
let servers = useServerListStore(useShallow((state) => Object.values(state.servers)))
|
||||
let servers = Object.values(
|
||||
useServerListStore(useShallow((state) => state.servers)),
|
||||
);
|
||||
|
||||
const matches = useMatches();
|
||||
|
||||
let list = React.useMemo(() => {
|
||||
return matches.map(match => (match.handle as {
|
||||
listComponent?: React.ReactNode
|
||||
})?.listComponent).reverse().find(component => !!component)
|
||||
}, [matches])
|
||||
return matches
|
||||
.map(
|
||||
(match) =>
|
||||
(
|
||||
match.handle as {
|
||||
listComponent?: React.ReactNode;
|
||||
}
|
||||
)?.listComponent,
|
||||
)
|
||||
.reverse()
|
||||
.find((component) => !!component);
|
||||
}, [matches]);
|
||||
|
||||
return (
|
||||
<div className="flex h-screen w-screen overflow-hidden">
|
||||
<div className="grid h-full max-h-screen bg-background min-w-80 border-r-2" style={{ gridTemplateColumns: "auto 1fr", gridTemplateRows: "1fr auto" }}>
|
||||
<div
|
||||
className="grid h-full max-h-screen bg-background min-w-80 border-r-2"
|
||||
style={{
|
||||
gridTemplateColumns: "auto 1fr",
|
||||
gridTemplateRows: "1fr auto",
|
||||
}}
|
||||
>
|
||||
<div className="col-start-1 row-start-1 col-span-1 row-span-1 overflow-hidden border-r-2 min-w-fit">
|
||||
<ScrollArea className="h-full px-1" scrollbarSize="none">
|
||||
<aside className="flex flex-col gap-4 p-2 h-full">
|
||||
<HomeButton />
|
||||
<Separator />
|
||||
{
|
||||
servers.map((server, _) =>
|
||||
<React.Fragment key={server.id}>
|
||||
<ServerButton server={server} />
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
{servers.map((server, _) => (
|
||||
<React.Fragment key={server.id}>
|
||||
<ServerButton server={server} />
|
||||
</React.Fragment>
|
||||
))}
|
||||
{servers.length > 0 && <Separator />}
|
||||
<CreateServerButton />
|
||||
</aside>
|
||||
@@ -53,9 +67,7 @@ export default function AppLayout({ children }: AppLayoutProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grow">
|
||||
{children}
|
||||
</div>
|
||||
<div className="grow">{children}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,23 +1,29 @@
|
||||
import { useInfiniteQuery, type QueryFunctionContext } from "@tanstack/react-query"
|
||||
import type { Channel, MessageId } from "~/lib/api/types"
|
||||
import ChatMessage from "./chat-message"
|
||||
import MessageBox from "./message-box"
|
||||
import VisibleTrigger from "./visible-trigger"
|
||||
import {
|
||||
useInfiniteQuery,
|
||||
type QueryFunctionContext,
|
||||
} from "@tanstack/react-query";
|
||||
import type { Channel, Message, MessageId } from "~/lib/api/types";
|
||||
import ChatMessage from "./chat-message";
|
||||
import MessageBox from "./message-box";
|
||||
import { Separator } from "./ui/separator";
|
||||
import VisibleTrigger from "./visible-trigger";
|
||||
|
||||
interface ChannelAreaProps {
|
||||
channel: Channel
|
||||
channel: Channel;
|
||||
}
|
||||
|
||||
export default function ChannelArea(
|
||||
{ channel }: ChannelAreaProps
|
||||
) {
|
||||
const channelId = channel.id
|
||||
export default function ChannelArea({ channel }: ChannelAreaProps) {
|
||||
const channelId = channel.id;
|
||||
|
||||
const fetchMessages = async ({ pageParam }: QueryFunctionContext) => {
|
||||
return await import("~/lib/api/client/channel").then(m => m.default.paginatedMessages(channelId, 50, pageParam as MessageId | undefined))
|
||||
}
|
||||
|
||||
|
||||
return await import("~/lib/api/client/channel").then((m) =>
|
||||
m.default.paginatedMessages(
|
||||
channelId,
|
||||
50,
|
||||
pageParam as MessageId | undefined,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const {
|
||||
data,
|
||||
@@ -32,38 +38,38 @@ export default function ChannelArea(
|
||||
queryKey: ["messages", channelId],
|
||||
initialPageParam: undefined,
|
||||
queryFn: fetchMessages,
|
||||
getNextPageParam: (lastPage) => lastPage.length < 50 ? undefined : lastPage[lastPage.length - 1]?.id,
|
||||
getNextPageParam: (lastPage) =>
|
||||
lastPage.length < 50
|
||||
? undefined
|
||||
: lastPage[lastPage.length - 1]?.id,
|
||||
staleTime: Infinity,
|
||||
})
|
||||
});
|
||||
|
||||
const fetchNextPageVisible = () => {
|
||||
if (!isFetchingNextPage && hasNextPage)
|
||||
fetchNextPage()
|
||||
}
|
||||
if (!isFetchingNextPage && hasNextPage) fetchNextPage();
|
||||
};
|
||||
|
||||
let messageArea = null
|
||||
let messageArea = null;
|
||||
|
||||
if (isPending) {
|
||||
messageArea = <div className="flex items-center justify-center size-full">
|
||||
<span>Loading...</span>
|
||||
</div>
|
||||
} else {
|
||||
messageArea = <>
|
||||
<div className="flex-1" />
|
||||
<div className="flex flex-col-reverse overflow-auto gap-2">
|
||||
{
|
||||
status === "success" && data.pages.map((page, i) => (
|
||||
page.map((message) => (
|
||||
<div key={message.id} className="w-full">
|
||||
<ChatMessage message={message} />
|
||||
</div>
|
||||
))
|
||||
)
|
||||
)
|
||||
}
|
||||
<VisibleTrigger triggerOnce={false} onVisible={fetchNextPageVisible} />
|
||||
messageArea = (
|
||||
<div className="flex items-center justify-center size-full">
|
||||
<span>Loading...</span>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
} else {
|
||||
messageArea = (
|
||||
<>
|
||||
<div className="flex-1" />
|
||||
<div className="flex flex-col-reverse overflow-auto gap-2 pb-2 pr-2">
|
||||
{status === "success" && renderMessages(data.pages)}
|
||||
<VisibleTrigger
|
||||
triggerOnce={false}
|
||||
onVisible={fetchNextPageVisible}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -75,10 +81,79 @@ export default function ChannelArea(
|
||||
<div className="flex-1 overflow-y-auto flex flex-col pl-2 pr-0.5">
|
||||
{messageArea}
|
||||
</div>
|
||||
<div className="w-full max-w-full max-h-1/2">
|
||||
<div className="w-full">
|
||||
<MessageBox channelId={channelId} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function renderMessages(pages: Message[][]) {
|
||||
const messageElements: React.ReactNode[] = [];
|
||||
let lastDate: string | null = null;
|
||||
|
||||
const formatMessageDate = (date: Date) => {
|
||||
const now = new Date();
|
||||
const today = new Date(
|
||||
now.getFullYear(),
|
||||
now.getMonth(),
|
||||
now.getDate(),
|
||||
);
|
||||
const yesterday = new Date(today);
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
|
||||
const messageDate = new Date(
|
||||
date.getFullYear(),
|
||||
date.getMonth(),
|
||||
date.getDate(),
|
||||
);
|
||||
|
||||
const capitalize = (str: string) =>
|
||||
str.charAt(0).toUpperCase() + str.slice(1);
|
||||
|
||||
if (messageDate.getTime() === today.getTime()) {
|
||||
const rtf = new Intl.RelativeTimeFormat(undefined, {
|
||||
numeric: "auto",
|
||||
});
|
||||
return capitalize(rtf.format(0, "day"));
|
||||
} else if (messageDate.getTime() === yesterday.getTime()) {
|
||||
const rtf = new Intl.RelativeTimeFormat(undefined, {
|
||||
numeric: "auto",
|
||||
});
|
||||
return capitalize(rtf.format(-1, "day"));
|
||||
} else {
|
||||
return date.toLocaleDateString(undefined, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
pages.forEach((page) => {
|
||||
page.forEach((message) => {
|
||||
const messageDate = message.createdAt.toDateString();
|
||||
if (messageDate != lastDate) {
|
||||
if (lastDate)
|
||||
messageElements.push(
|
||||
<div className="flex items-center justify-center py-2 w-full">
|
||||
<Separator className="flex-1" />
|
||||
<span className="mx-4 text-sm text-muted-foreground">
|
||||
{formatMessageDate(new Date(lastDate))}
|
||||
</span>
|
||||
<Separator className="flex-1" />
|
||||
</div>,
|
||||
);
|
||||
lastDate = messageDate;
|
||||
}
|
||||
|
||||
messageElements.push(
|
||||
<div key={message.id} className="w-full">
|
||||
<ChatMessage message={message} />
|
||||
</div>,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
return messageElements;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
Download,
|
||||
ExternalLink,
|
||||
Maximize
|
||||
} from "lucide-react";
|
||||
import { Download, ExternalLink, Maximize } from "lucide-react";
|
||||
import { AspectRatio } from "~/components/ui/aspect-ratio"; // Shadcn UI AspectRatio
|
||||
import { Button } from "~/components/ui/button"; // Shadcn UI Button
|
||||
import {
|
||||
@@ -28,7 +24,9 @@ interface ChatMessageAttachmentProps {
|
||||
file: UploadedFile;
|
||||
}
|
||||
|
||||
export default function ChatMessageAttachment({ file }: ChatMessageAttachmentProps) {
|
||||
export default function ChatMessageAttachment({
|
||||
file,
|
||||
}: ChatMessageAttachmentProps) {
|
||||
if (file.contentType.startsWith("image/")) {
|
||||
return <ImageAttachment file={file} />;
|
||||
}
|
||||
@@ -38,9 +36,12 @@ export default function ChatMessageAttachment({ file }: ChatMessageAttachmentPro
|
||||
function GenericFileAttachment({ file }: ChatMessageAttachmentProps) {
|
||||
return (
|
||||
<TooltipProvider delayDuration={100}>
|
||||
<div className="flex items-center gap-3 rounded-lg border bg-card p-3 shadow-sm w-full max-w-xs sm:max-w-sm">
|
||||
<div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-md bg-muted">
|
||||
<FileIcon className="h-8 w-8 text-muted-foreground" contentType={file.contentType} />
|
||||
<div className="flex items-center gap-3 rounded-lg border bg-card p-3 shadow-sm ">
|
||||
<div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-md">
|
||||
<FileIcon
|
||||
className="h-8 w-8 text-muted-foreground"
|
||||
contentType={file.contentType}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<p className="truncate text-sm font-medium text-card-foreground">
|
||||
@@ -54,7 +55,12 @@ function GenericFileAttachment({ file }: ChatMessageAttachmentProps) {
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button variant="ghost" size="icon" asChild>
|
||||
<a href={file.url} target="_blank" rel="noreferrer" download={file.filename}>
|
||||
<a
|
||||
href={file.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
download={file.filename}
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
<span className="sr-only">Download</span>
|
||||
</a>
|
||||
@@ -65,9 +71,15 @@ function GenericFileAttachment({ file }: ChatMessageAttachmentProps) {
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button variant="ghost" size="icon" asChild>
|
||||
<a href={file.url} target="_blank" rel="noreferrer">
|
||||
<a
|
||||
href={file.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
<span className="sr-only">Open in new tab</span>
|
||||
<span className="sr-only">
|
||||
Open in new tab
|
||||
</span>
|
||||
</a>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
@@ -85,7 +97,10 @@ function ImageAttachment({ file }: ChatMessageAttachmentProps) {
|
||||
<TooltipProvider delayDuration={100}>
|
||||
<div className="group relative w-48 cursor-pointer sm:w-64">
|
||||
<DialogTrigger asChild>
|
||||
<AspectRatio ratio={16 / 9} className="overflow-hidden rounded-lg border bg-muted">
|
||||
<AspectRatio
|
||||
ratio={16 / 9}
|
||||
className="overflow-hidden rounded-lg border bg-muted"
|
||||
>
|
||||
<img
|
||||
src={file.url}
|
||||
alt={file.filename}
|
||||
@@ -106,7 +121,9 @@ function ImageAttachment({ file }: ChatMessageAttachmentProps) {
|
||||
|
||||
<DialogContent className="max-w-3xl p-0">
|
||||
<DialogHeader className="p-4 pb-0">
|
||||
<DialogTitle className="truncate">{file.filename}</DialogTitle>
|
||||
<DialogTitle className="truncate">
|
||||
{file.filename}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="p-4 pt-0 max-h-[70vh] overflow-y-auto">
|
||||
<img
|
||||
@@ -118,7 +135,8 @@ function ImageAttachment({ file }: ChatMessageAttachmentProps) {
|
||||
<DialogFooter className="flex-col items-stretch gap-2 border-t p-4 sm:flex-row sm:justify-end sm:space-x-2">
|
||||
<Button variant="outline" asChild>
|
||||
<a href={file.url} target="_blank" rel="noreferrer">
|
||||
<ExternalLink className="mr-2 h-4 w-4" /> Open original
|
||||
<ExternalLink className="mr-2 h-4 w-4" /> Open
|
||||
original
|
||||
</a>
|
||||
</Button>
|
||||
<Button asChild>
|
||||
@@ -133,4 +151,4 @@ function ImageAttachment({ file }: ChatMessageAttachmentProps) {
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,86 +1,112 @@
|
||||
import { Clock } from "lucide-react"
|
||||
import React from "react"
|
||||
import { useShallow } from "zustand/react/shallow"
|
||||
import type { Message } from "~/lib/api/types"
|
||||
import { useUsersStore } from "~/stores/users-store"
|
||||
import ChatMessageAttachment from "./chat-message-attachment"
|
||||
import UserAvatar from "./user-avatar"
|
||||
import { Clock } from "lucide-react";
|
||||
import React from "react";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import type { Message } from "~/lib/api/types";
|
||||
import { useUsersStore } from "~/stores/users-store";
|
||||
import ChatMessageAttachment from "./chat-message-attachment";
|
||||
import UserAvatar from "./user-avatar";
|
||||
import UserContextMenu from "./user-context-menu";
|
||||
|
||||
interface ChatMessageProps {
|
||||
message: Message
|
||||
message: Message;
|
||||
}
|
||||
|
||||
export default function ChatMessage(
|
||||
{ message }: ChatMessageProps
|
||||
) {
|
||||
const { user, fetchUsersIfNotPresent } = useUsersStore(useShallow(state => ({
|
||||
user: state.users[message.authorId],
|
||||
fetchUsersIfNotPresent: state.fetchUsersIfNotPresent
|
||||
})))
|
||||
export default function ChatMessage({ message }: ChatMessageProps) {
|
||||
const { user, fetchUsersIfNotPresent } = useUsersStore(
|
||||
useShallow((state) => ({
|
||||
user: state.users[message.authorId],
|
||||
fetchUsersIfNotPresent: state.fetchUsersIfNotPresent,
|
||||
})),
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
fetchUsersIfNotPresent([message.authorId])
|
||||
}, [])
|
||||
fetchUsersIfNotPresent([message.authorId]);
|
||||
}, []);
|
||||
|
||||
const formatMessageDate = (date: Date) => {
|
||||
const now = new Date()
|
||||
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
|
||||
const yesterday = new Date(today)
|
||||
yesterday.setDate(yesterday.getDate() - 1)
|
||||
const now = new Date();
|
||||
const today = new Date(
|
||||
now.getFullYear(),
|
||||
now.getMonth(),
|
||||
now.getDate(),
|
||||
);
|
||||
const yesterday = new Date(today);
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
|
||||
const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())
|
||||
const messageDate = new Date(
|
||||
date.getFullYear(),
|
||||
date.getMonth(),
|
||||
date.getDate(),
|
||||
);
|
||||
|
||||
// Get localized time string
|
||||
const timeString = date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', hour12: false })
|
||||
const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1)
|
||||
const timeString = date.toLocaleTimeString(undefined, {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
hour12: false,
|
||||
});
|
||||
const capitalize = (str: string) =>
|
||||
str.charAt(0).toUpperCase() + str.slice(1);
|
||||
|
||||
if (messageDate.getTime() === today.getTime()) {
|
||||
// Use Intl.RelativeTimeFormat for localized "Today"
|
||||
const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' })
|
||||
return `${(capitalize(rtf.format(0, 'day')))}, ${timeString}`
|
||||
const rtf = new Intl.RelativeTimeFormat(undefined, {
|
||||
numeric: "auto",
|
||||
});
|
||||
return `${capitalize(rtf.format(0, "day"))}, ${timeString}`;
|
||||
} else if (messageDate.getTime() === yesterday.getTime()) {
|
||||
// Use Intl.RelativeTimeFormat for localized "Yesterday"
|
||||
const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' })
|
||||
return `${capitalize(rtf.format(-1, 'day'))}, ${timeString}`
|
||||
const rtf = new Intl.RelativeTimeFormat(undefined, {
|
||||
numeric: "auto",
|
||||
});
|
||||
return `${capitalize(rtf.format(-1, "day"))}, ${timeString}`;
|
||||
} else {
|
||||
return date.toLocaleDateString(undefined, {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false
|
||||
})
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
hour12: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="grid gap-x-2" style={{ gridTemplateColumns: "auto 1fr", gridTemplateRows: "auto 1fr" }}>
|
||||
<div
|
||||
className="grid gap-x-2"
|
||||
style={{
|
||||
gridTemplateColumns: "auto 1fr",
|
||||
gridTemplateRows: "auto 1fr",
|
||||
}}
|
||||
>
|
||||
<div className="row-start-1 col-start-1 row-span-2 col-span-1">
|
||||
<UserAvatar user={user} />
|
||||
<UserContextMenu userId={message.authorId}>
|
||||
<UserAvatar user={user} />
|
||||
</UserContextMenu>
|
||||
</div>
|
||||
<div className="row-start-1 col-start-2 row-span-1 col-span-1 flex items-center gap-2">
|
||||
<span className="font-medium text-sm">
|
||||
{user?.displayName || user?.username}
|
||||
<UserContextMenu userId={message.authorId}>
|
||||
<div>{user?.displayName || user?.username}</div>
|
||||
</UserContextMenu>
|
||||
</span>
|
||||
<div className="flex items-center gap-0.5 text-xs text-muted-foreground whitespace-nowrap">
|
||||
<Clock className="size-3" />
|
||||
<span>
|
||||
{formatMessageDate(message.createdAt)}
|
||||
</span>
|
||||
<span>{formatMessageDate(message.createdAt)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-start-2 col-start-2 row-span-1 col-span-1">
|
||||
<div className="wrap-break-word contain-inline-size">
|
||||
{message.content}
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
{
|
||||
message.attachments.map((file, i) => (<div key={file.id}>
|
||||
<div className="grid gap-2 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 justify-start">
|
||||
{message.attachments.map((file, i) => (
|
||||
<div key={file.id}>
|
||||
<ChatMessageAttachment file={file} />
|
||||
</div>))
|
||||
}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,19 +1,31 @@
|
||||
import { ChevronDown, Hash, Volume2 } from "lucide-react"
|
||||
import React from "react"
|
||||
import { NavLink } from "react-router"
|
||||
import { useShallow } from "zustand/react/shallow"
|
||||
import { ChannelType, type ServerChannel } from "~/lib/api/types"
|
||||
import { cn } from "~/lib/utils"
|
||||
import { useChannelsVoiceStateStore } from "~/stores/channels-voice-state"
|
||||
import { useGatewayStore } from "~/stores/gateway-store"
|
||||
import { useUsersStore } from "~/stores/users-store"
|
||||
import { Button } from "../ui/button"
|
||||
import UserAvatar from "../user-avatar"
|
||||
import { ChevronDown, Hash, Volume2 } from "lucide-react";
|
||||
import React from "react";
|
||||
import { NavLink } from "react-router";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { deleteChannel } from "~/lib/api/client/server";
|
||||
import { ChannelType, type ServerChannel } from "~/lib/api/types";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { useChannelsVoiceStateStore } from "~/stores/channels-voice-state";
|
||||
import { useGatewayStore } from "~/stores/gateway-store";
|
||||
import { useUsersStore } from "~/stores/users-store";
|
||||
import { useVoiceStateStore } from "~/stores/voice-state-store";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuTrigger,
|
||||
} from "../ui/context-menu";
|
||||
import UserAvatar from "../user-avatar";
|
||||
|
||||
interface ChannelListItemProps {
|
||||
channel: ServerChannel
|
||||
channel: ServerChannel;
|
||||
}
|
||||
|
||||
const onDeleteChannel = async (channel: ServerChannel) => {
|
||||
const response = await deleteChannel(channel.serverId, channel.id);
|
||||
};
|
||||
|
||||
function ServerCategory({ channel }: ChannelListItemProps) {
|
||||
return (
|
||||
<div className="text-xs flex flex-row justify-between mt-4">
|
||||
@@ -24,91 +36,140 @@ function ServerCategory({ channel }: ChannelListItemProps) {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function ServerVoice({ channel }: ChannelListItemProps) {
|
||||
const updateVoiceState = useGatewayStore(state => state.updateVoiceState)
|
||||
const channelVoiceState = useChannelsVoiceStateStore(state => state.channels[channel.id]) || {}
|
||||
const userIds = Object.keys(channelVoiceState.users ?? {})
|
||||
const updateVoiceState = useGatewayStore((state) => state.updateVoiceState);
|
||||
const voiceStateChannel = useVoiceStateStore(
|
||||
(state) => state.activeChannel,
|
||||
);
|
||||
const channelVoiceState =
|
||||
useChannelsVoiceStateStore((state) => state.channels[channel.id]) || {};
|
||||
const userIds = Object.keys(channelVoiceState.users ?? {});
|
||||
|
||||
const { users, fetchUsersIfNotPresent } = useUsersStore(useShallow(state => ({
|
||||
users: state.users,
|
||||
fetchUsersIfNotPresent: state.fetchUsersIfNotPresent
|
||||
})))
|
||||
const { users, fetchUsersIfNotPresent } = useUsersStore(
|
||||
useShallow((state) => ({
|
||||
users: state.users,
|
||||
fetchUsersIfNotPresent: state.fetchUsersIfNotPresent,
|
||||
})),
|
||||
);
|
||||
|
||||
const channelUsers = React.useMemo(() => userIds.map(userId => users[userId]).filter(Boolean), [userIds, users])
|
||||
const channelUsers = React.useMemo(
|
||||
() => userIds.map((userId) => users[userId]).filter(Boolean),
|
||||
[userIds, users],
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
fetchUsersIfNotPresent(userIds)
|
||||
}, [userIds])
|
||||
fetchUsersIfNotPresent(userIds);
|
||||
}, [userIds]);
|
||||
|
||||
const onClick = () => {
|
||||
updateVoiceState(channel.serverId, channel.id)
|
||||
}
|
||||
if (
|
||||
voiceStateChannel?.serverId === channel.serverId &&
|
||||
voiceStateChannel.channelId === channel.id
|
||||
)
|
||||
return;
|
||||
|
||||
updateVoiceState(channel.serverId, channel.id);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button variant="secondary" size="sm" className="justify-start" onClick={onClick}>
|
||||
<div className="flex items-center gap-2 max-w-72">
|
||||
<div>
|
||||
<Volume2 />
|
||||
</div>
|
||||
<div className="truncate">
|
||||
{channel.name}
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
{channelUsers.length > 0 &&
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="justify-start"
|
||||
onClick={onClick}
|
||||
>
|
||||
<div className="flex items-center gap-2 max-w-72">
|
||||
<div>
|
||||
<Volume2 />
|
||||
</div>
|
||||
<div className="truncate">{channel.name}</div>
|
||||
</div>
|
||||
</Button>
|
||||
</ContextMenuTrigger>
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem
|
||||
variant="destructive"
|
||||
onClick={() => onDeleteChannel(channel)}
|
||||
>
|
||||
Delete
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
{channelUsers.length > 0 && (
|
||||
<div className="ml-2 border-l-2 flex flex-col gap-1">
|
||||
{
|
||||
channelUsers
|
||||
.map(user => (
|
||||
<div key={user.id} className="flex items-center gap-2 max-w-72 pl-4">
|
||||
<UserAvatar user={user} className="size-6" />
|
||||
{user.displayName || user.username}
|
||||
</div>
|
||||
))
|
||||
}
|
||||
</div>}
|
||||
{channelUsers.map((user) => (
|
||||
<div
|
||||
key={user.id}
|
||||
className="flex items-center gap-2 max-w-72 pl-4"
|
||||
>
|
||||
<UserAvatar user={user} className="size-6" />
|
||||
{user.displayName || user.username}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function ServerText({ channel }: ChannelListItemProps) {
|
||||
return (
|
||||
<NavLink to={`/app/server/${channel.serverId}/${channel.id}`} discover="none" >
|
||||
<NavLink
|
||||
to={`/app/server/${channel.serverId}/${channel.id}`}
|
||||
discover="none"
|
||||
>
|
||||
{({ isActive }) => (
|
||||
<Button variant="secondary" size="sm" className={
|
||||
cn(
|
||||
"justify-start w-full",
|
||||
isActive ? "bg-accent hover:bg-accent" : "bg-secondary"
|
||||
)
|
||||
}>
|
||||
<div className="flex items-center gap-2 max-w-72">
|
||||
<div>
|
||||
<Hash />
|
||||
</div>
|
||||
<div className="truncate">
|
||||
{channel.name}
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className={cn(
|
||||
"justify-start w-full",
|
||||
isActive
|
||||
? "bg-accent hover:bg-accent"
|
||||
: "bg-secondary",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2 max-w-72">
|
||||
<div>
|
||||
<Hash />
|
||||
</div>
|
||||
<div className="truncate">{channel.name}</div>
|
||||
</div>
|
||||
</Button>
|
||||
</ContextMenuTrigger>
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem
|
||||
variant="destructive"
|
||||
onClick={() => onDeleteChannel(channel)}
|
||||
>
|
||||
Delete
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
)}
|
||||
</NavLink>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export default function ServerChannelListItem({ channel }: ChannelListItemProps) {
|
||||
export default function ServerChannelListItem({
|
||||
channel,
|
||||
}: ChannelListItemProps) {
|
||||
switch (channel.type) {
|
||||
case ChannelType.SERVER_CATEGORY:
|
||||
return <ServerCategory channel={channel} />
|
||||
return <ServerCategory channel={channel} />;
|
||||
case ChannelType.SERVER_VOICE:
|
||||
return <ServerVoice channel={channel} />
|
||||
return <ServerVoice channel={channel} />;
|
||||
case ChannelType.SERVER_TEXT:
|
||||
return <ServerText channel={channel} />
|
||||
return <ServerText channel={channel} />;
|
||||
default:
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import { CirclePlus } from "lucide-react";
|
||||
|
||||
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { ModalType, useModalStore } from "~/stores/modal-store";
|
||||
|
||||
export function CreateServerButton() {
|
||||
const onOpen = useModalStore(state => state.onOpen)
|
||||
const onOpen = useModalStore((state) => state.onOpen);
|
||||
|
||||
return (
|
||||
<Button variant="outline" size="none" onClick={() => onOpen(ModalType.CREATE_SERVER)}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="none"
|
||||
onClick={() => onOpen(ModalType.CREATE_SERVER)}
|
||||
>
|
||||
<CirclePlus className="size-8 m-2" />
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,17 +5,18 @@ import { Button } from "../ui/button";
|
||||
export function HomeButton() {
|
||||
return (
|
||||
<NavLink to={`/app/@me`}>
|
||||
{
|
||||
({ isActive }) => (
|
||||
<Button variant="outline" size="none" asChild className={
|
||||
isActive ? "bg-accent size-12" : "size-12"
|
||||
}>
|
||||
<div>
|
||||
<Discord className="size-full p-2" />
|
||||
</div>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
{({ isActive }) => (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="none"
|
||||
asChild
|
||||
className={isActive ? "bg-accent size-12" : "size-12"}
|
||||
>
|
||||
<div>
|
||||
<Discord className="size-full p-2" />
|
||||
</div>
|
||||
</Button>
|
||||
)}
|
||||
</NavLink>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,11 +10,19 @@ export function OnlineStatus({
|
||||
<div className="relative">
|
||||
<div {...props}></div>
|
||||
<div className="absolute bottom-0 right-0 bg-background rounded-full p-0.5 size-1/2">
|
||||
{status === "online" && <Circle className="size-full stroke-emerald-400 fill-emerald-400" />}
|
||||
{status === "dnd" && <CircleMinus className="size-full stroke-red-400 stroke-3" />}
|
||||
{status === "idle" && <Moon className="size-full stroke-amber-400 fill-amber-400" />}
|
||||
{status === "offline" && <Circle className="size-full stroke-gray-400 stroke-3" />}
|
||||
{status === "online" && (
|
||||
<Circle className="size-full stroke-emerald-400 fill-emerald-400" />
|
||||
)}
|
||||
{status === "dnd" && (
|
||||
<CircleMinus className="size-full stroke-red-400 stroke-3" />
|
||||
)}
|
||||
{status === "idle" && (
|
||||
<Moon className="size-full stroke-amber-400 fill-amber-400" />
|
||||
)}
|
||||
{status === "offline" && (
|
||||
<Circle className="size-full stroke-gray-400 stroke-3" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { EyeIcon, EyeOffIcon } from "lucide-react"
|
||||
import React from "react"
|
||||
import { Button } from "../ui/button"
|
||||
import { Input } from "../ui/input"
|
||||
import { EyeIcon, EyeOffIcon } from "lucide-react";
|
||||
import React from "react";
|
||||
import { Button } from "../ui/button";
|
||||
import { Input } from "../ui/input";
|
||||
|
||||
export function PasswordInput(props: React.ComponentProps<"input">) {
|
||||
const [showPassword, setShowPassword] = React.useState(false)
|
||||
const disabled = props.value === '' || props.value === undefined || props.disabled
|
||||
const [showPassword, setShowPassword] = React.useState(false);
|
||||
const disabled =
|
||||
props.value === "" || props.value === undefined || props.disabled;
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
@@ -23,7 +24,9 @@ export function PasswordInput(props: React.ComponentProps<"input">) {
|
||||
) : (
|
||||
<EyeOffIcon className="h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
<span className="sr-only">{showPassword ? 'Hide password' : 'Show password'}</span>
|
||||
<span className="sr-only">
|
||||
{showPassword ? "Hide password" : "Show password"}
|
||||
</span>
|
||||
</Button>
|
||||
<style>
|
||||
{`
|
||||
@@ -36,5 +39,5 @@ export function PasswordInput(props: React.ComponentProps<"input">) {
|
||||
`}
|
||||
</style>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,48 +1,71 @@
|
||||
import { Check } from "lucide-react"
|
||||
import { NavLink } from "react-router"
|
||||
import type { RecipientChannel } from "~/lib/api/types"
|
||||
import { cn } from "~/lib/utils"
|
||||
import { useUsersStore } from "~/stores/users-store"
|
||||
import { Badge } from "../ui/badge"
|
||||
import { Button } from "../ui/button"
|
||||
import UserAvatar from "../user-avatar"
|
||||
import { OnlineStatus } from "./online-status"
|
||||
import { Check } from "lucide-react";
|
||||
import { NavLink } from "react-router";
|
||||
import type { RecipientChannel } from "~/lib/api/types";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { useUsersStore } from "~/stores/users-store";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Button } from "../ui/button";
|
||||
import UserAvatar from "../user-avatar";
|
||||
import { OnlineStatus } from "./online-status";
|
||||
|
||||
interface PrivateChannelListItemProps {
|
||||
channel: RecipientChannel
|
||||
channel: RecipientChannel;
|
||||
}
|
||||
|
||||
export default function PrivateChannelListItem({ channel }: PrivateChannelListItemProps) {
|
||||
const currentUserId = useUsersStore(state => state.currentUserId)
|
||||
const recipients = channel.recipients.filter(recipient => recipient.id !== currentUserId);
|
||||
const renderSystemBadge = recipients.some(recipient => recipient.system) && recipients.length === 1
|
||||
export default function PrivateChannelListItem({
|
||||
channel,
|
||||
}: PrivateChannelListItemProps) {
|
||||
const currentUserId = useUsersStore((state) => state.currentUserId);
|
||||
const recipients = channel.recipients.filter(
|
||||
(recipient) => recipient.id !== currentUserId,
|
||||
);
|
||||
const renderSystemBadge =
|
||||
recipients.some((recipient) => recipient.system) &&
|
||||
recipients.length === 1;
|
||||
|
||||
return (
|
||||
<>
|
||||
<NavLink to={`/app/@me/channels/${channel.id}`}>
|
||||
{
|
||||
({ isActive }) => (
|
||||
<Button variant="secondary" size="none" asChild className={
|
||||
cn(
|
||||
isActive ? "bg-accent hover:bg-accent" : "",
|
||||
"w-full flex flex-row justify-start"
|
||||
)
|
||||
}>
|
||||
<div className="flex items-center gap-2 max-w-72 p-2">
|
||||
<div>
|
||||
<OnlineStatus status="online">
|
||||
<UserAvatar user={channel.recipients.find(recipient => recipient.id !== currentUserId)} />
|
||||
</OnlineStatus>
|
||||
</div>
|
||||
<div className="truncate">
|
||||
{recipients.map(recipient => recipient.displayName || recipient.username).join(", ")}
|
||||
</div>
|
||||
{renderSystemBadge && <Badge variant="default"> <Check /> System</Badge>}
|
||||
{({ isActive }) => (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="none"
|
||||
asChild
|
||||
className={cn(
|
||||
isActive ? "bg-accent hover:bg-accent" : "",
|
||||
"w-full flex flex-row justify-start",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2 max-w-72 p-2">
|
||||
<div>
|
||||
<OnlineStatus status="online">
|
||||
<UserAvatar
|
||||
user={channel.recipients.find(
|
||||
(recipient) =>
|
||||
recipient.id !== currentUserId,
|
||||
)}
|
||||
/>
|
||||
</OnlineStatus>
|
||||
</div>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
<div className="truncate">
|
||||
{recipients
|
||||
.map(
|
||||
(recipient) =>
|
||||
recipient.displayName ||
|
||||
recipient.username,
|
||||
)
|
||||
.join(", ")}
|
||||
</div>
|
||||
{renderSystemBadge && (
|
||||
<Badge variant="default">
|
||||
{" "}
|
||||
<Check /> System
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</Button>
|
||||
)}
|
||||
</NavLink>
|
||||
</>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,36 +1,36 @@
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@radix-ui/react-avatar"
|
||||
import { NavLink } from "react-router"
|
||||
import type { Server } from "~/lib/api/types"
|
||||
import { getFirstLetters } from "~/lib/utils"
|
||||
import { Button } from "../ui/button"
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@radix-ui/react-avatar";
|
||||
import { NavLink } from "react-router";
|
||||
import type { Server } from "~/lib/api/types";
|
||||
import { getFirstLetters } from "~/lib/utils";
|
||||
import { Button } from "../ui/button";
|
||||
|
||||
export interface ServerButtonProps {
|
||||
server: Server
|
||||
server: Server;
|
||||
}
|
||||
|
||||
export function ServerButton(
|
||||
{ server }: ServerButtonProps
|
||||
) {
|
||||
export function ServerButton({ server }: ServerButtonProps) {
|
||||
return (
|
||||
<NavLink to={`/app/server/${server.id}`}>
|
||||
{
|
||||
({ isActive }) => (
|
||||
<Button variant="outline" size="none" asChild className={
|
||||
isActive ? "bg-accent" : ""
|
||||
}>
|
||||
<div>
|
||||
<Avatar className="size-12 rounded-none flex items-center justify-center">
|
||||
<AvatarImage src={server.iconUrl} className="rounded-none" />
|
||||
<AvatarFallback>
|
||||
<div>
|
||||
{getFirstLetters(server.name, 4)}
|
||||
</div>
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</div>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
{({ isActive }) => (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="none"
|
||||
asChild
|
||||
className={isActive ? "bg-accent" : ""}
|
||||
>
|
||||
<div>
|
||||
<Avatar className="size-12 rounded-none flex items-center justify-center">
|
||||
<AvatarImage
|
||||
src={server.iconUrl}
|
||||
className="rounded-none"
|
||||
/>
|
||||
<AvatarFallback>
|
||||
<div>{getFirstLetters(server.name, 4)}</div>
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</div>
|
||||
</Button>
|
||||
)}
|
||||
</NavLink>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,21 +1,33 @@
|
||||
import { Settings } from "lucide-react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { ModalType, useModalStore } from "~/stores/modal-store";
|
||||
import { useTokenStore } from "~/stores/token-store";
|
||||
import { Button } from "../ui/button";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "../ui/dropdown-menu";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "../ui/dropdown-menu";
|
||||
|
||||
export function SettingsButton() {
|
||||
const setToken = useTokenStore(state => state.setToken)
|
||||
const onOpen = useModalStore(state => state.onOpen)
|
||||
const setToken = useTokenStore((state) => state.setToken);
|
||||
const onOpen = useModalStore((state) => state.onOpen);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const onUpdateProfile = () => {
|
||||
onOpen(ModalType.UPDATE_PROFILE)
|
||||
}
|
||||
onOpen(ModalType.UPDATE_PROFILE);
|
||||
};
|
||||
|
||||
const onOpenSettings = () => {
|
||||
navigate("/app/settings");
|
||||
};
|
||||
|
||||
const onLogout = () => {
|
||||
setToken(undefined)
|
||||
window.location.reload()
|
||||
}
|
||||
setToken(undefined);
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
@@ -25,8 +37,8 @@ export function SettingsButton() {
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem onClick={onUpdateProfile}>
|
||||
Update profile
|
||||
<DropdownMenuItem onClick={onOpenSettings}>
|
||||
Settings
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem variant="destructive" onClick={onLogout}>
|
||||
@@ -34,5 +46,5 @@ export function SettingsButton() {
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import React, { forwardRef, useEffect, useImperativeHandle, useRef } from 'react';
|
||||
import { cn } from '~/lib/utils';
|
||||
import React, {
|
||||
forwardRef,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useRef,
|
||||
} from "react";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
export interface TextBoxProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange' | 'value'> {
|
||||
export interface TextBoxProps
|
||||
extends Omit<React.HTMLAttributes<HTMLDivElement>, "onChange" | "value"> {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
placeholder?: string;
|
||||
@@ -28,7 +34,7 @@ export const TextBox = forwardRef<HTMLDivElement, TextBoxProps>(
|
||||
onFocus,
|
||||
...rest
|
||||
},
|
||||
ref
|
||||
ref,
|
||||
) => {
|
||||
const localRef = useRef<HTMLDivElement>(null);
|
||||
useImperativeHandle(ref, () => localRef.current as HTMLDivElement);
|
||||
@@ -39,10 +45,13 @@ export const TextBox = forwardRef<HTMLDivElement, TextBoxProps>(
|
||||
// Only update if different to avoid selection issues
|
||||
if (localRef.current.textContent !== newValue) {
|
||||
localRef.current.textContent = newValue;
|
||||
|
||||
|
||||
// Clear any <br> elements if the content is empty
|
||||
if (!newValue && localRef.current.innerHTML.includes('<br>')) {
|
||||
localRef.current.innerHTML = '';
|
||||
if (
|
||||
!newValue &&
|
||||
localRef.current.innerHTML.includes("<br>")
|
||||
) {
|
||||
localRef.current.innerHTML = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,34 +69,34 @@ export const TextBox = forwardRef<HTMLDivElement, TextBoxProps>(
|
||||
}, [autoFocus]);
|
||||
|
||||
const handleInput = (event: React.FormEvent<HTMLDivElement>) => {
|
||||
const newValue = event.currentTarget.textContent || '';
|
||||
|
||||
const newValue = event.currentTarget.textContent || "";
|
||||
|
||||
// Handle the case where the content is empty but contains a <br>
|
||||
if (!newValue && event.currentTarget.innerHTML.includes('<br>')) {
|
||||
event.currentTarget.innerHTML = '';
|
||||
if (!newValue && event.currentTarget.innerHTML.includes("<br>")) {
|
||||
event.currentTarget.innerHTML = "";
|
||||
}
|
||||
|
||||
|
||||
onChange(newValue);
|
||||
onInput?.(event);
|
||||
};
|
||||
|
||||
const handlePaste = (event: React.ClipboardEvent<HTMLDivElement>) => {
|
||||
event.preventDefault();
|
||||
const text = event.clipboardData.getData('text/plain');
|
||||
|
||||
const text = event.clipboardData.getData("text/plain");
|
||||
|
||||
// Use document.execCommand to maintain undo stack
|
||||
document.execCommand('insertText', false, text);
|
||||
|
||||
document.execCommand("insertText", false, text);
|
||||
|
||||
// Manually trigger input event
|
||||
const inputEvent = new Event('input', { bubbles: true });
|
||||
const inputEvent = new Event("input", { bubbles: true });
|
||||
event.currentTarget.dispatchEvent(inputEvent);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"max-h-96 w-full overflow-y-auto min-h-6",
|
||||
wrapperClassName
|
||||
"overflow-y-auto overflow-x-hidden w-full min-h-6",
|
||||
wrapperClassName,
|
||||
)}
|
||||
onClick={() => localRef.current?.focus()}
|
||||
>
|
||||
@@ -99,10 +108,10 @@ export const TextBox = forwardRef<HTMLDivElement, TextBoxProps>(
|
||||
onBlur={onBlur}
|
||||
onFocus={onFocus}
|
||||
className={cn(
|
||||
"break-words whitespace-pre-wrap outline-none w-full",
|
||||
"outline-none break-all",
|
||||
"empty:before:content-[attr(data-placeholder)] empty:before:text-muted-foreground empty:before:cursor-text",
|
||||
disabled && "cursor-not-allowed opacity-50",
|
||||
inputClassName
|
||||
inputClassName,
|
||||
)}
|
||||
data-placeholder={placeholder}
|
||||
role="textbox"
|
||||
@@ -116,9 +125,9 @@ export const TextBox = forwardRef<HTMLDivElement, TextBoxProps>(
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
TextBox.displayName = 'TextBox';
|
||||
TextBox.displayName = "TextBox";
|
||||
|
||||
export default TextBox;
|
||||
export default TextBox;
|
||||
|
||||
@@ -11,16 +11,22 @@ import { OnlineStatus } from "./online-status";
|
||||
import { SettingsButton } from "./settings-button";
|
||||
|
||||
function VoiceStatus({
|
||||
voiceState
|
||||
}: { voiceState: { serverId: string; channelId: string } }) {
|
||||
voiceState,
|
||||
}: {
|
||||
voiceState: { serverId: string; channelId: string };
|
||||
}) {
|
||||
// const webrtcState = useWebRTCStore(state => state.status)
|
||||
|
||||
const leaveVoiceChannel = () => {
|
||||
useVoiceStateStore.getState().leaveVoiceChannel()
|
||||
}
|
||||
useVoiceStateStore.getState().leaveVoiceChannel();
|
||||
};
|
||||
|
||||
const channel = useServerChannelsStore(state => state.channels[voiceState.serverId]?.[voiceState.channelId])
|
||||
const server = useServerListStore(state => state.servers[voiceState.serverId])
|
||||
const channel = useServerChannelsStore(
|
||||
(state) => state.channels[voiceState.serverId]?.[voiceState.channelId],
|
||||
);
|
||||
const server = useServerListStore(
|
||||
(state) => state.servers[voiceState.serverId],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="gap-1 flex justify-between items-center ">
|
||||
@@ -35,20 +41,21 @@ function VoiceStatus({
|
||||
<PhoneMissed className="size-5 m-1.5" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export default function UserStatus() {
|
||||
const user = useUsersStore(state => state.getCurrentUser()!)
|
||||
const voiceState = useVoiceStateStore(state => state.activeChannel)
|
||||
const user = useUsersStore((state) => state.getCurrentUser()!);
|
||||
const voiceState = useVoiceStateStore((state) => state.activeChannel);
|
||||
|
||||
return (
|
||||
<div className="outline-1 outline-none border border-input p-2 h-full rounded-xl flex flex-col gap-2">
|
||||
{voiceState && <>
|
||||
<VoiceStatus voiceState={voiceState} />
|
||||
<Separator />
|
||||
</>
|
||||
}
|
||||
<div className="outline-1 outline-none border border-input p-2 h-full rounded-xl flex flex-col gap-2 shadow-sm">
|
||||
{voiceState && (
|
||||
<>
|
||||
<VoiceStatus voiceState={voiceState} />
|
||||
<Separator />
|
||||
</>
|
||||
)}
|
||||
<div className="flex justify-between items-center gap-2">
|
||||
<div className="grow flex flex-row gap-2">
|
||||
<OnlineStatus status="online">
|
||||
@@ -57,9 +64,13 @@ export default function UserStatus() {
|
||||
|
||||
<div className="flex flex-col text-sm justify-center">
|
||||
<div className="truncate max-w-30">
|
||||
{user?.displayName || user?.username || "Unknown user"}
|
||||
{user?.displayName ||
|
||||
user?.username ||
|
||||
"Unknown user"}
|
||||
</div>
|
||||
<span className="text-muted-foreground text-xs">@{user?.username}</span>
|
||||
<span className="text-muted-foreground text-xs">
|
||||
@{user?.username}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
@@ -76,5 +87,5 @@ export default function UserStatus() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import {
|
||||
FileArchive,
|
||||
FileAudio,
|
||||
FileImage,
|
||||
FileQuestion,
|
||||
FileSpreadsheet,
|
||||
FileText,
|
||||
FileVideo,
|
||||
ImageIcon,
|
||||
type LucideProps,
|
||||
} from "lucide-react";
|
||||
|
||||
@@ -17,7 +18,7 @@ export function FileIcon({ contentType, className, ...props }: FileIconProps) {
|
||||
const commonProps = { className: className ?? "h-5 w-5", ...props };
|
||||
|
||||
if (contentType.startsWith("image/")) {
|
||||
return <ImageIcon {...commonProps} />;
|
||||
return <FileImage {...commonProps} />;
|
||||
}
|
||||
if (contentType.startsWith("audio/")) {
|
||||
return <FileAudio {...commonProps} />;
|
||||
@@ -30,19 +31,25 @@ export function FileIcon({ contentType, className, ...props }: FileIconProps) {
|
||||
}
|
||||
if (
|
||||
contentType.startsWith("application/vnd.ms-excel") ||
|
||||
contentType.startsWith("application/vnd.openxmlformats-officedocument.spreadsheetml")
|
||||
contentType.startsWith(
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml",
|
||||
)
|
||||
) {
|
||||
return <FileText {...commonProps} />; // Could use a specific Excel icon if available/desired
|
||||
return <FileSpreadsheet {...commonProps} />; // Could use a specific Excel icon if available/desired
|
||||
}
|
||||
if (
|
||||
contentType.startsWith("application/msword") ||
|
||||
contentType.startsWith("application/vnd.openxmlformats-officedocument.wordprocessingml")
|
||||
contentType.startsWith(
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml",
|
||||
)
|
||||
) {
|
||||
return <FileText {...commonProps} />;
|
||||
}
|
||||
if (
|
||||
contentType.startsWith("application/vnd.ms-powerpoint") ||
|
||||
contentType.startsWith("application/vnd.openxmlformats-officedocument.presentationml")
|
||||
contentType.startsWith(
|
||||
"application/vnd.openxmlformats-officedocument.presentationml",
|
||||
)
|
||||
) {
|
||||
return <FileText {...commonProps} />;
|
||||
}
|
||||
@@ -59,4 +66,4 @@ export function FileIcon({ contentType, className, ...props }: FileIconProps) {
|
||||
return <FileText {...commonProps} />;
|
||||
}
|
||||
return <FileQuestion {...commonProps} />; // Default for unknown types
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,19 @@
|
||||
import type { SVGProps } from "react";
|
||||
|
||||
const Discord = (props: SVGProps<SVGSVGElement>) => <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" preserveAspectRatio="xMidYMid" viewBox="0 0 256 226" {...props}><path fill="#1185FE" d="M55.491 15.172c29.35 22.035 60.917 66.712 72.509 90.686 11.592-23.974 43.159-68.651 72.509-90.686C221.686-.727 256-13.028 256 26.116c0 7.818-4.482 65.674-7.111 75.068-9.138 32.654-42.436 40.983-72.057 35.942 51.775 8.812 64.946 38 36.501 67.187-54.021 55.433-77.644-13.908-83.696-31.676-1.11-3.257-1.63-4.78-1.637-3.485-.008-1.296-.527.228-1.637 3.485-6.052 17.768-29.675 87.11-83.696 31.676-28.445-29.187-15.274-58.375 36.5-67.187-29.62 5.041-62.918-3.288-72.056-35.942C4.482 91.79 0 33.934 0 26.116 0-13.028 34.314-.727 55.491 15.172Z" /></svg>;
|
||||
const Discord = (props: SVGProps<SVGSVGElement>) => (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="1em"
|
||||
height="1em"
|
||||
preserveAspectRatio="xMidYMid"
|
||||
viewBox="0 0 256 226"
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
fill="#1185FE"
|
||||
d="M55.491 15.172c29.35 22.035 60.917 66.712 72.509 90.686 11.592-23.974 43.159-68.651 72.509-90.686C221.686-.727 256-13.028 256 26.116c0 7.818-4.482 65.674-7.111 75.068-9.138 32.654-42.436 40.983-72.057 35.942 51.775 8.812 64.946 38 36.501 67.187-54.021 55.433-77.644-13.908-83.696-31.676-1.11-3.257-1.63-4.78-1.637-3.485-.008-1.296-.527.228-1.637 3.485-6.052 17.768-29.675 87.11-83.696 31.676-28.445-29.187-15.274-58.375 36.5-67.187-29.62 5.041-62.918-3.288-72.056-35.942C4.482 91.79 0 33.934 0 26.116 0-13.028 34.314-.727 55.491 15.172Z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export default Discord;
|
||||
|
||||
@@ -1,20 +1,18 @@
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useEffect } from 'react';
|
||||
import { ConnectionState } from '~/lib/websocket/gateway/types';
|
||||
import { useGatewayStore } from '~/stores/gateway-store';
|
||||
import { useTokenStore } from '~/stores/token-store';
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect } from "react";
|
||||
import { ConnectionState } from "~/lib/websocket/gateway/types";
|
||||
import { useGatewayStore } from "~/stores/gateway-store";
|
||||
import { useTokenStore } from "~/stores/token-store";
|
||||
|
||||
export function GatewayWebSocketConnectionManager() {
|
||||
const token = useTokenStore((state) =>
|
||||
state.token,
|
||||
);
|
||||
const token = useTokenStore((state) => state.token);
|
||||
|
||||
const { setQueryClient } = useGatewayStore();
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
useEffect(() => {
|
||||
setQueryClient(queryClient);
|
||||
}, [queryClient])
|
||||
}, [queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
const { status, connect, disconnect } = useGatewayStore.getState();
|
||||
@@ -34,9 +32,5 @@ export function GatewayWebSocketConnectionManager() {
|
||||
};
|
||||
}, [token]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
return <>{null}</>;
|
||||
}
|
||||
|
||||
@@ -9,11 +9,11 @@ export function WebRTCConnectionManager() {
|
||||
const voiceState = useVoiceStateStore();
|
||||
const webrtc = useWebRTCStore();
|
||||
|
||||
const remoteStream = useWebRTCStore(state => state.remoteStream);
|
||||
const audioRef = useRef<HTMLAudioElement>(null)
|
||||
const remoteStream = useWebRTCStore((state) => state.remoteStream);
|
||||
const audioRef = useRef<HTMLAudioElement>(null);
|
||||
|
||||
if (audioRef.current) {
|
||||
audioRef.current.srcObject = remoteStream
|
||||
audioRef.current.srcObject = remoteStream;
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -25,7 +25,7 @@ export function WebRTCConnectionManager() {
|
||||
audio: {
|
||||
noiseSuppression: false,
|
||||
},
|
||||
video: false
|
||||
video: false,
|
||||
});
|
||||
|
||||
webrtc.createOffer(stream);
|
||||
@@ -41,7 +41,6 @@ export function WebRTCConnectionManager() {
|
||||
if (webrtc.status === ConnectionState.DISCONNECTED) {
|
||||
voiceState.leaveVoiceChannel();
|
||||
}
|
||||
|
||||
}, [webrtc.status]);
|
||||
|
||||
return (
|
||||
@@ -49,4 +48,4 @@ export function WebRTCConnectionManager() {
|
||||
<audio autoPlay ref={audioRef} className="hidden" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,103 +1,220 @@
|
||||
import { Plus, Send, Trash } from "lucide-react"
|
||||
import React from "react"
|
||||
import { sendMessage } from "~/lib/api/client/channel"
|
||||
import { uploadFiles } from "~/lib/api/client/file"
|
||||
import TextBox from "./custom-ui/text-box"
|
||||
import { Button } from "./ui/button"
|
||||
import { Loader2, Paperclip, Send, X } from "lucide-react";
|
||||
import React from "react";
|
||||
import { FileIcon } from "~/components/file-icon"; // Adjust path
|
||||
import { sendMessage } from "~/lib/api/client/channel"; // Adjust path
|
||||
import { uploadFiles } from "~/lib/api/client/file"; // Adjust path
|
||||
import type { Uuid } from "~/lib/api/types"; // Adjust path
|
||||
import { cn, formatFileSize } from "~/lib/utils"; // Adjust path
|
||||
import TextBox from "./custom-ui/text-box"; // Adjust path, assuming TextBox is in ./custom-ui/
|
||||
import { Button } from "./ui/button"; // Adjust path
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "./ui/tooltip"; // Adjust path
|
||||
|
||||
export interface MessageBoxProps {
|
||||
channelId: string
|
||||
channelId: string;
|
||||
}
|
||||
|
||||
export default function MessageBox(
|
||||
{ channelId }: MessageBoxProps
|
||||
) {
|
||||
const [text, setText] = React.useState("")
|
||||
const [attachments, setAttachments] = React.useState<File[]>([])
|
||||
export default function MessageBox({ channelId }: MessageBoxProps) {
|
||||
const [text, setText] = React.useState("");
|
||||
const [attachments, setAttachments] = React.useState<File[]>([]);
|
||||
const [isLoading, setIsLoading] = React.useState(false);
|
||||
|
||||
const fileInputRef = React.useRef<HTMLInputElement>(null)
|
||||
const fileInputRef = React.useRef<HTMLInputElement>(null);
|
||||
const textBoxRef = React.useRef<HTMLDivElement>(null);
|
||||
|
||||
const onSendMessage = async () => {
|
||||
const content = text.trim()
|
||||
if (!content && !attachments.length)
|
||||
return
|
||||
const handleSendMessage = async () => {
|
||||
const content = text.trim();
|
||||
if ((!content && attachments.length === 0) || isLoading) return;
|
||||
|
||||
const uploadedAttachments = await uploadFiles(attachments)
|
||||
setIsLoading(true);
|
||||
try {
|
||||
let uploadedAttachments: Uuid[] = [];
|
||||
if (attachments.length > 0) {
|
||||
uploadedAttachments = await uploadFiles(attachments);
|
||||
}
|
||||
await sendMessage(channelId, text, uploadedAttachments);
|
||||
setText("");
|
||||
setAttachments([]);
|
||||
|
||||
await sendMessage(channelId, text, uploadedAttachments)
|
||||
setText("")
|
||||
setAttachments([])
|
||||
}
|
||||
setTimeout(() => textBoxRef.current?.focus(), 0);
|
||||
} catch (error) {
|
||||
console.error("Failed to send message:", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const addAttachment = async () => {
|
||||
if (!fileInputRef.current)
|
||||
return
|
||||
|
||||
fileInputRef.current.click()
|
||||
}
|
||||
const addAttachment = () => {
|
||||
if (attachments.length >= 10 || isLoading) return;
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = Array.from(e.target.files || [])
|
||||
const newAttachments = [...attachments, ...files]
|
||||
setAttachments(newAttachments.slice(0, 10))
|
||||
const files = Array.from(e.target.files || []);
|
||||
if (files.length === 0) return;
|
||||
|
||||
if (!fileInputRef.current)
|
||||
return
|
||||
setAttachments((prev) => {
|
||||
const newAttachments = [...prev, ...files];
|
||||
return newAttachments.slice(0, 10);
|
||||
});
|
||||
|
||||
fileInputRef.current.value = ""
|
||||
}
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = "";
|
||||
}
|
||||
setTimeout(() => textBoxRef.current?.focus(), 0);
|
||||
};
|
||||
|
||||
const removeAttachment = (indexToRemove: number) => {
|
||||
setAttachments((prev) => prev.filter((_, i) => i !== indexToRemove));
|
||||
setTimeout(() => textBoxRef.current?.focus(), 0);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSendMessage();
|
||||
}
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
setText("")
|
||||
setAttachments([])
|
||||
}, [channelId])
|
||||
setText("");
|
||||
setAttachments([]);
|
||||
setIsLoading(false);
|
||||
setTimeout(() => textBoxRef.current?.focus(), 0);
|
||||
}, [channelId]);
|
||||
|
||||
const canSend =
|
||||
(text.trim().length > 0 || attachments.length > 0) && !isLoading;
|
||||
const attachmentsRemaining = 10 - attachments.length;
|
||||
|
||||
return (
|
||||
<div className="p-2">
|
||||
<div className="max-h-1/2 w-full max-w-full grid items-center gap-x-2 outline-none py-4 px-2 rounded-xl no-scrollbar bg-background border border-input focus-within:ring-2 focus-within:ring-ring focus-within:border-ring"
|
||||
style={{ gridTemplateColumns: "auto 1fr auto", gridTemplateRows: "1fr auto" }}>
|
||||
<div className="row-start-1 col-start-1 row-span-2 col-span-1 h-full">
|
||||
<Button size="icon" variant="ghost" onClick={addAttachment} disabled={attachments.length >= 10}>
|
||||
<Plus />
|
||||
</Button>
|
||||
<input type="file" multiple className="hidden" ref={fileInputRef} onChange={onFileChange} />
|
||||
</div>
|
||||
|
||||
<div className="flex-1 row-start-1 col-start-2 row-span-1 col-span-1">
|
||||
<TextBox value={text}
|
||||
wrapperClassName="contain-inline-size"
|
||||
onChange={setText}
|
||||
placeholder="Type your message here..."
|
||||
aria-label="Message input">
|
||||
|
||||
</TextBox>
|
||||
</div>
|
||||
<div className="flex-1 row-start-2 col-start-2 row-span-1 col-span-1 overflow-y-auto max-h-40">
|
||||
<div className={`${attachments.length > 0 ? "pt-2" : "hidden"}`}>
|
||||
<div className="flex flex-col gap-2">
|
||||
{
|
||||
attachments.map((file, i) => (
|
||||
<div key={i} className="flex items-center gap-2 wrap-anywhere rounded-xl border border-input bg-background p-2">
|
||||
<div className="flex-1">
|
||||
{file.name}
|
||||
</div>
|
||||
<div>
|
||||
<Button size="icon" variant="destructive" onClick={() => setAttachments(attachments.filter((_, j) => i !== j))}>
|
||||
<Trash />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
}
|
||||
<div className="border-t bg-background p-2">
|
||||
{attachments.length > 0 && (
|
||||
<div className="mb-2 max-h-44 space-y-2 overflow-y-auto rounded-md border bg-muted/20 p-2 scrollbar-thin scrollbar-thumb-muted-foreground/30 scrollbar-track-transparent">
|
||||
{attachments.map((file, i) => (
|
||||
<div
|
||||
key={`${file.name}-${file.lastModified}-${i}`}
|
||||
className="flex items-center gap-2.5 rounded-md border bg-card p-2 text-sm shadow-sm"
|
||||
>
|
||||
<FileIcon
|
||||
contentType={file.type}
|
||||
className="h-7 w-7 flex-shrink-0 text-muted-foreground"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate font-medium text-card-foreground">
|
||||
{file.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{formatFileSize(file.size)}
|
||||
</p>
|
||||
</div>
|
||||
<TooltipProvider delayDuration={100}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7 flex-shrink-0 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => removeAttachment(i)}
|
||||
disabled={isLoading}
|
||||
aria-label={`Remove ${file.name}`}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">
|
||||
<p>Remove attachment</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="row-start-1 col-start-3 row-span-2 col-span-1 h-full">
|
||||
<Button size="icon" onClick={onSendMessage}>
|
||||
<Send />
|
||||
)}
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
"grid gap-x-2 rounded-xl border bg-card p-2.5 shadow-sm transition-all",
|
||||
"focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/30",
|
||||
)}
|
||||
style={{
|
||||
gridTemplateColumns: "auto 1fr auto",
|
||||
gridTemplateRows: "auto 1fr",
|
||||
}}
|
||||
>
|
||||
<TooltipProvider delayDuration={100}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="self-start row-start-1 col-start-1 row-span-2 col-span-1">
|
||||
<input
|
||||
type="file"
|
||||
multiple
|
||||
className="hidden"
|
||||
ref={fileInputRef}
|
||||
onChange={onFileChange}
|
||||
accept="image/*,application/pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.rar,audio/*,video/*"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
onClick={addAttachment}
|
||||
disabled={
|
||||
attachments.length >= 10 || isLoading
|
||||
}
|
||||
aria-label="Add attachment"
|
||||
>
|
||||
<Paperclip className="h-5 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">
|
||||
{attachments.length >= 10 ? (
|
||||
<p>Maximum 10 attachments</p>
|
||||
) : (
|
||||
<p>
|
||||
Add attachment ({attachmentsRemaining}{" "}
|
||||
remaining)
|
||||
</p>
|
||||
)}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
|
||||
<div className="self-center row-start-1 col-start-2 row-span-2 col-span-1">
|
||||
<TextBox
|
||||
ref={textBoxRef}
|
||||
value={text}
|
||||
onChange={setText}
|
||||
placeholder="Message..."
|
||||
aria-label="Message input"
|
||||
onKeyDown={handleKeyDown}
|
||||
wrapperClassName="max-h-40"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="self-start row-start-1 col-start-3 row-span-2 col-span-1">
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
onClick={handleSendMessage}
|
||||
disabled={!canSend}
|
||||
aria-label="Send message"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
) : (
|
||||
<Send className="h-5 w-5" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,42 +2,71 @@ import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { ChannelType } from "~/lib/api/types";
|
||||
import { ModalType, useModalStore, type CreateServerChannelModalData } from "~/stores/modal-store";
|
||||
import {
|
||||
ModalType,
|
||||
useModalStore,
|
||||
type CreateServerChannelModalData,
|
||||
} from "~/stores/modal-store";
|
||||
import { Button } from "../ui/button";
|
||||
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "../ui/form";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../ui/dialog";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "../ui/form";
|
||||
import { Input } from "../ui/input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "../ui/select";
|
||||
|
||||
const schema = z.object({
|
||||
name: z.string().min(1).max(32),
|
||||
type: z.nativeEnum(ChannelType),
|
||||
});
|
||||
|
||||
|
||||
export default function CreateServerChannelModal() {
|
||||
const { type, data, isOpen, onClose } = useModalStore();
|
||||
|
||||
const isModalOpen = type === ModalType.CREATE_SERVER_CHANNEL && isOpen
|
||||
const isModalOpen = type === ModalType.CREATE_SERVER_CHANNEL && isOpen;
|
||||
|
||||
let form = useForm<z.infer<typeof schema>>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
type: ChannelType.SERVER_TEXT
|
||||
}
|
||||
type: ChannelType.SERVER_TEXT,
|
||||
},
|
||||
});
|
||||
|
||||
const onOpenChange = () => {
|
||||
form.reset()
|
||||
onClose()
|
||||
}
|
||||
form.reset();
|
||||
onClose();
|
||||
};
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof schema>) => {
|
||||
const response = await import("~/lib/api/client/server").then(m => m.default.createChannel((data as CreateServerChannelModalData['data']).serverId, values))
|
||||
const response = await import("~/lib/api/client/server").then((m) =>
|
||||
m.default.createChannel(
|
||||
(data as CreateServerChannelModalData["data"]).serverId,
|
||||
values,
|
||||
),
|
||||
);
|
||||
|
||||
form.reset()
|
||||
onClose()
|
||||
}
|
||||
form.reset();
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
||||
@@ -50,13 +79,22 @@ export default function CreateServerChannelModal() {
|
||||
</DialogHeader>
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<form
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className="space-y-4"
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel required={!schema.shape.name.isOptional()}>Name</FormLabel>
|
||||
<FormLabel
|
||||
required={
|
||||
!schema.shape.name.isOptional()
|
||||
}
|
||||
>
|
||||
Name
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
@@ -69,8 +107,17 @@ export default function CreateServerChannelModal() {
|
||||
name="type"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel required={!schema.shape.type.isOptional()}>Type</FormLabel>
|
||||
<Select defaultValue={field.value} onValueChange={field.onChange}>
|
||||
<FormLabel
|
||||
required={
|
||||
!schema.shape.type.isOptional()
|
||||
}
|
||||
>
|
||||
Type
|
||||
</FormLabel>
|
||||
<Select
|
||||
defaultValue={field.value}
|
||||
onValueChange={field.onChange}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="Select a channel type" />
|
||||
@@ -78,10 +125,15 @@ export default function CreateServerChannelModal() {
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{Object.entries({
|
||||
[ChannelType.SERVER_TEXT]: "Text",
|
||||
[ChannelType.SERVER_VOICE]: "Voice",
|
||||
[ChannelType.SERVER_TEXT]:
|
||||
"Text",
|
||||
[ChannelType.SERVER_VOICE]:
|
||||
"Voice",
|
||||
}).map(([type, label]) => (
|
||||
<SelectItem key={type} value={type}>
|
||||
<SelectItem
|
||||
key={type}
|
||||
value={type}
|
||||
>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
@@ -97,13 +149,18 @@ export default function CreateServerChannelModal() {
|
||||
Close
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
{form.formState.isSubmitting ? "Creating..." : "Create"}
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={form.formState.isSubmitting}
|
||||
>
|
||||
{form.formState.isSubmitting
|
||||
? "Creating..."
|
||||
: "Create"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,42 +3,63 @@ import React from "react";
|
||||
import { useOrigin } from "~/hooks/use-origin";
|
||||
import { ModalType, useModalStore } from "~/stores/modal-store";
|
||||
import { Button } from "../ui/button";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../ui/dialog";
|
||||
import { Input } from "../ui/input";
|
||||
import { Label } from "../ui/label";
|
||||
|
||||
export default function CreateServerInviteModal() {
|
||||
const { type, data, isOpen, onClose } = useModalStore();
|
||||
const [inviteCode, setInviteCode] = React.useState<string | undefined>(undefined)
|
||||
const origin = useOrigin()
|
||||
const [isCopied, setCopied] = React.useState(false)
|
||||
const [inviteCode, setInviteCode] = React.useState<string | undefined>(
|
||||
undefined,
|
||||
);
|
||||
const origin = useOrigin();
|
||||
const [isCopied, setCopied] = React.useState(false);
|
||||
|
||||
const isModalOpen = type === ModalType.CREATE_SERVER_INVITE && isOpen
|
||||
const inviteLink = `${origin}/app/invite/${inviteCode}`
|
||||
const isModalOpen = type === ModalType.CREATE_SERVER_INVITE && isOpen;
|
||||
const inviteLink = `${origin}/app/invite/${inviteCode}`;
|
||||
|
||||
const onOpenChange = (openState: boolean) => {
|
||||
onClose()
|
||||
}
|
||||
onClose();
|
||||
};
|
||||
|
||||
const regenerateInviteCode = () => {
|
||||
import("~/lib/api/client/server").then(m => m.default.createInvite((data as { serverId: string }).serverId)).then(invite => { setInviteCode(invite.code) })
|
||||
}
|
||||
import("~/lib/api/client/server")
|
||||
.then((m) =>
|
||||
m.default.createInvite((data as { serverId: string }).serverId),
|
||||
)
|
||||
.then((invite) => {
|
||||
setInviteCode(invite.code);
|
||||
});
|
||||
};
|
||||
|
||||
const onCopy = () => {
|
||||
navigator.clipboard.writeText(inviteLink)
|
||||
setCopied(true)
|
||||
navigator.clipboard.writeText(inviteLink);
|
||||
setCopied(true);
|
||||
|
||||
setTimeout(() => setCopied(false), 1000)
|
||||
}
|
||||
setTimeout(() => setCopied(false), 1000);
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
if (isModalOpen) {
|
||||
import("~/lib/api/client/server").then(m => m.default.createInvite((data as { serverId: string }).serverId)).then(invite => { setInviteCode(invite.code) })
|
||||
import("~/lib/api/client/server")
|
||||
.then((m) =>
|
||||
m.default.createInvite(
|
||||
(data as { serverId: string }).serverId,
|
||||
),
|
||||
)
|
||||
.then((invite) => {
|
||||
setInviteCode(invite.code);
|
||||
});
|
||||
} else {
|
||||
setInviteCode(undefined)
|
||||
setInviteCode(undefined);
|
||||
}
|
||||
}, [isModalOpen])
|
||||
|
||||
}, [isModalOpen]);
|
||||
|
||||
return (
|
||||
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
||||
@@ -51,16 +72,25 @@ export default function CreateServerInviteModal() {
|
||||
<div className="flex items-center gap-x-2">
|
||||
<Input value={inviteLink} readOnly />
|
||||
<Button variant="ghost" size="icon" onClick={onCopy}>
|
||||
{isCopied ? <Check className="size-4" /> : <Copy className="size-4" />}
|
||||
{isCopied ? (
|
||||
<Check className="size-4" />
|
||||
) : (
|
||||
<Copy className="size-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="link" size="none" className="h-9 py-2" onClick={regenerateInviteCode}>
|
||||
<Button
|
||||
variant="link"
|
||||
size="none"
|
||||
className="h-9 py-2"
|
||||
onClick={regenerateInviteCode}
|
||||
>
|
||||
Generate a new invite
|
||||
<RefreshCw />
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,8 +5,23 @@ import file from "~/lib/api/client/file";
|
||||
import server from "~/lib/api/client/server";
|
||||
import { ModalType, useModalStore } from "~/stores/modal-store";
|
||||
import { Button } from "../ui/button";
|
||||
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "../ui/form";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../ui/dialog";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "../ui/form";
|
||||
import { IconUploadField } from "../ui/icon-upload-field";
|
||||
import { Input } from "../ui/input";
|
||||
|
||||
@@ -15,37 +30,34 @@ const schema = z.object({
|
||||
icon: z.instanceof(File).optional(),
|
||||
});
|
||||
|
||||
|
||||
export default function CreateServerModal() {
|
||||
const { type, isOpen, onClose } = useModalStore();
|
||||
|
||||
const isModalOpen = type === ModalType.CREATE_SERVER && isOpen
|
||||
const isModalOpen = type === ModalType.CREATE_SERVER && isOpen;
|
||||
|
||||
let form = useForm<z.infer<typeof schema>>({
|
||||
resolver: zodResolver(schema),
|
||||
});
|
||||
|
||||
const onOpenChange = (openState: boolean) => {
|
||||
form.reset()
|
||||
onClose()
|
||||
}
|
||||
form.reset();
|
||||
onClose();
|
||||
};
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof schema>) => {
|
||||
let iconId = undefined
|
||||
let iconId = undefined;
|
||||
if (values.icon) {
|
||||
iconId = (await file.uploadFile(values.icon))[0]
|
||||
iconId = (await file.uploadFile(values.icon))[0];
|
||||
}
|
||||
|
||||
const response = await server.create({
|
||||
name: values.name,
|
||||
iconId
|
||||
})
|
||||
|
||||
form.reset()
|
||||
onClose()
|
||||
}
|
||||
|
||||
iconId,
|
||||
});
|
||||
|
||||
form.reset();
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
||||
@@ -58,13 +70,22 @@ export default function CreateServerModal() {
|
||||
</DialogHeader>
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<form
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className="space-y-4"
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="icon"
|
||||
render={({ field, fieldState }) => (
|
||||
<FormItem>
|
||||
<FormLabel required={!schema.shape.icon.isOptional()}>Icon</FormLabel>
|
||||
<FormLabel
|
||||
required={
|
||||
!schema.shape.icon.isOptional()
|
||||
}
|
||||
>
|
||||
Icon
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<div className="flex flex-col items-center justify-center">
|
||||
<IconUploadField
|
||||
@@ -82,7 +103,13 @@ export default function CreateServerModal() {
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel required={!schema.shape.name.isOptional()}>Name</FormLabel>
|
||||
<FormLabel
|
||||
required={
|
||||
!schema.shape.name.isOptional()
|
||||
}
|
||||
>
|
||||
Name
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
@@ -96,13 +123,18 @@ export default function CreateServerModal() {
|
||||
Close
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
{form.formState.isSubmitting ? "Creating..." : "Create"}
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={form.formState.isSubmitting}
|
||||
>
|
||||
{form.formState.isSubmitting
|
||||
? "Creating..."
|
||||
: "Create"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,20 +1,29 @@
|
||||
import { ModalType, useModalStore } from "~/stores/modal-store";
|
||||
import { Button } from "../ui/button";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../ui/dialog";
|
||||
|
||||
export default function DeleteServerConfirmModal() {
|
||||
const { type, data, isOpen, onClose } = useModalStore();
|
||||
|
||||
const isModalOpen = type === ModalType.DELETE_SERVER_CONFIRM && isOpen
|
||||
const isModalOpen = type === ModalType.DELETE_SERVER_CONFIRM && isOpen;
|
||||
|
||||
const onOpenChange = () => {
|
||||
onClose()
|
||||
}
|
||||
onClose();
|
||||
};
|
||||
|
||||
const onConfirm = async () => {
|
||||
await import("~/lib/api/client/server").then(m => m.default.delet((data as { serverId: string }).serverId))
|
||||
onClose()
|
||||
}
|
||||
await import("~/lib/api/client/server").then((m) =>
|
||||
m.default.delet((data as { serverId: string }).serverId),
|
||||
);
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
||||
@@ -36,5 +45,5 @@ export default function DeleteServerConfirmModal() {
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,8 +7,23 @@ import { patchUser } from "~/lib/api/client/user";
|
||||
import { ModalType, useModalStore } from "~/stores/modal-store";
|
||||
import { useUsersStore } from "~/stores/users-store";
|
||||
import { Button } from "../ui/button";
|
||||
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "../ui/form";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../ui/dialog";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "../ui/form";
|
||||
import { IconUploadField } from "../ui/icon-upload-field";
|
||||
import { Input } from "../ui/input";
|
||||
|
||||
@@ -17,61 +32,73 @@ const schema = z.object({
|
||||
avatar: z.instanceof(File).optional().nullable(),
|
||||
});
|
||||
|
||||
|
||||
export default function UpdateProfileModal() {
|
||||
const { type, isOpen, onClose } = useModalStore();
|
||||
const user = useUsersStore(useShallow(state => state.getCurrentUser()))
|
||||
const user = useUsersStore(useShallow((state) => state.getCurrentUser()));
|
||||
|
||||
const isModalOpen = type === ModalType.UPDATE_PROFILE && isOpen
|
||||
const isModalOpen = type === ModalType.UPDATE_PROFILE && isOpen;
|
||||
|
||||
let form = useForm<z.infer<typeof schema>>({
|
||||
resolver: zodResolver(schema),
|
||||
});
|
||||
|
||||
const onOpenChange = () => {
|
||||
form.reset()
|
||||
onClose()
|
||||
}
|
||||
form.reset();
|
||||
onClose();
|
||||
};
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof schema>) => {
|
||||
if (!values)
|
||||
return
|
||||
console.log("values", values);
|
||||
|
||||
let avatarId = undefined
|
||||
if (!values) return;
|
||||
|
||||
let avatarId: string | null | undefined =
|
||||
values.avatar === null ? null : undefined;
|
||||
if (values.avatar) {
|
||||
avatarId = (await file.uploadFile(values.avatar))[0]
|
||||
avatarId = (await file.uploadFile(values.avatar))[0];
|
||||
}
|
||||
|
||||
const response = await patchUser({
|
||||
displayName: values.displayName,
|
||||
avatarId
|
||||
})
|
||||
avatarId,
|
||||
});
|
||||
|
||||
form.reset()
|
||||
onClose()
|
||||
}
|
||||
form.reset();
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Update profile</DialogTitle>
|
||||
<DialogDescription>
|
||||
Update your profile.
|
||||
</DialogDescription>
|
||||
<DialogDescription>Update your profile.</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<form
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className="space-y-4"
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="avatar"
|
||||
render={({ field, fieldState }) => (
|
||||
<FormItem>
|
||||
<FormLabel required={!schema.shape.avatar.isOptional()}>Avatar</FormLabel>
|
||||
<FormLabel
|
||||
required={
|
||||
!schema.shape.avatar.isOptional()
|
||||
}
|
||||
>
|
||||
Avatar
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<div className="flex flex-col items-center justify-center">
|
||||
<IconUploadField
|
||||
defaultPreview={user?.avatarUrl}
|
||||
formDefaultValue={
|
||||
user?.avatarUrl
|
||||
}
|
||||
field={field}
|
||||
error={fieldState.error}
|
||||
/>
|
||||
@@ -86,9 +113,18 @@ export default function UpdateProfileModal() {
|
||||
name="displayName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel required={!schema.shape.displayName.isOptional()}>Display Name</FormLabel>
|
||||
<FormLabel
|
||||
required={
|
||||
!schema.shape.displayName.isOptional()
|
||||
}
|
||||
>
|
||||
Display Name
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} placeholder={user?.displayName} />
|
||||
<Input
|
||||
{...field}
|
||||
placeholder={user?.displayName}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -100,13 +136,18 @@ export default function UpdateProfileModal() {
|
||||
Close
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
{form.formState.isSubmitting ? "Updating..." : "Update"}
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={form.formState.isSubmitting}
|
||||
>
|
||||
{form.formState.isSubmitting
|
||||
? "Updating..."
|
||||
: "Update"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -25,4 +25,4 @@ export default function ModalProvider() {
|
||||
<UpdateProfileModal />
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,73 +1,74 @@
|
||||
import { createContext, useContext, useEffect, useState } from "react"
|
||||
import { createContext, useContext, useEffect, useState } from "react";
|
||||
|
||||
export type Theme = "dark" | "light" | "system"
|
||||
export type Theme = "dark" | "light" | "system";
|
||||
|
||||
type ThemeProviderProps = {
|
||||
children: React.ReactNode
|
||||
defaultTheme?: Theme
|
||||
storageKey?: string
|
||||
}
|
||||
children: React.ReactNode;
|
||||
defaultTheme?: Theme;
|
||||
storageKey?: string;
|
||||
};
|
||||
|
||||
type ThemeProviderState = {
|
||||
theme: Theme
|
||||
setTheme: (theme: Theme) => void
|
||||
}
|
||||
theme: Theme;
|
||||
setTheme: (theme: Theme) => void;
|
||||
};
|
||||
|
||||
const initialState: ThemeProviderState = {
|
||||
theme: "system",
|
||||
setTheme: () => null,
|
||||
}
|
||||
theme: "system",
|
||||
setTheme: () => null,
|
||||
};
|
||||
|
||||
const ThemeProviderContext = createContext<ThemeProviderState>(initialState)
|
||||
const ThemeProviderContext = createContext<ThemeProviderState>(initialState);
|
||||
|
||||
export function ThemeProvider({
|
||||
children,
|
||||
defaultTheme = "system",
|
||||
storageKey = "ui-theme",
|
||||
...props
|
||||
children,
|
||||
defaultTheme = "system",
|
||||
storageKey = "ui-theme",
|
||||
...props
|
||||
}: ThemeProviderProps) {
|
||||
const [theme, setTheme] = useState<Theme>(
|
||||
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme
|
||||
)
|
||||
const [theme, setTheme] = useState<Theme>(
|
||||
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const root = window.document.documentElement
|
||||
useEffect(() => {
|
||||
const root = window.document.documentElement;
|
||||
|
||||
root.classList.remove("light", "dark")
|
||||
root.classList.remove("light", "dark");
|
||||
|
||||
if (theme === "system") {
|
||||
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
|
||||
.matches
|
||||
? "dark"
|
||||
: "light"
|
||||
if (theme === "system") {
|
||||
const systemTheme = window.matchMedia(
|
||||
"(prefers-color-scheme: dark)",
|
||||
).matches
|
||||
? "dark"
|
||||
: "light";
|
||||
|
||||
root.classList.add(systemTheme)
|
||||
return
|
||||
}
|
||||
root.classList.add(systemTheme);
|
||||
return;
|
||||
}
|
||||
|
||||
root.classList.add(theme)
|
||||
}, [theme])
|
||||
root.classList.add(theme);
|
||||
}, [theme]);
|
||||
|
||||
const value = {
|
||||
theme,
|
||||
setTheme: (theme: Theme) => {
|
||||
localStorage.setItem(storageKey, theme)
|
||||
setTheme(theme)
|
||||
},
|
||||
}
|
||||
const value = {
|
||||
theme,
|
||||
setTheme: (theme: Theme) => {
|
||||
localStorage.setItem(storageKey, theme);
|
||||
setTheme(theme);
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<ThemeProviderContext.Provider {...props} value={value}>
|
||||
{children}
|
||||
</ThemeProviderContext.Provider>
|
||||
)
|
||||
return (
|
||||
<ThemeProviderContext.Provider {...props} value={value}>
|
||||
{children}
|
||||
</ThemeProviderContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export const useTheme = () => {
|
||||
const context = useContext(ThemeProviderContext)
|
||||
const context = useContext(ThemeProviderContext);
|
||||
|
||||
if (context === undefined)
|
||||
throw new Error("useTheme must be used within a ThemeProvider")
|
||||
if (context === undefined)
|
||||
throw new Error("useTheme must be used within a ThemeProvider");
|
||||
|
||||
return context
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
@@ -1,40 +1,43 @@
|
||||
import { Moon, Sun } from "lucide-react"
|
||||
import { Moon, Sun } from "lucide-react";
|
||||
|
||||
import { useTheme, type Theme } from "~/components/theme/theme-provider"
|
||||
import { Button } from "~/components/ui/button"
|
||||
import { useTheme, type Theme } from "~/components/theme/theme-provider";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuTrigger
|
||||
} from "~/components/ui/dropdown-menu"
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu";
|
||||
|
||||
export function ThemeToggle() {
|
||||
const { theme, setTheme } = useTheme()
|
||||
const { theme, setTheme } = useTheme();
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="icon">
|
||||
<Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
|
||||
<Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
|
||||
<span className="sr-only">Toggle theme</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuRadioGroup value={theme} onValueChange={(value) => setTheme(value as Theme)}>
|
||||
<DropdownMenuRadioItem value="light">
|
||||
Light
|
||||
</DropdownMenuRadioItem>
|
||||
<DropdownMenuRadioItem value="dark">
|
||||
Dark
|
||||
</DropdownMenuRadioItem>
|
||||
<DropdownMenuRadioItem value="system">
|
||||
System
|
||||
</DropdownMenuRadioItem>
|
||||
</DropdownMenuRadioGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="icon">
|
||||
<Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
|
||||
<Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
|
||||
<span className="sr-only">Toggle theme</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuRadioGroup
|
||||
value={theme}
|
||||
onValueChange={(value) => setTheme(value as Theme)}
|
||||
>
|
||||
<DropdownMenuRadioItem value="light">
|
||||
Light
|
||||
</DropdownMenuRadioItem>
|
||||
<DropdownMenuRadioItem value="dark">
|
||||
Dark
|
||||
</DropdownMenuRadioItem>
|
||||
<DropdownMenuRadioItem value="system">
|
||||
System
|
||||
</DropdownMenuRadioItem>
|
||||
</DropdownMenuRadioGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio"
|
||||
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio";
|
||||
|
||||
function AspectRatio({
|
||||
...props
|
||||
...props
|
||||
}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
|
||||
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />
|
||||
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />;
|
||||
}
|
||||
|
||||
export { AspectRatio }
|
||||
export { AspectRatio };
|
||||
|
||||
@@ -1,52 +1,51 @@
|
||||
import * as AvatarPrimitive from "@radix-ui/react-avatar"
|
||||
import * as React from "react"
|
||||
import * as AvatarPrimitive from "@radix-ui/react-avatar";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function Avatar({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
|
||||
return (
|
||||
<AvatarPrimitive.Root
|
||||
data-slot="avatar"
|
||||
className={cn(
|
||||
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<AvatarPrimitive.Root
|
||||
data-slot="avatar"
|
||||
className={cn(
|
||||
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AvatarImage({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
||||
return (
|
||||
<AvatarPrimitive.Image
|
||||
data-slot="avatar-image"
|
||||
className={cn("aspect-square size-full", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<AvatarPrimitive.Image
|
||||
data-slot="avatar-image"
|
||||
className={cn("aspect-square size-full", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AvatarFallback({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
||||
return (
|
||||
<AvatarPrimitive.Fallback
|
||||
data-slot="avatar-fallback"
|
||||
className={cn(
|
||||
"bg-muted flex size-full items-center justify-center rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<AvatarPrimitive.Fallback
|
||||
data-slot="avatar-fallback"
|
||||
className={cn(
|
||||
"bg-muted flex size-full items-center justify-center rounded-full",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Avatar, AvatarFallback, AvatarImage }
|
||||
|
||||
export { Avatar, AvatarFallback, AvatarImage };
|
||||
|
||||
@@ -1,46 +1,46 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
},
|
||||
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant,
|
||||
asChild = false,
|
||||
...props
|
||||
className,
|
||||
variant,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "span"
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "span";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
export { Badge, badgeVariants };
|
||||
|
||||
@@ -1,60 +1,59 @@
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
none: ""
|
||||
},
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
none: "",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean;
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
export { Button, buttonVariants };
|
||||
|
||||
@@ -1,87 +1,92 @@
|
||||
import * as React from "react"
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle
|
||||
}
|
||||
|
||||
Card,
|
||||
CardAction,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
};
|
||||
|
||||
256
app/components/ui/context-menu.tsx
Normal file
256
app/components/ui/context-menu.tsx
Normal file
@@ -0,0 +1,256 @@
|
||||
import * as React from "react";
|
||||
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu";
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function ContextMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />;
|
||||
}
|
||||
|
||||
function ContextMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Trigger
|
||||
data-slot="context-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal
|
||||
data-slot="context-menu-portal"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />;
|
||||
}
|
||||
|
||||
function ContextMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioGroup
|
||||
data-slot="context-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubTrigger
|
||||
data-slot="context-menu-sub-trigger"
|
||||
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 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto" />
|
||||
</ContextMenuPrimitive.SubTrigger>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubContent
|
||||
data-slot="context-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-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.Content
|
||||
data-slot="context-menu-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 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||
inset?: boolean;
|
||||
variant?: "default" | "destructive";
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Item
|
||||
data-slot="context-menu-item"
|
||||
data-inset={inset}
|
||||
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,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.CheckboxItem
|
||||
data-slot="context-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,
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.CheckboxItem>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioItem
|
||||
data-slot="context-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,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.RadioItem>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Label
|
||||
data-slot="context-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"text-foreground px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Separator
|
||||
data-slot="context-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="context-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
ContextMenu,
|
||||
ContextMenuTrigger,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuCheckboxItem,
|
||||
ContextMenuRadioItem,
|
||||
ContextMenuLabel,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuShortcut,
|
||||
ContextMenuGroup,
|
||||
ContextMenuPortal,
|
||||
ContextMenuSub,
|
||||
ContextMenuSubContent,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuRadioGroup,
|
||||
};
|
||||
@@ -1,134 +1,133 @@
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
||||
import { XIcon } from "lucide-react";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content>) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn(
|
||||
"flex flex-col gap-2 text-center sm:text-left",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn("flex flex-col-reverse gap-2 sm:flex-row", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger
|
||||
}
|
||||
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
};
|
||||
|
||||
@@ -1,247 +1,263 @@
|
||||
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 * as React from "react";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
...props
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
)
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal
|
||||
data-slot="dropdown-menu-portal"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
...props
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
className,
|
||||
sideOffset = 4,
|
||||
...props
|
||||
className,
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
data-slot="dropdown-menu-content"
|
||||
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
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
)
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
data-slot="dropdown-menu-content"
|
||||
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,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
...props
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
)
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group
|
||||
data-slot="dropdown-menu-group"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
inset?: boolean;
|
||||
variant?: "default" | "destructive";
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
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-pointer 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
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
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-pointer 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,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
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
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
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,
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
...props
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
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
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
)
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
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,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
...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({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
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
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
)
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
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,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
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
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
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,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent,
|
||||
DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger
|
||||
}
|
||||
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuTrigger,
|
||||
};
|
||||
|
||||
@@ -1,165 +1,170 @@
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import * as React from "react";
|
||||
import {
|
||||
Controller,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
useFormState,
|
||||
type ControllerProps,
|
||||
type FieldPath,
|
||||
type FieldValues,
|
||||
} from "react-hook-form"
|
||||
Controller,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
useFormState,
|
||||
type ControllerProps,
|
||||
type FieldPath,
|
||||
type FieldValues,
|
||||
} from "react-hook-form";
|
||||
|
||||
import { Label } from "~/components/ui/label"
|
||||
import { cn } from "~/lib/utils"
|
||||
import { Label } from "~/components/ui/label";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const Form = FormProvider
|
||||
const Form = FormProvider;
|
||||
|
||||
type FormFieldContextValue<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
> = {
|
||||
name: TName,
|
||||
}
|
||||
name: TName;
|
||||
};
|
||||
|
||||
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||
{} as FormFieldContextValue
|
||||
)
|
||||
{} as FormFieldContextValue,
|
||||
);
|
||||
|
||||
const FormField = <
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
>({
|
||||
...props
|
||||
...props
|
||||
}: ControllerProps<TFieldValues, TName>) => {
|
||||
return (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
</FormFieldContext.Provider>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
</FormFieldContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
const useFormField = () => {
|
||||
const fieldContext = React.useContext(FormFieldContext)
|
||||
const itemContext = React.useContext(FormItemContext)
|
||||
const { getFieldState } = useFormContext()
|
||||
const formState = useFormState({ name: fieldContext.name })
|
||||
const fieldState = getFieldState(fieldContext.name, formState)
|
||||
const fieldContext = React.useContext(FormFieldContext);
|
||||
const itemContext = React.useContext(FormItemContext);
|
||||
const { getFieldState } = useFormContext();
|
||||
const formState = useFormState({ name: fieldContext.name });
|
||||
const fieldState = getFieldState(fieldContext.name, formState);
|
||||
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>")
|
||||
}
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>");
|
||||
}
|
||||
|
||||
const { id } = itemContext
|
||||
const { id } = itemContext;
|
||||
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
}
|
||||
}
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
};
|
||||
};
|
||||
|
||||
type FormItemContextValue = {
|
||||
id: string,
|
||||
}
|
||||
id: string;
|
||||
};
|
||||
|
||||
const FormItemContext = React.createContext<FormItemContextValue>(
|
||||
{} as FormItemContextValue
|
||||
)
|
||||
{} as FormItemContextValue,
|
||||
);
|
||||
|
||||
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const id = React.useId()
|
||||
const id = React.useId();
|
||||
|
||||
return (
|
||||
<FormItemContext.Provider value={{ id }}>
|
||||
<div
|
||||
data-slot="form-item"
|
||||
className={cn("grid gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
</FormItemContext.Provider>
|
||||
)
|
||||
return (
|
||||
<FormItemContext.Provider value={{ id }}>
|
||||
<div
|
||||
data-slot="form-item"
|
||||
className={cn("grid gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
</FormItemContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function FormLabel({
|
||||
className,
|
||||
required,
|
||||
...props
|
||||
className,
|
||||
required,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root> & { required?: boolean }) {
|
||||
const { error, formItemId } = useFormField()
|
||||
const { error, formItemId } = useFormField();
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<Label
|
||||
data-slot="form-label"
|
||||
data-error={!!error}
|
||||
className={cn("data-[error=true]:text-destructive", className)}
|
||||
htmlFor={formItemId}
|
||||
{...props}
|
||||
/>
|
||||
{required && <Label className="text-destructive">*</Label>}
|
||||
</div>
|
||||
)
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<Label
|
||||
data-slot="form-label"
|
||||
data-error={!!error}
|
||||
className={cn("data-[error=true]:text-destructive", className)}
|
||||
htmlFor={formItemId}
|
||||
{...props}
|
||||
/>
|
||||
{required && <Label className="text-destructive">*</Label>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
|
||||
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
||||
const { error, formItemId, formDescriptionId, formMessageId } =
|
||||
useFormField();
|
||||
|
||||
return (
|
||||
<Slot
|
||||
data-slot="form-control"
|
||||
id={formItemId}
|
||||
aria-describedby={
|
||||
!error
|
||||
? `${formDescriptionId}`
|
||||
: `${formDescriptionId} ${formMessageId}`
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<Slot
|
||||
data-slot="form-control"
|
||||
id={formItemId}
|
||||
aria-describedby={
|
||||
!error
|
||||
? `${formDescriptionId}`
|
||||
: `${formDescriptionId} ${formMessageId}`
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { formDescriptionId } = useFormField()
|
||||
const { formDescriptionId } = useFormField();
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-description"
|
||||
id={formDescriptionId}
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<p
|
||||
data-slot="form-description"
|
||||
id={formDescriptionId}
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { error, formMessageId } = useFormField()
|
||||
const body = error ? String(error?.message ?? "") : props.children
|
||||
const { error, formMessageId } = useFormField();
|
||||
const body = error ? String(error?.message ?? "") : props.children;
|
||||
|
||||
if (!body) {
|
||||
return null
|
||||
}
|
||||
if (!body) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-message"
|
||||
id={formMessageId}
|
||||
className={cn("text-destructive text-sm", className)}
|
||||
{...props}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
)
|
||||
return (
|
||||
<p
|
||||
data-slot="form-message"
|
||||
id={formMessageId}
|
||||
className={cn("text-destructive text-sm", className)}
|
||||
{...props}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Form, FormControl,
|
||||
FormDescription, FormField, FormItem,
|
||||
FormLabel, FormMessage, useFormField
|
||||
}
|
||||
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
useFormField,
|
||||
};
|
||||
|
||||
@@ -1,43 +1,52 @@
|
||||
import { ImagePlus, XCircle } from "lucide-react";
|
||||
import React, { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { ImagePlus, RotateCcw, XCircle } from "lucide-react";
|
||||
import React, { useCallback } from "react";
|
||||
import type { ControllerRenderProps, FieldError } from "react-hook-form";
|
||||
import { Button } from "./button"; // Your existing Button component
|
||||
import { Button } from "./button";
|
||||
|
||||
// Props for our custom field component
|
||||
interface IconUploadFieldProps {
|
||||
field: ControllerRenderProps<any, string>; // Provided by RHF's FormField render prop
|
||||
error?: FieldError; // Optional: if you want to pass error for internal styling
|
||||
accept?: string; // e.g., "image/png, image/jpeg"
|
||||
previewContainerClassName?: string; // Style for the preview box itself
|
||||
// Add any other props you might want to customize its appearance/behavior
|
||||
field: ControllerRenderProps<any, string>; // field.value can be File | string (URL) | null | undefined
|
||||
error?: FieldError;
|
||||
accept?: string;
|
||||
previewContainerClassName?: string;
|
||||
defaultPreview?: string; // Visual fallback URL if field.value is initially undefined
|
||||
formDefaultValue?: string | null | undefined; // The actual RHF default value for this field
|
||||
}
|
||||
|
||||
export function IconUploadField({
|
||||
field,
|
||||
error,
|
||||
accept = "image/*",
|
||||
previewContainerClassName = "w-24 h-24 rounded-full", // Default circular preview
|
||||
previewContainerClassName = "w-24 h-24 rounded-full",
|
||||
defaultPreview,
|
||||
formDefaultValue, // New prop
|
||||
}: IconUploadFieldProps) {
|
||||
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [previewUrl, setPreviewUrl] = React.useState<string | null>(null);
|
||||
const fileInputRef = React.useRef<HTMLInputElement>(null);
|
||||
|
||||
const currentFileValue = field.value as File | undefined | null;
|
||||
React.useEffect(() => {
|
||||
let objectUrlToRevoke: string | null = null;
|
||||
|
||||
useEffect(() => {
|
||||
let objectUrl: string | null = null;
|
||||
if (currentFileValue && currentFileValue instanceof File) {
|
||||
objectUrl = URL.createObjectURL(currentFileValue);
|
||||
setPreviewUrl(objectUrl);
|
||||
if (field.value instanceof File) {
|
||||
objectUrlToRevoke = URL.createObjectURL(field.value);
|
||||
setPreviewUrl(objectUrlToRevoke);
|
||||
} else if (typeof field.value === "string" && field.value) {
|
||||
setPreviewUrl(field.value);
|
||||
} else if (field.value === null) {
|
||||
setPreviewUrl(null);
|
||||
} else if (field.value === undefined && defaultPreview) {
|
||||
// Show visual default prop if field value is undefined
|
||||
setPreviewUrl(defaultPreview);
|
||||
} else {
|
||||
setPreviewUrl(null);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (objectUrl) {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
if (objectUrlToRevoke) {
|
||||
URL.revokeObjectURL(objectUrlToRevoke);
|
||||
}
|
||||
};
|
||||
}, [currentFileValue]);
|
||||
}, [field.value, defaultPreview]);
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
@@ -47,25 +56,60 @@ export function IconUploadField({
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveImage = useCallback((e: React.MouseEvent<HTMLButtonElement>) => {
|
||||
e.preventDefault();
|
||||
field.onChange(undefined);
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = "";
|
||||
}
|
||||
}, [field]);
|
||||
const handleRemoveImage = useCallback(
|
||||
(e: React.MouseEvent<HTMLButtonElement>) => {
|
||||
e.preventDefault();
|
||||
field.onChange(null); // Set RHF value to null
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = ""; // Clear the native file input
|
||||
}
|
||||
},
|
||||
[field],
|
||||
);
|
||||
|
||||
const handleResetToDefault = useCallback(
|
||||
(e: React.MouseEvent<HTMLButtonElement>) => {
|
||||
e.preventDefault();
|
||||
// The button's visibility logic ensures formDefaultValue is relevant.
|
||||
// This will set RHF value to string (URL), null, or undefined, as per formDefaultValue.
|
||||
field.onChange(undefined);
|
||||
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = ""; // Clear the native file input
|
||||
}
|
||||
},
|
||||
[field, formDefaultValue],
|
||||
);
|
||||
|
||||
const triggerFileInput = useCallback(() => {
|
||||
fileInputRef.current?.click();
|
||||
}, []);
|
||||
|
||||
// Visibility for the "Remove" button: show if there's a File or a URL string in field.value
|
||||
const showRemoveButton =
|
||||
(!!field.value &&
|
||||
(field.value instanceof File || typeof field.value === "string")) ||
|
||||
(formDefaultValue && field.value === undefined);
|
||||
|
||||
// Visibility for the "Reset to Default" button
|
||||
const canReset = typeof formDefaultValue !== "undefined"; // Was a formDefaultValue prop provided?
|
||||
// Is current value different from the formDefaultValue?
|
||||
// (A File object is always different from a URL string/null/undefined default)
|
||||
const isDifferentFromDefault =
|
||||
(field.value instanceof File ||
|
||||
(field.value !== formDefaultValue && field.value !== undefined)) &&
|
||||
formDefaultValue;
|
||||
const showResetButton = canReset && isDifferentFromDefault;
|
||||
|
||||
return (
|
||||
<div className="flex items-center space-x-4">
|
||||
{/* Main clickable area for upload, also receives RHF's ref */}
|
||||
<div
|
||||
ref={field.ref} // Attach RHF's ref here for focus management
|
||||
className={`relative ${previewContainerClassName} border-2 ${error ? "border-destructive" : "border-dashed border-muted-foreground"
|
||||
} flex items-center justify-center cursor-pointer hover:border-primary transition-colors overflow-hidden`}
|
||||
ref={field.ref}
|
||||
className={`relative ${previewContainerClassName} border-2 ${
|
||||
error
|
||||
? "border-destructive"
|
||||
: "border-dashed border-muted-foreground"
|
||||
} flex items-center justify-center cursor-pointer hover:border-primary transition-colors overflow-hidden`}
|
||||
onClick={triggerFileInput}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
@@ -86,36 +130,51 @@ export function IconUploadField({
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<ImagePlus className={`w-10 h-10 ${error ? "text-destructive" : "text-muted-foreground"}`} />
|
||||
<ImagePlus
|
||||
className={`w-10 h-10 ${error ? "text-destructive" : "text-muted-foreground"}`}
|
||||
/>
|
||||
)}
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef} // Internal ref for programmatic click
|
||||
className="hidden" // Visually hidden
|
||||
ref={fileInputRef}
|
||||
className="hidden"
|
||||
accept={accept}
|
||||
onChange={handleFileChange}
|
||||
onBlur={field.onBlur} // RHF's onBlur for touched state
|
||||
name={field.name} // RHF's field name
|
||||
// The `value` of a file input is not directly controlled by RHF's `field.value` (which is a File object)
|
||||
onBlur={field.onBlur}
|
||||
name={field.name}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col space-y-2">
|
||||
{/* Optional: A separate button to trigger file input, if needed. */}
|
||||
{/* <Button type="button" variant="outline" size="sm" onClick={triggerFileInput}>
|
||||
{previewUrl ? "Change Icon" : "Upload Icon"}
|
||||
</Button> */}
|
||||
{currentFileValue && ( // Show remove button only if a file is selected
|
||||
|
||||
{showRemoveButton && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={handleRemoveImage}
|
||||
>
|
||||
<XCircle className="" />
|
||||
<XCircle className="mr-2 h-4 w-4" />
|
||||
Remove
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{showResetButton && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline" // Choose a suitable variant
|
||||
size="sm"
|
||||
onClick={handleResetToDefault}
|
||||
>
|
||||
<RotateCcw className="mr-2 h-4 w-4" />
|
||||
Reset to Default
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import * as React from "react"
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Input }
|
||||
export { Input };
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import * as React from "react";
|
||||
import * as LabelPrimitive from "@radix-ui/react-label";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Label }
|
||||
export { Label };
|
||||
|
||||
@@ -1,82 +1,82 @@
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
|
||||
import * as React from "react"
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
scrollbarSize,
|
||||
viewportRef,
|
||||
...props
|
||||
className,
|
||||
children,
|
||||
scrollbarSize,
|
||||
viewportRef,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root> & {
|
||||
scrollbarSize?: "default" | "narrow" | "none",
|
||||
viewportRef?: React.Ref<HTMLDivElement>
|
||||
scrollbarSize?: "default" | "narrow" | "none";
|
||||
viewportRef?: React.Ref<HTMLDivElement>;
|
||||
}) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
ref={viewportRef}
|
||||
data-slot="scroll-area-viewport"
|
||||
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar size={scrollbarSize} />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
)
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
ref={viewportRef}
|
||||
data-slot="scroll-area-viewport"
|
||||
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar size={scrollbarSize} />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
size = "default",
|
||||
...props
|
||||
className,
|
||||
orientation = "vertical",
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar> & {
|
||||
size?: "default" | "narrow" | "none"
|
||||
size?: "default" | "narrow" | "none";
|
||||
}) {
|
||||
const classes = {
|
||||
vertical: {
|
||||
className: "h-full border-l border-l-transparent",
|
||||
size: {
|
||||
default: "w-2.5",
|
||||
narrow: "w-1.5",
|
||||
none: "hidden",
|
||||
},
|
||||
},
|
||||
horizontal: {
|
||||
className: "flex-col border-t border-t-transparent",
|
||||
size: {
|
||||
default: "h-2.5",
|
||||
narrow: "h-1.5",
|
||||
none: "hidden",
|
||||
},
|
||||
},
|
||||
}
|
||||
const classes = {
|
||||
vertical: {
|
||||
className: "h-full border-l border-l-transparent",
|
||||
size: {
|
||||
default: "w-2.5",
|
||||
narrow: "w-1.5",
|
||||
none: "hidden",
|
||||
},
|
||||
},
|
||||
horizontal: {
|
||||
className: "flex-col border-t border-t-transparent",
|
||||
size: {
|
||||
default: "h-2.5",
|
||||
narrow: "h-1.5",
|
||||
none: "hidden",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
data-slot="scroll-area-scrollbar"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none p-px transition-colors select-none",
|
||||
classes[orientation].className,
|
||||
classes[orientation].size[size],
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb
|
||||
data-slot="scroll-area-thumb"
|
||||
className="bg-border relative flex-1 rounded-full"
|
||||
/>
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
)
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
data-slot="scroll-area-scrollbar"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none p-px transition-colors select-none",
|
||||
classes[orientation].className,
|
||||
classes[orientation].size[size],
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb
|
||||
data-slot="scroll-area-thumb"
|
||||
className="bg-border relative flex-1 rounded-full"
|
||||
/>
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
);
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
export { ScrollArea, ScrollBar };
|
||||
|
||||
@@ -1,183 +1,189 @@
|
||||
import * as React from "react"
|
||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||
import * as React from "react";
|
||||
import * as SelectPrimitive from "@radix-ui/react-select";
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function Select({
|
||||
...props
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
...props
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default"
|
||||
size?: "sm" | "default";
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
)
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "popper",
|
||||
...props
|
||||
className,
|
||||
children,
|
||||
position = "popper",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-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 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
)
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-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 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className,
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn(
|
||||
"text-muted-foreground px-2 py-1.5 text-xs",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 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 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute right-2 flex size-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
)
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 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 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute right-2 flex size-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn(
|
||||
"bg-border pointer-events-none -mx-1 my-1 h-px",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
)
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
)
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
}
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
};
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
import * as React from "react"
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
import * as React from "react";
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator-root"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator-root"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
export { Separator };
|
||||
|
||||
@@ -1,64 +1,64 @@
|
||||
import * as React from "react"
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs"
|
||||
import * as React from "react";
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function Tabs({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||
return (
|
||||
<TabsPrimitive.Root
|
||||
data-slot="tabs"
|
||||
className={cn("flex flex-col gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<TabsPrimitive.Root
|
||||
data-slot="tabs"
|
||||
className={cn("flex flex-col gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TabsList({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.List>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
className={cn(
|
||||
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
className={cn(
|
||||
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TabsTrigger({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
return (
|
||||
<TabsPrimitive.Trigger
|
||||
data-slot="tabs-trigger"
|
||||
className={cn(
|
||||
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<TabsPrimitive.Trigger
|
||||
data-slot="tabs-trigger"
|
||||
className={cn(
|
||||
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TabsContent({
|
||||
className,
|
||||
...props
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
||||
return (
|
||||
<TabsPrimitive.Content
|
||||
data-slot="tabs-content"
|
||||
className={cn("flex-1 outline-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<TabsPrimitive.Content
|
||||
data-slot="tabs-content"
|
||||
className={cn("flex-1 outline-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent }
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent };
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import * as React from "react"
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Textarea }
|
||||
export { Textarea };
|
||||
|
||||
@@ -1,59 +1,59 @@
|
||||
import * as React from "react"
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function Tooltip({
|
||||
...props
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
</TooltipProvider>
|
||||
)
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function TooltipTrigger({
|
||||
...props
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
sideOffset = 0,
|
||||
children,
|
||||
...props
|
||||
className,
|
||||
sideOffset = 0,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger };
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import type { PartialUser } from "~/lib/api/types"
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar"
|
||||
import type { PartialUser } from "~/lib/api/types";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar";
|
||||
|
||||
interface UserAvatarProps {
|
||||
user: PartialUser | undefined
|
||||
user: PartialUser | undefined;
|
||||
}
|
||||
|
||||
export default function UserAvatar(
|
||||
{ user, ...props }: UserAvatarProps & React.ComponentProps<typeof Avatar>
|
||||
) {
|
||||
export default function UserAvatar({
|
||||
user,
|
||||
...props
|
||||
}: UserAvatarProps & React.ComponentProps<typeof Avatar>) {
|
||||
return (
|
||||
<Avatar {...props}>
|
||||
<AvatarImage src={user?.avatarUrl} />
|
||||
@@ -15,5 +16,5 @@ export default function UserAvatar(
|
||||
{user?.username?.[0]}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
62
app/components/user-context-menu.tsx
Normal file
62
app/components/user-context-menu.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import { IdCard, Mail } from "lucide-react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { createChannel } from "~/lib/api/client/user";
|
||||
import type { UserId } from "~/lib/api/types";
|
||||
import { useUsersStore } from "~/stores/users-store";
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuTrigger,
|
||||
} from "./ui/context-menu";
|
||||
|
||||
interface UserContextMenuProps {
|
||||
userId: UserId;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export default function UserContextMenu({
|
||||
userId,
|
||||
children,
|
||||
}: UserContextMenuProps) {
|
||||
const currentUser = useUsersStore((state) => state.getCurrentUser());
|
||||
const navigate = useNavigate();
|
||||
|
||||
const onMessage = async () => {
|
||||
const reponse = await createChannel([userId]);
|
||||
|
||||
navigate(`/app/@me/channels/${reponse.id}`);
|
||||
};
|
||||
|
||||
const onCopyId = () => {
|
||||
navigator.clipboard.writeText(userId);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
|
||||
<ContextMenuContent>
|
||||
{currentUser?.id !== userId && (
|
||||
<>
|
||||
<ContextMenuItem asChild onClick={onMessage}>
|
||||
<div className="flex justify-between gap-2">
|
||||
Message
|
||||
<Mail />
|
||||
</div>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
<ContextMenuItem asChild onClick={onCopyId}>
|
||||
<div className="flex justify-between gap-2">
|
||||
Copy ID
|
||||
<IdCard />
|
||||
</div>
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
interface VisibleTriggerProps {
|
||||
onVisible: () => void | Promise<void>;
|
||||
@@ -20,7 +20,7 @@ export default function VisibleTrigger({
|
||||
children,
|
||||
style,
|
||||
...props
|
||||
}: VisibleTriggerProps & React.ComponentProps<'div'>) {
|
||||
}: VisibleTriggerProps & React.ComponentProps<"div">) {
|
||||
const elementRef = useRef(null); // Ref to attach to the DOM element we want to observe
|
||||
|
||||
useEffect(() => {
|
||||
@@ -34,7 +34,7 @@ export default function VisibleTrigger({
|
||||
// Default IntersectionObserver options
|
||||
const defaultOptions = {
|
||||
root: null, // default is the viewport
|
||||
rootMargin: '0px', // No margin by default
|
||||
rootMargin: "0px", // No margin by default
|
||||
threshold: 0, // Trigger as soon as any part of the element is visible
|
||||
};
|
||||
|
||||
@@ -62,7 +62,7 @@ export default function VisibleTrigger({
|
||||
// console.log('VisibleTrigger: Element is NOT intersecting.', entry);
|
||||
}
|
||||
},
|
||||
observerOptions // Pass the options to the observer
|
||||
observerOptions, // Pass the options to the observer
|
||||
);
|
||||
|
||||
// Start observing the element
|
||||
@@ -93,10 +93,10 @@ export default function VisibleTrigger({
|
||||
return (
|
||||
<div
|
||||
ref={elementRef}
|
||||
style={{ minHeight: children ? 'auto' : '1px', ...style }}
|
||||
style={{ minHeight: children ? "auto" : "1px", ...style }}
|
||||
{...props}
|
||||
>
|
||||
{children} {/* Render any children passed to the component */}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,11 +7,14 @@ export const useOrigin = () => {
|
||||
setIsMounted(true);
|
||||
}, []);
|
||||
|
||||
const origin = typeof window !== 'undefined' && window.location.origin ? window.location.origin : '';
|
||||
const origin =
|
||||
typeof window !== "undefined" && window.location.origin
|
||||
? window.location.origin
|
||||
: "";
|
||||
|
||||
if (!isMounted) {
|
||||
return '';
|
||||
return "";
|
||||
}
|
||||
|
||||
return origin;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,34 +1,34 @@
|
||||
import axios from "../http-client"
|
||||
import type { FullUser } from "../types"
|
||||
import axios from "../http-client";
|
||||
import type { FullUser } from "../types";
|
||||
|
||||
interface RegisterRequest {
|
||||
email: string
|
||||
username: string
|
||||
displayName?: string
|
||||
password: string
|
||||
email: string;
|
||||
username: string;
|
||||
displayName?: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
interface LoginRequest {
|
||||
username: string
|
||||
password: string
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
interface LoginResponse {
|
||||
user: FullUser
|
||||
token: string
|
||||
user: FullUser;
|
||||
token: string;
|
||||
}
|
||||
|
||||
export async function register(request: RegisterRequest) {
|
||||
await axios.post("/auth/register", request)
|
||||
await axios.post("/auth/register", request);
|
||||
}
|
||||
|
||||
export async function login(request: LoginRequest) {
|
||||
const response = await axios.post("/auth/login", request)
|
||||
const response = await axios.post("/auth/login", request);
|
||||
|
||||
return response.data as LoginResponse
|
||||
return response.data as LoginResponse;
|
||||
}
|
||||
|
||||
export default {
|
||||
register,
|
||||
login,
|
||||
}
|
||||
};
|
||||
|
||||
@@ -10,26 +10,28 @@ export async function paginatedMessages(
|
||||
params: {
|
||||
limit,
|
||||
before,
|
||||
}
|
||||
})
|
||||
},
|
||||
});
|
||||
|
||||
return (response.data as any[]).map((value, _) => messageSchema.parse(value))
|
||||
return (response.data as any[]).map((value, _) =>
|
||||
messageSchema.parse(value),
|
||||
);
|
||||
}
|
||||
|
||||
export async function sendMessage(
|
||||
channelId: ChannelId,
|
||||
content: string,
|
||||
attachments?: Uuid[]
|
||||
attachments?: Uuid[],
|
||||
) {
|
||||
const response = await axios.post(`/channels/${channelId}/messages`, {
|
||||
content,
|
||||
attachments,
|
||||
})
|
||||
});
|
||||
|
||||
return messageSchema.parse(response.data)
|
||||
return messageSchema.parse(response.data);
|
||||
}
|
||||
|
||||
export default {
|
||||
paginatedMessages,
|
||||
sendMessage,
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
import axios from "../http-client"
|
||||
import axios from "../http-client";
|
||||
|
||||
export async function uploadFile(file: File) {
|
||||
const formData = new FormData()
|
||||
formData.append("files", file)
|
||||
const formData = new FormData();
|
||||
formData.append("files", file);
|
||||
|
||||
const response = await axios.postForm(`/files`, formData)
|
||||
const response = await axios.postForm(`/files`, formData);
|
||||
|
||||
return response.data as string[]
|
||||
return response.data as string[];
|
||||
}
|
||||
|
||||
export async function uploadFiles(file: File[]) {
|
||||
const formData = new FormData()
|
||||
const formData = new FormData();
|
||||
for (const f of file) {
|
||||
formData.append("files", f)
|
||||
formData.append("files", f);
|
||||
}
|
||||
|
||||
const response = await axios.postForm(`/files`, formData)
|
||||
const response = await axios.postForm(`/files`, formData);
|
||||
|
||||
return response.data as string[]
|
||||
return response.data as string[];
|
||||
}
|
||||
|
||||
export default {
|
||||
uploadFile,
|
||||
uploadFiles
|
||||
}
|
||||
uploadFiles,
|
||||
};
|
||||
|
||||
@@ -1,74 +1,88 @@
|
||||
import axios from "../http-client"
|
||||
import type { ChannelId, ChannelType, Server, ServerChannel, ServerId, ServerInvite } from "../types"
|
||||
import axios from "../http-client";
|
||||
import type {
|
||||
ChannelId,
|
||||
ChannelType,
|
||||
Server,
|
||||
ServerChannel,
|
||||
ServerId,
|
||||
ServerInvite,
|
||||
} from "../types";
|
||||
|
||||
interface CreateServerRequest {
|
||||
name: string
|
||||
iconId?: string
|
||||
name: string;
|
||||
iconId?: string;
|
||||
}
|
||||
|
||||
interface CreateServerChannelRequest {
|
||||
name: string
|
||||
type: ChannelType
|
||||
name: string;
|
||||
type: ChannelType;
|
||||
}
|
||||
|
||||
export async function list() {
|
||||
const response = await axios.get("/servers")
|
||||
const response = await axios.get("/servers");
|
||||
|
||||
return response.data as Server[]
|
||||
return response.data as Server[];
|
||||
}
|
||||
|
||||
export async function create(request: CreateServerRequest) {
|
||||
const response = await axios.post("/servers", request)
|
||||
const response = await axios.post("/servers", request);
|
||||
|
||||
return response.data as Server
|
||||
return response.data as Server;
|
||||
}
|
||||
|
||||
export async function get(serverId: ServerId) {
|
||||
const response = await axios.get(`/servers/${serverId}`)
|
||||
const response = await axios.get(`/servers/${serverId}`);
|
||||
|
||||
return response.data as Server
|
||||
return response.data as Server;
|
||||
}
|
||||
|
||||
export async function delet(serverId: ServerId) {
|
||||
const response = await axios.delete(`/servers/${serverId}`)
|
||||
const response = await axios.delete(`/servers/${serverId}`);
|
||||
|
||||
return response.data as Server
|
||||
return response.data as Server;
|
||||
}
|
||||
|
||||
export async function listChannels(serverId: ServerId) {
|
||||
const response = await axios.get(`/servers/${serverId}/channels`)
|
||||
const response = await axios.get(`/servers/${serverId}/channels`);
|
||||
|
||||
return response.data as ServerChannel[]
|
||||
return response.data as ServerChannel[];
|
||||
}
|
||||
|
||||
export async function createChannel(serverId: ServerId, request: CreateServerChannelRequest) {
|
||||
const response = await axios.post(`/servers/${serverId}/channels`, request)
|
||||
export async function createChannel(
|
||||
serverId: ServerId,
|
||||
request: CreateServerChannelRequest,
|
||||
) {
|
||||
const response = await axios.post(`/servers/${serverId}/channels`, request);
|
||||
|
||||
return response.data as ServerChannel
|
||||
return response.data as ServerChannel;
|
||||
}
|
||||
|
||||
export async function getChannel(serverId: ServerId, channelId: ChannelId) {
|
||||
const response = await axios.get(`/servers/${serverId}/channels/${channelId}`)
|
||||
const response = await axios.get(
|
||||
`/servers/${serverId}/channels/${channelId}`,
|
||||
);
|
||||
|
||||
return response.data as ServerChannel
|
||||
return response.data as ServerChannel;
|
||||
}
|
||||
|
||||
export async function deleteChannel(serverId: ServerId, channelId: ChannelId) {
|
||||
const response = await axios.delete(`/servers/${serverId}/channels/${channelId}`)
|
||||
const response = await axios.delete(
|
||||
`/servers/${serverId}/channels/${channelId}`,
|
||||
);
|
||||
|
||||
return response.data as ServerChannel
|
||||
return response.data as ServerChannel;
|
||||
}
|
||||
|
||||
export async function createInvite(serverId: ServerId) {
|
||||
const response = await axios.post(`/servers/${serverId}/invites`)
|
||||
const response = await axios.post(`/servers/${serverId}/invites`);
|
||||
|
||||
return response.data as ServerInvite
|
||||
return response.data as ServerInvite;
|
||||
}
|
||||
|
||||
export async function getInvite(inviteCode: string) {
|
||||
const response = await axios.get(`/invites/${inviteCode}`)
|
||||
const response = await axios.get(`/invites/${inviteCode}`);
|
||||
|
||||
return response.data as Server
|
||||
return response.data as Server;
|
||||
}
|
||||
|
||||
export default {
|
||||
@@ -81,5 +95,5 @@ export default {
|
||||
getChannel,
|
||||
deleteChannel,
|
||||
createInvite,
|
||||
getInvite
|
||||
}
|
||||
getInvite,
|
||||
};
|
||||
|
||||
@@ -1,38 +1,53 @@
|
||||
import axios from "../http-client"
|
||||
import type { FullUser, PartialUser, RecipientChannel, UserId, Uuid } from "../types"
|
||||
import axios from "../http-client";
|
||||
import type {
|
||||
FullUser,
|
||||
PartialUser,
|
||||
RecipientChannel,
|
||||
UserId,
|
||||
Uuid,
|
||||
} from "../types";
|
||||
|
||||
export async function me() {
|
||||
const response = await axios.get("/users/@me")
|
||||
const response = await axios.get("/users/@me");
|
||||
|
||||
return response.data as FullUser
|
||||
return response.data as FullUser;
|
||||
}
|
||||
|
||||
export async function getUser(userId: UserId) {
|
||||
const response = await axios.get(`/users/${userId}`)
|
||||
const response = await axios.get(`/users/${userId}`);
|
||||
|
||||
return response.data as PartialUser
|
||||
return response.data as PartialUser;
|
||||
}
|
||||
|
||||
export async function channels() {
|
||||
const response = await axios.get("/users/@me/channels")
|
||||
const response = await axios.get("/users/@me/channels");
|
||||
|
||||
return response.data as RecipientChannel[]
|
||||
return response.data as RecipientChannel[];
|
||||
}
|
||||
|
||||
export async function createChannel(recipients: UserId[]) {
|
||||
const response = await axios.post("/users/@me/channels", {
|
||||
recipients,
|
||||
});
|
||||
|
||||
return response.data as RecipientChannel;
|
||||
}
|
||||
|
||||
interface PatchUserRequest {
|
||||
displayName?: string | null
|
||||
avatarId?: Uuid | null
|
||||
displayName?: string | null;
|
||||
avatarId?: Uuid | null;
|
||||
}
|
||||
|
||||
export async function patchUser(request: PatchUserRequest) {
|
||||
const response = await axios.patch(`/users/@me`, request)
|
||||
const response = await axios.patch(`/users/@me`, request);
|
||||
|
||||
return response.data as FullUser
|
||||
return response.data as FullUser;
|
||||
}
|
||||
|
||||
export default {
|
||||
me,
|
||||
channels,
|
||||
createChannel,
|
||||
getUser,
|
||||
patchUser
|
||||
}
|
||||
patchUser,
|
||||
};
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
import axios from "axios"
|
||||
import { useTokenStore } from "~/stores/token-store"
|
||||
import { API_URL } from "../consts"
|
||||
import axios from "axios";
|
||||
import { useTokenStore } from "~/stores/token-store";
|
||||
import { API_URL } from "../consts";
|
||||
|
||||
axios.interceptors.request.use(
|
||||
(config) => {
|
||||
const token = useTokenStore.getState().token
|
||||
const token = useTokenStore.getState().token;
|
||||
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
return config
|
||||
return config;
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
|
||||
axios.defaults.baseURL = API_URL
|
||||
axios.defaults.headers.common["Content-Type"] = "application/json"
|
||||
axios.defaults.baseURL = API_URL;
|
||||
axios.defaults.headers.common["Content-Type"] = "application/json";
|
||||
|
||||
export default axios
|
||||
export default axios;
|
||||
|
||||
@@ -1,85 +1,86 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export type TypeToZod<T> = {
|
||||
[K in keyof T]:
|
||||
// 1. Handle Arrays (including arrays of objects, optional or required)
|
||||
[K in keyof T]: // 1. Handle Arrays (including arrays of objects, optional or required)
|
||||
T[K] extends ReadonlyArray<infer E> | undefined
|
||||
? undefined extends T[K]
|
||||
? E extends object
|
||||
? z.ZodOptional<z.ZodArray<z.ZodObject<TypeToZod<E>>>>
|
||||
: z.ZodOptional<z.ZodArray<z.ZodType<Exclude<E, null | undefined>>>>
|
||||
: E extends object
|
||||
? z.ZodArray<z.ZodObject<TypeToZod<E>>>
|
||||
: z.ZodArray<z.ZodType<Exclude<E, null | undefined>>>
|
||||
// 2. Handle Primitives
|
||||
: T[K] extends string | number | boolean | Date | null | undefined
|
||||
? undefined extends T[K]
|
||||
? z.ZodOptional<z.ZodType<Exclude<T[K], undefined | null>>>
|
||||
: z.ZodType<T[K]>
|
||||
// 3. Handle Objects (required or optional, but not arrays)
|
||||
: T[K] extends object | undefined
|
||||
? undefined extends T[K]
|
||||
? z.ZodOptional<z.ZodObject<TypeToZod<NonNullable<T[K]>>>>
|
||||
: T[K] extends object
|
||||
? z.ZodObject<TypeToZod<T[K]>>
|
||||
: z.ZodUnknown // Fallback for unexpected required non-object/non-primitive types
|
||||
// 4. Fallback for any other types
|
||||
: z.ZodUnknown;
|
||||
? undefined extends T[K]
|
||||
? E extends object
|
||||
? z.ZodOptional<z.ZodArray<z.ZodObject<TypeToZod<E>>>>
|
||||
: z.ZodOptional<
|
||||
z.ZodArray<z.ZodType<Exclude<E, null | undefined>>>
|
||||
>
|
||||
: E extends object
|
||||
? z.ZodArray<z.ZodObject<TypeToZod<E>>>
|
||||
: z.ZodArray<z.ZodType<Exclude<E, null | undefined>>>
|
||||
: // 2. Handle Primitives
|
||||
T[K] extends string | number | boolean | Date | null | undefined
|
||||
? undefined extends T[K]
|
||||
? z.ZodOptional<z.ZodType<Exclude<T[K], undefined | null>>>
|
||||
: z.ZodType<T[K]>
|
||||
: // 3. Handle Objects (required or optional, but not arrays)
|
||||
T[K] extends object | undefined
|
||||
? undefined extends T[K]
|
||||
? z.ZodOptional<z.ZodObject<TypeToZod<NonNullable<T[K]>>>>
|
||||
: T[K] extends object
|
||||
? z.ZodObject<TypeToZod<T[K]>>
|
||||
: z.ZodUnknown // Fallback for unexpected required non-object/non-primitive types
|
||||
: // 4. Fallback for any other types
|
||||
z.ZodUnknown;
|
||||
};
|
||||
|
||||
export const createZodObject = <T>(obj: TypeToZod<T>) => {
|
||||
return z.object(obj);
|
||||
};
|
||||
|
||||
export type Uuid = string
|
||||
export type Uuid = string;
|
||||
|
||||
export type UserId = Uuid
|
||||
export type ServerId = Uuid
|
||||
export type ChannelId = Uuid
|
||||
export type MessageId = Uuid
|
||||
export type UserId = Uuid;
|
||||
export type ServerId = Uuid;
|
||||
export type ChannelId = Uuid;
|
||||
export type MessageId = Uuid;
|
||||
|
||||
export interface FullUser {
|
||||
id: UserId
|
||||
avatarUrl?: string
|
||||
username: string
|
||||
displayName?: string
|
||||
email: string
|
||||
bot: boolean
|
||||
system: boolean
|
||||
settings: any
|
||||
id: UserId;
|
||||
avatarUrl?: string;
|
||||
username: string;
|
||||
displayName?: string;
|
||||
email: string;
|
||||
bot: boolean;
|
||||
system: boolean;
|
||||
settings: any;
|
||||
}
|
||||
|
||||
export interface Server {
|
||||
id: ServerId
|
||||
name: string
|
||||
iconUrl?: string
|
||||
ownerId: UserId
|
||||
id: ServerId;
|
||||
name: string;
|
||||
iconUrl?: string;
|
||||
ownerId: UserId;
|
||||
}
|
||||
|
||||
export enum ChannelType {
|
||||
SERVER_TEXT = 'server_text',
|
||||
SERVER_VOICE = 'server_voice',
|
||||
SERVER_CATEGORY = 'server_category',
|
||||
SERVER_TEXT = "server_text",
|
||||
SERVER_VOICE = "server_voice",
|
||||
SERVER_CATEGORY = "server_category",
|
||||
|
||||
DIRECT_MESSAGE = 'direct_message',
|
||||
GROUP = 'group',
|
||||
DIRECT_MESSAGE = "direct_message",
|
||||
GROUP = "group",
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
id: MessageId
|
||||
channelId: ChannelId
|
||||
authorId: UserId
|
||||
content: string
|
||||
createdAt: Date
|
||||
attachments: UploadedFile[]
|
||||
id: MessageId;
|
||||
channelId: ChannelId;
|
||||
authorId: UserId;
|
||||
content: string;
|
||||
createdAt: Date;
|
||||
attachments: UploadedFile[];
|
||||
}
|
||||
|
||||
export interface UploadedFile {
|
||||
id: Uuid
|
||||
filename: string
|
||||
contentType: string
|
||||
size: number
|
||||
url: string
|
||||
id: Uuid;
|
||||
filename: string;
|
||||
contentType: string;
|
||||
size: number;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export const uploadFileSchema = createZodObject<UploadedFile>({
|
||||
@@ -88,7 +89,7 @@ export const uploadFileSchema = createZodObject<UploadedFile>({
|
||||
contentType: z.string(),
|
||||
size: z.number(),
|
||||
url: z.string(),
|
||||
})
|
||||
});
|
||||
|
||||
export const messageSchema = createZodObject<Message>({
|
||||
id: z.string(),
|
||||
@@ -97,44 +98,44 @@ export const messageSchema = createZodObject<Message>({
|
||||
content: z.string(),
|
||||
createdAt: z.coerce.date(),
|
||||
attachments: z.array(uploadFileSchema),
|
||||
})
|
||||
});
|
||||
|
||||
export interface Channel {
|
||||
id: ChannelId
|
||||
name: string
|
||||
type: ChannelType
|
||||
lastMessageId?: MessageId
|
||||
id: ChannelId;
|
||||
name: string;
|
||||
type: ChannelType;
|
||||
lastMessageId?: MessageId;
|
||||
}
|
||||
|
||||
export interface ServerChannel {
|
||||
id: ChannelId
|
||||
name: string
|
||||
type: ChannelType
|
||||
lastMessageId?: MessageId
|
||||
serverId: ServerId
|
||||
parentId?: ChannelId
|
||||
id: ChannelId;
|
||||
name: string;
|
||||
type: ChannelType;
|
||||
lastMessageId?: MessageId;
|
||||
serverId: ServerId;
|
||||
parentId?: ChannelId;
|
||||
}
|
||||
|
||||
export interface ServerInvite {
|
||||
code: string
|
||||
serverId: ServerId
|
||||
inviterId?: UserId
|
||||
expiresAt?: string
|
||||
code: string;
|
||||
serverId: ServerId;
|
||||
inviterId?: UserId;
|
||||
expiresAt?: string;
|
||||
}
|
||||
|
||||
export interface RecipientChannel {
|
||||
id: ChannelId
|
||||
name: string
|
||||
type: ChannelType
|
||||
lastMessageId?: MessageId
|
||||
recipients: PartialUser[]
|
||||
id: ChannelId;
|
||||
name: string;
|
||||
type: ChannelType;
|
||||
lastMessageId?: MessageId;
|
||||
recipients: PartialUser[];
|
||||
}
|
||||
|
||||
export interface PartialUser {
|
||||
id: ChannelId
|
||||
username: string
|
||||
displayName?: string
|
||||
avatarUrl?: string,
|
||||
bot: boolean
|
||||
system: boolean
|
||||
}
|
||||
id: ChannelId;
|
||||
username: string;
|
||||
displayName?: string;
|
||||
avatarUrl?: string;
|
||||
bot: boolean;
|
||||
system: boolean;
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
export const API_URL = "http://localhost:12345/api/v1"
|
||||
export const API_URL = "http://localhost:12345/api/v1";
|
||||
|
||||
@@ -2,42 +2,46 @@ import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
export function getFirstLetters(str: string, n: number): string {
|
||||
return str
|
||||
.split(/\s+/)
|
||||
.slice(0, n)
|
||||
.map(word => word[0] || '')
|
||||
.join('');
|
||||
return str
|
||||
.split(/\s+/)
|
||||
.slice(0, n)
|
||||
.map((word) => word[0] || "")
|
||||
.join("");
|
||||
}
|
||||
|
||||
export function formatFileSize(bytes: number, decimals = 2): string {
|
||||
if (bytes === 0) return '0 Bytes';
|
||||
if (bytes === 0) return "0 Bytes";
|
||||
const k = 1024;
|
||||
const dm = decimals < 0 ? 0 : decimals;
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
|
||||
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
|
||||
}
|
||||
|
||||
export function createPrefixedLogger(prefix: string, styles?: string[]) {
|
||||
const result: Record<string, (...args: any[]) => void> = {};
|
||||
const result: Record<string, (...args: any[]) => void> = {};
|
||||
|
||||
const methods = ['log', 'trace', 'debug', 'info', 'warn', 'error'] as const;
|
||||
const methods = ["log", "trace", "debug", "info", "warn", "error"] as const;
|
||||
|
||||
for (const methodName of methods) {
|
||||
const originalMethod = console[methodName].bind(console);
|
||||
for (const methodName of methods) {
|
||||
const originalMethod = console[methodName].bind(console);
|
||||
|
||||
result[methodName] = (...args: any[]) => {
|
||||
if (typeof args[0] === 'string') {
|
||||
originalMethod(`${prefix} ${args[0]}`, ...(styles || []), ...args.slice(1));
|
||||
} else {
|
||||
originalMethod(prefix, styles, ...args);
|
||||
}
|
||||
};
|
||||
}
|
||||
result[methodName] = (...args: any[]) => {
|
||||
if (typeof args[0] === "string") {
|
||||
originalMethod(
|
||||
`${prefix} ${args[0]}`,
|
||||
...(styles || []),
|
||||
...args.slice(1),
|
||||
);
|
||||
} else {
|
||||
originalMethod(prefix, styles, ...args);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ChannelId, ServerId, UserId } from '~/lib/api/types';
|
||||
import { createPrefixedLogger } from '~/lib/utils';
|
||||
import type { ChannelId, ServerId, UserId } from "~/lib/api/types";
|
||||
import { createPrefixedLogger } from "~/lib/utils";
|
||||
import {
|
||||
type ClientMessage,
|
||||
ClientMessageType,
|
||||
@@ -8,11 +8,11 @@ import {
|
||||
type EventData,
|
||||
EventType,
|
||||
type ServerMessage,
|
||||
ServerMessageType
|
||||
} from './types';
|
||||
ServerMessageType,
|
||||
} from "./types";
|
||||
|
||||
export type GatewayEvents = {
|
||||
[K in EventType]: (data: Extract<EventData, { type: K }>['data']) => void;
|
||||
[K in EventType]: (data: Extract<EventData, { type: K }>["data"]) => void;
|
||||
};
|
||||
|
||||
export type ControlEvents = {
|
||||
@@ -48,21 +48,21 @@ export class GatewayClient {
|
||||
this.options = {
|
||||
reconnect: options.reconnect ?? true,
|
||||
reconnectDelay: options.reconnectDelay ?? 5000,
|
||||
maxReconnectAttempts: options.maxReconnectAttempts ?? 10
|
||||
maxReconnectAttempts: options.maxReconnectAttempts ?? 10,
|
||||
};
|
||||
}
|
||||
|
||||
// Public methods
|
||||
public connect(token: string): void {
|
||||
logger.log('Connecting to %s', this.url);
|
||||
logger.log("Connecting to %s", this.url);
|
||||
|
||||
if (this.connectionLock) {
|
||||
logger.warn('Connection already in progress');
|
||||
logger.warn("Connection already in progress");
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.token === token) {
|
||||
logger.warn('Token is the same as the current token');
|
||||
logger.warn("Token is the same as the current token");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ export class GatewayClient {
|
||||
}
|
||||
|
||||
public disconnect(): void {
|
||||
logger.log('Disconnecting');
|
||||
logger.log("Disconnecting");
|
||||
|
||||
this.closeInitiatedByClient = true;
|
||||
this.cleanupSocket();
|
||||
@@ -91,18 +91,21 @@ export class GatewayClient {
|
||||
public updateVoiceState(serverId: ServerId, channelId: ChannelId): void {
|
||||
this.sendMessage({
|
||||
type: ClientMessageType.VOICE_STATE_UPDATE,
|
||||
data: { serverId, channelId }
|
||||
data: { serverId, channelId },
|
||||
});
|
||||
}
|
||||
|
||||
public requestVoiceStates(serverId: ServerId): void {
|
||||
this.sendMessage({
|
||||
type: ClientMessageType.REQUEST_VOICE_STATES,
|
||||
data: { serverId }
|
||||
data: { serverId },
|
||||
});
|
||||
}
|
||||
|
||||
public onEvent<K extends keyof GatewayEvents>(event: K | string, handler: GatewayEvents[K]): void {
|
||||
public onEvent<K extends keyof GatewayEvents>(
|
||||
event: K | string,
|
||||
handler: GatewayEvents[K],
|
||||
): void {
|
||||
this.serverEventHandlers[event as K] = handler;
|
||||
}
|
||||
|
||||
@@ -110,7 +113,10 @@ export class GatewayClient {
|
||||
delete this.serverEventHandlers[event];
|
||||
}
|
||||
|
||||
public onControl<K extends keyof ControlEvents>(event: K, handler: ControlEvents[K]): void {
|
||||
public onControl<K extends keyof ControlEvents>(
|
||||
event: K,
|
||||
handler: ControlEvents[K],
|
||||
): void {
|
||||
this.eventHandlers[event] = handler;
|
||||
}
|
||||
|
||||
@@ -142,7 +148,7 @@ export class GatewayClient {
|
||||
this.socket.onerror = this.onSocketError.bind(this);
|
||||
this.socket.onclose = this.onSocketClose.bind(this);
|
||||
} catch (error) {
|
||||
this.emitError(new Error('Failed to create WebSocket connection'));
|
||||
this.emitError(new Error("Failed to create WebSocket connection"));
|
||||
this.setState(ConnectionState.ERROR);
|
||||
}
|
||||
}
|
||||
@@ -150,16 +156,16 @@ export class GatewayClient {
|
||||
private onSocketOpen(): void {
|
||||
this.connectionLock = false;
|
||||
|
||||
logger.log('Socket opened');
|
||||
logger.log("Socket opened");
|
||||
this.setState(ConnectionState.AUTHENTICATING);
|
||||
|
||||
if (this.token) {
|
||||
this.sendMessage({
|
||||
type: ClientMessageType.AUTHENTICATE,
|
||||
data: { token: this.token }
|
||||
data: { token: this.token },
|
||||
});
|
||||
} else {
|
||||
this.emitError(new Error('No authentication token provided'));
|
||||
this.emitError(new Error("No authentication token provided"));
|
||||
this.disconnect();
|
||||
}
|
||||
}
|
||||
@@ -169,19 +175,23 @@ export class GatewayClient {
|
||||
const message = JSON.parse(event.data) as ServerMessage;
|
||||
this.handleServerMessage(message);
|
||||
} catch (error) {
|
||||
this.emitError(new Error('Failed to parse WebSocket message', { cause: error }));
|
||||
this.emitError(
|
||||
new Error("Failed to parse WebSocket message", {
|
||||
cause: error,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private onSocketError(event: Event): void {
|
||||
this.connectionLock = false;
|
||||
logger.log('Socket error: %s', event);
|
||||
logger.log("Socket error: %s", event);
|
||||
|
||||
this.emitError(new Error('WebSocket error occurred'));
|
||||
this.emitError(new Error("WebSocket error occurred"));
|
||||
}
|
||||
|
||||
private onSocketClose(event: CloseEvent): void {
|
||||
logger.log('Socket closed: %s', event);
|
||||
logger.log("Socket closed: %s", event);
|
||||
|
||||
this.connectionLock = false;
|
||||
|
||||
@@ -190,7 +200,12 @@ export class GatewayClient {
|
||||
!this.closeInitiatedByClient &&
|
||||
this.reconnectAttempts < this.options.maxReconnectAttempts
|
||||
) {
|
||||
logger.log('Reconnecting in %d seconds (%d/%d)', this.options.reconnectDelay / 1000, this.reconnectAttempts + 1, this.options.maxReconnectAttempts);
|
||||
logger.log(
|
||||
"Reconnecting in %d seconds (%d/%d)",
|
||||
this.options.reconnectDelay / 1000,
|
||||
this.reconnectAttempts + 1,
|
||||
this.options.maxReconnectAttempts,
|
||||
);
|
||||
this.reconnectAttempts++;
|
||||
|
||||
this.reconnectTimeout = setTimeout(() => {
|
||||
@@ -204,23 +219,30 @@ export class GatewayClient {
|
||||
}
|
||||
|
||||
private handleServerMessage(message: ServerMessage): void {
|
||||
logger.log('Received message: ', message);
|
||||
logger.log("Received message: ", message);
|
||||
|
||||
switch (message.type) {
|
||||
case ServerMessageType.AUTHENTICATE_ACCEPTED:
|
||||
this.userId = message.data.userId;
|
||||
this.sessionKey = message.data.sessionKey;
|
||||
this.setState(ConnectionState.CONNECTED);
|
||||
this.emitControl('authenticated', message.data.userId, message.data.sessionKey);
|
||||
this.emitControl(
|
||||
"authenticated",
|
||||
message.data.userId,
|
||||
message.data.sessionKey,
|
||||
);
|
||||
break;
|
||||
|
||||
case ServerMessageType.AUTHENTICATE_DENIED:
|
||||
this.emitError(new Error('Authentication denied'));
|
||||
this.emitError(new Error("Authentication denied"));
|
||||
this.disconnect();
|
||||
break;
|
||||
|
||||
case ServerMessageType.ERROR:
|
||||
this.emitError(new Error(`Server error: ${message.data.code}`), message.data.code);
|
||||
this.emitError(
|
||||
new Error(`Server error: ${message.data.code}`),
|
||||
message.data.code,
|
||||
);
|
||||
break;
|
||||
|
||||
case ServerMessageType.EVENT:
|
||||
@@ -228,7 +250,7 @@ export class GatewayClient {
|
||||
break;
|
||||
|
||||
default:
|
||||
console.warn('Unhandled server message type:', message);
|
||||
console.warn("Unhandled server message type:", message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,39 +259,47 @@ export class GatewayClient {
|
||||
}
|
||||
|
||||
private sendMessage(message: ClientMessage): void {
|
||||
logger.log('Sending message: %o', message);
|
||||
logger.log("Sending message: %o", message);
|
||||
|
||||
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
|
||||
this.socket.send(JSON.stringify(message));
|
||||
} else {
|
||||
this.emitError(new Error('Cannot send message: socket not connected'));
|
||||
this.emitError(
|
||||
new Error("Cannot send message: socket not connected"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private setState(state: ConnectionState): void {
|
||||
if (this.state !== state) {
|
||||
logger.log('State changed to %s', state);
|
||||
logger.log("State changed to %s", state);
|
||||
|
||||
this.state = state;
|
||||
this.emitControl('stateChange', state);
|
||||
this.emitControl("stateChange", state);
|
||||
}
|
||||
}
|
||||
|
||||
private emitError(error: Error, code?: ErrorCode): void {
|
||||
logger.error('Error: %s', error, error.cause);
|
||||
logger.error("Error: %s", error, error.cause);
|
||||
|
||||
this.setState(ConnectionState.ERROR);
|
||||
this.emitControl('error', error, code);
|
||||
this.emitControl("error", error, code);
|
||||
}
|
||||
|
||||
private emitControl<K extends keyof ControlEvents>(event: K, ...args: Parameters<ControlEvents[K]>): void {
|
||||
private emitControl<K extends keyof ControlEvents>(
|
||||
event: K,
|
||||
...args: Parameters<ControlEvents[K]>
|
||||
): void {
|
||||
const handler = this.eventHandlers[event];
|
||||
if (handler) {
|
||||
(handler as Function)(...args);
|
||||
}
|
||||
}
|
||||
|
||||
private emitEvent<K extends keyof GatewayEvents>(event: K, ...args: Parameters<GatewayEvents[K]>): void {
|
||||
private emitEvent<K extends keyof GatewayEvents>(
|
||||
event: K,
|
||||
...args: Parameters<GatewayEvents[K]>
|
||||
): void {
|
||||
const handler = this.serverEventHandlers[event];
|
||||
if (handler) {
|
||||
(handler as Function)(...args);
|
||||
@@ -277,7 +307,7 @@ export class GatewayClient {
|
||||
}
|
||||
|
||||
private cleanupSocket(): void {
|
||||
logger.log('Cleaning up socket');
|
||||
logger.log("Cleaning up socket");
|
||||
|
||||
if (this.reconnectTimeout) {
|
||||
clearTimeout(this.reconnectTimeout);
|
||||
@@ -292,8 +322,10 @@ export class GatewayClient {
|
||||
this.socket.onclose = null;
|
||||
|
||||
// Close the connection if it's still open
|
||||
if (this.socket.readyState === WebSocket.OPEN ||
|
||||
this.socket.readyState === WebSocket.CONNECTING) {
|
||||
if (
|
||||
this.socket.readyState === WebSocket.OPEN ||
|
||||
this.socket.readyState === WebSocket.CONNECTING
|
||||
) {
|
||||
this.socket.close();
|
||||
}
|
||||
|
||||
@@ -305,4 +337,7 @@ export class GatewayClient {
|
||||
}
|
||||
}
|
||||
|
||||
const logger = createPrefixedLogger('%cGateway WS%c:', ['color: red; font-weight: bold;', '']);
|
||||
const logger = createPrefixedLogger("%cGateway WS%c:", [
|
||||
"color: red; font-weight: bold;",
|
||||
"",
|
||||
]);
|
||||
|
||||
@@ -1,50 +1,58 @@
|
||||
import type { ChannelId, Message, MessageId, PartialUser, Server, ServerId, UserId } from "~/lib/api/types";
|
||||
import type {
|
||||
ChannelId,
|
||||
Message,
|
||||
MessageId,
|
||||
PartialUser,
|
||||
Server,
|
||||
ServerId,
|
||||
UserId,
|
||||
} from "~/lib/api/types";
|
||||
|
||||
type Channel = any; // TODO: Define Channel type
|
||||
|
||||
export enum ServerMessageType {
|
||||
AUTHENTICATE_ACCEPTED = 'AUTHENTICATE_ACCEPTED',
|
||||
AUTHENTICATE_DENIED = 'AUTHENTICATE_DENIED',
|
||||
EVENT = 'EVENT',
|
||||
ERROR = 'ERROR'
|
||||
AUTHENTICATE_ACCEPTED = "AUTHENTICATE_ACCEPTED",
|
||||
AUTHENTICATE_DENIED = "AUTHENTICATE_DENIED",
|
||||
EVENT = "EVENT",
|
||||
ERROR = "ERROR",
|
||||
}
|
||||
|
||||
export enum ClientMessageType {
|
||||
AUTHENTICATE = 'AUTHENTICATE',
|
||||
VOICE_STATE_UPDATE = 'VOICE_STATE_UPDATE',
|
||||
REQUEST_VOICE_STATES = 'REQUEST_VOICE_STATES',
|
||||
AUTHENTICATE = "AUTHENTICATE",
|
||||
VOICE_STATE_UPDATE = "VOICE_STATE_UPDATE",
|
||||
REQUEST_VOICE_STATES = "REQUEST_VOICE_STATES",
|
||||
}
|
||||
|
||||
// Error codes from the server
|
||||
export enum ErrorCode {
|
||||
AUTHENTICATION_FAILED = 'AUTHENTICATION_FAILED',
|
||||
TOKEN_GENERATION_FAILED = 'TOKEN_GENERATION_FAILED'
|
||||
AUTHENTICATION_FAILED = "AUTHENTICATION_FAILED",
|
||||
TOKEN_GENERATION_FAILED = "TOKEN_GENERATION_FAILED",
|
||||
}
|
||||
|
||||
// Event types from the server
|
||||
export enum EventType {
|
||||
ADD_SERVER = 'ADD_SERVER',
|
||||
REMOVE_SERVER = 'REMOVE_SERVER',
|
||||
ADD_SERVER = "ADD_SERVER",
|
||||
REMOVE_SERVER = "REMOVE_SERVER",
|
||||
|
||||
ADD_DM_CHANNEL = 'ADD_DM_CHANNEL',
|
||||
REMOVE_DM_CHANNEL = 'REMOVE_DM_CHANNEL',
|
||||
ADD_DM_CHANNEL = "ADD_DM_CHANNEL",
|
||||
REMOVE_DM_CHANNEL = "REMOVE_DM_CHANNEL",
|
||||
|
||||
ADD_SERVER_CHANNEL = 'ADD_SERVER_CHANNEL',
|
||||
REMOVE_SERVER_CHANNEL = 'REMOVE_SERVER_CHANNEL',
|
||||
ADD_SERVER_CHANNEL = "ADD_SERVER_CHANNEL",
|
||||
REMOVE_SERVER_CHANNEL = "REMOVE_SERVER_CHANNEL",
|
||||
|
||||
ADD_USER = 'ADD_USER',
|
||||
REMOVE_USER = 'REMOVE_USER',
|
||||
ADD_USER = "ADD_USER",
|
||||
REMOVE_USER = "REMOVE_USER",
|
||||
|
||||
ADD_SERVER_MEMBER = 'ADD_SERVER_MEMBER',
|
||||
REMOVE_SERVER_MEMBER = 'REMOVE_SERVER_MEMBER',
|
||||
ADD_SERVER_MEMBER = "ADD_SERVER_MEMBER",
|
||||
REMOVE_SERVER_MEMBER = "REMOVE_SERVER_MEMBER",
|
||||
|
||||
ADD_MESSAGE = 'ADD_MESSAGE',
|
||||
REMOVE_MESSAGE = 'REMOVE_MESSAGE',
|
||||
ADD_MESSAGE = "ADD_MESSAGE",
|
||||
REMOVE_MESSAGE = "REMOVE_MESSAGE",
|
||||
|
||||
VOICE_CHANNEL_CONNECTED = 'VOICE_CHANNEL_CONNECTED',
|
||||
VOICE_CHANNEL_DISCONNECTED = 'VOICE_CHANNEL_DISCONNECTED',
|
||||
VOICE_CHANNEL_CONNECTED = "VOICE_CHANNEL_CONNECTED",
|
||||
VOICE_CHANNEL_DISCONNECTED = "VOICE_CHANNEL_DISCONNECTED",
|
||||
|
||||
VOICE_SERVER_UPDATE = 'VOICE_SERVER_UPDATE'
|
||||
VOICE_SERVER_UPDATE = "VOICE_SERVER_UPDATE",
|
||||
}
|
||||
|
||||
// Client message types
|
||||
@@ -70,7 +78,10 @@ export interface RequestVoiceStatesMessage {
|
||||
};
|
||||
}
|
||||
|
||||
export type ClientMessage = AuthenticateMessage | VoiceStateUpdateMessage | RequestVoiceStatesMessage;
|
||||
export type ClientMessage =
|
||||
| AuthenticateMessage
|
||||
| VoiceStateUpdateMessage
|
||||
| RequestVoiceStatesMessage;
|
||||
|
||||
// Server message types
|
||||
export interface AuthenticateAcceptedMessage {
|
||||
@@ -111,6 +122,7 @@ export interface AddDmChannelEvent {
|
||||
type: EventType.ADD_DM_CHANNEL;
|
||||
data: {
|
||||
channel: Channel;
|
||||
recipients: PartialUser[];
|
||||
};
|
||||
}
|
||||
|
||||
@@ -241,9 +253,9 @@ export type ServerMessage =
|
||||
|
||||
// Connection states
|
||||
export enum ConnectionState {
|
||||
DISCONNECTED = 'DISCONNECTED',
|
||||
CONNECTING = 'CONNECTING',
|
||||
AUTHENTICATING = 'AUTHENTICATING',
|
||||
CONNECTED = 'CONNECTED',
|
||||
ERROR = 'ERROR'
|
||||
}
|
||||
DISCONNECTED = "DISCONNECTED",
|
||||
CONNECTING = "CONNECTING",
|
||||
AUTHENTICATING = "AUTHENTICATING",
|
||||
CONNECTED = "CONNECTED",
|
||||
ERROR = "ERROR",
|
||||
}
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { createPrefixedLogger } from "~/lib/utils";
|
||||
import { ClientMessageType, ConnectionState, ServerMessageType, type ClientMessage, type ServerMessage } from "./types";
|
||||
import {
|
||||
ClientMessageType,
|
||||
ConnectionState,
|
||||
ServerMessageType,
|
||||
type ClientMessage,
|
||||
type ServerMessage,
|
||||
} from "./types";
|
||||
|
||||
export class WebRTCClient {
|
||||
private socket: WebSocket | null = null;
|
||||
@@ -20,7 +26,7 @@ export class WebRTCClient {
|
||||
url: string,
|
||||
onStateChange: (state: ConnectionState) => void,
|
||||
onError: (error: Error) => void,
|
||||
onRemoteStream: (stream: MediaStream) => void
|
||||
onRemoteStream: (stream: MediaStream) => void,
|
||||
) {
|
||||
this.url = url;
|
||||
this.onStateChange = onStateChange;
|
||||
@@ -30,26 +36,29 @@ export class WebRTCClient {
|
||||
|
||||
public connect = async (token: string) => {
|
||||
if (this.connectionLock) {
|
||||
warn('WebRTC: Connection already in progress');
|
||||
warn("WebRTC: Connection already in progress");
|
||||
return;
|
||||
}
|
||||
|
||||
this.connectionLock = true;
|
||||
|
||||
if (this.state !== ConnectionState.DISCONNECTED && this.state !== ConnectionState.ERROR) {
|
||||
if (
|
||||
this.state !== ConnectionState.DISCONNECTED &&
|
||||
this.state !== ConnectionState.ERROR
|
||||
) {
|
||||
this.disconnect();
|
||||
}
|
||||
|
||||
if (this.disconnectPromise) {
|
||||
warn('WebRTC: Waiting for previous disconnect to complete');
|
||||
warn("WebRTC: Waiting for previous disconnect to complete");
|
||||
try {
|
||||
await this.disconnectPromise;
|
||||
} catch (error) {
|
||||
console.error('WebRTC: Previous disconnect failed:', error);
|
||||
console.error("WebRTC: Previous disconnect failed:", error);
|
||||
}
|
||||
}
|
||||
|
||||
log('Connecting to %s', this.url);
|
||||
log("Connecting to %s", this.url);
|
||||
|
||||
try {
|
||||
this.setState(ConnectionState.CONNECTING);
|
||||
@@ -57,25 +66,25 @@ export class WebRTCClient {
|
||||
this.socket = new WebSocket(this.url);
|
||||
|
||||
this.socket.onopen = () => {
|
||||
log('Socket opened');
|
||||
log("Socket opened");
|
||||
|
||||
this.connectionLock = false;
|
||||
|
||||
this.setState(ConnectionState.AUTHENTICATING);
|
||||
this.sendMessage({
|
||||
type: ClientMessageType.AUTHENTICATE,
|
||||
data: { token }
|
||||
data: { token },
|
||||
});
|
||||
};
|
||||
|
||||
this.socket.onmessage = this.handleServerMessage;
|
||||
|
||||
this.socket.onerror = (event) => {
|
||||
this.handleError(new Error('WebSocket error occurred'));
|
||||
this.handleError(new Error("WebSocket error occurred"));
|
||||
};
|
||||
|
||||
this.socket.onclose = (e) => {
|
||||
log('Socket closed', e);
|
||||
log("Socket closed", e);
|
||||
this.cleanupResources();
|
||||
if (this.state !== ConnectionState.ERROR) {
|
||||
this.setState(ConnectionState.DISCONNECTED);
|
||||
@@ -88,7 +97,9 @@ export class WebRTCClient {
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
this.handleError(error instanceof Error ? error : new Error('Unknown error'));
|
||||
this.handleError(
|
||||
error instanceof Error ? error : new Error("Unknown error"),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -112,16 +123,16 @@ export class WebRTCClient {
|
||||
});
|
||||
|
||||
const onSocketClose = () => {
|
||||
this.socket?.removeEventListener('close', onSocketClose);
|
||||
this.socket?.removeEventListener("close", onSocketClose);
|
||||
this.disconnectResolve?.();
|
||||
this.disconnectResolve = null;
|
||||
this.disconnectPromise = null;
|
||||
};
|
||||
|
||||
this.socket.addEventListener('close', onSocketClose);
|
||||
this.socket.addEventListener("close", onSocketClose);
|
||||
|
||||
if (this.socket.readyState !== WebSocket.CLOSING) {
|
||||
this.socket.close(1000, 'WebRTC: Cleaning up resources');
|
||||
this.socket.close(1000, "WebRTC: Cleaning up resources");
|
||||
}
|
||||
} else {
|
||||
this.cleanupResources();
|
||||
@@ -131,21 +142,21 @@ export class WebRTCClient {
|
||||
|
||||
public createOffer = async (localStream?: MediaStream): Promise<void> => {
|
||||
if (this.state !== ConnectionState.CONNECTED) {
|
||||
this.handleError(new Error('Cannot create offer: not connected'));
|
||||
this.handleError(new Error("Cannot create offer: not connected"));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Create RTCPeerConnection with standard configuration
|
||||
const configuration: RTCConfiguration = {
|
||||
iceServers: []
|
||||
iceServers: [],
|
||||
};
|
||||
|
||||
this.peerConnection = new RTCPeerConnection(configuration);
|
||||
|
||||
// Add local stream tracks if provided
|
||||
if (localStream) {
|
||||
localStream.getTracks().forEach(track => {
|
||||
localStream.getTracks().forEach((track) => {
|
||||
this.peerConnection!.addTrack(track, localStream);
|
||||
});
|
||||
}
|
||||
@@ -174,20 +185,26 @@ export class WebRTCClient {
|
||||
this.sendMessage({
|
||||
type: ClientMessageType.SDP_OFFER,
|
||||
data: {
|
||||
sdp: this.peerConnection.localDescription
|
||||
}
|
||||
sdp: this.peerConnection.localDescription,
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
this.handleError(error instanceof Error ? error : new Error('Error creating WebRTC offer'));
|
||||
this.handleError(
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error("Error creating WebRTC offer"),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
private handleServerMessage = async (event: MessageEvent): Promise<void> => {
|
||||
private handleServerMessage = async (
|
||||
event: MessageEvent,
|
||||
): Promise<void> => {
|
||||
try {
|
||||
const message: ServerMessage = JSON.parse(event.data);
|
||||
|
||||
log('Received message: %o', message);
|
||||
log("Received message: %o", message);
|
||||
|
||||
switch (message.type) {
|
||||
case ServerMessageType.AUTHENTICATE_ACCEPTED:
|
||||
@@ -195,7 +212,7 @@ export class WebRTCClient {
|
||||
break;
|
||||
|
||||
case ServerMessageType.AUTHENTICATE_DENIED:
|
||||
this.handleError(new Error('Authentication failed'));
|
||||
this.handleError(new Error("Authentication failed"));
|
||||
break;
|
||||
|
||||
case ServerMessageType.SDP_ANSWER:
|
||||
@@ -203,54 +220,66 @@ export class WebRTCClient {
|
||||
break;
|
||||
|
||||
default:
|
||||
warn('Unhandled message type:', message);
|
||||
warn("Unhandled message type:", message);
|
||||
}
|
||||
} catch (error) {
|
||||
this.handleError(error instanceof Error ? error : new Error('Failed to process message'));
|
||||
this.handleError(
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error("Failed to process message"),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
private handleSdpAnswer = async (sdp: RTCSessionDescription): Promise<void> => {
|
||||
log('Received SDP answer: %o', sdp);
|
||||
private handleSdpAnswer = async (
|
||||
sdp: RTCSessionDescription,
|
||||
): Promise<void> => {
|
||||
log("Received SDP answer: %o", sdp);
|
||||
|
||||
if (!this.peerConnection) {
|
||||
this.handleError(new Error('No peer connection established'));
|
||||
this.handleError(new Error("No peer connection established"));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.peerConnection.setRemoteDescription(sdp);
|
||||
} catch (error) {
|
||||
this.handleError(error instanceof Error ? error : new Error('Error setting remote description'));
|
||||
this.handleError(
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error("Error setting remote description"),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
private sendMessage = (message: ClientMessage): void => {
|
||||
log('Sending message: %o', message);
|
||||
log("Sending message: %o", message);
|
||||
|
||||
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
|
||||
this.socket.send(JSON.stringify(message));
|
||||
} else {
|
||||
this.handleError(new Error('Cannot send message: socket not connected'));
|
||||
this.handleError(
|
||||
new Error("Cannot send message: socket not connected"),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
private setState = (state: ConnectionState): void => {
|
||||
log('State changed to %s', state);
|
||||
log("State changed to %s", state);
|
||||
|
||||
this.state = state;
|
||||
this.onStateChange(state);
|
||||
};
|
||||
|
||||
private handleError = (error: Error): void => {
|
||||
log('Error: %s', error.message);
|
||||
log("Error: %s", error.message);
|
||||
|
||||
this.setState(ConnectionState.ERROR);
|
||||
this.onError(error);
|
||||
};
|
||||
|
||||
private cleanupResources = (): void => {
|
||||
log('Cleaning up resources');
|
||||
log("Cleaning up resources");
|
||||
|
||||
if (this.peerConnection) {
|
||||
this.peerConnection.close();
|
||||
@@ -258,14 +287,13 @@ export class WebRTCClient {
|
||||
}
|
||||
|
||||
if (this.socket) {
|
||||
this.socket.close(1000, 'WebRTC: Cleaning up resources');
|
||||
this.socket.close(1000, "WebRTC: Cleaning up resources");
|
||||
this.socket = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const {
|
||||
log,
|
||||
warn,
|
||||
...other
|
||||
} = createPrefixedLogger('%cWebRTC WS%c:', ['color: blue; font-weight: bold;', '']);
|
||||
const { log, warn, ...other } = createPrefixedLogger("%cWebRTC WS%c:", [
|
||||
"color: blue; font-weight: bold;",
|
||||
"",
|
||||
]);
|
||||
|
||||
@@ -1,36 +1,38 @@
|
||||
export enum ConnectionState {
|
||||
DISCONNECTED = 'DISCONNECTED',
|
||||
DISCONNECTING = 'DISCONNECTING',
|
||||
CONNECTING = 'CONNECTING',
|
||||
AUTHENTICATING = 'AUTHENTICATING',
|
||||
CONNECTED = 'CONNECTED',
|
||||
ERROR = 'ERROR',
|
||||
DISCONNECTED = "DISCONNECTED",
|
||||
DISCONNECTING = "DISCONNECTING",
|
||||
CONNECTING = "CONNECTING",
|
||||
AUTHENTICATING = "AUTHENTICATING",
|
||||
CONNECTED = "CONNECTED",
|
||||
ERROR = "ERROR",
|
||||
}
|
||||
|
||||
export enum ServerMessageType {
|
||||
AUTHENTICATE_ACCEPTED = 'AUTHENTICATE_ACCEPTED',
|
||||
AUTHENTICATE_DENIED = 'AUTHENTICATE_DENIED',
|
||||
SDP_ANSWER = 'SDP_ANSWER',
|
||||
AUTHENTICATE_ACCEPTED = "AUTHENTICATE_ACCEPTED",
|
||||
AUTHENTICATE_DENIED = "AUTHENTICATE_DENIED",
|
||||
SDP_ANSWER = "SDP_ANSWER",
|
||||
}
|
||||
|
||||
export type ServerMessage =
|
||||
| { type: ServerMessageType.AUTHENTICATE_ACCEPTED }
|
||||
| { type: ServerMessageType.AUTHENTICATE_DENIED }
|
||||
| {
|
||||
type: ServerMessageType.SDP_ANSWER; data: {
|
||||
sdp: RTCSessionDescription
|
||||
}
|
||||
}
|
||||
type: ServerMessageType.SDP_ANSWER;
|
||||
data: {
|
||||
sdp: RTCSessionDescription;
|
||||
};
|
||||
};
|
||||
|
||||
export enum ClientMessageType {
|
||||
AUTHENTICATE = 'AUTHENTICATE',
|
||||
SDP_OFFER = 'SDP_OFFER',
|
||||
AUTHENTICATE = "AUTHENTICATE",
|
||||
SDP_OFFER = "SDP_OFFER",
|
||||
}
|
||||
|
||||
export type ClientMessage =
|
||||
| { type: ClientMessageType.AUTHENTICATE; data: { token: string } }
|
||||
| {
|
||||
type: ClientMessageType.SDP_OFFER; data: {
|
||||
sdp: RTCSessionDescription
|
||||
}
|
||||
};
|
||||
type: ClientMessageType.SDP_OFFER;
|
||||
data: {
|
||||
sdp: RTCSessionDescription;
|
||||
};
|
||||
};
|
||||
|
||||
123
app/root.tsx
123
app/root.tsx
@@ -1,10 +1,10 @@
|
||||
import {
|
||||
isRouteErrorResponse,
|
||||
Links,
|
||||
Meta,
|
||||
Outlet,
|
||||
Scripts,
|
||||
ScrollRestoration,
|
||||
isRouteErrorResponse,
|
||||
Links,
|
||||
Meta,
|
||||
Outlet,
|
||||
Scripts,
|
||||
ScrollRestoration,
|
||||
} from "react-router";
|
||||
|
||||
import { ThemeProvider } from "~/components/theme/theme-provider";
|
||||
@@ -13,69 +13,72 @@ import type { Route } from "./+types/root";
|
||||
import "./app.css";
|
||||
|
||||
export const links: Route.LinksFunction = () => [
|
||||
{ rel: "preconnect", href: "https://fonts.googleapis.com" },
|
||||
{
|
||||
rel: "preconnect",
|
||||
href: "https://fonts.gstatic.com",
|
||||
crossOrigin: "anonymous",
|
||||
},
|
||||
{
|
||||
rel: "stylesheet",
|
||||
href: "https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap",
|
||||
},
|
||||
{ rel: "preconnect", href: "https://fonts.googleapis.com" },
|
||||
{
|
||||
rel: "preconnect",
|
||||
href: "https://fonts.gstatic.com",
|
||||
crossOrigin: "anonymous",
|
||||
},
|
||||
{
|
||||
rel: "stylesheet",
|
||||
href: "https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap",
|
||||
},
|
||||
];
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<ThemeProvider defaultTheme="system" storageKey="ui-theme">
|
||||
<Outlet />
|
||||
</ThemeProvider>
|
||||
);
|
||||
return (
|
||||
<ThemeProvider defaultTheme="system" storageKey="ui-theme">
|
||||
<Outlet />
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export function Layout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charSet="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<Meta />
|
||||
<Links />
|
||||
</head>
|
||||
<body>
|
||||
{children}
|
||||
<ScrollRestoration />
|
||||
<Scripts />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charSet="utf-8" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1"
|
||||
/>
|
||||
<Meta />
|
||||
<Links />
|
||||
</head>
|
||||
<body>
|
||||
{children}
|
||||
<ScrollRestoration />
|
||||
<Scripts />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
|
||||
let message = "Oops!";
|
||||
let details = "An unexpected error occurred.";
|
||||
let stack: string | undefined;
|
||||
let message = "Oops!";
|
||||
let details = "An unexpected error occurred.";
|
||||
let stack: string | undefined;
|
||||
|
||||
if (isRouteErrorResponse(error)) {
|
||||
message = error.status === 404 ? "404" : "Error";
|
||||
details =
|
||||
error.status === 404
|
||||
? "The requested page could not be found."
|
||||
: error.statusText || details;
|
||||
} else if (import.meta.env.DEV && error && error instanceof Error) {
|
||||
details = error.message;
|
||||
stack = error.stack;
|
||||
}
|
||||
if (isRouteErrorResponse(error)) {
|
||||
message = error.status === 404 ? "404" : "Error";
|
||||
details =
|
||||
error.status === 404
|
||||
? "The requested page could not be found."
|
||||
: error.statusText || details;
|
||||
} else if (import.meta.env.DEV && error && error instanceof Error) {
|
||||
details = error.message;
|
||||
stack = error.stack;
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="pt-16 p-4 container mx-auto">
|
||||
<h1>{message}</h1>
|
||||
<p>{details}</p>
|
||||
{stack && (
|
||||
<pre className="w-full p-4 overflow-x-auto">
|
||||
<code>{stack}</code>
|
||||
</pre>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
return (
|
||||
<main className="pt-16 p-4 container mx-auto">
|
||||
<h1>{message}</h1>
|
||||
<p>{details}</p>
|
||||
{stack && (
|
||||
<pre className="w-full p-4 overflow-x-auto">
|
||||
<code>{stack}</code>
|
||||
</pre>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { type RouteConfig, index, layout, prefix, route } from "@react-router/dev/routes";
|
||||
import {
|
||||
type RouteConfig,
|
||||
index,
|
||||
layout,
|
||||
prefix,
|
||||
route,
|
||||
} from "@react-router/dev/routes";
|
||||
|
||||
export default [
|
||||
index("routes/index.tsx"),
|
||||
@@ -15,15 +21,19 @@ export default [
|
||||
...prefix("/@me", [
|
||||
layout("routes/app/me/layout.tsx", [
|
||||
index("routes/app/me/index.tsx"),
|
||||
route("/channels/:channelId", "routes/app/me/channel.tsx"),
|
||||
])
|
||||
route(
|
||||
"/channels/:channelId",
|
||||
"routes/app/me/channel.tsx",
|
||||
),
|
||||
]),
|
||||
]),
|
||||
...prefix("/server/:serverId", [
|
||||
layout("routes/app/server/layout.tsx", [
|
||||
index("routes/app/server/index.tsx"),
|
||||
route("/:channelId", "routes/app/server/channel.tsx"),
|
||||
])
|
||||
])
|
||||
])]),
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
] satisfies RouteConfig;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { redirect } from "react-router";
|
||||
|
||||
export function clientLoader() {
|
||||
return redirect("/app/@me")
|
||||
return redirect("/app/@me");
|
||||
}
|
||||
|
||||
export default function Index() {
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { redirect } from "react-router";
|
||||
import type { Route } from "./+types/invite";
|
||||
|
||||
export async function clientLoader(
|
||||
{ params }: Route.ClientLoaderArgs
|
||||
) {
|
||||
const inviteCode = params.inviteCode
|
||||
export async function clientLoader({ params }: Route.ClientLoaderArgs) {
|
||||
const inviteCode = params.inviteCode;
|
||||
|
||||
try {
|
||||
const response = await import("~/lib/api/client/server").then(m => m.default.getInvite(inviteCode))
|
||||
const response = await import("~/lib/api/client/server").then((m) =>
|
||||
m.default.getInvite(inviteCode),
|
||||
);
|
||||
|
||||
return redirect(`/app/server/${response.id}`)
|
||||
return redirect(`/app/server/${response.id}`);
|
||||
} catch (error) {
|
||||
return redirect("/app/@me")
|
||||
return redirect("/app/@me");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,26 +1,46 @@
|
||||
import { Outlet, redirect } from "react-router";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Outlet } from "react-router";
|
||||
import AppLayout from "~/components/app-layout";
|
||||
import { useServerListStore } from "~/stores/server-list-store";
|
||||
import { useUsersStore } from "~/stores/users-store";
|
||||
|
||||
export async function clientLoader() {
|
||||
const { servers, addServers } = useServerListStore.getState()
|
||||
async function fetchServers() {
|
||||
const { addServers } = useServerListStore.getState();
|
||||
|
||||
try {
|
||||
if (!servers || Object.values(servers).length === 0) {
|
||||
const newServers = await import("~/lib/api/client/server").then(m => m.default.list())
|
||||
addServers(newServers)
|
||||
}
|
||||
const newServers = await import("~/lib/api/client/server").then((m) =>
|
||||
m.default.list(),
|
||||
);
|
||||
addServers(newServers);
|
||||
|
||||
} catch (error) {
|
||||
return redirect("/login")
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function fetchCurrentUser() {
|
||||
const { setCurrentUserId, addUser } = useUsersStore.getState();
|
||||
|
||||
const user = await import("~/lib/api/client/user").then((m) =>
|
||||
m.default.me(),
|
||||
);
|
||||
setCurrentUserId(user.id);
|
||||
addUser(user);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function Layout() {
|
||||
useQuery({
|
||||
queryKey: ["servers"],
|
||||
queryFn: fetchServers,
|
||||
});
|
||||
|
||||
useQuery({
|
||||
queryKey: ["users", "@me"],
|
||||
queryFn: fetchCurrentUser,
|
||||
});
|
||||
|
||||
return (
|
||||
<AppLayout >
|
||||
<AppLayout>
|
||||
<Outlet />
|
||||
</AppLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,32 +6,52 @@ import { Badge } from "~/components/ui/badge";
|
||||
import { usePrivateChannelsStore } from "~/stores/private-channels-store";
|
||||
import { useUsersStore } from "~/stores/users-store";
|
||||
|
||||
export default function Channel({
|
||||
params
|
||||
}: Route.ComponentProps) {
|
||||
const channelId = params.channelId
|
||||
const currentUserId = useUsersStore(state => state.currentUserId)
|
||||
export default function Channel({ params }: Route.ComponentProps) {
|
||||
const channelId = params.channelId;
|
||||
const currentUserId = useUsersStore((state) => state.currentUserId);
|
||||
|
||||
const nativeChannel = usePrivateChannelsStore(useShallow(state => state.channels[channelId]))
|
||||
const recipients = nativeChannel.recipients.filter(recipient => recipient.id !== currentUserId)
|
||||
const nativeChannel = usePrivateChannelsStore(
|
||||
useShallow((state) => state.channels[channelId]),
|
||||
);
|
||||
|
||||
const renderSystemBadge = recipients.some(recipient => recipient.system) && recipients.length === 1
|
||||
if (!nativeChannel) return null;
|
||||
|
||||
const recipients = nativeChannel.recipients.filter(
|
||||
(recipient) => recipient.id !== currentUserId,
|
||||
);
|
||||
|
||||
const renderSystemBadge =
|
||||
recipients.some((recipient) => recipient.system) &&
|
||||
recipients.length === 1;
|
||||
|
||||
const channel = {
|
||||
...nativeChannel,
|
||||
name: <>
|
||||
<div className="flex items-center gap-2">
|
||||
<div>
|
||||
{recipients.map(recipient => recipient.displayName || recipient.username).join(", ")}
|
||||
name: (
|
||||
<>
|
||||
<div className="flex items-center gap-2">
|
||||
<div>
|
||||
{recipients
|
||||
.map(
|
||||
(recipient) =>
|
||||
recipient.displayName || recipient.username,
|
||||
)
|
||||
.join(", ")}
|
||||
</div>
|
||||
{renderSystemBadge && (
|
||||
<Badge variant="default">
|
||||
{" "}
|
||||
<Check />
|
||||
System
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{renderSystemBadge && <Badge variant="default"> <Check />System</Badge>}
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
</>
|
||||
),
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ChannelArea channel={channel} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
export default function Index() {
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import React from "react";
|
||||
import { Outlet } from "react-router";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
@@ -5,19 +6,33 @@ import PrivateChannelListItem from "~/components/custom-ui/private-channel-list-
|
||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
||||
import { usePrivateChannelsStore } from "~/stores/private-channels-store";
|
||||
|
||||
export async function clientLoader() {
|
||||
const { channels, addChannels: setChannels } = usePrivateChannelsStore.getState()
|
||||
async function fetchPrivateChannels() {
|
||||
const { addChannels } = usePrivateChannelsStore.getState();
|
||||
|
||||
const channelList = Object.values(channels)
|
||||
const channels = await import("~/lib/api/client/user").then((m) =>
|
||||
m.default.channels(),
|
||||
);
|
||||
addChannels(channels);
|
||||
|
||||
if (!channels || channelList.length === 0) {
|
||||
const channels = await import("~/lib/api/client/user").then(m => m.default.channels())
|
||||
setChannels(channels)
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function ListComponent() {
|
||||
const channels = usePrivateChannelsStore(useShallow(state => Object.values(state.channels)))
|
||||
const channels = Object.values(
|
||||
usePrivateChannelsStore(useShallow((state) => state.channels)),
|
||||
);
|
||||
const sortedChannels = React.useMemo(
|
||||
() =>
|
||||
channels.sort((a, b) =>
|
||||
(a.lastMessageId ?? a.id) < (b.lastMessageId ?? b.id) ? 1 : -1,
|
||||
),
|
||||
[channels],
|
||||
);
|
||||
|
||||
useQuery({
|
||||
queryKey: ["channels", "@me"],
|
||||
queryFn: fetchPrivateChannels,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
@@ -29,7 +44,7 @@ function ListComponent() {
|
||||
|
||||
<ScrollArea className="overflow-auto" scrollbarSize="narrow">
|
||||
<div className="p-2 flex flex-col gap-1 h-full">
|
||||
{channels.sort((a, b) => (a.lastMessageId ?? a.id) < (b.lastMessageId ?? b.id) ? 1 : -1).map((channel, _) => (
|
||||
{sortedChannels.map((channel) => (
|
||||
<React.Fragment key={channel.id}>
|
||||
<PrivateChannelListItem channel={channel} />
|
||||
</React.Fragment>
|
||||
@@ -37,12 +52,12 @@ function ListComponent() {
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export const handle = {
|
||||
listComponent: <ListComponent />
|
||||
}
|
||||
listComponent: <ListComponent />,
|
||||
};
|
||||
|
||||
export default function Layout() {
|
||||
return (
|
||||
|
||||
@@ -1,30 +1,22 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { Outlet, redirect } from "react-router";
|
||||
import { create } from "zustand";
|
||||
import { Outlet } from "react-router";
|
||||
import { GatewayWebSocketConnectionManager } from "~/components/manager/gateway-websocket-connection-manager";
|
||||
import { WebRTCConnectionManager } from "~/components/manager/webrtc-connection-manager";
|
||||
import ModalProvider from "~/components/providers/modal-provider";
|
||||
import { useUsersStore } from "~/stores/users-store";
|
||||
|
||||
export async function clientLoader() {
|
||||
const { currentUserId, setCurrentUserId, addUser } = useUsersStore.getState()
|
||||
|
||||
try {
|
||||
if (!currentUserId) {
|
||||
const user = await import("~/lib/api/client/user").then(m => m.default.me())
|
||||
setCurrentUserId(user.id)
|
||||
addUser(user)
|
||||
}
|
||||
} catch (error) {
|
||||
return redirect("/login")
|
||||
}
|
||||
}
|
||||
|
||||
const useQueryClient = create(() => new QueryClient());
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: Infinity,
|
||||
refetchInterval: Infinity,
|
||||
refetchOnReconnect: false,
|
||||
refetchOnMount: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export default function Layout() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<>
|
||||
@@ -35,4 +27,4 @@ export default function Layout() {
|
||||
</>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
import { useNavigate } from "react-router";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import ChannelArea from "~/components/channel-area";
|
||||
import { useServerChannelsStore } from "~/stores/server-channels-store";
|
||||
import type { Route } from "./+types/channel";
|
||||
|
||||
export default function Channel(
|
||||
{ params: { serverId, channelId } }: Route.ComponentProps
|
||||
) {
|
||||
const channel = useServerChannelsStore(useShallow(state => state.channels[serverId][channelId]))
|
||||
export default function Channel({
|
||||
params: { serverId, channelId },
|
||||
}: Route.ComponentProps) {
|
||||
const navigate = useNavigate();
|
||||
const channel = useServerChannelsStore(
|
||||
useShallow((state) => state.channels[serverId][channelId]),
|
||||
);
|
||||
|
||||
if (!channel) {
|
||||
setTimeout(() => navigate(`/app/server/${serverId}`), 0);
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<ChannelArea channel={channel} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
export default function Index() {
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import React from "react";
|
||||
import { Outlet, redirect, useNavigate, useParams, type ShouldRevalidateFunctionArgs } from "react-router";
|
||||
import { Outlet, useNavigate, useParams } from "react-router";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import ServerChannelListItem from "~/components/custom-ui/channel-list-item";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "~/components/ui/dropdown-menu";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu";
|
||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
||||
import { listChannels } from "~/lib/api/client/server";
|
||||
import type { ServerId } from "~/lib/api/types";
|
||||
import { useGatewayStore } from "~/stores/gateway-store";
|
||||
import { ModalType, useModalStore } from "~/stores/modal-store";
|
||||
@@ -12,45 +20,42 @@ import { useServerListStore } from "~/stores/server-list-store";
|
||||
import { useUsersStore } from "~/stores/users-store";
|
||||
import type { Route } from "../server/+types/layout";
|
||||
|
||||
export async function clientLoader({
|
||||
params: { serverId }
|
||||
}: Route.ClientLoaderArgs) {
|
||||
const { channels, addChannels, addServer } = useServerChannelsStore.getState()
|
||||
async function fetchServerChannels(serverId: ServerId) {
|
||||
const { addChannels } = useServerChannelsStore.getState();
|
||||
|
||||
const server = useServerListStore.getState().servers[serverId as ServerId] || undefined
|
||||
const channels = await listChannels(serverId);
|
||||
addChannels(channels);
|
||||
|
||||
if (!server) {
|
||||
return redirect("/app/@me")
|
||||
}
|
||||
useGatewayStore.getState().requestVoiceStates(serverId as ServerId);
|
||||
|
||||
const channelList = channels[serverId as ServerId]
|
||||
|
||||
if (channelList === undefined) {
|
||||
const channels = await import("~/lib/api/client/server").then(m => m.default.listChannels(serverId as ServerId))
|
||||
addServer(serverId as ServerId)
|
||||
addChannels(channels)
|
||||
|
||||
useGatewayStore.getState().requestVoiceStates(serverId as ServerId)
|
||||
}
|
||||
}
|
||||
|
||||
export function shouldRevalidate(
|
||||
arg: ShouldRevalidateFunctionArgs
|
||||
) {
|
||||
return true
|
||||
return null;
|
||||
}
|
||||
|
||||
function ListComponent() {
|
||||
const serverId = useParams<{ serverId: ServerId }>().serverId!
|
||||
const currentUserId = useUsersStore(state => state.currentUserId)
|
||||
const onOpen = useModalStore(state => state.onOpen)
|
||||
const serverId = useParams<{ serverId: ServerId }>().serverId!;
|
||||
|
||||
const server = useServerListStore(useShallow(state => state.servers[serverId] || null))
|
||||
useQuery({
|
||||
queryKey: ["channels", serverId],
|
||||
queryFn: async () => fetchServerChannels(serverId),
|
||||
});
|
||||
|
||||
const channels = Array.from(useServerChannelsStore(useShallow(state => Object.values(state.channels[serverId] || {}))))
|
||||
const currentUserId = useUsersStore((state) => state.currentUserId);
|
||||
const onOpen = useModalStore((state) => state.onOpen);
|
||||
|
||||
const server = useServerListStore(
|
||||
useShallow((state) => state.servers[serverId] || null),
|
||||
);
|
||||
|
||||
const channels = Array.from(
|
||||
Object.values(
|
||||
useServerChannelsStore(
|
||||
useShallow((state) => state.channels[serverId] || {}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (!server) {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -63,42 +68,78 @@ function ListComponent() {
|
||||
</div>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem onClick={() => onOpen(ModalType.CREATE_SERVER_INVITE, { serverId })}>Create invite</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => onOpen(ModalType.CREATE_SERVER_CHANNEL, { serverId })}>Create channel</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
onOpen(ModalType.CREATE_SERVER_INVITE, {
|
||||
serverId,
|
||||
})
|
||||
}
|
||||
>
|
||||
Create invite
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
onOpen(ModalType.CREATE_SERVER_CHANNEL, {
|
||||
serverId,
|
||||
})
|
||||
}
|
||||
>
|
||||
Create channel
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
{currentUserId === server.ownerId &&
|
||||
<DropdownMenuItem variant="destructive" onClick={() => onOpen(ModalType.DELETE_SERVER_CONFIRM, { serverId })}>Delete</DropdownMenuItem>}
|
||||
{currentUserId !== server.ownerId &&
|
||||
<DropdownMenuItem variant="destructive">Leave</DropdownMenuItem>}
|
||||
{currentUserId === server.ownerId && (
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
onClick={() =>
|
||||
onOpen(ModalType.DELETE_SERVER_CONFIRM, {
|
||||
serverId,
|
||||
})
|
||||
}
|
||||
>
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{currentUserId !== server.ownerId && (
|
||||
<DropdownMenuItem variant="destructive">
|
||||
Leave
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="overflow-auto" scrollbarSize="narrow">
|
||||
<div className="p-2 flex flex-col gap-1 h-full">
|
||||
{channels.sort((a, b) => (a.lastMessageId ?? a.id) < (b.lastMessageId ?? b.id) ? 1 : -1).map((channel, _) => (
|
||||
<React.Fragment key={channel.id}>
|
||||
<ServerChannelListItem channel={channel} />
|
||||
</React.Fragment>
|
||||
))}
|
||||
{channels
|
||||
.sort((a, b) =>
|
||||
(a.lastMessageId ?? a.id) <
|
||||
(b.lastMessageId ?? b.id)
|
||||
? 1
|
||||
: -1,
|
||||
)
|
||||
.map((channel, _) => (
|
||||
<React.Fragment key={channel.id}>
|
||||
<ServerChannelListItem channel={channel} />
|
||||
</React.Fragment>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export const handle = {
|
||||
listComponent: <ListComponent />
|
||||
}
|
||||
listComponent: <ListComponent />,
|
||||
};
|
||||
|
||||
export default function Layout(
|
||||
{ params: { serverId } }: Route.ComponentProps
|
||||
) {
|
||||
const server = useServerListStore(useShallow(state => state.servers[serverId!] || null))
|
||||
const navigate = useNavigate()
|
||||
export default function Layout({ params: { serverId } }: Route.ComponentProps) {
|
||||
const server = useServerListStore(
|
||||
useShallow((state) => state.servers[serverId!] || null),
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
|
||||
if (!server) {
|
||||
setTimeout(() => navigate("/app/@me"), 0)
|
||||
setTimeout(() => navigate("/app/@me"), 0);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,72 @@
|
||||
import { LogOutIcon, PencilIcon, UserIcon } from "lucide-react";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "~/components/ui/avatar";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { LogOutIcon, UserIcon } from "lucide-react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "~/components/ui/form";
|
||||
import { IconUploadField } from "~/components/ui/icon-upload-field";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import file from "~/lib/api/client/file";
|
||||
import { patchUser } from "~/lib/api/client/user";
|
||||
import { useTokenStore } from "~/stores/token-store";
|
||||
import { useUsersStore } from "~/stores/users-store";
|
||||
|
||||
const schema = z.object({
|
||||
displayName: z.string().min(1).max(32).optional().nullable(),
|
||||
avatar: z.instanceof(File).optional().nullable(),
|
||||
});
|
||||
|
||||
// Note: This is a mockup based on the provided store structure
|
||||
export default function Settings() {
|
||||
const user = useUsersStore(state => state.getCurrentUser());
|
||||
const setToken = useTokenStore((state) => state.setToken);
|
||||
const user = useUsersStore((state) => state.getCurrentUser());
|
||||
|
||||
const form = useForm<z.infer<typeof schema>>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
displayName: user?.displayName,
|
||||
avatar: undefined,
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof schema>) => {
|
||||
if (!values) return;
|
||||
|
||||
let avatarId: string | null | undefined =
|
||||
values.avatar === null ? null : undefined;
|
||||
if (values.avatar) {
|
||||
avatarId = (await file.uploadFile(values.avatar))[0];
|
||||
}
|
||||
|
||||
const response = await patchUser({
|
||||
displayName:
|
||||
values.displayName === user?.displayName
|
||||
? undefined
|
||||
: values.displayName === ""
|
||||
? null
|
||||
: values.displayName,
|
||||
avatarId,
|
||||
});
|
||||
|
||||
form.control._defaultValues = {
|
||||
displayName: user?.displayName,
|
||||
avatar: undefined,
|
||||
};
|
||||
|
||||
form.reset();
|
||||
};
|
||||
|
||||
const onLogout = () => {
|
||||
setToken(undefined);
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen">
|
||||
@@ -20,7 +80,11 @@ export default function Settings() {
|
||||
</Button>
|
||||
|
||||
<div className="mt-auto">
|
||||
<Button variant="destructive" className="w-full">
|
||||
<Button
|
||||
variant="destructive"
|
||||
className="w-full"
|
||||
onClick={onLogout}
|
||||
>
|
||||
<LogOutIcon className="mr-2 h-4 w-4" />
|
||||
Logout
|
||||
</Button>
|
||||
@@ -30,74 +94,72 @@ export default function Settings() {
|
||||
{/* Main content */}
|
||||
<div className="flex-1 p-8">
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<div className="flex flex-col items-center mb-8">
|
||||
<Avatar className="h-24 w-24 mb-4">
|
||||
<AvatarImage src={user?.avatarUrl} alt={user?.displayName} />
|
||||
<AvatarFallback className="text-yellow-500">
|
||||
<UserIcon className="h-12 w-12" />
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
|
||||
<Button variant="outline" size="sm">
|
||||
<PencilIcon className="mr-2 h-4 w-4" />
|
||||
Change
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<form>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="name" className="block text-sm mb-1">
|
||||
Username
|
||||
</label>
|
||||
<Input
|
||||
id="name"
|
||||
name="name"
|
||||
value={user?.username}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="displayName" className="block text-sm mb-1">
|
||||
Display name
|
||||
</label>
|
||||
<Input
|
||||
id="displayName"
|
||||
name="displayName"
|
||||
value={user?.displayName}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm mb-1">
|
||||
Email
|
||||
</label>
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
value={user?.email}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm mb-1">
|
||||
Password
|
||||
</label>
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="mt-4">
|
||||
Save
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className="space-y-4"
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="avatar"
|
||||
render={({ field, fieldState }) => (
|
||||
<FormItem>
|
||||
<FormLabel
|
||||
required={
|
||||
!schema.shape.avatar.isOptional()
|
||||
}
|
||||
>
|
||||
Avatar
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<div className="flex flex-col items-center justify-center">
|
||||
<IconUploadField
|
||||
defaultPreview={
|
||||
user?.avatarUrl
|
||||
}
|
||||
formDefaultValue={
|
||||
user?.avatarUrl
|
||||
}
|
||||
field={field}
|
||||
error={fieldState.error}
|
||||
/>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="displayName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel
|
||||
required={
|
||||
!schema.shape.displayName.isOptional()
|
||||
}
|
||||
>
|
||||
Display Name
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={form.formState.isSubmitting}
|
||||
>
|
||||
{form.formState.isSubmitting
|
||||
? "Saving..."
|
||||
: "Save"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</form>
|
||||
</Form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,14 @@ import { useShallow } from "zustand/react/shallow";
|
||||
import { PasswordInput } from "~/components/custom-ui/password-input";
|
||||
import { ThemeToggle } from "~/components/theme/theme-toggle";
|
||||
import { Button, buttonVariants } from "~/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "~/components/ui/card";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -27,64 +34,84 @@ const schema = z.object({
|
||||
});
|
||||
|
||||
export async function clientLoader() {
|
||||
const { token, setToken } = useTokenStore.getState()
|
||||
const { token, setToken } = useTokenStore.getState();
|
||||
|
||||
if (token) {
|
||||
try {
|
||||
await import("~/lib/api/client/user").then(m => m.default.me())
|
||||
await import("~/lib/api/client/user").then((m) => m.default.me());
|
||||
|
||||
return redirect("/app/@me")
|
||||
return redirect("/app/@me");
|
||||
} catch (error) {
|
||||
const axiosError = error as AxiosError
|
||||
const axiosError = error as AxiosError;
|
||||
|
||||
if (axiosError.status === 401) {
|
||||
setToken(undefined)
|
||||
setToken(undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default function Login() {
|
||||
let navigate = useNavigate()
|
||||
let setToken = useTokenStore(state => state.setToken)
|
||||
const { setCurrentUserId, addUser } = useUsersStore(useShallow(state => {
|
||||
return {
|
||||
setCurrentUserId: state.setCurrentUserId,
|
||||
addUser: state.addUser
|
||||
}
|
||||
}))
|
||||
let navigate = useNavigate();
|
||||
let setToken = useTokenStore((state) => state.setToken);
|
||||
const { setCurrentUserId, addUser } = useUsersStore(
|
||||
useShallow((state) => {
|
||||
return {
|
||||
setCurrentUserId: state.setCurrentUserId,
|
||||
addUser: state.addUser,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
const form = useForm<z.infer<typeof schema>>({
|
||||
resolver: zodResolver(schema),
|
||||
})
|
||||
});
|
||||
|
||||
async function onSubmit(values: z.infer<typeof schema>) {
|
||||
const response = await auth.login(values)
|
||||
const response = await auth.login(values);
|
||||
|
||||
setToken(response.token)
|
||||
setCurrentUserId(response.user.id)
|
||||
addUser(response.user)
|
||||
setToken(response.token);
|
||||
setCurrentUserId(response.user.id);
|
||||
addUser(response.user);
|
||||
|
||||
navigate("/app")
|
||||
navigate("/app");
|
||||
}
|
||||
|
||||
return (
|
||||
<Card style={{ viewTransitionName: "auth-card-view" }}>
|
||||
<CardHeader style={{ viewTransitionName: "auth-card-header-view" }} className="relative" >
|
||||
<CardHeader
|
||||
style={{ viewTransitionName: "auth-card-header-view" }}
|
||||
className="relative"
|
||||
>
|
||||
<CardTitle>Welcome back!</CardTitle>
|
||||
<CardDescription>Please sign in to continue.</CardDescription>
|
||||
<div className="absolute top-0 right-0 px-6" style={{ viewTransitionName: "auth-card-header-mode-toggle-view" }}>
|
||||
<div
|
||||
className="absolute top-0 right-0 px-6"
|
||||
style={{
|
||||
viewTransitionName: "auth-card-header-mode-toggle-view",
|
||||
}}
|
||||
>
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent style={{ viewTransitionName: "auth-card-content-view" }}>
|
||||
<CardContent
|
||||
style={{ viewTransitionName: "auth-card-content-view" }}
|
||||
>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4" style={{ viewTransitionName: "auth-form-view" }}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className="space-y-4"
|
||||
style={{ viewTransitionName: "auth-form-view" }}
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="username"
|
||||
render={({ field }) => (
|
||||
<FormItem style={{ viewTransitionName: "email-field-view" }}>
|
||||
<FormItem
|
||||
style={{
|
||||
viewTransitionName: "email-field-view",
|
||||
}}
|
||||
>
|
||||
<FormLabel required>Username</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
@@ -97,7 +124,12 @@ export default function Login() {
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem style={{ viewTransitionName: "password-field-view" }}>
|
||||
<FormItem
|
||||
style={{
|
||||
viewTransitionName:
|
||||
"password-field-view",
|
||||
}}
|
||||
>
|
||||
<FormLabel required>Password</FormLabel>
|
||||
<FormControl>
|
||||
<PasswordInput {...field} />
|
||||
@@ -106,16 +138,33 @@ export default function Login() {
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button className="w-full" type="submit" style={{ viewTransitionName: "submit-button-view" }}>Log In</Button>
|
||||
<Button
|
||||
className="w-full"
|
||||
type="submit"
|
||||
style={{ viewTransitionName: "submit-button-view" }}
|
||||
>
|
||||
Log In
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</CardContent>
|
||||
<CardFooter style={{ viewTransitionName: "auth-card-footer-view" }}>
|
||||
<div className="flex items-center">
|
||||
<span className="text-muted-foreground text-sm">Don't have an account?</span>
|
||||
<Link className={buttonVariants({ variant: "link", size: "sm" })} to="/register" viewTransition>Register</Link>
|
||||
<span className="text-muted-foreground text-sm">
|
||||
Don't have an account?
|
||||
</span>
|
||||
<Link
|
||||
className={buttonVariants({
|
||||
variant: "link",
|
||||
size: "sm",
|
||||
})}
|
||||
to="/register"
|
||||
viewTransition
|
||||
>
|
||||
Register
|
||||
</Link>
|
||||
</div>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,14 @@ import { z } from "zod";
|
||||
import { PasswordInput } from "~/components/custom-ui/password-input";
|
||||
import { ThemeToggle } from "~/components/theme/theme-toggle";
|
||||
import { Button, buttonVariants } from "~/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "~/components/ui/card";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -20,43 +27,70 @@ import auth from "~/lib/api/client/auth";
|
||||
const schema = z.object({
|
||||
email: z.string().email(),
|
||||
displayName: z.string().min(1).optional(),
|
||||
username: z.string().min(3).regex(/^[a-zA-Z0-9_.]+$/),
|
||||
username: z
|
||||
.string()
|
||||
.min(3)
|
||||
.regex(/^[a-zA-Z0-9_.]+$/),
|
||||
password: z.string().min(8),
|
||||
});
|
||||
|
||||
export default function Register() {
|
||||
let navigate = useNavigate()
|
||||
|
||||
let navigate = useNavigate();
|
||||
|
||||
const form = useForm<z.infer<typeof schema>>({
|
||||
resolver: zodResolver(schema),
|
||||
})
|
||||
});
|
||||
|
||||
async function onSubmit(values: z.infer<typeof schema>) {
|
||||
await auth.register(values)
|
||||
await auth.register(values);
|
||||
|
||||
navigate("/login")
|
||||
navigate("/login");
|
||||
}
|
||||
|
||||
return (
|
||||
<Card style={{ viewTransitionName: "auth-card-view" }}>
|
||||
<CardHeader style={{ viewTransitionName: "auth-card-header-view" }} className="relative">
|
||||
<CardHeader
|
||||
style={{ viewTransitionName: "auth-card-header-view" }}
|
||||
className="relative"
|
||||
>
|
||||
<CardTitle>Create an account</CardTitle>
|
||||
<CardDescription>Please fill out the form below to create an account.</CardDescription>
|
||||
<div className="absolute top-0 right-0 px-6" style={{ viewTransitionName: "auth-card-header-mode-toggle-view" }}>
|
||||
<CardDescription>
|
||||
Please fill out the form below to create an account.
|
||||
</CardDescription>
|
||||
<div
|
||||
className="absolute top-0 right-0 px-6"
|
||||
style={{
|
||||
viewTransitionName: "auth-card-header-mode-toggle-view",
|
||||
}}
|
||||
>
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent style={{ viewTransitionName: "auth-card-content-view" }}>
|
||||
<CardContent
|
||||
style={{ viewTransitionName: "auth-card-content-view" }}
|
||||
>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4" style={{ viewTransitionName: "auth-form-view" }}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className="space-y-4"
|
||||
style={{ viewTransitionName: "auth-form-view" }}
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem style={{ viewTransitionName: "email-field-view" }}>
|
||||
<FormItem
|
||||
style={{
|
||||
viewTransitionName: "email-field-view",
|
||||
}}
|
||||
>
|
||||
<FormLabel required>Email</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="email" placeholder="email@example.com" {...field} />
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="email@example.com"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -92,7 +126,12 @@ export default function Register() {
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem style={{ viewTransitionName: "password-field-view" }}>
|
||||
<FormItem
|
||||
style={{
|
||||
viewTransitionName:
|
||||
"password-field-view",
|
||||
}}
|
||||
>
|
||||
<FormLabel required>Password</FormLabel>
|
||||
<FormControl>
|
||||
<PasswordInput {...field} />
|
||||
@@ -101,16 +140,33 @@ export default function Register() {
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button className="w-full" type="submit" style={{ viewTransitionName: "submit-button-view" }}>Register</Button>
|
||||
<Button
|
||||
className="w-full"
|
||||
type="submit"
|
||||
style={{ viewTransitionName: "submit-button-view" }}
|
||||
>
|
||||
Register
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</CardContent>
|
||||
<CardFooter style={{ viewTransitionName: "auth-card-footer-view" }}>
|
||||
<div className="flex items-center">
|
||||
<span className="text-muted-foreground text-sm">Already have an account?</span>
|
||||
<Link className={buttonVariants({ variant: "link", size: "sm" })} to="/login" viewTransition>Log In</Link>
|
||||
<span className="text-muted-foreground text-sm">
|
||||
Already have an account?
|
||||
</span>
|
||||
<Link
|
||||
className={buttonVariants({
|
||||
variant: "link",
|
||||
size: "sm",
|
||||
})}
|
||||
to="/login"
|
||||
viewTransition
|
||||
>
|
||||
Log In
|
||||
</Link>
|
||||
</div>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
import { redirect } from "react-router";
|
||||
import type { Route } from "./+types/index";
|
||||
|
||||
export function meta({ }: Route.MetaArgs) {
|
||||
return [
|
||||
{ title: "New React Router App" },
|
||||
];
|
||||
export function meta({}: Route.MetaArgs) {
|
||||
return [{ title: "New React Router App" }];
|
||||
}
|
||||
|
||||
export function clientLoader() {
|
||||
return redirect("/login");
|
||||
return redirect("/login");
|
||||
}
|
||||
|
||||
export default function Index() {
|
||||
return <></>;
|
||||
return <></>;
|
||||
}
|
||||
|
||||
@@ -13,32 +13,37 @@ interface ChannelVoiceState {
|
||||
|
||||
interface ChannelsVoiceState {
|
||||
channels: Record<ChannelId, ChannelVoiceState>;
|
||||
addUser: (channelId: ChannelId, userId: UserId, userVoiceState: UserVoiceState) => void;
|
||||
addUser: (
|
||||
channelId: ChannelId,
|
||||
userId: UserId,
|
||||
userVoiceState: UserVoiceState,
|
||||
) => void;
|
||||
removeUser: (channelId: ChannelId, userId: UserId) => void;
|
||||
removeChannel: (channelId: ChannelId) => void;
|
||||
}
|
||||
|
||||
export const useChannelsVoiceStateStore = create<ChannelsVoiceState>()(
|
||||
immer(
|
||||
(set, get) => ({
|
||||
channels: {},
|
||||
addUser: (channelId, userId, userVoiceState) => set((state) => {
|
||||
immer((set, get) => ({
|
||||
channels: {},
|
||||
addUser: (channelId, userId, userVoiceState) =>
|
||||
set((state) => {
|
||||
if (!state.channels[channelId]) {
|
||||
state.channels[channelId] = {
|
||||
users: {}
|
||||
}
|
||||
users: {},
|
||||
};
|
||||
}
|
||||
|
||||
state.channels[channelId].users[userId] = userVoiceState;
|
||||
}),
|
||||
removeUser: (channelId, userId) => set((state) => {
|
||||
removeUser: (channelId, userId) =>
|
||||
set((state) => {
|
||||
if (state.channels[channelId]) {
|
||||
delete state.channels[channelId].users[userId];
|
||||
}
|
||||
}),
|
||||
removeChannel: (channelId) => set((state) => {
|
||||
removeChannel: (channelId) =>
|
||||
set((state) => {
|
||||
delete state.channels[channelId];
|
||||
})
|
||||
})
|
||||
)
|
||||
)
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -1,102 +1,187 @@
|
||||
import type { QueryClient } from '@tanstack/react-query';
|
||||
import { create } from 'zustand';
|
||||
import { messageSchema, type ChannelId, type Message, type MessageId, type ServerId } from '~/lib/api/types';
|
||||
import { GatewayClient } from '~/lib/websocket/gateway/client';
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import { create } from "zustand";
|
||||
import {
|
||||
messageSchema,
|
||||
type ChannelId,
|
||||
type Message,
|
||||
type MessageId,
|
||||
type ServerId,
|
||||
} from "~/lib/api/types";
|
||||
import { GatewayClient } from "~/lib/websocket/gateway/client";
|
||||
import {
|
||||
ConnectionState,
|
||||
EventType,
|
||||
type EventData,
|
||||
type VoiceServerUpdateEvent
|
||||
} from '~/lib/websocket/gateway/types';
|
||||
import { useChannelsVoiceStateStore } from './channels-voice-state';
|
||||
import { usePrivateChannelsStore } from './private-channels-store';
|
||||
import { useServerChannelsStore } from './server-channels-store';
|
||||
import { useServerListStore } from './server-list-store';
|
||||
import { useUsersStore } from './users-store';
|
||||
type VoiceServerUpdateEvent,
|
||||
} from "~/lib/websocket/gateway/types";
|
||||
import { useChannelsVoiceStateStore } from "./channels-voice-state";
|
||||
import { usePrivateChannelsStore } from "./private-channels-store";
|
||||
import { useServerChannelsStore } from "./server-channels-store";
|
||||
import { useServerListStore } from "./server-list-store";
|
||||
import { useUsersStore } from "./users-store";
|
||||
|
||||
const GATEWAY_URL = 'ws://localhost:12345/gateway/ws';
|
||||
const GATEWAY_URL = "ws://localhost:12345/gateway/ws";
|
||||
|
||||
const HANDLERS = {
|
||||
[EventType.ADD_SERVER]: (self: GatewayState, data: Extract<EventData, { type: EventType.ADD_SERVER }>['data']) => {
|
||||
[EventType.ADD_SERVER]: (
|
||||
self: GatewayState,
|
||||
data: Extract<EventData, { type: EventType.ADD_SERVER }>["data"],
|
||||
) => {
|
||||
useServerListStore.getState().addServer(data.server);
|
||||
},
|
||||
|
||||
[EventType.REMOVE_SERVER]: (self: GatewayState, data: Extract<EventData, { type: EventType.REMOVE_SERVER }>['data']) => {
|
||||
[EventType.REMOVE_SERVER]: (
|
||||
self: GatewayState,
|
||||
data: Extract<EventData, { type: EventType.REMOVE_SERVER }>["data"],
|
||||
) => {
|
||||
useServerListStore.getState().removeServer(data.serverId);
|
||||
useServerChannelsStore.getState().removeServer(data.serverId);
|
||||
useChannelsVoiceStateStore.getState().removeChannel(data.serverId);
|
||||
},
|
||||
|
||||
[EventType.ADD_DM_CHANNEL]: (self: GatewayState, data: Extract<EventData, { type: EventType.ADD_DM_CHANNEL }>['data']) => {
|
||||
usePrivateChannelsStore.getState().addChannel(data.channel);
|
||||
[EventType.ADD_DM_CHANNEL]: (
|
||||
self: GatewayState,
|
||||
data: Extract<EventData, { type: EventType.ADD_DM_CHANNEL }>["data"],
|
||||
) => {
|
||||
usePrivateChannelsStore.getState().addChannel({
|
||||
...data.channel,
|
||||
recipients: data.recipients,
|
||||
});
|
||||
},
|
||||
|
||||
[EventType.REMOVE_DM_CHANNEL]: (self: GatewayState, data: Extract<EventData, { type: EventType.REMOVE_DM_CHANNEL }>['data']) => {
|
||||
[EventType.REMOVE_DM_CHANNEL]: (
|
||||
self: GatewayState,
|
||||
data: Extract<EventData, { type: EventType.REMOVE_DM_CHANNEL }>["data"],
|
||||
) => {
|
||||
usePrivateChannelsStore.getState().removeChannel(data.channelId);
|
||||
useChannelsVoiceStateStore.getState().removeChannel(data.channelId);
|
||||
},
|
||||
|
||||
[EventType.ADD_SERVER_CHANNEL]: (self: GatewayState, data: Extract<EventData, { type: EventType.ADD_SERVER_CHANNEL }>['data']) => {
|
||||
[EventType.ADD_SERVER_CHANNEL]: (
|
||||
self: GatewayState,
|
||||
data: Extract<
|
||||
EventData,
|
||||
{ type: EventType.ADD_SERVER_CHANNEL }
|
||||
>["data"],
|
||||
) => {
|
||||
useServerChannelsStore.getState().addChannel(data.channel);
|
||||
},
|
||||
|
||||
[EventType.REMOVE_SERVER_CHANNEL]: (self: GatewayState, data: Extract<EventData, { type: EventType.REMOVE_SERVER_CHANNEL }>['data']) => {
|
||||
useServerChannelsStore.getState().removeChannel(data.serverId, data.channelId);
|
||||
[EventType.REMOVE_SERVER_CHANNEL]: (
|
||||
self: GatewayState,
|
||||
data: Extract<
|
||||
EventData,
|
||||
{ type: EventType.REMOVE_SERVER_CHANNEL }
|
||||
>["data"],
|
||||
) => {
|
||||
useServerChannelsStore
|
||||
.getState()
|
||||
.removeChannel(data.serverId, data.channelId);
|
||||
useChannelsVoiceStateStore.getState().removeChannel(data.serverId);
|
||||
},
|
||||
|
||||
[EventType.ADD_USER]: (self: GatewayState, data: Extract<EventData, { type: EventType.ADD_USER }>['data']) => {
|
||||
[EventType.ADD_USER]: (
|
||||
self: GatewayState,
|
||||
data: Extract<EventData, { type: EventType.ADD_USER }>["data"],
|
||||
) => {
|
||||
useUsersStore.getState().addUser(data.user);
|
||||
},
|
||||
|
||||
[EventType.REMOVE_USER]: (self: GatewayState, data: Extract<EventData, { type: EventType.REMOVE_USER }>['data']) => {
|
||||
[EventType.REMOVE_USER]: (
|
||||
self: GatewayState,
|
||||
data: Extract<EventData, { type: EventType.REMOVE_USER }>["data"],
|
||||
) => {
|
||||
useUsersStore.getState().removeUser(data.userId);
|
||||
},
|
||||
|
||||
[EventType.ADD_SERVER_MEMBER]: (self: GatewayState, data: Extract<EventData, { type: EventType.ADD_SERVER_MEMBER }>['data']) => {
|
||||
[EventType.ADD_SERVER_MEMBER]: (
|
||||
self: GatewayState,
|
||||
data: Extract<EventData, { type: EventType.ADD_SERVER_MEMBER }>["data"],
|
||||
) => {
|
||||
useUsersStore.getState().addUser(data.user);
|
||||
},
|
||||
|
||||
[EventType.REMOVE_SERVER_MEMBER]: (self: GatewayState, data: Extract<EventData, { type: EventType.REMOVE_SERVER_MEMBER }>['data']) => {
|
||||
[EventType.REMOVE_SERVER_MEMBER]: (
|
||||
self: GatewayState,
|
||||
data: Extract<
|
||||
EventData,
|
||||
{ type: EventType.REMOVE_SERVER_MEMBER }
|
||||
>["data"],
|
||||
) => {
|
||||
useUsersStore.getState().removeUser(data.userId);
|
||||
},
|
||||
|
||||
[EventType.ADD_MESSAGE]: (self: GatewayState, data: Extract<EventData, { type: EventType.ADD_MESSAGE }>['data']) => {
|
||||
const message = messageSchema.parse(data.message)
|
||||
[EventType.ADD_MESSAGE]: (
|
||||
self: GatewayState,
|
||||
data: Extract<EventData, { type: EventType.ADD_MESSAGE }>["data"],
|
||||
) => {
|
||||
const message = messageSchema.parse(data.message);
|
||||
|
||||
if (self.queryClient) {
|
||||
self.queryClient.setQueryData(['messages', message.channelId], (oldData: {
|
||||
pages: Message[][],
|
||||
pageParams: MessageId[]
|
||||
}) => {
|
||||
return {
|
||||
pages: oldData?.pages ? [[message, ...oldData.pages[0]], ...oldData.pages.slice(1)] : [[message]],
|
||||
pageParams: oldData?.pageParams ?? [undefined, message.id]
|
||||
}
|
||||
});
|
||||
self.queryClient.setQueryData(
|
||||
["messages", message.channelId],
|
||||
(oldData: { pages: Message[][]; pageParams: MessageId[] }) => {
|
||||
return {
|
||||
pages: oldData?.pages
|
||||
? [
|
||||
[message, ...oldData.pages[0]],
|
||||
...oldData.pages.slice(1),
|
||||
]
|
||||
: [[message]],
|
||||
pageParams: oldData?.pageParams ?? [
|
||||
undefined,
|
||||
message.id,
|
||||
],
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
[EventType.REMOVE_MESSAGE]: (self: GatewayState, data: Extract<EventData, { type: EventType.REMOVE_MESSAGE }>['data']) => {
|
||||
[EventType.REMOVE_MESSAGE]: (
|
||||
self: GatewayState,
|
||||
data: Extract<EventData, { type: EventType.REMOVE_MESSAGE }>["data"],
|
||||
) => {
|
||||
if (self.queryClient) {
|
||||
self.queryClient.setQueryData(['messages', data.channelId], (oldData: any) => {
|
||||
if (!oldData) return [];
|
||||
return oldData.filter((message: any) => message.id !== data.messageId);
|
||||
});
|
||||
self.queryClient.setQueryData(
|
||||
["messages", data.channelId],
|
||||
(oldData: any) => {
|
||||
if (!oldData) return [];
|
||||
return oldData.filter(
|
||||
(message: any) => message.id !== data.messageId,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
[EventType.VOICE_CHANNEL_CONNECTED]: (self: GatewayState, data: Extract<EventData, { type: EventType.VOICE_CHANNEL_CONNECTED }>['data']) => {
|
||||
useChannelsVoiceStateStore.getState().addUser(data.channelId, data.userId, {
|
||||
deaf: false,
|
||||
muted: false
|
||||
});
|
||||
[EventType.VOICE_CHANNEL_CONNECTED]: (
|
||||
self: GatewayState,
|
||||
data: Extract<
|
||||
EventData,
|
||||
{ type: EventType.VOICE_CHANNEL_CONNECTED }
|
||||
>["data"],
|
||||
) => {
|
||||
useChannelsVoiceStateStore
|
||||
.getState()
|
||||
.addUser(data.channelId, data.userId, {
|
||||
deaf: false,
|
||||
muted: false,
|
||||
});
|
||||
},
|
||||
|
||||
[EventType.VOICE_CHANNEL_DISCONNECTED]: (self: GatewayState, data: Extract<EventData, { type: EventType.VOICE_CHANNEL_DISCONNECTED }>['data']) => {
|
||||
useChannelsVoiceStateStore.getState().removeUser(data.channelId, data.userId);
|
||||
[EventType.VOICE_CHANNEL_DISCONNECTED]: (
|
||||
self: GatewayState,
|
||||
data: Extract<
|
||||
EventData,
|
||||
{ type: EventType.VOICE_CHANNEL_DISCONNECTED }
|
||||
>["data"],
|
||||
) => {
|
||||
useChannelsVoiceStateStore
|
||||
.getState()
|
||||
.removeUser(data.channelId, data.userId);
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
interface GatewayState {
|
||||
client: GatewayClient | null;
|
||||
@@ -110,16 +195,22 @@ interface GatewayState {
|
||||
|
||||
updateVoiceState: (serverId: ServerId, channelId: ChannelId) => void;
|
||||
requestVoiceStates: (serverId: ServerId) => void;
|
||||
onVoiceServerUpdate: (handler: (event: VoiceServerUpdateEvent['data']) => void | Promise<void>) => (() => void);
|
||||
onVoiceServerUpdate: (
|
||||
handler: (
|
||||
event: VoiceServerUpdateEvent["data"],
|
||||
) => void | Promise<void>,
|
||||
) => () => void;
|
||||
}
|
||||
|
||||
export const useGatewayStore = create<GatewayState>()((set, get) => {
|
||||
const client = new GatewayClient(GATEWAY_URL);
|
||||
|
||||
const voiceHandlers = new Set<(event: VoiceServerUpdateEvent['data']) => void>();
|
||||
const voiceHandlers = new Set<
|
||||
(event: VoiceServerUpdateEvent["data"]) => void
|
||||
>();
|
||||
|
||||
client.onEvent(EventType.VOICE_SERVER_UPDATE, (event) => {
|
||||
voiceHandlers.forEach(handler => handler(event));
|
||||
voiceHandlers.forEach((handler) => handler(event));
|
||||
});
|
||||
|
||||
for (const [type, handler] of Object.entries(HANDLERS)) {
|
||||
@@ -137,7 +228,7 @@ export const useGatewayStore = create<GatewayState>()((set, get) => {
|
||||
client.connect(token);
|
||||
set({ status: client.connectionState });
|
||||
|
||||
client.onControl('stateChange', (state) => {
|
||||
client.onControl("stateChange", (state) => {
|
||||
set({ status: state });
|
||||
});
|
||||
},
|
||||
@@ -163,9 +254,8 @@ export const useGatewayStore = create<GatewayState>()((set, get) => {
|
||||
voiceHandlers.add(handler);
|
||||
|
||||
return () => {
|
||||
console.log("removing voice server update handler", handler);
|
||||
voiceHandlers.delete(handler);
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,23 +20,26 @@ export type DeleteServerConfirmModalData = {
|
||||
type: ModalType.CREATE_SERVER_CHANNEL;
|
||||
data: {
|
||||
serverId: ServerId;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
export type CreateServerChannelModalData = {
|
||||
type: ModalType.CREATE_SERVER_CHANNEL;
|
||||
data: {
|
||||
serverId: ServerId;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
export type ModalData = CreateServerChannelModalData | CreateServerInviteModalData | DeleteServerConfirmModalData;
|
||||
export type ModalData =
|
||||
| CreateServerChannelModalData
|
||||
| CreateServerInviteModalData
|
||||
| DeleteServerConfirmModalData;
|
||||
|
||||
interface ModalState {
|
||||
type: ModalType | null;
|
||||
data?: ModalData['data'];
|
||||
data?: ModalData["data"];
|
||||
isOpen: boolean;
|
||||
onOpen: (type: ModalType, data?: ModalData['data']) => void;
|
||||
onOpen: (type: ModalType, data?: ModalData["data"]) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
@@ -46,4 +49,4 @@ export const useModalStore = create<ModalState>()((set) => ({
|
||||
isOpen: false,
|
||||
onOpen: (type, data) => set({ type, data, isOpen: true }),
|
||||
onClose: () => set({ type: null, isOpen: false }),
|
||||
}));
|
||||
}));
|
||||
|
||||
@@ -1,25 +1,33 @@
|
||||
import { create } from 'zustand'
|
||||
import { immer } from 'zustand/middleware/immer'
|
||||
import type { ChannelId, RecipientChannel } from '~/lib/api/types'
|
||||
import { create } from "zustand";
|
||||
import { immer } from "zustand/middleware/immer";
|
||||
import type { ChannelId, RecipientChannel } from "~/lib/api/types";
|
||||
|
||||
type PrivateChannelsStore = {
|
||||
channels: Record<ChannelId, RecipientChannel>
|
||||
addChannels: (channels: RecipientChannel[]) => void
|
||||
addChannel: (channel: RecipientChannel) => void
|
||||
removeChannel: (channelId: ChannelId) => void
|
||||
}
|
||||
channels: Record<ChannelId, RecipientChannel>;
|
||||
addChannels: (channels: RecipientChannel[]) => void;
|
||||
addChannel: (channel: RecipientChannel) => void;
|
||||
removeChannel: (channelId: ChannelId) => void;
|
||||
};
|
||||
|
||||
export const usePrivateChannelsStore = create<PrivateChannelsStore>()(
|
||||
immer(
|
||||
(set) => ({
|
||||
channels: {},
|
||||
addChannels: (channels: RecipientChannel[]) => set((state) => {
|
||||
immer((set) => ({
|
||||
channels: {},
|
||||
addChannels: (channels: RecipientChannel[]) =>
|
||||
set((state) => {
|
||||
for (const channel of channels) {
|
||||
state.channels[channel.id] = channel
|
||||
state.channels[channel.id] = channel;
|
||||
console.log("add channel", channel);
|
||||
}
|
||||
}),
|
||||
addChannel: (channel: RecipientChannel) => set((state) => { state.channels[channel.id] = channel }),
|
||||
removeChannel: (channelId: ChannelId) => set((state) => { delete state.channels[channelId] }),
|
||||
})
|
||||
)
|
||||
)
|
||||
addChannel: (channel: RecipientChannel) =>
|
||||
set((state) => {
|
||||
state.channels[channel.id] = {
|
||||
...channel,
|
||||
};
|
||||
}),
|
||||
removeChannel: (channelId: ChannelId) =>
|
||||
set((state) => {
|
||||
delete state.channels[channelId];
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -1,41 +1,48 @@
|
||||
import { create } from 'zustand'
|
||||
import { immer } from 'zustand/middleware/immer'
|
||||
import type { ChannelId, ServerChannel, ServerId } from "~/lib/api/types"
|
||||
import { create } from "zustand";
|
||||
import { immer } from "zustand/middleware/immer";
|
||||
import type { ChannelId, ServerChannel, ServerId } from "~/lib/api/types";
|
||||
|
||||
type ServerChannelsStore = {
|
||||
channels: Record<ServerId, Record<ChannelId, ServerChannel>>
|
||||
addServer: (serverId: ServerId) => void
|
||||
addChannel: (channel: ServerChannel) => void
|
||||
addChannels: (channels: ServerChannel[]) => void
|
||||
removeChannel: (serverId: ServerId, channelId: ChannelId) => void
|
||||
removeServer: (serverId: ServerId) => void
|
||||
}
|
||||
channels: Record<ServerId, Record<ChannelId, ServerChannel>>;
|
||||
addServer: (serverId: ServerId) => void;
|
||||
addChannel: (channel: ServerChannel) => void;
|
||||
addChannels: (channels: ServerChannel[]) => void;
|
||||
removeChannel: (serverId: ServerId, channelId: ChannelId) => void;
|
||||
removeServer: (serverId: ServerId) => void;
|
||||
};
|
||||
|
||||
export const useServerChannelsStore = create<ServerChannelsStore>()(
|
||||
immer(
|
||||
(set, get) => ({
|
||||
channels: {},
|
||||
addServer: (serverId) => set((state) => {
|
||||
state.channels[serverId] = {}
|
||||
immer((set, get) => ({
|
||||
channels: {},
|
||||
addServer: (serverId) =>
|
||||
set((state) => {
|
||||
state.channels[serverId] = {};
|
||||
}),
|
||||
addChannel: (channel) => set((state) => {
|
||||
addChannel: (channel) =>
|
||||
set((state) => {
|
||||
if (state.channels[channel.serverId] === undefined) {
|
||||
state.channels[channel.serverId] = {}
|
||||
state.channels[channel.serverId] = {};
|
||||
}
|
||||
|
||||
state.channels[channel.serverId][channel.id] = channel
|
||||
state.channels[channel.serverId][channel.id] = channel;
|
||||
}),
|
||||
addChannels: (channels) => set((state) => {
|
||||
addChannels: (channels) =>
|
||||
set((state) => {
|
||||
for (const channel of channels) {
|
||||
if (state.channels[channel.serverId] === undefined) {
|
||||
state.channels[channel.serverId] = {}
|
||||
state.channels[channel.serverId] = {};
|
||||
}
|
||||
|
||||
state.channels[channel.serverId][channel.id] = channel
|
||||
state.channels[channel.serverId][channel.id] = channel;
|
||||
}
|
||||
}),
|
||||
removeChannel: (serverId, channelId) => set((state) => { delete state.channels[serverId][channelId] }),
|
||||
removeServer: (serverId) => set((state) => { delete state.channels[serverId] }),
|
||||
})
|
||||
)
|
||||
)
|
||||
removeChannel: (serverId, channelId) =>
|
||||
set((state) => {
|
||||
delete state.channels[serverId][channelId];
|
||||
}),
|
||||
removeServer: (serverId) =>
|
||||
set((state) => {
|
||||
delete state.channels[serverId];
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -1,25 +1,30 @@
|
||||
import { create } from 'zustand'
|
||||
import { immer } from 'zustand/middleware/immer'
|
||||
import type { Server, ServerId, Uuid } from '~/lib/api/types'
|
||||
import { create } from "zustand";
|
||||
import { immer } from "zustand/middleware/immer";
|
||||
import type { Server, ServerId, Uuid } from "~/lib/api/types";
|
||||
|
||||
type ServerListStore = {
|
||||
servers: Record<ServerId, Server>
|
||||
addServers: (newServers: Server[]) => void
|
||||
addServer: (server: Server) => void
|
||||
removeServer: (serverId: Uuid) => void
|
||||
}
|
||||
servers: Record<ServerId, Server>;
|
||||
addServers: (newServers: Server[]) => void;
|
||||
addServer: (server: Server) => void;
|
||||
removeServer: (serverId: Uuid) => void;
|
||||
};
|
||||
|
||||
export const useServerListStore = create<ServerListStore>()(
|
||||
immer(
|
||||
(set) => ({
|
||||
servers: {},
|
||||
addServers: (servers: Server[]) => set((state) => {
|
||||
immer((set) => ({
|
||||
servers: {},
|
||||
addServers: (servers: Server[]) =>
|
||||
set((state) => {
|
||||
for (const server of servers) {
|
||||
state.servers[server.id] = server
|
||||
state.servers[server.id] = server;
|
||||
}
|
||||
}),
|
||||
addServer: (server: Server) => set((state) => { state.servers[server.id] = server }),
|
||||
removeServer: (serverId: Uuid) => set((state) => { delete state.servers[serverId] }),
|
||||
})
|
||||
)
|
||||
)
|
||||
addServer: (server: Server) =>
|
||||
set((state) => {
|
||||
state.servers[server.id] = server;
|
||||
}),
|
||||
removeServer: (serverId: Uuid) =>
|
||||
set((state) => {
|
||||
delete state.servers[serverId];
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { create } from 'zustand'
|
||||
import { persist } from 'zustand/middleware'
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
|
||||
type TokenStore = {
|
||||
token?: string
|
||||
setToken: (token?: string) => void
|
||||
removeToken: () => void
|
||||
}
|
||||
token?: string;
|
||||
setToken: (token?: string) => void;
|
||||
removeToken: () => void;
|
||||
};
|
||||
|
||||
export const useTokenStore = create<TokenStore>()(
|
||||
persist(
|
||||
@@ -15,7 +15,7 @@ export const useTokenStore = create<TokenStore>()(
|
||||
removeToken: () => set({ token: undefined }),
|
||||
}),
|
||||
{
|
||||
name: 'token',
|
||||
name: "token",
|
||||
},
|
||||
),
|
||||
)
|
||||
);
|
||||
|
||||
@@ -1,92 +1,78 @@
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { create as batshitCreate, keyResolver } from "@yornaath/batshit"
|
||||
import { create } from "zustand"
|
||||
import { immer } from "zustand/middleware/immer"
|
||||
import { getUser } from "~/lib/api/client/user"
|
||||
import type { FullUser, PartialUser, UserId } from "~/lib/api/types"
|
||||
import { create as batshitCreate, keyResolver } from "@yornaath/batshit";
|
||||
import { create } from "zustand";
|
||||
import { immer } from "zustand/middleware/immer";
|
||||
import { getUser } from "~/lib/api/client/user";
|
||||
import type { FullUser, PartialUser, UserId } from "~/lib/api/types";
|
||||
|
||||
type UsersStore = {
|
||||
users: Record<UserId, PartialUser>
|
||||
currentUserId: UserId | undefined
|
||||
fetchUsersIfNotPresent: (userIds: UserId[]) => Promise<void>
|
||||
addUser: (user: PartialUser) => void
|
||||
removeUser: (userId: UserId) => void
|
||||
setCurrentUserId: (userId: UserId) => void
|
||||
getCurrentUser: () => FullUser | undefined
|
||||
}
|
||||
users: Record<UserId, PartialUser>;
|
||||
currentUserId: UserId | undefined;
|
||||
fetchUsersIfNotPresent: (userIds: UserId[]) => Promise<void>;
|
||||
addUser: (user: PartialUser) => void;
|
||||
removeUser: (userId: UserId) => void;
|
||||
setCurrentUserId: (userId: UserId) => void;
|
||||
getCurrentUser: () => FullUser | undefined;
|
||||
};
|
||||
|
||||
const usersFetcher = batshitCreate({
|
||||
fetcher: async (userIds: UserId[]) => {
|
||||
let users = []
|
||||
let users = [];
|
||||
|
||||
for (const userId of userIds) {
|
||||
users.push(getUser(userId))
|
||||
users.push(getUser(userId));
|
||||
}
|
||||
|
||||
return await Promise.all(users)
|
||||
return await Promise.all(users);
|
||||
},
|
||||
resolver: keyResolver("id")
|
||||
})
|
||||
|
||||
export const useUserQuery = (userId: UserId) => useQuery(
|
||||
{
|
||||
queryKey: ["users", userId],
|
||||
queryFn: async () => {
|
||||
const user = await getUser(userId)
|
||||
return user
|
||||
},
|
||||
select: (data) => {
|
||||
useUsersStore.getState().addUser(data)
|
||||
return data
|
||||
}
|
||||
}
|
||||
)
|
||||
resolver: keyResolver("id"),
|
||||
});
|
||||
|
||||
export const useUsersStore = create<UsersStore>()(
|
||||
immer(
|
||||
(set, get) => ({
|
||||
users: {},
|
||||
currentUserId: undefined,
|
||||
fetchUsersIfNotPresent: async (userIds) => {
|
||||
let userPromises: Promise<PartialUser>[] = []
|
||||
for (const userId of userIds) {
|
||||
const user = get().users[userId]
|
||||
if (!user) {
|
||||
userPromises.push(usersFetcher.fetch(userId))
|
||||
}
|
||||
immer((set, get) => ({
|
||||
users: {},
|
||||
currentUserId: undefined,
|
||||
fetchUsersIfNotPresent: async (userIds) => {
|
||||
let userPromises: Promise<PartialUser>[] = [];
|
||||
for (const userId of userIds) {
|
||||
const user = get().users[userId];
|
||||
if (!user) {
|
||||
userPromises.push(usersFetcher.fetch(userId));
|
||||
}
|
||||
}
|
||||
|
||||
const users = await Promise.all(userPromises)
|
||||
const activeUsers = users.filter(Boolean)
|
||||
const users = await Promise.all(userPromises);
|
||||
const activeUsers = users.filter(Boolean);
|
||||
|
||||
set((state) => {
|
||||
for (const user of activeUsers) {
|
||||
if (user?.id)
|
||||
state.users[user.id] = user
|
||||
}
|
||||
|
||||
})
|
||||
},
|
||||
addUser: (user) => set((state) => {
|
||||
set((state) => {
|
||||
for (const user of activeUsers) {
|
||||
if (user?.id) state.users[user.id] = user;
|
||||
}
|
||||
});
|
||||
},
|
||||
addUser: (user) =>
|
||||
set((state) => {
|
||||
if (user.id !== get().currentUserId)
|
||||
state.users[user.id] = user
|
||||
state.users[user.id] = user;
|
||||
else {
|
||||
const currentUser = get().users[user.id]
|
||||
const currentUser = get().users[user.id];
|
||||
if (currentUser)
|
||||
state.users[user.id] = { ...currentUser, ...user }
|
||||
else
|
||||
state.users[user.id] = user
|
||||
state.users[user.id] = { ...currentUser, ...user };
|
||||
else state.users[user.id] = user;
|
||||
}
|
||||
}),
|
||||
removeUser: (userId) => set((state) => {
|
||||
delete state.users[userId]
|
||||
removeUser: (userId) =>
|
||||
set((state) => {
|
||||
delete state.users[userId];
|
||||
}),
|
||||
|
||||
setCurrentUserId: (userId) => set((state) => {
|
||||
state.currentUserId = userId
|
||||
setCurrentUserId: (userId) =>
|
||||
set((state) => {
|
||||
state.currentUserId = userId;
|
||||
}),
|
||||
|
||||
getCurrentUser: () => !!get().currentUserId ? get().users[get().currentUserId!] as FullUser : undefined
|
||||
}),
|
||||
)
|
||||
)
|
||||
getCurrentUser: () =>
|
||||
!!get().currentUserId
|
||||
? (get().users[get().currentUserId!] as FullUser)
|
||||
: undefined,
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { create } from 'zustand';
|
||||
import { useWebRTCStore } from './webrtc-store';
|
||||
import { create } from "zustand";
|
||||
import { useWebRTCStore } from "./webrtc-store";
|
||||
|
||||
interface VoiceState {
|
||||
activeChannel: { serverId: string; channelId: string } | null;
|
||||
@@ -20,7 +20,7 @@ export const useVoiceStateStore = create<VoiceState>()((set, get) => {
|
||||
joinVoiceChannel: (serverId, channelId) => {
|
||||
set({
|
||||
activeChannel: { serverId, channelId },
|
||||
error: null
|
||||
error: null,
|
||||
});
|
||||
},
|
||||
|
||||
@@ -41,6 +41,6 @@ export const useVoiceStateStore = create<VoiceState>()((set, get) => {
|
||||
|
||||
resetError: () => {
|
||||
set({ error: null });
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { create } from 'zustand';
|
||||
import { WebRTCClient } from '~/lib/websocket/voice/client';
|
||||
import { ConnectionState } from '~/lib/websocket/voice/types';
|
||||
import { useVoiceStateStore } from './voice-state-store';
|
||||
import { create } from "zustand";
|
||||
import { WebRTCClient } from "~/lib/websocket/voice/client";
|
||||
import { ConnectionState } from "~/lib/websocket/voice/types";
|
||||
import { useVoiceStateStore } from "./voice-state-store";
|
||||
|
||||
const VOICE_GATEWAY_URL = 'ws://localhost:12345/voice/ws';
|
||||
const VOICE_GATEWAY_URL = "ws://localhost:12345/voice/ws";
|
||||
|
||||
interface WebRTCState {
|
||||
client: WebRTCClient | null;
|
||||
@@ -22,11 +22,11 @@ export const useWebRTCStore = create<WebRTCState>()((set, get) => {
|
||||
(error) => {
|
||||
set({
|
||||
status: ConnectionState.ERROR,
|
||||
error: error.message
|
||||
error: error.message,
|
||||
});
|
||||
useVoiceStateStore.getState().setError(error.message);
|
||||
},
|
||||
(stream) => set({ remoteStream: stream })
|
||||
(stream) => set({ remoteStream: stream }),
|
||||
);
|
||||
|
||||
return {
|
||||
@@ -43,12 +43,12 @@ export const useWebRTCStore = create<WebRTCState>()((set, get) => {
|
||||
client.disconnect();
|
||||
set({
|
||||
status: ConnectionState.DISCONNECTED,
|
||||
remoteStream: null
|
||||
remoteStream: null,
|
||||
});
|
||||
},
|
||||
|
||||
createOffer: async (localStream) => {
|
||||
await client.createOffer(localStream);
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user