snapshot of https://github.com/makeplane/plane.git @ d868349a55de79979eb8b98701bf1702c67ad634 (2026-09-15)
Some checks failed
CodeQL / Analyze (javascript) (push) Failing after 16s
CodeQL / Analyze (python) (push) Failing after 3s
i18n sync check / check:sync (push) Failing after 3s
React Doctor / react-doctor (push) Failing after 16s
Branch Build CE / Build-Push Admin Docker Image (${{ matrix.arch }}) (push) Has been cancelled
Branch Build CE / Merge Admin Manifest (push) Has been cancelled
Branch Build CE / Build-Push Web Docker Image (${{ matrix.arch }}) (push) Has been cancelled
Branch Build CE / Merge Web Manifest (push) Has been cancelled
Branch Build CE / Build-Push Space Docker Image (${{ matrix.arch }}) (push) Has been cancelled
Branch Build CE / Merge Proxy Manifest (push) Has been cancelled
Branch Build CE / Merge Space Manifest (push) Has been cancelled
Branch Build CE / Prepare AIO Assets (push) Has been cancelled
Branch Build CE / Build Setup (push) Has been cancelled
Branch Build CE / Build-Push Live Collaboration Docker Image (${{ matrix.arch }}) (push) Has been cancelled
Branch Build CE / Merge Live Collaboration Manifest (push) Has been cancelled
Branch Build CE / Build-Push API Server Docker Image (${{ matrix.arch }}) (push) Has been cancelled
Branch Build CE / Merge API Server Manifest (push) Has been cancelled
Branch Build CE / Build-Push Proxy Docker Image (${{ matrix.arch }}) (push) Has been cancelled
Branch Build CE / Build-Push AIO Docker Image (${{ matrix.arch }}) (push) Has been cancelled
Branch Build CE / Merge AIO Manifest (push) Has been cancelled
Branch Build CE / Upload Build Assets (push) Has been cancelled
Branch Build CE / Build Release (push) Has been cancelled

This commit is contained in:
upstream-mirror
2026-09-15 15:14:58 +05:00
commit 23059a1de3
5252 changed files with 573834 additions and 0 deletions

View File

@@ -0,0 +1,19 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
type Props = {
title: string;
description: string;
};
export function CommonOnboardingHeader({ title, description }: Props) {
return (
<div className="space-y-2 text-left">
<h1 className="text-h4-semibold text-primary">{title}</h1>
<p className="text-body-md-regular text-tertiary">{description}</p>
</div>
);
}

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
export * from "./header";

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
export * from "./root";

View File

@@ -0,0 +1,29 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
import { TickOutline } from "@makeplane/propel/icons";
type Props = {
isChecked: boolean;
handleChange: (checked: boolean) => void;
};
export function MarketingConsent({ isChecked, handleChange }: Props) {
return (
<div className="flex items-center justify-center gap-1.5">
<button
type="button"
onClick={() => handleChange(!isChecked)}
className={`flex size-4 items-center justify-center rounded-sm border-2 ${
isChecked ? "border-accent-strong bg-accent-primary" : "border-strong"
}`}
>
{isChecked && <TickOutline className="h-3 w-3 text-on-color" />}
</button>
<span className="text-13 text-tertiary">I agree to Plane marketing communications</span>
</div>
);
}

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
export * from "./root";

View File

@@ -0,0 +1,265 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
import { useMemo, useState } from "react";
import { observer } from "mobx-react";
import { Controller, useForm } from "react-hook-form";
import { ImageOutline } from "@makeplane/propel/icons";
// plane imports
import { E_PASSWORD_STRENGTH } from "@plane/constants";
import { Button } from "@plane/propel/button";
import { TOAST_TYPE, setToast } from "@plane/propel/toast";
import type { IUser } from "@plane/types";
import { EOnboardingSteps } from "@plane/types";
import { cn, getFileURL, getPasswordStrength, validatePersonName } from "@plane/utils";
// components
import { UserImageUploadModal } from "@/components/core/modals/user-image-upload-modal";
// hooks
import { useInstance } from "@/hooks/store/use-instance";
import { useUser, useUserProfile } from "@/hooks/store/user";
// services
import { AuthService } from "@/services/auth.service";
// local components
import { CommonOnboardingHeader } from "../common";
import { MarketingConsent } from "./consent";
import { SetPasswordRoot } from "./set-password";
type Props = {
handleStepChange: (step: EOnboardingSteps, skipInvites?: boolean) => void;
};
export type TProfileSetupFormValues = {
first_name: string;
last_name: string;
avatar_url?: string | null;
password?: string;
confirm_password?: string;
role?: string;
use_case?: string[];
has_marketing_email_consent?: boolean;
};
const authService = new AuthService();
const defaultValues: Partial<TProfileSetupFormValues> = {
first_name: "",
last_name: "",
avatar_url: "",
password: undefined,
confirm_password: undefined,
has_marketing_email_consent: true,
};
export const ProfileSetupStep = observer(function ProfileSetupStep({ handleStepChange }: Props) {
// states
const [isImageUploadModalOpen, setIsImageUploadModalOpen] = useState(false);
// store hooks
const { data: user, updateCurrentUser } = useUser();
const { updateUserProfile } = useUserProfile();
const { config: instanceConfig } = useInstance();
// form info
const {
getValues,
handleSubmit,
control,
watch,
setValue,
formState: { errors, isSubmitting, isValid },
} = useForm<TProfileSetupFormValues>({
defaultValues: {
...defaultValues,
first_name: user?.first_name,
last_name: user?.last_name,
avatar_url: user?.avatar_url,
},
mode: "onChange",
});
// derived values
const userAvatar = watch("avatar_url");
const handleSetPassword = async (password: string) => {
const token = await authService.requestCSRFToken().then((data) => data?.csrf_token);
await authService.setPassword(token, { password });
};
const handleSubmitUserDetail = async (formData: TProfileSetupFormValues) => {
const userDetailsPayload: Partial<IUser> = {
first_name: formData.first_name,
last_name: formData.last_name,
avatar_url: formData.avatar_url ?? undefined,
};
try {
await Promise.all([
updateCurrentUser(userDetailsPayload),
formData.password && handleSetPassword(formData.password),
]);
} catch {
setToast({
type: TOAST_TYPE.ERROR,
title: "Error",
message: "User details update failed. Please try again!",
});
}
};
const onSubmit = async (formData: TProfileSetupFormValues) => {
if (!user) return;
updateUserProfile({
has_marketing_email_consent: formData.has_marketing_email_consent,
});
await handleSubmitUserDetail(formData);
handleStepChange(EOnboardingSteps.PROFILE_SETUP);
};
const handleDelete = (url: string | null | undefined) => {
if (!url) return;
setValue("avatar_url", "");
};
// derived values
const isPasswordAlreadySetup = !user?.is_password_autoset;
const currentPassword = watch("password") || undefined;
const currentConfirmPassword = watch("confirm_password") || undefined;
const isValidPassword = useMemo(() => {
if (currentPassword) {
if (
currentPassword === currentConfirmPassword &&
getPasswordStrength(currentPassword) === E_PASSWORD_STRENGTH.STRENGTH_VALID
) {
return true;
} else {
return false;
}
} else {
return true;
}
}, [currentPassword, currentConfirmPassword]);
// Check for all available fields validation and if password field is available, then checks for password validation (strength + confirmation).
// Also handles the condition for optional password i.e if password field is optional it only checks for above validation if it's not empty.
const isButtonDisabled =
!isSubmitting && isValid ? (isPasswordAlreadySetup ? false : isValidPassword ? false : true) : true;
return (
<form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-10">
{/* Header */}
<CommonOnboardingHeader title="Create your profile." description="This is how you will appear in Plane." />
{/* Profile Picture Section */}
<Controller
control={control}
name="avatar_url"
render={({ field: { onChange, value } }) => (
<UserImageUploadModal
isOpen={isImageUploadModalOpen}
onClose={() => setIsImageUploadModalOpen(false)}
handleRemove={async () => handleDelete(getValues("avatar_url"))}
onSuccess={(url) => {
onChange(url);
setIsImageUploadModalOpen(false);
}}
value={value && value.trim() !== "" ? value : null}
/>
)}
/>
<div className="flex items-center gap-4">
<button
className="flex size-12 items-center justify-center rounded-full bg-accent-primary text-18 font-semibold text-on-color"
type="button"
onClick={() => setIsImageUploadModalOpen(true)}
>
{userAvatar ? (
<img
src={getFileURL(userAvatar ?? "")}
onClick={() => setIsImageUploadModalOpen(true)}
alt={user?.display_name}
className="h-full w-full rounded-full object-cover"
/>
) : (
<>{watch("first_name")[0] ?? "R"}</>
)}
</button>
<input type="file" className="hidden" id="profile-image-input" />
<button
className="flex items-center gap-1.5 px-2 py-1 text-13 text-tertiary hover:text-secondary"
type="button"
onClick={() => setIsImageUploadModalOpen(true)}
>
<ImageOutline className="size-4" />
<span className="text-13">{userAvatar ? "Change image" : "Upload image"}</span>
</button>
</div>
<div className="flex w-full flex-col gap-6">
{/* Name Input */}
<div className="flex flex-col gap-2">
<label
className="block text-13 font-medium text-tertiary after:ml-0.5 after:text-danger-primary after:content-['*']"
htmlFor="first_name"
>
Name
</label>
<Controller
control={control}
name="first_name"
rules={{
required: "Name is required",
validate: validatePersonName,
maxLength: {
value: 50,
message: "Name must be within 50 characters.",
},
}}
render={({ field: { value, onChange, ref } }) => (
<input
ref={ref}
id="first_name"
name="first_name"
type="text"
value={value}
onChange={(e) => onChange(e.target.value)}
autoFocus
className={cn(
"w-full rounded-md border border-strong bg-surface-1 px-3 py-2 text-secondary transition-all duration-200 placeholder:text-placeholder focus:border-transparent focus:ring-2 focus:ring-accent-strong focus:outline-none",
{
"border-strong": !errors.first_name,
"border-danger-strong": errors.first_name,
}
)}
placeholder="Enter your full name"
autoComplete="on"
/>
)}
/>
{errors.first_name && <span className="text-13 text-danger-primary">{errors.first_name.message}</span>}
</div>
{/* setting up password for the first time */}
{!isPasswordAlreadySetup && (
<SetPasswordRoot
onPasswordChange={(password) => setValue("password", password)}
onConfirmPasswordChange={(confirm_password) => setValue("confirm_password", confirm_password)}
/>
)}
</div>
{/* Continue Button */}
<Button variant="primary" type="submit" className="w-full" size="xl" disabled={isButtonDisabled}>
Continue
</Button>
{/* Marketing Consent */}
{!instanceConfig?.is_self_managed && (
<MarketingConsent
isChecked={!!watch("has_marketing_email_consent")}
handleChange={(has_marketing_email_consent) =>
setValue("has_marketing_email_consent", has_marketing_email_consent)
}
/>
)}
</form>
);
});

View File

@@ -0,0 +1,133 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
import React, { useState, useCallback, useMemo } from "react";
import { ChevronDownOutline, LockOutline } from "@makeplane/propel/icons";
import { PasswordInput, PasswordStrengthIndicator } from "@plane/ui";
import { cn } from "@plane/utils";
interface PasswordState {
password: string;
confirmPassword: string;
}
interface SetPasswordRootProps {
onPasswordChange?: (password: string) => void;
onConfirmPasswordChange?: (confirmPassword: string) => void;
disabled?: boolean;
}
export function SetPasswordRoot({ onPasswordChange, onConfirmPasswordChange, disabled = false }: SetPasswordRootProps) {
const [isExpanded, setIsExpanded] = useState(false);
const [passwordState, setPasswordState] = useState<PasswordState>({
password: "",
confirmPassword: "",
});
const handleToggleExpand = useCallback(() => {
if (disabled) return;
setIsExpanded((prev) => !prev);
}, [disabled]);
const handlePasswordChange = useCallback(
(field: keyof PasswordState, value: string) => {
setPasswordState((prev) => {
const newState = { ...prev, [field]: value };
// Notify parent component when password changes
if (field === "password" && onPasswordChange) {
onPasswordChange(value);
}
if (field === "confirmPassword" && onConfirmPasswordChange) {
onConfirmPasswordChange(value);
}
return newState;
});
},
[onPasswordChange, onConfirmPasswordChange]
);
const isPasswordValid = useMemo(() => {
const { password, confirmPassword } = passwordState;
return password.length >= 8 && password === confirmPassword;
}, [passwordState]);
const hasPasswordMismatch = useMemo(() => {
const { password, confirmPassword } = passwordState;
return confirmPassword.length > 0 && password !== confirmPassword;
}, [passwordState]);
const chevronIconClasses = useMemo(
() =>
`w-4 h-4 text-placeholder transition-transform duration-300 ease-in-out ${isExpanded ? "rotate-180" : "rotate-0"}`,
[isExpanded]
);
const expandedContentClasses = useMemo(
() =>
`flex flex-col gap-4 transition-all duration-300 ease-in-out overflow-hidden px-3 ${
isExpanded ? "max-h-96 opacity-100" : "max-h-0 opacity-0"
}`,
[isExpanded]
);
return (
<div className={`flex flex-col overflow-hidden rounded-lg bg-surface-2 transition-all duration-300 ease-in-out`}>
<div
className={cn(
"flex items-center justify-between px-3 py-2 text-13 transition-colors duration-200",
disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer",
isExpanded && "pb-1"
)}
onClick={handleToggleExpand}
>
<div className="flex items-center gap-1 text-tertiary">
<LockOutline className="size-3" />
<span className="font-medium">Set a password</span>
<span>{`(Optional)`}</span>
</div>
<div className="flex items-center gap-2 text-placeholder">
<ChevronDownOutline className={chevronIconClasses} />
</div>
</div>
<div className={expandedContentClasses}>
{/* Password input */}
<div className="flex transform flex-col gap-2 pt-1 transition-all duration-300 ease-in-out">
<PasswordInput
id="password"
value={passwordState.password}
onChange={(value) => handlePasswordChange("password", value)}
placeholder="Set a password"
className="transition-all duration-200"
/>
{passwordState.password.length > 0 && <PasswordStrengthIndicator password={passwordState.password} />}
</div>
<div className="flex flex-col gap-2 pb-2">
{/* Confirm password label */}
<div className="transform text-13 font-medium text-tertiary transition-all delay-75 duration-300 ease-in-out">
Confirm password
</div>
{/* Confirm password input */}
<div className="transform transition-all delay-100 duration-300 ease-in-out">
<PasswordInput
id="confirm-password"
value={passwordState.confirmPassword}
onChange={(value) => handlePasswordChange("confirmPassword", value)}
placeholder="Confirm password"
className="transition-all duration-200"
/>
{hasPasswordMismatch && <p className="mt-1 text-11 text-danger-primary">Passwords do not match</p>}
{isPasswordValid && <p className="mt-1 text-11 text-success-primary">✓ Passwords match</p>}
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
export * from "./root";

View File

@@ -0,0 +1,164 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
import { observer } from "mobx-react";
import { Controller, useForm } from "react-hook-form";
import { PenTool } from "lucide-react";
import {
CubeOutline,
MonitorOutline,
RefreshOutline,
RocketOutline,
TickOutline,
ViewsOutline,
} from "@makeplane/propel/icons";
// plane imports
import { Button } from "@plane/propel/button";
import { TOAST_TYPE, setToast } from "@plane/propel/toast";
import type { TUserProfile } from "@plane/types";
import { EOnboardingSteps } from "@plane/types";
// hooks
import { useUserProfile } from "@/hooks/store/user";
// local components
import { CommonOnboardingHeader } from "../common";
import type { TProfileSetupFormValues } from "../profile/root";
type Props = {
handleStepChange: (step: EOnboardingSteps, skipInvites?: boolean) => void;
};
const ROLES = [
{ id: "product-manager", label: "Product Manager", icon: CubeOutline },
{ id: "engineering-manager", label: "Engineering Manager", icon: ViewsOutline },
{ id: "designer", label: "Designer", icon: PenTool },
{ id: "developer", label: "Developer", icon: MonitorOutline },
{ id: "founder-executive", label: "Founder/Executive", icon: RocketOutline },
{ id: "operations-manager", label: "Operations Manager", icon: RefreshOutline },
{ id: "others", label: "Others", icon: CubeOutline },
];
const defaultValues = {
role: "",
};
export const RoleSetupStep = observer(function RoleSetupStep({ handleStepChange }: Props) {
// store hooks
const { data: profile, updateUserProfile } = useUserProfile();
// form info
const {
handleSubmit,
control,
formState: { errors, isSubmitting, isValid },
} = useForm<TProfileSetupFormValues>({
defaultValues: {
...defaultValues,
role: profile?.role,
},
mode: "onChange",
});
// handle submit
const handleSubmitUserPersonalization = async (formData: TProfileSetupFormValues) => {
const profileUpdatePayload: Partial<TUserProfile> = {
role: formData.role,
};
try {
await Promise.all([
updateUserProfile(profileUpdatePayload),
// totalSteps > 2 && stepChange({ profile_complete: true }),
]);
setToast({
type: TOAST_TYPE.SUCCESS,
title: "Success",
message: "Profile setup completed!",
});
} catch {
setToast({
type: TOAST_TYPE.ERROR,
title: "Error",
message: "Profile setup failed. Please try again!",
});
}
};
const onSubmit = async (formData: TProfileSetupFormValues) => {
if (!profile) return;
await handleSubmitUserPersonalization(formData);
handleStepChange(EOnboardingSteps.ROLE_SETUP);
};
const handleSkip = () => {
handleStepChange(EOnboardingSteps.ROLE_SETUP);
};
const isButtonDisabled = !isSubmitting && isValid ? false : true;
return (
<form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-10">
{/* Header */}
<CommonOnboardingHeader title="What's your role?" description="Let's set up Plane for how you work." />
{/* Role Selection */}
<div className="flex flex-col gap-3">
<p className="text-body-sm-semibold text-placeholder">Select one</p>
<Controller
control={control}
name="role"
rules={{
required: "This field is required",
}}
render={({ field: { value, onChange } }) => (
<div className="flex flex-col gap-3">
{ROLES.map((role) => {
const Icon = role.icon;
const isSelected = value === role.id;
return (
<button
key={role.id}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
onChange(role.id);
}}
className={`flex w-full items-center justify-between rounded-lg border px-3 py-2 transition-all duration-200 ${
isSelected
? "border-accent-strong bg-accent-subtle text-accent-primary"
: "border-subtle text-tertiary hover:border-strong"
}`}
>
<div className="flex items-center space-x-3">
<Icon className="size-3.5" />
<span className="text-body-sm-semibold">{role.label}</span>
</div>
{isSelected && (
<>
<button
className={`border-blue-500 flex size-4 items-center justify-center rounded-sm border-2 bg-accent-primary`}
>
<TickOutline className="h-3 w-3 text-on-color" />
</button>
</>
)}
</button>
);
})}
</div>
)}
/>
{errors.role && <span className="text-13 text-danger-primary">{errors.role.message}</span>}
</div>
{/* Action Buttons */}
<div className="space-y-3">
<Button variant="primary" type="submit" className="w-full" size="xl" disabled={isButtonDisabled}>
Continue
</Button>
<Button variant="ghost" onClick={handleSkip} className="w-full text-tertiary" size="xl">
Skip
</Button>
</div>
</form>
);
});

View File

@@ -0,0 +1,65 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
import { useEffect, useRef } from "react";
// plane imports
import type { IWorkspaceMemberInvitation } from "@plane/types";
import { EOnboardingSteps } from "@plane/types";
// local components
import { ProfileSetupStep } from "./profile";
import { RoleSetupStep } from "./role";
import { InviteTeamStep } from "./team";
import { UseCaseSetupStep } from "./usecase";
import { WorkspaceSetupStep } from "./workspace";
type Props = {
currentStep: EOnboardingSteps;
invitations: IWorkspaceMemberInvitation[];
handleStepChange: (step: EOnboardingSteps, skipInvites?: boolean) => void;
};
function OnboardingStepContent({ currentStep, invitations, handleStepChange }: Props) {
switch (currentStep) {
case EOnboardingSteps.PROFILE_SETUP:
return <ProfileSetupStep handleStepChange={handleStepChange} />;
case EOnboardingSteps.ROLE_SETUP:
return <RoleSetupStep handleStepChange={handleStepChange} />;
case EOnboardingSteps.USE_CASE_SETUP:
return <UseCaseSetupStep handleStepChange={handleStepChange} />;
case EOnboardingSteps.WORKSPACE_CREATE_OR_JOIN:
return <WorkspaceSetupStep invitations={invitations ?? []} handleStepChange={handleStepChange} />;
case EOnboardingSteps.INVITE_MEMBERS:
return <InviteTeamStep handleStepChange={handleStepChange} />;
default:
return null;
}
}
export function OnboardingStepRoot(props: Props) {
const { currentStep } = props;
// ref for the scrollable container
const scrollContainerRef = useRef<HTMLDivElement>(null);
// scroll to top when step changes
useEffect(() => {
if (scrollContainerRef.current) {
scrollContainerRef.current.scrollTo({
top: 0,
behavior: "smooth",
});
}
}, [currentStep]);
return (
<div ref={scrollContainerRef} className="flex-1 overflow-y-auto">
<div className="flex min-h-full items-center justify-center p-8">
<div className="w-full max-w-[24rem]">
<OnboardingStepContent {...props} />
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
export * from "./root";

View File

@@ -0,0 +1,400 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
import React, { useEffect, useState } from "react";
import { observer } from "mobx-react";
import type {
Control,
FieldArrayWithId,
UseFieldArrayRemove,
UseFormGetValues,
UseFormSetValue,
UseFormWatch,
} from "react-hook-form";
import { Controller, useFieldArray, useForm } from "react-hook-form";
import { usePopper } from "react-popper";
import { AddOutline, ChevronDownOutline, CloseCircleOutline, TickOutline } from "@makeplane/propel/icons";
import { Listbox } from "@headlessui/react";
// plane imports
import { Field } from "@makeplane/propel/components/field";
import { Input, InputGroup } from "@makeplane/propel/components/input";
import type { EUserPermissions } from "@plane/constants";
import { ROLE, ROLE_DETAILS } from "@plane/constants";
import { useTranslation } from "@plane/i18n";
import { Button } from "@plane/propel/button";
import { TOAST_TYPE, setToast } from "@plane/propel/toast";
import { EOnboardingSteps } from "@plane/types";
import { Spinner } from "@plane/ui";
// hooks
import { useWorkspace } from "@/hooks/store/use-workspace";
// services
import { WorkspaceService } from "@/services/workspace.service";
// components
import { CommonOnboardingHeader } from "../common";
type Props = {
handleStepChange: (step: EOnboardingSteps, skipInvites?: boolean) => void;
};
type EmailRole = {
email: string;
role: EUserPermissions;
role_active: boolean;
};
type FormValues = {
emails: EmailRole[];
};
type InviteMemberFormProps = {
index: number;
remove: UseFieldArrayRemove;
control: Control<FormValues, any>;
setValue: UseFormSetValue<FormValues>;
getValues: UseFormGetValues<FormValues>;
watch: UseFormWatch<FormValues>;
field: FieldArrayWithId<FormValues, "emails", "id">;
fields: FieldArrayWithId<FormValues, "emails", "id">[];
errors: any;
isInvitationDisabled: boolean;
setIsInvitationDisabled: (value: boolean) => void;
};
// services
const workspaceService = new WorkspaceService();
const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
const placeholderEmails = [
"charlie.taylor@frstflt.com",
"octave.chanute@frstflt.com",
"george.spratt@frstflt.com",
"frank.coffyn@frstflt.com",
"amos.root@frstflt.com",
"edward.deeds@frstflt.com",
"charles.m.manly@frstflt.com",
"glenn.curtiss@frstflt.com",
"thomas.selfridge@frstflt.com",
"albert.zahm@frstflt.com",
];
const InviteMemberInput = observer(function InviteMemberInput(props: InviteMemberFormProps) {
const {
control,
index,
fields,
remove,
errors,
isInvitationDisabled,
setIsInvitationDisabled,
setValue,
getValues,
watch,
} = props;
const [referenceElement, setReferenceElement] = useState<HTMLButtonElement | null>(null);
const [popperElement, setPopperElement] = useState<HTMLDivElement | null>(null);
const { t } = useTranslation();
const email = watch(`emails.${index}.email`);
const emailOnChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.value === "") {
const validEmail = fields.map((_, i) => emailRegex.test(getValues(`emails.${i}.email`))).includes(true);
if (validEmail) {
setIsInvitationDisabled(false);
} else {
setIsInvitationDisabled(true);
}
if (getValues(`emails.${index}.role_active`)) {
setValue(`emails.${index}.role_active`, false);
}
} else {
if (!getValues(`emails.${index}.role_active`)) {
setValue(`emails.${index}.role_active`, true);
}
if (isInvitationDisabled && emailRegex.test(event.target.value)) {
setIsInvitationDisabled(false);
} else if (!isInvitationDisabled && !emailRegex.test(event.target.value)) {
setIsInvitationDisabled(true);
}
}
};
const { styles, attributes } = usePopper(referenceElement, popperElement, {
placement: "bottom-end",
modifiers: [
{
name: "preventOverflow",
options: {
padding: 12,
},
},
],
});
return (
<div>
<div className="group relative grid grid-cols-10 gap-4">
<div className="col-span-6">
<Controller
control={control}
name={`emails.${index}.email`}
rules={{
pattern: {
value: emailRegex,
message: "Invalid Email ID",
},
}}
render={({ field: { value, onChange, ref } }) => (
<Field name="input" invalid={Boolean(errors.emails?.[index]?.email)}>
<InputGroup size="2xl">
<Input
size="2xl"
id={`emails.${index}.email`}
name={`emails.${index}.email`}
type="text"
value={value}
onChange={(event) => {
emailOnChange(event);
onChange(event);
}}
ref={ref}
placeholder={placeholderEmails[index % placeholderEmails.length]}
autoComplete="off"
/>
</InputGroup>
</Field>
)}
/>
</div>
<div className="col-span-4 mr-8">
<Controller
control={control}
name={`emails.${index}.role`}
rules={{ required: true }}
render={({ field: { value, onChange } }) => (
<Listbox
as="div"
value={value}
onChange={(val) => {
onChange(val);
setValue(`emails.${index}.role_active`, true);
}}
className="w-full flex-shrink-0 text-left"
>
<Listbox.Button
type="button"
ref={setReferenceElement}
className="flex w-full items-center justify-between gap-1 rounded-md border-[0.5px] border-strong px-2.5 py-2 text-13"
>
<span
className={`text-13 ${
!getValues(`emails.${index}.role_active`) ? "text-placeholder" : "text-primary"
} sm:text-13`}
>
{ROLE[value]}
</span>
<ChevronDownOutline
className={`size-3 ${
!getValues(`emails.${index}.role_active`) ? "text-placeholder" : "text-primary"
}`}
/>
</Listbox.Button>
<Listbox.Options as="div">
<div
className="shadow-sm absolute z-10 mt-1 h-fit w-48 space-y-1 rounded-md border border-strong bg-surface-1 p-2 focus:outline-none sm:w-60"
ref={setPopperElement}
style={styles.popper}
{...attributes.popper}
>
{Object.entries(ROLE_DETAILS).map(([key, value]) => (
<Listbox.Option
as="div"
key={key}
value={parseInt(key)}
className={({ active, selected }) =>
`cursor-pointer truncate rounded-sm px-1 py-1.5 select-none ${
active || selected ? "bg-onboarding-background-400/40" : ""
} ${selected ? "text-primary" : "text-secondary"}`
}
>
{({ selected }) => (
<div className="flex items-center gap-2 p-1 text-wrap">
<div className="flex flex-col">
<div className="text-13 font-medium">{t(value.i18n_title)}</div>
<div className="flex text-11 text-tertiary">{t(value.i18n_description)}</div>
</div>
{selected && <TickOutline className="h-4 w-4 shrink-0" />}
</div>
)}
</Listbox.Option>
))}
</div>
</Listbox.Options>
</Listbox>
)}
/>
</div>
{fields.length > 1 && (
<button
type="button"
className="absolute right-0 hidden place-items-center self-center rounded-sm group-hover:grid"
onClick={() => remove(index)}
>
<CloseCircleOutline className="h-5 w-5 pl-0.5 text-placeholder" />
</button>
)}
</div>
{email && !emailRegex.test(email) && (
<div className="mx-8 my-1">
<span className="text-13">🤥</span>{" "}
<span className="mt-1 text-11 text-danger-primary">That doesn{"'"}t look like an email address.</span>
</div>
)}
</div>
);
});
export const InviteTeamStep = observer(function InviteTeamStep(props: Props) {
const { handleStepChange } = props;
const [isInvitationDisabled, setIsInvitationDisabled] = useState(true);
const { workspaces } = useWorkspace();
const workspacesList = Object.values(workspaces ?? {});
const workspace = workspacesList[0];
const {
control,
watch,
getValues,
setValue,
handleSubmit,
formState: { isSubmitting, errors, isValid },
} = useForm<FormValues>();
const { fields, append, remove } = useFieldArray({
control,
name: "emails",
});
const nextStep = async () => {
await handleStepChange(EOnboardingSteps.INVITE_MEMBERS);
};
const onSubmit = async (formData: FormValues) => {
if (!workspace) return;
let payload = { ...formData };
payload = { emails: payload.emails.filter((email) => email.email !== "") };
await workspaceService
.inviteWorkspace(workspace.slug, {
emails: payload.emails.map((email) => ({
email: email.email,
role: email.role,
})),
})
.then(async () => {
setToast({
type: TOAST_TYPE.SUCCESS,
title: "Success!",
message: "Invitations sent successfully.",
});
await nextStep();
})
.catch((err) => {
setToast({
type: TOAST_TYPE.ERROR,
title: "Error!",
message: err?.error,
});
});
};
const appendField = () => {
append({ email: "", role: 15, role_active: false });
};
useEffect(() => {
if (fields.length === 0) {
append(
[
{ email: "", role: 15, role_active: false },
{ email: "", role: 15, role_active: false },
{ email: "", role: 15, role_active: false },
],
{
focusIndex: 0,
}
);
}
}, [fields, append]);
return (
<form
className="flex flex-col gap-10"
onSubmit={handleSubmit(onSubmit)}
onKeyDown={(e) => {
if (e.code === "Enter") e.preventDefault();
}}
>
<CommonOnboardingHeader
title="Invite your teammates"
description="Work in plane happens best with your team. Invite them now to use Plane to its potential."
/>
<div className="w-full py-4 text-13">
<div className="group relative mx-8 grid grid-cols-10 gap-4 py-2">
<div className="col-span-6 px-1 text-13 font-medium text-secondary">Email</div>
<div className="col-span-4 px-1 text-13 font-medium text-secondary">Role</div>
</div>
<div className="mb-3 space-y-3 sm:space-y-4">
{fields.map((field, index) => (
<InviteMemberInput
watch={watch}
getValues={getValues}
setValue={setValue}
isInvitationDisabled={isInvitationDisabled}
setIsInvitationDisabled={(value: boolean) => setIsInvitationDisabled(value)}
control={control}
errors={errors}
field={field}
fields={fields}
index={index}
remove={remove}
key={field.id}
/>
))}
</div>
<button
type="button"
className="mx-8 flex items-center gap-1.5 bg-transparent text-13 font-medium text-accent-primary outline-accent-strong"
onClick={appendField}
>
<AddOutline className="h-4 w-4" />
Add another
</button>
</div>
<div className="mx-auto flex w-full flex-col items-center justify-center gap-4 px-8 sm:px-2">
<Button
variant="primary"
type="submit"
size="xl"
className="w-full"
disabled={isInvitationDisabled || !isValid || isSubmitting}
>
{isSubmitting ? <Spinner height="20px" width="20px" /> : "Continue"}
</Button>
<Button variant="ghost" size="xl" className="w-full" onClick={nextStep}>
I’ll do it later
</Button>
</div>
</form>
);
});

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
export * from "./root";

View File

@@ -0,0 +1,162 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
import { observer } from "mobx-react";
import { Controller, useForm } from "react-hook-form";
// plane imports
import { USE_CASES } from "@plane/constants";
import { Button } from "@plane/propel/button";
import { TickOutline } from "@makeplane/propel/icons";
import { TOAST_TYPE, setToast } from "@plane/propel/toast";
import type { TUserProfile } from "@plane/types";
import { EOnboardingSteps } from "@plane/types";
import { cn } from "@plane/utils";
// hooks
import { useUserProfile } from "@/hooks/store/user";
// local imports
import { CommonOnboardingHeader } from "../common";
import type { TProfileSetupFormValues } from "../profile/root";
type Props = {
handleStepChange: (step: EOnboardingSteps, skipInvites?: boolean) => void;
};
const defaultValues = {
use_case: [] as string[],
};
export const UseCaseSetupStep = observer(function UseCaseSetupStep({ handleStepChange }: Props) {
// store hooks
const { data: profile, updateUserProfile } = useUserProfile();
// form info
const {
handleSubmit,
control,
formState: { errors, isSubmitting, isValid },
} = useForm<TProfileSetupFormValues>({
defaultValues: {
...defaultValues,
use_case: profile?.use_case ? profile.use_case.split(". ") : [],
},
mode: "onChange",
});
// handle submit
const handleSubmitUserPersonalization = async (formData: TProfileSetupFormValues) => {
const profileUpdatePayload: Partial<TUserProfile> = {
use_case: formData.use_case && formData.use_case.length > 0 ? formData.use_case.join(". ") : undefined,
};
try {
await Promise.all([
updateUserProfile(profileUpdatePayload),
// totalSteps > 2 && stepChange({ profile_complete: true }),
]);
setToast({
type: TOAST_TYPE.SUCCESS,
title: "Success",
message: "Profile setup completed!",
});
} catch {
setToast({
type: TOAST_TYPE.ERROR,
title: "Error",
message: "Profile setup failed. Please try again!",
});
}
};
// on submit
const onSubmit = async (formData: TProfileSetupFormValues) => {
if (!profile) return;
await handleSubmitUserPersonalization(formData);
handleStepChange(EOnboardingSteps.USE_CASE_SETUP);
};
// handle skip
const handleSkip = () => {
handleStepChange(EOnboardingSteps.USE_CASE_SETUP);
};
// derived values
const isButtonDisabled = !isSubmitting && isValid ? false : true;
return (
<form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-10">
{/* Header */}
<CommonOnboardingHeader title="What brings you to Plane?" description="Tell us your goals and team size." />
{/* Use Case Selection */}
<div className="flex flex-col gap-3">
<p className="text-body-sm-semibold text-placeholder">Select one or more</p>
<Controller
control={control}
name="use_case"
rules={{
required: "Please select at least one option",
validate: (value) => (value && value.length > 0) || "Please select at least one option",
}}
render={({ field: { value, onChange } }) => (
<div className="flex flex-col gap-3">
{USE_CASES.map((useCase) => {
const isSelected = value?.includes(useCase) || false;
return (
<button
key={useCase}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
const currentValue = value || [];
if (isSelected) {
// Remove from array
onChange(currentValue.filter((item) => item !== useCase));
} else {
// Add to array
onChange([...currentValue, useCase]);
}
}}
className={`flex w-full items-center gap-2 rounded-lg border px-3 py-2 transition-all duration-200 ${
isSelected
? "border-accent-strong bg-accent-subtle text-accent-primary"
: "border-subtle text-tertiary hover:border-strong"
}`}
>
<span
className={cn(`flex size-4 items-center justify-center rounded-sm border-2`, {
"border-accent-strong bg-accent-primary": isSelected,
"border-strong": !isSelected,
})}
>
<TickOutline
className={cn("h-3 w-3 text-on-color", {
"opacity-100": isSelected,
"opacity-0": !isSelected,
})}
/>
</span>
<span className="text-body-sm-regular">{useCase}</span>
</button>
);
})}
</div>
)}
/>
{errors.use_case && <span className="text-13 text-danger-primary">{errors.use_case.message}</span>}
</div>
{/* Action Buttons */}
<div className="space-y-3">
<Button variant="primary" type="submit" className="w-full" size="xl" disabled={isButtonDisabled}>
Continue
</Button>
<Button variant="ghost" onClick={handleSkip} className="w-full" size="xl">
Skip
</Button>
</div>
</form>
);
});

View File

@@ -0,0 +1,304 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
import { useState } from "react";
import { observer } from "mobx-react";
import { Controller, useForm } from "react-hook-form";
import { TickCircleOutline } from "@makeplane/propel/icons";
// plane imports
import { ORGANIZATION_SIZE, RESTRICTED_URLS } from "@plane/constants";
import { useTranslation } from "@plane/i18n";
import { Button } from "@plane/propel/button";
import { TOAST_TYPE, setToast } from "@plane/propel/toast";
import type { IUser, IWorkspace } from "@plane/types";
import { Spinner } from "@plane/ui";
import { cn, validateWorkspaceName, validateSlug } from "@plane/utils";
// hooks
import { useInstance } from "@/hooks/store/use-instance";
import { useWorkspace } from "@/hooks/store/use-workspace";
import { useUserProfile, useUserSettings } from "@/hooks/store/user";
// services
import { WorkspaceService } from "@/services/workspace.service";
// local components
import { CommonOnboardingHeader } from "../common";
type Props = {
user: IUser | undefined;
onComplete: (skipInvites?: boolean) => void;
handleCurrentViewChange: () => void;
hasInvitations?: boolean;
};
const workspaceService = new WorkspaceService();
export const WorkspaceCreateStep = observer(function WorkspaceCreateStep({
user,
onComplete,
handleCurrentViewChange,
hasInvitations = false,
}: Props) {
// states
const [slugError, setSlugError] = useState(false);
const [invalidSlug, setInvalidSlug] = useState(false);
// plane hooks
const { t } = useTranslation();
// store hooks
const { config } = useInstance();
const { updateUserProfile } = useUserProfile();
const { fetchCurrentUserSettings } = useUserSettings();
const { createWorkspace, fetchWorkspaces } = useWorkspace();
const isWorkspaceCreationDisabled = config?.is_workspace_creation_disabled ?? false;
// form info
const {
handleSubmit,
control,
setValue,
formState: { errors, isSubmitting, isValid },
} = useForm<IWorkspace>({
defaultValues: {
name: "",
slug: "",
organization_size: "",
},
mode: "onChange",
});
const handleCreateWorkspace = async (formData: IWorkspace) => {
if (isSubmitting) return;
try {
const res = (await workspaceService.workspaceSlugCheck(formData.slug)) as { status: boolean };
if (res.status === true && !RESTRICTED_URLS.includes(formData.slug)) {
setSlugError(false);
try {
const workspaceResponse = await createWorkspace(formData);
setToast({
type: TOAST_TYPE.SUCCESS,
title: t("workspace_creation.toast.success.title"),
message: t("workspace_creation.toast.success.message"),
});
await fetchWorkspaces();
await completeStep(workspaceResponse.id);
onComplete(formData.organization_size === "Just myself");
} catch {
setToast({
type: TOAST_TYPE.ERROR,
title: t("workspace_creation.toast.error.title"),
message: t("workspace_creation.toast.error.message"),
});
}
} else {
setSlugError(true);
}
} catch {
setToast({
type: TOAST_TYPE.ERROR,
title: t("workspace_creation.toast.error.title"),
message: t("workspace_creation.toast.error.message"),
});
}
};
const completeStep = async (workspaceId: string) => {
if (!user) return;
await updateUserProfile({
last_workspace_id: workspaceId,
});
await fetchCurrentUserSettings();
};
const isButtonDisabled = !isValid || invalidSlug || isSubmitting;
if (isWorkspaceCreationDisabled) {
return (
<div className="flex flex-col gap-10">
<span className="text-center text-14 text-tertiary">
You don&apos;t seem to have any invites to a workspace and your instance admin has restricted creation of new
workspaces. Please ask a workspace owner or admin to invite you to a workspace first and come back to this
screen to join.
</span>
</div>
);
}
return (
<form
className="flex flex-col gap-10"
onSubmit={(e) => {
void handleSubmit(handleCreateWorkspace)(e);
}}
>
<CommonOnboardingHeader title="Create your workspace" description="All your work — unified." />
<div className="flex flex-col gap-8">
<div className="flex flex-col gap-2">
<label
className="text-13 font-medium text-tertiary after:ml-0.5 after:text-danger-primary after:content-['*']"
htmlFor="name"
>
{t("workspace_creation.form.name.label")}
</label>
<Controller
control={control}
name="name"
rules={{
required: t("common.errors.required"),
validate: (value) => validateWorkspaceName(value, true),
maxLength: {
value: 80,
message: t("workspace_creation.errors.validation.name_length"),
},
}}
render={({ field: { value, ref, onChange } }) => (
<div className="relative flex items-center rounded-md">
<input
id="name"
name="name"
type="text"
value={value}
onChange={(event) => {
onChange(event.target.value);
setValue("name", event.target.value);
setValue("slug", event.target.value.toLocaleLowerCase().trim().replace(/ /g, "-"), {
shouldValidate: true,
});
}}
placeholder="Enter workspace name"
ref={ref}
className={cn(
"w-full rounded-md border border-strong bg-surface-1 px-3 py-2 text-secondary transition-all duration-200 placeholder:text-placeholder focus:border-transparent focus:ring-2 focus:ring-accent-strong focus:outline-none",
{
"border-strong": !errors.name,
"border-danger-strong": errors.name,
}
)}
// eslint-disable-next-line jsx-a11y/no-autofocus
autoFocus
/>
</div>
)}
/>
{errors.name && <span className="text-13 text-danger-primary">{errors.name.message}</span>}
</div>
<div className="flex flex-col gap-2">
<label
className="text-13 font-medium text-tertiary after:ml-0.5 after:text-danger-primary after:content-['*']"
htmlFor="slug"
>
{t("workspace_creation.form.url.label")}
</label>
<Controller
control={control}
name="slug"
rules={{
required: t("common.errors.required"),
maxLength: {
value: 48,
message: t("workspace_creation.errors.validation.url_length"),
},
}}
render={({ field: { value, ref, onChange } }) => (
<div
className={cn(
"flex w-full items-center rounded-md border border-strong bg-surface-1 px-3 py-2 text-secondary transition-all duration-200 focus:border-transparent focus:ring-2 focus:ring-accent-strong focus:outline-none",
{
"border-strong": !errors.name,
"border-danger-strong": errors.name,
}
)}
>
<span className={cn("rounded-md pr-0 whitespace-nowrap text-secondary")}>
{window && window.location.host}/
</span>
<input
id="slug"
name="slug"
type="text"
value={value.toLocaleLowerCase().trim().replace(/ /g, "-")}
onChange={(e) => {
const validation = validateSlug(e.target.value);
if (validation === true) setInvalidSlug(false);
else setInvalidSlug(true);
onChange(e.target.value.toLowerCase());
}}
ref={ref}
placeholder={t("workspace_creation.form.url.placeholder")}
className={cn(
"ring-none w-full rounded-md border-none bg-surface-1 px-3 py-0 pl-0 text-secondary outline-none placeholder:text-placeholder"
)}
/>
</div>
)}
/>
<p className="text-13 text-tertiary">{t("workspace_creation.form.url.edit_slug")}</p>
{slugError && (
<p className="-mt-3 text-13 text-danger-primary">
{t("workspace_creation.errors.validation.url_already_taken")}
</p>
)}
{invalidSlug && (
<p className="text-13 text-danger-primary">{t("workspace_creation.errors.validation.url_alphanumeric")}</p>
)}
{errors.slug && <span className="text-13 text-danger-primary">{errors.slug.message}</span>}
</div>
<div className="flex flex-col gap-2">
<label
className="text-13 font-medium text-tertiary after:ml-0.5 after:text-danger-primary after:content-['*']"
htmlFor="organization_size"
>
{t("workspace_creation.form.organization_size.label")}
</label>
<div className="w-full">
<Controller
name="organization_size"
control={control}
rules={{ required: t("common.errors.required") }}
render={({ field: { value, onChange } }) => (
<div className="flex flex-wrap gap-3">
{ORGANIZATION_SIZE.map((size) => {
const isSelected = value === size;
return (
<button
key={size}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onChange(size);
}}
className={`flex items-center justify-between gap-1 rounded-lg border px-3 py-2 text-13 transition-all duration-200 ${
isSelected
? "border-subtle bg-layer-1 text-secondary"
: "border-subtle text-tertiary hover:border-strong"
}`}
>
<TickCircleOutline className={cn("size-4 text-placeholder", isSelected && "text-secondary")} />
<span className="font-medium">{size}</span>
</button>
);
})}
</div>
)}
/>
{errors.organization_size && (
<span className="text-13 text-danger-primary">{errors.organization_size.message}</span>
)}
</div>
</div>
</div>
<div className="flex flex-col gap-4">
<Button variant="primary" type="submit" size="xl" className="w-full" disabled={isButtonDisabled}>
{isSubmitting ? <Spinner height="20px" width="20px" /> : t("workspace_creation.button.default")}
</Button>
{hasInvitations && (
<Button variant="ghost" size="xl" className="w-full" onClick={handleCurrentViewChange}>
Join existing workspace
</Button>
)}
</div>
</form>
);
});

View File

@@ -0,0 +1,9 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
export * from "./create";
export * from "./join-invites";
export * from "./root";

View File

@@ -0,0 +1,126 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
import { useState } from "react";
// plane imports
import { ROLE } from "@plane/constants";
import { Button } from "@plane/propel/button";
import type { IWorkspaceMemberInvitation } from "@plane/types";
import { Checkbox } from "@makeplane/propel/components/checkbox";
import { Spinner } from "@plane/ui";
import { truncateText } from "@plane/utils";
// constants
import { WorkspaceLogo } from "@/components/workspace/logo";
// hooks
import { useWorkspace } from "@/hooks/store/use-workspace";
import { useUserSettings } from "@/hooks/store/user";
// services
import { WorkspaceService } from "@/services/workspace.service";
// local components
import { CommonOnboardingHeader } from "../common";
type Props = {
invitations: IWorkspaceMemberInvitation[];
handleNextStep: () => Promise<void>;
handleCurrentViewChange: () => void;
};
const workspaceService = new WorkspaceService();
export function WorkspaceJoinInvitesStep(props: Props) {
const { invitations, handleNextStep, handleCurrentViewChange } = props;
// states
const [isJoiningWorkspaces, setIsJoiningWorkspaces] = useState(false);
const [invitationsRespond, setInvitationsRespond] = useState<string[]>([]);
// store hooks
const { fetchWorkspaces } = useWorkspace();
const { fetchCurrentUserSettings } = useUserSettings();
// handle invitation
const handleInvitation = (workspace_invitation: IWorkspaceMemberInvitation, action: "accepted" | "withdraw") => {
if (action === "accepted") {
setInvitationsRespond((prevData) => [...prevData, workspace_invitation.id]);
} else if (action === "withdraw") {
setInvitationsRespond((prevData) => prevData.filter((item: string) => item !== workspace_invitation.id));
}
};
// submit invitations
const submitInvitations = async () => {
const invitation = invitations?.find((invitation) => invitation.id === invitationsRespond[0]);
if (invitationsRespond.length <= 0 && !invitation?.role) return;
setIsJoiningWorkspaces(true);
try {
await workspaceService.joinWorkspaces({ invitations: invitationsRespond });
await fetchWorkspaces();
await fetchCurrentUserSettings();
await handleNextStep();
} catch (error: any) {
console.error(error);
setIsJoiningWorkspaces(false);
}
};
return invitations && invitations.length > 0 ? (
<div className="flex flex-col gap-10">
<CommonOnboardingHeader title="Join invites or create a workspace" description="All your work — unified." />
<div className="flex flex-col gap-3">
{invitations &&
invitations.length > 0 &&
invitations.map((invitation) => {
const isSelected = invitationsRespond.includes(invitation.id);
const invitedWorkspace = invitation.workspace;
return (
<div
key={invitation.id}
className={`flex cursor-pointer items-center gap-2 rounded-lg border border-subtle px-3 py-2 hover:bg-surface-2`}
onClick={() => handleInvitation(invitation, isSelected ? "withdraw" : "accepted")}
>
<div className="flex-shrink-0">
<WorkspaceLogo
logo={invitedWorkspace?.logo_url}
name={invitedWorkspace?.name}
classNames="size-8 flex-shrink-0 rounded-lg"
/>
</div>
<div className="min-w-0 flex-1">
<div className="text-13 font-medium">{truncateText(invitedWorkspace?.name, 30)}</div>
<p className="text-11 text-secondary">{ROLE[invitation.role]}</p>
</div>
<span className="pointer-events-none flex-shrink-0">
<Checkbox checked={isSelected} aria-label={invitedWorkspace?.name ?? "Select workspace invitation"} />
</span>
</div>
);
})}
</div>
<div className="flex flex-col gap-4">
<Button
variant="primary"
size="xl"
className="w-full"
onClick={submitInvitations}
disabled={isJoiningWorkspaces || !invitationsRespond.length}
>
{isJoiningWorkspaces ? <Spinner height="20px" width="20px" /> : "Continue"}
</Button>
<Button
variant="ghost"
size="xl"
className="w-full"
onClick={handleCurrentViewChange}
disabled={isJoiningWorkspaces}
>
Create new workspace
</Button>
</div>
</div>
) : (
<div>No Invitations found</div>
);
}

View File

@@ -0,0 +1,56 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
import React, { useEffect, useState } from "react";
import { observer } from "mobx-react";
// plane imports
import type { IWorkspaceMemberInvitation } from "@plane/types";
import { ECreateOrJoinWorkspaceViews, EOnboardingSteps } from "@plane/types";
// hooks
import { useUser } from "@/hooks/store/user";
// local components
import { WorkspaceCreateStep, WorkspaceJoinInvitesStep } from "./";
type Props = {
invitations: IWorkspaceMemberInvitation[];
handleStepChange: (step: EOnboardingSteps, skipInvites?: boolean) => void;
};
export const WorkspaceSetupStep = observer(function WorkspaceSetupStep({ invitations, handleStepChange }: Props) {
// states
const [currentView, setCurrentView] = useState<ECreateOrJoinWorkspaceViews | null>(null);
// store hooks
const { data: user } = useUser();
useEffect(() => {
if (invitations.length > 0) {
setCurrentView(ECreateOrJoinWorkspaceViews.WORKSPACE_JOIN);
} else {
setCurrentView(ECreateOrJoinWorkspaceViews.WORKSPACE_CREATE);
}
}, [invitations]);
return (
<>
{currentView === ECreateOrJoinWorkspaceViews.WORKSPACE_JOIN ? (
<WorkspaceJoinInvitesStep
invitations={invitations}
handleNextStep={async () => {
handleStepChange(EOnboardingSteps.WORKSPACE_CREATE_OR_JOIN, true);
}}
handleCurrentViewChange={() => setCurrentView(ECreateOrJoinWorkspaceViews.WORKSPACE_CREATE)}
/>
) : (
<WorkspaceCreateStep
user={user}
onComplete={(skipInvites) => handleStepChange(EOnboardingSteps.WORKSPACE_CREATE_OR_JOIN, skipInvites)}
handleCurrentViewChange={() => setCurrentView(ECreateOrJoinWorkspaceViews.WORKSPACE_JOIN)}
hasInvitations={invitations.length > 0}
/>
)}
</>
);
});