mirror of
https://github.com/Shadowfita/docmost.git
synced 2025-11-26 06:31:07 +10:00
vite
* replace next with vite * disable strictmode (it interferes with collaboration in dev mode)
This commit is contained in:
14
client/src/features/auth/atoms/auth-tokens-atom.ts
Normal file
14
client/src/features/auth/atoms/auth-tokens-atom.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import Cookies from "js-cookie";
|
||||
import { createJSONStorage, atomWithStorage } from "jotai/utils";
|
||||
import { ITokens } from '../types/auth.types';
|
||||
|
||||
|
||||
const cookieStorage = createJSONStorage<ITokens>(() => {
|
||||
return {
|
||||
getItem: () => Cookies.get("authTokens"),
|
||||
setItem: (key, value) => Cookies.set(key, value),
|
||||
removeItem: (key) => Cookies.remove(key),
|
||||
};
|
||||
});
|
||||
|
||||
export const authTokensAtom = atomWithStorage<ITokens | null>("authTokens", null, cookieStorage);
|
||||
78
client/src/features/auth/components/login-form.tsx
Normal file
78
client/src/features/auth/components/login-form.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import * as React from 'react';
|
||||
import * as z from 'zod';
|
||||
|
||||
import { useForm, zodResolver } from '@mantine/form';
|
||||
import useAuth from '@/features/auth/hooks/use-auth';
|
||||
import { ILogin } from '@/features/auth/types/auth.types';
|
||||
import {
|
||||
Container,
|
||||
Title,
|
||||
Anchor,
|
||||
Paper,
|
||||
TextInput,
|
||||
Button,
|
||||
Text,
|
||||
PasswordInput,
|
||||
} from '@mantine/core';
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
const formSchema = z.object({
|
||||
email: z
|
||||
.string({ required_error: 'email is required' })
|
||||
.email({ message: 'Invalid email address' }),
|
||||
password: z.string({ required_error: 'password is required' }),
|
||||
});
|
||||
|
||||
export function LoginForm() {
|
||||
const { signIn, isLoading } = useAuth();
|
||||
|
||||
const form = useForm<ILogin>({
|
||||
validate: zodResolver(formSchema),
|
||||
initialValues: {
|
||||
email: '',
|
||||
password: '',
|
||||
},
|
||||
});
|
||||
|
||||
async function onSubmit(data: ILogin) {
|
||||
await signIn(data);
|
||||
}
|
||||
|
||||
return (
|
||||
<Container size={420} my={40}>
|
||||
<Title ta="center" fw={800}>
|
||||
Login
|
||||
</Title>
|
||||
<Text c="dimmed" size="sm" ta="center" mt={5}>
|
||||
Don't have an account yet?{' '}
|
||||
<Anchor size="sm" component={Link} to="/signup">
|
||||
Create account
|
||||
</Anchor>
|
||||
</Text>
|
||||
|
||||
<Paper withBorder shadow="md" p={30} mt={30} radius="md">
|
||||
<form onSubmit={form.onSubmit(onSubmit)}>
|
||||
<TextInput
|
||||
id="email"
|
||||
type="email"
|
||||
label="Email"
|
||||
placeholder="email@example.com"
|
||||
required
|
||||
{...form.getInputProps('email')}
|
||||
/>
|
||||
|
||||
<PasswordInput
|
||||
label="Password"
|
||||
placeholder="Your password"
|
||||
required
|
||||
mt="md"
|
||||
{...form.getInputProps('password')}
|
||||
/>
|
||||
<Button type="submit" fullWidth mt="xl" loading={isLoading}>
|
||||
Sign In
|
||||
</Button>
|
||||
</form>
|
||||
</Paper>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
78
client/src/features/auth/components/sign-up-form.tsx
Normal file
78
client/src/features/auth/components/sign-up-form.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import * as React from 'react';
|
||||
import * as z from 'zod';
|
||||
|
||||
import { useForm, zodResolver } from '@mantine/form';
|
||||
import {
|
||||
Container,
|
||||
Title,
|
||||
Anchor,
|
||||
Paper,
|
||||
TextInput,
|
||||
Button,
|
||||
Text,
|
||||
PasswordInput,
|
||||
} from '@mantine/core';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { IRegister } from '@/features/auth/types/auth.types';
|
||||
import useAuth from '@/features/auth/hooks/use-auth';
|
||||
|
||||
const formSchema = z.object({
|
||||
email: z
|
||||
.string({ required_error: 'email is required' })
|
||||
.email({ message: 'Invalid email address' }),
|
||||
password: z.string({ required_error: 'password is required' }),
|
||||
});
|
||||
|
||||
export function SignUpForm() {
|
||||
const { signUp, isLoading } = useAuth();
|
||||
|
||||
const form = useForm<IRegister>({
|
||||
validate: zodResolver(formSchema),
|
||||
initialValues: {
|
||||
email: '',
|
||||
password: '',
|
||||
},
|
||||
});
|
||||
|
||||
async function onSubmit(data: IRegister) {
|
||||
await signUp(data);
|
||||
}
|
||||
|
||||
return (
|
||||
<Container size={420} my={40}>
|
||||
<Title ta="center" fw={800}>
|
||||
Create an account
|
||||
</Title>
|
||||
<Text c="dimmed" size="sm" ta="center" mt={5}>
|
||||
Already have an account?{' '}
|
||||
<Anchor size="sm" component={Link} to="/login">
|
||||
Login
|
||||
</Anchor>
|
||||
</Text>
|
||||
|
||||
<Paper withBorder shadow="md" p={30} mt={30} radius="md">
|
||||
<form onSubmit={form.onSubmit(onSubmit)}>
|
||||
<TextInput
|
||||
id="email"
|
||||
type="email"
|
||||
label="Email"
|
||||
placeholder="email@example.com"
|
||||
required
|
||||
{...form.getInputProps('email')}
|
||||
/>
|
||||
|
||||
<PasswordInput
|
||||
label="Password"
|
||||
placeholder="Your password"
|
||||
required
|
||||
mt="md"
|
||||
{...form.getInputProps('password')}
|
||||
/>
|
||||
<Button type="submit" fullWidth mt="xl" loading={isLoading}>
|
||||
Sign Up
|
||||
</Button>
|
||||
</form>
|
||||
</Paper>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
58
client/src/features/auth/hooks/use-auth.ts
Normal file
58
client/src/features/auth/hooks/use-auth.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { useState } from "react";
|
||||
import { login, register } from "@/features/auth/services/auth-service";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAtom } from "jotai";
|
||||
import { authTokensAtom } from "@/features/auth/atoms/auth-tokens-atom";
|
||||
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
|
||||
import { ILogin, IRegister } from "@/features/auth/types/auth.types";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
export default function useAuth() {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [, setCurrentUser] = useAtom(currentUserAtom);
|
||||
const [authToken, setAuthToken] = useAtom(authTokensAtom);
|
||||
|
||||
const handleSignIn = async (data: ILogin) => {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const res = await login(data);
|
||||
setIsLoading(false);
|
||||
setAuthToken(res.tokens);
|
||||
|
||||
navigate("/home");
|
||||
} catch (err) {
|
||||
setIsLoading(false);
|
||||
toast.error(err.response?.data.message)
|
||||
}
|
||||
};
|
||||
|
||||
const handleSignUp = async (data: IRegister) => {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const res = await register(data);
|
||||
setIsLoading(false);
|
||||
|
||||
setAuthToken(res.tokens);
|
||||
|
||||
navigate("/home");
|
||||
} catch (err) {
|
||||
setIsLoading(false);
|
||||
toast.error(err.response?.data.message)
|
||||
}
|
||||
};
|
||||
|
||||
const hasTokens = () => {
|
||||
return !!authToken;
|
||||
};
|
||||
|
||||
const handleLogout = async () => {
|
||||
setAuthToken(null);
|
||||
setCurrentUser(null);
|
||||
}
|
||||
|
||||
return { signIn: handleSignIn, signUp: handleSignUp, isLoading, hasTokens };
|
||||
}
|
||||
12
client/src/features/auth/services/auth-service.ts
Normal file
12
client/src/features/auth/services/auth-service.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import api from "@/lib/api-client";
|
||||
import { ILogin, IRegister, ITokenResponse } from "@/features/auth/types/auth.types";
|
||||
|
||||
export async function login(data: ILogin): Promise<ITokenResponse>{
|
||||
const req = await api.post<ITokenResponse>("/auth/login", data);
|
||||
return req.data as ITokenResponse;
|
||||
}
|
||||
|
||||
export async function register(data: IRegister): Promise<ITokenResponse>{
|
||||
const req = await api.post<ITokenResponse>("/auth/register", data);
|
||||
return req.data as ITokenResponse;
|
||||
}
|
||||
18
client/src/features/auth/types/auth.types.ts
Normal file
18
client/src/features/auth/types/auth.types.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
export interface ILogin {
|
||||
email: string,
|
||||
password: string
|
||||
}
|
||||
|
||||
export interface IRegister {
|
||||
email: string,
|
||||
password: string
|
||||
}
|
||||
|
||||
export interface ITokens {
|
||||
accessToken: string,
|
||||
refreshToken: string
|
||||
}
|
||||
|
||||
export interface ITokenResponse {
|
||||
tokens: ITokens
|
||||
}
|
||||
161
client/src/features/editor/editor.tsx
Normal file
161
client/src/features/editor/editor.tsx
Normal file
@@ -0,0 +1,161 @@
|
||||
import '@/features/editor/styles/editor.css';
|
||||
|
||||
import { HocuspocusProvider } from '@hocuspocus/provider';
|
||||
import * as Y from 'yjs';
|
||||
import { EditorContent, useEditor } from '@tiptap/react';
|
||||
import { StarterKit } from '@tiptap/starter-kit';
|
||||
import { Placeholder } from '@tiptap/extension-placeholder';
|
||||
import { Collaboration } from '@tiptap/extension-collaboration';
|
||||
import { CollaborationCursor } from '@tiptap/extension-collaboration-cursor';
|
||||
import { useEffect, useLayoutEffect, useState } from 'react';
|
||||
import { useAtom } from 'jotai';
|
||||
import { currentUserAtom } from '@/features/user/atoms/current-user-atom';
|
||||
import { authTokensAtom } from '@/features/auth/atoms/auth-tokens-atom';
|
||||
import useCollaborationUrl from '@/features/editor/hooks/use-collaboration-url';
|
||||
import { IndexeddbPersistence } from 'y-indexeddb';
|
||||
import { RichTextEditor } from '@mantine/tiptap';
|
||||
import { TextAlign } from '@tiptap/extension-text-align';
|
||||
import { Highlight } from '@tiptap/extension-highlight';
|
||||
import { Superscript } from '@tiptap/extension-superscript';
|
||||
import SubScript from '@tiptap/extension-subscript';
|
||||
import { Link } from '@tiptap/extension-link';
|
||||
import { Underline } from '@tiptap/extension-underline';
|
||||
|
||||
interface EditorProps {
|
||||
pageId: string,
|
||||
token?: string,
|
||||
}
|
||||
|
||||
const colors = ['#958DF1', '#F98181', '#FBBC88', '#FAF594', '#70CFF8', '#94FADB', '#B9F18D'];
|
||||
const getRandomElement = list => list[Math.floor(Math.random() * list.length)];
|
||||
const getRandomColor = () => getRandomElement(colors);
|
||||
|
||||
export default function Editor({ pageId }: EditorProps) {
|
||||
const [token] = useAtom(authTokensAtom);
|
||||
const collaborationURL = useCollaborationUrl();
|
||||
const [provider, setProvider] = useState<any>();
|
||||
const [yDoc] = useState(() => new Y.Doc());
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (token) {
|
||||
const indexeddbProvider = new IndexeddbPersistence(pageId, yDoc)
|
||||
const provider = new HocuspocusProvider({
|
||||
url: collaborationURL,
|
||||
name: pageId,
|
||||
document: yDoc,
|
||||
token: token.accessToken,
|
||||
});
|
||||
|
||||
setProvider(provider);
|
||||
|
||||
return () => {
|
||||
provider.destroy();
|
||||
setProvider(null);
|
||||
indexeddbProvider.destroy();
|
||||
};
|
||||
}
|
||||
}, [pageId, token]);
|
||||
|
||||
if (!provider) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<TiptapEditor ydoc={yDoc} provider={provider} />
|
||||
);
|
||||
}
|
||||
|
||||
interface TiptapEditorProps {
|
||||
ydoc: Y.Doc,
|
||||
provider: HocuspocusProvider
|
||||
}
|
||||
|
||||
function TiptapEditor({ ydoc, provider }: TiptapEditorProps) {
|
||||
const [currentUser] = useAtom(currentUserAtom);
|
||||
|
||||
const extensions = [
|
||||
StarterKit.configure({
|
||||
history: false,
|
||||
}),
|
||||
Placeholder.configure({
|
||||
placeholder: 'Write here',
|
||||
}),
|
||||
Collaboration.configure({
|
||||
document: ydoc,
|
||||
}),
|
||||
CollaborationCursor.configure({
|
||||
provider,
|
||||
}),
|
||||
Underline,
|
||||
Link,
|
||||
Superscript,
|
||||
SubScript,
|
||||
Highlight,
|
||||
TextAlign.configure({ types: ['heading', 'paragraph'] }),
|
||||
];
|
||||
|
||||
const editor = useEditor({
|
||||
extensions: extensions,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (editor && currentUser.user) {
|
||||
editor.chain().focus().updateUser({ ...currentUser.user, color: getRandomColor() }).run();
|
||||
}
|
||||
}, [editor, currentUser.user]);
|
||||
|
||||
useEffect(() => {
|
||||
provider.on('status', event => {
|
||||
console.log(event);
|
||||
});
|
||||
|
||||
}, [provider]);
|
||||
|
||||
|
||||
return (
|
||||
<RichTextEditor editor={editor}>
|
||||
<RichTextEditor.Toolbar sticky stickyOffset={60}>
|
||||
<RichTextEditor.ControlsGroup>
|
||||
<RichTextEditor.Bold />
|
||||
<RichTextEditor.Italic />
|
||||
<RichTextEditor.Underline />
|
||||
<RichTextEditor.Strikethrough />
|
||||
<RichTextEditor.ClearFormatting />
|
||||
<RichTextEditor.Highlight />
|
||||
<RichTextEditor.Code />
|
||||
</RichTextEditor.ControlsGroup>
|
||||
|
||||
<RichTextEditor.ControlsGroup>
|
||||
<RichTextEditor.H1 />
|
||||
<RichTextEditor.H2 />
|
||||
<RichTextEditor.H3 />
|
||||
<RichTextEditor.H4 />
|
||||
</RichTextEditor.ControlsGroup>
|
||||
|
||||
<RichTextEditor.ControlsGroup>
|
||||
<RichTextEditor.Blockquote />
|
||||
<RichTextEditor.Hr />
|
||||
<RichTextEditor.BulletList />
|
||||
<RichTextEditor.OrderedList />
|
||||
<RichTextEditor.Subscript />
|
||||
<RichTextEditor.Superscript />
|
||||
</RichTextEditor.ControlsGroup>
|
||||
|
||||
<RichTextEditor.ControlsGroup>
|
||||
<RichTextEditor.Link />
|
||||
<RichTextEditor.Unlink />
|
||||
</RichTextEditor.ControlsGroup>
|
||||
|
||||
<RichTextEditor.ControlsGroup>
|
||||
<RichTextEditor.AlignLeft />
|
||||
<RichTextEditor.AlignCenter />
|
||||
<RichTextEditor.AlignJustify />
|
||||
<RichTextEditor.AlignRight />
|
||||
</RichTextEditor.ControlsGroup>
|
||||
</RichTextEditor.Toolbar>
|
||||
|
||||
<RichTextEditor.Content />
|
||||
</RichTextEditor>
|
||||
);
|
||||
}
|
||||
17
client/src/features/editor/hooks/use-collaboration-url.ts
Normal file
17
client/src/features/editor/hooks/use-collaboration-url.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
const useCollaborationURL = (): string => {
|
||||
const PATH = "/collaboration";
|
||||
|
||||
if (import.meta.env.VITE_COLLABORATION_URL) {
|
||||
return import.meta.env.VITE_COLLABORATION_URL + PATH;
|
||||
}
|
||||
|
||||
const API_URL = import.meta.env.VITE_BACKEND_API_URL;
|
||||
if (!API_URL) {
|
||||
throw new Error("Backend API URL is not defined");
|
||||
}
|
||||
|
||||
const wsProtocol = API_URL.startsWith('https') ? 'wss' : 'ws';
|
||||
return `${wsProtocol}://${API_URL.split('://')[1]}${PATH}`;
|
||||
};
|
||||
|
||||
export default useCollaborationURL;
|
||||
199
client/src/features/editor/styles/editor.css
Normal file
199
client/src/features/editor/styles/editor.css
Normal file
@@ -0,0 +1,199 @@
|
||||
/* Basic editor styles */
|
||||
.tiptap {
|
||||
> * + * {
|
||||
margin-top: 0.75em;
|
||||
}
|
||||
|
||||
ul,
|
||||
ol {
|
||||
padding: 0 1rem;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4,
|
||||
h5,
|
||||
h6 {
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
code {
|
||||
background-color: rgba(#616161, 0.1);
|
||||
color: #616161;
|
||||
}
|
||||
|
||||
pre {
|
||||
background: #0d0d0d;
|
||||
border-radius: 0.5rem;
|
||||
color: #fff;
|
||||
font-family: "JetBrainsMono", monospace;
|
||||
padding: 0.75rem 1rem;
|
||||
|
||||
code {
|
||||
background: none;
|
||||
color: inherit;
|
||||
font-size: 0.8rem;
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
|
||||
mark {
|
||||
background-color: #faf594;
|
||||
}
|
||||
|
||||
img {
|
||||
height: auto;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
hr {
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
border-left: 2px solid rgba(#0d0d0d, 0.1);
|
||||
padding-left: 1rem;
|
||||
}
|
||||
|
||||
hr {
|
||||
border: none;
|
||||
border-top: 2px solid rgba(#0d0d0d, 0.1);
|
||||
margin: 2rem 0;
|
||||
}
|
||||
|
||||
ul[data-type="taskList"] {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
|
||||
li {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
|
||||
> label {
|
||||
flex: 0 0 auto;
|
||||
margin-right: 0.5rem;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
> div {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.editor {
|
||||
background-color: #fff;
|
||||
border: 2px solid #0d0d0d;
|
||||
border-radius: 0.75rem;
|
||||
box-shadow: 5px 5px #000;
|
||||
color: #0d0d0d;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: 26rem;
|
||||
|
||||
&__header {
|
||||
align-items: center;
|
||||
border-bottom: 2px solid #0d0d0d;
|
||||
border-top-left-radius: 0.25rem;
|
||||
border-top-right-radius: 0.25rem;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 0.5rem 1rem;
|
||||
}
|
||||
|
||||
&__users {
|
||||
color: rgba(#000, 0.8);
|
||||
display: flex;
|
||||
font-size: 0.85rem;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
&__content {
|
||||
flex: 1 1 auto;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
padding: 1.25rem 1rem;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
/* Some information about the status */
|
||||
&__status {
|
||||
align-items: center;
|
||||
border-radius: 5px;
|
||||
display: flex;
|
||||
|
||||
&::before {
|
||||
background: rgba(#0d0d0d, 0.5);
|
||||
border-radius: 50%;
|
||||
content: " ";
|
||||
display: inline-block;
|
||||
flex: 0 0 auto;
|
||||
height: 0.5rem;
|
||||
margin-right: 0.5rem;
|
||||
width: 0.5rem;
|
||||
}
|
||||
|
||||
&--connecting::before {
|
||||
background: #616161;
|
||||
}
|
||||
|
||||
&--connected::before {
|
||||
background: #b9f18d;
|
||||
}
|
||||
}
|
||||
|
||||
&__name button {
|
||||
appearance: none;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
line-height: normal;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow: visible;
|
||||
width: auto;
|
||||
}
|
||||
}
|
||||
|
||||
/* Give a remote user a caret */
|
||||
.collaboration-cursor__caret {
|
||||
border-left: 1px solid #0d0d0d;
|
||||
border-right: 1px solid #0d0d0d;
|
||||
margin-left: -1px;
|
||||
margin-right: -1px;
|
||||
pointer-events: none;
|
||||
position: relative;
|
||||
word-break: normal;
|
||||
}
|
||||
|
||||
/* Render the username above the caret */
|
||||
.collaboration-cursor__label {
|
||||
border-radius: 3px 3px 3px 0;
|
||||
color: #0d0d0d;
|
||||
font-size: 0.75rem;
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
left: -1px;
|
||||
line-height: normal;
|
||||
padding: 0.1rem 0.3rem;
|
||||
position: absolute;
|
||||
top: -1.4em;
|
||||
user-select: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.dots {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.dot {
|
||||
background: #000;
|
||||
border-radius: 100%;
|
||||
height: 0.625rem;
|
||||
width: 0.625rem;
|
||||
}
|
||||
34
client/src/features/page/hooks/usePage.ts
Normal file
34
client/src/features/page/hooks/usePage.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { useMutation, useQuery, UseQueryResult } from '@tanstack/react-query';
|
||||
import { ICurrentUserResponse } from '@/features/user/types/user.types';
|
||||
import { getUserInfo } from '@/features/user/services/user-service';
|
||||
import { createPage, deletePage, getPageById, updatePage } from '@/features/page/services/page-service';
|
||||
import { IPage } from '@/features/page/types/page.types';
|
||||
|
||||
|
||||
export default function usePage() {
|
||||
|
||||
const createMutation = useMutation(
|
||||
(data: Partial<IPage>) => createPage(data),
|
||||
);
|
||||
|
||||
const getPageByIdQuery = (id: string) => ({
|
||||
queryKey: ['page', id],
|
||||
queryFn: async () => getPageById(id),
|
||||
});
|
||||
|
||||
const updateMutation = useMutation(
|
||||
(data: Partial<IPage>) => updatePage(data),
|
||||
);
|
||||
|
||||
|
||||
const deleteMutation = useMutation(
|
||||
(id: string) => deletePage(id),
|
||||
);
|
||||
|
||||
return {
|
||||
create: createMutation.mutate,
|
||||
getPageById: getPageByIdQuery,
|
||||
update: updateMutation.mutate,
|
||||
delete: deleteMutation.mutate,
|
||||
};
|
||||
}
|
||||
35
client/src/features/page/services/page-service.ts
Normal file
35
client/src/features/page/services/page-service.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import api from '@/lib/api-client';
|
||||
import { IMovePage, IPage, IWorkspacePageOrder } from '@/features/page/types/page.types';
|
||||
|
||||
export async function createPage(data: Partial<IPage>): Promise<IPage> {
|
||||
const req = await api.post<IPage>('/page/create', data);
|
||||
return req.data as IPage;
|
||||
}
|
||||
|
||||
export async function getPageById(id: string): Promise<IPage> {
|
||||
const req = await api.post<IPage>('/page/details', { id });
|
||||
return req.data as IPage;
|
||||
}
|
||||
|
||||
export async function getPages(): Promise<IPage[]> {
|
||||
const req = await api.post<IPage[]>('/page/list');
|
||||
return req.data as IPage[];
|
||||
}
|
||||
|
||||
export async function getWorkspacePageOrder(): Promise<IWorkspacePageOrder[]> {
|
||||
const req = await api.post<IWorkspacePageOrder[]>('/page/list/order');
|
||||
return req.data as IWorkspacePageOrder[];
|
||||
}
|
||||
|
||||
export async function updatePage(data: Partial<IPage>): Promise<IPage> {
|
||||
const req = await api.post<IPage>(`/page/update`, data);
|
||||
return req.data as IPage;
|
||||
}
|
||||
|
||||
export async function movePage(data: IMovePage): Promise<void> {
|
||||
await api.post<IMovePage>('/page/move', data);
|
||||
}
|
||||
|
||||
export async function deletePage(id: string): Promise<void> {
|
||||
await api.post('/page/delete', { id });
|
||||
}
|
||||
5
client/src/features/page/tree/atoms/tree-api-atom.ts
Normal file
5
client/src/features/page/tree/atoms/tree-api-atom.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { atom } from "jotai";
|
||||
import { TreeApi } from 'react-arborist';
|
||||
import { TreeNode } from "../types";
|
||||
|
||||
export const treeApiAtom = atom<TreeApi<TreeNode> | null>(null);
|
||||
4
client/src/features/page/tree/atoms/tree-data-atom.ts
Normal file
4
client/src/features/page/tree/atoms/tree-data-atom.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { atom } from "jotai";
|
||||
import { TreeNode } from '@/features/page/tree/types';
|
||||
|
||||
export const treeDataAtom = atom<TreeNode[]>([]);
|
||||
@@ -0,0 +1,4 @@
|
||||
import { atomWithStorage } from "jotai/utils";
|
||||
import { IWorkspacePageOrder } from '@/features/page/types/page.types';
|
||||
|
||||
export const workspacePageOrderAtom = atomWithStorage<IWorkspacePageOrder | null>("workspace-page-order", null);
|
||||
@@ -0,0 +1,28 @@
|
||||
import React, { ReactElement } from 'react';
|
||||
import { useElementSize } from '@mantine/hooks';
|
||||
import { useMergedRef } from '@mantine/hooks';
|
||||
|
||||
type Props = {
|
||||
children: (dimens: { width: number; height: number }) => ReactElement;
|
||||
};
|
||||
|
||||
const style = {
|
||||
flex: 1,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
minHeight: 0,
|
||||
minWidth: 0,
|
||||
};
|
||||
|
||||
export const FillFlexParent = React.forwardRef(function FillFlexParent(
|
||||
props: Props,
|
||||
forwardRef
|
||||
) {
|
||||
const { ref, width, height } = useElementSize();
|
||||
const mergedRef = useMergedRef(ref, forwardRef);
|
||||
return (
|
||||
<div style={style} ref={mergedRef}>
|
||||
{width && height ? props.children({ width, height }) : null}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
101
client/src/features/page/tree/hooks/use-persistence.ts
Normal file
101
client/src/features/page/tree/hooks/use-persistence.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import { useMemo } from 'react';
|
||||
import {
|
||||
CreateHandler,
|
||||
DeleteHandler,
|
||||
MoveHandler,
|
||||
RenameHandler,
|
||||
SimpleTree,
|
||||
} from 'react-arborist';
|
||||
import { useAtom } from 'jotai';
|
||||
import { treeDataAtom } from '@/features/page/tree/atoms/tree-data-atom';
|
||||
import { createPage, deletePage, movePage, updatePage } from '@/features/page/services/page-service';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { IMovePage } from '@/features/page/types/page.types';
|
||||
import { useNavigate} from 'react-router-dom';
|
||||
import { TreeNode } from '@/features/page/tree/types';
|
||||
|
||||
|
||||
export function usePersistence<T>() {
|
||||
const [data, setData] = useAtom(treeDataAtom);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const tree = useMemo(() => new SimpleTree<TreeNode>(data), [data]);
|
||||
|
||||
|
||||
const onMove: MoveHandler<T> = (args: { parentId, index, parentNode, dragNodes, dragIds }) => {
|
||||
for (const id of args.dragIds) {
|
||||
tree.move({ id, parentId: args.parentId, index: args.index });
|
||||
}
|
||||
setData(tree.data);
|
||||
|
||||
const newDragIndex = tree.find(args.dragIds[0])?.childIndex;
|
||||
|
||||
const currentTreeData = args.parentId ? tree.find(args.parentId).children : tree.data;
|
||||
const afterId = currentTreeData[newDragIndex - 1]?.id || null;
|
||||
const beforeId = !afterId && currentTreeData[newDragIndex + 1]?.id || null;
|
||||
|
||||
const params: IMovePage= {
|
||||
id: args.dragIds[0],
|
||||
after: afterId,
|
||||
before: beforeId,
|
||||
parentId: args.parentId || null,
|
||||
};
|
||||
|
||||
const payload = Object.fromEntries(
|
||||
Object.entries(params).filter(([key, value]) => value !== null && value !== undefined)
|
||||
);
|
||||
|
||||
try {
|
||||
movePage(payload as IMovePage);
|
||||
} catch (error) {
|
||||
console.error('Error moving page:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const onRename: RenameHandler<T> = ({ name, id }) => {
|
||||
tree.update({ id, changes: { name } as any });
|
||||
setData(tree.data);
|
||||
|
||||
try {
|
||||
updatePage({ id, title: name });
|
||||
} catch (error) {
|
||||
console.error('Error updating page title:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const onCreate: CreateHandler<T> = async ({ parentId, index, type }) => {
|
||||
const data = { id: uuidv4(), name: '' } as any;
|
||||
data.children = [];
|
||||
tree.create({ parentId, index, data });
|
||||
setData(tree.data);
|
||||
|
||||
const payload: { id: string; parentPageId?: string } = { id: data.id };
|
||||
if (parentId) {
|
||||
payload.parentPageId = parentId;
|
||||
}
|
||||
|
||||
try {
|
||||
await createPage(payload);
|
||||
navigate(`/p/${payload.id}`);
|
||||
} catch (error) {
|
||||
console.error('Error creating the page:', error);
|
||||
}
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
const onDelete: DeleteHandler<T> = async (args: { ids: string[] }) => {
|
||||
args.ids.forEach((id) => tree.drop({ id }));
|
||||
setData(tree.data);
|
||||
|
||||
try {
|
||||
await deletePage(args.ids[0]);
|
||||
} catch (error) {
|
||||
console.error('Error deleting page:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const controllers = { onMove, onRename, onCreate, onDelete };
|
||||
|
||||
return { data, setData, controllers } as const;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { useQuery, UseQueryResult } from "@tanstack/react-query";
|
||||
import { IWorkspacePageOrder } from '@/features/page/types/page.types';
|
||||
import { getWorkspacePageOrder } from '@/features/page/services/page-service';
|
||||
|
||||
export default function useWorkspacePageOrder(): UseQueryResult<IWorkspacePageOrder> {
|
||||
return useQuery({
|
||||
queryKey: ["workspace-page-order"],
|
||||
queryFn: async () => {
|
||||
return await getWorkspacePageOrder();
|
||||
},
|
||||
});
|
||||
}
|
||||
279
client/src/features/page/tree/page-tree.tsx
Normal file
279
client/src/features/page/tree/page-tree.tsx
Normal file
@@ -0,0 +1,279 @@
|
||||
import { NodeApi, NodeRendererProps, Tree, TreeApi } from 'react-arborist';
|
||||
import {
|
||||
IconArrowsLeftRight,
|
||||
IconChevronDown,
|
||||
IconChevronRight,
|
||||
IconCornerRightUp,
|
||||
IconDotsVertical,
|
||||
IconEdit,
|
||||
IconFileDescription,
|
||||
IconLink,
|
||||
IconPlus,
|
||||
IconStar,
|
||||
IconTrash,
|
||||
} from '@tabler/icons-react';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import clsx from 'clsx';
|
||||
|
||||
import styles from './styles/tree.module.css';
|
||||
import { ActionIcon, Menu, rem } from '@mantine/core';
|
||||
import { useAtom } from 'jotai';
|
||||
import { FillFlexParent } from './components/fill-flex-parent';
|
||||
import { TreeNode } from './types';
|
||||
import { treeApiAtom } from './atoms/tree-api-atom';
|
||||
import { usePersistence } from '@/features/page/tree/hooks/use-persistence';
|
||||
import { IPage } from '@/features/page/types/page.types';
|
||||
import { getPages } from '@/features/page/services/page-service';
|
||||
import useWorkspacePageOrder from '@/features/page/tree/hooks/use-workspace-page-order';
|
||||
import { useLocation, useNavigate} from 'react-router-dom';
|
||||
|
||||
export default function PageTree() {
|
||||
const { data, setData, controllers } = usePersistence<TreeApi<TreeNode>>();
|
||||
const [tree, setTree] = useAtom<TreeApi<TreeNode>>(treeApiAtom);
|
||||
const { data: pageOrderData } = useWorkspacePageOrder();
|
||||
const location = useLocation();
|
||||
|
||||
const fetchAndSetTreeData = async () => {
|
||||
if (pageOrderData?.childrenIds) {
|
||||
try {
|
||||
const pages = await getPages();
|
||||
const treeData = convertToTree(pages, pageOrderData.childrenIds);
|
||||
setData(treeData);
|
||||
} catch (err) {
|
||||
console.error('Error fetching tree data: ', err);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchAndSetTreeData();
|
||||
}, [pageOrderData?.childrenIds]);
|
||||
|
||||
useEffect(() => {
|
||||
const pageId = location.pathname.split('/')[2];
|
||||
setTimeout(() => {
|
||||
tree?.select(pageId);
|
||||
}, 100);
|
||||
}, [tree, location.pathname]);
|
||||
|
||||
return (
|
||||
<div className={styles.treeContainer}>
|
||||
<FillFlexParent>
|
||||
{(dimens) => (
|
||||
<Tree
|
||||
data={data}
|
||||
{...controllers}
|
||||
{...dimens}
|
||||
// @ts-ignore
|
||||
ref={(t) => setTree(t)}
|
||||
openByDefault={false}
|
||||
disableMultiSelection={true}
|
||||
className={styles.tree}
|
||||
rowClassName={styles.row}
|
||||
padding={15}
|
||||
rowHeight={30}
|
||||
overscanCount={5}
|
||||
>
|
||||
{Node}
|
||||
</Tree>
|
||||
)}
|
||||
</FillFlexParent>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Node({ node, style, dragHandle }: NodeRendererProps<any>) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleClick = () => {
|
||||
navigate(`/p/${node.id}`);
|
||||
}
|
||||
|
||||
if (node.willReceiveDrop && node.isClosed){
|
||||
setTimeout(() => {
|
||||
if (node.state.willReceiveDrop) node.open();
|
||||
}, 650);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
style={style}
|
||||
className={clsx(styles.node, node.state)}
|
||||
ref={dragHandle}
|
||||
onClick={handleClick}
|
||||
>
|
||||
<PageArrow node={node} />
|
||||
|
||||
<IconFileDescription size="18px" style={{ marginRight: '4px' }} />
|
||||
|
||||
<span className={styles.text}>
|
||||
{node.isEditing ? (
|
||||
<Input node={node} />
|
||||
) : (
|
||||
node.data.name || 'untitled'
|
||||
)}
|
||||
</span>
|
||||
|
||||
<div className={styles.actions}>
|
||||
<NodeMenu node={node} />
|
||||
<CreateNode node={node} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateNode({ node }: { node: NodeApi<TreeNode> }) {
|
||||
const [tree] = useAtom(treeApiAtom);
|
||||
|
||||
function handleCreate() {
|
||||
tree?.create({ type: 'internal', parentId: node.id, index: 0 });
|
||||
}
|
||||
|
||||
return (
|
||||
<ActionIcon variant="transparent" color="gray" onClick={handleCreate}>
|
||||
<IconPlus style={{ width: rem(20), height: rem(20) }} stroke={2} />
|
||||
</ActionIcon>
|
||||
);
|
||||
}
|
||||
|
||||
function NodeMenu({ node }: { node: NodeApi<TreeNode> }) {
|
||||
const [tree] = useAtom(treeApiAtom);
|
||||
|
||||
function handleDelete() {
|
||||
tree?.delete(node);
|
||||
}
|
||||
|
||||
return (
|
||||
<Menu shadow="md" width={200}>
|
||||
<Menu.Target>
|
||||
<ActionIcon variant="transparent" color="gray">
|
||||
<IconDotsVertical
|
||||
style={{ width: rem(20), height: rem(20) }}
|
||||
stroke={2}
|
||||
/>
|
||||
</ActionIcon>
|
||||
</Menu.Target>
|
||||
|
||||
<Menu.Dropdown>
|
||||
<Menu.Item
|
||||
leftSection={<IconEdit style={{ width: rem(14), height: rem(14) }} />}
|
||||
onClick={() => node.edit()}
|
||||
>
|
||||
Rename
|
||||
</Menu.Item>
|
||||
<Menu.Item
|
||||
leftSection={<IconStar style={{ width: rem(14), height: rem(14) }} />}
|
||||
>
|
||||
Favorite
|
||||
</Menu.Item>
|
||||
|
||||
<Menu.Divider />
|
||||
|
||||
<Menu.Item
|
||||
leftSection={<IconLink style={{ width: rem(14), height: rem(14) }} />}
|
||||
>
|
||||
Copy link
|
||||
</Menu.Item>
|
||||
|
||||
<Menu.Item
|
||||
leftSection={
|
||||
<IconCornerRightUp style={{ width: rem(14), height: rem(14) }} />
|
||||
}
|
||||
>
|
||||
Move
|
||||
</Menu.Item>
|
||||
|
||||
<Menu.Divider />
|
||||
<Menu.Item
|
||||
leftSection={
|
||||
<IconArrowsLeftRight style={{ width: rem(14), height: rem(14) }} />
|
||||
}
|
||||
>
|
||||
Archive
|
||||
</Menu.Item>
|
||||
<Menu.Item
|
||||
color="red"
|
||||
leftSection={
|
||||
<IconTrash style={{ width: rem(14), height: rem(14) }} />
|
||||
}
|
||||
onClick={() => handleDelete()}
|
||||
>
|
||||
Delete
|
||||
</Menu.Item>
|
||||
</Menu.Dropdown>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
|
||||
function PageArrow({ node }: { node: NodeApi<TreeNode> }) {
|
||||
return (
|
||||
<span onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
node.toggle();
|
||||
}}>
|
||||
|
||||
{node.isInternal ? (
|
||||
node.children && node.children.length > 0 ? (
|
||||
node.isOpen ? (
|
||||
<IconChevronDown size={18} />
|
||||
) : (
|
||||
<IconChevronRight size={18} />
|
||||
)
|
||||
) : (
|
||||
<IconChevronRight size={18} style={{ visibility: 'hidden' }} />
|
||||
)
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Input({ node }: { node: NodeApi<TreeNode> }) {
|
||||
return (
|
||||
<input
|
||||
autoFocus
|
||||
name="name"
|
||||
type="text"
|
||||
placeholder="untitled"
|
||||
defaultValue={node.data.name}
|
||||
onFocus={(e) => e.currentTarget.select()}
|
||||
onBlur={() => node.reset()}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') node.reset();
|
||||
if (e.key === 'Enter') node.submit(e.currentTarget.value);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function convertToTree(pages: IPage[], pageOrder: string[]): TreeNode[] {
|
||||
const pageMap: { [id: string]: IPage } = {};
|
||||
pages.forEach(page => {
|
||||
pageMap[page.id] = page;
|
||||
});
|
||||
|
||||
function buildTreeNode(id: string): TreeNode | undefined {
|
||||
const page = pageMap[id];
|
||||
if (!page) return;
|
||||
|
||||
const node: TreeNode = {
|
||||
id: page.id,
|
||||
name: page.title,
|
||||
children: [],
|
||||
};
|
||||
|
||||
if (page.icon) node.icon = page.icon;
|
||||
|
||||
if (page.childrenIds && page.childrenIds.length > 0) {
|
||||
node.children = page.childrenIds.map(childId => buildTreeNode(childId)).filter(Boolean) as TreeNode[];
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
return pageOrder.map(id => buildTreeNode(id)).filter(Boolean) as TreeNode[];
|
||||
}
|
||||
|
||||
99
client/src/features/page/tree/styles/tree.module.css
Normal file
99
client/src/features/page/tree/styles/tree.module.css
Normal file
@@ -0,0 +1,99 @@
|
||||
.tree {
|
||||
border-radius: 0px;
|
||||
}
|
||||
|
||||
.treeContainer {
|
||||
display: flex;
|
||||
height: 60vh;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.node {
|
||||
position: relative;
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
|
||||
color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-0));
|
||||
|
||||
&:hover {
|
||||
background-color: light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-5));
|
||||
}
|
||||
|
||||
|
||||
.actions {
|
||||
visibility: hidden;
|
||||
position: absolute;
|
||||
height: 100%;
|
||||
top: 0;
|
||||
right: 0;
|
||||
border-top-right-radius: 4px;
|
||||
border-bottom-right-radius: 4px;
|
||||
background-color: light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-6));
|
||||
}
|
||||
|
||||
&:hover .actions {
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
.node:global(.willReceiveDrop) {
|
||||
background-color: light-dark(var(--mantine-color-blue-1), var(--mantine-color-gray-7));
|
||||
}
|
||||
|
||||
.node:global(.isSelected) {
|
||||
border-radius: 0;
|
||||
|
||||
background-color: light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-6));
|
||||
/*
|
||||
color: white;
|
||||
|
||||
// background-color: light-dark(
|
||||
// var(--mantine-color-gray-0),
|
||||
// var(--mantine-color-dark-6)
|
||||
//);
|
||||
//background: rgb(20, 127, 250, 0.5);*/
|
||||
}
|
||||
|
||||
.node:global(.isSelectedStart.isSelectedEnd) {
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.row:focus .node:global(.isSelected) {
|
||||
background-color: light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-6));
|
||||
}
|
||||
|
||||
.row {
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.row:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.row:focus .node {
|
||||
/** come back to this **/
|
||||
background-color: light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-5));
|
||||
}
|
||||
|
||||
.icon {
|
||||
margin: 0 rem(10px);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.text {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font-size: rem(14px);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.arrow {
|
||||
display: flex;
|
||||
}
|
||||
7
client/src/features/page/tree/types.ts
Normal file
7
client/src/features/page/tree/types.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export type TreeNode = {
|
||||
id: string
|
||||
name: string
|
||||
icon?: string
|
||||
slug?: string
|
||||
children: TreeNode[]
|
||||
}
|
||||
35
client/src/features/page/types/page.types.ts
Normal file
35
client/src/features/page/types/page.types.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
export interface IPage {
|
||||
id: string;
|
||||
title: string;
|
||||
content: string;
|
||||
html: string;
|
||||
slug: string;
|
||||
icon: string;
|
||||
coverPhoto: string;
|
||||
editor: string;
|
||||
shareId: string;
|
||||
parentPageId: string;
|
||||
creatorId: string;
|
||||
workspaceId: string;
|
||||
children:[]
|
||||
childrenIds:[]
|
||||
isLocked: boolean;
|
||||
status: string;
|
||||
publishedAt: Date;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
deletedAt: Date;
|
||||
}
|
||||
|
||||
export interface IMovePage {
|
||||
id: string;
|
||||
after?: string;
|
||||
before?: string;
|
||||
parentId?: string;
|
||||
}
|
||||
|
||||
export interface IWorkspacePageOrder {
|
||||
id: string;
|
||||
childrenIds: string[];
|
||||
workspaceId: string;
|
||||
}
|
||||
43
client/src/features/search/search-spotlight.tsx
Normal file
43
client/src/features/search/search-spotlight.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
import { rem } from '@mantine/core';
|
||||
import { Spotlight, SpotlightActionData } from '@mantine/spotlight';
|
||||
import { IconHome, IconDashboard, IconSettings, IconSearch } from '@tabler/icons-react';
|
||||
|
||||
const actions: SpotlightActionData[] = [
|
||||
{
|
||||
id: 'home',
|
||||
label: 'Home',
|
||||
description: 'Get to home page',
|
||||
onClick: () => console.log('Home'),
|
||||
leftSection: <IconHome style={{ width: rem(24), height: rem(24) }} stroke={1.5} />,
|
||||
},
|
||||
{
|
||||
id: 'dashboard',
|
||||
label: 'Dashboard',
|
||||
description: 'Get full information about current system status',
|
||||
onClick: () => console.log('Dashboard'),
|
||||
leftSection: <IconDashboard style={{ width: rem(24), height: rem(24) }} stroke={1.5} />,
|
||||
},
|
||||
{
|
||||
id: 'settings',
|
||||
label: 'Settings',
|
||||
description: 'Account settings and workspace management',
|
||||
onClick: () => console.log('Settings'),
|
||||
leftSection: <IconSettings style={{ width: rem(24), height: rem(24) }} stroke={1.5} />,
|
||||
},
|
||||
];
|
||||
|
||||
export function SearchSpotlight() {
|
||||
return (
|
||||
<>
|
||||
<Spotlight
|
||||
actions={actions}
|
||||
nothingFound="Nothing found..."
|
||||
highlightQuery
|
||||
searchProps={{
|
||||
leftSection: <IconSearch style={{ width: rem(20), height: rem(20) }} stroke={1.5} />,
|
||||
placeholder: 'Search...',
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import React from "react";
|
||||
import AccountNameForm from '@/features/settings/account/settings/components/account-name-form';
|
||||
import ChangeEmail from '@/features/settings/account/settings/components/change-email';
|
||||
import ChangePassword from '@/features/settings/account/settings/components/change-password';
|
||||
import { Divider } from '@mantine/core';
|
||||
|
||||
export default function AccountSettings() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<AccountNameForm />
|
||||
|
||||
<Divider my="lg" />
|
||||
|
||||
<ChangeEmail />
|
||||
|
||||
<Divider my="lg" />
|
||||
|
||||
<ChangePassword />
|
||||
</>);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useAtom } from 'jotai';
|
||||
import { focusAtom } from 'jotai-optics';
|
||||
import * as z from 'zod';
|
||||
import { useForm, zodResolver } from '@mantine/form';
|
||||
import { currentUserAtom } from '@/features/user/atoms/current-user-atom';
|
||||
import { updateUser } from '@/features/user/services/user-service';
|
||||
import { IUser } from '@/features/user/types/user.types';
|
||||
import { useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import { TextInput, Button } from '@mantine/core';
|
||||
|
||||
const formSchema = z.object({
|
||||
name: z.string().min(2).max(40).nonempty('Your name cannot be blank'),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof formSchema>;
|
||||
|
||||
const userAtom = focusAtom(currentUserAtom, (optic) => optic.prop('user'));
|
||||
|
||||
export default function AccountNameForm() {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [currentUser] = useAtom(currentUserAtom);
|
||||
const [, setUser] = useAtom(userAtom);
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
validate: zodResolver(formSchema),
|
||||
initialValues: {
|
||||
name: currentUser?.user?.name,
|
||||
},
|
||||
});
|
||||
|
||||
async function handleSubmit(data: Partial<IUser>) {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const updatedUser = await updateUser(data);
|
||||
setUser(updatedUser);
|
||||
toast.success('Updated successfully');
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
toast.error('Failed to update data.');
|
||||
}
|
||||
|
||||
setIsLoading(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<TextInput
|
||||
id="name"
|
||||
label="Name"
|
||||
placeholder="Your name"
|
||||
variant="filled"
|
||||
{...form.getInputProps('name')}
|
||||
rightSection={
|
||||
<Button type="submit" disabled={isLoading} loading={isLoading}>
|
||||
Save
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { Modal, TextInput, Button, Text, Group, PasswordInput } from '@mantine/core';
|
||||
import * as z from 'zod';
|
||||
import { useState } from 'react';
|
||||
import { useAtom } from 'jotai';
|
||||
import { currentUserAtom } from '@/features/user/atoms/current-user-atom';
|
||||
import { useDisclosure } from '@mantine/hooks';
|
||||
import * as React from 'react';
|
||||
import { useForm, zodResolver } from '@mantine/form';
|
||||
|
||||
|
||||
export default function ChangeEmail() {
|
||||
const [currentUser] = useAtom(currentUserAtom);
|
||||
const [opened, { open, close }] = useDisclosure(false);
|
||||
|
||||
return (
|
||||
<Group justify="space-between" wrap="nowrap" gap="xl">
|
||||
<div>
|
||||
<Text size="md">Email</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
{currentUser.user.email}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<Button onClick={open} variant="default">Change email</Button>
|
||||
|
||||
<Modal opened={opened} onClose={close} title="Change email" centered>
|
||||
<Text mb="md">To change your email, you have to enter your password and new email.</Text>
|
||||
<ChangePasswordForm />
|
||||
</Modal>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
|
||||
const formSchema = z.object({
|
||||
email: z.string({ required_error: 'New email is required' }).email(),
|
||||
password: z.string({ required_error: 'your current password is required' }).min(8),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof formSchema>
|
||||
|
||||
function ChangePasswordForm() {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
validate: zodResolver(formSchema),
|
||||
initialValues: {
|
||||
password: '',
|
||||
email: '',
|
||||
},
|
||||
});
|
||||
|
||||
function handleSubmit(data: FormValues) {
|
||||
setIsLoading(true);
|
||||
console.log(data);
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
|
||||
<PasswordInput
|
||||
label="Password"
|
||||
placeholder="Enter your password"
|
||||
variant="filled"
|
||||
mb="md"
|
||||
{...form.getInputProps('password')}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
id="email"
|
||||
label="Email"
|
||||
description="Enter your new preferred email"
|
||||
placeholder="New email"
|
||||
variant="filled"
|
||||
mb="md"
|
||||
{...form.getInputProps('email')}
|
||||
/>
|
||||
|
||||
<Button type="submit" disabled={isLoading} loading={isLoading}>
|
||||
Change email
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Button, Group, Text, Modal, PasswordInput } from '@mantine/core';
|
||||
import * as z from 'zod';
|
||||
import { useState } from 'react';
|
||||
import { useDisclosure } from '@mantine/hooks';
|
||||
import * as React from 'react';
|
||||
import { useForm, zodResolver } from '@mantine/form';
|
||||
|
||||
|
||||
export default function ChangePassword() {
|
||||
const [opened, { open, close }] = useDisclosure(false);
|
||||
|
||||
return (
|
||||
<Group justify="space-between" wrap="nowrap" gap="xl">
|
||||
<div>
|
||||
<Text size="md">Password</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
You can change your password here.
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<Button onClick={open} variant="default">Change password</Button>
|
||||
|
||||
<Modal opened={opened} onClose={close} title="Change password" centered>
|
||||
<Text mb="md">Your password must be a minimum of 8 characters.</Text>
|
||||
<ChangePasswordForm />
|
||||
|
||||
</Modal>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
|
||||
const formSchema = z.object({
|
||||
current: z.string({ required_error: 'your current password is required' }).min(1),
|
||||
password: z.string({ required_error: 'New password is required' }).min(8),
|
||||
confirm_password: z.string({ required_error: 'Password confirmation is required' }).min(8),
|
||||
}).refine(data => data.password === data.confirm_password, {
|
||||
message: 'Your new password and confirmation does not match.',
|
||||
path: ['confirm_password'],
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof formSchema>
|
||||
|
||||
function ChangePasswordForm() {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
validate: zodResolver(formSchema),
|
||||
initialValues: {
|
||||
current: '',
|
||||
password: '',
|
||||
confirm_password: '',
|
||||
},
|
||||
});
|
||||
|
||||
function handleSubmit(data: FormValues) {
|
||||
setIsLoading(true);
|
||||
console.log(data);
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
|
||||
<PasswordInput
|
||||
label="Current password"
|
||||
name="current"
|
||||
placeholder="Enter your password"
|
||||
variant="filled"
|
||||
mb="md"
|
||||
{...form.getInputProps('password')}
|
||||
/>
|
||||
|
||||
<PasswordInput
|
||||
label="New password"
|
||||
placeholder="Enter your password"
|
||||
variant="filled"
|
||||
mb="md"
|
||||
{...form.getInputProps('password')}
|
||||
/>
|
||||
|
||||
<Button type="submit" disabled={isLoading} loading={isLoading}>
|
||||
Change password
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { atom } from "jotai";
|
||||
|
||||
export const settingsModalAtom = atom<boolean>(false);
|
||||
76
client/src/features/settings/modal/modal.module.css
Normal file
76
client/src/features/settings/modal/modal.module.css
Normal file
@@ -0,0 +1,76 @@
|
||||
.sidebar {
|
||||
max-height: rem(700px);
|
||||
width: rem(180px);
|
||||
padding: var(--mantine-spacing-sm);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-right: rem(1px) solid
|
||||
light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-4));
|
||||
}
|
||||
|
||||
.sidebarFlex {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.sidebarMain {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.sidebarRightSection {
|
||||
flex: 1;
|
||||
padding: rem(16px) rem(40px);
|
||||
}
|
||||
|
||||
.sidebarItemHeader {
|
||||
padding: var(--mantine-spacing-xs) var(--mantine-spacing-sm);
|
||||
font-size: var(--mantine-font-size-sm);
|
||||
color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-1));
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.sidebarItem {
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
text-decoration: none;
|
||||
font-size: var(--mantine-font-size-sm);
|
||||
color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-1));
|
||||
padding: var(--mantine-spacing-xs) var(--mantine-spacing-sm);
|
||||
border-radius: var(--mantine-radius-sm);
|
||||
font-weight: 500;
|
||||
user-select: none;
|
||||
|
||||
@mixin hover {
|
||||
background-color: light-dark(
|
||||
var(--mantine-color-gray-1),
|
||||
var(--mantine-color-dark-6)
|
||||
);
|
||||
color: light-dark(var(--mantine-color-black), var(--mantine-color-white));
|
||||
|
||||
.sidebarItemIcon {
|
||||
color: light-dark(var(--mantine-color-black), var(--mantine-color-white));
|
||||
}
|
||||
}
|
||||
|
||||
&[data-active] {
|
||||
&,
|
||||
& :hover {
|
||||
background-color: var(--mantine-color-blue-light);
|
||||
color: var(--mantine-color-blue-light-color);
|
||||
|
||||
.sidebarItemIcon {
|
||||
color: var(--mantine-color-blue-light-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.sidebarItemIcon {
|
||||
color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-dark-2));
|
||||
margin-right: var(--mantine-spacing-sm);
|
||||
width: rem(20px);
|
||||
height: rem(20px);
|
||||
}
|
||||
30
client/src/features/settings/modal/settings-modal.tsx
Normal file
30
client/src/features/settings/modal/settings-modal.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import { Modal, Text } from '@mantine/core';
|
||||
import React from 'react';
|
||||
import SettingsSidebar from '@/features/settings/modal/settings-sidebar';
|
||||
import { useAtom } from 'jotai';
|
||||
import { settingsModalAtom } from '@/features/settings/modal/atoms/settings-modal-atom';
|
||||
|
||||
export default function SettingsModal() {
|
||||
const [isModalOpen, setModalOpen] = useAtom(settingsModalAtom);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal.Root size={1000} opened={isModalOpen} onClose={() => setModalOpen(false)}>
|
||||
<Modal.Overlay />
|
||||
<Modal.Content>
|
||||
<Modal.Header>
|
||||
<Modal.Title>
|
||||
<Text size="xl" fw={500}>Settings</Text>
|
||||
</Modal.Title>
|
||||
<Modal.CloseButton />
|
||||
</Modal.Header>
|
||||
<Modal.Body>
|
||||
|
||||
<SettingsSidebar />
|
||||
|
||||
</Modal.Body>
|
||||
</Modal.Content>
|
||||
</Modal.Root>
|
||||
</>
|
||||
);
|
||||
}
|
||||
101
client/src/features/settings/modal/settings-sidebar.tsx
Normal file
101
client/src/features/settings/modal/settings-sidebar.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
import React, { useState } from 'react';
|
||||
import classes from '@/features/settings/modal/modal.module.css';
|
||||
import { IconBell, IconFingerprint, IconReceipt, IconSettingsCog, IconUser, IconUsers } from '@tabler/icons-react';
|
||||
import { Loader, ScrollArea, Text } from '@mantine/core';
|
||||
|
||||
const AccountSettings = React.lazy(() => import('@/features/settings/account/settings/account-settings'));
|
||||
const WorkspaceSettings = React.lazy(() => import('@/features/settings/workspace/settings/workspace-settings'));
|
||||
const WorkspaceMembers = React.lazy(() => import('@/features/settings/workspace/members/workspace-members'));
|
||||
|
||||
interface DataItem {
|
||||
label: string;
|
||||
icon: React.ElementType;
|
||||
}
|
||||
|
||||
interface DataGroup {
|
||||
heading: string;
|
||||
items: DataItem[];
|
||||
}
|
||||
|
||||
const groupedData: DataGroup[] = [
|
||||
{
|
||||
heading: 'Account',
|
||||
items: [
|
||||
{ label: 'Account', icon: IconUser },
|
||||
{ label: 'Notifications', icon: IconBell },
|
||||
],
|
||||
},
|
||||
{
|
||||
heading: 'Workspace',
|
||||
items: [
|
||||
{ label: 'General', icon: IconSettingsCog },
|
||||
{ label: 'Members', icon: IconUsers },
|
||||
{ label: 'Security', icon: IconFingerprint },
|
||||
{ label: 'Billing', icon: IconReceipt },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export default function SettingsSidebar() {
|
||||
const [active, setActive] = useState('Account');
|
||||
|
||||
const menu = groupedData.map((group) => (
|
||||
<div key={group.heading}>
|
||||
<Text c="dimmed" className={classes.sidebarItemHeader}>{group.heading}</Text>
|
||||
{group.items.map((item) => (
|
||||
<div
|
||||
className={classes.sidebarItem}
|
||||
data-active={item.label === active || undefined}
|
||||
key={item.label}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
setActive(item.label);
|
||||
}}
|
||||
>
|
||||
<item.icon className={classes.sidebarItemIcon} stroke={1.5} />
|
||||
<span>{item.label}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
));
|
||||
|
||||
let ActiveComponent;
|
||||
|
||||
switch (active) {
|
||||
case 'Account':
|
||||
ActiveComponent = AccountSettings;
|
||||
break;
|
||||
case 'General':
|
||||
ActiveComponent = WorkspaceSettings;
|
||||
break;
|
||||
case 'Members':
|
||||
ActiveComponent = WorkspaceMembers;
|
||||
break;
|
||||
default:
|
||||
ActiveComponent = null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={classes.sidebarFlex}>
|
||||
<nav className={classes.sidebar}>
|
||||
<div className={classes.sidebarMain}>
|
||||
{menu}
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
|
||||
<ScrollArea h="650" w="100%" scrollbarSize={4}>
|
||||
|
||||
<div className={classes.sidebarRightSection}>
|
||||
|
||||
<React.Suspense fallback={<Loader size="sm" color="gray" />}>
|
||||
{ActiveComponent && <ActiveComponent />}
|
||||
</React.Suspense>
|
||||
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import {
|
||||
Group,
|
||||
Box,
|
||||
Text,
|
||||
Button,
|
||||
TagsInput,
|
||||
Space, Select,
|
||||
} from '@mantine/core';
|
||||
import WorkspaceInviteSection from '@/features/settings/workspace/members/components/workspace-invite-section';
|
||||
import React from 'react';
|
||||
|
||||
enum UserRole {
|
||||
GUEST = 'Guest',
|
||||
MEMBER = 'Member',
|
||||
OWNER = 'Owner',
|
||||
}
|
||||
|
||||
|
||||
export function WorkspaceInviteForm() {
|
||||
|
||||
function handleSubmit(data) {
|
||||
console.log(data);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Box maw="500" mx="auto">
|
||||
|
||||
<WorkspaceInviteSection />
|
||||
|
||||
<Space h="md" />
|
||||
|
||||
<TagsInput
|
||||
description="Enter valid email addresses separated by comma or space"
|
||||
label="Invite from email"
|
||||
placeholder="enter valid emails addresses"
|
||||
variant="filled"
|
||||
splitChars={[',', ' ']}
|
||||
maxDropdownHeight={200}
|
||||
maxTags={50}
|
||||
/>
|
||||
|
||||
<Space h="md" />
|
||||
|
||||
<Select
|
||||
description="Select role to assign to all invited members"
|
||||
label="Select role"
|
||||
placeholder="Pick a role"
|
||||
variant="filled"
|
||||
data={Object.values(UserRole)}
|
||||
defaultValue={UserRole.MEMBER}
|
||||
allowDeselect={false}
|
||||
checkIconPosition="right"
|
||||
/>
|
||||
|
||||
<Group justify="center" mt="md">
|
||||
<Button>Send invitation
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
</Box>
|
||||
</>
|
||||
);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { IconUserPlus } from '@tabler/icons-react';
|
||||
import { WorkspaceInviteForm } from '@/features/settings/workspace/members/components/workspace-invite-form';
|
||||
import { Button, Divider, Modal, ScrollArea, Text } from '@mantine/core';
|
||||
import { useDisclosure } from '@mantine/hooks';
|
||||
|
||||
export default function WorkspaceInviteModal() {
|
||||
const [opened, { open, close }] = useDisclosure(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button onClick={open} leftSection={<IconUserPlus size={18} />}>
|
||||
Invite Members
|
||||
</Button>
|
||||
|
||||
<Modal size="600" opened={opened} onClose={close} title="Invite new members" centered>
|
||||
|
||||
<Divider size="xs" mb="xs"/>
|
||||
|
||||
<ScrollArea h="80%">
|
||||
|
||||
<WorkspaceInviteForm />
|
||||
|
||||
</ScrollArea>
|
||||
</Modal>
|
||||
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useAtom } from 'jotai';
|
||||
import { currentUserAtom } from '@/features/user/atoms/current-user-atom';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Button, CopyButton, Text, TextInput } from '@mantine/core';
|
||||
|
||||
export default function WorkspaceInviteSection() {
|
||||
const [currentUser] = useAtom(currentUserAtom);
|
||||
const [inviteLink, setInviteLink] = useState<string>('');
|
||||
|
||||
useEffect(() => {
|
||||
setInviteLink(`${window.location.origin}/invite/${currentUser.workspace.inviteCode}`);
|
||||
}, [currentUser.workspace.inviteCode]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<Text fw={500} mb="sm">Invite link</Text>
|
||||
<Text c="dimmed" mb="sm">
|
||||
Anyone with this link can join this workspace.
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<TextInput
|
||||
variant="filled"
|
||||
value={inviteLink}
|
||||
readOnly
|
||||
rightSection={
|
||||
<CopyButton value={inviteLink}>
|
||||
{({ copied, copy }) => (
|
||||
<Button color={copied ? 'teal' : ''} onClick={copy}>
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
</Button>
|
||||
)}
|
||||
</CopyButton>
|
||||
}
|
||||
/>
|
||||
|
||||
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useAtom } from 'jotai';
|
||||
import { currentUserAtom } from '@/features/user/atoms/current-user-atom';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { getWorkspaceUsers } from '@/features/workspace/services/workspace-service';
|
||||
import { Group, Table, Avatar, Text, Badge } from '@mantine/core';
|
||||
|
||||
export default function WorkspaceMembersTable() {
|
||||
const [currentUser] = useAtom(currentUserAtom);
|
||||
|
||||
const workspaceUsers = useQuery({
|
||||
queryKey: ['workspaceUsers', currentUser.workspace.id],
|
||||
queryFn: async () => {
|
||||
return await getWorkspaceUsers();
|
||||
},
|
||||
});
|
||||
|
||||
const { data, isLoading, isSuccess } = workspaceUsers;
|
||||
|
||||
return (
|
||||
<>
|
||||
{isSuccess &&
|
||||
|
||||
<Table verticalSpacing="sm">
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th>Name</Table.Th>
|
||||
<Table.Th>Status</Table.Th>
|
||||
<Table.Th>Role</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
|
||||
<Table.Tbody>
|
||||
|
||||
{
|
||||
data['users']?.map((user, index) => (
|
||||
<Table.Tr key={index}>
|
||||
|
||||
<Table.Td>
|
||||
<Group gap="sm">
|
||||
<Avatar size={40} src={user.name} radius={40} />
|
||||
<div>
|
||||
<Text fz="sm" fw={500}>
|
||||
{user.name}
|
||||
</Text>
|
||||
<Text fz="xs" c="dimmed">
|
||||
{user.email}
|
||||
</Text>
|
||||
</div>
|
||||
</Group>
|
||||
</Table.Td>
|
||||
|
||||
<Table.Td>
|
||||
<Badge variant="light">
|
||||
Active
|
||||
</Badge>
|
||||
</Table.Td>
|
||||
|
||||
<Table.Td>{user.workspaceRole}</Table.Td>
|
||||
</Table.Tr>
|
||||
))
|
||||
}
|
||||
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import WorkspaceInviteSection from '@/features/settings/workspace/members/components/workspace-invite-section';
|
||||
import React from 'react';
|
||||
import WorkspaceInviteModal from '@/features/settings/workspace/members/components/workspace-invite-modal';
|
||||
import { Divider, Group, Space, Text } from '@mantine/core';
|
||||
|
||||
const WorkspaceMembersTable = React.lazy(() => import('@/features/settings/workspace/members/components/workspace-members-table'));
|
||||
|
||||
export default function WorkspaceMembers() {
|
||||
return (
|
||||
<>
|
||||
<WorkspaceInviteSection />
|
||||
|
||||
<Divider my="lg" />
|
||||
|
||||
<Group justify="space-between">
|
||||
<Text fw={500}>Members</Text>
|
||||
|
||||
<WorkspaceInviteModal />
|
||||
|
||||
</Group>
|
||||
|
||||
<Space h="lg" />
|
||||
|
||||
<WorkspaceMembersTable />
|
||||
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { currentUserAtom } from '@/features/user/atoms/current-user-atom';
|
||||
import { useAtom } from 'jotai';
|
||||
import * as z from 'zod';
|
||||
import toast from 'react-hot-toast';
|
||||
import { useState } from 'react';
|
||||
import { focusAtom } from 'jotai-optics';
|
||||
import { updateWorkspace } from '@/features/workspace/services/workspace-service';
|
||||
import { IWorkspace } from '@/features/workspace/types/workspace.types';
|
||||
import { TextInput, Button } from '@mantine/core';
|
||||
import { useForm, zodResolver } from '@mantine/form';
|
||||
|
||||
const formSchema = z.object({
|
||||
name: z.string().nonempty('Workspace name cannot be blank'),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof formSchema>;
|
||||
|
||||
const workspaceAtom = focusAtom(currentUserAtom, (optic) => optic.prop('workspace'));
|
||||
|
||||
export default function WorkspaceNameForm() {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [currentUser] = useAtom(currentUserAtom);
|
||||
const [, setWorkspace] = useAtom(workspaceAtom);
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
validate: zodResolver(formSchema),
|
||||
initialValues: {
|
||||
name: currentUser?.workspace?.name,
|
||||
},
|
||||
});
|
||||
|
||||
async function handleSubmit(data: Partial<IWorkspace>) {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const updatedWorkspace = await updateWorkspace(data);
|
||||
setWorkspace(updatedWorkspace);
|
||||
toast.success('Updated successfully');
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
toast.error('Failed to update data.');
|
||||
}
|
||||
|
||||
setIsLoading(false);
|
||||
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<TextInput
|
||||
id="name"
|
||||
label="Name"
|
||||
placeholder="e.g ACME"
|
||||
variant="filled"
|
||||
{...form.getInputProps('name')}
|
||||
rightSection={
|
||||
<Button type="submit" disabled={isLoading} loading={isLoading}>
|
||||
Save
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import WorkspaceNameForm from '@/features/settings/workspace/settings/components/workspace-name-form';
|
||||
|
||||
export default function WorkspaceSettings() {
|
||||
|
||||
return (<WorkspaceNameForm />);
|
||||
}
|
||||
5
client/src/features/user/atoms/current-user-atom.ts
Normal file
5
client/src/features/user/atoms/current-user-atom.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { atomWithStorage } from "jotai/utils";
|
||||
|
||||
import { ICurrentUserResponse } from "@/features/user/types/user.types";
|
||||
|
||||
export const currentUserAtom = atomWithStorage<ICurrentUserResponse | null>("currentUser", null);
|
||||
12
client/src/features/user/hooks/use-current-user.ts
Normal file
12
client/src/features/user/hooks/use-current-user.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { useQuery, UseQueryResult } from "@tanstack/react-query";
|
||||
import { getUserInfo } from "@/features/user/services/user-service";
|
||||
import { ICurrentUserResponse } from "@/features/user/types/user.types";
|
||||
|
||||
export default function useCurrentUser(): UseQueryResult<ICurrentUserResponse> {
|
||||
return useQuery({
|
||||
queryKey: ["currentUser"],
|
||||
queryFn: async () => {
|
||||
return await getUserInfo();
|
||||
},
|
||||
});
|
||||
}
|
||||
18
client/src/features/user/services/user-service.ts
Normal file
18
client/src/features/user/services/user-service.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import api from '@/lib/api-client';
|
||||
import { ICurrentUserResponse, IUser } from '@/features/user/types/user.types';
|
||||
|
||||
export async function getMe(): Promise<IUser> {
|
||||
const req = await api.get<IUser>('/user/me');
|
||||
return req.data as IUser;
|
||||
}
|
||||
|
||||
export async function getUserInfo(): Promise<ICurrentUserResponse> {
|
||||
const req = await api.get<ICurrentUserResponse>('/user/info');
|
||||
return req.data as ICurrentUserResponse;
|
||||
}
|
||||
|
||||
export async function updateUser(data: Partial<IUser>) {
|
||||
const req = await api.post<IUser>('/user/update', data);
|
||||
|
||||
return req.data as IUser;
|
||||
}
|
||||
21
client/src/features/user/types/user.types.ts
Normal file
21
client/src/features/user/types/user.types.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { IWorkspace } from "@/features/workspace/types/workspace.types";
|
||||
|
||||
export interface IUser {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
emailVerifiedAt: Date;
|
||||
avatarUrl: string;
|
||||
timezone: string;
|
||||
settings: any;
|
||||
lastLoginAt: string;
|
||||
lastLoginIp: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
workspaceRole?: string;
|
||||
}
|
||||
|
||||
export interface ICurrentUserResponse {
|
||||
user: IUser,
|
||||
workspace: IWorkspace
|
||||
}
|
||||
23
client/src/features/user/user-provider.tsx
Normal file
23
client/src/features/user/user-provider.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { useAtom } from 'jotai';
|
||||
import { currentUserAtom } from '@/features/user/atoms/current-user-atom';
|
||||
import React, { useEffect } from 'react';
|
||||
import useCurrentUser from '@/features/user/hooks/use-current-user';
|
||||
|
||||
export function UserProvider({ children }: React.PropsWithChildren) {
|
||||
const [, setCurrentUser] = useAtom(currentUserAtom);
|
||||
const { data, isLoading, error } = useCurrentUser();
|
||||
|
||||
useEffect(() => {
|
||||
if (data && data.user) {
|
||||
setCurrentUser(data);
|
||||
}
|
||||
}, [data, isLoading, setCurrentUser]);
|
||||
|
||||
if (isLoading) return <></>;
|
||||
|
||||
if (error) {
|
||||
return <>an error occurred</>;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
19
client/src/features/workspace/services/workspace-service.ts
Normal file
19
client/src/features/workspace/services/workspace-service.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import api from '@/lib/api-client';
|
||||
import { ICurrentUserResponse, IUser } from '@/features/user/types/user.types';
|
||||
import { IWorkspace } from '../types/workspace.types';
|
||||
|
||||
export async function getWorkspace(): Promise<IWorkspace> {
|
||||
const req = await api.get<IWorkspace>('/workspace');
|
||||
return req.data as IWorkspace;
|
||||
}
|
||||
|
||||
export async function getWorkspaceUsers(): Promise<IUser[]> {
|
||||
const req = await api.get<IUser[]>('/workspace/members');
|
||||
return req.data as IUser[];
|
||||
}
|
||||
|
||||
export async function updateWorkspace(data: Partial<IWorkspace>) {
|
||||
const req = await api.post<IWorkspace>('/workspace/update', data);
|
||||
|
||||
return req.data as IWorkspace;
|
||||
}
|
||||
15
client/src/features/workspace/types/workspace.types.ts
Normal file
15
client/src/features/workspace/types/workspace.types.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
export interface IWorkspace {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
logo: string;
|
||||
hostname: string;
|
||||
customDomain: string;
|
||||
enableInvite: boolean;
|
||||
inviteCode: string;
|
||||
settings: any;
|
||||
creatorId: string;
|
||||
pageOrder?:[]
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
Reference in New Issue
Block a user