Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Form state updates

Tim Wilson4dd463902695
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-action-bar.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-action-bar.tsx
index c4d5112f2d..b772b16fcd 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-action-bar.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-action-bar.tsx
@@ -8,6 +8,7 @@ import { useCampaignFormContext } from "./campaign-form-context";
interface CampaignActionBarProps extends PropsWithChildren {
onSave?: () => void;
isSaving?: boolean;
+ onReset?: () => void;
campaignStatus: Campaign["status"];
}
@@ -15,6 +16,7 @@ export function CampaignActionBar({
children,
onSave,
isSaving = false,
+ onReset,
campaignStatus,
}: CampaignActionBarProps) {
const { control, reset } = useCampaignFormContext();
@@ -54,7 +56,10 @@ export function CampaignActionBar({
text="Discard"
variant="secondary"
className="hidden h-7 px-2.5 text-xs lg:flex"
- onClick={() => reset()}
+ onClick={() => {
+ reset();
+ onReset?.();
+ }}
disabled={isSubmitting || isSaving}
/>
<Button
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx
index ad991cee90..8dc5a08365 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx
@@ -17,7 +17,7 @@ import {
} from "@dub/ui";
import { useAction } from "next-safe-action/hooks";
import Link from "next/link";
-import { useCallback, useEffect } from "react";
+import { useCallback, useEffect, useRef } from "react";
import { Controller, FormProvider, useForm } from "react-hook-form";
import { toast } from "sonner";
import { useDebouncedCallback } from "use-debounce";
@@ -43,14 +43,33 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
isSubmitting: isSavingDraftCampaign,
} = useApiMutation<Campaign>();
+ useEffect(() => {
+ console.log({
+ defaultValues: {
+ type: campaign.type,
+ name: campaign.name,
+ subject: campaign.subject,
+ body: campaign.body,
+ groupIds: campaign.groups.map(({ id }) => id),
+ triggerCondition: campaign.triggerCondition ?? {
+ attribute: "partnerEnrolledDays",
+ value: 1,
+ },
+ },
+ });
+ }, []);
+
const form = useForm<UpdateCampaignFormData>({
defaultValues: {
- type: campaign?.type,
- name: campaign?.name,
- subject: campaign?.subject,
- body: campaign?.body,
+ type: campaign.type,
+ name: campaign.name,
+ subject: campaign.subject,
+ body: campaign.body,
groupIds: campaign.groups.map(({ id }) => id),
- triggerCondition: campaign.triggerCondition,
+ triggerCondition: campaign.triggerCondition ?? {
+ attribute: "partnerEnrolledDays",
+ value: 1,
+ },
},
});
@@ -63,6 +82,8 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
formState: { isDirty, dirtyFields },
} = form;
+ console.log({ isDirty, dirtyFields, values: getValues() });
+
const handleSaveCampaign = useCallback(
async (isDraft: boolean = false, showSuccessToast: boolean = false) => {
if (isSavingDraftCampaign) {
@@ -143,6 +164,8 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
const statusBadge = CAMPAIGN_STATUS_BADGES[campaign.status];
+ const editorRef = useRef<{ setContent: (content: any) => void }>(null);
+
return (
<FormProvider {...form}>
<PageContentWithSidePanel
@@ -246,6 +269,7 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
name="body"
render={({ field }) => (
<RichTextArea
+ ref={editorRef}
editorClassName="-m-2 min-h-[200px] p-2"
initialValue={field.value}
onChange={(editor) => {
@@ -318,6 +342,9 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
campaignStatus={campaign.status}
onSave={handleManualSave}
isSaving={isSavingDraftCampaign}
+ onReset={() => {
+ editorRef.current?.setContent(getValues("body"));
+ }}
/>
</PageContentWithSidePanel>
</FormProvider>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/transactional-campaign-logic.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/transactional-campaign-logic.tsx
index 256de7065c..63b602bdda 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/transactional-campaign-logic.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/transactional-campaign-logic.tsx
@@ -7,27 +7,11 @@ import {
InlineBadgePopoverMenu,
} from "@/ui/shared/inline-badge-popover";
import { pluralize } from "@dub/utils";
-import { useEffect } from "react";
import { Controller } from "react-hook-form";
import { useCampaignFormContext } from "./campaign-form-context";
export function TransactionalCampaignLogic() {
- const { control, watch, setValue } = useCampaignFormContext();
-
- const [attribute, value] = watch([
- "triggerCondition.attribute",
- "triggerCondition.value",
- ]);
-
- useEffect(() => {
- if (!attribute) {
- setValue("triggerCondition.attribute", "partnerEnrolledDays");
- }
-
- if (value === undefined || value === null) {
- setValue("triggerCondition.value", 1);
- }
- }, [attribute, value, setValue]);
+ const { control } = useCampaignFormContext();
return (
<div className="flex h-8 w-full items-center px-2">
@@ -64,33 +48,34 @@ export function TransactionalCampaignLogic() {
control={control}
name="triggerCondition.value"
render={({ field }) => (
- <InlineBadgePopover
- text={
- field.value !== undefined && field.value !== null
- ? String(field.value)
- : "1"
- }
- invalid={field.value === undefined || field.value === null}
- >
- <InlineBadgePopoverMenu
- selectedValue={
+ <>
+ <InlineBadgePopover
+ text={
field.value !== undefined && field.value !== null
? String(field.value)
: "1"
}
- onSelect={(val) => field.onChange(Number(val))}
- items={ALLOWED_ATTRIBUTE_VALUES_IN_DAYS.filter(
- (days) => days !== 0,
- ).map((days) => ({
- text: String(days),
- value: String(days),
- }))}
- />
- </InlineBadgePopover>
+ invalid={field.value === undefined || field.value === null}
+ >
+ <InlineBadgePopoverMenu
+ selectedValue={
+ field.value !== undefined && field.value !== null
+ ? String(field.value)
+ : "1"
+ }
+ onSelect={(val) => field.onChange(Number(val))}
+ items={ALLOWED_ATTRIBUTE_VALUES_IN_DAYS.filter(
+ (days) => days !== 0,
+ ).map((days) => ({
+ text: String(days),
+ value: String(days),
+ }))}
+ />
+ </InlineBadgePopover>
+ {pluralize("day", field.value || 1)}
+ </>
)}
/>
-
- {pluralize("day", value || 1)}
</div>
</span>
</div>
diff --git a/packages/ui/src/rich-text-area/index.tsx b/packages/ui/src/rich-text-area/index.tsx
index f833c0e3a0..bf9251b3e0 100644
--- a/packages/ui/src/rich-text-area/index.tsx
+++ b/packages/ui/src/rich-text-area/index.tsx
@@ -5,7 +5,7 @@ import Mention from "@tiptap/extension-mention";
import { Placeholder } from "@tiptap/extensions";
import { Editor, EditorContent, EditorContext, useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
-import { useMemo, useState } from "react";
+import { forwardRef, useImperativeHandle, useMemo, useState } from "react";
import { LoadingSpinner } from "../icons";
import { RichTextToolbar } from "./rich-text-toolbar";
import { suggestions } from "./variables";
@@ -18,15 +18,7 @@ export const richTextAreaExtensions = [
}),
];
-export function RichTextArea({
- initialValue,
- onChange,
- placeholder = "Start typing...",
- className,
- editorClassName,
- uploadImage,
- variables,
-}: {
+interface RichTextAreaProps {
initialValue?: any;
onChange?: (editor: Editor) => void;
placeholder?: string;
@@ -34,138 +26,167 @@ export function RichTextArea({
editorClassName?: string;
uploadImage?: (file: File) => Promise<string | null>;
variables?: string[];
-}) {
- const [isUploading, setIsUploading] = useState(false);
+}
- const handleImageUpload = async (
- file: File,
- currentEditor: Editor,
- pos: number,
- ) => {
- setIsUploading(true);
+export interface RichTextAreaRef {
+ setContent: (content: any) => void;
+}
- const src = await uploadImage?.(file);
- if (!src) {
- setIsUploading(false);
- return;
- }
+export const RichTextArea = forwardRef<RichTextAreaRef, RichTextAreaProps>(
+ function RichTextArea(
+ {
+ initialValue,
+ onChange,
+ placeholder = "Start typing...",
+ className,
+ editorClassName,
+ uploadImage,
+ variables,
+ },
+ ref,
+ ) {
+ const [isUploading, setIsUploading] = useState(false);
- currentEditor
- .chain()
- .insertContentAt(pos, {
- type: "image",
- attrs: {
- src,
- },
- })
- .focus()
- .run();
+ const handleImageUpload = async (
+ file: File,
+ currentEditor: Editor,
+ pos: number,
+ ) => {
+ setIsUploading(true);
+
+ const src = await uploadImage?.(file);
+ if (!src) {
+ setIsUploading(false);
+ return;
+ }
- setIsUploading(false);
- };
+ currentEditor
+ .chain()
+ .insertContentAt(pos, {
+ type: "image",
+ attrs: {
+ src,
+ },
+ })
+ .focus()
+ .run();
- const editor = useEditor({
- extensions: [
- ...richTextAreaExtensions,
- Placeholder.configure({
- placeholder,
- emptyEditorClass:
- "before:content-[attr(data-placeholder)] before:float-left before:text-content-muted before:h-0 before:pointer-events-none",
- }),
+ setIsUploading(false);
+ };
- // Images
- ...(uploadImage
- ? [
- Image,
- FileHandler.configure({
- allowedMimeTypes: [
- "image/png",
- "image/jpeg",
- "image/gif",
- "image/webp",
- ],
- onDrop: (currentEditor, files, pos) => {
- files.forEach((file) =>
- handleImageUpload(file, currentEditor, pos),
- );
- },
- onPaste: (currentEditor, files, htmlContent) => {
- if (htmlContent) return false;
- files.forEach((file) =>
- handleImageUpload(
- file,
- currentEditor,
- currentEditor.state.selection.anchor,
- ),
- );
- },
- }),
- ]
- : []),
- ...(variables
- ? [
- Mention.extend({
- renderHTML({ node }: { node: any }) {
- return [
- "span",
- {
- class:
- "px-1 py-0.5 bg-blue-100 text-blue-700 rounded font-semibold",
- "data-type": "mention",
- "data-id": node.attrs.id,
- },
- `{{${node.attrs.id}}}`,
- ];
- },
- renderText({ node }: { node: any }) {
- return `{{${node.attrs.id}}}`;
- },
- }).configure({
- suggestion: suggestions(variables),
- }),
- ]
- : []),
- ],
- editorProps: {
- attributes: {
- class: cn(
- "prose prose-sm prose-neutral max-w-none focus:outline-none",
- editorClassName,
- ),
+ const editor = useEditor({
+ extensions: [
+ ...richTextAreaExtensions,
+ Placeholder.configure({
+ placeholder,
+ emptyEditorClass:
+ "before:content-[attr(data-placeholder)] before:float-left before:text-content-muted before:h-0 before:pointer-events-none",
+ }),
+
+ // Images
+ ...(uploadImage
+ ? [
+ Image,
+ FileHandler.configure({
+ allowedMimeTypes: [
+ "image/png",
+ "image/jpeg",
+ "image/gif",
+ "image/webp",
+ ],
+ onDrop: (currentEditor, files, pos) => {
+ files.forEach((file) =>
+ handleImageUpload(file, currentEditor, pos),
+ );
+ },
+ onPaste: (currentEditor, files, htmlContent) => {
+ if (htmlContent) return false;
+ files.forEach((file) =>
+ handleImageUpload(
+ file,
+ currentEditor,
+ currentEditor.state.selection.anchor,
+ ),
+ );
+ },
+ }),
+ ]
+ : []),
+ ...(variables
+ ? [
+ Mention.extend({
+ renderHTML({ node }: { node: any }) {
+ return [
+ "span",
+ {
+ class:
+ "px-1 py-0.5 bg-blue-100 text-blue-700 rounded font-semibold",
+ "data-type": "mention",
+ "data-id": node.attrs.id,
+ },
+ `{{${node.attrs.id}}}`,
+ ];
+ },
+ renderText({ node }: { node: any }) {
+ return `{{${node.attrs.id}}}`;
+ },
+ }).configure({
+ suggestion: suggestions(variables),
+ }),
+ ]
+ : []),
+ ],
+ editorProps: {
+ attributes: {
+ class: cn(
+ "prose prose-sm prose-neutral max-w-none focus:outline-none",
+ editorClassName,
+ ),
+ },
},
- },
- content: initialValue,
- onUpdate: ({ editor }) => onChange?.(editor),
- immediatelyRender: false,
- });
+ content: initialValue,
+ onUpdate: ({ editor }) => onChange?.(editor),
+ immediatelyRender: false,
+ });
- const providerValue = useMemo(() => ({ editor }), [editor]);
+ useImperativeHandle(ref, () => ({
+ setContent: (content: any) => {
+ editor?.commands.setContent(content);
+ },
+ }));
- return (
- <EditorContext.Provider value={providerValue}>
- <div
- className={cn(
- "relative flex flex-col gap-4",
- isUploading && "pointer-events-none opacity-50",
- className,
- )}
- >
- <RichTextToolbar
- onImageUpload={
- uploadImage && editor
- ? (file) =>
- handleImageUpload(file, editor, editor.state.selection.anchor)
- : undefined
- }
- />
- <EditorContent editor={editor} />
+ const providerValue = useMemo(() => ({ editor }), [editor]);
- {isUploading && (
- <div className="absolute inset-0 flex items-center justify-center">
- <LoadingSpinner className="size-4" />
- </div>
- )}
- </div>
- </EditorContext.Provider>
- );
-}
+ return (
+ <EditorContext.Provider value={providerValue}>
+ <div
+ className={cn(
+ "relative flex flex-col gap-4",
+ isUploading && "pointer-events-none opacity-50",
+ className,
+ )}
+ >
+ <RichTextToolbar
+ onImageUpload={
+ uploadImage && editor
+ ? (file) =>
+ handleImageUpload(
+ file,
+ editor,
+ editor.state.selection.anchor,
+ )
+ : undefined
+ }
+ />
+ <EditorContent editor={editor} />
+
+ {isUploading && (
+ <div className="absolute inset-0 flex items-center justify-center">
+ <LoadingSpinner className="size-4" />
+ </div>
+ )}
+ </div>
+ </EditorContext.Provider>
+ );
+ },
+);