Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(workflows): add feature-flagged tree workflow builder (#95047)

Ben White311b1a835872
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a977bd1db73b..c9b26fb8f16c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6009,13 +6009,13 @@ snapshots:
products-workflows-editor-configuration-panel--build-palette--light:
hash: v1.k794b7964.ec28f7c380ae5e13b96257d733150e4cde8443dfab152e8d92f3c730c05cc52f.DeHnuPIJ3F_CEIwi_6ECbRYd7uPKPj-6ZlKj5_KSCqg
products-workflows-editor-configuration-panel--cohort-branch--dark:
- hash: v1.k794b7964.330ad940d732b05530ad6c6d1c1ce0c26149b857bd20cc214cbe7209fccee415.WtGoxeyoXxBu5AkOrj4CPxgMTsI2gwqi63gvoimPHqI
+ hash: v1.k794b7964.89705899ccfa2ee8b18d86d538e800a3a25e91fd25261d88738dd97809388c45.waPXpQ-N2vcu8Ta_GIKzoX0InqMySnxWOXWn6BsfA4g
products-workflows-editor-configuration-panel--cohort-branch--light:
- hash: v1.k794b7964.72a2c1f5905bd969e2179a030ce399b3a8ff3c3e23546adb3f2c4129077f4227.RfaimUSHlUpwmK7W_t_H6ZlEthxtdSQr6W_oJyU8gZg
+ hash: v1.k794b7964.4fd0f6ff9c17a685913afb00d14a5804d28eac0f4dbe5b89ab2b60c9258d757f.dGeUSO7-kt1SuNSTiOTtQ0yWrCXD3wWCrJ0JkzXqPHQ
products-workflows-editor-configuration-panel--conditional-branch--dark:
- hash: v1.k794b7964.d4b0b279073ea581caf96a8bbc8c8d338a5ec1c7419172612f5dfcb8a35dc20b.-U4fPTAIryjtGBV2kTcfuM2W8u3rvFGzoeGCOnBo40c
+ hash: v1.k794b7964.28ef96bdb240694b8b0786bccdeec07dffc677410a0977d2b16d7794ccc85c14.cVh6dFIr01Hi6QIOwO31L9RqOP4rLQJUHKMucRSdljE
products-workflows-editor-configuration-panel--conditional-branch--light:
- hash: v1.k794b7964.37849e4c1f80f5aeadaef15e594e0412d41873851a658f8f43943c7996fe52fd.DQulw_YGBM8n0wQKd1rHWDNIOasvltY5UU2wPOMbezw
+ hash: v1.k794b7964.cf5243dc2191758d2b098416822df172ac32e54c51f7b8ff5d441fa54cdf9501.PUjF_kDSbjW4Kd9AJGy1JSIwipvVVWu4tZ4QSL9TumA
products-workflows-editor-configuration-panel--logs--dark:
hash: v1.k794b7964.beabe0c2c69154a7e7b8e5709226f710bbb707c7a2a96ea3b908e7b5348ad177.l8BzDM-8b8Z6jYzADnoiRggNuU02m3lgVa6vtNm2VOw
products-workflows-editor-configuration-panel--logs--light:
@@ -6064,6 +6064,34 @@ snapshots:
hash: v1.k794b7964.7c60c3d139d5b5dabbd7fb974f621f135149176f1c86184aed079c6deaef414e.AkijMDM4cBxIWBu4E8V7VThp1fwVqHJcfVB24fcGK0Y
products-workflows-editor-graph--support-sla-routing--light:
hash: v1.k794b7964.96264d77ca9e5d4897c48f8552d051ab6a414675e9a5d62b1878c40955e60a12.veQ0qlbkuVu45XgikLqMm6GhiTqaU-iYLBAUuvq-W_o
+ products-workflows-editor-tree--add-on-promotion-emails--dark:
+ hash: v1.k794b7964.1202418cc4c50379946e01301529486380301fdff5e9ad2dd9c2d0dac0fef147.dNUPRnQLzwNr-0wVPVZM-6SIaRk3BxBMzEonhSYWBFI
+ products-workflows-editor-tree--add-on-promotion-emails--light:
+ hash: v1.k794b7964.ed5711f80707d0bdaf6c3ff69190a611df5a7308f96d496de7d9067f55c523e8.scmkRCwb31T_7QrMHVUdqSYhxtZahu6CTJT5kMLl80A
+ products-workflows-editor-tree--customer-onboarding-and-retention--dark:
+ hash: v1.k794b7964.394c02b15685b7265d09074c75e4c21927ee95d97218733228d494053696c8fb.ZjHJZARWFepbdyEVyk_ZNSuOP8mwR6KbuyfGMyp0B_A
+ products-workflows-editor-tree--customer-onboarding-and-retention--light:
+ hash: v1.k794b7964.e8c79a78950a972b0fdf470d426bb4e30275ffeac095736fe9327bf7571cc6ac.uTTD_H5rAqcyA5WcE6Qt2RGAIVNoxElEuqn5i-NGPg4
+ products-workflows-editor-tree--narrow-workflow--dark:
+ hash: v1.k794b7964.5987a1e8ac93211af4c06f3f437f67ace8a6cd85792f6bc808db270ca9755590.8iPtpr3uRGPKFkTO6uSb5Fc6HTdcoRpJy9O68FlnZOE
+ products-workflows-editor-tree--narrow-workflow--light:
+ hash: v1.k794b7964.1ecf844d0cf9dca540167c55152ad28ecab3f954bd1726003975463e852586d2.S9aEvGKokejfIHSNU3H1XvCY74PLq8P3zeRBOghSMQc
+ products-workflows-editor-tree--new-workflow--dark:
+ hash: v1.k794b7964.cd72834d7abe4e9f3a0ae929ae2d4febf89098d4e7314d99a862348f4ab75ad8.vhQ97W-jtCR8QOq426N3511PF4Qc8VXhpZe_VFDbIJM
+ products-workflows-editor-tree--new-workflow--light:
+ hash: v1.k794b7964.a4a490e58e2257711ecae7765ef8e82237a5b5ca92f52e0ed4e60eea8ae535ef.2nuJGSjyLz8KwWyAaaep01smVPGJXAx_2P4zG9C0vH4
+ products-workflows-editor-tree--pending-ticket-cleanup--dark:
+ hash: v1.k794b7964.fafef288c1348951beaccdc0c9efdf0d2235666b793799092889b5385055a637.weB8WLzpZW7YRVLb1PkDi7fLlr2FJYoMql5fgqndKGE
+ products-workflows-editor-tree--pending-ticket-cleanup--light:
+ hash: v1.k794b7964.9e5b6e33b8eaae865e2d5be2252018ebcffeb1447df16b91143ab3ad936de433.wIojA1DlZMRP4xnSW2UsP7W0LjNCqleLvKduHciF20w
+ products-workflows-editor-tree--renewal-window-alerts--dark:
+ hash: v1.k794b7964.babdf039c0cbd1d842e382d24be952ca7ca17fc1379f59538b00554964ed923d.Q8fJZYT2zZhhvQvnqKIXcIiuI4RRvnSVokJ0-3s9CLU
+ products-workflows-editor-tree--renewal-window-alerts--light:
+ hash: v1.k794b7964.37c50007d42a1eca7926337d20f153be6a3614d14bd3a1a6d7979b4c66f10570.J0nGYNeeV1NDUF9e6IR0RcGNo1VZiR94lxDW0Hwhob4
+ products-workflows-editor-tree--support-sla-routing--dark:
+ hash: v1.k794b7964.6b4a7840fe8b0b69a5df425c0952dd48f909494ce59f8f320855e7670c5df838.xbVTFStEZfMOlnynAPArJJk4yqCG_TbPrNUwdOejX7I
+ products-workflows-editor-tree--support-sla-routing--light:
+ hash: v1.k794b7964.8aec1d3b65bb0d2e1b4bee72e6192dec55912fcd0bdce146dcf48e16453ec44f.HDlYfFMWDXWuYU9krTw6IX8Emw0zG1uzsMvRfdNDIZQ
products-workflows-reputation--domain-withheld-from-caller--dark:
hash: v1.k794b7964.b37b29c7894aedb7ca34c4976577e3aaed60f5e81a99d29c427ad4d5eeaf16ce.p2UYtjwRYsZEy_dF6JZTqzYZC8PD-WIUSALXCQGdpjM
products-workflows-reputation--domain-withheld-from-caller--light:
@@ -6108,26 +6136,10 @@ snapshots:
hash: v1.k794b7964.5ca1cd71851625754d87c675688f56c0feb039ade940912f8df2ddd171d89d83.5SQmAn1fsl5RQ572BttZHT0wNAtJeZRNP0OqajxrUMc
products-workflows-template-card--ai--light:
hash: v1.k794b7964.5a31f5a57fe751ed5a9ec04bca6f2d5f62e2fbd86179cee3454db11924f21be1.GEdQ_SUwmnx3J9sqhog7T_uNJYnC5ph5eiKOwoYui-A
- products-workflows-template-card--basic--dark:
- hash: v1.k794b7964.5e92df62c57af26cdce62c752d1520bc51346a86f584de4915711155f46c30ef.9yCP2MeM_W_Gw2LyPZV1mkP_IvvWpHDA1e-sna1BFSw
- products-workflows-template-card--basic--light:
- hash: v1.k794b7964.fcad6a84112c48e0c1178e59477421d96950329743fce424d13a9798a207bd75.WQYkIoH-tZPH9NEwyfbOyEm79f7bcqGlX9DUaxNGcgE
products-workflows-template-card--blank--dark:
hash: v1.k794b7964.23ca3e9c4eb925a659ce4553dda6c27955f48bafba4fc1355c3d7c0cefcec862.M-USb6QCbLNLEHpio3NNncnc1FRh-JSo7oV0XEosD1Y
products-workflows-template-card--blank--light:
hash: v1.k794b7964.10249e46871b8b2f8382d2af9c62214098bf6a1a8f4baed3f2cdea8a43d45914.pDn78avyYvuB8i7MQotDOvokbWJUDneghYCfxxv7M0Q
- products-workflows-template-card--longest-description--dark:
- hash: v1.k794b7964.11dc07a26fd819ad4c9c5b41131c626fe54262f12a0fe8b033fdbbb694bc9988.WdUl8hdamKaJUeScrYS9KGkYYv1r0sUApsJRzZBsZo4
- products-workflows-template-card--longest-description--light:
- hash: v1.k794b7964.8ca8ae54cf847387bcab9cdea9a3f313158da6f3cf091b551e42cf21dd13e2df._bJpmDR8Vk8OSIsYIzzDA0Ip_q9y1c5hwwcC06giQWA
- products-workflows-template-card--narrow--dark:
- hash: v1.k794b7964.02cd68ad28118eef7360a8d93cdb71a3aa80b3bf23d71788bb4c1cd02b647a98.YodJ5IXVT3EoRbzZ0Zw52XiuRcb0hUV8BJbxi3gu3YY
- products-workflows-template-card--narrow--light:
- hash: v1.k794b7964.f14ce1bd1533072e19f0dd4136807a43502ba958d1c01970552955bb0bd16505.BRimZEFm-Oh0wDZSnWuwP_gCiXgS6mV9DhkaUopQxFI
- products-workflows-template-card--picker--dark:
- hash: v1.k794b7964.ded75abe4e8eb09bccf9b970188d13b022bf0c43636e887273791b72a4636ee2.R28mwGSEfFH1ZxrFl4cRA-zpg5RprlDTRSu96cg-v20
- products-workflows-template-card--picker--light:
- hash: v1.k794b7964.59e165d7ede2cc4e3138b95c64a7329134a16e722ff2fe224f8bf700e81d544c.SRWbL89CbOMgwObgHB8qGt_63Lh4SB0-2of7YS3PlQw
queries-webvitals--web-vitals--dark:
hash: v1.k794b7964.2ae778a0c5fdba3c69dfcbd3e9589c3c3d9cc2f0fef2eefd304c565be7e9a7c9.hH71byl33sIAdRCgaPk1lDOev0qooW1xhv0AL_yrIvg
queries-webvitals--web-vitals--light:
@@ -8857,9 +8869,9 @@ snapshots:
scenes-app-notebooks-widget-views--survey-views--light:
hash: v1.k794b7964.8a47035e27adf28ea1aa55a4d9727ec53fa48adb8b3a2b713ac1b8d85e1b507d.wIS2hemanssypExa3H7n4CO7SvRbcurSLmqBYcCPCNs
scenes-app-notebooks-widget-views--workflow-views--dark:
- hash: v1.k794b7964.f0925e7e3630c4ad91250fa7060c55e5dbf94841a847b5fb1b07a874121d6d70.1WP3_PNV_1ly9tJEzXnuVWY5eP_Rg2WWkL9_YJ8kcf8
+ hash: v1.k794b7964.dded071925e13813948059d3a851fda7045079765dd39c35a1909a33f4818670.uLBVI91IfZ7a2kAB6tnEs6CHaEQ_xl-6gI91X4096sM
scenes-app-notebooks-widget-views--workflow-views--light:
- hash: v1.k794b7964.10374665f60a6264239ae1efe6726c42611f17b391286ad09f29d752d96d4e70.vNLXzmHiA_B3gCYXQ6nD5NFPUtrveq1WK8WHjde4s6k
+ hash: v1.k794b7964.cd7fa77d9236079839583863834cd6f2a7a0aea88be4bdb1fb68e4e9c0ab4dab.df8Gy7QN0LSBis_grrNFZCyPlgTJV9k90oTKS9o2ouI
scenes-app-oauth-authorize--all-scopes-optional--dark:
hash: v1.k794b7964.a03d00f6626add00255abe8fa712c056cecbf929f724284de20cf6e936a96fbe.cCaJ_N0193dGvxNreYfm9ltl9zmGo4r3-9-vKCX7TwQ
scenes-app-oauth-authorize--all-scopes-optional--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index f3c6f66fcc71..035f9d1d4ad1 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -576,6 +576,7 @@ export const FEATURE_FLAGS = {
WORKFLOWS_EMAIL_SENDER_ROTATION: 'workflows-email-sender-rotation', // owner: @arthurdedeus #team-workflows
WORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflows
WORKFLOWS_ISP_SENDING_HEALTH: 'workflows-isp-sending-health', // owner: #team-workflows
+ WORKFLOWS_LINEAR_VIEW: 'workflows-linear-view', // owner: #team-workflows
WORKFLOWS_PUSH_NOTIFICATIONS: 'workflows-push-notifications', // owner: #team-workflows
WORKFLOWS_TRIGGER_VOLUME_ESTIMATE: 'workflows-trigger-volume-estimate', // owner: @mayteio #team-workflows
XAA_AUTHENTICATION: 'xaa-authentication', // owner: @reecejones #team-platform-features
diff --git a/products/workflows/frontend/Workflows/Workflow.tsx b/products/workflows/frontend/Workflows/Workflow.tsx
index ac08e7e1e5fd..22cd52a74134 100644
--- a/products/workflows/frontend/Workflows/Workflow.tsx
+++ b/products/workflows/frontend/Workflows/Workflow.tsx
@@ -2,19 +2,30 @@ import { useActions, useValues } from 'kea'
import { LemonBanner, LemonButton, SpinnerOverlay } from '@posthog/lemon-ui'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+
import { HogFlowEditor } from './hogflows/HogFlowEditor'
+import { hogFlowEditorLogic } from './hogflows/hogFlowEditorLogic'
import { WorkflowLogicProps, workflowLogic } from './workflowLogic'
import { WorkflowStatusBar } from './WorkflowStatusBar'
export function Workflow(props: WorkflowLogicProps): JSX.Element {
- const { originalWorkflow, workflowLoading, externallyEdited, isSyncingExternalEdit } = useValues(
+ const { originalWorkflow, workflowLoading, externallyEdited, isSyncingExternalEdit, logicProps } = useValues(
workflowLogic(props)
)
const { loadWorkflow, keepMyWorkflowVersion } = useActions(workflowLogic(props))
+ const { editorLayout } = useValues(hogFlowEditorLogic(logicProps))
+ const { setEditorLayout } = useActions(hogFlowEditorLogic(logicProps))
+ const treeViewEnabled = useFeatureFlag('WORKFLOWS_LINEAR_VIEW')
return (
- <div className="flex flex-col grow relative border rounded-md">
- <WorkflowStatusBar {...props} />
+ <div className="relative flex h-[calc(100vh-13rem)] max-h-full min-h-[25rem] grow flex-col overflow-hidden rounded-md border">
+ <WorkflowStatusBar
+ {...props}
+ editorLayout={editorLayout}
+ showEditorLayoutToggle={treeViewEnabled}
+ onEditorLayoutChange={setEditorLayout}
+ />
{/* Brief working/disabled overlay while we reconcile to an edit made elsewhere (clean state). */}
{isSyncingExternalEdit && <SpinnerOverlay />}
{externallyEdited && (
@@ -36,7 +47,11 @@ export function Workflow(props: WorkflowLogicProps): JSX.Element {
</div>
</LemonBanner>
)}
- {!originalWorkflow && workflowLoading ? <SpinnerOverlay /> : <HogFlowEditor />}
+ {!originalWorkflow && workflowLoading ? (
+ <SpinnerOverlay />
+ ) : (
+ <HogFlowEditor isTreeView={!!treeViewEnabled && editorLayout === 'simple'} />
+ )}
</div>
)
}
diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsx
index d7f8ae5f5782..e7a3c9488460 100644
--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx
@@ -30,7 +30,7 @@ import {
import { WorkflowAssets } from './WorkflowAssets'
import { WorkflowEmailPauseBanner } from './WorkflowEmailPauseBanner'
import { WorkflowInvocations } from './WorkflowInvocations'
-import { workflowLogic } from './workflowLogic'
+import { WorkflowLogicProps, workflowLogic } from './workflowLogic'
import { WorkflowMetrics } from './WorkflowMetrics'
import { WorkflowRevisions } from './WorkflowRevisions'
import { WorkflowSceneHeader } from './WorkflowSceneHeader'
@@ -58,10 +58,16 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
const templateId = searchParams.templateId as string | undefined
const editTemplateId = searchParams.editTemplateId as string | undefined
const triggerPrefill = searchParams[TRIGGER_PREFILL_PARAM] as string | undefined
+ const workflowProps: WorkflowLogicProps = {
+ id: workflowSceneProps.id,
+ templateId,
+ editTemplateId,
+ triggerPrefill,
+ }
const batchJobsLogic = batchWorkflowJobsLogic({ id: workflowSceneProps.id })
- const logic = workflowLogic({ id: props.id, templateId, editTemplateId, triggerPrefill })
+ const logic = workflowLogic(workflowProps)
// The save/auto-save indicators moved into the WorkflowStatusBar; the scene only needs the
// workflow itself (for the agent context) and the load state.
const { workflow, workflowLoading, originalWorkflow, hogFunctionTemplatesById } = useValues(logic)
@@ -118,7 +124,7 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
{
label: 'Workflow',
key: 'workflow',
- content: <Workflow {...workflowSceneProps} />,
+ content: <Workflow {...workflowProps} />,
},
{
@@ -167,12 +173,12 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
return (
<SceneContent className="h-full flex flex-col grow" data-attr="workflow-scene">
- <BindLogic logic={workflowLogic} props={{ id: props.id, templateId, editTemplateId, triggerPrefill }}>
+ <BindLogic logic={workflowLogic} props={workflowProps}>
<WorkflowSceneHeader {...props} />
<WorkflowEmailPauseBanner />
{/* Only show Logs and Metrics tabs if the workflow has already been created */}
{!props.id || props.id === 'new' ? (
- <Workflow {...props} />
+ <Workflow {...workflowProps} />
) : (
<LemonTabs
activeKey={currentTab}
diff --git a/products/workflows/frontend/Workflows/WorkflowStatusBar.tsx b/products/workflows/frontend/Workflows/WorkflowStatusBar.tsx
index 6f8ceb093b9f..b91fa57f8fbb 100644
--- a/products/workflows/frontend/Workflows/WorkflowStatusBar.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowStatusBar.tsx
@@ -1,20 +1,27 @@
import { useValues, useActions } from 'kea'
-import { IconClock, IconInfo } from '@posthog/icons'
-import { LemonButton, LemonSwitch, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'
+import { IconClock, IconDecisionTree, IconInfo, IconList } from '@posthog/icons'
+import { LemonButton, LemonSegmentedButton, LemonSwitch, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'
import { LastSavedIndicator } from 'lib/components/LastSavedIndicator'
import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'
import { urls } from 'scenes/urls'
+import type { HogFlowEditorLayout } from './hogflows/hogFlowEditorLogic'
import { WorkflowLogicProps, workflowLogic } from './workflowLogic'
-/**
- * State narration for a saved workflow: what you're editing (live config vs staged draft), save
- * state, and the auto-save toggle. Deliberately no write actions here - save/publish/discard live
- * in the scene header with every other scene's primary actions, and in the scene menu bar.
- */
-export function WorkflowStatusBar(props: WorkflowLogicProps): JSX.Element | null {
+type WorkflowStatusBarProps = WorkflowLogicProps & {
+ editorLayout: HogFlowEditorLayout
+ showEditorLayoutToggle: boolean
+ onEditorLayoutChange: (layout: HogFlowEditorLayout) => void
+}
+
+export function WorkflowStatusBar({
+ editorLayout,
+ showEditorLayoutToggle,
+ onEditorLayoutChange,
+ ...props
+}: WorkflowStatusBarProps): JSX.Element | null {
const logic = workflowLogic(props)
const {
originalWorkflow,
@@ -28,24 +35,48 @@ export function WorkflowStatusBar(props: WorkflowLogicProps): JSX.Element | null
const { setAutoSaveEnabled } = useActions(logic)
const showSaving = useDebouncedValue(isAutoSavePending || workflowLoading, 1000)
- if (!props.id || props.id === 'new' || props.editTemplateId || !originalWorkflow) {
+ if (!originalWorkflow) {
return null
}
+ const showWorkflowStatus = !props.editTemplateId
+ const historyWorkflowId = props.id && props.id !== 'new' ? props.id : null
const isActive = originalWorkflow.status === 'active'
const isEditingDraftOfLive = isActive && (hasStagedDraft || hasUnsavedChanges)
return (
<div className="flex items-center justify-between gap-2 px-2 py-1.5 border-b bg-surface-secondary rounded-t-md flex-wrap">
<div className="flex items-center gap-3 min-w-0">
- {isEditingDraftOfLive ? (
- <LemonTag type="warning">Editing draft</LemonTag>
- ) : isActive ? (
- <LemonTag type="success">Live</LemonTag>
- ) : (
- <LemonTag>Draft</LemonTag>
+ {showEditorLayoutToggle && (
+ <LemonSegmentedButton
+ value={editorLayout}
+ onChange={onEditorLayoutChange}
+ size="small"
+ options={[
+ {
+ value: 'simple',
+ icon: <IconList />,
+ tooltip: 'List view',
+ 'data-attr': 'workflow-switch-to-simple-view',
+ },
+ {
+ value: 'advanced',
+ icon: <IconDecisionTree />,
+ tooltip: 'Graph view',
+ 'data-attr': 'workflow-switch-to-advanced-view',
+ },
+ ]}
+ />
)}
- {isActive && (
+ {showWorkflowStatus &&
+ (isEditingDraftOfLive ? (
+ <LemonTag type="warning">Editing draft</LemonTag>
+ ) : isActive ? (
+ <LemonTag type="success">Live</LemonTag>
+ ) : (
+ <LemonTag>Draft</LemonTag>
+ ))}
+ {showWorkflowStatus && isActive && (
<span className="text-xs text-secondary truncate">
{isEditingDraftOfLive
? 'The live version keeps running until you publish.'
@@ -55,42 +86,44 @@ export function WorkflowStatusBar(props: WorkflowLogicProps): JSX.Element | null
</div>
{/* Interactive controls sit right-anchored with variable-width text leftmost, so the
toggle and History never shift as the narration or the timestamp changes. */}
- <div className="flex items-center gap-3 shrink-0">
- {autoSaveEnabled && showSaving ? (
- <span className="text-xs text-tertiary flex items-center gap-1">
- <Spinner textColored /> Saving…
+ {showWorkflowStatus && historyWorkflowId && (
+ <div className="flex items-center gap-3 shrink-0">
+ {autoSaveEnabled && showSaving ? (
+ <span className="text-xs text-tertiary flex items-center gap-1">
+ <Spinner textColored /> Saving…
+ </span>
+ ) : lastSavedAt ? (
+ <LastSavedIndicator timestamp={lastSavedAt} />
+ ) : null}
+ <span className="flex items-center gap-1">
+ <LemonSwitch
+ checked={autoSaveEnabled}
+ onChange={setAutoSaveEnabled}
+ label="Auto-save"
+ size="small"
+ />
+ <Tooltip
+ title={
+ isActive
+ ? 'Auto-save stores your changes as a draft. Nothing goes live until you publish.'
+ : 'Draft workflows auto-save as you edit.'
+ }
+ placement="bottom"
+ >
+ <IconInfo className="text-tertiary size-4" />
+ </Tooltip>
</span>
- ) : lastSavedAt ? (
- <LastSavedIndicator timestamp={lastSavedAt} />
- ) : null}
- <span className="flex items-center gap-1">
- <LemonSwitch
- checked={autoSaveEnabled}
- onChange={setAutoSaveEnabled}
- label="Auto-save"
+ <LemonButton
+ type="tertiary"
size="small"
- />
- <Tooltip
- title={
- isActive
- ? 'Auto-save stores your changes as a draft. Nothing goes live until you publish.'
- : 'Draft workflows auto-save as you edit.'
- }
- placement="bottom"
+ icon={<IconClock />}
+ to={urls.workflow(historyWorkflowId, 'history')}
+ tooltip="See and restore previous versions"
>
- <IconInfo className="text-tertiary size-4" />
- </Tooltip>
- </span>
- <LemonButton
- type="tertiary"
- size="small"
- icon={<IconClock />}
- to={urls.workflow(props.id, 'history')}
- tooltip="See and restore previous versions"
- >
- History
- </LemonButton>
- </div>
+ History
+ </LemonButton>
+ </div>
+ )}
</div>
)
}
diff --git a/products/workflows/frontend/Workflows/hogflows/HogFlowBranchSelection.tsx b/products/workflows/frontend/Workflows/hogflows/HogFlowBranchSelection.tsx
new file mode 100644
index 000000000000..62a611bfdb18
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/HogFlowBranchSelection.tsx
@@ -0,0 +1,72 @@
+import { useValues } from 'kea'
+import { createContext, useContext, useEffect, useState } from 'react'
+import type { CSSProperties, ReactNode } from 'react'
+
+import { hogFlowEditorLogic } from './hogFlowEditorLogic'
+
+const BRANCH_COLORS = [
+ 'var(--data-color-1)',
+ 'var(--data-color-7)',
+ 'var(--data-color-14)',
+ 'var(--data-color-12)',
+ 'var(--data-color-11)',
+ 'var(--data-color-4)',
+]
+
+export interface HogFlowBranchSelection {
+ actionId: string
+ index: number | null
+}
+
+interface HogFlowBranchSelectionContextValue {
+ selectedBranch: HogFlowBranchSelection | null
+ setSelectedBranch: (branch: HogFlowBranchSelection | null) => void
+}
+
+const HogFlowBranchSelectionContext = createContext<HogFlowBranchSelectionContextValue>({
+ selectedBranch: null,
+ setSelectedBranch: () => undefined,
+})
+
+export function getHogFlowBranchColor(index: number | null): string {
+ return index === null ? 'var(--muted-foreground)' : BRANCH_COLORS[index % BRANCH_COLORS.length]
+}
+
+export function getHogFlowBranchTint(index: number | null): string {
+ return `color-mix(in oklab, ${getHogFlowBranchColor(index)} 8%, var(--color-bg-surface-primary))`
+}
+
+export function getHogFlowBranchStyle(index: number | null, selected: boolean): CSSProperties {
+ const color = getHogFlowBranchColor(index)
+
+ return {
+ borderColor: color,
+ ...(selected
+ ? {
+ backgroundColor: getHogFlowBranchTint(index),
+ boxShadow: `0 0 0 2px color-mix(in oklab, ${color} 35%, transparent)`,
+ }
+ : {}),
+ }
+}
+
+export function HogFlowBranchSelectionProvider({ children }: { children: ReactNode }): JSX.Element {
+ const { selectedNodeId } = useValues(hogFlowEditorLogic)
+ const [selectedBranch, setSelectedBranch] = useState<HogFlowBranchSelection | null>(null)
+
+ useEffect(() => {
+ if (selectedBranch && selectedBranch.actionId !== selectedNodeId) {
+ setSelectedBranch(null)
+ }
+ }, [selectedBranch, selectedNodeId])
+
+ return (
+ <HogFlowBranchSelectionContext.Provider value={{ selectedBranch, setSelectedBranch }}>
+ {children}
+ </HogFlowBranchSelectionContext.Provider>
+ )
+}
+
+export function useHogFlowBranchSelection(): HogFlowBranchSelectionContextValue {
+ return useContext(HogFlowBranchSelectionContext)
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsx b/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsx
index 6d845067b038..ca8be8c0972b 100644
--- a/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsx
@@ -20,15 +20,16 @@ import { IconInfo } from '@posthog/icons'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
import { workflowLogic } from '../workflowLogic'
+import { HogFlowBranchSelectionProvider } from './HogFlowBranchSelection'
import { hogFlowEditorLogic } from './hogFlowEditorLogic'
import { HogFlowEditorPanel } from './panel/HogFlowEditorPanel'
import { LOW_DETAIL_ZOOM, MIN_ZOOM } from './react_flow_utils/constants'
import { REACT_FLOW_EDGE_TYPES } from './react_flow_utils/SmartEdge'
import { REACT_FLOW_NODE_TYPES } from './steps/Nodes'
+import { HogFlowTreeEditor } from './tree/HogFlowTreeEditor'
import { HogFlowActionEdge, HogFlowActionNode } from './types'
-// Inner component that encapsulates React Flow
-function HogFlowEditorContent(): JSX.Element {
+function HogFlowGraphEditor(): JSX.Element {
const { isDarkModeOn } = useValues(themeLogic)
const { nodes, edges, dropzoneNodes, isMovingNode, isCopyingNode, isZoomedOutFar } = useValues(hogFlowEditorLogic)
@@ -38,7 +39,6 @@ function HogFlowEditorContent(): JSX.Element {
setSelectedNodeId,
setReactFlowInstance,
onNodesDelete,
- showDropzones,
onDragOver,
onDrop,
setReactFlowWrapper,
@@ -73,62 +73,89 @@ function HogFlowEditorContent(): JSX.Element {
)
return (
- <div ref={reactFlowWrapper} className="flex flex-col grow w-full" data-attr="workflow-editor">
- <ReactFlow<HogFlowActionNode, HogFlowActionEdge>
- className="grow"
- fitView
- minZoom={MIN_ZOOM}
- // Only dispatched when the detail tier flips, so panning and zooming don't put a
- // Redux action on every animation frame.
- onMove={(_, viewport) => {
- const zoomedOutFar = viewport.zoom < LOW_DETAIL_ZOOM
- if (zoomedOutFar !== isZoomedOutFar) {
- setIsZoomedOutFar(zoomedOutFar)
- }
- }}
- nodes={nodesWithDropzones}
- edges={edges}
- onNodesChange={onNodesChange}
- onEdgesChange={onEdgesChange}
- onNodesDelete={onNodesDelete}
- onDragStart={showDropzones}
- onDragOver={onDragOver}
- onDrop={onDrop}
- onNodeClick={(_, node) => node.selectable && setSelectedNodeId(node.id)}
- nodeTypes={REACT_FLOW_NODE_TYPES as NodeTypes}
- edgeTypes={REACT_FLOW_EDGE_TYPES as EdgeTypes}
- nodesDraggable={false}
- colorMode={isDarkModeOn ? 'dark' : 'light'}
- onPaneClick={handlePaneClick}
- >
- <Background gap={36} variant={BackgroundVariant.Dots} />
-
- {(isMovingNode || isCopyingNode) && (
- <Panel position="bottom-left">
- {/* Offset right of the zoom controls so the hint sits beside them */}
- <div className="flex items-center gap-1.5 ml-12 px-3 py-1.5 rounded border shadow-sm bg-surface-primary text-sm">
- <IconInfo className="text-base text-muted shrink-0" />
- <span>Click a highlighted spot to {isMovingNode ? 'move' : 'copy'} this step</span>
- <span className="text-muted">· press Esc to cancel</span>
- </div>
- </Panel>
- )}
-
- <Controls showInteractive={false} />
-
- <HogFlowEditorPanel />
- </ReactFlow>
+ <div
+ ref={reactFlowWrapper}
+ className="relative flex min-h-0 flex-1 overflow-hidden"
+ data-attr="workflow-editor"
+ >
+ <div className="flex min-h-0 min-w-0 grow">
+ <ReactFlow<HogFlowActionNode, HogFlowActionEdge>
+ className="grow"
+ fitView
+ minZoom={MIN_ZOOM}
+ // Only dispatched when the detail tier flips, so panning and zooming don't put a
+ // Redux action on every animation frame.
+ onMove={(_, viewport) => {
+ const zoomedOutFar = viewport.zoom < LOW_DETAIL_ZOOM
+ if (zoomedOutFar !== isZoomedOutFar) {
+ setIsZoomedOutFar(zoomedOutFar)
+ }
+ }}
+ nodes={nodesWithDropzones}
+ edges={edges}
+ onNodesChange={onNodesChange}
+ onEdgesChange={onEdgesChange}
+ onNodesDelete={onNodesDelete}
+ onDragOver={onDragOver}
+ onDrop={onDrop}
+ onNodeClick={(_, node) => node.selectable && setSelectedNodeId(node.id)}
+ nodeTypes={REACT_FLOW_NODE_TYPES as NodeTypes}
+ edgeTypes={REACT_FLOW_EDGE_TYPES as EdgeTypes}
+ nodesDraggable={false}
+ colorMode={isDarkModeOn ? 'dark' : 'light'}
+ onPaneClick={handlePaneClick}
+ >
+ <Background gap={36} variant={BackgroundVariant.Dots} />
+
+ {(isMovingNode || isCopyingNode) && (
+ <Panel position="bottom-left">
+ {/* Offset right of the zoom controls so the hint sits beside them */}
+ <div className="flex items-center gap-1.5 ml-12 px-3 py-1.5 rounded border shadow-sm bg-surface-primary text-sm">
+ <IconInfo className="text-base text-muted shrink-0" />
+ <span>Click a highlighted spot to {isMovingNode ? 'move' : 'copy'} this step</span>
+ <span className="text-muted">· press Esc to cancel</span>
+ </div>
+ </Panel>
+ )}
+
+ <Controls showInteractive={false} />
+ </ReactFlow>
+ </div>
+
+ <HogFlowEditorPanel />
</div>
)
}
-export function HogFlowEditor(): JSX.Element {
+function HogFlowTreeEditorContent(): JSX.Element {
+ return (
+ <div
+ className="relative flex min-h-0 flex-1 overflow-hidden @max-[48rem]/workflow-editor:flex-col @max-[48rem]/workflow-editor:overflow-y-auto"
+ data-attr="workflow-editor"
+ >
+ <HogFlowTreeEditor />
+ <HogFlowEditorPanel layout="panel" />
+ </div>
+ )
+}
+
+export function HogFlowEditor({ isTreeView }: { isTreeView: boolean }): JSX.Element {
const { logicProps } = useValues(workflowLogic)
return (
- <ReactFlowProvider>
- <BindLogic logic={hogFlowEditorLogic} props={logicProps}>
- <HogFlowEditorContent />
- </BindLogic>
- </ReactFlowProvider>
+ <BindLogic logic={hogFlowEditorLogic} props={logicProps}>
+ <HogFlowBranchSelectionProvider>
+ <div className="@container/workflow-editor flex min-h-0 flex-1">
+ {isTreeView ? (
+ <ReactFlowProvider>
+ <HogFlowTreeEditorContent />
+ </ReactFlowProvider>
+ ) : (
+ <ReactFlowProvider>
+ <HogFlowGraphEditor />
+ </ReactFlowProvider>
+ )}
+ </div>
+ </HogFlowBranchSelectionProvider>
+ </BindLogic>
)
}
diff --git a/products/workflows/frontend/Workflows/hogflows/dragPreview.ts b/products/workflows/frontend/Workflows/hogflows/dragPreview.ts
new file mode 100644
index 000000000000..6008256d6f9f
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/dragPreview.ts
@@ -0,0 +1,19 @@
+import { NODE_HEIGHT, NODE_WIDTH } from './react_flow_utils/constants'
+
+export function setHogFlowDragImage(dataTransfer: DataTransfer, element: HTMLElement | null): void {
+ if (!element || typeof dataTransfer.setDragImage !== 'function') {
+ return
+ }
+
+ const preview = element.cloneNode(true) as HTMLElement
+ preview.classList.remove('invisible')
+ preview.style.position = 'fixed'
+ preview.style.left = '0'
+ preview.style.top = '0'
+ preview.style.width = `${NODE_WIDTH * 1.5}px`
+ preview.style.height = `${NODE_HEIGHT * 1.5}px`
+ preview.style.transform = 'translate(-101%, -101%)'
+ document.body.appendChild(preview)
+ dataTransfer.setDragImage(preview, (NODE_WIDTH * 3) / 4, (NODE_HEIGHT * 3) / 4)
+ window.setTimeout(() => preview.remove())
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/graph/HogFlowGraphEditor.stories.tsx b/products/workflows/frontend/Workflows/hogflows/editor/graph/HogFlowGraphEditor.stories.tsx
index e5e34510bfb3..38e8e24c4b3c 100644
--- a/products/workflows/frontend/Workflows/hogflows/editor/graph/HogFlowGraphEditor.stories.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/editor/graph/HogFlowGraphEditor.stories.tsx
@@ -38,7 +38,7 @@ function StorybookWorkflow(): JSX.Element {
return (
<div className="flex h-full flex-col">
- {originalWorkflow ? <HogFlowEditor key={originalWorkflow.id} /> : <SpinnerOverlay />}
+ {originalWorkflow ? <HogFlowEditor key={originalWorkflow.id} isTreeView={false} /> : <SpinnerOverlay />}
</div>
)
}
diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.ts
index b76816758cdc..d62b8571509e 100644
--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.ts
@@ -2,7 +2,8 @@ import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
-import { computeMoveEdges, hogFlowEditorLogic } from './hogFlowEditorLogic'
+import { EXIT_NODE_ID, NEW_WORKFLOW, TRIGGER_NODE_ID, workflowLogic } from '../workflowLogic'
+import { computeInsertEdges, computeMoveEdges, hogFlowEditorLogic } from './hogFlowEditorLogic'
import { HogFlow, HogFlowAction, HogFlowActionEdge, HogFlowActionNode } from './types'
type Edge = HogFlow['edges'][0]
@@ -76,6 +77,84 @@ describe('computeMoveEdges', () => {
expect(result).toEqual(expected)
})
+ it('inserts a step after only the nested split paths', () => {
+ const edges = [
+ edge('trigger', 'outer', 'continue'),
+ edge('outer', 'paid', 'branch', 0),
+ edge('outer', 'onboarding', 'branch', 1),
+ edge('outer', 'at-risk', 'continue'),
+ edge('paid', 'shared', 'continue'),
+ edge('at-risk', 'shared', 'continue'),
+ edge('onboarding', 'guided', 'branch', 0),
+ edge('onboarding', 'self-serve', 'branch', 1),
+ edge('onboarding', 'shared', 'continue'),
+ edge('guided', 'shared', 'continue'),
+ edge('self-serve', 'shared', 'continue'),
+ edge('shared', 'exit', 'continue'),
+ ]
+
+ expect(
+ computeInsertEdges(edges, 'after-onboarding', 0, [
+ edge('guided', 'shared', 'continue'),
+ edge('self-serve', 'shared', 'continue'),
+ edge('onboarding', 'shared', 'continue'),
+ ])
+ ).toEqual([
+ edge('trigger', 'outer', 'continue'),
+ edge('outer', 'paid', 'branch', 0),
+ edge('outer', 'onboarding', 'branch', 1),
+ edge('outer', 'at-risk', 'continue'),
+ edge('paid', 'shared', 'continue'),
+ edge('at-risk', 'shared', 'continue'),
+ edge('onboarding', 'guided', 'branch', 0),
+ edge('onboarding', 'self-serve', 'branch', 1),
+ edge('shared', 'exit', 'continue'),
+ edge('onboarding', 'after-onboarding', 'continue'),
+ edge('guided', 'after-onboarding', 'continue'),
+ edge('self-serve', 'after-onboarding', 'continue'),
+ edge('after-onboarding', 'shared', 'continue'),
+ ])
+ })
+
+ it('moves a step after only the nested split paths', () => {
+ const edges = [
+ edge('trigger', 'move', 'continue'),
+ edge('move', 'outer', 'continue'),
+ edge('outer', 'paid', 'branch', 0),
+ edge('outer', 'onboarding', 'branch', 1),
+ edge('outer', 'at-risk', 'continue'),
+ edge('paid', 'shared', 'continue'),
+ edge('at-risk', 'shared', 'continue'),
+ edge('onboarding', 'guided', 'branch', 0),
+ edge('onboarding', 'self-serve', 'branch', 1),
+ edge('onboarding', 'shared', 'continue'),
+ edge('guided', 'shared', 'continue'),
+ edge('self-serve', 'shared', 'continue'),
+ edge('shared', 'exit', 'continue'),
+ ]
+ const joinEdges = [
+ edge('guided', 'shared', 'continue'),
+ edge('self-serve', 'shared', 'continue'),
+ edge('onboarding', 'shared', 'continue'),
+ ]
+
+ expect(computeMoveEdges(edges, 'move', joinEdges[0], true, joinEdges)).toEqual([
+ edge('trigger', 'outer', 'continue'),
+ edge('outer', 'paid', 'branch', 0),
+ edge('outer', 'onboarding', 'branch', 1),
+ edge('outer', 'at-risk', 'continue'),
+ edge('paid', 'shared', 'continue'),
+ edge('at-risk', 'shared', 'continue'),
+ edge('onboarding', 'guided', 'branch', 0),
+ edge('onboarding', 'self-serve', 'branch', 1),
+ edge('shared', 'exit', 'continue'),
+ edge('onboarding', 'move', 'continue'),
+ edge('guided', 'move', 'continue'),
+ edge('self-serve', 'move', 'continue'),
+ edge('move', 'shared', 'continue'),
+ ])
+ })
+
it('returns null when moving node has no outgoing edge', () => {
const edges = [edge('trigger', 'A', 'continue')]
expect(computeMoveEdges(edges, 'A', edge('trigger', 'A', 'continue'), false)).toBeNull()
@@ -97,6 +176,42 @@ describe('hogFlowEditorLogic', () => {
logic.mount()
})
+ it('resolves the selected action while React Flow nodes are still laying out', () => {
+ const action = logic.values.workflow.actions[0]
+ logic.actions.setNodesRaw([])
+ logic.actions.setSelectedNodeId(action.id)
+
+ expect(logic.values.selectedNode).toMatchObject({ id: action.id, data: action })
+ })
+
+ it('duplicates a linear step below itself', () => {
+ const delay: HogFlowAction = {
+ id: 'delay',
+ name: 'Delay',
+ description: '',
+ type: 'delay',
+ created_at: 0,
+ updated_at: 0,
+ config: { delay_duration: '1d' },
+ }
+ workflowLogic().actions.setWorkflowInfo({
+ actions: [NEW_WORKFLOW.actions[0], delay, NEW_WORKFLOW.actions[1]],
+ edges: [edge(TRIGGER_NODE_ID, delay.id, 'continue'), edge(delay.id, EXIT_NODE_ID, 'continue')],
+ })
+
+ logic.actions.duplicateNodeBelow(delay.id)
+
+ const duplicatedAction = logic.values.workflow.actions.find(
+ (action) => action.id !== delay.id && action.type === delay.type
+ )
+ expect(duplicatedAction).toMatchObject({ name: delay.name, config: delay.config })
+ expect(logic.values.workflow.edges).toEqual([
+ edge(TRIGGER_NODE_ID, delay.id, 'continue'),
+ edge(delay.id, duplicatedAction!.id, 'continue'),
+ edge(duplicatedAction!.id, EXIT_NODE_ID, 'continue'),
+ ])
+ })
+
describe('conditional branch naming', () => {
const createMockHogFlow = (conditionNames?: (string | undefined)[]): HogFlow => ({
id: 'test-flow',
diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
index 3196a6c70a26..939588df78a0 100644
--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
@@ -34,12 +34,44 @@ import { BOTTOM_HANDLE_POSITION, NODE_HEIGHT, NODE_WIDTH, TOP_HANDLE_POSITION }
import { getSmartStepPath } from './react_flow_utils/SmartEdge'
import { getHogFlowStep } from './steps/HogFlowSteps'
import { CyclotronInputType, StepViewNodeHandle } from './steps/types'
+import { isWorkflowTreeComplete } from './tree/workflowTree'
import type { DropzoneNode, HogFlow, HogFlowAction, HogFlowActionEdge, HogFlowActionNode } from './types'
import type { HogFlowEdge } from './types'
const getEdgeId = (edge: HogFlow['edges'][number]): string =>
`${edge.from}->${edge.to} ${edge.type} ${edge.index ?? ''}`.trim()
+export function computeInsertEdges(
+ edges: HogFlow['edges'],
+ newActionId: string,
+ branchEdges: number,
+ edgesToReplace: HogFlow['edges']
+): HogFlow['edges'] | null {
+ const edgeIdsToReplace = new Set(edgesToReplace.map(getEdgeId))
+ const matchingEdges = edges.filter((edge) => edgeIdsToReplace.has(getEdgeId(edge)))
+
+ if (matchingEdges.length === 0 || matchingEdges.length !== edgesToReplace.length) {
+ return null
+ }
+
+ return [
+ ...edges.filter((edge) => !edgeIdsToReplace.has(getEdgeId(edge))),
+ ...matchingEdges.map((edge) => ({ ...edge, to: newActionId })),
+ ...Array.from({ length: branchEdges }, (_, index) => ({
+ ...matchingEdges[0],
+ index,
+ type: 'branch' as const,
+ from: newActionId,
+ })),
+ {
+ ...matchingEdges[0],
+ index: undefined,
+ type: 'continue' as const,
+ from: newActionId,
+ },
+ ]
+}
+
/**
* Helper to get branch label with custom name fallback
*/
@@ -77,7 +109,8 @@ export function computeMoveEdges(
edges: HogFlow['edges'],
movingNodeId: string,
targetEdge: HogFlow['edges'][0],
- isBranchJoinDropzone: boolean
+ isBranchJoinDropzone: boolean,
+ joinEdges?: HogFlow['edges']
): HogFlow['edges'] | null {
const incomingEdges = edges.filter((e) => e.to === movingNodeId)
const outgoingEdge = edges.find((e) => e.from === movingNodeId)
@@ -98,9 +131,10 @@ export function computeMoveEdges(
if (isBranchJoinDropzone) {
const newTarget = targetEdge.to === movingNodeId ? outgoingEdge.to : targetEdge.to
+ const joinEdgeIds = joinEdges ? new Set(joinEdges.map(getEdgeId)) : null
edgesToSplitIndexes = newEdges
.map((edge, index) => ({ edge, index }))
- .filter(({ edge }) => edge.to === newTarget)
+ .filter(({ edge }) => (joinEdgeIds ? joinEdgeIds.has(getEdgeId(edge)) : edge.to === newTarget))
.map(({ index }) => index)
} else {
edgesToSplitIndexes = [
@@ -138,6 +172,7 @@ export function computeMoveEdges(
export const HOG_FLOW_EDITOR_MODES = ['build', 'variables', 'test', 'metrics', 'logs'] as const
export type HogFlowEditorMode = (typeof HOG_FLOW_EDITOR_MODES)[number]
export const HOG_FLOW_EDITOR_DEFAULT_PANEL_WIDTH = 592
+export type HogFlowEditorLayout = 'simple' | 'advanced'
export type HogFlowEditorActionMetrics = {
actionId: string
succeeded: number
@@ -170,6 +205,7 @@ export interface hogFlowEditorLogicValues {
animatingEdgePair: string | null
dropzoneNodes: DropzoneNode[]
edges: HogFlowActionEdge[]
+ editorLayout: HogFlowEditorLayout
highlightedDropzoneNodeId: string | null
isCopyingNode: boolean
isMovingNode: boolean
@@ -1944,6 +1980,9 @@ export interface hogFlowEditorLogicActions {
copyNodeToHighlightedDropzone: () => {
value: true
}
+ duplicateNodeBelow: (actionId: string) => {
+ actionId: string
+ }
fitView: (options?: { duration?: number; noZoom?: boolean }) => {
duration?: number | undefined
noZoom?: boolean | undefined
@@ -1981,14 +2020,31 @@ export interface hogFlowEditorLogicActions {
timezone: string
}
}
+ moveNodeToEdge: (
+ movingNodeId: string,
+ targetEdge: HogFlowEdge,
+ isBranchJoinDropzone: boolean,
+ joinEdges?: HogFlowEdge[]
+ ) => {
+ isBranchJoinDropzone: boolean
+ joinEdges: HogFlowEdge[] | undefined
+ movingNodeId: string
+ targetEdge: HogFlowEdge
+ }
moveNodeToHighlightedDropzone: () => {
value: true
}
onDragOver: (event: DragEvent) => {
event: DragEvent<Element>
}
- onDrop: (event?: DragEvent) => {
+ onDrop: (
+ event?: DragEvent,
+ targetEdge?: HogFlowEdge,
+ joinEdges?: HogFlowEdge[]
+ ) => {
event: DragEvent<Element> | undefined
+ joinEdges: HogFlowEdge[] | undefined
+ targetEdge: HogFlowEdge | undefined
}
onEdgesChange: (edges: EdgeChange<HogFlowActionEdge>[]) => {
edges: EdgeChange<HogFlowActionEdge>[]
@@ -2015,6 +2071,9 @@ export interface hogFlowEditorLogicActions {
setEdges: (edges: HogFlowActionEdge[]) => {
edges: HogFlowActionEdge[]
}
+ setEditorLayout: (editorLayout: HogFlowEditorLayout) => {
+ editorLayout: HogFlowEditorLayout
+ }
setHighlightedDropzoneNodeId: (highlightedDropzoneNodeId: string | null) => {
highlightedDropzoneNodeId: string | null
}
@@ -2067,7 +2126,11 @@ export interface hogFlowEditorLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
nodesById: (nodes: HogFlowActionNode[]) => Record<string, HogFlowActionNode>
- selectedNode: (nodes: HogFlowActionNode[], selectedNodeId: string | null) => HogFlowActionNode | null
+ selectedNode: (
+ nodes: HogFlowActionNode[],
+ selectedNodeId: string | null,
+ workflow: HogFlow
+ ) => HogFlowActionNode | null
selectedNodeCanBeDeleted: (
selectedNode: HogFlowActionNode | null,
nodes: HogFlowActionNode[],
@@ -2090,7 +2153,7 @@ export type hogFlowEditorLogicType = MakeLogicType<
export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
props({} as WorkflowLogicProps),
path((key) => ['scenes', 'hogflows', 'hogFlowEditorLogic', key]),
- key((props) => `hog-flow-editor-${props.id}`),
+ key((props) => `hog-flow-editor-${props.id}-${props.templateId || 'default'}-${props.editTemplateId || 'default'}`),
connect(() => ({
values: [
workflowLogic,
@@ -2124,9 +2187,14 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
}),
setReactFlowWrapper: (reactFlowWrapper: RefObject<HTMLDivElement>) => ({ reactFlowWrapper }),
onDragOver: (event: DragEvent) => ({ event }),
- onDrop: (event?: DragEvent) => ({ event }),
+ onDrop: (event?: DragEvent, targetEdge?: HogFlowEdge, joinEdges?: HogFlowEdge[]) => ({
+ event,
+ targetEdge,
+ joinEdges,
+ }),
setNodeToBeAdded: (nodeToBeAdded: CreateActionType | HogFlowActionNode | null) => ({ nodeToBeAdded }),
setHighlightedDropzoneNodeId: (highlightedDropzoneNodeId: string | null) => ({ highlightedDropzoneNodeId }),
+ setEditorLayout: (editorLayout: HogFlowEditorLayout) => ({ editorLayout }),
setMode: (mode: HogFlowEditorMode) => ({ mode }),
setPanelWidth: (panelWidth: number) => ({ panelWidth }),
clearPanelWidth: true,
@@ -2138,6 +2206,18 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
startMovingNode: (node: HogFlowActionNode) => ({ node }),
stopMovingNode: true,
moveNodeToHighlightedDropzone: true,
+ moveNodeToEdge: (
+ movingNodeId: string,
+ targetEdge: HogFlowEdge,
+ isBranchJoinDropzone: boolean,
+ joinEdges?: HogFlowEdge[]
+ ) => ({
+ movingNodeId,
+ targetEdge,
+ isBranchJoinDropzone,
+ joinEdges,
+ }),
+ duplicateNodeBelow: (actionId: string) => ({ actionId }),
loadActionMetricsById: (
params: Pick<AppMetricsTotalsRequest, 'appSource' | 'appSourceId' | 'dateFrom' | 'dateTo'>,
timezone: string
@@ -2147,6 +2227,12 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
setIsZoomedOutFar: (isZoomedOutFar: boolean) => ({ isZoomedOutFar }),
}),
reducers(() => ({
+ editorLayout: [
+ 'simple' as HogFlowEditorLayout,
+ {
+ setEditorLayout: (_, { editorLayout }) => editorLayout,
+ },
+ ],
mode: [
'build' as HogFlowEditorMode,
{
@@ -2262,9 +2348,30 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
},
],
selectedNode: [
- (s) => [s.nodes, s.selectedNodeId],
- (nodes: HogFlowActionNode[], selectedNodeId: string | null) => {
- return nodes.find((node) => node.id === selectedNodeId) ?? null
+ (s) => [s.nodes, s.selectedNodeId, s.workflow],
+ (
+ nodes: HogFlowActionNode[],
+ selectedNodeId: string | null,
+ workflow: HogFlow
+ ): HogFlowActionNode | null => {
+ const node = nodes.find((node) => node.id === selectedNodeId)
+ if (node || !selectedNodeId) {
+ return node ?? null
+ }
+
+ const action = workflow.actions.find((action) => action.id === selectedNodeId)
+ return action
+ ? ({
+ id: action.id,
+ type: 'action',
+ data: action,
+ position: { x: 0, y: 0 },
+ deletable: !['trigger', 'exit'].includes(action.type),
+ selectable: true,
+ draggable: false,
+ connectable: false,
+ } satisfies HogFlowActionNode)
+ : null
},
],
selectedNodeCanBeDeleted: [
@@ -2490,13 +2597,13 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
// Find the deleted node
const deletedNode = deleted.find((node) => node.id === hogFlowEdge.to)
if (deletedNode) {
- // Find the first outgoer of the deleted node
- const outgoers = getOutgoers(deletedNode, values.nodes, values.edges)
- if (outgoers.length > 0) {
+ // The React Flow layout may still be pending, so rewire from the canonical workflow.
+ const outgoer = values.workflow.edges.find((edge) => edge.from === deletedNode.id)
+ if (outgoer) {
// Change target to the first outgoer
return {
...hogFlowEdge,
- to: outgoers[0].id,
+ to: outgoer.to,
}
}
}
@@ -2605,12 +2712,18 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
event.dataTransfer.dropEffect = 'move'
},
- onDrop: ({ event }) => {
+ onDrop: ({ event, targetEdge, joinEdges }) => {
event?.preventDefault()
const dropzoneNode = values.dropzoneNodes.find((x) => x.id === values.highlightedDropzoneNodeId)
- if (values.nodeToBeAdded && dropzoneNode) {
- const edgeToInsertNodeInto = dropzoneNode?.data.edge
+ if (values.nodeToBeAdded && (dropzoneNode || targetEdge)) {
+ const edgeToInsertNodeInto = targetEdge
+ ? ({
+ id: getEdgeId(targetEdge),
+ source: targetEdge.from,
+ target: targetEdge.to,
+ } as HogFlowActionEdge)
+ : dropzoneNode!.data.edge
// Check if nodeToBeAdded is a HogFlowActionNode (has 'data' property) or CreateActionType
const isHogFlowActionNode = 'data' in values.nodeToBeAdded
@@ -2658,81 +2771,31 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
const branchEdges = isHogFlowActionNode
? 0
: ((partialNewAction as CreateActionType).branchEdges ?? 0)
- const isBranchJoinDropzone = dropzoneNode?.data.isBranchJoinDropzone ?? false
+ const isBranchJoinDropzone =
+ !!joinEdges || (!targetEdge && (dropzoneNode?.data.isBranchJoinDropzone ?? false))
if (!step) {
throw new Error(`Step not found for action type: ${newAction}`)
}
- let edgesToBeReplacedIndexes = []
-
- if (isBranchJoinDropzone) {
- // There are multiple edges that need to be replaced here to join the branches on new node
-
- /**
- * If isBranchJoinDropzone is set, we know to connect this new node on top with all previous target's sources
- * and below with the original edges' shared target
- */
- edgesToBeReplacedIndexes = values.workflow.edges
- .map((edge, index) => ({
- edge,
- index,
- }))
- .filter(({ edge }) => edge.to === edgeToInsertNodeInto.target)
- .map(({ index }) => index)
- } else {
- // There is just the one *very specific* (i.e. getEdgeId must be used) target edge that needs to be replaced
- edgesToBeReplacedIndexes = [
- values.workflow.edges.findIndex((edge) => getEdgeId(edge) === edgeToInsertNodeInto.id),
- ]
- }
+ const edgesToBeReplaced = joinEdges
+ ? values.workflow.edges.filter((edge) =>
+ joinEdges.some((joinEdge) => getEdgeId(edge) === getEdgeId(joinEdge))
+ )
+ : isBranchJoinDropzone
+ ? values.workflow.edges.filter((edge) => edge.to === edgeToInsertNodeInto.target)
+ : values.workflow.edges.filter((edge) => getEdgeId(edge) === edgeToInsertNodeInto.id)
+ const newEdges = computeInsertEdges(
+ values.workflow.edges,
+ newAction.id,
+ branchEdges,
+ edgesToBeReplaced
+ )
- if (edgesToBeReplacedIndexes.length === 0) {
+ if (!newEdges) {
throw new Error('Edge to be replaced not found')
}
- // We add the new action with two new edges - the continue edge and the target edge
- // We also then check for any other missing edges based on the type of edge being replaced
-
- const newEdges: HogFlow['edges'] = [...values.workflow.edges]
-
- // First remove the edge to be replaced
- const edgesToBeReplaced = edgesToBeReplacedIndexes.map((index) => values.workflow.edges[index])
-
- // Sort indexes in descending order to avoid index shifting during removal
- edgesToBeReplacedIndexes
- .sort((a, b) => b - a)
- .forEach((index) => {
- newEdges.splice(index, 1)
- })
-
- for (const edgeToBeReplaced of edgesToBeReplaced) {
- // Push the source edge first
- newEdges.push({
- ...edgeToBeReplaced,
- to: newAction.id,
- })
- }
-
- // Then any branch edges (once, not per incoming edge)
- for (let i = 0; i < branchEdges; i++) {
- // Add in branching edges
- newEdges.push({
- ...edgesToBeReplaced[0],
- index: i,
- type: 'branch',
- from: newAction.id,
- })
- }
-
- // Finally the last continue edge
- newEdges.push({
- ...edgesToBeReplaced[0],
- index: undefined,
- type: 'continue',
- from: newAction.id,
- })
-
// Auto-create workflow variables if the action has a default output_variable
let updatedVariables = values.workflow.variables
const outputVars = Array.isArray(newAction.output_variable)
@@ -2889,23 +2952,39 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
}
const isBranchJoinDropzone = dropzoneNode.data.isBranchJoinDropzone ?? false
+ actions.moveNodeToEdge(movingNodeId, targetHogFlowEdge, isBranchJoinDropzone)
+ actions.hideDropzones()
+ actions.stopMovingNode()
+ },
+ moveNodeToEdge: ({ movingNodeId, targetEdge, isBranchJoinDropzone, joinEdges }) => {
+ // Uses computeMoveEdges (pure function) to manipulate edges in a single
+ // setWorkflowInfo call. This preserves node identity while moving a step.
const newEdges = computeMoveEdges(
values.workflow.edges,
movingNodeId,
- targetHogFlowEdge,
- isBranchJoinDropzone
+ targetEdge,
+ isBranchJoinDropzone,
+ joinEdges
)
if (!newEdges) {
lemonToast.error("Couldn't move this step there. Try a different spot.")
- actions.stopMovingNode()
return
}
actions.setWorkflowInfo({ actions: values.workflow.actions, edges: newEdges })
actions.setSelectedNodeId(movingNodeId)
- actions.hideDropzones()
- actions.stopMovingNode()
+ },
+ duplicateNodeBelow: ({ actionId }) => {
+ const action = values.workflow.actions.find((action) => action.id === actionId)
+ const targetEdge = values.workflow.edges.find((edge) => edge.from === actionId)
+
+ if (!action || action.type === 'trigger' || action.type === 'exit' || !targetEdge) {
+ return
+ }
+
+ actions.setNodeToBeAdded(action)
+ actions.onDrop(undefined, targetEdge)
},
handlePaneClick: () => {
actions.setSelectedNodeId(null)
@@ -2919,11 +2998,14 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
}
}),
- subscriptions(({ actions }) => ({
+ subscriptions(({ actions, values }) => ({
workflow: (hogFlow?: HogFlow, oldHogFlow?: HogFlow) => {
// Auto-save round-trips can emit a deep-equal workflow; skipping the rebuild avoids
// re-deriving every node and edge (including the async layout pass) for no change.
if (hogFlow && !objectsEqual(hogFlow, oldHogFlow)) {
+ if (values.editorLayout === 'simple' && !isWorkflowTreeComplete(hogFlow)) {
+ actions.setEditorLayout('advanced')
+ }
actions.resetFlowFromHogFlow(hogFlow)
}
},
@@ -2947,17 +3029,26 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
return {
setSelectedNodeId: () => syncProperty('node', values.selectedNodeId ?? null),
setMode: () => syncProperty('mode', values.mode),
+ setEditorLayout: () => syncProperty('view', values.editorLayout === 'simple' ? 'linear' : 'graph'),
}
}),
urlToAction(({ actions, values }) => {
const reactToTabChange = (_: any, search: Record<string, string>): void => {
- const { node = null, mode } = search
+ const { node = null, mode, view } = search
if (node !== values.selectedNodeId) {
actions.setSelectedNodeId(node ?? null)
}
if (mode && HOG_FLOW_EDITOR_MODES.includes(mode as HogFlowEditorMode) && mode !== values.mode) {
actions.setMode(mode as HogFlowEditorMode)
}
+ const requestedEditorLayout = view === 'graph' ? 'advanced' : 'simple'
+ const editorLayout =
+ requestedEditorLayout === 'simple' && !isWorkflowTreeComplete(values.workflow)
+ ? 'advanced'
+ : requestedEditorLayout
+ if (editorLayout !== values.editorLayout) {
+ actions.setEditorLayout(editorLayout)
+ }
}
return {
@@ -2966,6 +3057,11 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
}),
events(({ actions, values }) => ({
afterMount: () => {
+ if (values.editorLayout === 'simple' && !isWorkflowTreeComplete(values.workflow)) {
+ actions.setEditorLayout('advanced')
+ }
+ actions.resetFlowFromHogFlow(values.workflow)
+
const handleKeyDown = (e: KeyboardEvent): void => {
if (e.key === 'Escape') {
if (values.isCopyingNode) {
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.tsx
index f050deefd584..e9a1ccf3c2d8 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.tsx
@@ -1,9 +1,12 @@
import clsx from 'clsx'
import { useActions, useValues } from 'kea'
+import { useRef } from 'react'
import { IconArrowLeft } from '@posthog/icons'
import { LemonBadge, LemonButton, LemonTab, LemonTabs } from '@posthog/lemon-ui'
+import { Resizer } from 'lib/components/Resizer/Resizer'
+import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'
import { capitalizeFirstLetter } from 'lib/utils/strings'
import {
@@ -22,9 +25,19 @@ import { HogFlowEditorPanelVariables } from './HogFlowEditorPanelVariables'
import { EmailActionTestContent } from './testing/HogFlowEditorNotificationPanelTest'
import { HogFlowEditorPanelTest } from './testing/HogFlowEditorPanelTest'
-export function HogFlowEditorPanel(): JSX.Element | null {
+export function HogFlowEditorPanel({
+ layout = 'floating',
+}: { layout?: 'floating' | 'panel' } = {}): JSX.Element | null {
const { panelWidth, selectedNode, mode, workflow } = useValues(hogFlowEditorLogic)
const { clearPanelWidth, setMode, setPanelWidth, setSelectedNodeId } = useActions(hogFlowEditorLogic)
+ const panelRef = useRef<HTMLDivElement>(null)
+ const resizerProps: ResizerLogicProps = {
+ logicKey: 'hog-flow-simple-panel',
+ containerRef: panelRef,
+ placement: 'left',
+ persistent: true,
+ }
+ const { desiredSize: panelLayoutWidth } = useValues(resizerLogic(resizerProps))
const variablesCount = workflow?.variables?.length || 0
@@ -48,16 +61,39 @@ export function HogFlowEditorPanel(): JSX.Element | null {
return (
<div
- className="absolute right-0 flex max-h-full max-w-full flex-col justify-end overflow-hidden p-2"
- style={{ width: panelWidth ?? HOG_FLOW_EDITOR_DEFAULT_PANEL_WIDTH }}
+ ref={panelRef}
+ className={clsx(
+ 'flex min-h-0 max-h-full flex-col justify-end overflow-hidden',
+ layout === 'floating'
+ ? 'absolute right-0 max-w-full p-2'
+ : 'relative h-full shrink-0 bg-surface-primary @max-[48rem]/workflow-editor:!h-96 @max-[48rem]/workflow-editor:!min-w-0 @max-[48rem]/workflow-editor:!w-full @max-[48rem]/workflow-editor:!max-w-full @max-[48rem]/workflow-editor:border-t'
+ )}
+ style={
+ layout === 'floating'
+ ? { width: panelWidth ?? HOG_FLOW_EDITOR_DEFAULT_PANEL_WIDTH }
+ : { width: panelLayoutWidth ?? '50%', minWidth: '20rem', maxWidth: '70%' }
+ }
>
- <HogFlowEditorPanelResizeHandle
- width={panelWidth ?? HOG_FLOW_EDITOR_DEFAULT_PANEL_WIDTH}
- onResize={setPanelWidth}
- onReset={clearPanelWidth}
- />
- <div className="relative z-10 flex max-h-full flex-col overflow-hidden rounded-md border bg-surface-primary shadow-[0_3px_0_var(--border)]">
- <div className="flex gap-2 border-b items-center">
+ {layout === 'floating' ? (
+ <HogFlowEditorPanelResizeHandle
+ width={panelWidth ?? HOG_FLOW_EDITOR_DEFAULT_PANEL_WIDTH}
+ onResize={setPanelWidth}
+ onReset={clearPanelWidth}
+ />
+ ) : (
+ <div className="@max-[48rem]/workflow-editor:hidden">
+ <Resizer {...resizerProps} />
+ </div>
+ )}
+ <div
+ className={clsx(
+ 'relative z-10 flex min-h-0 flex-col overflow-hidden bg-surface-primary',
+ layout === 'floating'
+ ? 'max-h-full rounded-md border shadow-[0_3px_0_var(--border)]'
+ : 'h-full !rounded-none'
+ )}
+ >
+ <div className="flex shrink-0 items-center gap-2 border-b">
<div
className={clsx(
'transition-all overflow-hidden flex p-1',
@@ -72,7 +108,7 @@ export function HogFlowEditorPanel(): JSX.Element | null {
/>
</div>
- <div className="flex-1">
+ <div className="min-w-0 flex-1">
<LemonTabs
activeKey={mode}
onChange={(key) => setMode(key)}
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx
index ef92fc7a1823..766ece8bef50 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx
@@ -18,7 +18,7 @@ import '../registry'
import { FEATURE_FLAGS } from 'lib/constants'
import { PERSON_DEPENDENT_ACTION_TYPES, workflowLogic } from '../../workflowLogic'
-import { NODE_HEIGHT, NODE_WIDTH } from '../react_flow_utils/constants'
+import { setHogFlowDragImage } from '../dragPreview'
import { getRegisteredActionNodeCategories } from '../registry/actions/actionNodeRegistry'
import { StepView } from '../steps/components/StepView'
import { useHogFlowStep } from '../steps/HogFlowSteps'
@@ -189,31 +189,27 @@ const TEMPLATE_IDS_AT_TOP_LEVEL: string[] = [
function HogFlowEditorToolbarNode({
action,
+ onActionSelect,
children,
}: {
action: CreateActionType
+ onActionSelect?: (action: CreateActionType) => void
children?: React.ReactNode
}): JSX.Element | null {
- const { setNodeToBeAdded } = useActions(hogFlowEditorLogic)
+ const { hideDropzones, setNodeToBeAdded, showDropzones } = useActions(hogFlowEditorLogic)
const dragPreviewRef = useRef<HTMLDivElement>(null)
const onDragStart = (event: React.DragEvent): void => {
setNodeToBeAdded(action)
+ showDropzones()
event.dataTransfer.setData('application/reactflow', action.type)
event.dataTransfer.effectAllowed = 'move'
- if (dragPreviewRef.current) {
- const dragPreview = dragPreviewRef.current.cloneNode(true) as HTMLDivElement
- dragPreview.classList.remove('invisible')
- dragPreview.style.position = 'fixed'
- dragPreview.style.left = '0'
- dragPreview.style.top = '0'
- dragPreview.style.width = `${NODE_WIDTH * 1.5}px`
- dragPreview.style.height = `${NODE_HEIGHT * 1.5}px`
- dragPreview.style.transform = 'translate(-101%, -101%)'
- document.body.appendChild(dragPreview)
- event.dataTransfer.setDragImage(dragPreview, (NODE_WIDTH * 3) / 4, (NODE_HEIGHT * 3) / 4)
- window.setTimeout(() => dragPreview.remove())
- }
+ setHogFlowDragImage(event.dataTransfer, dragPreviewRef.current)
+ }
+
+ const onDragEnd = (): void => {
+ setNodeToBeAdded(null)
+ hideDropzones()
}
const step = useHogFlowStep(action as HogFlowAction)
@@ -224,22 +220,29 @@ function HogFlowEditorToolbarNode({
return (
<>
- <div draggable onDragStart={onDragStart}>
+ <div
+ draggable={!onActionSelect}
+ onDragStart={onActionSelect ? undefined : onDragStart}
+ onDragEnd={onActionSelect ? undefined : onDragEnd}
+ >
<LemonButton
icon={<span style={{ color: step.color }}>{step.icon}</span>}
- sideIcon={<IconDrag />}
+ sideIcon={onActionSelect ? undefined : <IconDrag />}
fullWidth
+ onClick={onActionSelect ? () => onActionSelect(action) : undefined}
>
{children ?? action.name}
</LemonButton>
</div>
- <div ref={dragPreviewRef} className="pointer-events-none absolute invisible" aria-hidden="true">
- <div className="origin-top-left scale-150">
- <StepView
- action={{ ...action, id: `drag-preview-${action.type}-${action.name}` } as HogFlowAction}
- />
+ {!onActionSelect && (
+ <div ref={dragPreviewRef} className="pointer-events-none absolute invisible" aria-hidden="true">
+ <div className="origin-top-left scale-150">
+ <StepView
+ action={{ ...action, id: `drag-preview-${action.type}-${action.name}` } as HogFlowAction}
+ />
+ </div>
</div>
- </div>
+ )}
</>
)
}
@@ -272,7 +275,11 @@ const customFilterFunction = (template: HogFunctionTemplateType): boolean => {
return true
}
-function HogFunctionTemplatesChooser(): JSX.Element {
+function HogFunctionTemplatesChooser({
+ onActionSelect,
+}: {
+ onActionSelect?: (action: CreateActionType) => void
+}): JSX.Element {
const logic = hogFunctionTemplateListLogic({
type: 'destination',
customFilterFunction,
@@ -319,6 +326,7 @@ function HogFunctionTemplatesChooser(): JSX.Element {
: '',
config: { template_id: template.id, inputs: {} },
}}
+ onActionSelect={onActionSelect}
>
<div className="py-1 flex items-center gap-1 flex-1">
<div className="flex-1">
@@ -343,7 +351,13 @@ function HogFunctionTemplatesChooser(): JSX.Element {
)
}
-export function HogFlowEditorPanelBuild(): JSX.Element {
+export function HogFlowEditorPanelBuild({
+ className,
+ onActionSelect,
+}: {
+ className?: string
+ onActionSelect?: (action: CreateActionType) => void
+} = {}): JSX.Element {
const { featureFlags } = useValues(featureFlagLogic)
const { currentTeam } = useValues(teamLogic)
const { isRowScopedTrigger } = useValues(workflowLogic)
@@ -360,13 +374,24 @@ export function HogFlowEditorPanelBuild(): JSX.Element {
const logicNodes = hideIfRowScoped(LOGIC_NODES_TO_SHOW)
return (
- <div className="flex flex-col overflow-y-auto" data-attr="workflow-add-action">
+ <div
+ className={`flex flex-col overflow-y-auto${className ? ` ${className}` : ''}`}
+ data-attr="workflow-add-action"
+ >
<HogFlowEditorToolbarSection title="Dispatch">
{ACTION_NODES_TO_SHOW.map((node, index) => (
- <HogFlowEditorToolbarNode key={`${node.type}-${index}`} action={node} />
+ <HogFlowEditorToolbarNode
+ key={`${node.type}-${index}`}
+ action={node}
+ onActionSelect={onActionSelect}
+ />
))}
{featureFlags[FEATURE_FLAGS.WORKFLOWS_PUSH_NOTIFICATIONS] && (
- <HogFlowEditorToolbarNode key="push-notifications" action={PUSH_NOTIFICATION_ACTION_NODE}>
+ <HogFlowEditorToolbarNode
+ key="push-notifications"
+ action={PUSH_NOTIFICATION_ACTION_NODE}
+ onActionSelect={onActionSelect}
+ >
<span className="inline-flex items-center gap-1.5">
{PUSH_NOTIFICATION_ACTION_NODE.name}
<LemonTag type="completion">Beta</LemonTag>
@@ -374,7 +399,11 @@ export function HogFlowEditorPanelBuild(): JSX.Element {
</HogFlowEditorToolbarNode>
)}
{featureFlags[FEATURE_FLAGS.WORKFLOW_AI_TASK_ACTION] && (
- <HogFlowEditorToolbarNode key="ai-task" action={AI_TASK_ACTION_NODE}>
+ <HogFlowEditorToolbarNode
+ key="ai-task"
+ action={AI_TASK_ACTION_NODE}
+ onActionSelect={onActionSelect}
+ >
<span className="inline-flex items-center gap-1.5">
{AI_TASK_ACTION_NODE.name}
<LemonTag type="completion">Beta</LemonTag>
@@ -387,40 +416,60 @@ export function HogFlowEditorPanelBuild(): JSX.Element {
{featureFlags[FEATURE_FLAGS.WORKFLOW_RUN_SCOUT_ACTION] &&
!!currentTeam &&
currentTeam.id === currentTeam.project_id && (
- <HogFlowEditorToolbarNode key="run-scout" action={RUN_SCOUT_ACTION_NODE}>
+ <HogFlowEditorToolbarNode
+ key="run-scout"
+ action={RUN_SCOUT_ACTION_NODE}
+ onActionSelect={onActionSelect}
+ >
<span className="inline-flex items-center gap-1.5">
{RUN_SCOUT_ACTION_NODE.name}
<LemonTag type="completion">Beta</LemonTag>
</span>
</HogFlowEditorToolbarNode>
)}
- <HogFunctionTemplatesChooser />
+ <HogFunctionTemplatesChooser onActionSelect={onActionSelect} />
</HogFlowEditorToolbarSection>
<HogFlowEditorToolbarSection title="Delays">
{delayNodes.map((action, index) => (
- <HogFlowEditorToolbarNode key={`${action.type}-${index}`} action={action} />
+ <HogFlowEditorToolbarNode
+ key={`${action.type}-${index}`}
+ action={action}
+ onActionSelect={onActionSelect}
+ />
))}
</HogFlowEditorToolbarSection>
{logicNodes.length > 0 && (
<HogFlowEditorToolbarSection title="Audience split">
{logicNodes.map((action, index) => (
- <HogFlowEditorToolbarNode key={`${action.type}-${index}`} action={action} />
+ <HogFlowEditorToolbarNode
+ key={`${action.type}-${index}`}
+ action={action}
+ onActionSelect={onActionSelect}
+ />
))}
</HogFlowEditorToolbarSection>
)}
<HogFlowEditorToolbarSection title="PostHog actions">
{POSTHOG_NODES_TO_SHOW.map((action, index) => (
- <HogFlowEditorToolbarNode key={`${action.type}-${index}`} action={action} />
+ <HogFlowEditorToolbarNode
+ key={`${action.type}-${index}`}
+ action={action}
+ onActionSelect={onActionSelect}
+ />
))}
</HogFlowEditorToolbarSection>
{registeredCategories.map((cat) => (
<HogFlowEditorToolbarSection key={cat.label} title={cat.label}>
{cat.nodes.map((action, index) => (
- <HogFlowEditorToolbarNode key={`${action.type}-${index}`} action={action} />
+ <HogFlowEditorToolbarNode
+ key={`${action.type}-${index}`}
+ action={action}
+ onActionSelect={onActionSelect}
+ />
))}
</HogFlowEditorToolbarSection>
))}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/HogFlowBranchCard.tsx b/products/workflows/frontend/Workflows/hogflows/steps/HogFlowBranchCard.tsx
new file mode 100644
index 000000000000..3823a546b495
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/HogFlowBranchCard.tsx
@@ -0,0 +1,60 @@
+import type { ReactNode } from 'react'
+
+import { IconX } from '@posthog/icons'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+
+import { getHogFlowBranchColor, getHogFlowBranchStyle, useHogFlowBranchSelection } from '../HogFlowBranchSelection'
+import { HogFlowBranchNameInput } from './HogFlowBranchNameInput'
+
+export function HogFlowBranchCard({
+ actionId,
+ index,
+ name,
+ onNameChange,
+ placeholder,
+ ariaLabel,
+ onRemove,
+ removeDisabledReason,
+ headerAddon,
+ children,
+}: {
+ actionId: string
+ index: number
+ name: string
+ onNameChange: (value: string) => void
+ placeholder: string
+ ariaLabel: string
+ onRemove: () => void
+ removeDisabledReason?: string
+ headerAddon?: ReactNode
+ children: ReactNode
+}): JSX.Element {
+ const { selectedBranch, setSelectedBranch } = useHogFlowBranchSelection()
+ const branchColor = getHogFlowBranchColor(index)
+ const isSelected = selectedBranch?.actionId === actionId && selectedBranch.index === index
+
+ return (
+ <div
+ className="flex flex-col gap-3 rounded border p-3 transition-colors motion-reduce:transition-none"
+ style={getHogFlowBranchStyle(index, isSelected)}
+ onFocusCapture={() => setSelectedBranch({ actionId, index })}
+ onPointerDownCapture={() => setSelectedBranch({ actionId, index })}
+ >
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <HogFlowBranchNameInput
+ branchColor={branchColor}
+ value={name}
+ onChange={onNameChange}
+ placeholder={placeholder}
+ ariaLabel={ariaLabel}
+ />
+ {headerAddon}
+ </div>
+ <LemonButton size="xsmall" icon={<IconX />} onClick={onRemove} disabledReason={removeDisabledReason} />
+ </div>
+ {children}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/HogFlowBranchNameInput.tsx b/products/workflows/frontend/Workflows/hogflows/steps/HogFlowBranchNameInput.tsx
index 344b67f507c2..8fbf2ae06f3e 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/HogFlowBranchNameInput.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/HogFlowBranchNameInput.tsx
@@ -3,25 +3,28 @@ import './HogFlowBranchNameInput.scss'
import { LemonInput } from 'lib/lemon-ui/LemonInput'
export function HogFlowBranchNameInput({
+ branchColor,
value,
onChange,
placeholder,
ariaLabel,
}: {
+ branchColor: string
value: string | undefined
onChange: (value: string) => void
placeholder: string
ariaLabel: string
}): JSX.Element {
return (
- <div className="HogFlowBranchNameInput min-w-0 flex-1">
+ <div className="HogFlowBranchNameInput flex min-w-0 flex-1 items-center gap-2">
+ <span className="size-2 shrink-0 rounded-full" style={{ backgroundColor: branchColor }} />
<LemonInput
value={value || ''}
onChange={onChange}
placeholder={placeholder}
size="small"
transparentBackground
- className="min-w-0"
+ className="min-w-0 flex-1"
aria-label={ariaLabel}
data-attr="workflow-panel-select-branch"
/>
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/HogFlowSteps.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/HogFlowSteps.test.ts
new file mode 100644
index 000000000000..9720aeee021c
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/HogFlowSteps.test.ts
@@ -0,0 +1,62 @@
+import { HogFlowAction } from '../types'
+import { getHogFlowStep } from './HogFlowSteps'
+
+const action = (type: HogFlowAction['type'], config: unknown): HogFlowAction =>
+ ({ id: type, type, name: type, description: '', config }) as HogFlowAction
+
+const previewLabels = (workflowAction: HogFlowAction): string[] =>
+ getHogFlowStep(workflowAction, {})?.previews.map(({ label }) => label) ?? []
+
+describe('HogFlow step previews', () => {
+ it.each([
+ [
+ action('trigger', {
+ type: 'event',
+ filters: { events: [{ id: '$pageview' }], properties: [{}, {}] },
+ }),
+ ['Event · $pageview · 2 filters'],
+ ],
+ [action('delay', { delay_duration: '2h' }), ['Wait for 2 hours']],
+ [action('wait_until_condition', { max_wait_duration: '1d' }), ['Up to 1d']],
+ [
+ action('wait_until_time_window', {
+ day: 'weekday',
+ time: ['09:00', '17:00'],
+ timezone: 'UTC',
+ }),
+ ['Wait until weekdays between 09:00 and 17:00 (UTC)'],
+ ],
+ [action('conditional_branch', { conditions: [{}, {}] }), ['2 conditions']],
+ [action('random_cohort_branch', { cohorts: [{}] }), ['1 cohort']],
+ [
+ action('function', {
+ template_id: 'template-webhook',
+ inputs: { method: { value: 'post' }, url: { value: 'https://hooks.example.com/path' } },
+ }),
+ ['POST hooks.example.com'],
+ ],
+ [
+ action('function_email', {
+ inputs: { email: { value: { to: { email: '[email protected]' } } } },
+ }),
+ ],
+ [action('function_sms', { inputs: { phoneNumber: { value: '+15555550123' } } }), ['To +15555550123']],
+ [action('function_push', { inputs: { title: { value: 'Welcome back' } } }), ['Welcome back']],
+ [action('exit', {}), ['End workflow']],
+ ])('derives preview labels from the action config', (workflowAction, expected) => {
+ expect(previewLabels(workflowAction)).toEqual(expected)
+ })
+
+ it('adds the number of action conditions', () => {
+ const workflowAction = {
+ ...action('function', {
+ template_id: 'template-webhook',
+ inputs: { method: { value: 'POST' }, url: { value: 'https://hooks.example.com/path' } },
+ }),
+ filters: { properties: [{}, {}] },
+ } as HogFlowAction
+
+ expect(previewLabels(workflowAction)).toEqual(['POST hooks.example.com', '2'])
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/HogFlowSteps.tsx b/products/workflows/frontend/Workflows/hogflows/steps/HogFlowSteps.tsx
index e12f7ac26b10..16d6a666a97d 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/HogFlowSteps.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/HogFlowSteps.tsx
@@ -4,18 +4,23 @@ import { useMemo } from 'react'
import {
IconBolt,
+ IconButton,
IconClock,
IconDay,
IconDecisionTree,
+ IconFilter,
IconHourglass,
IconLeave,
IconLetter,
IconNotification,
+ IconPeople,
IconPercentage,
+ IconTarget,
IconWebhooks,
} from '@posthog/icons'
import { IconTwilio } from 'lib/lemon-ui/icons'
+import { getNotificationDescription } from 'scenes/hog-functions/list/notificationDescription'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
import { HogFunctionTemplateType } from '~/types'
@@ -24,12 +29,19 @@ import { workflowLogic } from '../../workflowLogic'
import { HogFlowAction } from '../types'
import { StepConditionalBranchConfiguration } from './StepConditionalBranch'
import { StepDelayConfiguration } from './StepDelay'
+import { getDelayDescription } from './stepDelayLogic'
import { StepExitConfiguration } from './StepExit'
import { StepFunctionConfiguration } from './StepFunction'
import { StepRandomCohortBranchConfiguration } from './StepRandomCohortBranch'
import { StepTriggerConfiguration } from './StepTrigger'
import { StepWaitUntilConditionConfiguration } from './StepWaitUntilCondition'
import { StepWaitUntilTimeWindowConfiguration } from './StepWaitUntilTimeWindow'
+import { getWaitUntilTimeWindowDescription } from './stepWaitUntilTimeWindowLogic'
+
+type HogFlowStepPreview = {
+ label: string
+ icon?: JSX.Element
+}
type HogFlowStepBuilder<T extends HogFlowAction['type']> = {
type: T
@@ -38,6 +50,10 @@ type HogFlowStepBuilder<T extends HogFlowAction['type']> = {
hogFunctionTemplatesById: Record<string, HogFunctionTemplateType>
) => JSX.Element
color: (action: Extract<HogFlowAction, { type: T }>, isDarkModeOn: boolean) => string
+ getPreviews: (
+ action: Extract<HogFlowAction, { type: T }>,
+ hogFunctionTemplatesById: Record<string, HogFunctionTemplateType>
+ ) => HogFlowStepPreview[]
renderConfiguration: (node: Node<Extract<HogFlowAction, { type: T }>>) => JSX.Element
}
@@ -45,9 +61,64 @@ type HogFlowStep<T extends HogFlowAction['type']> = {
type: T
icon: JSX.Element
color: string
+ previews: HogFlowStepPreview[]
renderConfiguration: (node: Node<Extract<HogFlowAction, { type: T }>>) => JSX.Element
}
+const TRIGGER_PREVIEWS: Record<string, HogFlowStepPreview> = {
+ event: { label: 'Event', icon: <IconBolt /> },
+ webhook: { label: 'Webhook', icon: <IconWebhooks /> },
+ manual: { label: 'Manual', icon: <IconButton /> },
+ tracking_pixel: { label: 'Tracking pixel', icon: <IconTarget /> },
+ schedule: { label: 'Schedule', icon: <IconClock /> },
+ batch: { label: 'Audience', icon: <IconPeople /> },
+ 'internal-event': { label: 'Internal event', icon: <IconBolt /> },
+ 'data-warehouse-table': { label: 'Data warehouse table', icon: <IconBolt /> },
+ 'data-warehouse-view': { label: 'Data warehouse view', icon: <IconBolt /> },
+}
+
+function getTriggerPreviews(action: Extract<HogFlowAction, { type: 'trigger' }>): HogFlowStepPreview[] {
+ const config = action.config
+ const preview = TRIGGER_PREVIEWS[config.type] ?? { label: config.type, icon: <IconBolt /> }
+ if (!('filters' in config)) {
+ return [preview]
+ }
+
+ const selectedFilter =
+ config.type === 'event' || config.type === 'internal-event'
+ ? (config.filters.events?.[0] ?? ('actions' in config.filters ? config.filters.actions?.[0] : null))
+ : null
+ const selectedName = selectedFilter?.name ?? selectedFilter?.id
+ const propertyCount = config.filters.properties?.length ?? 0
+
+ return [
+ {
+ ...preview,
+ label: [
+ preview.label,
+ selectedName,
+ propertyCount ? `${propertyCount} ${propertyCount === 1 ? 'filter' : 'filters'}` : null,
+ ]
+ .filter(Boolean)
+ .join(' · '),
+ },
+ ]
+}
+
+function getFunctionPreviews(
+ action: Extract<HogFlowAction, { type: 'function' }>,
+ hogFunctionTemplatesById: Record<string, HogFunctionTemplateType>
+): HogFlowStepPreview[] {
+ const destination = getNotificationDescription({ inputs: action.config.inputs })
+ if (action.config.template_id === 'template-webhook') {
+ const method = String(action.config.inputs.method?.value || 'POST').toUpperCase()
+ return [{ label: destination ? `${method} ${destination}` : method }]
+ }
+
+ const templateName = hogFunctionTemplatesById[action.config.template_id]?.name ?? 'Destination'
+ return [{ label: destination ? `${templateName} · ${destination}` : templateName }]
+}
+
const HogFlowStepConfigs: Partial<{
[K in HogFlowAction['type']]: HogFlowStepBuilder<K>
}> = {
@@ -55,18 +126,25 @@ const HogFlowStepConfigs: Partial<{
type: 'conditional_branch',
icon: () => <IconDecisionTree />,
color: (_, isDarkModeOn) => (isDarkModeOn ? '#35C46F' : '#005841'),
+ getPreviews: (action) => [
+ {
+ label: `${action.config.conditions.length} ${action.config.conditions.length === 1 ? 'condition' : 'conditions'}`,
+ },
+ ],
renderConfiguration: (node) => <StepConditionalBranchConfiguration key={node.id} node={node} />,
},
delay: {
type: 'delay',
icon: () => <IconClock />,
color: () => '#a20031',
+ getPreviews: (action) => [{ label: getDelayDescription(action.config).replace(/\.$/, '') }],
renderConfiguration: (node) => <StepDelayConfiguration key={node.id} node={node} />,
},
exit: {
type: 'exit',
icon: () => <IconLeave />,
color: () => '#4b4b4b',
+ getPreviews: (action) => [{ label: action.config.reason || 'End workflow' }],
renderConfiguration: (node) => <StepExitConfiguration key={node.id} node={node} />,
},
@@ -74,24 +152,42 @@ const HogFlowStepConfigs: Partial<{
type: 'random_cohort_branch',
icon: () => <IconPercentage />,
color: (_, isDarkModeOn) => (isDarkModeOn ? '#D6247B' : '#9a004d'),
+ getPreviews: (action) => [
+ {
+ label: `${action.config.cohorts.length} ${action.config.cohorts.length === 1 ? 'cohort' : 'cohorts'}`,
+ },
+ ],
renderConfiguration: (node) => <StepRandomCohortBranchConfiguration key={node.id} node={node} />,
},
trigger: {
type: 'trigger',
icon: () => <IconBolt />,
color: (_, isDarkModeOn) => (isDarkModeOn ? '#35C46F' : '#005841'),
+ getPreviews: getTriggerPreviews,
renderConfiguration: (node) => <StepTriggerConfiguration key={node.id} node={node} />,
},
wait_until_condition: {
type: 'wait_until_condition',
icon: () => <IconHourglass />,
color: () => '#ffaa00',
+ getPreviews: (action) => [{ label: `Up to ${action.config.max_wait_duration}` }],
renderConfiguration: (node) => <StepWaitUntilConditionConfiguration key={node.id} node={node} />,
},
wait_until_time_window: {
type: 'wait_until_time_window',
icon: () => <IconDay />,
color: () => '#FF653F',
+ getPreviews: (action) => [
+ {
+ label: getWaitUntilTimeWindowDescription(
+ action.config.day,
+ action.config.time,
+ action.config.timezone,
+ action.config.use_person_timezone,
+ action.config.fallback_timezone
+ ).replace(/\.$/, ''),
+ },
+ ],
renderConfiguration: (node) => <StepWaitUntilTimeWindowConfiguration key={node.id} node={node} />,
},
@@ -100,18 +196,35 @@ const HogFlowStepConfigs: Partial<{
type: 'function_email',
icon: () => <IconLetter />,
color: (_, isDarkModeOn) => (isDarkModeOn ? '#2F80FA' : '#2F80FA'),
+ getPreviews: (action) => [
+ {
+ label: action.config.inputs.email?.value?.to?.email
+ ? `To ${action.config.inputs.email.value.to.email}`
+ : 'Email',
+ },
+ ],
renderConfiguration: (node) => <StepFunctionConfiguration key={node.id} node={node} />,
},
function_sms: {
type: 'function_sms',
icon: () => <IconTwilio />,
color: () => '#f22f46',
+ getPreviews: (action) => [
+ { label: action.config.inputs.phoneNumber?.value ? `To ${action.config.inputs.phoneNumber.value}` : 'SMS' },
+ ],
renderConfiguration: (node) => <StepFunctionConfiguration key={node.id} node={node} />,
},
function_push: {
type: 'function_push',
icon: () => <IconNotification />,
color: (_, isDarkModeOn) => (isDarkModeOn ? '#F8BE2A' : '#F44D01'),
+ getPreviews: (action) => [
+ {
+ label: action.config.inputs.title?.value
+ ? String(action.config.inputs.title.value)
+ : 'Push notification',
+ },
+ ],
renderConfiguration: (node) => <StepFunctionConfiguration key={node.id} node={node} />,
},
function: {
@@ -131,7 +244,7 @@ const HogFlowStepConfigs: Partial<{
const template = hogFunctionTemplatesById[action.config.template_id]
return template?.icon_url ? (
- <img className="LemonIcon rounded" src={template.icon_url} alt={template.name} />
+ <img className="LemonIcon rounded !object-contain" src={template.icon_url} alt={template.name} />
) : (
<IconBolt />
)
@@ -147,6 +260,7 @@ const HogFlowStepConfigs: Partial<{
return isDarkModeOn ? '#F8BE2A' : '#F44D01'
},
+ getPreviews: getFunctionPreviews,
renderConfiguration: (node) => <StepFunctionConfiguration key={node.id} node={node} />,
},
} as const
@@ -162,10 +276,20 @@ export function getHogFlowStep<T extends HogFlowAction['type']>(
if (!builder) {
return undefined
}
+ const conditionCount =
+ (action.filters?.events?.length ?? 0) +
+ (action.filters?.actions?.length ?? 0) +
+ (action.filters?.properties?.length ?? 0)
+ const previews = builder.getPreviews(action, hogFunctionTemplatesById)
+ if (conditionCount) {
+ previews.push({ label: String(conditionCount), icon: <IconFilter /> })
+ }
+
return {
type,
icon: builder.icon(action, hogFunctionTemplatesById),
color: builder.color(action, isDarkModeOn),
+ previews,
renderConfiguration: builder.renderConfiguration,
}
}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepConditionalBranch.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepConditionalBranch.tsx
index ede6f7d41320..ef9f895513aa 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/StepConditionalBranch.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepConditionalBranch.tsx
@@ -2,19 +2,20 @@ import { Node } from '@xyflow/react'
import { useActions, useValues } from 'kea'
import { useMemo } from 'react'
-import { IconPlus, IconX } from '@posthog/icons'
+import { IconPlus } from '@posthog/icons'
import { Spinner, Tooltip } from '@posthog/lemon-ui'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { HogFlowPropertyFilters } from '../filters/HogFlowFilters'
+import { useHogFlowBranchSelection } from '../HogFlowBranchSelection'
import { hogFlowEditorLogic } from '../hogFlowEditorLogic'
import { HogFlow, HogFlowAction } from '../types'
import { batchTriggerLogic } from './batchTriggerLogic'
import { StepSchemaErrors } from './components/StepSchemaErrors'
-import { HogFlowBranchNameInput } from './HogFlowBranchNameInput'
-import { getBranchRemovalDisabledReason, isCountableCondition, removeBranchEdge, useDebouncedNameInputs } from './utils'
+import { HogFlowBranchCard } from './HogFlowBranchCard'
+import { getBranchRemovalDisabledReason, isCountableCondition, removeBranchEdge, useNameInputs } from './utils'
type ConditionFilters = Extract<
HogFlowAction,
@@ -74,6 +75,7 @@ export function StepConditionalBranchConfiguration({
const { edgesByActionId } = useValues(hogFlowEditorLogic)
const { setWorkflowAction, setWorkflowActionEdges } = useActions(hogFlowEditorLogic)
+ const { setSelectedBranch } = useHogFlowBranchSelection()
const nodeEdges = edgesByActionId[action.id] ?? []
@@ -87,7 +89,7 @@ export function StepConditionalBranchConfiguration({
})
}
- const { localNames: localConditionNames, handleNameChange } = useDebouncedNameInputs(conditions, setConditions)
+ const { localNames: localConditionNames, handleNameChange } = useNameInputs(conditions, setConditions)
const [branchEdges, nonBranchEdges] = useMemo(() => {
const branchEdges: HogFlow['edges'] = []
@@ -125,41 +127,37 @@ export function StepConditionalBranchConfiguration({
}
const removeCondition = (index: number): void => {
+ setSelectedBranch(null)
setConditions(conditions.filter((_, i) => i !== index))
// Branch edges come first as they are sorted to show on the left
setWorkflowActionEdges(action.id, [...removeBranchEdge(branchEdges, index), ...nonBranchEdges])
}
return (
- <div>
+ <div className="flex flex-col gap-3">
<StepSchemaErrors />
- <div className="flex flex-col gap-3">
- {conditions.map((condition, index) => (
- <div key={index} className="flex flex-col gap-2 p-2 rounded border">
- <div className="flex justify-between items-center gap-2">
- <div className="flex flex-1 items-center gap-2 min-w-0">
- <HogFlowBranchNameInput
- value={localConditionNames[index]}
- onChange={(value) => handleNameChange(index, value)}
- placeholder={`Condition ${index + 1}`}
- ariaLabel={`Condition ${index + 1} name`}
+ {conditions.map((condition, index) => {
+ return (
+ <HogFlowBranchCard
+ key={index}
+ actionId={action.id}
+ index={index}
+ name={localConditionNames[index] || ''}
+ onNameChange={(value) => handleNameChange(index, value)}
+ placeholder={`Condition ${index + 1}`}
+ ariaLabel={`Condition ${index + 1} name`}
+ onRemove={() => removeCondition(index)}
+ removeDisabledReason={getBranchRemovalDisabledReason(branchEdges, index, edgesByActionId)}
+ headerAddon={
+ isCountableCondition(condition.filters) && (
+ <ConditionAudienceEstimate
+ actionId={action.id}
+ index={index}
+ filters={condition.filters}
/>
- {isCountableCondition(condition.filters) && (
- <ConditionAudienceEstimate
- actionId={action.id}
- index={index}
- filters={condition.filters}
- />
- )}
- </div>
- <LemonButton
- size="xsmall"
- icon={<IconX />}
- onClick={() => removeCondition(index)}
- disabledReason={getBranchRemovalDisabledReason(branchEdges, index, edgesByActionId)}
- />
- </div>
-
+ )
+ }
+ >
<HogFlowPropertyFilters
filtersKey={`condition-branch-condition-${action.id}-${index}`}
filters={condition.filters ?? {}}
@@ -172,11 +170,11 @@ export function StepConditionalBranchConfiguration({
}
typeKey={`workflow-trigger-${index}`}
/>
- </div>
- ))}
- </div>
+ </HogFlowBranchCard>
+ )
+ })}
- <LemonButton type="secondary" icon={<IconPlus />} onClick={() => addCondition()} className="mt-2">
+ <LemonButton type="secondary" icon={<IconPlus />} onClick={() => addCondition()}>
Add condition
</LemonButton>
</div>
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepRandomCohortBranch.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepRandomCohortBranch.tsx
index feb1d24e1a7c..7861db84b909 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/StepRandomCohortBranch.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepRandomCohortBranch.tsx
@@ -2,20 +2,16 @@ import { Node } from '@xyflow/react'
import { useActions, useValues } from 'kea'
import { useMemo, useState } from 'react'
-import { IconBalance, IconPlus, IconX } from '@posthog/icons'
+import { IconBalance, IconPlus } from '@posthog/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { useHogFlowBranchSelection } from '../HogFlowBranchSelection'
import { hogFlowEditorLogic } from '../hogFlowEditorLogic'
import { HogFlow, HogFlowAction } from '../types'
import { StepSchemaErrors } from './components/StepSchemaErrors'
-import { HogFlowBranchNameInput } from './HogFlowBranchNameInput'
-import {
- cohortPercentagesAddUp,
- normalizeCohortPercentages,
- parseCohortPercentage,
- useDebouncedNameInputs,
-} from './utils'
+import { HogFlowBranchCard } from './HogFlowBranchCard'
+import { cohortPercentagesAddUp, normalizeCohortPercentages, parseCohortPercentage, useNameInputs } from './utils'
// Print enough precision that the two figures in the imbalance warning cannot contradict each other:
// rounding a 99.996% total to hundredths would claim it adds up to 100% with 0% left over. Number()
@@ -32,6 +28,7 @@ export function StepRandomCohortBranchConfiguration({
const { edgesByActionId } = useValues(hogFlowEditorLogic)
const { setWorkflowAction, setWorkflowActionEdges } = useActions(hogFlowEditorLogic)
+ const { setSelectedBranch } = useHogFlowBranchSelection()
const nodeEdges = edgesByActionId[action.id] ?? []
@@ -44,7 +41,7 @@ export function StepRandomCohortBranchConfiguration({
})
}
- const { localNames: localCohortNames, handleNameChange } = useDebouncedNameInputs(cohorts, setCohorts)
+ const { localNames: localCohortNames, handleNameChange } = useNameInputs(cohorts, setCohorts)
const [branchEdges, nonBranchEdges] = useMemo(() => {
const branchEdges: HogFlow['edges'] = []
@@ -81,6 +78,7 @@ export function StepRandomCohortBranchConfiguration({
}
const removeCohort = (index: number): void => {
+ setSelectedBranch(null)
const newBranchEdges = branchEdges.filter((_, i) => i !== index).map((edge, i) => ({ ...edge, index: i }))
setCohorts(cohorts.filter((_, i) => i !== index))
setWorkflowActionEdges(action.id, [...newBranchEdges, ...nonBranchEdges])
@@ -125,33 +123,34 @@ export function StepRandomCohortBranchConfiguration({
<div className="flex flex-col gap-3">
<StepSchemaErrors />
- {cohorts.map((cohort, index) => (
- <div key={index} className="flex flex-col gap-2 p-2 rounded border">
- <div className="flex justify-between items-center gap-2">
- <HogFlowBranchNameInput
- value={localCohortNames[index]}
- onChange={(value) => handleNameChange(index, value)}
- placeholder={`Cohort ${index + 1}`}
- ariaLabel={`Cohort ${index + 1} name`}
- />
- <LemonButton size="xsmall" icon={<IconX />} onClick={() => removeCohort(index)} />
- </div>
-
- <div className="flex items-center gap-2">
- <input
- type="number"
- min="0"
- max="100"
- step="any"
- value={percentageDrafts[index] ?? String(cohort.percentage)}
- onChange={(e) => updateCohortPercentage(index, e.target.value)}
- onBlur={() => clearPercentageDraft(index)}
- className="w-20 px-2 py-1 border rounded"
- />
- <span>%</span>
- </div>
- </div>
- ))}
+ {cohorts.map((cohort, index) => {
+ return (
+ <HogFlowBranchCard
+ key={index}
+ actionId={action.id}
+ index={index}
+ name={localCohortNames[index] || ''}
+ onNameChange={(value) => handleNameChange(index, value)}
+ placeholder={`Cohort ${index + 1}`}
+ ariaLabel={`Cohort ${index + 1} name`}
+ onRemove={() => removeCohort(index)}
+ >
+ <div className="flex items-center gap-2">
+ <input
+ type="number"
+ min="0"
+ max="100"
+ step="any"
+ value={percentageDrafts[index] ?? String(cohort.percentage)}
+ onChange={(e) => updateCohortPercentage(index, e.target.value)}
+ onBlur={() => clearPercentageDraft(index)}
+ className="w-20 px-2 py-1 border rounded"
+ />
+ <span>%</span>
+ </div>
+ </HogFlowBranchCard>
+ )
+ })}
{cohorts.length > 0 && !isBalanced && (
<div className="text-sm text-orange-600">
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/StepView.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/StepView.tsx
index b40e32211e69..f35a39bbd1dd 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/components/StepView.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/StepView.tsx
@@ -83,7 +83,7 @@ export function StepView({ action }: { action: HogFlowAction }): JSX.Element {
color: Step?.color || 'var(--text-secondary)',
icon: Step?.icon,
}
- }, [action, isSelected, Step])
+ }, [isSelected, Step])
const hasValidationError = actionValidationErrorsById[action.id]?.valid === false
const hasValidationWarning = Object.keys(actionValidationErrorsById[action.id]?.warnings ?? {}).length > 0
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/StepViewMetrics.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/StepViewMetrics.tsx
index 05d28c1b5471..2dcb6887d02b 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/components/StepViewMetrics.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/StepViewMetrics.tsx
@@ -20,7 +20,7 @@ export function StepViewMetrics({ action }: { action: HogFlowAction }): JSX.Elem
if (actionMetricsByIdLoading) {
return (
- <div className="flex items-center gap-1 h-2 px-1">
+ <div className="flex h-2 items-center gap-1 px-1">
<LemonSkeleton className="w-full h-[6px]" />
<LemonSkeleton className="w-full h-[6px]" />
<LemonSkeleton className="w-full h-[6px]" />
@@ -29,12 +29,7 @@ export function StepViewMetrics({ action }: { action: HogFlowAction }): JSX.Elem
}
return (
- <div
- className="flex flex-row items-center font-mono"
- style={{
- fontSize: 6,
- }}
- >
+ <div className="flex flex-row items-center text-[6px] font-mono">
<Tooltip title="Successful runs of this action">
<div className="flex-1 px-1 text-success">
<IconCheck /> {humanFriendlyLargeNumber(metrics.succeeded)}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/utils.ts b/products/workflows/frontend/Workflows/hogflows/steps/utils.ts
index a74beebe289c..bf7f22baafdb 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/utils.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/utils.ts
@@ -118,10 +118,9 @@ export function updateItemWithOptionalName<T>(
})
}
-export function useDebouncedNameInputs<T extends { name?: string }>(
+export function useNameInputs<T extends { name?: string }>(
items: T[],
- updateItems: (items: T[]) => void,
- debounceDelay: number = 300
+ updateItems: (items: T[]) => void
): {
localNames: (string | undefined)[]
handleNameChange: (index: number, value: string | undefined) => void
@@ -133,19 +132,13 @@ export function useDebouncedNameInputs<T extends { name?: string }>(
setLocalNames((items ?? []).map((item) => item.name))
}, [items?.length, items]) // Only update when number of items changes
- // Debounced function to update items
- const debouncedUpdate = useDebouncedCallback((index: number, value: string | undefined) => {
- updateItems(updateItemWithOptionalName(items, index, value))
- }, debounceDelay)
-
const handleNameChange = (index: number, value: string | undefined): void => {
// Update local state immediately for responsive typing
const newNames = [...localNames]
newNames[index] = value
setLocalNames(newNames)
- // Debounced update to persist the name
- debouncedUpdate(index, value)
+ updateItems(updateItemWithOptionalName(items, index, value))
}
return {
diff --git a/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeBranchIndicator.tsx b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeBranchIndicator.tsx
new file mode 100644
index 000000000000..f166b18fdf6e
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeBranchIndicator.tsx
@@ -0,0 +1,11 @@
+import { cn } from 'lib/ui/quill'
+
+export function HogFlowTreeBranchIndicator({ color, className }: { color: string; className?: string }): JSX.Element {
+ return (
+ <span
+ aria-hidden="true"
+ className={cn('pointer-events-none absolute -start-4 w-0.5 rounded-full', className)}
+ style={{ backgroundColor: color }}
+ />
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeDropzone.tsx b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeDropzone.tsx
new file mode 100644
index 000000000000..7480256fc3b5
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeDropzone.tsx
@@ -0,0 +1,173 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+import type { DragEvent } from 'react'
+
+import { IconPlus } from '@posthog/icons'
+
+import { Button, cn, Popover, PopoverContent, PopoverTrigger } from 'lib/ui/quill'
+
+import { type CreateActionType, hogFlowEditorLogic } from '../hogFlowEditorLogic'
+import { HogFlowEditorPanelBuild } from '../panel/HogFlowEditorPanelBuild'
+import type { HogFlowEdge } from '../types'
+import { computeMoveTreeBranchEdges, isBranchingAction } from './workflowTree'
+
+export function HogFlowTreeDropzone({
+ active,
+ draggedActionId,
+ draggedActionIdRef,
+ onDragEnd,
+ edge,
+ isBranchJoin = false,
+ joinEdges,
+ showConnector = true,
+ compact = false,
+}: {
+ active: boolean
+ draggedActionId: string | null
+ draggedActionIdRef: { current: string | null }
+ onDragEnd: () => void
+ edge: HogFlowEdge
+ isBranchJoin?: boolean
+ joinEdges?: HogFlowEdge[]
+ showConnector?: boolean
+ compact?: boolean
+}): JSX.Element {
+ const { workflow } = useValues(hogFlowEditorLogic)
+ const {
+ moveNodeToEdge,
+ onDragOver,
+ onDrop,
+ setHighlightedDropzoneNodeId,
+ setNodeToBeAdded,
+ setSelectedNodeId,
+ setWorkflowInfo,
+ } = useActions(hogFlowEditorLogic)
+ const [highlighted, setHighlighted] = useState(false)
+ const [pickerOpen, setPickerOpen] = useState(false)
+ const isAdjacentToDraggedAction = draggedActionId === edge.to || (!isBranchJoin && draggedActionId === edge.from)
+ const handleDragOver = (event: DragEvent<HTMLElement>): void => {
+ setHighlighted(true)
+ onDragOver(event)
+ }
+ const handleDrop = (event: DragEvent<HTMLElement>): void => {
+ setHighlighted(false)
+ const draggedActionId = draggedActionIdRef.current
+ if (draggedActionId) {
+ if (edge.to === draggedActionId || (!isBranchJoin && edge.from === draggedActionId)) {
+ onDragEnd()
+ return
+ }
+ const action = workflow.actions.find((action) => action.id === draggedActionId)
+ if (!action || !isBranchingAction(action)) {
+ moveNodeToEdge(draggedActionId, edge, isBranchJoin, joinEdges)
+ } else {
+ const newEdges = computeMoveTreeBranchEdges(workflow, draggedActionId, edge, isBranchJoin, joinEdges)
+ if (newEdges) {
+ setWorkflowInfo({ actions: workflow.actions, edges: newEdges })
+ setSelectedNodeId(draggedActionId)
+ }
+ }
+ onDragEnd()
+ } else if (isBranchJoin) {
+ if (joinEdges) {
+ onDrop(event, edge, joinEdges)
+ } else {
+ setHighlightedDropzoneNodeId(`dropzone_target_${edge.to}_branch_join`)
+ onDrop(event)
+ }
+ } else {
+ onDrop(event, edge)
+ }
+ }
+ const handleInsertAction = (action: CreateActionType): void => {
+ setPickerOpen(false)
+ setNodeToBeAdded(action)
+
+ if (isBranchJoin && !joinEdges) {
+ setHighlightedDropzoneNodeId(`dropzone_target_${edge.to}_branch_join`)
+ onDrop()
+ } else {
+ onDrop(undefined, edge, joinEdges)
+ }
+ }
+ return (
+ <div
+ className={cn('group relative flex w-full items-center justify-center', compact ? 'h-2' : 'h-4')}
+ data-workflow-tree-dropzone-candidate
+ data-workflow-tree-dropzone-disabled={isAdjacentToDraggedAction || undefined}
+ >
+ <div
+ className={cn(
+ 'absolute inset-0 flex items-center justify-center',
+ active ? 'hidden' : 'group-data-[workflow-tree-dragging=true]/tree:hidden'
+ )}
+ >
+ <div
+ aria-hidden="true"
+ className={cn(
+ 'absolute inset-x-0 top-1/2 h-px -translate-y-1/2 bg-muted-foreground/50 opacity-0 transition-opacity',
+ (pickerOpen || !showConnector) && 'opacity-100',
+ showConnector && 'group-hover:opacity-100'
+ )}
+ />
+ <Popover open={pickerOpen} onOpenChange={setPickerOpen}>
+ <PopoverTrigger
+ render={
+ <Button
+ type="button"
+ variant="outline"
+ size="icon-sm"
+ className={cn(
+ 'absolute -right-2 top-1/2 z-10 !size-4 -translate-y-1/2 border-0 bg-transparent p-0 hover:bg-transparent focus-visible:outline-none'
+ )}
+ aria-label="Insert step here"
+ data-attr="workflow-tree-insert-action"
+ />
+ }
+ >
+ <span
+ className={cn(
+ 'flex size-4 items-center justify-center rounded-full border border-primary bg-primary text-primary-foreground opacity-0 transition-[opacity,box-shadow] group-hover:opacity-100 group-hover:shadow-sm',
+ pickerOpen && 'opacity-100 shadow-sm'
+ )}
+ >
+ <IconPlus className="size-3" />
+ </span>
+ </PopoverTrigger>
+ <PopoverContent side="bottom" align="end" className="w-72 max-h-96 overflow-hidden p-0">
+ <HogFlowEditorPanelBuild className="max-h-96 p-2" onActionSelect={handleInsertAction} />
+ </PopoverContent>
+ </Popover>
+ </div>
+ <div
+ className={cn(
+ 'absolute -inset-y-3 inset-x-0 z-20 items-center',
+ isAdjacentToDraggedAction
+ ? 'hidden'
+ : 'hidden group-data-[workflow-tree-dropzone-closest=true]:flex'
+ )}
+ onDragOver={handleDragOver}
+ onDragLeave={() => setHighlighted(false)}
+ onDrop={handleDrop}
+ data-attr="workflow-tree-dropzone"
+ >
+ <div
+ aria-hidden="true"
+ className={cn(
+ 'absolute inset-x-0 top-1/2 h-0.5 -translate-y-1/2 bg-primary opacity-30 transition-opacity duration-150 group-data-[workflow-tree-dropzone-closest=true]:opacity-100',
+ highlighted && 'opacity-100'
+ )}
+ />
+ <span
+ aria-hidden="true"
+ className={cn(
+ 'absolute -right-2 top-1/2 flex size-4 -translate-y-1/2 items-center justify-center rounded-full border border-primary bg-primary text-primary-foreground opacity-30 transition-[opacity,transform,box-shadow] duration-150 group-data-[workflow-tree-dropzone-closest=true]:scale-110 group-data-[workflow-tree-dropzone-closest=true]:opacity-100 group-data-[workflow-tree-dropzone-closest=true]:shadow-sm',
+ highlighted && 'scale-110 opacity-100 shadow-sm'
+ )}
+ >
+ <IconPlus className="size-3" />
+ </span>
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeEditor.stories.tsx b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeEditor.stories.tsx
new file mode 100644
index 000000000000..32d09afa4db6
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeEditor.stories.tsx
@@ -0,0 +1,367 @@
+import type { Meta, StoryFn } from '@storybook/react'
+import { BindLogic, useActions } from 'kea'
+import { useEffect, type ReactNode } from 'react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { lemonBannerLogic } from 'lib/lemon-ui/LemonBanner/lemonBannerLogic'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import { Workflow } from '../../Workflow'
+import { NEW_WORKFLOW, workflowLogic } from '../../workflowLogic'
+import type { HogFlow, HogFlowAction } from '../types'
+import { EXAMPLE_WORKFLOWS } from './exampleWorkflows'
+import { HogFlowTreeEditor } from './HogFlowTreeEditor'
+
+const COMPLEX_WORKFLOW_ID = 'storybook-complex-workflow'
+const FEATURE_PREVIEW_DISMISS_KEY = 'workflow-tree-feature-preview'
+
+function ResetFeaturePreviewDismissal({ children, storyId }: { children: ReactNode; storyId: string }): JSX.Element {
+ const { resetDismissKey } = useActions(lemonBannerLogic({ dismissKey: FEATURE_PREVIEW_DISMISS_KEY }))
+
+ useEffect(() => {
+ resetDismissKey()
+ }, [resetDismissKey, storyId])
+
+ return <>{children}</>
+}
+
+const COMPLEX_WORKFLOW: HogFlow = {
+ id: COMPLEX_WORKFLOW_ID,
+ team_id: 1,
+ version: 7,
+ name: 'Customer onboarding and retention',
+ description: 'Routes new accounts by stage and follows up when activation stalls.',
+ status: 'draft',
+ trigger: {
+ type: 'event',
+ filters: {
+ events: [{ id: 'account_created', name: 'Account created', type: 'events' }],
+ properties: [],
+ actions: [],
+ },
+ },
+ conversion: { window_minutes: 10080, filters: [] },
+ exit_condition: 'exit_only_at_end',
+ variables: [
+ { key: 'account_stage', type: 'string', label: 'Account stage', default: 'new' },
+ { key: 'follow_up_count', type: 'number', label: 'Follow-up count', default: 0 },
+ ],
+ actions: [
+ {
+ id: 'trigger',
+ type: 'trigger',
+ name: 'Account created',
+ description: 'Starts when a new account is created.',
+ config: {
+ type: 'event',
+ filters: {
+ events: [{ id: 'account_created', name: 'Account created', type: 'events' }],
+ properties: [],
+ actions: [],
+ },
+ },
+ },
+ {
+ id: 'route-by-stage',
+ type: 'conditional_branch',
+ name: 'Route by customer stage',
+ description: 'Choose a path based on the current account stage.',
+ config: {
+ conditions: [
+ {
+ name: 'Paid account',
+ filters: {
+ properties: [{ key: 'account_stage', value: ['paid'], operator: 'exact', type: 'person' }],
+ },
+ },
+ {
+ name: 'Trial account',
+ filters: {
+ properties: [{ key: 'account_stage', value: ['trial'], operator: 'exact', type: 'person' }],
+ },
+ },
+ {
+ name: 'At-risk account',
+ filters: {
+ properties: [
+ { key: 'account_stage', value: ['at_risk'], operator: 'exact', type: 'person' },
+ ],
+ },
+ },
+ ],
+ },
+ },
+ {
+ id: 'notify-account-team',
+ type: 'function',
+ name: 'Notify account team',
+ description: 'Send the paid account to the account team.',
+ config: {
+ template_id: 'template-slack',
+ inputs: {
+ slack_workspace: { value: 1 },
+ channel: { value: '#account-updates' },
+ text: { value: 'A paid account was created for {person.properties.email}.', templating: 'hog' },
+ },
+ },
+ },
+ {
+ id: 'wait-for-business-hours',
+ type: 'wait_until_time_window',
+ name: 'Wait for business hours',
+ description: 'Continue on a weekday between 09:00 and 17:00 UTC.',
+ config: { timezone: 'UTC', day: 'weekday', time: ['09:00', '17:00'] },
+ },
+ {
+ id: 'choose-onboarding-path',
+ type: 'random_cohort_branch',
+ name: 'Choose onboarding path',
+ description: 'Split trial accounts between two onboarding paths.',
+ config: {
+ cohorts: [
+ { name: 'Guided onboarding', percentage: 60 },
+ { name: 'Self-serve onboarding', percentage: 30 },
+ ],
+ },
+ },
+ {
+ id: 'create-onboarding-task',
+ type: 'function',
+ name: 'Create onboarding task',
+ description: 'Create a task for the guided onboarding path.',
+ config: {
+ template_id: 'template-webhook',
+ inputs: {
+ url: { value: 'https://example.com/hooks/onboarding' },
+ method: { value: 'POST' },
+ body: { value: { account_id: '{person.id}', path: 'guided' }, templating: 'hog' },
+ },
+ },
+ },
+ {
+ id: 'wait-one-day',
+ type: 'delay',
+ name: 'Wait one day',
+ description: 'Give the self-serve path time to activate.',
+ config: { delay_duration: '1d' },
+ },
+ {
+ id: 'send-self-serve-reminder',
+ type: 'function',
+ name: 'Send self-serve reminder',
+ description: 'Request a reminder from the messaging service.',
+ config: {
+ template_id: 'template-webhook',
+ inputs: {
+ url: { value: 'https://example.com/hooks/reminders' },
+ method: { value: 'POST' },
+ body: { value: { account_id: '{person.id}', reminder: 'activation' }, templating: 'hog' },
+ },
+ },
+ },
+ {
+ id: 'hold-control-group',
+ type: 'delay',
+ name: 'Hold control group',
+ description: 'Wait before measuring the control group.',
+ config: { delay_duration: '3d' },
+ },
+ {
+ id: 'wait-for-activation',
+ type: 'wait_until_condition',
+ name: 'Wait for activation',
+ description: 'Continue when the account activates or after seven days.',
+ config: {
+ condition: {
+ name: 'Product activated',
+ filters: { events: [{ id: 'product_activated', name: 'Product activated', type: 'events' }] },
+ },
+ max_wait_duration: '7d',
+ },
+ },
+ {
+ id: 'share-activation',
+ type: 'function',
+ name: 'Share activation',
+ description: 'Notify the retention team that activation completed.',
+ config: {
+ template_id: 'template-slack',
+ inputs: {
+ slack_workspace: { value: 1 },
+ channel: { value: '#retention-updates' },
+ text: { value: 'Account {person.id} activated.', templating: 'hog' },
+ },
+ },
+ },
+ {
+ id: 'create-follow-up-task',
+ type: 'function',
+ name: 'Create follow-up task',
+ description: 'Create a task when activation does not complete.',
+ config: {
+ template_id: 'template-webhook',
+ inputs: {
+ url: { value: 'https://example.com/hooks/follow-up' },
+ method: { value: 'POST' },
+ body: { value: { account_id: '{person.id}', reason: 'activation_timeout' }, templating: 'hog' },
+ },
+ },
+ },
+ {
+ id: 'send-activation-outcome',
+ type: 'function',
+ name: 'Send activation outcome',
+ description: 'Record whether the account activated or needs a follow-up.',
+ config: {
+ template_id: 'template-webhook',
+ inputs: {
+ url: { value: 'https://example.com/hooks/activation-outcomes' },
+ method: { value: 'POST' },
+ body: { value: { account_id: '{person.id}' }, templating: 'hog' },
+ },
+ },
+ },
+ {
+ id: 'record-self-serve-account',
+ type: 'function',
+ name: 'Record self-serve account',
+ description: 'Record accounts that do not match a managed stage.',
+ config: {
+ template_id: 'template-webhook',
+ inputs: {
+ url: { value: 'https://example.com/hooks/self-serve' },
+ method: { value: 'POST' },
+ body: { value: { account_id: '{person.id}', path: 'self_serve' }, templating: 'hog' },
+ },
+ },
+ },
+ {
+ id: 'pause-before-summary',
+ type: 'delay',
+ name: 'Pause before summary',
+ description: 'Wait 30 seconds before recording the final outcome.',
+ config: { delay_duration: '30s' },
+ },
+ {
+ id: 'record-workflow-outcome',
+ type: 'function',
+ name: 'Record workflow outcome',
+ description: 'Send the completed route to the example endpoint.',
+ config: {
+ template_id: 'template-webhook',
+ inputs: {
+ url: { value: 'https://example.com/hooks/outcomes' },
+ method: { value: 'POST' },
+ body: { value: { account_id: '{person.id}', status: 'complete' }, templating: 'hog' },
+ },
+ },
+ },
+ {
+ id: 'exit',
+ type: 'exit',
+ name: 'End workflow',
+ description: 'The account has completed its onboarding route.',
+ config: { reason: 'Onboarding route completed' },
+ },
+ ] as HogFlowAction[],
+ edges: [
+ { from: 'trigger', to: 'route-by-stage', type: 'continue' },
+ { from: 'route-by-stage', to: 'notify-account-team', type: 'branch', index: 0 },
+ { from: 'notify-account-team', to: 'wait-for-business-hours', type: 'continue' },
+ { from: 'wait-for-business-hours', to: 'pause-before-summary', type: 'continue' },
+ { from: 'route-by-stage', to: 'choose-onboarding-path', type: 'branch', index: 1 },
+ { from: 'choose-onboarding-path', to: 'create-onboarding-task', type: 'branch', index: 0 },
+ { from: 'create-onboarding-task', to: 'pause-before-summary', type: 'continue' },
+ { from: 'choose-onboarding-path', to: 'wait-one-day', type: 'branch', index: 1 },
+ { from: 'wait-one-day', to: 'send-self-serve-reminder', type: 'continue' },
+ { from: 'send-self-serve-reminder', to: 'pause-before-summary', type: 'continue' },
+ { from: 'choose-onboarding-path', to: 'hold-control-group', type: 'continue' },
+ { from: 'hold-control-group', to: 'pause-before-summary', type: 'continue' },
+ { from: 'route-by-stage', to: 'wait-for-activation', type: 'branch', index: 2 },
+ { from: 'wait-for-activation', to: 'share-activation', type: 'branch', index: 0 },
+ { from: 'share-activation', to: 'send-activation-outcome', type: 'continue' },
+ { from: 'wait-for-activation', to: 'create-follow-up-task', type: 'continue' },
+ { from: 'create-follow-up-task', to: 'send-activation-outcome', type: 'continue' },
+ { from: 'send-activation-outcome', to: 'pause-before-summary', type: 'continue' },
+ { from: 'route-by-stage', to: 'record-self-serve-account', type: 'continue' },
+ { from: 'record-self-serve-account', to: 'pause-before-summary', type: 'continue' },
+ { from: 'pause-before-summary', to: 'record-workflow-outcome', type: 'continue' },
+ { from: 'record-workflow-outcome', to: 'exit', type: 'continue' },
+ ],
+ created_at: '2026-09-04T12:00:00.000Z',
+ updated_at: '2026-09-04T12:00:00.000Z',
+}
+
+const meta: Meta<typeof HogFlowTreeEditor> = {
+ title: 'Products/Workflows/Editor/Tree',
+ component: HogFlowTreeEditor,
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.WORKFLOWS_LINEAR_VIEW],
+ layout: 'fullscreen',
+ mockDate: '2026-09-04 12:00:00',
+ testOptions: {
+ waitForLoadersToDisappear: true,
+ waitForSelector: '[data-attr=workflow-tree-editor]',
+ viewport: { width: 1600, height: 1000 },
+ },
+ },
+ decorators: [
+ (Story, context) => (
+ <ResetFeaturePreviewDismissal storyId={context.id}>
+ <Story />
+ </ResetFeaturePreviewDismissal>
+ ),
+ mswDecorator({
+ get: {
+ '/api/environments/:team_id/hog_flows/:id/': ({ params }) => [
+ 200,
+ PICKABLE_WORKFLOWS[String(params.id)] ?? COMPLEX_WORKFLOW,
+ ],
+ '/api/environments/:team_id/messaging_categories': { count: 0, results: [] },
+ },
+ patch: {
+ '/api/environments/:team_id/hog_flows/:id/': async ({ request, params }) => [
+ 200,
+ {
+ ...(PICKABLE_WORKFLOWS[String(params.id)] ?? COMPLEX_WORKFLOW),
+ ...((await request.json()) as Partial<HogFlow>),
+ updated_at: '2026-09-04T12:01:00.000Z',
+ },
+ ],
+ },
+ post: {
+ '/api/environments/:team_id/hog_flows/user_blast_radius/': {
+ affected: 240,
+ total: 1200,
+ limit: 100000,
+ dedupe_key: null,
+ confirm_token: 'storybook-confirm-token',
+ },
+ },
+ }),
+ ],
+}
+export default meta
+
+const PICKABLE_WORKFLOWS: Record<string, HogFlow> = {
+ new: NEW_WORKFLOW,
+ [COMPLEX_WORKFLOW_ID]: COMPLEX_WORKFLOW,
+ ...EXAMPLE_WORKFLOWS,
+}
+
+const InteractiveWorkflow = ({ id, className }: { id: string; className?: string }): JSX.Element => (
+ <BindLogic logic={workflowLogic} props={{ id }}>
+ <div className={`h-screen ${className ?? ''} [&>div]:!h-full [&>div]:!max-h-none`}>
+ <Workflow id={id} />
+ </div>
+ </BindLogic>
+)
+
+export const CustomerOnboardingAndRetention: StoryFn = () => <InteractiveWorkflow id={COMPLEX_WORKFLOW_ID} />
+export const NewWorkflow: StoryFn = () => <InteractiveWorkflow id="new" />
+export const NarrowWorkflow: StoryFn = () => <InteractiveWorkflow id="new" className="w-[40rem] max-w-full" />
+export const SupportSlaRouting: StoryFn = () => <InteractiveWorkflow id="example-support-sla-routing" />
+export const RenewalWindowAlerts: StoryFn = () => <InteractiveWorkflow id="example-renewal-window-alerts" />
+export const PendingTicketCleanup: StoryFn = () => <InteractiveWorkflow id="example-pending-ticket-cleanup" />
+export const AddOnPromotionEmails: StoryFn = () => <InteractiveWorkflow id="example-add-on-promotion-emails" />
diff --git a/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeEditor.tsx b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeEditor.tsx
new file mode 100644
index 000000000000..58d60472263b
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeEditor.tsx
@@ -0,0 +1,164 @@
+import { useValues } from 'kea'
+import { useEffect, useMemo, useRef, useState } from 'react'
+import type { DragEvent } from 'react'
+
+import { ScrollArea, ScrollBar } from 'lib/ui/quill'
+
+import { setHogFlowDragImage } from '../dragPreview'
+import { hogFlowEditorLogic } from '../hogFlowEditorLogic'
+import { HogFlowTreeFeaturePreview } from './HogFlowTreeFeaturePreview'
+import { HogFlowTreeNode } from './HogFlowTreeNode'
+import { buildWorkflowTree } from './workflowTree'
+
+export function HogFlowTreeEditor(): JSX.Element {
+ const { nodeToBeAdded, workflow } = useValues(hogFlowEditorLogic)
+ const treeRef = useRef<HTMLDivElement>(null)
+ const draggedActionIdRef = useRef<string | null>(null)
+ const [draggedActionId, setDraggedActionId] = useState<string | null>(null)
+ const draggedStepRef = useRef<HTMLElement | null>(null)
+ const closestDropzoneRef = useRef<HTMLElement | null>(null)
+ const dragStartYRef = useRef<number | null>(null)
+ const tree = useMemo(() => buildWorkflowTree(workflow), [workflow])
+ const activeDropzones = !!nodeToBeAdded
+
+ const clearClosestDropzone = (): void => {
+ closestDropzoneRef.current?.removeAttribute('data-workflow-tree-dropzone-closest')
+ closestDropzoneRef.current = null
+ }
+
+ useEffect(() => {
+ if (!activeDropzones) {
+ clearClosestDropzone()
+ }
+ }, [activeDropzones])
+
+ const onDragStart = (
+ event: DragEvent<HTMLDivElement>,
+ actionId: string,
+ dragPreviewElement: HTMLDivElement | null
+ ): void => {
+ event.dataTransfer.effectAllowed = 'move'
+ event.dataTransfer.setData('text/plain', actionId)
+ dragStartYRef.current = event.clientY
+ const step = event.currentTarget.closest('[data-attr="workflow-tree-step"]')
+ if (step instanceof HTMLElement && typeof event.dataTransfer.setDragImage === 'function') {
+ setHogFlowDragImage(event.dataTransfer, dragPreviewElement)
+ step.dataset.workflowTreeDragging = 'true'
+ draggedStepRef.current = step
+ }
+ draggedActionIdRef.current = actionId
+ setDraggedActionId(actionId)
+ treeRef.current?.setAttribute('data-workflow-tree-dragging', 'true')
+ }
+
+ const onTreeDragOver = (event: DragEvent<HTMLDivElement>): void => {
+ if (!draggedActionIdRef.current && !activeDropzones) {
+ return
+ }
+
+ event.preventDefault()
+ if (dragStartYRef.current !== null && Math.abs(event.clientY - dragStartYRef.current) < 16) {
+ clearClosestDropzone()
+ return
+ }
+
+ const candidates = Array.from(
+ treeRef.current?.querySelectorAll<HTMLElement>('[data-workflow-tree-dropzone-candidate]') ?? []
+ ).filter((candidate) => {
+ if (candidate.dataset.workflowTreeDropzoneDisabled === 'true') {
+ return false
+ }
+
+ let ancestor: HTMLElement | null = candidate
+ while (ancestor) {
+ if (ancestor.dataset.workflowTreeBranchContent === draggedActionIdRef.current) {
+ return false
+ }
+ ancestor = ancestor.parentElement
+ }
+ return true
+ })
+ const closestDropzone = candidates.reduce<HTMLElement | null>((closest, candidate) => {
+ if (!closest) {
+ return candidate
+ }
+ const closestCenter = closest.getBoundingClientRect().top + closest.getBoundingClientRect().height / 2
+ const candidateCenter = candidate.getBoundingClientRect().top + candidate.getBoundingClientRect().height / 2
+ return Math.abs(event.clientY - candidateCenter) < Math.abs(event.clientY - closestCenter)
+ ? candidate
+ : closest
+ }, null)
+
+ if (closestDropzone !== closestDropzoneRef.current) {
+ clearClosestDropzone()
+ closestDropzone?.setAttribute('data-workflow-tree-dropzone-closest', 'true')
+ closestDropzoneRef.current = closestDropzone
+ }
+ }
+
+ const onTreeDropCapture = (event: DragEvent<HTMLDivElement>): void => {
+ const nativeEvent = event.nativeEvent as globalThis.DragEvent & { workflowTreeNearestDrop?: boolean }
+ if (nativeEvent.workflowTreeNearestDrop) {
+ return
+ }
+
+ event.preventDefault()
+ event.stopPropagation()
+ const closestDropzone = closestDropzoneRef.current
+ if (!closestDropzone) {
+ onDragEnd()
+ return
+ }
+
+ const dropEvent = new window.DragEvent('drop', {
+ bubbles: true,
+ cancelable: true,
+ clientX: event.clientX,
+ clientY: event.clientY,
+ dataTransfer: event.dataTransfer,
+ }) as globalThis.DragEvent & { workflowTreeNearestDrop?: boolean }
+ dropEvent.workflowTreeNearestDrop = true
+ closestDropzone.querySelector<HTMLElement>('[data-attr="workflow-tree-dropzone"]')?.dispatchEvent(dropEvent)
+ }
+
+ const onDragEnd = (): void => {
+ clearClosestDropzone()
+ dragStartYRef.current = null
+ treeRef.current?.removeAttribute('data-workflow-tree-dragging')
+ draggedStepRef.current?.removeAttribute('data-workflow-tree-dragging')
+ draggedStepRef.current = null
+ draggedActionIdRef.current = null
+ setDraggedActionId(null)
+ }
+
+ return (
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">
+ <HogFlowTreeFeaturePreview />
+ <ScrollArea
+ className="min-h-0 min-w-0 flex-1 bg-background @max-[48rem]/workflow-editor:min-h-80 @max-[48rem]/workflow-editor:shrink-0"
+ data-quill
+ data-attr="workflow-tree-editor"
+ >
+ <div
+ ref={treeRef}
+ className="group/tree mx-auto flex w-full max-w-3xl flex-col p-4"
+ onDragOver={onTreeDragOver}
+ onDropCapture={onTreeDropCapture}
+ >
+ {tree.nodes.map((node) => (
+ <HogFlowTreeNode
+ key={node.action.id}
+ node={node}
+ activeDropzones={activeDropzones}
+ draggedActionId={draggedActionId}
+ draggedActionIdRef={draggedActionIdRef}
+ onDragStart={onDragStart}
+ onDragEnd={onDragEnd}
+ />
+ ))}
+ </div>
+ <ScrollBar orientation="vertical" />
+ </ScrollArea>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeFeaturePreview.tsx b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeFeaturePreview.tsx
new file mode 100644
index 000000000000..3085956f0273
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeFeaturePreview.tsx
@@ -0,0 +1,134 @@
+import posthog from 'posthog-js'
+import { useEffect, useState } from 'react'
+
+import { IconThumbsDown, IconThumbsDownFilled, IconThumbsUp, IconThumbsUpFilled } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonModal, LemonTextArea } from '@posthog/lemon-ui'
+
+import { uuid } from 'lib/utils/dom'
+import { getSurveyIdBasedResponseKey, getSurveyResponseKey } from 'scenes/surveys/utils'
+
+import { SurveyEventName, SurveyEventProperties } from '~/types'
+
+const SURVEY_ID = '01a0856f-7ae3-0000-eef6-fec0a2e1b78f'
+const RATING_QUESTION_ID = 'a899da8d-092a-41ce-ab9b-8e18b2c7cfd8'
+const FEEDBACK_QUESTION_ID = 'acbad4b5-52c2-4a56-a280-5d2ddd064612'
+
+type WorkflowTreeFeedbackRating = 'useful' | 'needs improvement'
+
+const surveyResponses: Record<WorkflowTreeFeedbackRating, string> = {
+ useful: 'Useful',
+ 'needs improvement': 'Needs improvement',
+}
+
+export function HogFlowTreeFeaturePreview(): JSX.Element {
+ const [rating, setRating] = useState<WorkflowTreeFeedbackRating | null>(null)
+ const [submissionId, setSubmissionId] = useState<string | null>(null)
+ const [feedbackText, setFeedbackText] = useState('')
+ const [feedbackOpen, setFeedbackOpen] = useState(false)
+
+ useEffect(() => {
+ posthog.capture(SurveyEventName.SHOWN, {
+ [SurveyEventProperties.SURVEY_ID]: SURVEY_ID,
+ feedback_surface: 'workflow_tree_editor',
+ })
+ }, [])
+
+ const ratePreview = (nextRating: WorkflowTreeFeedbackRating): void => {
+ if (rating) {
+ return
+ }
+
+ const nextSubmissionId = uuid()
+ const response = surveyResponses[nextRating]
+
+ setRating(nextRating)
+ setSubmissionId(nextSubmissionId)
+ setFeedbackOpen(true)
+ posthog.capture(SurveyEventName.SENT, {
+ [SurveyEventProperties.SURVEY_ID]: SURVEY_ID,
+ [SurveyEventProperties.SURVEY_SUBMISSION_ID]: nextSubmissionId,
+ [SurveyEventProperties.SURVEY_COMPLETED]: false,
+ [getSurveyResponseKey(0)]: response,
+ [getSurveyIdBasedResponseKey(RATING_QUESTION_ID)]: response,
+ feedback_surface: 'workflow_tree_editor',
+ })
+ }
+
+ const submitFeedback = (): void => {
+ const feedback = feedbackText.trim()
+ if (!feedback || !submissionId) {
+ return
+ }
+
+ posthog.capture(SurveyEventName.SENT, {
+ [SurveyEventProperties.SURVEY_ID]: SURVEY_ID,
+ [SurveyEventProperties.SURVEY_SUBMISSION_ID]: submissionId,
+ [SurveyEventProperties.SURVEY_COMPLETED]: true,
+ [getSurveyResponseKey(1)]: feedback,
+ [getSurveyIdBasedResponseKey(FEEDBACK_QUESTION_ID)]: feedback,
+ feedback_surface: 'workflow_tree_editor',
+ })
+ setFeedbackOpen(false)
+ setFeedbackText('')
+ }
+
+ return (
+ <>
+ <LemonBanner type="info" dismissKey="workflow-tree-feature-preview" className="m-2">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div className="text-secondary">
+ {rating
+ ? 'Thanks, your rating is saved.'
+ : 'We’re trialling a new list based workflow view. What do you think?'}
+ </div>
+ <div className="flex items-center gap-1">
+ <LemonButton
+ type={rating === 'useful' ? 'primary' : 'secondary'}
+ size="xsmall"
+ icon={rating === 'useful' ? <IconThumbsUpFilled /> : <IconThumbsUp />}
+ tooltip="This is useful"
+ disabled={!!rating}
+ onClick={() => ratePreview('useful')}
+ data-attr="workflow-tree-feature-preview-thumbs-up"
+ />
+ <LemonButton
+ type={rating === 'needs improvement' ? 'primary' : 'secondary'}
+ size="xsmall"
+ icon={rating === 'needs improvement' ? <IconThumbsDownFilled /> : <IconThumbsDown />}
+ tooltip="Needs improvement"
+ disabled={!!rating}
+ onClick={() => ratePreview('needs improvement')}
+ data-attr="workflow-tree-feature-preview-thumbs-down"
+ />
+ </div>
+ </div>
+ </LemonBanner>
+ <LemonModal
+ title="Help shape the new workflow view"
+ description="Thanks, your rating is saved. What would make this better?"
+ isOpen={feedbackOpen}
+ onClose={() => setFeedbackOpen(false)}
+ data-attr="workflow-tree-feature-preview-feedback"
+ footer={
+ <div className="flex justify-end gap-2">
+ <LemonButton type="secondary" onClick={() => setFeedbackOpen(false)}>
+ Not now
+ </LemonButton>
+ <LemonButton type="primary" disabled={!feedbackText.trim()} onClick={submitFeedback}>
+ Send feedback
+ </LemonButton>
+ </div>
+ }
+ >
+ <LemonTextArea
+ value={feedbackText}
+ onChange={setFeedbackText}
+ placeholder="Tell us what works, what doesn’t, or what you’d change"
+ minRows={4}
+ autoFocus
+ data-attr="workflow-tree-feature-preview-feedback-text"
+ />
+ </LemonModal>
+ </>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeNode.tsx b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeNode.tsx
new file mode 100644
index 000000000000..74d41a585538
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeNode.tsx
@@ -0,0 +1,317 @@
+import { useActions } from 'kea'
+import { useEffect, useRef, useState } from 'react'
+import type { DragEvent } from 'react'
+
+import { IconArrowRight, IconChevronDown } from '@posthog/icons'
+
+import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { Badge, Button, Item, ItemContent, ItemTitle, Text, cn } from 'lib/ui/quill'
+
+import { getHogFlowBranchColor, useHogFlowBranchSelection } from '../HogFlowBranchSelection'
+import { hogFlowEditorLogic } from '../hogFlowEditorLogic'
+import { HogFlowTreeBranchIndicator } from './HogFlowTreeBranchIndicator'
+import { HogFlowTreeDropzone } from './HogFlowTreeDropzone'
+import { HogFlowTreeStep } from './HogFlowTreeStep'
+import type { WorkflowTreeNode } from './workflowTree'
+
+const BRANCH_LIMIT = 6
+export function HogFlowTreeNode({
+ activeDropzones,
+ draggedActionId,
+ draggedActionIdRef,
+ node,
+ onDragEnd,
+ onDragStart,
+ branchColor,
+ showIncomingConnector = true,
+}: {
+ activeDropzones: boolean
+ draggedActionId: string | null
+ draggedActionIdRef: { current: string | null }
+ node: WorkflowTreeNode
+ onDragEnd: () => void
+ onDragStart: (event: DragEvent<HTMLDivElement>, actionId: string, dragPreviewElement: HTMLDivElement | null) => void
+ branchColor?: string
+ showIncomingConnector?: boolean
+}): JSX.Element {
+ const { setSelectedNodeId } = useActions(hogFlowEditorLogic)
+ const { selectedBranch, setSelectedBranch } = useHogFlowBranchSelection()
+ const [branchesOpen, setBranchesOpen] = useState(true)
+ const [collapsedBranches, setCollapsedBranches] = useState<Set<string>>(new Set())
+ const [showAllBranches, setShowAllBranches] = useState(false)
+ const nodeRef = useRef<HTMLDivElement>(null)
+ const visibleBranches = showAllBranches ? node.branches : node.branches.slice(0, BRANCH_LIMIT)
+ const hiddenBranchCount = node.branches.length - visibleBranches.length
+ const joinEdge = node.joinEdges[0]
+ const joinAction = node.joinAction
+ const branchNoun = node.action.type === 'random_cohort_branch' ? 'paths' : 'conditions'
+ const toggleBranchCollapsed = (branchKey: string): void => {
+ setCollapsedBranches((current) => {
+ const next = new Set(current)
+ next.has(branchKey) ? next.delete(branchKey) : next.add(branchKey)
+ return next
+ })
+ }
+
+ useEffect(() => {
+ if (selectedBranch?.actionId === node.action.id) {
+ nodeRef.current
+ ?.querySelector(`[data-workflow-branch-index="${selectedBranch.index ?? 'continue'}"]`)
+ ?.scrollIntoView({ block: 'nearest' })
+ }
+ }, [node.action.id, selectedBranch])
+
+ const step = (
+ <HogFlowTreeStep
+ action={node.action}
+ branchColor={branchColor}
+ collapseControl={
+ node.branches.length > 0 ? (
+ <Tooltip title={`${branchesOpen ? 'Hide' : 'Show'} ${branchNoun}`}>
+ <Button
+ type="button"
+ variant="default"
+ size="icon"
+ aria-label={`${branchesOpen ? 'Hide' : 'Show'} ${branchNoun}`}
+ onClick={() => setBranchesOpen((open) => !open)}
+ >
+ <IconChevronDown
+ className={cn('size-5 transition-transform', !branchesOpen && '-rotate-90')}
+ />
+ </Button>
+ </Tooltip>
+ ) : undefined
+ }
+ onDragStart={onDragStart}
+ onDragEnd={onDragEnd}
+ canDrag={
+ node.action.type !== 'trigger' &&
+ node.action.type !== 'exit' &&
+ (!node.branches.length || !!node.joinActionId)
+ }
+ />
+ )
+
+ return (
+ <div ref={nodeRef} className="flex w-full flex-col">
+ {node.incomingEdge && (
+ <HogFlowTreeDropzone
+ active={activeDropzones}
+ draggedActionId={draggedActionId}
+ draggedActionIdRef={draggedActionIdRef}
+ onDragEnd={onDragEnd}
+ edge={node.incomingEdge}
+ showConnector={showIncomingConnector}
+ compact={!showIncomingConnector}
+ />
+ )}
+ {node.branches.length === 0 ? (
+ step
+ ) : (
+ <>
+ {step}
+ {branchesOpen && (
+ <div className="flex flex-col gap-3 pt-2" data-workflow-tree-branch-content={node.action.id}>
+ {visibleBranches.map((branch, index) => {
+ const branchIndex = branch.edge.type === 'branch' ? (branch.edge.index ?? index) : null
+ const branchColor = getHogFlowBranchColor(branchIndex)
+ const isBranchSelected =
+ selectedBranch?.actionId === node.action.id && selectedBranch.index === branchIndex
+ const branchFilters =
+ branchIndex !== null && node.action.type === 'conditional_branch'
+ ? (node.action.config.conditions[branchIndex]?.filters.properties ?? [])
+ : []
+ const cohortPercentage =
+ branchIndex !== null && node.action.type === 'random_cohort_branch'
+ ? node.action.config.cohorts[branchIndex]?.percentage
+ : undefined
+
+ const branchKey = `${branch.edge.from}-${branch.edge.type}-${branch.edge.index ?? 'continue'}`
+ const branchCollapsed = collapsedBranches.has(branchKey)
+ const hiddenStepCount = branch.sequence.nodes.length
+
+ return (
+ <div
+ key={branchKey}
+ className="relative flex min-w-0 flex-col ps-0"
+ data-workflow-branch-index={branchIndex ?? 'continue'}
+ >
+ <Item
+ variant="outline"
+ size="xs"
+ className="relative z-10 flex-nowrap bg-card text-start"
+ style={{
+ borderColor: branchColor,
+ borderWidth: isBranchSelected ? 2 : undefined,
+ }}
+ data-attr="workflow-tree-select-branch"
+ >
+ <Button
+ type="button"
+ variant="link"
+ className="absolute inset-0 z-0 h-full w-full"
+ aria-label={`Edit ${branch.label} path from ${node.action.name}`}
+ aria-pressed={isBranchSelected}
+ onClick={() => {
+ setSelectedNodeId(node.action.id)
+ setSelectedBranch({ actionId: node.action.id, index: branchIndex })
+ }}
+ />
+ <Badge
+ variant="default"
+ className="pointer-events-none relative z-10 font-mono text-xxs"
+ style={{ color: branchColor, borderColor: branchColor }}
+ >
+ {branch.edge.type === 'continue' ? 'ELSE' : 'IF'}
+ </Badge>
+ <ItemContent className="pointer-events-none relative z-10 min-w-0">
+ <ItemTitle className="max-w-full truncate text-xs">
+ {branch.label}
+ </ItemTitle>
+ </ItemContent>
+ {branchFilters.length > 0 && (
+ <div className="pointer-events-none relative z-10 ms-auto min-w-0 max-w-[60%] overflow-hidden [&_.PropertyFilterButton]:!gap-1 [&_.PropertyFilterButton]:!px-1.5 [&_.PropertyFilterButton]:!py-px [&_.PropertyFilterButton]:!text-xs [&_.PropertyFilterButton>_.LemonIcon]:!text-xs">
+ <PropertyFiltersDisplay filters={branchFilters} compact />
+ </div>
+ )}
+ {cohortPercentage !== undefined && (
+ <Text
+ size="xs"
+ variant="muted"
+ render={<span />}
+ className="pointer-events-none relative z-10 ms-auto shrink-0"
+ >
+ {cohortPercentage}%
+ </Text>
+ )}
+ <div className="relative z-20 ms-auto flex shrink-0 items-center gap-1">
+ <Tooltip title={`${branchCollapsed ? 'Show' : 'Hide'} branch steps`}>
+ <Button
+ type="button"
+ variant="default"
+ size="xs"
+ className={cn(
+ !(branchCollapsed && hiddenStepCount > 0) && '!w-5 !px-0'
+ )}
+ aria-label={`${branchCollapsed ? 'Show' : 'Hide'} branch steps`}
+ onClick={() => toggleBranchCollapsed(branchKey)}
+ >
+ {branchCollapsed &&
+ hiddenStepCount > 0 &&
+ `${hiddenStepCount} ${hiddenStepCount === 1 ? 'step' : 'steps'} hidden`}
+ <IconChevronDown
+ className={cn(
+ 'size-4 transition-transform',
+ branchCollapsed && '-rotate-90'
+ )}
+ />
+ </Button>
+ </Tooltip>
+ </div>
+ </Item>
+ <div className={cn('flex flex-col ps-8', branchCollapsed && 'hidden')}>
+ {branch.sequence.nodes.length === 0 && (
+ <div className="relative">
+ <HogFlowTreeBranchIndicator
+ color={branchColor}
+ className="inset-y-2"
+ />
+ <Text size="xs" variant="muted" className="py-2">
+ No steps in this branch.
+ </Text>
+ </div>
+ )}
+ {branch.sequence.nodes.map((childNode, childIndex) => (
+ <HogFlowTreeNode
+ key={childNode.action.id}
+ node={childNode}
+ activeDropzones={activeDropzones}
+ draggedActionId={draggedActionId}
+ draggedActionIdRef={draggedActionIdRef}
+ onDragStart={onDragStart}
+ onDragEnd={onDragEnd}
+ branchColor={branchColor}
+ showIncomingConnector={childIndex > 0}
+ />
+ ))}
+ {branch.sequence.trailingEdge && (
+ <HogFlowTreeDropzone
+ active={activeDropzones}
+ draggedActionId={draggedActionId}
+ draggedActionIdRef={draggedActionIdRef}
+ onDragEnd={onDragEnd}
+ edge={branch.sequence.trailingEdge}
+ showConnector={false}
+ compact
+ />
+ )}
+ {joinAction && (
+ <div className="relative flex items-center gap-1">
+ <HogFlowTreeBranchIndicator
+ color={branchColor}
+ className="inset-y-1"
+ />
+ <Text size="xxs" variant="muted" render={<span />}>
+ {node.action.type === 'random_cohort_branch'
+ ? 'End of cohort split · continues to'
+ : 'End of condition · continues to'}
+ </Text>
+ <Button
+ type="button"
+ variant="link"
+ size="xs"
+ className="min-w-0 max-w-56 px-0"
+ onClick={() => {
+ setSelectedBranch(null)
+ setSelectedNodeId(joinAction.id)
+ document
+ .getElementById(`workflow-tree-step-${joinAction.id}`)
+ ?.scrollIntoView({
+ behavior: 'smooth',
+ block: 'center',
+ })
+ }}
+ data-attr="workflow-tree-select-continuation"
+ >
+ <span className="truncate">{joinAction.name}</span>
+ <IconArrowRight className="size-3" />
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+ )
+ })}
+ {node.branches.length > BRANCH_LIMIT && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="self-start border-dashed"
+ onClick={() => setShowAllBranches((showAll) => !showAll)}
+ data-attr="workflow-tree-toggle-more-branches"
+ >
+ {showAllBranches
+ ? 'Show fewer branches'
+ : `Show ${hiddenBranchCount} more branches`}
+ </Button>
+ )}
+ </div>
+ )}
+ {joinEdge && (
+ <HogFlowTreeDropzone
+ active={activeDropzones}
+ draggedActionId={draggedActionId}
+ draggedActionIdRef={draggedActionIdRef}
+ onDragEnd={onDragEnd}
+ edge={joinEdge}
+ isBranchJoin
+ joinEdges={node.joinEdges}
+ />
+ )}
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeStep.tsx b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeStep.tsx
new file mode 100644
index 000000000000..1a8222c099a7
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeStep.tsx
@@ -0,0 +1,204 @@
+import { useActions, useValues } from 'kea'
+import { useRef } from 'react'
+import type { DragEvent, ReactNode } from 'react'
+
+import { IconCopy, IconDrag, IconTrash } from '@posthog/icons'
+
+import { Badge, Button, Item, ItemActions, ItemContent, ItemDescription, ItemMedia, ItemTitle, cn } from 'lib/ui/quill'
+
+import { workflowLogic } from '../../workflowLogic'
+import { useHogFlowBranchSelection } from '../HogFlowBranchSelection'
+import { hogFlowEditorLogic } from '../hogFlowEditorLogic'
+import { StepView } from '../steps/components/StepView'
+import { useHogFlowStep } from '../steps/HogFlowSteps'
+import type { HogFlowAction, HogFlowActionNode } from '../types'
+import { HogFlowTreeBranchIndicator } from './HogFlowTreeBranchIndicator'
+import { isBranchingAction } from './workflowTree'
+
+export function HogFlowTreeStep({
+ action,
+ onDragEnd,
+ onDragStart,
+ branchColor,
+ collapseControl,
+ canDrag = !['trigger', 'exit'].includes(action.type) && !isBranchingAction(action),
+}: {
+ action: HogFlowAction
+ onDragEnd: () => void
+ onDragStart: (event: DragEvent<HTMLDivElement>, actionId: string, dragPreviewElement: HTMLDivElement | null) => void
+ branchColor?: string
+ collapseControl?: ReactNode
+ canDrag?: boolean
+}): JSX.Element {
+ const { animatingEdgePair, nodesById, selectedNode } = useValues(hogFlowEditorLogic)
+ const { duplicateNodeBelow, onNodesDelete, setSelectedNodeId } = useActions(hogFlowEditorLogic)
+ const { setSelectedBranch } = useHogFlowBranchSelection()
+ const { actionValidationErrorsById, workflow } = useValues(workflowLogic)
+ const step = useHogFlowStep(action)
+ const dragPreviewRef = useRef<HTMLDivElement>(null)
+
+ const isSelected = selectedNode?.id === action.id
+ const canHaveActions = !['trigger', 'exit'].includes(action.type)
+ const outgoingActionIds = workflow.edges.filter((edge) => edge.from === action.id).map((edge) => edge.to)
+ const canDelete = canHaveActions && (outgoingActionIds.length === 1 || new Set(outgoingActionIds).size === 1)
+ const canDuplicate = canDelete && !isBranchingAction(action)
+ const node =
+ nodesById[action.id] ??
+ ({
+ id: action.id,
+ type: 'action',
+ data: action,
+ position: { x: 0, y: 0 },
+ deletable: canHaveActions,
+ selectable: true,
+ draggable: false,
+ connectable: false,
+ } satisfies HogFlowActionNode)
+ const validationResult = actionValidationErrorsById[action.id]
+ const hasValidationIssue =
+ validationResult?.valid === false || Object.keys(validationResult?.warnings ?? {}).length > 0
+ const isAnimationTarget = animatingEdgePair?.endsWith(`->${action.id}`) ?? false
+ const hasFooterContent = !!action.description || !!step?.previews.length
+
+ return (
+ <Item
+ variant="outline"
+ size="xs"
+ className={cn(
+ 'relative flex-nowrap !gap-2 bg-card !px-2 !py-1.5',
+ isSelected && 'border-ring ring-2 ring-ring/30',
+ isAnimationTarget && 'border-success',
+ 'data-[workflow-tree-dragging]:opacity-50'
+ )}
+ data-attr="workflow-tree-step"
+ id={`workflow-tree-step-${action.id}`}
+ >
+ {branchColor && <HogFlowTreeBranchIndicator color={branchColor} className="inset-y-1" />}
+ <Button
+ type="button"
+ variant="link"
+ className="absolute inset-0 z-0 h-full w-full"
+ aria-label={`Edit ${action.name}`}
+ aria-pressed={isSelected}
+ onClick={() => {
+ setSelectedBranch(null)
+ setSelectedNodeId(action.id)
+ }}
+ />
+ {canDrag && (
+ <div
+ draggable
+ className="relative z-10 -ms-0.5 -me-1 flex size-5 shrink-0 cursor-grab items-center justify-center text-muted-foreground active:cursor-grabbing"
+ onDragStart={(event) => onDragStart(event, action.id, dragPreviewRef.current)}
+ onDragEnd={onDragEnd}
+ data-attr="workflow-tree-step-drag"
+ >
+ <IconDrag className="size-4" />
+ </div>
+ )}
+ <ItemMedia
+ variant="image"
+ className="pointer-events-none relative z-10 !size-8 shrink-0 [&>img]:!size-6 [&>img]:!object-contain [&>svg]:!size-6 [&>svg]:shrink-0"
+ style={
+ step?.color
+ ? {
+ alignSelf: 'center',
+ translate: 'none',
+ backgroundColor: `${step.color}20`,
+ color: step.color,
+ }
+ : { alignSelf: 'center', translate: 'none' }
+ }
+ >
+ {step?.icon}
+ </ItemMedia>
+ <ItemContent className="pointer-events-none relative z-10 min-w-0 gap-0.5">
+ <div className="flex min-w-0 items-center gap-1">
+ <ItemTitle className="pointer-events-none min-w-0 flex-1 max-w-full truncate leading-tight">
+ {action.name}
+ </ItemTitle>
+ {canHaveActions && (
+ <ItemActions
+ className={cn(
+ 'pointer-events-auto',
+ '!gap-px ms-auto shrink-0 transition-opacity group-hover/item:opacity-100 group-focus-within/item:opacity-100',
+ isSelected ? 'opacity-100' : 'opacity-20'
+ )}
+ >
+ {canDuplicate && (
+ <Button
+ type="button"
+ variant="default"
+ size="icon-sm"
+ aria-label="Duplicate step"
+ title="Duplicate step"
+ onClick={() => duplicateNodeBelow(action.id)}
+ data-attr="workflow-tree-duplicate-step"
+ >
+ <IconCopy />
+ </Button>
+ )}
+ <Button
+ type="button"
+ variant="default"
+ size="icon-sm"
+ aria-label="Delete step"
+ title={canDelete ? 'Delete step' : 'Clean up branching steps first'}
+ disabled={!canDelete}
+ onClick={() => {
+ onNodesDelete([node])
+ setSelectedNodeId(null)
+ }}
+ data-attr="workflow-tree-delete-step"
+ >
+ <IconTrash />
+ </Button>
+ </ItemActions>
+ )}
+ </div>
+ {hasFooterContent && (
+ <div className="flex min-w-0 items-center gap-2">
+ {action.description && (
+ <ItemDescription className="pointer-events-none min-w-0 flex-1 truncate leading-tight">
+ {action.description}
+ </ItemDescription>
+ )}
+ {!!step?.previews.length && (
+ <div className="pointer-events-none ms-auto flex min-w-0 shrink-0 items-center gap-1 overflow-hidden">
+ {step.previews.slice(0, 3).map((preview, index) => (
+ <Badge
+ key={`${preview.label}-${index}`}
+ variant="default"
+ className="max-w-36 truncate"
+ >
+ {preview.icon}
+ {preview.label}
+ </Badge>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </ItemContent>
+ {collapseControl && (
+ <div className="pointer-events-auto relative z-10 -my-1.5 -me-2 flex w-10 shrink-0 items-center justify-center border-s">
+ {collapseControl}
+ </div>
+ )}
+ {hasValidationIssue && (
+ <Badge
+ variant="warning"
+ className="pointer-events-none absolute -end-1 -top-1 z-20 !size-5 !min-w-5 shrink-0 !rounded-full border-2 border-card !p-0 !leading-none shadow-sm"
+ aria-label="Some fields need attention"
+ >
+ !
+ </Badge>
+ )}
+ <div ref={dragPreviewRef} className="pointer-events-none absolute invisible" aria-hidden="true">
+ <div className="origin-top-left scale-150">
+ <StepView action={{ ...action, id: `drag-preview-${action.id}` }} />
+ </div>
+ </div>
+ </Item>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/tree/workflowTree.test.ts b/products/workflows/frontend/Workflows/hogflows/tree/workflowTree.test.ts
new file mode 100644
index 000000000000..3a382fe32303
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/tree/workflowTree.test.ts
@@ -0,0 +1,176 @@
+import type { HogFlow, HogFlowAction, HogFlowEdge } from '../types'
+import { buildWorkflowTree, computeMoveTreeBranchEdges, isWorkflowTreeComplete } from './workflowTree'
+
+const action = (id: string, type: HogFlowAction['type'] = 'function'): HogFlowAction =>
+ ({ id, type, name: id, description: '', config: {} }) as HogFlowAction
+
+const edge = (from: string, to: string, type: HogFlowEdge['type'] = 'continue', index?: number): HogFlowEdge => ({
+ from,
+ to,
+ type,
+ index,
+})
+
+const workflow = (actions: HogFlowAction[], edges: HogFlowEdge[]): Pick<HogFlow, 'actions' | 'edges'> => ({
+ actions,
+ edges,
+})
+
+describe('buildWorkflowTree', () => {
+ it('falls back when an action is unreachable from the trigger', () => {
+ expect(
+ isWorkflowTreeComplete(
+ workflow(
+ [action('trigger', 'trigger'), action('exit', 'exit'), action('orphan')],
+ [edge('trigger', 'exit')]
+ )
+ )
+ ).toBe(false)
+ })
+
+ it('renders converging routes before one shared continuation', () => {
+ const tree = buildWorkflowTree(
+ workflow(
+ [
+ action('trigger', 'trigger'),
+ action('condition', 'conditional_branch'),
+ action('yes'),
+ action('no'),
+ action('shared'),
+ action('exit', 'exit'),
+ ],
+ [
+ edge('trigger', 'condition'),
+ edge('condition', 'yes', 'branch', 0),
+ edge('condition', 'no'),
+ edge('yes', 'shared'),
+ edge('no', 'shared'),
+ edge('shared', 'exit'),
+ ]
+ )
+ )
+
+ expect(tree.nodes.map((node) => node.action.id)).toEqual(['trigger', 'condition', 'shared', 'exit'])
+ expect(tree.nodes[1].branches.map((branch) => branch.sequence.nodes.map((node) => node.action.id))).toEqual([
+ ['yes'],
+ ['no'],
+ ])
+ expect(tree.nodes[1].joinActionId).toBe('shared')
+ expect(tree.nodes[1].joinAction?.id).toBe('shared')
+ })
+
+ it('keeps immediate routes empty and exposes their insertion edges', () => {
+ const tree = buildWorkflowTree(
+ workflow(
+ [action('trigger', 'trigger'), action('condition', 'conditional_branch'), action('exit', 'exit')],
+ [edge('trigger', 'condition'), edge('condition', 'exit', 'branch', 0), edge('condition', 'exit')]
+ )
+ )
+
+ expect(tree.nodes.map((node) => node.action.id)).toEqual(['trigger', 'condition', 'exit'])
+ expect(tree.nodes[1].branches.map((branch) => branch.sequence.nodes)).toEqual([[], []])
+ expect(tree.nodes[1].branches.map((branch) => branch.sequence.trailingEdge)).toEqual([
+ edge('condition', 'exit', 'branch', 0),
+ edge('condition', 'exit'),
+ ])
+ })
+
+ it('leaves routes terminal when they have no shared continuation', () => {
+ const tree = buildWorkflowTree(
+ workflow(
+ [
+ action('trigger', 'trigger'),
+ action('condition', 'conditional_branch'),
+ action('left-exit', 'exit'),
+ action('right-exit', 'exit'),
+ ],
+ [
+ edge('trigger', 'condition'),
+ edge('condition', 'left-exit', 'branch', 0),
+ edge('condition', 'right-exit'),
+ ]
+ )
+ )
+
+ expect(tree.nodes.map((node) => node.action.id)).toEqual(['trigger', 'condition'])
+ expect(tree.nodes[1].joinActionId).toBeNull()
+ expect(tree.nodes[1].branches.map((branch) => branch.sequence.nodes.map((node) => node.action.id))).toEqual([
+ ['left-exit'],
+ ['right-exit'],
+ ])
+ })
+
+ it('scopes a nested branch join to its own routes', () => {
+ const tree = buildWorkflowTree(
+ workflow(
+ [
+ action('trigger', 'trigger'),
+ action('outer', 'conditional_branch'),
+ action('paid'),
+ action('trial'),
+ action('at-risk'),
+ action('onboarding', 'conditional_branch'),
+ action('guided'),
+ action('self-serve'),
+ action('shared'),
+ action('exit', 'exit'),
+ ],
+ [
+ edge('trigger', 'outer'),
+ edge('outer', 'paid', 'branch', 0),
+ edge('outer', 'trial', 'branch', 1),
+ edge('outer', 'at-risk'),
+ edge('paid', 'shared'),
+ edge('trial', 'onboarding'),
+ edge('at-risk', 'shared'),
+ edge('onboarding', 'guided', 'branch', 0),
+ edge('onboarding', 'self-serve', 'branch', 1),
+ edge('onboarding', 'shared'),
+ edge('guided', 'shared'),
+ edge('self-serve', 'shared'),
+ edge('shared', 'exit'),
+ ]
+ )
+ )
+
+ const onboarding = tree.nodes[1].branches[1].sequence.nodes.find((node) => node.action.id === 'onboarding')
+ expect(onboarding?.joinEdges).toEqual([
+ edge('guided', 'shared'),
+ edge('self-serve', 'shared'),
+ edge('onboarding', 'shared'),
+ ])
+ })
+
+ it('moves a branching action with all of its paths', () => {
+ const workflowWithJoin = workflow(
+ [
+ action('trigger', 'trigger'),
+ action('condition', 'conditional_branch'),
+ action('yes'),
+ action('no'),
+ action('shared'),
+ action('after'),
+ action('exit', 'exit'),
+ ],
+ [
+ edge('trigger', 'condition'),
+ edge('condition', 'yes', 'branch', 0),
+ edge('condition', 'no'),
+ edge('yes', 'shared'),
+ edge('no', 'shared'),
+ edge('shared', 'after'),
+ edge('after', 'exit'),
+ ]
+ )
+
+ expect(computeMoveTreeBranchEdges(workflowWithJoin, 'condition', edge('shared', 'after'), false)).toEqual([
+ edge('trigger', 'shared'),
+ edge('condition', 'yes', 'branch', 0),
+ edge('condition', 'no'),
+ edge('yes', 'after'),
+ edge('no', 'after'),
+ edge('after', 'exit'),
+ edge('shared', 'condition'),
+ ])
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/tree/workflowTree.ts b/products/workflows/frontend/Workflows/hogflows/tree/workflowTree.ts
new file mode 100644
index 000000000000..4c44518008ca
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/tree/workflowTree.ts
@@ -0,0 +1,363 @@
+import type { HogFlow, HogFlowAction, HogFlowEdge } from '../types'
+
+export const BRANCHING_ACTION_TYPES = ['conditional_branch', 'random_cohort_branch', 'wait_until_condition'] as const
+
+export interface WorkflowTreeSequence {
+ nodes: WorkflowTreeNode[]
+ trailingEdge: HogFlowEdge | null
+}
+
+export interface WorkflowTreeNode {
+ action: HogFlowAction
+ incomingEdge: HogFlowEdge | null
+ branches: WorkflowTreeBranch[]
+ joinActionId: string | null
+ joinAction: HogFlowAction | null
+ joinEdges: HogFlowEdge[]
+}
+
+export interface WorkflowTreeBranch {
+ edge: HogFlowEdge
+ label: string
+ sequence: WorkflowTreeSequence
+}
+
+export function isBranchingAction(action: Pick<HogFlowAction, 'type'>): boolean {
+ return BRANCHING_ACTION_TYPES.includes(action.type as (typeof BRANCHING_ACTION_TYPES)[number])
+}
+
+export function getWorkflowBranchLabel(action: HogFlowAction | undefined, edge: HogFlowEdge): string {
+ if (edge.type === 'continue') {
+ return 'No match'
+ }
+
+ if (!action) {
+ return `If condition #${(edge.index ?? 0) + 1} matches`
+ }
+
+ switch (action.type) {
+ case 'wait_until_condition':
+ return action.config.condition?.name || 'If condition matches'
+ case 'random_cohort_branch':
+ return action.config.cohorts?.[edge.index ?? 0]?.name || `If cohort #${(edge.index ?? 0) + 1} matches`
+ case 'conditional_branch':
+ return action.config.conditions?.[edge.index ?? 0]?.name || `If condition #${(edge.index ?? 0) + 1} matches`
+ default:
+ return `If condition #${(edge.index ?? 0) + 1} matches`
+ }
+}
+
+function intersectSets(sets: Set<string>[]): Set<string> {
+ if (sets.length === 0) {
+ return new Set()
+ }
+
+ return new Set([...sets[0]].filter((value) => sets.slice(1).every((set) => set.has(value))))
+}
+
+function setsEqual(left: Set<string>, right: Set<string>): boolean {
+ return left.size === right.size && [...left].every((value) => right.has(value))
+}
+
+function buildPostDominators(
+ actionIds: string[],
+ outgoingEdgesByActionId: Map<string, HogFlowEdge[]>
+): Map<string, Set<string>> {
+ const allActionIds = new Set(actionIds)
+ const postDominators = new Map(
+ actionIds.map((actionId) => [
+ actionId,
+ outgoingEdgesByActionId.get(actionId)?.length ? new Set(allActionIds) : new Set([actionId]),
+ ])
+ )
+
+ for (let pass = 0; pass < actionIds.length * actionIds.length; pass++) {
+ let changed = false
+
+ for (const actionId of actionIds) {
+ const successors = (outgoingEdgesByActionId.get(actionId) ?? [])
+ .map((edge) => postDominators.get(edge.to))
+ .filter((set): set is Set<string> => !!set)
+ const next = new Set([actionId, ...intersectSets(successors)])
+
+ if (!setsEqual(next, postDominators.get(actionId) ?? new Set())) {
+ postDominators.set(actionId, next)
+ changed = true
+ }
+ }
+
+ if (!changed) {
+ break
+ }
+ }
+
+ return postDominators
+}
+
+function distancesFrom(
+ startActionId: string,
+ outgoingEdgesByActionId: Map<string, HogFlowEdge[]>
+): Map<string, number> {
+ const distances = new Map([[startActionId, 0]])
+ const queue = [startActionId]
+
+ for (let index = 0; index < queue.length; index++) {
+ const actionId = queue[index]
+ const distance = distances.get(actionId) ?? 0
+
+ for (const edge of outgoingEdgesByActionId.get(actionId) ?? []) {
+ if (!distances.has(edge.to)) {
+ distances.set(edge.to, distance + 1)
+ queue.push(edge.to)
+ }
+ }
+ }
+
+ return distances
+}
+
+function findBranchJoinActionId(
+ actionId: string,
+ edges: HogFlowEdge[],
+ outgoingEdgesByActionId: Map<string, HogFlowEdge[]>,
+ postDominatorsByActionId: Map<string, Set<string>>,
+ actionOrder: Map<string, number>
+): string | null {
+ const targetIds = [...new Set(edges.map((edge) => edge.to))]
+ const candidates = intersectSets(
+ targetIds.map((targetId) => postDominatorsByActionId.get(targetId) ?? new Set<string>())
+ )
+ candidates.delete(actionId)
+
+ const distances = targetIds.map((targetId) => distancesFrom(targetId, outgoingEdgesByActionId))
+
+ return (
+ [...candidates].sort((left, right) => {
+ const leftDistances = distances.map((map) => map.get(left) ?? Number.POSITIVE_INFINITY)
+ const rightDistances = distances.map((map) => map.get(right) ?? Number.POSITIVE_INFINITY)
+ const maxDifference = Math.max(...leftDistances) - Math.max(...rightDistances)
+ const totalDifference =
+ leftDistances.reduce((total, distance) => total + distance, 0) -
+ rightDistances.reduce((total, distance) => total + distance, 0)
+
+ return maxDifference || totalDifference || (actionOrder.get(left) ?? 0) - (actionOrder.get(right) ?? 0)
+ })[0] ?? null
+ )
+}
+
+function collectBranchJoinEdges(
+ sequence: WorkflowTreeSequence,
+ joinActionId: string,
+ joinEdges: Map<string, HogFlowEdge>
+): void {
+ if (sequence.trailingEdge?.to === joinActionId) {
+ const edge = sequence.trailingEdge
+ joinEdges.set(`${edge.from}:${edge.to}:${edge.type}:${edge.index ?? ''}`, edge)
+ }
+
+ for (const node of sequence.nodes) {
+ for (const branch of node.branches) {
+ collectBranchJoinEdges(branch.sequence, joinActionId, joinEdges)
+ }
+ }
+}
+
+export function buildWorkflowTree(workflow: Pick<HogFlow, 'actions' | 'edges'>): WorkflowTreeSequence {
+ const actionsById = new Map(workflow.actions.map((action) => [action.id, action]))
+ const actionOrder = new Map(workflow.actions.map((action, index) => [action.id, index]))
+ const outgoingEdgesByActionId = new Map<string, HogFlowEdge[]>()
+
+ for (const edge of workflow.edges) {
+ if (!actionsById.has(edge.from) || !actionsById.has(edge.to)) {
+ continue
+ }
+ outgoingEdgesByActionId.set(edge.from, [...(outgoingEdgesByActionId.get(edge.from) ?? []), edge])
+ }
+
+ for (const edges of outgoingEdgesByActionId.values()) {
+ edges.sort((left, right) => {
+ if (left.type !== right.type) {
+ return left.type === 'branch' ? -1 : 1
+ }
+ return (left.index ?? Number.POSITIVE_INFINITY) - (right.index ?? Number.POSITIVE_INFINITY)
+ })
+ }
+
+ const postDominatorsByActionId = buildPostDominators([...actionsById.keys()], outgoingEdgesByActionId)
+
+ const buildSequence = (
+ startActionId: string | undefined,
+ stopActionId: string | null,
+ incomingEdge: HogFlowEdge | null,
+ ancestors: Set<string>
+ ): WorkflowTreeSequence => {
+ const nodes: WorkflowTreeNode[] = []
+ let actionId = startActionId
+ let edgeIntoAction = incomingEdge
+
+ while (actionId && actionId !== stopActionId && !ancestors.has(actionId)) {
+ const action = actionsById.get(actionId)
+ if (!action) {
+ break
+ }
+
+ ancestors.add(actionId)
+ const outgoingEdges = outgoingEdgesByActionId.get(actionId) ?? []
+ const node: WorkflowTreeNode = {
+ action,
+ incomingEdge: edgeIntoAction,
+ branches: [],
+ joinActionId: null,
+ joinAction: null,
+ joinEdges: [],
+ }
+
+ if (outgoingEdges.length <= 1) {
+ nodes.push(node)
+ edgeIntoAction = outgoingEdges[0] ?? null
+ actionId = outgoingEdges[0]?.to
+ continue
+ }
+
+ const joinActionId = findBranchJoinActionId(
+ actionId,
+ outgoingEdges,
+ outgoingEdgesByActionId,
+ postDominatorsByActionId,
+ actionOrder
+ )
+ node.joinActionId = joinActionId
+ node.joinAction = joinActionId ? (actionsById.get(joinActionId) ?? null) : null
+ node.branches = outgoingEdges.map((edge) => ({
+ edge,
+ label: getWorkflowBranchLabel(action, edge),
+ sequence: buildSequence(edge.to, joinActionId, edge, new Set(ancestors)),
+ }))
+ if (joinActionId) {
+ const joinEdges = new Map<string, HogFlowEdge>()
+ for (const branch of node.branches) {
+ collectBranchJoinEdges(branch.sequence, joinActionId, joinEdges)
+ }
+ node.joinEdges = [...joinEdges.values()]
+ }
+ nodes.push(node)
+
+ if (!joinActionId) {
+ return { nodes, trailingEdge: null }
+ }
+
+ actionId = joinActionId
+ edgeIntoAction = null
+ }
+
+ return { nodes, trailingEdge: actionId === stopActionId ? edgeIntoAction : null }
+ }
+
+ const trigger = workflow.actions.find((action) => action.type === 'trigger') ?? workflow.actions[0]
+ return buildSequence(trigger?.id, null, null, new Set())
+}
+
+export function isWorkflowTreeComplete(workflow: Pick<HogFlow, 'actions' | 'edges'>): boolean {
+ const actionIds = new Set<string>()
+ collectWorkflowTreeActionIds(buildWorkflowTree(workflow), actionIds)
+ return workflow.actions.every((action) => actionIds.has(action.id))
+}
+
+function findWorkflowTreeNode(sequence: WorkflowTreeSequence, actionId: string): WorkflowTreeNode | null {
+ for (const node of sequence.nodes) {
+ if (node.action.id === actionId) {
+ return node
+ }
+
+ for (const branch of node.branches) {
+ const branchNode = findWorkflowTreeNode(branch.sequence, actionId)
+ if (branchNode) {
+ return branchNode
+ }
+ }
+ }
+
+ return null
+}
+
+function collectWorkflowTreeActionIds(sequence: WorkflowTreeSequence, actionIds: Set<string>): void {
+ for (const node of sequence.nodes) {
+ actionIds.add(node.action.id)
+ for (const branch of node.branches) {
+ collectWorkflowTreeActionIds(branch.sequence, actionIds)
+ }
+ }
+}
+
+export function computeMoveTreeBranchEdges(
+ workflow: Pick<HogFlow, 'actions' | 'edges'>,
+ movingActionId: string,
+ targetEdge: HogFlowEdge,
+ isBranchJoinDropzone: boolean,
+ joinEdges?: HogFlowEdge[]
+): HogFlow['edges'] | null {
+ const branchNode = findWorkflowTreeNode(buildWorkflowTree(workflow), movingActionId)
+ const joinActionId = branchNode?.joinActionId
+
+ if (!branchNode || !joinActionId) {
+ return null
+ }
+
+ const movedActionIds = new Set([movingActionId])
+ for (const branch of branchNode.branches) {
+ collectWorkflowTreeActionIds(branch.sequence, movedActionIds)
+ }
+
+ if (movedActionIds.has(targetEdge.from) || movedActionIds.has(targetEdge.to)) {
+ return null
+ }
+
+ const terminalEdges = workflow.edges.filter((edge) => movedActionIds.has(edge.from) && edge.to === joinActionId)
+ if (terminalEdges.length === 0 || !workflow.edges.some((edge) => edge.to === movingActionId)) {
+ return null
+ }
+
+ let newEdges = workflow.edges.map((edge) => (edge.to === movingActionId ? { ...edge, to: joinActionId } : edge))
+
+ const targetEdgeIndexes = isBranchJoinDropzone
+ ? newEdges
+ .map((edge, index) => ({ edge, index }))
+ .filter(({ edge }) => {
+ if (movedActionIds.has(edge.from)) {
+ return false
+ }
+
+ if (joinEdges) {
+ return joinEdges.some(
+ (joinEdge) =>
+ edge.from === joinEdge.from &&
+ edge.to === joinEdge.to &&
+ edge.type === joinEdge.type &&
+ edge.index === joinEdge.index
+ )
+ }
+
+ return edge.to === targetEdge.to
+ })
+ .map(({ index }) => index)
+ : [
+ newEdges.findIndex(
+ (edge) =>
+ edge.from === targetEdge.from && edge.type === targetEdge.type && edge.index === targetEdge.index
+ ),
+ ]
+
+ if (targetEdgeIndexes.length === 0 || targetEdgeIndexes.includes(-1)) {
+ return null
+ }
+
+ const edgesToSplit = targetEdgeIndexes.map((index) => newEdges[index])
+ const insertionTarget = edgesToSplit[0].to
+ targetEdgeIndexes.sort((left, right) => right - left).forEach((index) => newEdges.splice(index, 1))
+
+ const terminalEdgeSet = new Set(terminalEdges)
+ newEdges = newEdges.map((edge) => (terminalEdgeSet.has(edge) ? { ...edge, to: insertionTarget } : edge))
+ newEdges.push(...edgesToSplit.map((edge) => ({ ...edge, to: movingActionId })))
+
+ return newEdges
+}