Initial commit: Plane
Some checks failed
Branch Build CE / Build Setup (push) Has been cancelled
Branch Build CE / Build-Push Admin Docker Image (push) Has been cancelled
Branch Build CE / Build-Push Web Docker Image (push) Has been cancelled
Branch Build CE / Build-Push Space Docker Image (push) Has been cancelled
Branch Build CE / Build-Push Live Collaboration Docker Image (push) Has been cancelled
Branch Build CE / Build-Push API Server Docker Image (push) Has been cancelled
Branch Build CE / Build-Push Proxy Docker Image (push) Has been cancelled
Branch Build CE / Build-Push AIO Docker Image (push) Has been cancelled
Branch Build CE / Upload Build Assets (push) Has been cancelled
Branch Build CE / Build Release (push) Has been cancelled
CodeQL / Analyze (javascript) (push) Has been cancelled
CodeQL / Analyze (python) (push) Has been cancelled
Codespell / Check for spelling errors (push) Has been cancelled
Sync Repositories / sync_changes (push) Has been cancelled

Synced from upstream: 8853637e981ed7d8a6cff32bd98e7afe20f54362
This commit is contained in:
chuan
2025-11-07 00:00:52 +08:00
commit 8ebde8aa05
4886 changed files with 462270 additions and 0 deletions

View File

@@ -0,0 +1,15 @@
"use client";
import type { FC } from "react";
type Props = {
title: string;
description: string;
};
export const CommonOnboardingHeader: FC<Props> = ({ title, description }) => (
<div className="text-left space-y-2">
<h1 className="text-2xl font-semibold text-custom-text-200">{title}</h1>
<p className="text-base text-custom-text-300">{description}</p>
</div>
);

View File

@@ -0,0 +1 @@
export * from "./header";

View File

@@ -0,0 +1 @@
export * from "./root";

View File

@@ -0,0 +1,24 @@
"use client";
import type { FC } from "react";
import { Check } from "lucide-react";
type Props = {
isChecked: boolean;
handleChange: (checked: boolean) => void;
};
export const MarketingConsent: FC<Props> = ({ isChecked, handleChange }) => (
<div className="flex items-center justify-center gap-1.5">
<button
type="button"
onClick={() => handleChange(!isChecked)}
className={`size-4 rounded border-2 flex items-center justify-center ${
isChecked ? "bg-custom-primary-100 border-custom-primary-100" : "border-custom-border-300"
}`}
>
{isChecked && <Check className="w-3 h-3 text-white" />}
</button>
<span className="text-sm text-custom-text-300">I agree to Plane marketing communications</span>
</div>
);

View File

@@ -0,0 +1 @@
export * from "./root";

View File

@@ -0,0 +1,266 @@
"use client";
import type { FC } from "react";
import { useMemo, useState } from "react";
import { observer } from "mobx-react";
import { Controller, useForm } from "react-hook-form";
import { ImageIcon } from "lucide-react";
// plane imports
import { E_PASSWORD_STRENGTH, ONBOARDING_TRACKER_ELEMENTS, USER_TRACKER_EVENTS } 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 } from "@plane/utils";
// components
import { UserImageUploadModal } from "@/components/core/modals/user-image-upload-modal";
// helpers
import { captureError, captureView } from "@/helpers/event-tracker.helper";
// hooks
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: FC<Props> = observer(({ handleStepChange }) => {
// states
const [isImageUploadModalOpen, setIsImageUploadModalOpen] = useState(false);
// store hooks
const { data: user, updateCurrentUser } = useUser();
const { updateUserProfile } = useUserProfile();
// 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 {
captureError({
eventName: USER_TRACKER_EVENTS.add_details,
});
setToast({
type: TOAST_TYPE.ERROR,
title: "Error",
message: "User details update failed. Please try again!",
});
}
};
const onSubmit = async (formData: TProfileSetupFormValues) => {
if (!user) return;
captureView({
elementName: ONBOARDING_TRACKER_ELEMENTS.PROFILE_SETUP_FORM,
});
updateUserProfile({
has_marketing_email_consent: formData.has_marketing_email_consent,
});
await handleSubmitUserDetail(formData).then(() => {
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="size-12 rounded-full bg-[#028375] flex items-center justify-center text-white font-semibold text-xl"
type="button"
onClick={() => setIsImageUploadModalOpen(true)}
>
{userAvatar ? (
<img
src={getFileURL(userAvatar ?? "")}
onClick={() => setIsImageUploadModalOpen(true)}
alt={user?.display_name}
className="w-full h-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 text-custom-text-300 hover:text-custom-text-200 text-sm px-2 py-1"
type="button"
onClick={() => setIsImageUploadModalOpen(true)}
>
<ImageIcon className="size-4" />
<span className="text-sm">{userAvatar ? "Change image" : "Upload image"}</span>
</button>
</div>
<div className="flex flex-col gap-6 w-full">
{/* Name Input */}
<div className="flex flex-col gap-2">
<label
className="block text-sm font-medium text-custom-text-300 after:content-['*'] after:ml-0.5 after:text-red-500"
htmlFor="first_name"
>
Name
</label>
<Controller
control={control}
name="first_name"
rules={{
required: "Name is required",
maxLength: {
value: 24,
message: "Name must be within 24 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 px-3 py-2 text-custom-text-200 border border-custom-border-300 rounded-md bg-custom-background-100 focus:outline-none focus:ring-2 focus:ring-custom-primary-100 placeholder:text-custom-text-400 focus:border-transparent transition-all duration-200",
{
"border-custom-border-300": !errors.first_name,
"border-red-500": errors.first_name,
}
)}
placeholder="Enter your full name"
autoComplete="on"
/>
)}
/>
{errors.first_name && <span className="text-sm text-red-500">{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="lg" disabled={isButtonDisabled}>
Continue
</Button>
{/* Marketing Consent */}
<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,136 @@
"use client";
import React, { useState, useCallback, useMemo } from "react";
import { Lock } from "lucide-react";
import { ChevronDownIcon } from "@plane/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 const SetPasswordRoot: React.FC<SetPasswordRootProps> = ({
onPasswordChange,
onConfirmPasswordChange,
disabled = false,
}) => {
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-custom-text-400 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 rounded-lg overflow-hidden transition-all duration-300 ease-in-out bg-custom-background-90`}
>
<div
className={cn(
"flex items-center justify-between transition-colors duration-200 px-3 py-2 text-sm",
disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer",
isExpanded && "pb-1"
)}
onClick={handleToggleExpand}
>
<div className="flex items-center gap-1 text-custom-text-300">
<Lock className="size-3" />
<span className="font-medium">Set a password</span>
<span>{`(Optional)`}</span>
</div>
<div className="flex items-center gap-2 text-custom-text-400">
<ChevronDownIcon className={chevronIconClasses} />
</div>
</div>
<div className={expandedContentClasses}>
{/* Password input */}
<div className="flex flex-col gap-2 transform transition-all duration-300 ease-in-out pt-1">
<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="text-custom-text-300 font-medium transform transition-all duration-300 ease-in-out delay-75 text-sm">
Confirm password
</div>
{/* Confirm password input */}
<div className="transform transition-all duration-300 ease-in-out delay-100">
<PasswordInput
id="confirm-password"
value={passwordState.confirmPassword}
onChange={(value) => handlePasswordChange("confirmPassword", value)}
placeholder="Confirm password"
className="transition-all duration-200"
/>
{hasPasswordMismatch && <p className="text-xs text-red-500 mt-1">Passwords do not match</p>}
{isPasswordValid && <p className="text-xs text-green-500 mt-1"> Passwords match</p>}
</div>
</div>
</div>
</div>
);
};

View File

@@ -0,0 +1 @@
export * from "./root";

View File

@@ -0,0 +1,171 @@
"use client";
import type { FC } from "react";
import { observer } from "mobx-react";
import { Controller, useForm } from "react-hook-form";
import { Box, Check, PenTool, Rocket, Monitor, RefreshCw } from "lucide-react";
// plane imports
import { ONBOARDING_TRACKER_ELEMENTS, USER_TRACKER_EVENTS } from "@plane/constants";
import { Button } from "@plane/propel/button";
import { ViewsIcon } from "@plane/propel/icons";
import { TOAST_TYPE, setToast } from "@plane/propel/toast";
import type { TUserProfile } from "@plane/types";
import { EOnboardingSteps } from "@plane/types";
// helpers
import { captureError, captureSuccess, captureView } from "@/helpers/event-tracker.helper";
// 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: Box },
{ id: "engineering-manager", label: "Engineering Manager", icon: ViewsIcon },
{ id: "designer", label: "Designer", icon: PenTool },
{ id: "developer", label: "Developer", icon: Monitor },
{ id: "founder-executive", label: "Founder/Executive", icon: Rocket },
{ id: "operations-manager", label: "Operations Manager", icon: RefreshCw },
{ id: "others", label: "Others", icon: Box },
];
const defaultValues = {
role: "",
};
export const RoleSetupStep: FC<Props> = observer(({ handleStepChange }) => {
// 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 }),
]);
captureSuccess({
eventName: USER_TRACKER_EVENTS.add_details,
payload: {
use_case: formData.use_case,
role: formData.role,
},
});
setToast({
type: TOAST_TYPE.SUCCESS,
title: "Success",
message: "Profile setup completed!",
});
} catch {
captureError({
eventName: USER_TRACKER_EVENTS.add_details,
});
setToast({
type: TOAST_TYPE.ERROR,
title: "Error",
message: "Profile setup failed. Please try again!",
});
}
};
const onSubmit = async (formData: TProfileSetupFormValues) => {
if (!profile) return;
captureView({
elementName: ONBOARDING_TRACKER_ELEMENTS.PROFILE_SETUP_FORM,
});
await handleSubmitUserPersonalization(formData).then(() => {
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-sm font-medium text-custom-text-400">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={`w-full px-3 py-2 rounded-lg border transition-all duration-200 flex items-center justify-between ${
isSelected
? "border-custom-primary-100 bg-custom-primary-10 text-custom-primary-100"
: "border-custom-border-200 hover:border-custom-border-300 text-custom-text-300"
}`}
>
<div className="flex items-center space-x-3">
<Icon className="size-3.5" />
<span className="font-medium">{role.label}</span>
</div>
{isSelected && (
<>
<button
className={`size-4 rounded border-2 flex items-center justify-center bg-blue-500 border-blue-500`}
>
<Check className="w-3 h-3 text-white" />
</button>
</>
)}
</button>
);
})}
</div>
)}
/>
{errors.role && <span className="text-sm text-red-500">{errors.role.message}</span>}
</div>
{/* Action Buttons */}
<div className="space-y-3">
<Button variant="primary" type="submit" className="w-full" size="lg" disabled={isButtonDisabled}>
Continue
</Button>
<Button variant="link-neutral" onClick={handleSkip} className="w-full" size="lg">
Skip
</Button>
</div>
</form>
);
});

View File

@@ -0,0 +1,57 @@
"use client";
import type { FC } from "react";
import { useEffect, useMemo, 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;
};
export const OnboardingStepRoot: FC<Props> = (props) => {
const { currentStep, invitations, handleStepChange } = 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]);
// memoized step component mapping
const stepComponents = useMemo(
() => ({
[EOnboardingSteps.PROFILE_SETUP]: <ProfileSetupStep handleStepChange={handleStepChange} />,
[EOnboardingSteps.ROLE_SETUP]: <RoleSetupStep handleStepChange={handleStepChange} />,
[EOnboardingSteps.USE_CASE_SETUP]: <UseCaseSetupStep handleStepChange={handleStepChange} />,
[EOnboardingSteps.WORKSPACE_CREATE_OR_JOIN]: (
<WorkspaceSetupStep invitations={invitations ?? []} handleStepChange={handleStepChange} />
),
[EOnboardingSteps.INVITE_MEMBERS]: <InviteTeamStep handleStepChange={handleStepChange} />,
}),
[handleStepChange, invitations]
);
return (
<div ref={scrollContainerRef} className="flex-1 overflow-y-auto">
<div className="flex items-center justify-center min-h-full p-8">
<div className="w-full max-w-[24rem]">{stepComponents[currentStep]} </div>
</div>
</div>
);
};

View File

@@ -0,0 +1 @@
export * from "./root";

View File

@@ -0,0 +1,416 @@
"use client";
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";
// icons
import { usePopper } from "react-popper";
import { Check, Plus, XCircle } from "lucide-react";
import { Listbox } from "@headlessui/react";
// plane imports
import type { EUserPermissions } from "@plane/constants";
import { ROLE, ROLE_DETAILS, MEMBER_TRACKER_EVENTS, MEMBER_TRACKER_ELEMENTS } from "@plane/constants";
import { useTranslation } from "@plane/i18n";
import { Button } from "@plane/propel/button";
import { ChevronDownIcon } from "@plane/propel/icons";
import { TOAST_TYPE, setToast } from "@plane/propel/toast";
// types
import { EOnboardingSteps } from "@plane/types";
// ui
import { Input, Spinner } from "@plane/ui";
// constants
// helpers
// hooks
import { captureError, captureSuccess } from "@/helpers/event-tracker.helper";
import { useWorkspace } from "@/hooks/store/use-workspace";
// services
import { WorkspaceService } from "@/plane-web/services";
// 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: React.FC<InviteMemberFormProps> = observer((props) => {
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 } }) => (
<Input
id={`emails.${index}.email`}
name={`emails.${index}.email`}
type="text"
value={value}
onChange={(event) => {
emailOnChange(event);
onChange(event);
}}
ref={ref}
hasError={Boolean(errors.emails?.[index]?.email)}
placeholder={placeholderEmails[index % placeholderEmails.length]}
className="w-full border-custom-border-300 text-xs placeholder:text-custom-text-400 sm:text-sm"
autoComplete="off"
/>
)}
/>
</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 px-2.5 py-2 text-sm border-[0.5px] border-custom-border-300"
>
<span
className={`text-sm ${
!getValues(`emails.${index}.role_active`) ? "text-custom-text-400" : "text-custom-text-100"
} sm:text-sm`}
>
{ROLE[value]}
</span>
<ChevronDownIcon
className={`size-3 ${
!getValues(`emails.${index}.role_active`)
? "stroke-onboarding-text-400"
: "stroke-onboarding-text-100"
}`}
/>
</Listbox.Button>
<Listbox.Options as="div">
<div
className="p-2 absolute space-y-1 z-10 mt-1 h-fit w-48 sm:w-60 rounded-md border border-custom-border-300 bg-custom-background-100 shadow-sm focus:outline-none"
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 select-none truncate rounded px-1 py-1.5 ${
active || selected ? "bg-onboarding-background-400/40" : ""
} ${selected ? "text-custom-text-100" : "text-custom-text-200"}`
}
>
{({ selected }) => (
<div className="flex items-center text-wrap gap-2 p-1">
<div className="flex flex-col">
<div className="text-sm font-medium">{t(value.i18n_title)}</div>
<div className="flex text-xs text-custom-text-300">{t(value.i18n_description)}</div>
</div>
{selected && <Check 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 group-hover:grid"
onClick={() => remove(index)}
>
<XCircle className="h-5 w-5 pl-0.5 text-custom-text-400" />
</button>
)}
</div>
{email && !emailRegex.test(email) && (
<div className="mx-8 my-1">
<span className="text-sm">🤥</span>{" "}
<span className="mt-1 text-xs text-red-500">That doesn{"'"}t look like an email address.</span>
</div>
)}
</div>
);
});
export const InviteTeamStep: React.FC<Props> = observer((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 () => {
captureSuccess({
eventName: MEMBER_TRACKER_EVENTS.invite,
payload: {
workspace: workspace.slug,
},
});
setToast({
type: TOAST_TYPE.SUCCESS,
title: "Success!",
message: "Invitations sent successfully.",
});
await nextStep();
})
.catch((err) => {
captureError({
eventName: MEMBER_TRACKER_EVENTS.invite,
payload: {
workspace: workspace.slug,
},
error: 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 text-sm py-4">
<div className="group relative grid grid-cols-10 gap-4 mx-8 py-2">
<div className="col-span-6 px-1 text-sm text-custom-text-200 font-medium">Email</div>
<div className="col-span-4 px-1 text-sm text-custom-text-200 font-medium">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="flex items-center mx-8 gap-1.5 bg-transparent text-sm font-medium text-custom-primary-100 outline-custom-primary-100"
onClick={appendField}
>
<Plus className="h-4 w-4" strokeWidth={2} />
Add another
</button>
</div>
<div className="flex flex-col mx-auto px-8 sm:px-2 items-center justify-center gap-4 w-full">
<Button
variant="primary"
type="submit"
size="lg"
className="w-full"
disabled={isInvitationDisabled || !isValid || isSubmitting}
data-ph-element={MEMBER_TRACKER_ELEMENTS.ONBOARDING_INVITE_MEMBER}
>
{isSubmitting ? <Spinner height="20px" width="20px" /> : "Continue"}
</Button>
<Button variant="link-neutral" size="lg" className="w-full" onClick={nextStep}>
Ill do it later
</Button>
</div>
</form>
);
});

View File

@@ -0,0 +1 @@
export * from "./root";

View File

@@ -0,0 +1,166 @@
"use client";
import type { FC } from "react";
import { observer } from "mobx-react";
import { Controller, useForm } from "react-hook-form";
import { Check } from "lucide-react";
// plane imports
import { ONBOARDING_TRACKER_ELEMENTS, USER_TRACKER_EVENTS, USE_CASES } from "@plane/constants";
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";
import { cn } from "@plane/utils";
// helpers
import { captureError, captureSuccess, captureView } from "@/helpers/event-tracker.helper";
// 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: "",
};
export const UseCaseSetupStep: FC<Props> = observer(({ handleStepChange }) => {
// 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,
},
mode: "onChange",
});
// handle submit
const handleSubmitUserPersonalization = async (formData: TProfileSetupFormValues) => {
const profileUpdatePayload: Partial<TUserProfile> = {
use_case: formData.use_case,
};
try {
await Promise.all([
updateUserProfile(profileUpdatePayload),
// totalSteps > 2 && stepChange({ profile_complete: true }),
]);
captureSuccess({
eventName: USER_TRACKER_EVENTS.add_details,
payload: {
use_case: formData.use_case,
},
});
setToast({
type: TOAST_TYPE.SUCCESS,
title: "Success",
message: "Profile setup completed!",
});
} catch {
captureError({
eventName: USER_TRACKER_EVENTS.add_details,
});
setToast({
type: TOAST_TYPE.ERROR,
title: "Error",
message: "Profile setup failed. Please try again!",
});
}
};
// on submit
const onSubmit = async (formData: TProfileSetupFormValues) => {
if (!profile) return;
captureView({
elementName: ONBOARDING_TRACKER_ELEMENTS.PROFILE_SETUP_FORM,
});
await handleSubmitUserPersonalization(formData).then(() => {
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-sm font-medium text-custom-text-400">Select any</p>
<Controller
control={control}
name="use_case"
rules={{
required: "This field is required",
}}
render={({ field: { value, onChange } }) => (
<div className="flex flex-col gap-3">
{USE_CASES.map((useCase) => {
const isSelected = value === useCase;
return (
<button
key={useCase}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onChange(useCase);
}}
className={`w-full px-3 py-2 rounded-lg border transition-all duration-200 flex items-center gap-2 ${
isSelected
? "border-custom-primary-100 bg-custom-primary-10 text-custom-primary-100"
: "border-custom-border-200 hover:border-custom-border-300 text-custom-text-300"
}`}
>
<span
className={cn(`size-4 rounded border-2 flex items-center justify-center`, {
"bg-custom-primary-100 border-custom-primary-100": isSelected,
"border-custom-border-300": !isSelected,
})}
>
<Check
className={cn("w-3 h-3 text-white", {
"opacity-100": isSelected,
"opacity-0": !isSelected,
})}
/>
</span>
<span className="font-medium">{useCase}</span>
</button>
);
})}
</div>
)}
/>
{errors.use_case && <span className="text-sm text-red-500">{errors.use_case.message}</span>}
</div>
{/* Action Buttons */}
<div className="space-y-3">
<Button variant="primary" type="submit" className="w-full" size="lg" disabled={isButtonDisabled}>
Continue
</Button>
<Button variant="link-neutral" onClick={handleSkip} className="w-full" size="lg">
Skip
</Button>
</div>
</form>
);
});

View File

@@ -0,0 +1,318 @@
"use client";
import React, { useState } from "react";
import { observer } from "mobx-react";
import { Controller, useForm } from "react-hook-form";
import { CircleCheck } from "lucide-react";
// plane imports
import {
ORGANIZATION_SIZE,
RESTRICTED_URLS,
WORKSPACE_TRACKER_ELEMENTS,
WORKSPACE_TRACKER_EVENTS,
} 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 } from "@plane/utils";
// helpers
import { captureError, captureSuccess } from "@/helpers/event-tracker.helper";
// hooks
import { useWorkspace } from "@/hooks/store/use-workspace";
import { useUserProfile, useUserSettings } from "@/hooks/store/user";
// plane-web imports
import { getIsWorkspaceCreationDisabled } from "@/plane-web/helpers/instance.helper";
import { WorkspaceService } from "@/plane-web/services";
// 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: React.FC<Props> = observer(
({ user, onComplete, handleCurrentViewChange, hasInvitations = false }) => {
// states
const [slugError, setSlugError] = useState(false);
const [invalidSlug, setInvalidSlug] = useState(false);
// plane hooks
const { t } = useTranslation();
// store hooks
const { updateUserProfile } = useUserProfile();
const { fetchCurrentUserSettings } = useUserSettings();
const { createWorkspace, fetchWorkspaces } = useWorkspace();
const isWorkspaceCreationEnabled = getIsWorkspaceCreationDisabled() === 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;
await workspaceService
.workspaceSlugCheck(formData.slug)
.then(async (res) => {
if (res.status === true && !RESTRICTED_URLS.includes(formData.slug)) {
setSlugError(false);
await createWorkspace(formData)
.then(async (workspaceResponse) => {
setToast({
type: TOAST_TYPE.SUCCESS,
title: t("workspace_creation.toast.success.title"),
message: t("workspace_creation.toast.success.message"),
});
captureSuccess({
eventName: WORKSPACE_TRACKER_EVENTS.create,
payload: { slug: formData.slug },
});
await fetchWorkspaces();
await completeStep(workspaceResponse.id);
onComplete(formData.organization_size === "Just myself");
})
.catch(() => {
captureError({
eventName: WORKSPACE_TRACKER_EVENTS.create,
payload: { slug: formData.slug },
error: new Error("Error creating workspace"),
});
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 (!isWorkspaceCreationEnabled) {
return (
<div className="flex flex-col gap-10">
<span className="text-center text-base text-custom-text-300">
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={handleSubmit(handleCreateWorkspace)}>
<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-sm text-custom-text-300 font-medium after:content-['*'] after:ml-0.5 after:text-red-500"
htmlFor="name"
>
{t("workspace_creation.form.name.label")}
</label>
<Controller
control={control}
name="name"
rules={{
required: t("common.errors.required"),
validate: (value) =>
/^[\w\s-]*$/.test(value) || t("workspace_creation.errors.validation.name_alphanumeric"),
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 px-3 py-2 text-custom-text-200 border border-custom-border-300 rounded-md bg-custom-background-100 focus:outline-none focus:ring-2 focus:ring-custom-primary-100 placeholder:text-custom-text-400 focus:border-transparent transition-all duration-200",
{
"border-custom-border-300": !errors.name,
"border-red-500": errors.name,
}
)}
autoFocus
/>
</div>
)}
/>
{errors.name && <span className="text-sm text-red-500">{errors.name.message}</span>}
</div>
<div className="flex flex-col gap-2">
<label
className="text-sm text-custom-text-300 font-medium after:content-['*'] after:ml-0.5 after:text-red-500"
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 items-center w-full px-3 py-2 text-custom-text-200 border border-custom-border-300 rounded-md bg-custom-background-100 focus:outline-none focus:ring-2 focus:ring-custom-primary-100 focus:border-transparent transition-all duration-200",
{
"border-custom-border-300": !errors.name,
"border-red-500": errors.name,
}
)}
>
<span className={cn("pr-0 text-custom-text-200 rounded-md whitespace-nowrap")}>
{window && window.location.host}/
</span>
<input
id="slug"
name="slug"
type="text"
value={value.toLocaleLowerCase().trim().replace(/ /g, "-")}
onChange={(e) => {
if (/^[a-zA-Z0-9_-]+$/.test(e.target.value)) setInvalidSlug(false);
else setInvalidSlug(true);
onChange(e.target.value.toLowerCase());
}}
ref={ref}
placeholder={t("workspace_creation.form.url.placeholder")}
className={cn(
"w-full px-3 py-0 pl-0 text-custom-text-200 border-none ring-none outline-none rounded-md bg-custom-background-100 placeholder:text-custom-text-400"
)}
/>
</div>
)}
/>
<p className="text-sm text-custom-text-300">{t("workspace_creation.form.url.edit_slug")}</p>
{slugError && (
<p className="-mt-3 text-sm text-red-500">
{t("workspace_creation.errors.validation.url_already_taken")}
</p>
)}
{invalidSlug && (
<p className="text-sm text-red-500">{t("workspace_creation.errors.validation.url_alphanumeric")}</p>
)}
{errors.slug && <span className="text-sm text-red-500">{errors.slug.message}</span>}
</div>
<div className="flex flex-col gap-2">
<label
className="text-sm text-custom-text-300 font-medium after:content-['*'] after:ml-0.5 after:text-red-500"
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={`text-sm px-3 py-2 rounded-lg border transition-all duration-200 flex gap-1 items-center justify-between ${
isSelected
? "border-custom-border-200 bg-custom-background-80 text-custom-text-200"
: "border-custom-border-200 hover:border-custom-border-300 text-custom-text-300"
}`}
>
<CircleCheck
className={cn("size-4 text-custom-text-400", isSelected && "text-custom-text-200")}
/>
<span className="font-medium">{size}</span>
</button>
);
})}
</div>
)}
/>
{errors.organization_size && (
<span className="text-sm text-red-500">{errors.organization_size.message}</span>
)}
</div>
</div>
</div>
<div className="flex flex-col gap-4">
<Button
data-ph-element={WORKSPACE_TRACKER_ELEMENTS.ONBOARDING_CREATE_WORKSPACE_BUTTON}
variant="primary"
type="submit"
size="lg"
className="w-full"
disabled={isButtonDisabled}
>
{isSubmitting ? <Spinner height="20px" width="20px" /> : t("workspace_creation.button.default")}
</Button>
{hasInvitations && (
<Button variant="link-neutral" size="lg" className="w-full" onClick={handleCurrentViewChange}>
Join existing workspace
</Button>
)}
</div>
</form>
);
}
);

View File

@@ -0,0 +1,3 @@
export * from "./create";
export * from "./join-invites";
export * from "./root";

View File

@@ -0,0 +1,137 @@
"use client";
import React, { useState } from "react";
// plane imports
import { MEMBER_TRACKER_ELEMENTS, MEMBER_TRACKER_EVENTS, ROLE } from "@plane/constants";
import { Button } from "@plane/propel/button";
import type { IWorkspaceMemberInvitation } from "@plane/types";
import { Checkbox, Spinner } from "@plane/ui";
import { truncateText } from "@plane/utils";
// constants
import { WorkspaceLogo } from "@/components/workspace/logo";
// helpers
import { captureError, captureSuccess } from "@/helpers/event-tracker.helper";
// hooks
import { useWorkspace } from "@/hooks/store/use-workspace";
import { useUserSettings } from "@/hooks/store/user";
// services
import { WorkspaceService } from "@/plane-web/services";
// local components
import { CommonOnboardingHeader } from "../common";
type Props = {
invitations: IWorkspaceMemberInvitation[];
handleNextStep: () => Promise<void>;
handleCurrentViewChange: () => void;
};
const workspaceService = new WorkspaceService();
export const WorkspaceJoinInvitesStep: React.FC<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 });
captureSuccess({
eventName: MEMBER_TRACKER_EVENTS.accept,
payload: {
member_id: invitation?.id,
},
});
await fetchWorkspaces();
await fetchCurrentUserSettings();
await handleNextStep();
} catch (error: any) {
console.error(error);
captureError({
eventName: MEMBER_TRACKER_EVENTS.accept,
payload: {
member_id: invitation?.id,
},
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 px-3 py-2 border-custom-border-200 hover:bg-custom-background-90`}
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-sm font-medium">{truncateText(invitedWorkspace?.name, 30)}</div>
<p className="text-xs text-custom-text-200">{ROLE[invitation.role]}</p>
</div>
<span className={`flex-shrink-0`}>
<Checkbox checked={isSelected} />
</span>
</div>
);
})}
</div>
<div className="flex flex-col gap-4">
<Button
variant="primary"
size="lg"
className="w-full"
onClick={submitInvitations}
disabled={isJoiningWorkspaces || !invitationsRespond.length}
data-ph-element={MEMBER_TRACKER_ELEMENTS.ONBOARDING_JOIN_WORKSPACE}
>
{isJoiningWorkspaces ? <Spinner height="20px" width="20px" /> : "Continue"}
</Button>
<Button
variant="link-neutral"
size="lg"
className="w-full"
onClick={handleCurrentViewChange}
disabled={isJoiningWorkspaces}
>
Create new workspace
</Button>
</div>
</div>
) : (
<div>No Invitations found</div>
);
};

View File

@@ -0,0 +1,52 @@
"use client";
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: React.FC<Props> = observer(({ invitations, handleStepChange }) => {
// 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}
/>
)}
</>
);
});