Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(dashboard): add delay step #7131

Open
wants to merge 20 commits into
base: next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions apps/dashboard/src/components/number-input-with-select.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { cn } from '@/utils/ui';
import { FormControl, FormField, FormItem, FormMessagePure } from '@/components/primitives/form/form';
import { Input } from '@/components/primitives/input';
import { InputFieldPure } from '@/components/primitives/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/primitives/select';
import { UseFormReturn } from 'react-hook-form';
import { useMemo } from 'react';

type InputWithSelectProps = {
form: UseFormReturn<any>;
inputName: string;
selectName: string;
options: string[];
defaultOption?: string;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need the default option prop? The unit prop should be the default option otherwise its defaultOption[0].

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We dictate the default selected value in ui schema coming from backend, so its needed.

className?: string;
placeholder?: string;
isReadOnly?: boolean;
};

export const NumberInputWithSelect = (props: InputWithSelectProps) => {
ChmaraX marked this conversation as resolved.
Show resolved Hide resolved
const { className, form, inputName, selectName, options, defaultOption, placeholder, isReadOnly } = props;

const amount = form.getFieldState(`${inputName}`);
const unit = form.getFieldState(`${selectName}`);
const error = amount.error || unit.error;

const defaultSelectedValue = useMemo(() => {
return defaultOption ?? options[0];
}, [defaultOption, options]);

const handleChange = (value: { input: number; select: string }) => {
// we want to always set both values and treat it as a single input
form.setValue(inputName, value.input, { shouldDirty: true });
form.setValue(selectName, value.select, { shouldDirty: true });
};

return (
<>
<InputFieldPure className="h-7 rounded-lg border pr-0">
ChmaraX marked this conversation as resolved.
Show resolved Hide resolved
<FormField
control={form.control}
name={inputName}
render={({ field }) => (
<FormItem className="w-full overflow-hidden">
<FormControl>
<Input
type="number"
ChmaraX marked this conversation as resolved.
Show resolved Hide resolved
className={cn(
'min-w-[20ch] [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none',
className
)}
placeholder={placeholder}
disabled={isReadOnly}
{...field}
onChange={(e) => {
handleChange({ input: Number(e.target.value), select: form.getValues(selectName) });
}}
/>
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name={selectName}
render={({ field }) => (
<FormItem>
<FormControl>
<Select
onValueChange={(value) => {
handleChange({ input: Number(form.getValues(inputName)), select: value });
}}
defaultValue={defaultSelectedValue}
disabled={isReadOnly}
{...field}
>
<SelectTrigger className="h-7 w-auto translate-x-1 gap-1 rounded-l-none border-l bg-neutral-50 p-2 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
{options.map((option) => (
<SelectItem key={option} value={option}>
{option}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
</FormItem>
)}
/>
</InputFieldPure>
<FormMessagePure error={error ? String(error.message) : undefined} />
ChmaraX marked this conversation as resolved.
Show resolved Hide resolved
</>
);
};
4 changes: 2 additions & 2 deletions apps/dashboard/src/components/primitives/form/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,8 @@ const FormMessagePure = React.forwardRef<
className={formMessageVariants({ variant: error ? 'error' : 'default', className })}
{...props}
>
{error ? <RiErrorWarningFill className="size-4" /> : <RiInformationFill className="size-4" />}
<span className="mt-[1px] text-xs leading-3">{body}</span>
<span>{error ? <RiErrorWarningFill className="size-4" /> : <RiInformationFill className="size-4" />}</span>
<span className="mt-[1px] text-xs leading-normal">{body}</span>
</p>
);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,13 @@ export const AddStepMenu = ({
<MenuTitle>Action Steps</MenuTitle>
<MenuItemsGroup>
<MenuItem stepType={StepTypeEnum.DIGEST}>Digest</MenuItem>
<MenuItem stepType={StepTypeEnum.DELAY}>Delay</MenuItem>
<MenuItem
stepType={StepTypeEnum.DELAY}
disabled={true}
onClick={() => handleMenuItemClick(StepTypeEnum.DELAY)}
>
Delay
</MenuItem>
ChmaraX marked this conversation as resolved.
Show resolved Hide resolved
</MenuItemsGroup>
</MenuGroup>
</div>
Expand Down
1 change: 1 addition & 0 deletions apps/dashboard/src/components/workflow-editor/nodes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ export const DelayNode = (props: NodeProps<NodeType>) => {
<NodeName>{data.name || 'Delay Step'}</NodeName>
</NodeHeader>
<NodeBody>{data.content || 'You have been invited to the Novu party on "commentSnippet"'}</NodeBody>
{data.error && <NodeError>{data.error}</NodeError>}
<Handle isConnectable={false} className={handleClassName} type="target" position={Position.Top} id="a" />
<Handle isConnectable={false} className={handleClassName} type="source" position={Position.Bottom} id="b" />
</StepNode>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { StepTypeEnum } from '@novu/shared';
import { useMemo } from 'react';
import { RiArrowRightSLine, RiPencilRuler2Fill } from 'react-icons/ri';
import { Link } from 'react-router-dom';
import { RiArrowRightSLine, RiPencilRuler2Fill } from 'react-icons/ri';
import { StepTypeEnum } from '@novu/shared';

import { DelayConfigure } from '@/components/workflow-editor/steps/delay/delay-configure';
import { Button } from '@/components/primitives/button';
import { Separator } from '@/components/primitives/separator';
import { SidebarContent } from '@/components/side-navigation/sidebar';
Expand All @@ -12,6 +12,7 @@ import { SdkBanner } from '@/components/workflow-editor/steps/sdk-banner';
import { useStep } from '@/components/workflow-editor/steps/use-step';
import { EXCLUDED_EDITOR_TYPES } from '@/utils/constants';
import { ConfigureInAppStepTemplate } from '@/components/workflow-editor/steps/in-app/configure-in-app-step-template';
import { useMemo } from 'react';

export const ConfigureStepContent = () => {
const { step } = useStep();
Expand All @@ -21,23 +22,33 @@ export const ConfigureStepContent = () => {
[step]
);

if (!step?.type) {
return null;
}

ChmaraX marked this conversation as resolved.
Show resolved Hide resolved
if (step?.type === StepTypeEnum.IN_APP) {
return <ConfigureInAppStepTemplate step={step} issue={firstError} />;
}

if (step.type === StepTypeEnum.DELAY) {
return <DelayConfigure />;
}

const showTemplateEditor = !EXCLUDED_EDITOR_TYPES.includes(step.type);

return (
<>
<SidebarContent>
<CommonFields />
</SidebarContent>
<Separator />
{!EXCLUDED_EDITOR_TYPES.includes(step?.type ?? '') && (
{showTemplateEditor && (
<>
<SidebarContent>
<Link to={'./edit'} relative="path" state={{ stepType: step?.type }}>
<Link to={'./edit'} relative="path" state={{ stepType: step.type }}>
<Button variant="outline" className="flex w-full justify-start gap-1.5 text-xs font-medium" type="button">
<RiPencilRuler2Fill className="h-4 w-4 text-neutral-600" />
Configure {step?.type} template <RiArrowRightSLine className="ml-auto h-4 w-4 text-neutral-600" />
Configure {step.type} template <RiArrowRightSLine className="ml-auto h-4 w-4 text-neutral-600" />
</Button>
</Link>
</SidebarContent>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import { Separator } from '@/components/primitives/separator';
import { SidebarContent } from '@/components/side-navigation/Sidebar';
import { CommonFields } from '@/components/workflow-editor/steps/common-fields';
import { useBlocker, useParams } from 'react-router-dom';
import { flattenIssues } from '@/components/workflow-editor/step-utils';
import { useCallback, useEffect, useMemo } from 'react';
import { useStepEditorContext } from '@/components/workflow-editor/steps/hooks';
import { buildDefaultValues, buildDynamicZodSchema } from '@/utils/schema';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { NumberInputWithSelect } from '@/components/number-input-with-select';
import { FormLabel } from '@/components/primitives/form/form';
import { Form } from '@/components/primitives/form/form';
import { useWorkflowEditorContext } from '@/components/workflow-editor/hooks';
import debounce from 'lodash.debounce';
import { z } from 'zod';
import { TimeUnitEnum } from '@novu/shared';
import { useUpdateWorkflow } from '@/hooks/use-update-workflow';
import { showToast } from '@/components/primitives/sonner-helpers';
import { ToastIcon } from '@/components/primitives/sonner';
import { UnsavedChangesAlertDialog } from '@/components/unsaved-changes-alert-dialog';
import merge from 'lodash.merge';

const TOAST_CONFIG = {
position: 'bottom-left' as const,
classNames: { toast: 'ml-10 mb-4' },
};

const delayControlsSchema = z
.object({
type: z.enum(['regular']).default('regular'),
amount: z.number(),
unit: z.nativeEnum(TimeUnitEnum),
})
.strict();
ChmaraX marked this conversation as resolved.
Show resolved Hide resolved

const defaultUnitValues = Object.values(TimeUnitEnum);

export const DelayConfigure = () => {
const { stepSlug = '' } = useParams<{ workflowSlug: string; stepSlug: string }>();
const { step, refetch } = useStepEditorContext();
ChmaraX marked this conversation as resolved.
Show resolved Hide resolved
const { workflow, isReadOnly } = useWorkflowEditorContext();
const { uiSchema, dataSchema, values } = step?.controls ?? {};

const unitOptions = useMemo(() => (dataSchema?.properties?.unit as any)?.enum ?? defaultUnitValues, [dataSchema]);
const schema = buildDynamicZodSchema(dataSchema ?? {});
const newFormValues = useMemo(() => merge(buildDefaultValues(uiSchema ?? {}), values), [uiSchema, values]);

const form = useForm<z.infer<typeof delayControlsSchema>>({
resolver: zodResolver(schema),
values: newFormValues as z.infer<typeof delayControlsSchema>,
});

const { updateWorkflow, isPending } = useUpdateWorkflow({
onSuccess: () => {
refetch();
showToast({
children: () => (
<>
<ToastIcon variant="success" />
<span className="text-sm">Saved</span>
</>
),
options: TOAST_CONFIG,
});
},
onError: () => {
showToast({
children: () => (
<>
<ToastIcon variant="error" />
<span className="text-sm">Failed to save</span>
</>
),
options: TOAST_CONFIG,
});
},
});

useEffect(() => {
const controlErrors = flattenIssues(step?.issues?.controls);
Object.entries(controlErrors).forEach(([key, value]) => {
form.setError(key as 'amount' | 'unit', { message: value });
});
}, [step, form]);

const onSubmit = useCallback(
async (data: z.infer<typeof delayControlsSchema>) => {
console.log('submit', data);

if (!workflow) {
return false;
}

await updateWorkflow({
id: workflow._id,
workflow: {
...workflow,
steps: workflow.steps.map((step) =>
step.slug === stepSlug ? { ...step, controlValues: { ...data } } : step
),
},
});

form.reset({ ...data });
},
[workflow, form, updateWorkflow, stepSlug]
);

const debouncedSave = useMemo(() => debounce(onSubmit, 800), [onSubmit]);

// Cleanup debounce on unmount
useEffect(() => () => debouncedSave.cancel(), [debouncedSave]);

const blocker = useBlocker(() => form.formState.isDirty || isPending);

return (
<>
<SidebarContent>
<CommonFields />
</SidebarContent>
<Separator />
<SidebarContent>
<Form {...form}>
<form
className="flex h-full flex-col gap-2"
onChange={(e) => {
e.preventDefault();
e.stopPropagation();
debouncedSave(form.getValues());
}}
>
<FormLabel tooltip="Delays workflow for the set time, then proceeds to the next step.">
Delay execution by
</FormLabel>
<NumberInputWithSelect
form={form}
inputName="amount"
selectName="unit"
options={unitOptions}
isReadOnly={isReadOnly}
/>
</form>
</Form>
</SidebarContent>
<UnsavedChangesAlertDialog
blocker={blocker}
description="This editor form has some unsaved changes. Save progress before you leave."
/>
</>
);
};
Loading
Loading