Merge branch 'chore-admin-file-structure' of github.com:makeplane/plane into chore-admin-file-structure

This commit is contained in:
pablohashescobar 2024-05-06 19:44:25 +05:30
commit 7d63e6ad25
24 changed files with 443 additions and 295 deletions

View File

@ -96,7 +96,7 @@ export const InstanceAIForm: FC<IInstanceAIForm> = (props) => {
<div className="pb-1 text-xl font-medium text-custom-text-100">OpenAI</div> <div className="pb-1 text-xl font-medium text-custom-text-100">OpenAI</div>
<div className="text-sm font-normal text-custom-text-300">If you use ChatGPT, this is for you.</div> <div className="text-sm font-normal text-custom-text-300">If you use ChatGPT, this is for you.</div>
</div> </div>
<div className="grid-col grid w-full grid-cols-1 items-center justify-between gap-x-16 gap-y-8 lg:grid-cols-3"> <div className="grid-col grid w-full grid-cols-1 items-center justify-between gap-x-12 gap-y-8 lg:grid-cols-3">
{aiFormFields.map((field) => ( {aiFormFields.map((field) => (
<ControllerInput <ControllerInput
key={field.key} key={field.key}

View File

@ -1,9 +1,9 @@
import { FC, useState } from "react"; import React, { FC, useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
// hooks // hooks
import { useInstance } from "@/hooks"; import { useInstance } from "@/hooks";
// ui // ui
import { Button, TOAST_TYPE, ToggleSwitch, setToast } from "@plane/ui"; import { Button, CustomSelect, TOAST_TYPE, setToast } from "@plane/ui";
// components // components
import { ControllerInput, TControllerInputFormField } from "components/common"; import { ControllerInput, TControllerInputFormField } from "components/common";
import { SendTestEmailModal } from "./test-email-modal"; import { SendTestEmailModal } from "./test-email-modal";
@ -16,6 +16,14 @@ type IInstanceEmailForm = {
type EmailFormValues = Record<TInstanceEmailConfigurationKeys, string>; type EmailFormValues = Record<TInstanceEmailConfigurationKeys, string>;
type TEmailSecurityKeys = "EMAIL_USE_TLS" | "EMAIL_USE_SSL" | "NONE";
const EMAIL_SECURITY_OPTIONS: { [key in TEmailSecurityKeys]: string } = {
EMAIL_USE_TLS: "TLS",
EMAIL_USE_SSL: "SSL",
NONE: "No email security",
};
export const InstanceEmailForm: FC<IInstanceEmailForm> = (props) => { export const InstanceEmailForm: FC<IInstanceEmailForm> = (props) => {
const { config } = props; const { config } = props;
// states // states
@ -26,8 +34,9 @@ export const InstanceEmailForm: FC<IInstanceEmailForm> = (props) => {
const { const {
handleSubmit, handleSubmit,
watch, watch,
setValue,
control, control,
formState: { errors, isSubmitting }, formState: { errors, isValid, isDirty, isSubmitting },
} = useForm<EmailFormValues>({ } = useForm<EmailFormValues>({
defaultValues: { defaultValues: {
EMAIL_HOST: config["EMAIL_HOST"], EMAIL_HOST: config["EMAIL_HOST"],
@ -35,7 +44,7 @@ export const InstanceEmailForm: FC<IInstanceEmailForm> = (props) => {
EMAIL_HOST_USER: config["EMAIL_HOST_USER"], EMAIL_HOST_USER: config["EMAIL_HOST_USER"],
EMAIL_HOST_PASSWORD: config["EMAIL_HOST_PASSWORD"], EMAIL_HOST_PASSWORD: config["EMAIL_HOST_PASSWORD"],
EMAIL_USE_TLS: config["EMAIL_USE_TLS"], EMAIL_USE_TLS: config["EMAIL_USE_TLS"],
// EMAIL_USE_SSL: config["EMAIL_USE_SSL"], EMAIL_USE_SSL: config["EMAIL_USE_SSL"],
EMAIL_FROM: config["EMAIL_FROM"], EMAIL_FROM: config["EMAIL_FROM"],
}, },
}); });
@ -57,13 +66,26 @@ export const InstanceEmailForm: FC<IInstanceEmailForm> = (props) => {
error: Boolean(errors.EMAIL_PORT), error: Boolean(errors.EMAIL_PORT),
required: true, required: true,
}, },
{
key: "EMAIL_FROM",
type: "text",
label: "Sender email address",
description:
"This is the email address your users will see when getting emails from this instance. You will need to verify this address.",
placeholder: "no-reply@projectplane.so",
error: Boolean(errors.EMAIL_FROM),
required: true,
},
];
const OptionalEmailFormFields: TControllerInputFormField[] = [
{ {
key: "EMAIL_HOST_USER", key: "EMAIL_HOST_USER",
type: "text", type: "text",
label: "Username", label: "Username",
placeholder: "getitdone@projectplane.so", placeholder: "getitdone@projectplane.so",
error: Boolean(errors.EMAIL_HOST_USER), error: Boolean(errors.EMAIL_HOST_USER),
required: true, required: false,
}, },
{ {
key: "EMAIL_HOST_PASSWORD", key: "EMAIL_HOST_PASSWORD",
@ -71,17 +93,7 @@ export const InstanceEmailForm: FC<IInstanceEmailForm> = (props) => {
label: "Password", label: "Password",
placeholder: "Password", placeholder: "Password",
error: Boolean(errors.EMAIL_HOST_PASSWORD), error: Boolean(errors.EMAIL_HOST_PASSWORD),
required: true, required: false,
},
{
key: "EMAIL_FROM",
type: "text",
label: "From address",
description:
"This is the email address your users will see when getting emails from this instance. You will need to verify this address.",
placeholder: "no-reply@projectplane.so",
error: Boolean(errors.EMAIL_FROM),
required: true,
}, },
]; ];
@ -99,11 +111,34 @@ export const InstanceEmailForm: FC<IInstanceEmailForm> = (props) => {
.catch((err) => console.error(err)); .catch((err) => console.error(err));
}; };
const useTLSValue = watch("EMAIL_USE_TLS");
const useSSLValue = watch("EMAIL_USE_SSL");
const emailSecurityKey: TEmailSecurityKeys = useMemo(() => {
if (useTLSValue === "1") return "EMAIL_USE_TLS";
if (useSSLValue === "1") return "EMAIL_USE_SSL";
return "NONE";
}, [useTLSValue, useSSLValue]);
const handleEmailSecurityChange = (key: TEmailSecurityKeys) => {
if (key === "EMAIL_USE_SSL") {
setValue("EMAIL_USE_TLS", "0");
setValue("EMAIL_USE_SSL", "1");
}
if (key === "EMAIL_USE_TLS") {
setValue("EMAIL_USE_TLS", "1");
setValue("EMAIL_USE_SSL", "0");
}
if (key === "NONE") {
setValue("EMAIL_USE_TLS", "0");
setValue("EMAIL_USE_SSL", "0");
}
};
return ( return (
<div className="space-y-8"> <div className="space-y-8">
<div> <div>
<SendTestEmailModal isOpen={isSendTestEmailModalOpen} handleClose={() => setIsSendTestEmailModalOpen(false)} /> <SendTestEmailModal isOpen={isSendTestEmailModalOpen} handleClose={() => setIsSendTestEmailModalOpen(false)} />
<div className="grid-col grid w-full max-w-4xl grid-cols-1 items-center justify-between gap-x-20 gap-y-10 lg:grid-cols-2"> <div className="grid-col grid w-full max-w-4xl grid-cols-1 items-start justify-between gap-10 lg:grid-cols-2">
{emailFormFields.map((field) => ( {emailFormFields.map((field) => (
<ControllerInput <ControllerInput
key={field.key} key={field.key}
@ -117,41 +152,67 @@ export const InstanceEmailForm: FC<IInstanceEmailForm> = (props) => {
required={field.required} required={field.required}
/> />
))} ))}
<div className="flex flex-col gap-1">
<h4 className="text-sm text-custom-text-300">Email security</h4>
<CustomSelect
value={emailSecurityKey}
label={EMAIL_SECURITY_OPTIONS[emailSecurityKey]}
onChange={handleEmailSecurityChange}
buttonClassName="rounded-md border-custom-border-200"
optionsClassName="w-full"
input
>
{Object.entries(EMAIL_SECURITY_OPTIONS).map(([key, value]) => (
<CustomSelect.Option key={key} value={key} className="w-full">
{value}
</CustomSelect.Option>
))}
</CustomSelect>
</div>
</div> </div>
<div className="flex w-full max-w-md flex-col gap-y-10 px-1"> <div className="flex flex-col gap-6 my-6 pt-4 border-t border-custom-border-100">
<div className="mr-8 flex items-center gap-10 pt-4"> <div className="flex w-full max-w-md flex-col gap-y-10 px-1">
<div className="grow"> <div className="mr-8 flex items-center gap-10 pt-4">
<div className="text-sm font-medium text-custom-text-100"> <div className="grow">
Turn TLS {Boolean(parseInt(watch("EMAIL_USE_TLS"))) ? "off" : "on"} <div className="text-sm font-medium text-custom-text-100">Authentication (optional)</div>
</div> <div className="text-xs font-normal text-custom-text-300">
<div className="text-xs font-normal text-custom-text-300"> We recommend setting up a username password for your SMTP server
Use this if your email domain supports TLS. </div>
</div> </div>
</div> </div>
<div className="shrink-0"> </div>
<Controller <div className="grid-col grid w-full max-w-4xl grid-cols-1 items-center justify-between gap-10 lg:grid-cols-2">
{OptionalEmailFormFields.map((field) => (
<ControllerInput
key={field.key}
control={control} control={control}
name="EMAIL_USE_TLS" type={field.type}
render={({ field: { value, onChange } }) => ( name={field.key}
<ToggleSwitch label={field.label}
value={Boolean(parseInt(value))} description={field.description}
onChange={() => { placeholder={field.placeholder}
Boolean(parseInt(value)) === true ? onChange("0") : onChange("1"); error={field.error}
}} required={field.required}
size="sm"
/>
)}
/> />
</div> ))}
</div> </div>
</div> </div>
</div> </div>
<div className="flex max-w-4xl items-center py-1 gap-4"> <div className="flex max-w-4xl items-center py-1 gap-4">
<Button variant="primary" onClick={handleSubmit(onSubmit)} loading={isSubmitting}> <Button
variant="primary"
onClick={handleSubmit(onSubmit)}
loading={isSubmitting}
disabled={!isValid || !isDirty}
>
{isSubmitting ? "Saving..." : "Save changes"} {isSubmitting ? "Saving..." : "Save changes"}
</Button> </Button>
<Button variant="outline-primary" onClick={() => setIsSendTestEmailModalOpen(true)} loading={isSubmitting}> <Button
variant="outline-primary"
onClick={() => setIsSendTestEmailModalOpen(true)}
loading={isSubmitting}
disabled={!isValid}
>
Send test email Send test email
</Button> </Button>
</div> </div>

View File

@ -4,7 +4,7 @@ import { FC, useState, useRef } from "react";
import { Transition } from "@headlessui/react"; import { Transition } from "@headlessui/react";
import Link from "next/link"; import Link from "next/link";
import { ExternalLink, FileText, HelpCircle, MoveLeft } from "lucide-react"; import { ExternalLink, FileText, HelpCircle, MoveLeft } from "lucide-react";
import { DiscordIcon, GithubIcon } from "@plane/ui"; import { DiscordIcon, GithubIcon, Tooltip } from "@plane/ui";
// hooks // hooks
import { useTheme } from "@/hooks"; import { useTheme } from "@/hooks";
// assets // assets
@ -45,39 +45,37 @@ export const HelpSection: FC = () => {
}`} }`}
> >
<div className={`flex items-center gap-1 ${isSidebarCollapsed ? "flex-col justify-center" : "w-full"}`}> <div className={`flex items-center gap-1 ${isSidebarCollapsed ? "flex-col justify-center" : "w-full"}`}>
<a <Tooltip tooltipContent="Redirect to plane" position="right" className="ml-4" disabled={!isSidebarCollapsed}>
href={redirectionLink} <a
className={`relative px-2 py-1.5 flex items-center gap-2 font-medium rounded border border-custom-primary-100/20 bg-custom-primary-100/10 text-xs text-custom-primary-200 whitespace-nowrap`} href={redirectionLink}
> className={`relative px-2 py-1.5 flex items-center gap-2 font-medium rounded border border-custom-primary-100/20 bg-custom-primary-100/10 text-xs text-custom-primary-200 whitespace-nowrap`}
<ExternalLink size={14} /> >
{!isSidebarCollapsed && "Redirect to plane"} <ExternalLink size={14} />
</a> {!isSidebarCollapsed && "Redirect to plane"}
</a>
<button </Tooltip>
type="button" <Tooltip tooltipContent="Help" position={isSidebarCollapsed ? "right" : "top"} className="ml-4">
className={`ml-auto grid place-items-center rounded-md p-1.5 text-custom-text-200 outline-none hover:bg-custom-background-90 hover:text-custom-text-100 ${ <button
isSidebarCollapsed ? "w-full" : "" type="button"
}`} className={`ml-auto grid place-items-center rounded-md p-1.5 text-custom-text-200 outline-none hover:bg-custom-background-90 hover:text-custom-text-100 ${
onClick={() => setIsNeedHelpOpen((prev) => !prev)} isSidebarCollapsed ? "w-full" : ""
> }`}
<HelpCircle className="h-3.5 w-3.5" /> onClick={() => setIsNeedHelpOpen((prev) => !prev)}
</button> >
<button <HelpCircle className="h-3.5 w-3.5" />
type="button" </button>
className="grid place-items-center rounded-md p-1.5 text-custom-text-200 outline-none hover:bg-custom-background-90 hover:text-custom-text-100 md:hidden" </Tooltip>
onClick={() => toggleSidebar(!isSidebarCollapsed)} <Tooltip tooltipContent="Toggle sidebar" position={isSidebarCollapsed ? "right" : "top"} className="ml-4">
> <button
<MoveLeft className="h-3.5 w-3.5" /> type="button"
</button> className={`grid place-items-center rounded-md p-1.5 text-custom-text-200 outline-none hover:bg-custom-background-90 hover:text-custom-text-100 ${
<button isSidebarCollapsed ? "w-full" : ""
type="button" }`}
className={`hidden place-items-center rounded-md p-1.5 text-custom-text-200 outline-none hover:bg-custom-background-90 hover:text-custom-text-100 md:grid ${ onClick={() => toggleSidebar(!isSidebarCollapsed)}
isSidebarCollapsed ? "w-full" : "" >
}`} <MoveLeft className={`h-3.5 w-3.5 duration-300 ${isSidebarCollapsed ? "rotate-180" : ""}`} />
onClick={() => toggleSidebar(!isSidebarCollapsed)} </button>
> </Tooltip>
<MoveLeft className={`h-3.5 w-3.5 duration-300 ${isSidebarCollapsed ? "rotate-180" : ""}`} />
</button>
</div> </div>
<div className="relative"> <div className="relative">

View File

@ -9,7 +9,7 @@ import { Avatar } from "@plane/ui";
// hooks // hooks
import { useTheme, useUser } from "@/hooks"; import { useTheme, useUser } from "@/hooks";
// helpers // helpers
import { API_BASE_URL } from "@/helpers/common.helper"; import { API_BASE_URL, cn } from "@/helpers/common.helper";
// services // services
import { AuthService } from "@/services"; import { AuthService } from "@/services";
@ -32,6 +32,45 @@ export const SidebarDropdown = observer(() => {
const handleSignOut = () => signOut(); const handleSignOut = () => signOut();
const getSidebarMenuItems = () => (
<Menu.Items
className={cn(
"absolute left-0 z-20 mt-1.5 flex w-52 flex-col divide-y divide-custom-sidebar-border-100 rounded-md border border-custom-sidebar-border-200 bg-custom-sidebar-background-100 px-1 py-2 text-xs shadow-lg outline-none",
{
"left-4": isSidebarCollapsed,
}
)}
>
<div className="flex flex-col gap-2.5 pb-2">
<span className="px-2 text-custom-sidebar-text-200">{currentUser?.email}</span>
</div>
<div className="py-2">
<Menu.Item
as="button"
type="button"
className="flex w-full items-center gap-2 rounded px-2 py-1 hover:bg-custom-sidebar-background-80"
onClick={handleThemeSwitch}
>
<Palette className="h-4 w-4 stroke-[1.5]" />
Switch to {resolvedTheme === "dark" ? "light" : "dark"} mode
</Menu.Item>
</div>
<div className="py-2">
<form method="POST" action={`${API_BASE_URL}/api/instances/admins/sign-out/`} onSubmit={handleSignOut}>
<input type="hidden" name="csrfmiddlewaretoken" value={csrfToken} />
<Menu.Item
as="button"
type="submit"
className="flex w-full items-center gap-2 rounded px-2 py-1 hover:bg-custom-sidebar-background-80"
>
<LogOut className="h-4 w-4 stroke-[1.5]" />
Sign out
</Menu.Item>
</form>
</div>
</Menu.Items>
);
useEffect(() => { useEffect(() => {
if (csrfToken === undefined) if (csrfToken === undefined)
authService.requestCSRFToken().then((data) => data?.csrf_token && setCsrfToken(data.csrf_token)); authService.requestCSRFToken().then((data) => data?.csrf_token && setCsrfToken(data.csrf_token));
@ -45,9 +84,30 @@ export const SidebarDropdown = observer(() => {
isSidebarCollapsed ? "justify-center" : "" isSidebarCollapsed ? "justify-center" : ""
}`} }`}
> >
<div className="flex h-7 w-7 flex-shrink-0 items-center justify-center rounded bg-custom-sidebar-background-80"> <Menu as="div" className="flex-shrink-0">
<UserCog2 className="h-5 w-5 text-custom-text-200" /> <Menu.Button
</div> className={cn("grid place-items-center outline-none", {
"cursor-default": !isSidebarCollapsed,
})}
>
<div className="flex h-7 w-7 flex-shrink-0 items-center justify-center rounded bg-custom-sidebar-background-80">
<UserCog2 className="h-5 w-5 text-custom-text-200" />
</div>
</Menu.Button>
{isSidebarCollapsed && (
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
{getSidebarMenuItems()}
</Transition>
)}
</Menu>
{!isSidebarCollapsed && ( {!isSidebarCollapsed && (
<div className="flex w-full gap-2"> <div className="flex w-full gap-2">
@ -78,38 +138,7 @@ export const SidebarDropdown = observer(() => {
leaveFrom="transform opacity-100 scale-100" leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95" leaveTo="transform opacity-0 scale-95"
> >
<Menu.Items {getSidebarMenuItems()}
className="absolute left-0 z-20 mt-1.5 flex w-52 flex-col divide-y
divide-custom-sidebar-border-100 rounded-md border border-custom-sidebar-border-200 bg-custom-sidebar-background-100 px-1 py-2 text-xs shadow-lg outline-none"
>
<div className="flex flex-col gap-2.5 pb-2">
<span className="px-2 text-custom-sidebar-text-200">{currentUser?.email}</span>
</div>
<div className="py-2">
<Menu.Item
as="button"
type="button"
className="flex w-full items-center gap-2 rounded px-2 py-1 hover:bg-custom-sidebar-background-80"
onClick={handleThemeSwitch}
>
<Palette className="h-4 w-4 stroke-[1.5]" />
Switch to {resolvedTheme === "dark" ? "light" : "dark"} mode
</Menu.Item>
</div>
<div className="py-2">
<form method="POST" action={`${API_BASE_URL}/api/instances/admins/sign-out/`} onSubmit={handleSignOut}>
<input type="hidden" name="csrfmiddlewaretoken" value={csrfToken} />
<Menu.Item
as="button"
type="submit"
className="flex w-full items-center gap-2 rounded px-2 py-1 hover:bg-custom-sidebar-background-80"
>
<LogOut className="h-4 w-4 stroke-[1.5]" />
Sign out
</Menu.Item>
</form>
</div>
</Menu.Items>
</Transition> </Transition>
</Menu> </Menu>
)} )}

View File

@ -6,6 +6,8 @@ import { Controller, Control } from "react-hook-form";
import { Input } from "@plane/ui"; import { Input } from "@plane/ui";
// icons // icons
import { Eye, EyeOff } from "lucide-react"; import { Eye, EyeOff } from "lucide-react";
// helpers
import { cn } from "@/helpers/common.helper";
type Props = { type Props = {
control: Control<any>; control: Control<any>;
@ -51,7 +53,9 @@ export const ControllerInput: React.FC<Props> = (props) => {
ref={ref} ref={ref}
hasError={error} hasError={error}
placeholder={placeholder} placeholder={placeholder}
className="w-full rounded-md font-medium" className={cn("w-full rounded-md font-medium", {
"pr-10": type === "password",
})}
/> />
)} )}
/> />
@ -72,7 +76,7 @@ export const ControllerInput: React.FC<Props> = (props) => {
</button> </button>
))} ))}
</div> </div>
{description && <p className="text-xs text-custom-text-400">{description}</p>} {description && <p className="text-xs text-custom-text-300">{description}</p>}
</div> </div>
); );
}; };

View File

@ -11,6 +11,7 @@
"lint": "next lint" "lint": "next lint"
}, },
"dependencies": { "dependencies": {
"@headlessui/react": "^1.7.19",
"@plane/types": "*", "@plane/types": "*",
"@plane/ui": "*", "@plane/ui": "*",
"@tailwindcss/typography": "^0.5.9", "@tailwindcss/typography": "^0.5.9",

View File

@ -111,6 +111,7 @@ class SignInAuthEndpoint(View):
return HttpResponseRedirect(url) return HttpResponseRedirect(url)
except AuthenticationException as e: except AuthenticationException as e:
params = { params = {
"email": email,
"error_code": str(e.error_code), "error_code": str(e.error_code),
"error_message": str(e.error_message), "error_message": str(e.error_message),
} }

View File

@ -333,7 +333,7 @@ SESSION_SAVE_EVERY_REQUEST = True
# Admin Cookie # Admin Cookie
ADMIN_SESSION_COOKIE_NAME = "plane-admin-session-id" ADMIN_SESSION_COOKIE_NAME = "plane-admin-session-id"
ADMIN_SESSION_COOKIE_AGE = 18000 ADMIN_SESSION_COOKIE_AGE = 3600
# CSRF cookies # CSRF cookies
CSRF_COOKIE_SECURE = secure_origins CSRF_COOKIE_SECURE = secure_origins

View File

@ -27,7 +27,7 @@ export interface IUser {
user_timezone: string; user_timezone: string;
username: string; username: string;
last_login_medium: TLoginMediums; last_login_medium: TLoginMediums;
// theme: IUserTheme; theme: IUserTheme;
} }
export interface IUserAccount { export interface IUserAccount {
@ -48,7 +48,7 @@ export type TUserProfile = {
palette: string | undefined; palette: string | undefined;
primary: string | undefined; primary: string | undefined;
background: string | undefined; background: string | undefined;
darkPalette: string | undefined; darkPalette: boolean | undefined;
sidebarText: string | undefined; sidebarText: string | undefined;
sidebarBackground: string | undefined; sidebarBackground: string | undefined;
}; };
@ -80,14 +80,14 @@ export interface IUserSettings {
} }
export interface IUserTheme { export interface IUserTheme {
background: string; text: string | undefined;
text: string; theme: string | undefined;
primary: string; palette: string | undefined;
sidebarBackground: string; primary: string | undefined;
sidebarText: string; background: string | undefined;
darkPalette: boolean; darkPalette: boolean | undefined;
palette: string; sidebarText: string | undefined;
theme: string; sidebarBackground: string | undefined;
} }
export interface IUserLite { export interface IUserLite {

View File

@ -67,7 +67,7 @@ const CustomSelect = (props: ICustomSelectProps) => {
className={`flex items-center justify-between gap-1 text-xs ${ className={`flex items-center justify-between gap-1 text-xs ${
disabled ? "cursor-not-allowed text-custom-text-200" : "cursor-pointer hover:bg-custom-background-80" disabled ? "cursor-not-allowed text-custom-text-200" : "cursor-pointer hover:bg-custom-background-80"
} ${customButtonClassName}`} } ${customButtonClassName}`}
onClick={openDropdown} onClick={isOpen ? closeDropdown : openDropdown}
> >
{customButton} {customButton}
</button> </button>
@ -77,12 +77,17 @@ const CustomSelect = (props: ICustomSelectProps) => {
<button <button
ref={setReferenceElement} ref={setReferenceElement}
type="button" type="button"
className={`flex w-full items-center justify-between gap-1 rounded border-[0.5px] border-custom-border-300 ${ className={cn(
input ? "px-3 py-2 text-sm" : "px-2 py-1 text-xs" "flex w-full items-center justify-between gap-1 rounded border-[0.5px] border-custom-border-300",
} ${ {
disabled ? "cursor-not-allowed text-custom-text-200" : "cursor-pointer hover:bg-custom-background-80" "px-3 py-2 text-sm": input,
} ${buttonClassName}`} "px-2 py-1 text-xs": !input,
onClick={openDropdown} "cursor-not-allowed text-custom-text-200": disabled,
"cursor-pointer hover:bg-custom-background-80": !disabled,
},
buttonClassName
)}
onClick={isOpen ? closeDropdown : openDropdown}
> >
{label} {label}
{!noChevron && !disabled && <ChevronDown className="h-3 w-3" aria-hidden="true" />} {!noChevron && !disabled && <ChevronDown className="h-3 w-3" aria-hidden="true" />}

View File

@ -48,7 +48,15 @@ export const SignInAuthRoot = observer(() => {
error_code?.toString() as EAuthenticationErrorCodes, error_code?.toString() as EAuthenticationErrorCodes,
error_message?.toString() error_message?.toString()
); );
if (errorhandler) setErrorInfo(errorhandler); if (errorhandler) {
if (errorhandler?.type === EErrorAlertType.TOAST_ALERT) {
setToast({
type: TOAST_TYPE.ERROR,
title: errorhandler?.title,
message: errorhandler?.message as string,
});
} else setErrorInfo(errorhandler);
}
} }
}, [error_code, error_message]); }, [error_code, error_message]);

View File

@ -52,7 +52,15 @@ export const SignUpAuthRoot: FC = observer(() => {
error_code?.toString() as EAuthenticationErrorCodes, error_code?.toString() as EAuthenticationErrorCodes,
error_message?.toString() error_message?.toString()
); );
if (errorhandler) setErrorInfo(errorhandler); if (errorhandler) {
if (errorhandler?.type === EErrorAlertType.TOAST_ALERT) {
setToast({
type: TOAST_TYPE.ERROR,
title: errorhandler?.title,
message: errorhandler?.message as string,
});
} else setErrorInfo(errorhandler);
}
} }
}, [error_code, error_message]); }, [error_code, error_message]);

View File

@ -2,10 +2,12 @@ import React, { FC, useEffect, useState } from "react";
import { Command } from "cmdk"; import { Command } from "cmdk";
import { observer } from "mobx-react"; import { observer } from "mobx-react";
import { useTheme } from "next-themes"; import { useTheme } from "next-themes";
// icons
import { Settings } from "lucide-react"; import { Settings } from "lucide-react";
import { TOAST_TYPE, setToast } from "@plane/ui";
// constants // constants
import { THEME_OPTIONS } from "@/constants/themes"; import { THEME_OPTIONS } from "@/constants/themes";
// hooks
import { useUserProfile } from "@/hooks/store";
type Props = { type Props = {
closePalette: () => void; closePalette: () => void;
@ -13,20 +15,20 @@ type Props = {
export const CommandPaletteThemeActions: FC<Props> = observer((props) => { export const CommandPaletteThemeActions: FC<Props> = observer((props) => {
const { closePalette } = props; const { closePalette } = props;
const { setTheme } = useTheme();
// hooks
const { updateUserTheme } = useUserProfile();
// states // states
const [mounted, setMounted] = useState(false); const [mounted, setMounted] = useState(false);
// hooks
const { setTheme } = useTheme();
const updateUserTheme = async (newTheme: string) => { const updateTheme = async (newTheme: string) => {
setTheme(newTheme); setTheme(newTheme);
return updateUserTheme({ theme: newTheme }).catch(() => {
// return updateUserProfile({ theme: newTheme }).catch(() => { setToast({
// setToast({ type: TOAST_TYPE.ERROR,
// type: TOAST_TYPE.ERROR, title: "Failed to save user theme settings!",
// title: "Failed to save user theme settings!", });
// }); });
// });
}; };
// useEffect only runs on the client, so now we can safely show the UI // useEffect only runs on the client, so now we can safely show the UI
@ -42,7 +44,7 @@ export const CommandPaletteThemeActions: FC<Props> = observer((props) => {
<Command.Item <Command.Item
key={theme.value} key={theme.value}
onSelect={() => { onSelect={() => {
updateUserTheme(theme.value); updateTheme(theme.value);
closePalette(); closePalette();
}} }}
className="focus:outline-none" className="focus:outline-none"

View File

@ -4,9 +4,9 @@ import { Controller, useForm } from "react-hook-form";
// types // types
import { IUserTheme } from "@plane/types"; import { IUserTheme } from "@plane/types";
// ui // ui
import { Button, InputColorPicker } from "@plane/ui"; import { Button, InputColorPicker, setPromiseToast } from "@plane/ui";
// hooks // hooks
import { useUser } from "@/hooks/store"; import { useUserProfile } from "@/hooks/store";
const inputRules = { const inputRules = {
required: "Background color is required", required: "Background color is required",
@ -25,13 +25,9 @@ const inputRules = {
}; };
export const CustomThemeSelector: React.FC = observer(() => { export const CustomThemeSelector: React.FC = observer(() => {
const {
userProfile: { data: userProfile },
} = useUser();
const userTheme: any = userProfile?.theme;
// hooks
const { setTheme } = useTheme(); const { setTheme } = useTheme();
// hooks
const { data: userProfile, updateUserTheme } = useUserProfile();
const { const {
control, control,
@ -40,17 +36,18 @@ export const CustomThemeSelector: React.FC = observer(() => {
watch, watch,
} = useForm<IUserTheme>({ } = useForm<IUserTheme>({
defaultValues: { defaultValues: {
background: userTheme?.background !== "" ? userTheme?.background : "#0d101b", background: userProfile?.theme?.background !== "" ? userProfile?.theme?.background : "#0d101b",
text: userTheme?.text !== "" ? userTheme?.text : "#c5c5c5", text: userProfile?.theme?.text !== "" ? userProfile?.theme?.text : "#c5c5c5",
primary: userTheme?.primary !== "" ? userTheme?.primary : "#3f76ff", primary: userProfile?.theme?.primary !== "" ? userProfile?.theme?.primary : "#3f76ff",
sidebarBackground: userTheme?.sidebarBackground !== "" ? userTheme?.sidebarBackground : "#0d101b", sidebarBackground:
sidebarText: userTheme?.sidebarText !== "" ? userTheme?.sidebarText : "#c5c5c5", userProfile?.theme?.sidebarBackground !== "" ? userProfile?.theme?.sidebarBackground : "#0d101b",
darkPalette: userTheme?.darkPalette || false, sidebarText: userProfile?.theme?.sidebarText !== "" ? userProfile?.theme?.sidebarText : "#c5c5c5",
palette: userTheme?.palette !== "" ? userTheme?.palette : "", darkPalette: userProfile?.theme?.darkPalette || false,
palette: userProfile?.theme?.palette !== "" ? userProfile?.theme?.palette : "",
}, },
}); });
const handleUpdateTheme = async (formData: any) => { const handleUpdateTheme = async (formData: Partial<IUserTheme>) => {
const payload: IUserTheme = { const payload: IUserTheme = {
background: formData.background, background: formData.background,
text: formData.text, text: formData.text,
@ -61,12 +58,22 @@ export const CustomThemeSelector: React.FC = observer(() => {
palette: `${formData.background},${formData.text},${formData.primary},${formData.sidebarBackground},${formData.sidebarText}`, palette: `${formData.background},${formData.text},${formData.primary},${formData.sidebarBackground},${formData.sidebarText}`,
theme: "custom", theme: "custom",
}; };
setTheme("custom"); setTheme("custom");
console.log(payload); const updateCurrentUserThemePromise = updateUserTheme(payload);
setPromiseToast(updateCurrentUserThemePromise, {
loading: "Updating theme...",
success: {
title: "Success!",
message: () => "Theme updated successfully!",
},
error: {
title: "Error!",
message: () => "Failed to Update the theme",
},
});
// return updateUserProfile({ theme: payload }); return;
}; };
const handleValueChange = (val: string | undefined, onChange: any) => { const handleValueChange = (val: string | undefined, onChange: any) => {

View File

@ -1,3 +1,5 @@
import { ReactNode } from "react";
export enum EPageTypes { export enum EPageTypes {
"PUBLIC" = "PUBLIC", "PUBLIC" = "PUBLIC",
"NON_AUTHENTICATED" = "NON_AUTHENTICATED", "NON_AUTHENTICATED" = "NON_AUTHENTICATED",
@ -35,11 +37,6 @@ export enum EAuthenticationErrorCodes {
REQUIRED_EMAIL_PASSWORD_FIRST_NAME = "REQUIRED_EMAIL_PASSWORD_FIRST_NAME", REQUIRED_EMAIL_PASSWORD_FIRST_NAME = "REQUIRED_EMAIL_PASSWORD_FIRST_NAME",
REQUIRED_EMAIL_PASSWORD = "REQUIRED_EMAIL_PASSWORD", REQUIRED_EMAIL_PASSWORD = "REQUIRED_EMAIL_PASSWORD",
EMAIL_CODE_REQUIRED = "EMAIL_CODE_REQUIRED", EMAIL_CODE_REQUIRED = "EMAIL_CODE_REQUIRED",
// inline local errors
INLINE_EMAIL = "INLINE_EMAIL",
INLINE_PASSWORD = "INLINE_PASSWORD",
INLINE_FIRST_NAME = "INLINE_FIRST_NAME",
INLINE_EMAIL_CODE = "INLINE_EMAIL_CODE",
} }
export enum EErrorAlertType { export enum EErrorAlertType {
@ -51,7 +48,64 @@ export enum EErrorAlertType {
INLINE_EMAIL_CODE = "INLINE_EMAIL_CODE", INLINE_EMAIL_CODE = "INLINE_EMAIL_CODE",
} }
export type TAuthErrorInfo = { type: EErrorAlertType; message: string }; export type TAuthErrorInfo = { type: EErrorAlertType; title: string; message: ReactNode };
const errorCodeMessages: { [key in EAuthenticationErrorCodes]: { title: string; message: ReactNode } } = {
[EAuthenticationErrorCodes.INSTANCE_NOT_CONFIGURED]: {
title: `Instance not configured`,
message: `Instance not configured. Please contact your administrator.`,
},
[EAuthenticationErrorCodes.SMTP_NOT_CONFIGURED]: {
title: `SMTP not configured`,
message: `SMTP not configured. Please contact your administrator.`,
},
[EAuthenticationErrorCodes.AUTHENTICATION_FAILED]: {
title: `Authentication failed.`,
message: `Authentication failed. Please try again.`,
},
[EAuthenticationErrorCodes.INVALID_TOKEN]: { title: `Invalid token.`, message: `Invalid token. Please try again.` },
[EAuthenticationErrorCodes.EXPIRED_TOKEN]: { title: `Expired token.`, message: `Expired token. Please try again.` },
[EAuthenticationErrorCodes.IMPROPERLY_CONFIGURED]: {
title: `Improperly configured.`,
message: `Improperly configured. Please contact your administrator.`,
},
[EAuthenticationErrorCodes.OAUTH_PROVIDER_ERROR]: {
title: `OAuth provider error.`,
message: `OAuth provider error. Please try again.`,
},
[EAuthenticationErrorCodes.INVALID_EMAIL]: {
title: `Invalid email.`,
message: `Invalid email. Please try again.`,
},
[EAuthenticationErrorCodes.INVALID_PASSWORD]: {
title: `Invalid password.`,
message: `Invalid password. Please try again.`,
},
[EAuthenticationErrorCodes.USER_DOES_NOT_EXIST]: {
title: `User does not exist.`,
message: `User does not exist. Please try again.`,
},
[EAuthenticationErrorCodes.ADMIN_ALREADY_EXIST]: {
title: `Admin already exists.`,
message: `Admin already exists. Please try again.`,
},
[EAuthenticationErrorCodes.USER_ALREADY_EXIST]: {
title: `User already exists.`,
message: `User already exists. Please try again.`,
},
[EAuthenticationErrorCodes.REQUIRED_EMAIL_PASSWORD_FIRST_NAME]: {
title: `Missing fields.`,
message: `Email, password, and first name are required.`,
},
[EAuthenticationErrorCodes.REQUIRED_EMAIL_PASSWORD]: {
title: `Missing fields.`,
message: `Email and password are required.`,
},
[EAuthenticationErrorCodes.EMAIL_CODE_REQUIRED]: {
title: `Missing fields.`,
message: `Email and code are required.`,
},
};
export const authErrorHandler = ( export const authErrorHandler = (
errorCode: EAuthenticationErrorCodes, errorCode: EAuthenticationErrorCodes,
@ -67,49 +121,28 @@ export const authErrorHandler = (
EAuthenticationErrorCodes.OAUTH_PROVIDER_ERROR, EAuthenticationErrorCodes.OAUTH_PROVIDER_ERROR,
]; ];
const bannerAlertErrorCodes = [ const bannerAlertErrorCodes = [
EAuthenticationErrorCodes.INVALID_EMAIL,
EAuthenticationErrorCodes.INVALID_PASSWORD,
EAuthenticationErrorCodes.USER_DOES_NOT_EXIST, EAuthenticationErrorCodes.USER_DOES_NOT_EXIST,
EAuthenticationErrorCodes.ADMIN_ALREADY_EXIST, EAuthenticationErrorCodes.ADMIN_ALREADY_EXIST,
EAuthenticationErrorCodes.USER_ALREADY_EXIST, EAuthenticationErrorCodes.USER_ALREADY_EXIST,
EAuthenticationErrorCodes.REQUIRED_EMAIL_PASSWORD_FIRST_NAME,
EAuthenticationErrorCodes.REQUIRED_EMAIL_PASSWORD,
EAuthenticationErrorCodes.EMAIL_CODE_REQUIRED,
]; ];
const inlineFirstNameErrorCodes = [EAuthenticationErrorCodes.INLINE_FIRST_NAME];
const inlineEmailErrorCodes = [EAuthenticationErrorCodes.INLINE_EMAIL];
const inlineEmailCodeErrorCodes = [EAuthenticationErrorCodes.INLINE_EMAIL_CODE];
const inlinePasswordErrorCodes = [EAuthenticationErrorCodes.INLINE_PASSWORD];
if (toastAlertErrorCodes.includes(errorCode)) if (toastAlertErrorCodes.includes(errorCode))
return { return {
type: EErrorAlertType.TOAST_ALERT, type: EErrorAlertType.TOAST_ALERT,
message: errorMessage || "Something went wrong. Please try again.", title: errorCodeMessages[errorCode]?.title || "Error",
message: errorMessage || errorCodeMessages[errorCode]?.message || "Something went wrong. Please try again.",
}; };
if (bannerAlertErrorCodes.includes(errorCode)) if (bannerAlertErrorCodes.includes(errorCode))
return { return {
type: EErrorAlertType.BANNER_ALERT, type: EErrorAlertType.BANNER_ALERT,
message: errorMessage || "Something went wrong. Please try again.", title: errorCodeMessages[errorCode]?.title || "Error",
}; message: errorMessage || errorCodeMessages[errorCode]?.message || "Something went wrong. Please try again.",
if (inlineFirstNameErrorCodes.includes(errorCode))
return {
type: EErrorAlertType.INLINE_FIRST_NAME,
message: errorMessage || "Something went wrong. Please try again.",
};
if (inlineEmailErrorCodes.includes(errorCode))
return {
type: EErrorAlertType.INLINE_EMAIL,
message: errorMessage || "Something went wrong. Please try again.",
};
if (inlinePasswordErrorCodes.includes(errorCode))
return {
type: EErrorAlertType.INLINE_PASSWORD,
message: errorMessage || "Something went wrong. Please try again.",
};
if (inlineEmailCodeErrorCodes.includes(errorCode))
return {
type: EErrorAlertType.INLINE_EMAIL_CODE,
message: errorMessage || "Something went wrong. Please try again.",
}; };
return undefined; return undefined;

View File

@ -2,8 +2,6 @@ import { useEffect, useRef, useState } from "react";
import { observer } from "mobx-react"; import { observer } from "mobx-react";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { useTheme } from "next-themes";
import { mutate } from "swr";
// icons // icons
import { ChevronLeft, LogOut, MoveLeft, Plus, UserPlus } from "lucide-react"; import { ChevronLeft, LogOut, MoveLeft, Plus, UserPlus } from "lucide-react";
// ui // ui
@ -11,7 +9,7 @@ import { TOAST_TYPE, Tooltip, setToast } from "@plane/ui";
// constants // constants
import { PROFILE_ACTION_LINKS } from "@/constants/profile"; import { PROFILE_ACTION_LINKS } from "@/constants/profile";
// hooks // hooks
import { useAppTheme, useUser, useWorkspace } from "@/hooks/store"; import { useAppTheme, useUser, useUserSettings, useWorkspace } from "@/hooks/store";
import useOutsideClickDetector from "@/hooks/use-outside-click-detector"; import useOutsideClickDetector from "@/hooks/use-outside-click-detector";
import { usePlatformOS } from "@/hooks/use-platform-os"; import { usePlatformOS } from "@/hooks/use-platform-os";
@ -35,22 +33,19 @@ export const ProfileLayoutSidebar = observer(() => {
const [isSigningOut, setIsSigningOut] = useState(false); const [isSigningOut, setIsSigningOut] = useState(false);
// router // router
const router = useRouter(); const router = useRouter();
// next themes
const { setTheme } = useTheme();
// store hooks // store hooks
const { sidebarCollapsed, toggleSidebar } = useAppTheme(); const { sidebarCollapsed, toggleSidebar } = useAppTheme();
const { data: currentUser, signOut } = useUser(); const { data: currentUser, signOut } = useUser();
// const { currentUserSettings } = useUser(); const { data: currentUserSettings } = useUserSettings();
const { workspaces } = useWorkspace(); const { workspaces } = useWorkspace();
const { isMobile } = usePlatformOS(); const { isMobile } = usePlatformOS();
const workspacesList = Object.values(workspaces ?? {}); const workspacesList = Object.values(workspaces ?? {});
// redirect url for normal mode // redirect url for normal mode
// FIXME:
const redirectWorkspaceSlug = const redirectWorkspaceSlug =
// currentUserSettings?.workspace?.last_workspace_slug || currentUserSettings?.workspace?.last_workspace_slug ||
// currentUserSettings?.workspace?.fallback_workspace_slug || currentUserSettings?.workspace?.fallback_workspace_slug ||
""; "";
const ref = useRef<HTMLDivElement>(null); const ref = useRef<HTMLDivElement>(null);

View File

@ -5,7 +5,7 @@ import { useTheme } from "next-themes";
// helpers // helpers
import { applyTheme, unsetCustomCssVariables } from "@/helpers/theme.helper"; import { applyTheme, unsetCustomCssVariables } from "@/helpers/theme.helper";
// hooks // hooks
import { useAppRouter, useAppTheme, useUser } from "@/hooks/store"; import { useAppRouter, useAppTheme, useUserProfile } from "@/hooks/store";
type TStoreWrapper = { type TStoreWrapper = {
children: ReactNode; children: ReactNode;
@ -20,9 +20,7 @@ const StoreWrapper: FC<TStoreWrapper> = observer((props) => {
// store hooks // store hooks
const { setQuery } = useAppRouter(); const { setQuery } = useAppRouter();
const { sidebarCollapsed, toggleSidebar } = useAppTheme(); const { sidebarCollapsed, toggleSidebar } = useAppTheme();
const { const { data: userProfile } = useUserProfile();
userProfile: { data: userProfile },
} = useUser();
// states // states
const [dom, setDom] = useState<undefined | HTMLElement>(); const [dom, setDom] = useState<undefined | HTMLElement>();
@ -40,14 +38,19 @@ const StoreWrapper: FC<TStoreWrapper> = observer((props) => {
* Setting up the theme of the user by fetching it from local storage * Setting up the theme of the user by fetching it from local storage
*/ */
useEffect(() => { useEffect(() => {
if (!userProfile) return; if (!userProfile?.theme?.theme) return;
if (window) setDom(window.document?.querySelector<HTMLElement>("[data-theme='custom']") || undefined); if (window) setDom(() => window.document?.querySelector<HTMLElement>("[data-theme='custom']") || undefined);
setTheme(userProfile?.theme?.theme || "system"); setTheme(userProfile?.theme?.theme || "system");
if (userProfile?.theme?.theme === "custom" && userProfile?.theme?.palette && dom) if (userProfile?.theme?.theme === "custom" && userProfile?.theme?.palette && dom)
applyTheme(userProfile?.theme?.palette, false); applyTheme(
userProfile?.theme?.palette !== ",,,,"
? userProfile?.theme?.palette
: "#0d101b,#c5c5c5,#3f76ff,#0d101b,#c5c5c5",
false
);
else unsetCustomCssVariables(); else unsetCustomCssVariables();
}, [userProfile, setTheme, dom]); }, [userProfile, userProfile?.theme?.theme, userProfile?.theme?.palette, setTheme, dom]);
useEffect(() => { useEffect(() => {
if (!router.query) return; if (!router.query) return;

View File

@ -2,64 +2,55 @@ import { useEffect, useState, ReactElement } from "react";
import { observer } from "mobx-react"; import { observer } from "mobx-react";
import { useTheme } from "next-themes"; import { useTheme } from "next-themes";
// ui // ui
import { import { Spinner, setPromiseToast } from "@plane/ui";
Spinner,
// setPromiseToast
} from "@plane/ui";
// components // components
import { CustomThemeSelector, ThemeSwitch, PageHead } from "@/components/core"; import { CustomThemeSelector, ThemeSwitch, PageHead } from "@/components/core";
// constants // constants
import { I_THEME_OPTION, THEME_OPTIONS } from "@/constants/themes"; import { I_THEME_OPTION, THEME_OPTIONS } from "@/constants/themes";
// hooks // hooks
import { useUser } from "@/hooks/store"; import { useUserProfile } from "@/hooks/store";
// layouts // layouts
import { ProfilePreferenceSettingsLayout } from "@/layouts/settings-layout/profile/preferences"; import { ProfilePreferenceSettingsLayout } from "@/layouts/settings-layout/profile/preferences";
// type // type
import { NextPageWithLayout } from "@/lib/types"; import { NextPageWithLayout } from "@/lib/types";
const ProfilePreferencesThemePage: NextPageWithLayout = observer(() => { const ProfilePreferencesThemePage: NextPageWithLayout = observer(() => {
const { setTheme } = useTheme();
// states // states
const [currentTheme, setCurrentTheme] = useState<I_THEME_OPTION | null>(null); const [currentTheme, setCurrentTheme] = useState<I_THEME_OPTION | null>(null);
// store hooks
const {
data: currentUser,
userProfile: { data: userProfile },
} = useUser();
// computed
const userTheme = userProfile?.theme;
// hooks // hooks
const { setTheme } = useTheme(); const { data: userProfile, updateUserTheme } = useUserProfile();
useEffect(() => { useEffect(() => {
if (userTheme) { if (userProfile?.theme?.theme) {
const userThemeOption = THEME_OPTIONS.find((t) => t.value === userTheme?.theme); const userThemeOption = THEME_OPTIONS.find((t) => t.value === userProfile?.theme?.theme);
if (userThemeOption) { if (userThemeOption) {
setCurrentTheme(userThemeOption); setCurrentTheme(userThemeOption);
} }
} }
}, [userTheme]); }, [userProfile?.theme?.theme]);
const handleThemeChange = (themeOption: I_THEME_OPTION) => { const handleThemeChange = (themeOption: I_THEME_OPTION) => {
setTheme(themeOption.value); setTheme(themeOption.value);
// const updateCurrentUserThemePromise = updateCurrentUserTheme(themeOption.value); const updateCurrentUserThemePromise = updateUserTheme({ theme: themeOption.value });
// setPromiseToast(updateCurrentUserThemePromise, { setPromiseToast(updateCurrentUserThemePromise, {
// loading: "Updating theme...", loading: "Updating theme...",
// success: { success: {
// title: "Success!", title: "Success!",
// message: () => "Theme updated successfully!", message: () => "Theme updated successfully!",
// }, },
// error: { error: {
// title: "Error!", title: "Error!",
// message: () => "Failed to Update the theme", message: () => "Failed to Update the theme",
// }, },
// }); });
}; };
return ( return (
<> <>
<PageHead title="Profile - Theme Prefrence" /> <PageHead title="Profile - Theme Prefrence" />
{currentUser ? ( {userProfile ? (
<div className="mx-auto mt-10 h-full w-full overflow-y-auto md:px-6 px-4 pb-8 md:mt-14 lg:px-20 vertical-scrollbar scrollbar-md"> <div className="mx-auto mt-10 h-full w-full overflow-y-auto md:px-6 px-4 pb-8 md:mt-14 lg:px-20 vertical-scrollbar scrollbar-md">
<div className="flex items-center border-b border-custom-border-100 pb-3.5"> <div className="flex items-center border-b border-custom-border-100 pb-3.5">
<h3 className="text-xl font-medium">Preferences</h3> <h3 className="text-xl font-medium">Preferences</h3>
@ -73,7 +64,7 @@ const ProfilePreferencesThemePage: NextPageWithLayout = observer(() => {
<ThemeSwitch value={currentTheme} onChange={handleThemeChange} /> <ThemeSwitch value={currentTheme} onChange={handleThemeChange} />
</div> </div>
</div> </div>
{userTheme?.theme === "custom" && <CustomThemeSelector />} {userProfile?.theme?.theme === "custom" && <CustomThemeSelector />}
</div> </div>
) : ( ) : (
<div className="grid h-full w-full place-items-center px-4 sm:px-0"> <div className="grid h-full w-full place-items-center px-4 sm:px-0">

View File

@ -25,13 +25,15 @@ export class AuthService extends APIService {
}); });
} }
signUpEmailCheck = async (data: IEmailCheckData): Promise<IEmailCheckResponse> => this.post("/auth/sign-up/email-check/", data, { headers: {} }) signUpEmailCheck = async (data: IEmailCheckData): Promise<IEmailCheckResponse> =>
this.post("/auth/sign-up/email-check/", data, { headers: {} })
.then((response) => response?.data) .then((response) => response?.data)
.catch((error) => { .catch((error) => {
throw error?.response?.data; throw error?.response?.data;
}); });
signInEmailCheck = async (data: IEmailCheckData): Promise<IEmailCheckResponse> => this.post("/auth/sign-in/email-check/", data, { headers: {} }) signInEmailCheck = async (data: IEmailCheckData): Promise<IEmailCheckResponse> =>
this.post("/auth/sign-in/email-check/", data, { headers: {} })
.then((response) => response?.data) .then((response) => response?.data)
.catch((error) => { .catch((error) => {
throw error?.response?.data; throw error?.response?.data;

View File

@ -77,6 +77,9 @@ export class RootStore {
} }
resetOnSignOut() { resetOnSignOut() {
// handling the system theme when user logged out from the app
localStorage.setItem("theme", "system");
this.workspaceRoot = new WorkspaceRootStore(this); this.workspaceRoot = new WorkspaceRootStore(this);
this.projectRoot = new ProjectRootStore(this); this.projectRoot = new ProjectRootStore(this);
this.memberRoot = new MemberRootStore(this); this.memberRoot = new MemberRootStore(this);

View File

@ -1,18 +1,15 @@
// mobx
import { action, observable, makeObservable } from "mobx"; import { action, observable, makeObservable } from "mobx";
// helper // store types
import { applyTheme, unsetCustomCssVariables } from "@/helpers/theme.helper"; import { RootStore } from "@/store/root.store";
export interface IThemeStore { export interface IThemeStore {
// observables // observables
theme: string | null;
sidebarCollapsed: boolean | undefined; sidebarCollapsed: boolean | undefined;
profileSidebarCollapsed: boolean | undefined; profileSidebarCollapsed: boolean | undefined;
workspaceAnalyticsSidebarCollapsed: boolean | undefined; workspaceAnalyticsSidebarCollapsed: boolean | undefined;
issueDetailSidebarCollapsed: boolean | undefined; issueDetailSidebarCollapsed: boolean | undefined;
// actions // actions
toggleSidebar: (collapsed?: boolean) => void; toggleSidebar: (collapsed?: boolean) => void;
setTheme: (theme: any) => void;
toggleProfileSidebar: (collapsed?: boolean) => void; toggleProfileSidebar: (collapsed?: boolean) => void;
toggleWorkspaceAnalyticsSidebar: (collapsed?: boolean) => void; toggleWorkspaceAnalyticsSidebar: (collapsed?: boolean) => void;
toggleIssueDetailSidebar: (collapsed?: boolean) => void; toggleIssueDetailSidebar: (collapsed?: boolean) => void;
@ -21,31 +18,23 @@ export interface IThemeStore {
export class ThemeStore implements IThemeStore { export class ThemeStore implements IThemeStore {
// observables // observables
sidebarCollapsed: boolean | undefined = undefined; sidebarCollapsed: boolean | undefined = undefined;
theme: string | null = null;
profileSidebarCollapsed: boolean | undefined = undefined; profileSidebarCollapsed: boolean | undefined = undefined;
workspaceAnalyticsSidebarCollapsed: boolean | undefined = undefined; workspaceAnalyticsSidebarCollapsed: boolean | undefined = undefined;
issueDetailSidebarCollapsed: boolean | undefined = undefined; issueDetailSidebarCollapsed: boolean | undefined = undefined;
// root store
rootStore;
constructor(_rootStore: any | null = null) { constructor(private store: RootStore) {
makeObservable(this, { makeObservable(this, {
// observable // observable
sidebarCollapsed: observable.ref, sidebarCollapsed: observable.ref,
theme: observable.ref,
profileSidebarCollapsed: observable.ref, profileSidebarCollapsed: observable.ref,
workspaceAnalyticsSidebarCollapsed: observable.ref, workspaceAnalyticsSidebarCollapsed: observable.ref,
issueDetailSidebarCollapsed: observable.ref, issueDetailSidebarCollapsed: observable.ref,
// action // action
toggleSidebar: action, toggleSidebar: action,
setTheme: action,
toggleProfileSidebar: action, toggleProfileSidebar: action,
toggleWorkspaceAnalyticsSidebar: action, toggleWorkspaceAnalyticsSidebar: action,
toggleIssueDetailSidebar: action, toggleIssueDetailSidebar: action,
// computed
}); });
// root store
this.rootStore = _rootStore;
} }
/** /**
@ -95,30 +84,4 @@ export class ThemeStore implements IThemeStore {
} }
localStorage.setItem("issue_detail_sidebar_collapsed", this.issueDetailSidebarCollapsed.toString()); localStorage.setItem("issue_detail_sidebar_collapsed", this.issueDetailSidebarCollapsed.toString());
}; };
/**
* Sets the user theme and applies it to the platform
* @param _theme
*/
setTheme = async (_theme: { theme: any }) => {
try {
const currentTheme: string = _theme?.theme?.theme?.toString();
// updating the local storage theme value
localStorage.setItem("theme", currentTheme);
// updating the mobx theme value
this.theme = currentTheme;
// applying the theme to platform if the selected theme is custom
if (currentTheme === "custom") {
const themeSettings = this.rootStore.user.currentUserSettings || null;
applyTheme(
themeSettings?.theme?.palette !== ",,,,"
? themeSettings?.theme?.palette
: "#0d101b,#c5c5c5,#3f76ff,#0d101b,#c5c5c5",
themeSettings?.theme?.darkPalette
);
} else unsetCustomCssVariables();
} catch (error) {
console.error("setting user theme error", error);
}
};
} }

View File

@ -54,7 +54,7 @@ export class UserStore implements IUserStore {
constructor(private store: RootStore) { constructor(private store: RootStore) {
// stores // stores
this.userProfile = new ProfileStore(); this.userProfile = new ProfileStore(store);
this.userSettings = new UserSettingsStore(); this.userSettings = new UserSettingsStore();
this.membership = new UserMembershipStore(store); this.membership = new UserMembershipStore(store);
// service // service

View File

@ -1,9 +1,11 @@
import cloneDeep from "lodash/cloneDeep";
import set from "lodash/set"; import set from "lodash/set";
import { action, makeObservable, observable, runInAction } from "mobx"; import { action, makeObservable, observable, runInAction } from "mobx";
// services // services
import { UserService } from "services/user.service"; import { UserService } from "services/user.service";
// types // types
import { TUserProfile } from "@plane/types"; import { IUserTheme, TUserProfile } from "@plane/types";
import { RootStore } from "@/store/root.store";
type TError = { type TError = {
status: string; status: string;
@ -20,6 +22,7 @@ export interface IUserProfileStore {
updateUserProfile: (data: Partial<TUserProfile>) => Promise<TUserProfile | undefined>; updateUserProfile: (data: Partial<TUserProfile>) => Promise<TUserProfile | undefined>;
updateUserOnBoard: () => Promise<TUserProfile | undefined>; updateUserOnBoard: () => Promise<TUserProfile | undefined>;
updateTourCompleted: () => Promise<TUserProfile | undefined>; updateTourCompleted: () => Promise<TUserProfile | undefined>;
updateUserTheme: (data: Partial<IUserTheme>) => Promise<TUserProfile | undefined>;
} }
export class ProfileStore implements IUserProfileStore { export class ProfileStore implements IUserProfileStore {
@ -59,7 +62,7 @@ export class ProfileStore implements IUserProfileStore {
// services // services
userService: UserService; userService: UserService;
constructor() { constructor(public store: RootStore) {
makeObservable(this, { makeObservable(this, {
// observables // observables
isLoading: observable.ref, isLoading: observable.ref,
@ -70,6 +73,7 @@ export class ProfileStore implements IUserProfileStore {
updateUserProfile: action, updateUserProfile: action,
updateUserOnBoard: action, updateUserOnBoard: action,
updateTourCompleted: action, updateTourCompleted: action,
updateUserTheme: action,
}); });
// services // services
this.userService = new UserService(); this.userService = new UserService();
@ -179,4 +183,34 @@ export class ProfileStore implements IUserProfileStore {
throw error; throw error;
} }
}; };
/**
* @description updates the user theme
* @returns @returns {Promise<TUserProfile | undefined>}
*/
updateUserTheme = async (data: Partial<IUserTheme>) => {
const currentProfileTheme = cloneDeep(this.data.theme);
try {
runInAction(() => {
Object.keys(data).forEach((key: string) => {
const userKey: keyof IUserTheme = key as keyof IUserTheme;
if (this.data.theme) set(this.data.theme, userKey, data[userKey]);
});
});
const userProfile = await this.userService.updateCurrentUserProfile({ theme: this.data.theme });
return userProfile;
} catch (error) {
runInAction(() => {
Object.keys(data).forEach((key: string) => {
const userKey: keyof IUserTheme = key as keyof IUserTheme;
if (currentProfileTheme) set(this.data.theme, userKey, currentProfileTheme[userKey]);
});
this.error = {
status: "user-profile-theme-update-error",
message: "Failed to update user profile theme",
};
});
throw error;
}
};
} }

View File

@ -1370,7 +1370,7 @@
resolved "https://registry.yarnpkg.com/@floating-ui/utils/-/utils-0.2.1.tgz#16308cea045f0fc777b6ff20a9f25474dd8293d2" resolved "https://registry.yarnpkg.com/@floating-ui/utils/-/utils-0.2.1.tgz#16308cea045f0fc777b6ff20a9f25474dd8293d2"
integrity sha512-9TANp6GPoMtYzQdt54kfAyMmz1+osLlXdg2ENroU7zzrtflTLrrC/lgrIfaSe+Wu0b89GKccT7vxXA0MoAIO+Q== integrity sha512-9TANp6GPoMtYzQdt54kfAyMmz1+osLlXdg2ENroU7zzrtflTLrrC/lgrIfaSe+Wu0b89GKccT7vxXA0MoAIO+Q==
"@headlessui/react@^1.7.13", "@headlessui/react@^1.7.17", "@headlessui/react@^1.7.3": "@headlessui/react@^1.7.13", "@headlessui/react@^1.7.17", "@headlessui/react@^1.7.19", "@headlessui/react@^1.7.3":
version "1.7.19" version "1.7.19"
resolved "https://registry.yarnpkg.com/@headlessui/react/-/react-1.7.19.tgz#91c78cf5fcb254f4a0ebe96936d48421caf75f40" resolved "https://registry.yarnpkg.com/@headlessui/react/-/react-1.7.19.tgz#91c78cf5fcb254f4a0ebe96936d48421caf75f40"
integrity sha512-Ll+8q3OlMJfJbAKM/+/Y2q6PPYbryqNTXDbryx7SXLIDamkF6iQFbriYHga0dY44PvDhvvBWCx1Xj4U5+G4hOw== integrity sha512-Ll+8q3OlMJfJbAKM/+/Y2q6PPYbryqNTXDbryx7SXLIDamkF6iQFbriYHga0dY44PvDhvvBWCx1Xj4U5+G4hOw==