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 a tile canvas editor behind a flag (#119738)

Daniel Marchuk6c592372f6c7
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 4f03b9530842..5a5ba8919507 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8198,6 +8198,26 @@ snapshots:
hash: v1.k794b7964.2034ac462aa68d73fa5bd96c4061c5140a33b165bd377be1d889a50715275bb0.idAfTEhk_aha6kvc1txhrs33W-XzI18viXvEszxE3aI
products-workflows-editor-graph--with-navigation--light:
hash: v1.k794b7964.56d8bf045970b426f994709ddc19478d18e1968fcf3a41f8e0d28485ff338fa1.QsH5OKiKp00RMcqNzSYgsacI4_1BZ7UtU31Qt2EYzuU
+ products-workflows-editor-tile-canvas--long-emails--dark:
+ hash: v1.k794b7964.1c68fbef090e03ad78553e83f9600ca723e1410c5dea6cde7724640423dc63a3.IpQlXvn4eu0Kx0xAvtWrFY0HWEDmW2PJSaTJ-DdzfuQ
+ products-workflows-editor-tile-canvas--long-emails--light:
+ hash: v1.k794b7964.a44070a707b2bb3a40b702e9a651c7f65ace1aacbca38638558385d335b46931.-Ngt_-R_pmOJcOIUzg0hvf17t1OdkMaL3XHfBp8resg
+ products-workflows-editor-tile-canvas--paths-collapsed--dark:
+ hash: v1.k794b7964.a7d1365772454bc11513284e6b78429127fd18f9e88dc8596005089e1ec69719.W3pCWyBom6wjFqo5FoXZ1Ve1o6zhmWDzy3X0gRZHdN0
+ products-workflows-editor-tile-canvas--paths-collapsed--light:
+ hash: v1.k794b7964.e31aafe29d8cdc6afe148c7eb70c8777ccee76f57f5c84dd4dcd1f20326a18f7.snezvPc-3tVItCBGG6bYUghv_df0U3TYloGuRI1kaV8
+ products-workflows-editor-tile-canvas--paths-open--dark:
+ hash: v1.k794b7964.e57ec2aab358744dd6c7ff13dace41bdc233f1176fc751366b47ba3a4d6bc712.sjRXt0A6GF7dDuoED0em4jT4CCxjoeT-8dWgvlbJkXg
+ products-workflows-editor-tile-canvas--paths-open--light:
+ hash: v1.k794b7964.e2682899187338a05587b9c79fc6e1973445700e921c69731d74e6c822825472.kEwE5QPZ3ChJ-i8R5T7JVJPZTdWsJsG_Wgsc8bn4PPY
+ products-workflows-editor-tile-canvas--time-window-and-webhook--dark:
+ hash: v1.k794b7964.5742bd6276714aa6b25de49b7004c4e65340b7e22c31566caf465677462dcdf3.GKcg0jOBKdPEkKBmSFCzj4oDaiBohGDZXzmmHcX2Ev8
+ products-workflows-editor-tile-canvas--time-window-and-webhook--light:
+ hash: v1.k794b7964.bb4d20744239d7853c41634985d6c021415cf69a6c7a7affd82cc1b66629c05c.V8xSVCs8-Ryzp0TxCYhQJGUE6lIVtIJhK3_z07BoEvc
+ products-workflows-editor-tile-canvas--with-step-counts--dark:
+ hash: v1.k794b7964.2316bb905034aa99508f6137d9c223b2b4748f4095dcd1fedfe9f201505a5860.fonj_IIaN6K5A3Y_4FuSU0S8XBM-aMC8uhrRRFD4ac8
+ products-workflows-editor-tile-canvas--with-step-counts--light:
+ hash: v1.k794b7964.9250d4a392bfacf5d7777281f0e9759727d32119667b05630dd0131f89043d1e.e6tQol5A8SUhDy8Ubh964qHOS0Vp329Jjst4MIRsx-k
products-workflows-editor-tree--add-on-promotion-emails--dark:
hash: v1.k794b7964.b57f08708c8687742a71ed295c7e0d342e11cc63c709a9b9b703385fbf4d1b31.yosoQWPjKotHOoPqaIycyvai4desJVjTgoOqJHZu1fA
products-workflows-editor-tree--add-on-promotion-emails--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 0713b22965c0..aba6fa7fafd4 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -617,6 +617,7 @@ export const FEATURE_FLAGS = {
WORKFLOWS_OVERVIEW_TAB: 'workflows-overview-tab', // owner: @dmarchuk #team-workflows, experimental Overview tab on a workflow
WORKFLOWS_PUSH_NOTIFICATIONS: 'workflows-push-notifications', // owner: #team-workflows
WORKFLOWS_SEND_CALENDAR: 'workflows-send-calendar', // owner: @meikelmosby #team-workflows, calendar of scheduled email sends in Broadcasts and Workflows
+ WORKFLOWS_TILE_CANVAS: 'workflows-tile-canvas', // owner: #team-workflows
WORKFLOWS_TRANSACTIONAL_EMAIL_API: 'workflows-transactional-email-api', // owner: @mayteio #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 22cd52a74134..a9c5f145db56 100644
--- a/products/workflows/frontend/Workflows/Workflow.tsx
+++ b/products/workflows/frontend/Workflows/Workflow.tsx
@@ -4,8 +4,10 @@ import { LemonBanner, LemonButton, SpinnerOverlay } from '@posthog/lemon-ui'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { CanvasCommandGroup } from './hogflows/editor/tile-canvas/CanvasCommandGroup'
import { HogFlowEditor } from './hogflows/HogFlowEditor'
import { hogFlowEditorLogic } from './hogflows/hogFlowEditorLogic'
+import { WorkflowHeaderBar } from './WorkflowHeaderBar'
import { WorkflowLogicProps, workflowLogic } from './workflowLogic'
import { WorkflowStatusBar } from './WorkflowStatusBar'
@@ -14,18 +16,24 @@ export function Workflow(props: WorkflowLogicProps): JSX.Element {
workflowLogic(props)
)
const { loadWorkflow, keepMyWorkflowVersion } = useActions(workflowLogic(props))
- const { editorLayout } = useValues(hogFlowEditorLogic(logicProps))
+ const { editorLayout, isTreeView, isTileCanvas, showsHeaderInWorkflowBar } = useValues(
+ hogFlowEditorLogic(logicProps)
+ )
const { setEditorLayout } = useActions(hogFlowEditorLogic(logicProps))
const treeViewEnabled = useFeatureFlag('WORKFLOWS_LINEAR_VIEW')
return (
<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}
- />
+ {showsHeaderInWorkflowBar ? (
+ <WorkflowHeaderBar {...props} commands={<CanvasCommandGroup {...logicProps} />} />
+ ) : (
+ <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 && (
@@ -50,7 +58,7 @@ export function Workflow(props: WorkflowLogicProps): JSX.Element {
{!originalWorkflow && workflowLoading ? (
<SpinnerOverlay />
) : (
- <HogFlowEditor isTreeView={!!treeViewEnabled && editorLayout === 'simple'} />
+ <HogFlowEditor isTreeView={isTreeView} isTileCanvas={isTileCanvas} />
)}
</div>
)
diff --git a/products/workflows/frontend/Workflows/WorkflowHeaderBar.tsx b/products/workflows/frontend/Workflows/WorkflowHeaderBar.tsx
new file mode 100644
index 000000000000..2739e38f3e9a
--- /dev/null
+++ b/products/workflows/frontend/Workflows/WorkflowHeaderBar.tsx
@@ -0,0 +1,143 @@
+import { useActions, useValues } from 'kea'
+
+import { IconInfo } from '@posthog/icons'
+import { LemonDivider, LemonSwitch, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'
+
+import { LastSavedIndicator } from 'lib/components/LastSavedIndicator'
+import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'
+
+import { SceneBreadcrumbBackButton } from '~/layout/scenes/components/SceneBreadcrumbs'
+import { SceneDescription } from '~/layout/scenes/components/SceneDescription'
+import { SceneTitlePanelButton } from '~/layout/scenes/components/SceneTitlePanelButton'
+import { SceneName } from '~/layout/scenes/components/SceneTitleSection'
+
+import { WorkflowActions } from './WorkflowActions'
+import { workflowBackTo } from './workflowBackTo'
+import { WorkflowLogicProps, workflowLogic } from './workflowLogic'
+
+type WorkflowHeaderBarProps = WorkflowLogicProps & {
+ commands?: JSX.Element
+}
+
+const BAR_CLASS_NAME =
+ 'flex flex-wrap items-start justify-between gap-x-4 gap-y-2 rounded-t-md border-b bg-surface-secondary px-2 py-2'
+
+function WorkflowHeaderBarLoading(): JSX.Element {
+ return (
+ <div className={BAR_CLASS_NAME}>
+ <div className="flex min-w-0 flex-1 basis-72 items-start gap-1">
+ <SceneBreadcrumbBackButton className="mt-0.5 shrink-0" />
+ <SceneName isLoading />
+ </div>
+ </div>
+ )
+}
+
+export function WorkflowHeaderBar({ commands, ...props }: WorkflowHeaderBarProps): JSX.Element {
+ const logic = workflowLogic(props)
+ const {
+ originalWorkflow,
+ workflow,
+ workflowLoading,
+ hasUnsavedChanges,
+ hasStagedDraft,
+ isAutoSavePending,
+ autoSaveEnabled,
+ lastSavedAt,
+ } = useValues(logic)
+ const { setAutoSaveEnabled, setWorkflowValue } = useActions(logic)
+ const showSaving = useDebouncedValue(isAutoSavePending || workflowLoading, 1000)
+
+ if (!originalWorkflow) {
+ return <WorkflowHeaderBarLoading />
+ }
+
+ const showWorkflowStatus = !props.editTemplateId
+ const isSaved = !!props.id && props.id !== 'new'
+ // Auto-save writes to a saved workflow, so a new one shows its Create button alone.
+ const showAutoSave = showWorkflowStatus && isSaved
+ const isActive = originalWorkflow.status === 'active'
+ const isEditingDraftOfLive = isActive && (hasStagedDraft || hasUnsavedChanges)
+
+ return (
+ <div className={BAR_CLASS_NAME}>
+ <div className="flex min-w-0 flex-1 basis-72 items-start gap-1">
+ <SceneBreadcrumbBackButton
+ className="mt-0.5 shrink-0"
+ forceBackTo={workflowBackTo(workflow, props.id)}
+ />
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div className="flex min-w-0 items-center gap-2">
+ <div className="min-w-0">
+ <SceneName
+ name={workflow?.name}
+ onChange={(name) => setWorkflowValue('name', name)}
+ canEdit
+ renameDebounceMs={200}
+ />
+ </div>
+ {showWorkflowStatus &&
+ (isEditingDraftOfLive ? (
+ <Tooltip title="The live version keeps running until you publish.">
+ <LemonTag type="warning">Editing draft</LemonTag>
+ </Tooltip>
+ ) : isActive ? (
+ <Tooltip title="Changes you make save as a draft.">
+ <LemonTag type="success">Live</LemonTag>
+ </Tooltip>
+ ) : (
+ <LemonTag>Draft</LemonTag>
+ ))}
+ </div>
+ <SceneDescription
+ description={workflow?.description}
+ onChange={(description) => setWorkflowValue('description', description)}
+ canEdit
+ renameDebounceMs={200}
+ />
+ </div>
+ </div>
+ <div className="flex flex-wrap items-center justify-end gap-x-3 gap-y-2">
+ {commands}
+ {commands && <LemonDivider vertical className="h-6" />}
+ {showAutoSave && (
+ // A fixed width keeps the buttons beside it still while the timestamp text changes.
+ <div className="flex w-44 flex-col">
+ <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>
+ <div className="truncate leading-tight">
+ {autoSaveEnabled && showSaving ? (
+ <span className="text-xs text-tertiary inline-flex items-center gap-1">
+ <Spinner textColored /> Saving…
+ </span>
+ ) : lastSavedAt ? (
+ <LastSavedIndicator timestamp={lastSavedAt} />
+ ) : null}
+ </div>
+ </div>
+ )}
+ <div className="flex flex-wrap items-center gap-1.5">
+ <WorkflowActions {...props} />
+ </div>
+ {/* A saved workflow shows the AI and side panel buttons beside its tabs, and a new one has no tabs yet. */}
+ {!isSaved && <SceneTitlePanelButton />}
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsx
index 4d942cefc57c..8728967f3467 100644
--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx
@@ -19,6 +19,7 @@ import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitlePanelButton } from '~/layout/scenes/components/SceneTitlePanelButton'
import { ProductKey } from '~/queries/schema/schema-general'
import { ActivityScope } from '~/types'
@@ -116,6 +117,7 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
const { featureFlags } = useValues(featureFlagLogic)
const overviewTabEnabled = !!featureFlags[FEATURE_FLAGS.WORKFLOWS_OVERVIEW_TAB]
const { suggestionsAvailable } = useValues(workflowSuggestionsAvailabilityLogic)
+ const tileCanvasEnabled = !!featureFlags[FEATURE_FLAGS.WORKFLOWS_TILE_CANVAS]
const isSavedWorkflow = !!props.id && props.id !== 'new'
const { sceneIntegrationEnabled } = useValues(sceneAgentPanelLogic)
const { aiComposerAvailable } = useValues(newWorkflowLogic)
@@ -242,29 +244,36 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
// A deep link to a tab the flag hides would leave LemonTabs with no active tab and a blank page.
const activeTab = tabs.some((tab) => tab?.key === currentTab) ? currentTab : 'workflow'
+ const renderScene = (editorShowsHeaderInBar: boolean): JSX.Element => {
+ const headerInWorkflowBar = editorShowsHeaderInBar && (activeTab === 'workflow' || !isSavedWorkflow)
+ return (
+ <SceneContent className="h-full flex flex-col grow" data-attr="workflow-scene">
+ <BindLogic logic={workflowLogic} props={workflowProps}>
+ <WorkflowSceneHeader {...props} headerInWorkflowBar={headerInWorkflowBar} />
+ <WorkflowEmailPauseBanner />
+ {!isSavedWorkflow && <WorkflowAiEmailDraftStatus {...workflowProps} />}
+ {suggestionsAvailable && isSavedWorkflow && <WorkflowSuggestionsNotice id={props.id!} />}
+ {/* Only show Logs and Metrics tabs if the workflow has already been created */}
+ {!props.id || props.id === 'new' ? (
+ <Workflow {...workflowProps} />
+ ) : (
+ <LemonTabs
+ activeKey={activeTab}
+ onChange={(tab) => router.actions.push(urls.workflow(props.id ?? 'new', tab))}
+ tabs={tabs}
+ sceneInset
+ rightSlot={headerInWorkflowBar ? <SceneTitlePanelButton /> : undefined}
+ className={clsx({
+ 'flex flex-col grow [&>div]:flex [&>div]:flex-col [&>div]:grow':
+ currentTab === 'workflow',
+ })}
+ />
+ )}
+ </BindLogic>
+ </SceneContent>
+ )
+ }
- return (
- <SceneContent className="h-full flex flex-col grow" data-attr="workflow-scene">
- <BindLogic logic={workflowLogic} props={workflowProps}>
- <WorkflowSceneHeader {...props} />
- <WorkflowEmailPauseBanner />
- {!isSavedWorkflow && <WorkflowAiEmailDraftStatus {...workflowProps} />}
- {suggestionsAvailable && isSavedWorkflow && <WorkflowSuggestionsNotice id={props.id!} />}
- {/* Only show Logs and Metrics tabs if the workflow has already been created */}
- {!props.id || props.id === 'new' ? (
- <Workflow {...workflowProps} />
- ) : (
- <LemonTabs
- activeKey={activeTab}
- onChange={(tab) => router.actions.push(urls.workflow(props.id ?? 'new', tab))}
- tabs={tabs}
- sceneInset
- className={clsx({
- 'flex flex-col grow [&>div]:flex [&>div]:flex-col [&>div]:grow': currentTab === 'workflow',
- })}
- />
- )}
- </BindLogic>
- </SceneContent>
- )
+ // The tile canvas carries the header in its own bar. Reading the flag here keeps the editor logic off the other tabs.
+ return renderScene(tileCanvasEnabled)
}
diff --git a/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx b/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx
index a58064066610..ee2c20640f0e 100644
--- a/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx
@@ -23,11 +23,19 @@ import { WorkflowSuggestionsMenuItem } from './suggestions/WorkflowSuggestionsMe
import { SaveAsTemplateModal } from './templates/SaveAsTemplateModal'
import { workflowTemplateLogic } from './templates/workflowTemplateLogic'
import { WorkflowActions } from './WorkflowActions'
+import { workflowBackTo } from './workflowBackTo'
import { workflowLogic } from './workflowLogic'
import { WorkflowSceneLogicProps } from './workflowSceneLogic'
import { WorkflowScenePanel } from './WorkflowScenePanel'
-export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.Element => {
+type WorkflowSceneHeaderProps = WorkflowSceneLogicProps & {
+ headerInWorkflowBar?: boolean
+}
+
+export const WorkflowSceneHeader = ({
+ headerInWorkflowBar = false,
+ ...props
+}: WorkflowSceneHeaderProps = {}): JSX.Element => {
const { workflow, hasUnsavedChanges, hasStagedDraft, workflowLoading, workflowUserAccessLevel } =
useValues(workflowLogic)
const { setWorkflowValue, duplicate, archiveWorkflow, publishDraft, discardDraft } = useActions(workflowLogic)
@@ -149,28 +157,27 @@ export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.El
</SceneMenuBarMenu>
</SceneMenuBar>
)}
- <SceneTitleSection
- name={workflow?.name}
- description={workflow?.description}
- resourceType={{ type: 'workflows' }}
- canEdit
- onNameChange={(name) => setWorkflowValue('name', name)}
- onDescriptionChange={(description) => setWorkflowValue('description', description)}
- isLoading={workflowLoading && !workflow}
- renameDebounceMs={200}
- // A broadcast isn't in the workflows list, so going back from here returns to the broadcast.
- forceBackTo={
- workflow?.origin_product === 'broadcasts' && props.id && props.id !== 'new'
- ? { key: 'broadcast', name: workflow.name || 'the broadcast', path: urls.broadcast(props.id) }
- : undefined
- }
- actions={
- <>
- <WorkflowActions {...props} />
- {isSavedWorkflow && <WorkflowScenePanel {...props} />}
- </>
- }
- />
+ {headerInWorkflowBar ? (
+ isSavedWorkflow && <WorkflowScenePanel {...props} />
+ ) : (
+ <SceneTitleSection
+ name={workflow?.name}
+ description={workflow?.description}
+ resourceType={{ type: 'workflows' }}
+ canEdit
+ onNameChange={(name) => setWorkflowValue('name', name)}
+ onDescriptionChange={(description) => setWorkflowValue('description', description)}
+ isLoading={workflowLoading && !workflow}
+ renameDebounceMs={200}
+ forceBackTo={workflowBackTo(workflow, props.id)}
+ actions={
+ <>
+ <WorkflowActions {...props} />
+ {isSavedWorkflow && <WorkflowScenePanel {...props} />}
+ </>
+ }
+ />
+ )}
</>
)
}
diff --git a/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsx b/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsx
index 34d1abaa8af0..993165f08880 100644
--- a/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsx
@@ -20,6 +20,7 @@ import { IconInfo } from '@posthog/icons'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
import { workflowLogic } from '../workflowLogic'
+import { TileCanvas } from './editor/tile-canvas/TileCanvas'
import { HogFlowBranchSelectionProvider } from './HogFlowBranchSelection'
import { hogFlowEditorLogic } from './hogFlowEditorLogic'
import { HogFlowEditorPanel } from './panel/HogFlowEditorPanel'
@@ -146,7 +147,13 @@ function HogFlowTreeEditorContent(): JSX.Element {
)
}
-export function HogFlowEditor({ isTreeView }: { isTreeView: boolean }): JSX.Element {
+export function HogFlowEditor({
+ isTreeView,
+ isTileCanvas = false,
+}: {
+ isTreeView: boolean
+ isTileCanvas?: boolean
+}): JSX.Element {
const { logicProps } = useValues(workflowLogic)
return (
<BindLogic logic={hogFlowEditorLogic} props={logicProps}>
@@ -156,6 +163,10 @@ export function HogFlowEditor({ isTreeView }: { isTreeView: boolean }): JSX.Elem
<ReactFlowProvider>
<HogFlowTreeEditorContent />
</ReactFlowProvider>
+ ) : isTileCanvas ? (
+ <ReactFlowProvider>
+ <TileCanvas />
+ </ReactFlowProvider>
) : (
<ReactFlowProvider>
<HogFlowGraphEditor />
diff --git a/products/workflows/frontend/Workflows/hogflows/edgeId.ts b/products/workflows/frontend/Workflows/hogflows/edgeId.ts
index 44b4bb6b8064..bb21d007d095 100644
--- a/products/workflows/frontend/Workflows/hogflows/edgeId.ts
+++ b/products/workflows/frontend/Workflows/hogflows/edgeId.ts
@@ -1,6 +1,6 @@
import type { HogFlowEdge } from './types'
-/** One id per workflow edge, so every editor surface that draws an edge names it the same way. */
+/** One id per edge for both editors, so a + on the tile canvas finds the graph editor's dropzone for the same edge. */
export function getEdgeId(edge: HogFlowEdge): string {
return `${edge.from}->${edge.to} ${edge.type} ${edge.index ?? ''}`.trim()
}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/CanvasCommandButtons.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/CanvasCommandButtons.tsx
new file mode 100644
index 000000000000..820896dba251
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/CanvasCommandButtons.tsx
@@ -0,0 +1,61 @@
+import { useActions, useValues } from 'kea'
+
+import { IconEllipsis } from '@posthog/icons'
+import { LemonButton, LemonMenu } from '@posthog/lemon-ui'
+
+import { tileCanvasLogic } from './tileCanvasLogic'
+import { useCanvasCommands } from './useCanvasCommands'
+
+export function CanvasCommandButtons(): JSX.Element {
+ const { panelMode } = useValues(tileCanvasLogic)
+ const { togglePanel } = useActions(tileCanvasLogic)
+ const { panel, morePanels, view } = useCanvasCommands()
+ const moreIsActive = morePanels.some((command) => command.mode === panelMode)
+
+ return (
+ <div className="flex flex-wrap items-center gap-1" data-attr="workflow-tile-commands">
+ {panel.map((command) => (
+ <LemonButton
+ key={command.id}
+ size="small"
+ icon={command.icon}
+ active={panelMode === command.mode}
+ onClick={() => togglePanel(command.mode)}
+ data-attr={`workflow-tile-command-${command.id}`}
+ >
+ {command.label}
+ </LemonButton>
+ ))}
+ <LemonMenu
+ items={[
+ {
+ items: morePanels.map((command) => ({
+ label: command.label,
+ icon: command.icon,
+ active: panelMode === command.mode,
+ onClick: () => togglePanel(command.mode),
+ 'data-attr': `workflow-tile-command-${command.id}`,
+ })),
+ },
+ {
+ items: view.map((command) => ({
+ label: command.label,
+ icon: command.icon,
+ onClick: command.run,
+ 'data-attr': `workflow-tile-command-${command.id}`,
+ })),
+ },
+ ]}
+ >
+ <LemonButton
+ size="small"
+ icon={<IconEllipsis />}
+ active={moreIsActive}
+ tooltip="More"
+ aria-label="More canvas commands"
+ data-attr="workflow-tile-command-more"
+ />
+ </LemonMenu>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/CanvasCommandGroup.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/CanvasCommandGroup.tsx
new file mode 100644
index 000000000000..f2e013d3c1ba
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/CanvasCommandGroup.tsx
@@ -0,0 +1,14 @@
+import { BindLogic } from 'kea'
+
+import { WorkflowLogicProps } from '../../../workflowLogic'
+import { CanvasCommandButtons } from './CanvasCommandButtons'
+import { tileCanvasLogic } from './tileCanvasLogic'
+
+/** The workflow bar sits outside the canvas's logic binding, so it binds the canvas logic itself. */
+export function CanvasCommandGroup(props: WorkflowLogicProps): JSX.Element {
+ return (
+ <BindLogic logic={tileCanvasLogic} props={props}>
+ <CanvasCommandButtons />
+ </BindLogic>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/CommandBar.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/CommandBar.tsx
new file mode 100644
index 000000000000..26325754981c
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/CommandBar.tsx
@@ -0,0 +1,50 @@
+import { useActions, useValues } from 'kea'
+import { useMemo, useRef } from 'react'
+
+import { IconPlus } from '@posthog/icons'
+
+import { StepPalette } from './StepPalette'
+import { tileCanvasLogic } from './tileCanvasLogic'
+import { CanvasCommand, useCanvasCommands } from './useCanvasCommands'
+
+export function CommandBar(): JSX.Element {
+ const triggerRef = useRef<HTMLButtonElement>(null)
+ const { commandPaletteQuery, paletteSections } = useValues(tileCanvasLogic)
+ const { openCommandPalette, closeCommandPalette, startPlacing } = useActions(tileCanvasLogic)
+ const { panel, morePanels, view } = useCanvasCommands()
+ const commands = useMemo((): CanvasCommand[] => [...panel, ...morePanels, ...view], [panel, morePanels, view])
+
+ return (
+ <div className="relative">
+ {commandPaletteQuery !== null && (
+ <div className="absolute bottom-full left-1/2 mb-3 -translate-x-1/2">
+ <StepPalette
+ key={commandPaletteQuery}
+ sections={paletteSections}
+ commands={commands}
+ initialQuery={commandPaletteQuery}
+ placeholder="Add a step or run a command"
+ trigger={triggerRef}
+ onSelectStep={startPlacing}
+ onClose={closeCommandPalette}
+ />
+ </div>
+ )}
+ <button
+ type="button"
+ ref={triggerRef}
+ data-attr="workflow-tile-command-bar"
+ onClick={() => (commandPaletteQuery !== null ? closeCommandPalette() : openCommandPalette())}
+ className="flex w-105 max-w-[calc(100cqw-7rem)] cursor-pointer items-center gap-2 rounded-full border bg-surface-primary px-3 py-2 text-left text-sm shadow-lg hover:border-[var(--color-accent)]"
+ >
+ <span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-[var(--color-accent)] text-white">
+ <IconPlus />
+ </span>
+ <span className="min-w-0 flex-1 truncate text-secondary">Add a step or run a command…</span>
+ <span className="shrink-0 rounded border px-1.5 text-[11px] text-secondary @max-[32rem]/tile-canvas:hidden">
+ Type anywhere
+ </span>
+ </button>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/MiniFlow.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/MiniFlow.tsx
new file mode 100644
index 000000000000..161f960d7956
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/MiniFlow.tsx
@@ -0,0 +1,69 @@
+import { useMemo } from 'react'
+
+import type { HogFlow } from '../../types'
+import { MiniFlowEdges } from './MiniFlowEdges'
+import { MiniFlowPreview } from './MiniFlowPreview'
+import { MiniFlowStep } from './MiniFlowStep'
+import { MINI_TILE_SIZE } from './MiniTile'
+import { actionsById, layoutMiniFlow } from './tileCanvasModel'
+import { useMiniFlowSpotlight } from './useMiniFlowSpotlight'
+
+const SPACING = { tile: MINI_TILE_SIZE, gapX: 30, gapY: 52 }
+const BADGE_ROOM = 16
+
+export function MiniFlow({
+ workflow,
+ memberIds,
+ countOf,
+ open,
+}: {
+ workflow: HogFlow
+ memberIds: string[]
+ countOf: (actionId: string) => number | undefined
+ open: boolean
+}): JSX.Element {
+ const spotlight = useMiniFlowSpotlight(open)
+ const layout = useMemo(() => layoutMiniFlow(workflow, memberIds, SPACING), [workflow, memberIds])
+ const byId = actionsById(workflow)
+ const spotlightNode = layout.nodes.find((node) => node.actionId === spotlight.spotlightId)
+ const spotlightAction = spotlightNode && byId.get(spotlightNode.actionId)
+
+ return (
+ <div
+ className="relative"
+ style={{ width: layout.width, height: layout.height + BADGE_ROOM }}
+ onMouseMove={spotlight.trackPointer}
+ onMouseLeave={spotlight.leaveFlow}
+ >
+ <MiniFlowEdges layout={layout} opacity={open ? (spotlightNode ? 0.35 : 1) : 0} />
+ {layout.nodes.map((node) => {
+ const action = byId.get(node.actionId)
+ return action ? (
+ <MiniFlowStep
+ key={node.actionId}
+ node={node}
+ action={action}
+ workflow={workflow}
+ count={countOf(action.id)}
+ open={open}
+ dimmed={!!spotlightNode && spotlightNode.actionId !== action.id}
+ highlighted={spotlight.spotlightId === action.id}
+ onEnter={() => spotlight.enterStep(node.actionId)}
+ onLeave={() => spotlight.leaveStep(node.actionId)}
+ />
+ ) : null
+ })}
+ {spotlightNode && spotlightAction && (
+ <MiniFlowPreview
+ at={spotlightNode}
+ action={spotlightAction}
+ workflow={workflow}
+ count={countOf(spotlightAction.id)}
+ showPreview={spotlight.showPreview}
+ previewRef={spotlight.previewRef}
+ onEnter={spotlight.enterPreview}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/MiniFlowEdges.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/MiniFlowEdges.tsx
new file mode 100644
index 000000000000..c1bdf8338b97
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/MiniFlowEdges.tsx
@@ -0,0 +1,26 @@
+import type { MiniFlowLayout } from './tileCanvasModel'
+
+const STROKE = { fill: 'none', stroke: 'var(--border-bold)', strokeWidth: 1.25 }
+
+export function MiniFlowEdges({ layout, opacity }: { layout: MiniFlowLayout; opacity: number }): JSX.Element {
+ return (
+ <svg className="absolute inset-0 overflow-visible" width={layout.width} height={layout.height}>
+ {layout.edges.map(({ from, to }, index) => {
+ const midX = (from.x + to.x) / 2
+ return (
+ <g
+ key={index}
+ className="transition-opacity duration-200 motion-reduce:transition-none"
+ style={{ opacity }}
+ >
+ <path d={`M ${from.x} ${from.y} H ${midX} V ${to.y} H ${to.x - 1}`} {...STROKE} />
+ <path
+ d={`M ${to.x - 5} ${to.y - 3} L ${to.x - 1} ${to.y} L ${to.x - 5} ${to.y + 3}`}
+ {...STROKE}
+ />
+ </g>
+ )
+ })}
+ </svg>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/MiniFlowPreview.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/MiniFlowPreview.tsx
new file mode 100644
index 000000000000..f586f090a141
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/MiniFlowPreview.tsx
@@ -0,0 +1,39 @@
+import type { RefObject } from 'react'
+
+import type { HogFlow, HogFlowAction } from '../../types'
+import { MINI_TILE_SIZE } from './MiniTile'
+import { SpotlightCard } from './SpotlightCard'
+import type { Point } from './tileCanvasModel'
+
+const BRIDGE_HEIGHT = 22
+
+/** The top padding is an invisible bridge over the gap, so moving down to the card keeps it open. */
+export function MiniFlowPreview({
+ at,
+ action,
+ workflow,
+ count,
+ showPreview,
+ previewRef,
+ onEnter,
+}: {
+ at: Point
+ action: HogFlowAction
+ workflow: HogFlow
+ count: number | undefined
+ showPreview: boolean
+ previewRef: RefObject<HTMLDivElement>
+ onEnter: () => void
+}): JSX.Element {
+ return (
+ <div
+ className="TileCanvas__appear absolute z-20 -translate-x-1/2"
+ style={{ left: at.x + MINI_TILE_SIZE / 2, top: at.y + MINI_TILE_SIZE, paddingTop: BRIDGE_HEIGHT }}
+ onMouseEnter={onEnter}
+ >
+ <div ref={previewRef}>
+ <SpotlightCard action={action} workflow={workflow} count={count} showPreview={showPreview} />
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/MiniFlowStep.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/MiniFlowStep.tsx
new file mode 100644
index 000000000000..caa08fe183ac
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/MiniFlowStep.tsx
@@ -0,0 +1,42 @@
+import type { HogFlow, HogFlowAction } from '../../types'
+import { MiniTile } from './MiniTile'
+import type { MiniFlowLayout } from './tileCanvasModel'
+
+export function MiniFlowStep({
+ node,
+ action,
+ workflow,
+ count,
+ open,
+ dimmed,
+ highlighted,
+ onEnter,
+ onLeave,
+}: {
+ node: MiniFlowLayout['nodes'][number]
+ action: HogFlowAction
+ workflow: HogFlow
+ count: number | undefined
+ open: boolean
+ dimmed: boolean
+ highlighted: boolean
+ onEnter: () => void
+ onLeave: () => void
+}): JSX.Element {
+ return (
+ <div
+ className="absolute transition-[opacity,transform] duration-200 motion-reduce:transition-none"
+ style={{
+ left: node.x,
+ top: node.y,
+ opacity: open ? 1 : 0,
+ transform: open ? 'none' : 'translateX(-10px) scale(0.85)',
+ transitionDelay: `${node.layer * 40}ms`,
+ }}
+ onMouseEnter={onEnter}
+ onMouseLeave={onLeave}
+ >
+ <MiniTile action={action} workflow={workflow} count={count} dimmed={dimmed} highlighted={highlighted} />
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/MiniTile.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/MiniTile.tsx
new file mode 100644
index 000000000000..8bbc918bb0f4
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/MiniTile.tsx
@@ -0,0 +1,47 @@
+import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
+
+import type { HogFlow, HogFlowAction } from '../../types'
+import { TileBadge } from './TileBadge'
+import { useTileStep } from './useTileStep'
+
+export const MINI_TILE_SIZE = 32
+
+export function MiniTile({
+ action,
+ workflow,
+ count,
+ dimmed,
+ highlighted,
+}: {
+ action: HogFlowAction
+ workflow: HogFlow
+ count: number | undefined
+ dimmed: boolean
+ highlighted: boolean
+}): JSX.Element {
+ const tile = useTileStep(action, workflow)
+ return (
+ <div className={cn('relative transition-opacity duration-150', dimmed && 'opacity-35')}>
+ <div
+ className={cn(
+ 'flex items-center justify-center rounded-lg border-2 bg-surface-primary text-[15px] transition-transform duration-150 motion-reduce:transition-none',
+ highlighted && 'scale-110 shadow-md'
+ )}
+ style={{ width: MINI_TILE_SIZE, height: MINI_TILE_SIZE, borderColor: tile.color, color: tile.color }}
+ >
+ {tile.icon}
+ </div>
+ {tile.badge && (
+ <TileBadge placement="setting" size="mini" color={tile.color}>
+ {tile.badge}
+ </TileBadge>
+ )}
+ {count !== undefined && (
+ <TileBadge placement="count" size="mini">
+ {humanFriendlyLargeNumber(count)}
+ </TileBadge>
+ )}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/PathChip.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/PathChip.tsx
new file mode 100644
index 000000000000..5a90f07c0fd3
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/PathChip.tsx
@@ -0,0 +1,41 @@
+import { NodeProps } from '@xyflow/react'
+import { useActions } from 'kea'
+
+import { IconChevronDown } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+import { motionProps } from './motionProps'
+import { tileCanvasLogic } from './tileCanvasLogic'
+import { pathColor } from './tileCanvasModel'
+import type { PathChipNodeType } from './tileCanvasNodes'
+
+export function PathChip({ data }: NodeProps<PathChipNodeType>): JSX.Element {
+ const { collapsePath } = useActions(tileCanvasLogic)
+ const color = pathColor(data.group.entryEdge)
+ const motionStyle = motionProps(data.motion)
+ return (
+ <div className={cn('-translate-y-1/2', motionStyle.className)} style={motionStyle.style}>
+ <div
+ className="nodrag flex w-max items-center gap-1.5 whitespace-nowrap rounded-full border bg-surface-primary pr-2.5 shadow-sm"
+ style={{ borderColor: color }}
+ >
+ <LemonButton
+ size="xsmall"
+ icon={<IconChevronDown />}
+ tooltip="Collapse this path"
+ data-attr="workflow-tile-collapse-path"
+ onClick={(event) => {
+ event.stopPropagation()
+ collapsePath(data.group.id)
+ }}
+ />
+ <span className="size-2 shrink-0 rounded-full" style={{ backgroundColor: color }} />
+ <span className="text-[13px] font-semibold" style={{ color }}>
+ {data.group.label}
+ </span>
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/PathFrame.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/PathFrame.tsx
new file mode 100644
index 000000000000..64b844c0c70f
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/PathFrame.tsx
@@ -0,0 +1,18 @@
+import { NodeProps } from '@xyflow/react'
+
+import { cn } from 'lib/utils/css-classes'
+
+import { motionProps } from './motionProps'
+import { pathColor, tint } from './tileCanvasModel'
+import type { PathFrameNodeType } from './tileCanvasNodes'
+
+export function PathFrame({ data, width, height }: NodeProps<PathFrameNodeType>): JSX.Element {
+ const color = pathColor(data.group.entryEdge)
+ const motionStyle = motionProps(data.motion)
+ return (
+ <div className={cn('relative', motionStyle.className)} style={{ width, height, ...motionStyle.style }}>
+ <div className="absolute inset-0 rounded-2xl" style={{ backgroundColor: tint(color, 6) }} />
+ <div className="absolute bottom-3 left-0 top-3 w-[3px] rounded-full" style={{ backgroundColor: color }} />
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/PlacementHint.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/PlacementHint.tsx
new file mode 100644
index 000000000000..7ddaef4f3ab2
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/PlacementHint.tsx
@@ -0,0 +1,33 @@
+import { useActions, useValues } from 'kea'
+
+import { IconX } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { tileCanvasLogic } from './tileCanvasLogic'
+
+export function PlacementHint(): JSX.Element | null {
+ const { nodeToBeAdded, isMovingNode, isCopyingNode } = useValues(tileCanvasLogic)
+ const { cancel } = useActions(tileCanvasLogic)
+ const action = isMovingNode ? 'move the step there' : isCopyingNode ? 'copy the step there' : null
+ if (!action && !nodeToBeAdded) {
+ return null
+ }
+ return (
+ <div className="flex items-center gap-2 rounded-full border bg-surface-primary py-1 pl-3 pr-1 text-sm shadow">
+ <span>
+ {action ? (
+ <>Click a highlighted + to {action}</>
+ ) : (
+ <>
+ Click a highlighted + to add{' '}
+ <strong>
+ {nodeToBeAdded && 'data' in nodeToBeAdded ? nodeToBeAdded.data.name : nodeToBeAdded?.name}
+ </strong>
+ </>
+ )}
+ </span>
+ <span className="text-secondary">· Esc to cancel</span>
+ <LemonButton size="xsmall" icon={<IconX />} tooltip="Cancel" onClick={cancel} />
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/QuickAddButton.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/QuickAddButton.tsx
new file mode 100644
index 000000000000..2571efa06029
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/QuickAddButton.tsx
@@ -0,0 +1,64 @@
+import { useActions, useValues } from 'kea'
+import { useRef } from 'react'
+
+import { IconPlus } from '@posthog/icons'
+
+import { Popover } from 'lib/lemon-ui/Popover'
+import { cn } from 'lib/utils/css-classes'
+
+import { getEdgeId } from '../../edgeId'
+import type { HogFlowEdge } from '../../types'
+import { StepPalette } from './StepPalette'
+import { tileCanvasLogic } from './tileCanvasLogic'
+import { Point } from './tileCanvasModel'
+
+export function QuickAddButton({ edge, at }: { edge: HogFlowEdge; at: Point }): JSX.Element {
+ const buttonRef = useRef<HTMLButtonElement>(null)
+ const { quickAddEdgeKey, isPlacing, paletteSections } = useValues(tileCanvasLogic)
+ const { openQuickAdd, closeQuickAdd, addStepAt, placeAt, onDrop } = useActions(tileCanvasLogic)
+ const key = getEdgeId(edge)
+ const isOpen = quickAddEdgeKey === key
+
+ return (
+ <div
+ className="nodrag nopan pointer-events-auto absolute"
+ style={{ transform: `translate(-50%, -50%) translate(${at.x}px, ${at.y}px)` }}
+ onDragOver={(event) => event.preventDefault()}
+ onDrop={(event) => {
+ event.preventDefault()
+ onDrop(undefined, edge)
+ }}
+ >
+ <Popover
+ visible={isOpen}
+ placement="right-start"
+ overlay={
+ <StepPalette
+ sections={paletteSections}
+ placeholder="Search steps"
+ trigger={buttonRef}
+ onSelectStep={(step) => addStepAt(step, edge)}
+ onClose={closeQuickAdd}
+ />
+ }
+ >
+ <button
+ type="button"
+ ref={buttonRef}
+ aria-label={isPlacing ? 'Place the step here' : 'Add a step here'}
+ title={isPlacing ? 'Place the step here' : 'Add a step here'}
+ data-attr="workflow-tile-quick-add"
+ onClick={() => (isPlacing ? placeAt(edge) : isOpen ? closeQuickAdd() : openQuickAdd(key))}
+ className={cn(
+ 'flex size-5 cursor-pointer items-center justify-center rounded-full border bg-surface-primary text-secondary transition-all hover:scale-125 hover:border-[var(--color-accent)] hover:text-[var(--color-accent)] motion-reduce:transition-none',
+ isPlacing || isOpen
+ ? 'scale-125 border-[var(--color-accent)] text-[var(--color-accent)] shadow'
+ : 'opacity-60'
+ )}
+ >
+ <IconPlus className="text-xs" />
+ </button>
+ </Popover>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/SpotlightCard.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/SpotlightCard.tsx
new file mode 100644
index 000000000000..b93e51a22863
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/SpotlightCard.tsx
@@ -0,0 +1,45 @@
+import type { HogFlow, HogFlowAction } from '../../types'
+import { StepPreview } from './step-preview/StepPreview'
+import { StepCountLine } from './StepCountLine'
+import { useTileStep } from './useTileStep'
+
+export function SpotlightCard({
+ action,
+ workflow,
+ count,
+ showPreview,
+}: {
+ action: HogFlowAction
+ workflow: HogFlow
+ count: number | undefined
+ showPreview: boolean
+}): JSX.Element {
+ const tile = useTileStep(action, workflow)
+ return (
+ <div
+ className="w-65 rounded-xl border bg-surface-primary p-2.5 text-left shadow-lg"
+ style={{ borderColor: tile.color }}
+ >
+ <div className="text-[10px] font-semibold uppercase tracking-wider" style={{ color: tile.color }}>
+ {tile.label}
+ </div>
+ <div className="ph-no-capture">
+ <div className="break-words text-[12.5px] font-semibold leading-snug">{tile.facts.headline}</div>
+ {tile.facts.detail && (
+ <div className="break-words text-[11.5px] leading-snug text-secondary">{tile.facts.detail}</div>
+ )}
+ </div>
+ <div
+ className="grid transition-[grid-template-rows,opacity] duration-200 motion-reduce:transition-none"
+ style={{ gridTemplateRows: showPreview ? '1fr' : '0fr', opacity: showPreview ? 1 : 0 }}
+ >
+ <div className="min-h-0 overflow-hidden">
+ <div className="mt-2 flex flex-col gap-2 border-t pt-2 text-xs">
+ <StepPreview action={action} tile={tile} />
+ <StepCountLine count={count} />
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StackCoverIcon.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StackCoverIcon.tsx
new file mode 100644
index 000000000000..29a5b07a8d7d
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StackCoverIcon.tsx
@@ -0,0 +1,15 @@
+import type { HogFlow, HogFlowAction } from '../../types'
+import { tint } from './tileCanvasModel'
+import { useTileStep } from './useTileStep'
+
+export function StackCoverIcon({ action, workflow }: { action: HogFlowAction; workflow: HogFlow }): JSX.Element {
+ const tile = useTileStep(action, workflow)
+ return (
+ <span
+ className="flex size-[22px] items-center justify-center rounded text-[14px]"
+ style={{ color: tile.color, backgroundColor: tint(tile.color, 10) }}
+ >
+ {tile.icon}
+ </span>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StackPeek.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StackPeek.tsx
new file mode 100644
index 000000000000..4a0398c57ee9
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StackPeek.tsx
@@ -0,0 +1,66 @@
+import { useEffect, useRef, useState } from 'react'
+
+import { cn } from 'lib/utils/css-classes'
+
+import type { HogFlow } from '../../types'
+import { MiniFlow } from './MiniFlow'
+import { TILE_SIZE } from './tileCanvasLayout'
+import type { PathGroup } from './tileCanvasModel'
+import { useKeepInView } from './useKeepInView'
+
+/** A closed peek renders no mini flow, so a stack of hidden steps costs nothing until someone looks inside. */
+function useHasOpened(open: boolean): boolean {
+ const [hasOpened, setHasOpened] = useState(open)
+ useEffect(() => {
+ if (open) {
+ setHasOpened(true)
+ }
+ }, [open])
+ return hasOpened || open
+}
+
+export function StackPeek({
+ group,
+ workflow,
+ color,
+ open,
+ countOf,
+}: {
+ group: PathGroup
+ workflow: HogFlow
+ color: string
+ open: boolean
+ countOf: (actionId: string) => number | undefined
+}): JSX.Element {
+ const ref = useRef<HTMLDivElement>(null)
+ const shift = useKeepInView(ref, open)
+ const hasOpened = useHasOpened(open)
+ return (
+ <div
+ ref={ref}
+ className={cn(
+ 'absolute z-10 rounded-2xl border bg-surface-primary p-3 shadow-xl transition-opacity duration-150 motion-reduce:transition-none',
+ open ? 'visible opacity-100' : 'invisible opacity-0'
+ )}
+ style={{
+ left: TILE_SIZE + 12,
+ top: -14,
+ transform: `translate(${shift.x}px, ${shift.y}px)`,
+ borderColor: color,
+ }}
+ >
+ <div className="mb-3 flex items-center gap-1.5 whitespace-nowrap text-[11px]">
+ <span className="size-2 rounded-full" style={{ backgroundColor: color }} />
+ <span className="font-semibold" style={{ color }}>
+ {group.label}
+ </span>
+ <span className="text-secondary">{group.memberIds.length} steps, click to open</span>
+ </div>
+ <div className="px-1 pt-1">
+ {hasOpened && (
+ <MiniFlow workflow={workflow} memberIds={group.memberIds} countOf={countOf} open={open} />
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepCountLine.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepCountLine.tsx
new file mode 100644
index 000000000000..6245784d00d3
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepCountLine.tsx
@@ -0,0 +1,13 @@
+export function StepCountLine({ count }: { count: number | undefined }): JSX.Element | null {
+ if (count === undefined) {
+ return null
+ }
+ return (
+ <div className="text-xs">
+ <span className="font-semibold" translate="no">
+ {count.toLocaleString()}
+ </span>
+ <span className="text-secondary">&nbsp;{count === 1 ? 'person' : 'people'} reached this step</span>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepFieldList.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepFieldList.tsx
new file mode 100644
index 000000000000..9ef27101cc9b
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepFieldList.tsx
@@ -0,0 +1,17 @@
+import type { StepFacts } from './stepFacts'
+
+export function StepFieldList({ facts }: { facts: StepFacts }): JSX.Element | null {
+ if (!facts.fields.length) {
+ return null
+ }
+ return (
+ <dl className="ph-no-capture m-0 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-left text-[12.5px] leading-snug">
+ {facts.fields.map(([label, value]) => (
+ <div key={label} className="contents">
+ <dt className="text-secondary">{label}</dt>
+ <dd className="m-0 min-w-0 break-words">{value}</dd>
+ </div>
+ ))}
+ </dl>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepIcon.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepIcon.tsx
new file mode 100644
index 000000000000..f1e9e3183a53
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepIcon.tsx
@@ -0,0 +1,17 @@
+import type { CreateActionType } from '../../hogFlowEditorLogic'
+import { useHogFlowStep } from '../../steps/HogFlowSteps'
+import type { HogFlowAction } from '../../types'
+import { tint } from './tileCanvasModel'
+
+export function StepIcon({ step }: { step: CreateActionType }): JSX.Element {
+ const look = useHogFlowStep(step as HogFlowAction)
+ const color = look?.color ?? 'var(--color-text-secondary)'
+ return (
+ <span
+ className="flex size-6 shrink-0 items-center justify-center rounded text-[14px]"
+ style={{ color, backgroundColor: tint(color, 10) }}
+ >
+ {look?.icon}
+ </span>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepPalette.test.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepPalette.test.tsx
new file mode 100644
index 000000000000..ba90322c1c33
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepPalette.test.tsx
@@ -0,0 +1,74 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { createRef } from 'react'
+
+import { initKeaTests } from '~/test/init'
+
+import { StepPalette } from './StepPalette'
+import type { PaletteSection } from './tileCanvasModel'
+
+const SECTIONS: PaletteSection[] = [
+ {
+ title: 'Delays',
+ steps: [
+ { type: 'delay', name: 'Delay', description: 'Pause.', config: { delay_duration: '1h' } },
+ { type: 'wait_until_time_window', name: 'Time window', description: 'Hold.', config: {} as any },
+ ],
+ },
+]
+
+function renderPalette(): { onSelectStep: jest.Mock; onClose: jest.Mock; trigger: HTMLButtonElement } {
+ const onSelectStep = jest.fn()
+ const onClose = jest.fn()
+ const triggerRef = createRef<HTMLButtonElement>()
+ render(
+ <>
+ <button ref={triggerRef}>Add a step here</button>
+ <StepPalette
+ sections={SECTIONS}
+ placeholder="Search steps"
+ trigger={triggerRef}
+ onSelectStep={onSelectStep}
+ onClose={onClose}
+ />
+ </>
+ )
+ return { onSelectStep, onClose, trigger: triggerRef.current as HTMLButtonElement }
+}
+
+describe('StepPalette', () => {
+ beforeEach(() => initKeaTests())
+ afterEach(() => cleanup())
+
+ it('points the search box at the highlighted option as the arrow keys move', () => {
+ renderPalette()
+ const search = screen.getByRole('combobox')
+
+ fireEvent.keyDown(search, { key: 'ArrowDown' })
+
+ const highlighted = screen.getByRole('option', { selected: true })
+ expect(highlighted).toHaveTextContent('Time window')
+ expect(search).toHaveAttribute('aria-activedescendant', highlighted.id)
+ expect(screen.getByRole('listbox')).toContainElement(highlighted)
+ })
+
+ it('leaves Enter to an input method that is still composing a word', () => {
+ const { onSelectStep } = renderPalette()
+
+ fireEvent.keyDown(screen.getByRole('combobox'), { key: 'Enter', isComposing: true })
+ expect(onSelectStep).not.toHaveBeenCalled()
+
+ fireEvent.keyDown(screen.getByRole('combobox'), { key: 'Enter' })
+ expect(onSelectStep).toHaveBeenCalledWith(SECTIONS[0].steps[0])
+ })
+
+ it('gives focus back to the button that opened it on Escape', () => {
+ const { onClose, trigger } = renderPalette()
+
+ fireEvent.keyDown(screen.getByRole('combobox'), { key: 'Escape' })
+
+ expect(onClose).toHaveBeenCalled()
+ expect(trigger).toHaveFocus()
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepPalette.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepPalette.tsx
new file mode 100644
index 000000000000..b757aab3c222
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepPalette.tsx
@@ -0,0 +1,165 @@
+import { KeyboardEvent, RefObject, useEffect, useId, useMemo, useRef, useState } from 'react'
+
+import { LemonInput } from '@posthog/lemon-ui'
+
+import type { CreateActionType } from '../../hogFlowEditorLogic'
+import { StepPaletteRow } from './StepPaletteRow'
+import { filterPaletteItems, PaletteItem, PaletteSection } from './tileCanvasModel'
+import type { CanvasCommand } from './useCanvasCommands'
+import { useComboboxInput } from './useComboboxInput'
+
+type PaletteKeyCommand = 'next' | 'previous' | 'choose' | 'close'
+
+function paletteKeyCommand(event: KeyboardEvent<HTMLElement>): PaletteKeyCommand | null {
+ switch (event.key) {
+ case 'ArrowDown':
+ return 'next'
+ case 'ArrowUp':
+ return 'previous'
+ case 'Enter':
+ return event.nativeEvent.isComposing ? null : 'choose'
+ case 'Escape':
+ return 'close'
+ default:
+ return null
+ }
+}
+
+/** A click on the trigger is left to the trigger, which toggles the palette. */
+function useCloseOnPointerOutside(
+ rootRef: RefObject<HTMLElement>,
+ trigger: RefObject<HTMLElement> | undefined,
+ onClose: () => void
+): void {
+ useEffect(() => {
+ const onPointerDown = (event: PointerEvent): void => {
+ const target = event.target as Node
+ if (!rootRef.current?.contains(target) && !trigger?.current?.contains(target)) {
+ onClose()
+ }
+ }
+ document.addEventListener('pointerdown', onPointerDown, true)
+ return () => document.removeEventListener('pointerdown', onPointerDown, true)
+ }, [rootRef, onClose, trigger])
+}
+
+const startsSection = (items: PaletteItem<CanvasCommand>[], index: number): boolean =>
+ index === 0 || items[index - 1].section !== items[index].section
+
+export function StepPalette({
+ sections,
+ commands = [],
+ initialQuery = '',
+ placeholder,
+ trigger,
+ onSelectStep,
+ onClose,
+}: {
+ sections: PaletteSection[]
+ commands?: CanvasCommand[]
+ initialQuery?: string
+ placeholder: string
+ trigger?: RefObject<HTMLElement>
+ onSelectStep: (step: CreateActionType) => void
+ onClose: () => void
+}): JSX.Element {
+ const [query, setQuery] = useState(initialQuery)
+ const [activeIndex, setActiveIndex] = useState(0)
+ const rootRef = useRef<HTMLDivElement>(null)
+ const listRef = useRef<HTMLDivElement>(null)
+ const inputRef = useRef<HTMLInputElement>(null)
+ const listId = useId()
+ const optionId = (index: number): string => `${listId}-option-${index}`
+ const items = useMemo(() => filterPaletteItems(query, sections, commands), [query, sections, commands])
+ useComboboxInput(inputRef, listId, items.length ? optionId(activeIndex) : undefined)
+ useCloseOnPointerOutside(rootRef, trigger, onClose)
+
+ useEffect(() => setActiveIndex(0), [query])
+ useEffect(() => {
+ listRef.current?.querySelector(`[data-index="${activeIndex}"]`)?.scrollIntoView({ block: 'nearest' })
+ }, [activeIndex])
+
+ const choose = (item: PaletteItem<CanvasCommand> | undefined): void => {
+ if (!item) {
+ return
+ }
+ onClose()
+ if (item.kind === 'step') {
+ onSelectStep(item.step)
+ } else {
+ item.command.run()
+ }
+ }
+
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {
+ const command = paletteKeyCommand(event)
+ if (command === 'close') {
+ event.stopPropagation()
+ onClose()
+ trigger?.current?.focus()
+ return
+ }
+ if (!command) {
+ return
+ }
+ event.preventDefault()
+ if (command === 'next') {
+ setActiveIndex(Math.min(activeIndex + 1, items.length - 1))
+ } else if (command === 'previous') {
+ setActiveIndex(Math.max(activeIndex - 1, 0))
+ } else {
+ choose(items[activeIndex])
+ }
+ }
+
+ return (
+ <div
+ ref={rootRef}
+ className="flex w-95 max-w-[calc(100cqw-2rem)] flex-col overflow-hidden rounded-lg border bg-surface-primary shadow-xl"
+ data-attr="workflow-step-palette"
+ onKeyDown={onKeyDown}
+ >
+ <div className="border-b p-2">
+ <LemonInput
+ autoFocus
+ fullWidth
+ inputRef={inputRef}
+ placeholder={placeholder}
+ value={query}
+ onChange={setQuery}
+ />
+ </div>
+ <div
+ ref={listRef}
+ id={listId}
+ role="listbox"
+ aria-label={placeholder}
+ className="max-h-90 overflow-y-auto p-1"
+ >
+ {items.length === 0 && <div className="p-3 text-sm text-secondary">Nothing matches your search.</div>}
+ {items.map((item, index) => (
+ <div key={item.key}>
+ {startsSection(items, index) && (
+ <div className="px-2 pb-0.5 pt-2 text-[10px] font-semibold uppercase tracking-wider text-secondary">
+ {item.section}
+ </div>
+ )}
+ <StepPaletteRow
+ item={item}
+ id={optionId(index)}
+ index={index}
+ active={index === activeIndex}
+ onHover={() => setActiveIndex(index)}
+ onChoose={() => choose(item)}
+ />
+ </div>
+ ))}
+ </div>
+ <div className="flex gap-3 border-t px-3 py-1.5 text-[11px] text-secondary">
+ <span>↑↓ to move</span>
+ <span>Enter to choose</span>
+ <span>Esc to close</span>
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepPaletteRow.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepPaletteRow.tsx
new file mode 100644
index 000000000000..f2fcf5840a51
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/StepPaletteRow.tsx
@@ -0,0 +1,51 @@
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { StepIcon } from './StepIcon'
+import type { PaletteItem } from './tileCanvasModel'
+import type { CanvasCommand } from './useCanvasCommands'
+
+export function StepPaletteRow({
+ item,
+ id,
+ index,
+ active,
+ onHover,
+ onChoose,
+}: {
+ item: PaletteItem<CanvasCommand>
+ id: string
+ index: number
+ active: boolean
+ onHover: () => void
+ onChoose: () => void
+}): JSX.Element {
+ return (
+ <LemonButton
+ fullWidth
+ size="small"
+ id={id}
+ role="option"
+ {...{ 'aria-selected': active }}
+ data-index={index}
+ active={active}
+ icon={
+ item.kind === 'step' ? (
+ <StepIcon step={item.step} />
+ ) : (
+ <span className="flex size-6 shrink-0 items-center justify-center rounded bg-surface-secondary text-[14px]">
+ {item.command.icon}
+ </span>
+ )
+ }
+ onMouseEnter={onHover}
+ onClick={onChoose}
+ >
+ <span className="flex min-w-0 flex-col text-left">
+ <span className="text-[13px] font-semibold">{item.label}</span>
+ {item.description && (
+ <span className="truncate text-[11.5px] font-normal text-secondary">{item.description}</span>
+ )}
+ </span>
+ </LemonButton>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileBadge.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileBadge.tsx
new file mode 100644
index 000000000000..3baff71d8843
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileBadge.tsx
@@ -0,0 +1,33 @@
+import { cn } from 'lib/utils/css-classes'
+
+export function TileBadge({
+ children,
+ placement,
+ color,
+ size = 'default',
+}: {
+ children: React.ReactNode
+ placement: 'count' | 'setting'
+ color?: string
+ size?: 'default' | 'mini'
+}): JSX.Element {
+ return (
+ <span
+ className={cn(
+ 'pointer-events-none absolute z-[2] whitespace-nowrap rounded-full border bg-surface-primary font-semibold',
+ size === 'mini' ? 'px-1 text-[9.5px] leading-[14px]' : 'px-1.5 text-[11px] leading-[18px] shadow-sm',
+ placement === 'count'
+ ? size === 'mini'
+ ? '-right-2.5 -top-2'
+ : '-right-3 -top-2.5'
+ : size === 'mini'
+ ? 'left-1/2 top-full mt-0.5 -translate-x-1/2'
+ : '-bottom-2 left-1/2 -translate-x-1/2'
+ )}
+ style={color ? { color } : undefined}
+ translate="no"
+ >
+ {children}
+ </span>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvas.scss b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvas.scss
new file mode 100644
index 000000000000..501bea557bf9
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvas.scss
@@ -0,0 +1,120 @@
+.TileCanvas {
+ --tile-canvas-edge: var(--border-bold);
+}
+
+[theme='dark'] .TileCanvas {
+ --tile-canvas-edge: var(--color-text-tertiary);
+}
+
+// Steps fly out of a stack when it opens and back into it when the path closes, while the rest of the
+// canvas glides to its new place. Each moving node sets --tile-canvas-dx and --tile-canvas-dy to the
+// distance from its new spot to the stack.
+@keyframes TileCanvas__enter {
+ from {
+ opacity: 0;
+ transform: translate(var(--tile-canvas-dx), var(--tile-canvas-dy)) scale(0.4);
+ }
+}
+
+@keyframes TileCanvas__leave {
+ to {
+ opacity: 0;
+ transform: translate(var(--tile-canvas-dx), var(--tile-canvas-dy)) scale(0.4);
+ }
+}
+
+@keyframes TileCanvas__pop {
+ from {
+ opacity: 0;
+ transform: scale(0.6);
+ }
+}
+
+@keyframes TileCanvas__fadeIn {
+ from {
+ opacity: 0;
+ }
+}
+
+@keyframes TileCanvas__fadeOut {
+ to {
+ opacity: 0;
+ }
+}
+
+@keyframes TileCanvas__edges {
+ 0%,
+ 55% {
+ opacity: 0;
+ }
+
+ 100% {
+ opacity: 1;
+ }
+}
+
+.TileCanvas__motion--enter {
+ animation: TileCanvas__enter 460ms cubic-bezier(0.2, 0.8, 0.2, 1) both;
+}
+
+.TileCanvas__motion--leave {
+ animation: TileCanvas__leave 260ms cubic-bezier(0.4, 0, 1, 1) forwards;
+}
+
+.TileCanvas__motion--pop {
+ animation: TileCanvas__pop 320ms cubic-bezier(0.2, 0.8, 0.2, 1) 200ms both;
+}
+
+.TileCanvas__motion--fade-in {
+ animation: TileCanvas__fadeIn 380ms ease 180ms both;
+}
+
+.TileCanvas__motion--fade-out {
+ animation: TileCanvas__fadeOut 160ms ease forwards;
+}
+
+.TileCanvas__appear {
+ animation: TileCanvas__fadeIn 160ms ease both;
+}
+
+.TileCanvas--moving {
+ .react-flow__node,
+ .react-flow__viewport {
+ transition: transform 420ms cubic-bezier(0.2, 0.8, 0.2, 1);
+ }
+
+ .react-flow__edges,
+ .react-flow__edgelabel-renderer {
+ animation: TileCanvas__edges 760ms ease both;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .TileCanvas__motion--enter,
+ .TileCanvas__motion--leave,
+ .TileCanvas__motion--pop,
+ .TileCanvas__motion--fade-in,
+ .TileCanvas__motion--fade-out,
+ .TileCanvas__appear,
+ .TileCanvas--moving .react-flow__edges,
+ .TileCanvas--moving .react-flow__edgelabel-renderer {
+ animation: none;
+ }
+
+ .TileCanvas--moving .react-flow__node,
+ .TileCanvas--moving .react-flow__viewport {
+ transition: none;
+ }
+}
+
+// React Flow focuses the node wrapper, whose box spans the tile and its caption, so the default
+// outline draws a square around both. The ring goes on the tile face instead.
+.TileCanvas .react-flow__node:focus-visible {
+ outline: none;
+}
+
+.TileCanvas .react-flow__node:focus-visible [data-tile-anchor] {
+ border-radius: 14px;
+ outline: 2px solid var(--color-text-tertiary);
+ outline-offset: 3px;
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvas.stories.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvas.stories.tsx
new file mode 100644
index 000000000000..dc4d9322d749
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvas.stories.tsx
@@ -0,0 +1,101 @@
+import type { Meta, StoryFn } from '@storybook/react'
+import { BindLogic, useActions, useValues } from 'kea'
+import { useEffect } from 'react'
+
+import { SpinnerOverlay } from '@posthog/lemon-ui'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+
+import { workflowLogic } from '../../../workflowLogic'
+import { HogFlowEditor } from '../../HogFlowEditor'
+import type { HogFlowEditorActionMetrics } from '../../hogFlowEditorLogic'
+import { createWorkflowEditorStoryDecorator } from '../workflowEditorStoryFixtures'
+import { tileCanvasLogic } from './tileCanvasLogic'
+import {
+ AI_SUPPORT_TRIAGE,
+ LONG_EMAILS,
+ TICKET_TO_SLACK,
+ TILE_CANVAS_WORKFLOWS,
+ TRIAL_TO_PAID,
+ TRIAL_TO_PAID_METRICS,
+} from './tileCanvasStoryFixtures'
+
+const meta: Meta = {
+ title: 'Products/Workflows/Editor/Tile canvas',
+ parameters: {
+ layout: 'fullscreen',
+ featureFlags: [FEATURE_FLAGS.WORKFLOWS_TILE_CANVAS],
+ mockDate: '2026-10-10 12:00:00',
+ testOptions: {
+ waitForLoadersToDisappear: true,
+ waitForSelector: '.react-flow__node',
+ viewport: { width: 1440, height: 900 },
+ },
+ },
+ decorators: [createWorkflowEditorStoryDecorator(TILE_CANVAS_WORKFLOWS)],
+}
+export default meta
+
+function StoryState({
+ metrics,
+ openAllPaths,
+}: {
+ metrics?: Record<string, HogFlowEditorActionMetrics>
+ openAllPaths?: boolean
+}): null {
+ const { logicProps } = useValues(workflowLogic)
+ const { loadStepCountsSuccess, toggleAllPaths } = useActions(tileCanvasLogic(logicProps))
+ useEffect(() => {
+ if (metrics) {
+ loadStepCountsSuccess(metrics)
+ }
+ if (openAllPaths) {
+ toggleAllPaths()
+ }
+ }, [metrics, openAllPaths, loadStepCountsSuccess, toggleAllPaths])
+ return null
+}
+
+function StoryEditor({
+ metrics,
+ openAllPaths,
+}: {
+ metrics?: Record<string, HogFlowEditorActionMetrics>
+ openAllPaths?: boolean
+}): JSX.Element {
+ const { originalWorkflow } = useValues(workflowLogic)
+ const tileCanvasEnabled = useFeatureFlag('WORKFLOWS_TILE_CANVAS')
+ return (
+ <div className="flex h-full flex-col">
+ {originalWorkflow ? (
+ <>
+ <HogFlowEditor key={originalWorkflow.id} isTreeView={false} isTileCanvas={!!tileCanvasEnabled} />
+ <StoryState metrics={metrics} openAllPaths={openAllPaths} />
+ </>
+ ) : (
+ <SpinnerOverlay />
+ )}
+ </div>
+ )
+}
+
+function canvasStory(
+ id: string,
+ state: { metrics?: Record<string, HogFlowEditorActionMetrics>; openAllPaths?: boolean } = {}
+): StoryFn {
+ const Story: StoryFn = () => (
+ <BindLogic logic={workflowLogic} props={{ id }}>
+ <div className="h-screen">
+ <StoryEditor {...state} />
+ </div>
+ </BindLogic>
+ )
+ return Story
+}
+
+export const PathsCollapsed = canvasStory(AI_SUPPORT_TRIAGE.id)
+export const PathsOpen = canvasStory(AI_SUPPORT_TRIAGE.id, { openAllPaths: true })
+export const WithStepCounts = canvasStory(TRIAL_TO_PAID.id, { metrics: TRIAL_TO_PAID_METRICS })
+export const TimeWindowAndWebhook = canvasStory(TICKET_TO_SLACK.id, { openAllPaths: true })
+export const LongEmails = canvasStory(LONG_EMAILS.id)
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvas.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvas.tsx
new file mode 100644
index 000000000000..de133b8b2573
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvas.tsx
@@ -0,0 +1,16 @@
+import './TileCanvas.scss'
+
+import { BindLogic, useValues } from 'kea'
+
+import { workflowLogic } from '../../../workflowLogic'
+import { TileCanvasContent } from './TileCanvasContent'
+import { tileCanvasLogic } from './tileCanvasLogic'
+
+export function TileCanvas(): JSX.Element {
+ const { logicProps } = useValues(workflowLogic)
+ return (
+ <BindLogic logic={tileCanvasLogic} props={logicProps}>
+ <TileCanvasContent />
+ </BindLogic>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasContent.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasContent.tsx
new file mode 100644
index 000000000000..c29841a64353
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasContent.tsx
@@ -0,0 +1,161 @@
+import { Background, BackgroundVariant, EdgeTypes, NodeTypes, Panel, ReactFlow } from '@xyflow/react'
+import { useActions, useValues } from 'kea'
+import { KeyboardEvent, useMemo, useRef } from 'react'
+
+import { cn } from 'lib/utils/css-classes'
+
+import { themeLogic } from '~/layout/navigation-3000/themeLogic'
+
+import { CommandBar } from './CommandBar'
+import { PathChip } from './PathChip'
+import { PathFrame } from './PathFrame'
+import { PlacementHint } from './PlacementHint'
+import { TileCanvasControls } from './TileCanvasControls'
+import { TileCanvasLayoutError } from './TileCanvasLayoutError'
+import { tileCanvasLogic } from './tileCanvasLogic'
+import { TileCanvasMeasureLayer } from './TileCanvasMeasureLayer'
+import { CANVAS_MIN_ZOOM, hasStepMenu } from './tileCanvasModel'
+import { buildCanvasEdges, buildCanvasNodes, keepUnchangedNodes, TileCanvasNode, TileEdgeType } from './tileCanvasNodes'
+import { TileCanvasPanel } from './TileCanvasPanel'
+import { TileEdge } from './TileEdge'
+import { TileFlowNode } from './TileFlowNode'
+import { useCanvasViewport } from './useCanvasViewport'
+
+const NODE_TYPES = { tile: TileFlowNode, frame: PathFrame, chip: PathChip } as NodeTypes
+const EDGE_TYPES = { tile: TileEdge } as EdgeTypes
+const MAX_ZOOM = 1.5
+
+type TileKeyCommand = 'activate' | 'menu'
+
+function tileKeyCommand(event: KeyboardEvent<HTMLElement>): TileKeyCommand | null {
+ if (event.key === 'Enter' || event.key === ' ') {
+ return 'activate'
+ }
+ return event.key === 'ContextMenu' || (event.shiftKey && event.key === 'F10') ? 'menu' : null
+}
+
+/** React Flow focuses its own node wrapper, which carries the node id. */
+function focusedTileId(event: KeyboardEvent<HTMLElement>): string | undefined {
+ const target = event.target as HTMLElement
+ return target.classList.contains('react-flow__node-tile') ? target.dataset.id : undefined
+}
+
+export function TileCanvasContent(): JSX.Element {
+ const wrapperRef = useRef<HTMLDivElement>(null)
+ const { isDarkModeOn } = useValues(themeLogic)
+ const {
+ drawnGraph,
+ frameSpecs,
+ layout,
+ motion,
+ isPanelOpen,
+ commandPaletteQuery,
+ layoutError,
+ workflow,
+ pathGroups,
+ measuredSizes,
+ selectedStepId,
+ stepMenuActionId,
+ countOf,
+ templateNameOf,
+ } = useValues(tileCanvasLogic)
+ const { activateNode, openStepMenu, handlePaneClick } = useActions(tileCanvasLogic)
+ useCanvasViewport(wrapperRef)
+
+ const previousNodes = useRef<TileCanvasNode[]>([])
+ const nodes = useMemo(() => {
+ const state = {
+ workflow,
+ groups: pathGroups,
+ motion,
+ sizes: measuredSizes,
+ selectedStepId,
+ menuStepId: stepMenuActionId,
+ countOf,
+ templateNameOf,
+ }
+ previousNodes.current = keepUnchangedNodes(
+ previousNodes.current,
+ buildCanvasNodes(layout, frameSpecs, drawnGraph, state)
+ )
+ return previousNodes.current
+ }, [
+ layout,
+ frameSpecs,
+ drawnGraph,
+ workflow,
+ pathGroups,
+ motion,
+ measuredSizes,
+ selectedStepId,
+ stepMenuActionId,
+ countOf,
+ templateNameOf,
+ ])
+ const edges = useMemo(() => buildCanvasEdges(drawnGraph, layout), [drawnGraph, layout])
+
+ const hasMenu = (nodeId: string): boolean =>
+ drawnGraph.nodes.some((node) => node.id === nodeId && node.kind === 'step' && hasStepMenu(node.action))
+
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {
+ const nodeId = focusedTileId(event)
+ const command = nodeId ? tileKeyCommand(event) : null
+ if (!nodeId || !command) {
+ return
+ }
+ event.preventDefault()
+ if (command === 'activate') {
+ activateNode(nodeId)
+ } else if (hasMenu(nodeId)) {
+ openStepMenu(nodeId, true)
+ }
+ }
+
+ return (
+ <div
+ className={cn(
+ 'TileCanvas relative flex min-h-0 min-w-0 flex-1 overflow-hidden @max-[48rem]/workflow-editor:flex-col @max-[48rem]/workflow-editor:overflow-y-auto',
+ motion && 'TileCanvas--moving'
+ )}
+ data-attr="workflow-editor"
+ >
+ <TileCanvasMeasureLayer />
+ <div
+ ref={wrapperRef}
+ onKeyDown={onKeyDown}
+ className="TileCanvas__flow @container/tile-canvas relative flex min-h-0 min-w-0 grow @max-[48rem]/workflow-editor:min-h-80 @max-[48rem]/workflow-editor:shrink-0"
+ >
+ <ReactFlow<TileCanvasNode, TileEdgeType>
+ className="grow"
+ nodes={nodes}
+ edges={edges}
+ nodeTypes={NODE_TYPES}
+ edgeTypes={EDGE_TYPES}
+ minZoom={CANVAS_MIN_ZOOM}
+ maxZoom={MAX_ZOOM}
+ panOnScroll
+ zoomOnScroll={false}
+ zoomActivationKeyCode={['Meta', 'Control']}
+ nodesDraggable={false}
+ nodesConnectable={false}
+ edgesFocusable={false}
+ colorMode={isDarkModeOn ? 'dark' : 'light'}
+ onNodeClick={(_, node) => activateNode(node.id)}
+ onPaneClick={handlePaneClick}
+ proOptions={{ hideAttribution: true }}
+ >
+ <Background gap={36} variant={BackgroundVariant.Dots} />
+ <Panel position="bottom-center" className="!mb-5">
+ <div className="flex flex-col items-center gap-2">
+ {commandPaletteQuery === null && <PlacementHint />}
+ <CommandBar />
+ </div>
+ </Panel>
+ <TileCanvasControls />
+ </ReactFlow>
+ {layoutError && <TileCanvasLayoutError message={layoutError} />}
+ </div>
+ {isPanelOpen && <TileCanvasPanel />}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasControls.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasControls.tsx
new file mode 100644
index 000000000000..0aae7b173731
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasControls.tsx
@@ -0,0 +1,40 @@
+import { ControlButton, Controls, useReactFlow, useStore } from '@xyflow/react'
+
+import { IconExpand45, IconMinus, IconPlus } from '@posthog/icons'
+
+/** React Flow's own buttons take no data attributes, so the canvas draws its own to keep their use measurable. */
+export function TileCanvasControls(): JSX.Element {
+ const { zoomIn, zoomOut, fitView } = useReactFlow()
+ const atMin = useStore((state) => state.transform[2] <= state.minZoom)
+ const atMax = useStore((state) => state.transform[2] >= state.maxZoom)
+ return (
+ <Controls showZoom={false} showFitView={false} showInteractive={false}>
+ <ControlButton
+ onClick={() => void zoomIn()}
+ disabled={atMax}
+ title="Zoom in"
+ aria-label="Zoom in"
+ data-attr="workflow-tile-zoom-in"
+ >
+ <IconPlus />
+ </ControlButton>
+ <ControlButton
+ onClick={() => void zoomOut()}
+ disabled={atMin}
+ title="Zoom out"
+ aria-label="Zoom out"
+ data-attr="workflow-tile-zoom-out"
+ >
+ <IconMinus />
+ </ControlButton>
+ <ControlButton
+ onClick={() => void fitView()}
+ title="Fit view"
+ aria-label="Fit view"
+ data-attr="workflow-tile-fit-view"
+ >
+ <IconExpand45 />
+ </ControlButton>
+ </Controls>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasLayoutError.test.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasLayoutError.test.tsx
new file mode 100644
index 000000000000..44bf8b46c8b8
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasLayoutError.test.tsx
@@ -0,0 +1,88 @@
+import '@testing-library/jest-dom'
+
+import { act, cleanup, render, screen } from '@testing-library/react'
+import { BindLogic, Provider } from 'kea'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { workflowLogic } from '../../../workflowLogic'
+import type { HogFlow } from '../../types'
+import { TileCanvasLayoutError } from './TileCanvasLayoutError'
+import { tileCanvasLogic } from './tileCanvasLogic'
+
+jest.mock('lib/components/AppMetrics/appMetricsLogic', () => ({
+ ...jest.requireActual('lib/components/AppMetrics/appMetricsLogic'),
+ loadAppMetricsTotals: () => new Promise(() => {}),
+}))
+
+const WORKFLOW_ID = 'wf-layout-error-1'
+
+const WORKFLOW = {
+ id: WORKFLOW_ID,
+ name: 'Layout error test',
+ version: 1,
+ status: 'draft',
+ team_id: 1,
+ exit_condition: 'exit_only_at_end',
+ trigger: { type: 'event', filters: {} },
+ actions: [
+ { id: 'trigger_node', type: 'trigger', name: 'Trigger', config: { type: 'event', filters: {} } },
+ { id: 'exit_node', type: 'exit', name: 'Exit', config: { reason: '' } },
+ ],
+ edges: [{ from: 'trigger_node', to: 'exit_node', type: 'continue' }],
+ created_at: '2026-10-01T00:00:00.000Z',
+ updated_at: '2026-10-01T00:00:00.000Z',
+} as unknown as HogFlow
+
+describe('TileCanvasLayoutError', () => {
+ let flowLogic: ReturnType<typeof workflowLogic.build>
+
+ beforeEach(async () => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/hog_flows/:id/': WORKFLOW,
+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },
+ },
+ })
+ initKeaTests()
+ flowLogic = workflowLogic({ id: WORKFLOW_ID })
+ flowLogic.mount()
+ await act(async () => {
+ await flowLogic.asyncActions.loadWorkflow()
+ })
+ tileCanvasLogic({ id: WORKFLOW_ID }).mount()
+ })
+
+ afterEach(() => cleanup())
+
+ const renderError = (): void => {
+ render(
+ <Provider>
+ <BindLogic logic={workflowLogic} props={{ id: WORKFLOW_ID }}>
+ <BindLogic logic={tileCanvasLogic} props={{ id: WORKFLOW_ID }}>
+ <TileCanvasLayoutError message="Maximum call stack size exceeded" />
+ </BindLogic>
+ </BindLogic>
+ </Provider>
+ )
+ }
+
+ it('points a saved workflow to its history instead of a retry that fails again', () => {
+ renderError()
+
+ expect(screen.getByText(/Your saved workflow did not change/)).toBeInTheDocument()
+ expect(screen.getByText('Open history')).toBeInTheDocument()
+ expect(screen.queryByText('Try again')).not.toBeInTheDocument()
+ })
+
+ it('offers to discard unsaved changes, and does not say the workflow is saved', () => {
+ act(() => flowLogic.actions.setWorkflowValue('name', 'Renamed'))
+
+ renderError()
+
+ expect(screen.getByText(/Your unsaved changes are still here/)).toBeInTheDocument()
+ expect(screen.getByText('Discard changes')).toBeInTheDocument()
+ expect(screen.queryByText(/saved workflow did not change/)).not.toBeInTheDocument()
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasLayoutError.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasLayoutError.tsx
new file mode 100644
index 000000000000..45efdb3f72d1
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasLayoutError.tsx
@@ -0,0 +1,41 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { tileCanvasLogic } from './tileCanvasLogic'
+
+/** Laying out the same steps fails the same way again, so the way out is an earlier version. */
+export function TileCanvasLayoutError({ message }: { message: string }): JSX.Element {
+ const { hasUnsavedChanges, isSavedWorkflow } = useValues(tileCanvasLogic)
+ const { discardChanges, openPanel } = useActions(tileCanvasLogic)
+ return (
+ <div
+ className="absolute inset-0 z-10 flex items-center justify-center p-6"
+ data-attr="workflow-tile-layout-error"
+ >
+ <div className="flex max-w-120 flex-col gap-3 rounded-lg border bg-surface-primary p-5 shadow">
+ <h3 className="m-0 text-base font-semibold">The canvas couldn't draw this workflow</h3>
+ <p className="m-0 text-sm text-secondary">
+ Laying out its steps failed, and it fails the same way each time.{' '}
+ {hasUnsavedChanges
+ ? 'Your unsaved changes are still here. Discard them to go back to the saved workflow.'
+ : 'Your saved workflow did not change. Open its history to go back to an earlier version.'}
+ </p>
+ <code className="block break-words rounded bg-surface-secondary px-2 py-1 text-xs">{message}</code>
+ <div className="flex flex-wrap justify-end gap-2">
+ {hasUnsavedChanges ? (
+ <LemonButton type="primary" onClick={discardChanges}>
+ Discard changes
+ </LemonButton>
+ ) : (
+ isSavedWorkflow && (
+ <LemonButton type="primary" onClick={() => openPanel('history')}>
+ Open history
+ </LemonButton>
+ )
+ )}
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasMeasureLayer.test.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasMeasureLayer.test.tsx
new file mode 100644
index 000000000000..58b3cbdf09b6
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasMeasureLayer.test.tsx
@@ -0,0 +1,114 @@
+import '@testing-library/jest-dom'
+
+import { act, cleanup, render } from '@testing-library/react'
+import { BindLogic, Provider } from 'kea'
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { workflowLogic } from '../../../workflowLogic'
+import type { HogFlow } from '../../types'
+import { tileCanvasLogic } from './tileCanvasLogic'
+import { TileCanvasMeasureLayer } from './TileCanvasMeasureLayer'
+
+jest.mock('lib/components/AppMetrics/appMetricsLogic', () => ({
+ ...jest.requireActual('lib/components/AppMetrics/appMetricsLogic'),
+ loadAppMetricsTotals: () => new Promise(() => {}),
+}))
+
+const WORKFLOW_ID = 'wf-measure-1'
+
+const WORKFLOW = {
+ id: WORKFLOW_ID,
+ name: 'Measure test',
+ version: 1,
+ status: 'draft',
+ team_id: 1,
+ exit_condition: 'exit_only_at_end',
+ trigger: { type: 'event', filters: {} },
+ actions: [
+ { id: 'trigger_node', type: 'trigger', name: 'Trigger', config: { type: 'event', filters: {} } },
+ { id: 'sync', type: 'function', name: 'Sync', config: { template_id: 'template-hubspot', inputs: {} } },
+ { id: 'exit_node', type: 'exit', name: 'Exit', config: { reason: '' } },
+ ],
+ edges: [
+ { from: 'trigger_node', to: 'sync', type: 'continue' },
+ { from: 'sync', to: 'exit_node', type: 'continue' },
+ ],
+ created_at: '2026-10-01T00:00:00.000Z',
+ updated_at: '2026-10-01T00:00:00.000Z',
+} as unknown as HogFlow
+
+describe('TileCanvasMeasureLayer', () => {
+ let flowLogic: ReturnType<typeof workflowLogic.build>
+ let canvasLogic: ReturnType<typeof tileCanvasLogic.build>
+
+ beforeEach(async () => {
+ Object.defineProperty(document, 'fonts', { value: { ready: new Promise(() => {}) }, configurable: true })
+ useMocks({
+ get: {
+ '/api/environments/:team_id/hog_flows/:id/': WORKFLOW,
+ '/api/projects/:team_id/hog_function_templates/': {
+ results: [{ id: 'template-hubspot', name: 'HubSpot', type: 'destination' }],
+ count: 1,
+ },
+ },
+ })
+ initKeaTests()
+ flowLogic = workflowLogic({ id: WORKFLOW_ID })
+ flowLogic.mount()
+ await act(async () => {
+ await flowLogic.asyncActions.loadWorkflow()
+ })
+ canvasLogic = tileCanvasLogic({ id: WORKFLOW_ID })
+ canvasLogic.mount()
+ })
+
+ afterEach(() => cleanup())
+
+ const renderLayer = (): HTMLElement =>
+ render(
+ <Provider>
+ <BindLogic logic={workflowLogic} props={{ id: WORKFLOW_ID }}>
+ <BindLogic logic={tileCanvasLogic} props={{ id: WORKFLOW_ID }}>
+ <TileCanvasMeasureLayer />
+ </BindLogic>
+ </BindLogic>
+ </Provider>
+ ).container
+
+ it('measures the tiles again once template names change their captions', async () => {
+ const container = renderLayer()
+ await expectLogic(canvasLogic).toDispatchActions([
+ 'setMeasuredSizes',
+ flowLogic.actionTypes.loadHogFunctionTemplatesByIdSuccess,
+ 'setMeasuredSizes',
+ ])
+ expect(container).toHaveTextContent('HubSpot')
+ })
+
+ it('measures only the step that changed', async () => {
+ renderLayer()
+ await expectLogic(canvasLogic).toDispatchActions([
+ 'setMeasuredSizes',
+ flowLogic.actionTypes.loadHogFunctionTemplatesByIdSuccess,
+ 'setMeasuredSizes',
+ ])
+ const sync = flowLogic.values.workflow.actions.find((action) => action.id === 'sync')!
+ const measuredIds = new Set<string | undefined>()
+ const measure = jest
+ .spyOn(HTMLElement.prototype, 'getBoundingClientRect')
+ .mockImplementation(function (this: HTMLElement) {
+ measuredIds.add(this.closest<HTMLElement>('[data-measure-id]')?.dataset.measureId)
+ return new DOMRect()
+ })
+
+ act(() => flowLogic.actions.setWorkflowAction('sync', { ...sync, name: 'Sync contacts' }))
+
+ await expectLogic(canvasLogic).toDispatchActions(['setMeasuredSizes'])
+ measure.mockRestore()
+ expect([...measuredIds]).toEqual(['sync'])
+ expect(Object.keys(canvasLogic.values.measuredSizes ?? {})).toEqual(['trigger_node', 'sync', 'exit_node'])
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasMeasureLayer.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasMeasureLayer.tsx
new file mode 100644
index 000000000000..c05a9b6659f8
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasMeasureLayer.tsx
@@ -0,0 +1,179 @@
+import { useActions, useValues } from 'kea'
+import { memo, useEffect, useLayoutEffect, useRef, useState } from 'react'
+
+import type { HogFunctionTemplateType } from '~/types'
+
+import { workflowLogic } from '../../../workflowLogic'
+import type { HogFlow } from '../../types'
+import type { NodeSize } from './tileCanvasLayout'
+import { TemplateNameOf, tileCanvasLogic } from './tileCanvasLogic'
+import { outgoingEdges, pathActions, VisibleNode } from './tileCanvasModel'
+import { TileStackNode } from './TileStackNode'
+import { TileStepNode } from './TileStepNode'
+
+const STACK_COVER_STEPS = 4
+
+function sizeOf(node: HTMLElement): NodeSize {
+ const box = node.getBoundingClientRect()
+ const anchor = node.querySelector<HTMLElement>('[data-tile-anchor]')?.getBoundingClientRect()
+ return {
+ width: node.offsetWidth,
+ height: node.offsetHeight,
+ anchor: anchor && {
+ x: anchor.left - box.left + anchor.width / 2,
+ y: anchor.top - box.top + anchor.height / 2,
+ width: anchor.width,
+ height: anchor.height,
+ },
+ }
+}
+
+const HIDDEN = { display: 'none' }
+
+/** Copies stay hidden, so they cost no layout, and only the ones measured now are shown for that moment. */
+function measure(container: HTMLElement, ids: ReadonlySet<string>): Record<string, NodeSize> {
+ const wrappers = [...container.querySelectorAll<HTMLElement>('[data-measure-id]')].filter((wrapper) =>
+ ids.has(wrapper.dataset.measureId ?? '')
+ )
+ wrappers.forEach((wrapper) => (wrapper.style.display = 'block'))
+ const sizes: Record<string, NodeSize> = {}
+ wrappers.forEach((wrapper) => {
+ const node = wrapper.firstElementChild as HTMLElement | null
+ if (node) {
+ sizes[wrapper.dataset.measureId as string] = sizeOf(node)
+ }
+ })
+ wrappers.forEach((wrapper) => (wrapper.style.display = HIDDEN.display))
+ return sizes
+}
+
+/**
+ * Everything that can change a node's size. A node whose inputs match its last measure keeps that size. Counts
+ * sit in a badge over the tile, so they never change it.
+ */
+function sizeInputs(
+ node: VisibleNode,
+ workflow: HogFlow,
+ templates: Record<string, HogFunctionTemplateType>
+): unknown[] {
+ if (node.kind === 'step') {
+ return [
+ node.action,
+ templates,
+ node.action.type === 'exit' ? workflow.exit_condition : undefined,
+ outgoingEdges(workflow, node.id).length,
+ ]
+ }
+ return [
+ node.group.label,
+ node.group.memberIds.length,
+ templates,
+ ...pathActions(workflow, node.group).slice(0, STACK_COVER_STEPS),
+ ]
+}
+
+const sameInputs = (a: unknown[] | undefined, b: unknown[]): boolean =>
+ !!a && a.length === b.length && a.every((value, index) => value === b[index])
+
+/** Captions wrap differently once the web font loads, so every node is measured again then. */
+function useFontsLoaded(): boolean {
+ const [loaded, setLoaded] = useState(() => document.fonts?.status === 'loaded')
+ useEffect(() => {
+ let cancelled = false
+ void document.fonts?.ready.then(() => !cancelled && setLoaded(true))
+ return () => {
+ cancelled = true
+ }
+ }, [])
+ return loaded
+}
+
+const noCount = (): undefined => undefined
+
+/** Re-renders only when the node's size inputs change, so a measured tile stays mounted untouched. */
+const MeasureCopy = memo(
+ function MeasureCopy({
+ node,
+ workflow,
+ templateNameOf,
+ }: {
+ node: VisibleNode
+ workflow: HogFlow
+ templateNameOf: TemplateNameOf
+ inputs: unknown[]
+ }): JSX.Element {
+ return (
+ <div data-measure-id={node.id} className="w-max" style={HIDDEN}>
+ {node.kind === 'step' ? (
+ <TileStepNode action={node.action} workflow={workflow} count={undefined} interactive={false} />
+ ) : (
+ <TileStackNode
+ group={node.group}
+ workflow={workflow}
+ countOf={noCount}
+ templateNameOf={templateNameOf}
+ interactive={false}
+ />
+ )}
+ </div>
+ )
+ },
+ (previous, next) => sameInputs(previous.inputs, next.inputs)
+)
+
+interface MeasuredNode {
+ inputs: unknown[]
+ size: NodeSize
+}
+
+export function TileCanvasMeasureLayer(): JSX.Element {
+ const ref = useRef<HTMLDivElement>(null)
+ const measured = useRef(new Map<string, MeasuredNode>())
+ const { visibleGraph, workflow, templateNameOf } = useValues(tileCanvasLogic)
+ const { hogFunctionTemplatesById } = useValues(workflowLogic)
+ const { setMeasuredSizes } = useActions(tileCanvasLogic)
+ const fontsLoaded = useFontsLoaded()
+
+ const nodes = visibleGraph.nodes.map((node) => ({
+ node,
+ inputs: [...sizeInputs(node, workflow, hogFunctionTemplatesById), fontsLoaded],
+ }))
+ const changed = nodes.filter(({ node, inputs }) => !sameInputs(measured.current.get(node.id)?.inputs, inputs))
+
+ useLayoutEffect(() => {
+ const container = ref.current
+ if (!container) {
+ return
+ }
+ const sizes = measure(container, new Set(changed.map(({ node }) => node.id)))
+ changed.forEach(({ node, inputs }) => {
+ if (sizes[node.id]) {
+ measured.current.set(node.id, { inputs, size: sizes[node.id] })
+ }
+ })
+ setMeasuredSizes(
+ Object.fromEntries(
+ nodes.flatMap(({ node }) => {
+ const size = measured.current.get(node.id)?.size
+ return size ? [[node.id, size]] : []
+ })
+ )
+ )
+ // `changed` and `nodes` derive from these inputs on every render.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [visibleGraph, workflow, hogFunctionTemplatesById, fontsLoaded, setMeasuredSizes])
+
+ return (
+ <div ref={ref} aria-hidden className="pointer-events-none invisible absolute left-[-20000px] top-0">
+ {nodes.map(({ node, inputs }) => (
+ <MeasureCopy
+ key={node.id}
+ node={node}
+ workflow={workflow}
+ templateNameOf={templateNameOf}
+ inputs={inputs}
+ />
+ ))}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasPanel.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasPanel.tsx
new file mode 100644
index 000000000000..c3056cb0066f
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasPanel.tsx
@@ -0,0 +1,32 @@
+import { useActions, useValues } from 'kea'
+
+import { workflowLogic } from '../../../workflowLogic'
+import { WorkflowRevisions } from '../../../WorkflowRevisions'
+import { HogFlowEditorPanel } from '../../panel/HogFlowEditorPanel'
+import { tileCanvasLogic } from './tileCanvasLogic'
+import { TileStepPanelHead } from './TileStepPanelHead'
+
+export function TileCanvasPanel(): JSX.Element {
+ const { isHistoryOpen, selectedNode } = useValues(tileCanvasLogic)
+ const { closePanel } = useActions(tileCanvasLogic)
+ const { logicProps } = useValues(workflowLogic)
+ const historyView =
+ isHistoryOpen && logicProps.id
+ ? {
+ title: 'History',
+ content: (
+ <div className="min-h-0 flex-1 overflow-y-auto p-3">
+ <WorkflowRevisions id={logicProps.id} />
+ </div>
+ ),
+ }
+ : undefined
+ return (
+ <HogFlowEditorPanel
+ layout="docked"
+ onClose={closePanel}
+ view={historyView}
+ stepHead={selectedNode ? <TileStepPanelHead action={selectedNode.data} /> : undefined}
+ />
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCaption.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCaption.tsx
new file mode 100644
index 000000000000..c378c29141d6
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCaption.tsx
@@ -0,0 +1,22 @@
+import { cn } from 'lib/utils/css-classes'
+
+import type { StepFacts } from './stepFacts'
+
+export const CAPTION_WIDTH = 230
+
+// Facts quote step content such as property values and messages, so recordings must not capture them.
+/** A tile and the panel head keep the caption short, so a long email subject cannot stretch them. The hover card shows more. */
+const LINES = { tile: 'line-clamp-2', card: 'line-clamp-4' }
+
+export function TileCaption({ facts, size = 'tile' }: { facts: StepFacts; size?: keyof typeof LINES }): JSX.Element {
+ return (
+ <div className="ph-no-capture flex w-57.5 flex-col gap-0.5 pt-1 text-left">
+ <div className={cn('break-words text-[13px] font-semibold leading-tight', LINES[size])}>
+ {facts.headline}
+ </div>
+ {facts.detail && (
+ <div className={cn('break-words text-xs leading-snug text-secondary', LINES[size])}>{facts.detail}</div>
+ )}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileEdge.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileEdge.tsx
new file mode 100644
index 000000000000..845d3c2ffc43
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileEdge.tsx
@@ -0,0 +1,43 @@
+import { EdgeLabelRenderer, EdgeProps } from '@xyflow/react'
+
+import { QuickAddButton } from './QuickAddButton'
+import { arrowHead, EDGE_LABEL_HEIGHT, edgeLabelWidth, insertPoint, roundedPath } from './tileCanvasLayout'
+import type { TileEdgeType } from './tileCanvasNodes'
+
+const QUICK_ADD_GAP = 14
+
+export function TileEdge({ data }: EdgeProps<TileEdgeType>): JSX.Element | null {
+ const routed = data?.routed
+ if (!data || !routed) {
+ return null
+ }
+ const { edge } = data
+ const label = edge.label && routed.label ? edge.label : undefined
+ const at = label && routed.label ? routed.label : insertPoint(routed.points)
+ return (
+ <>
+ <path d={roundedPath(routed.points)} fill="none" stroke="var(--tile-canvas-edge)" strokeWidth={1.5} />
+ <path d={arrowHead(routed.points)} fill="none" stroke="var(--tile-canvas-edge)" strokeWidth={1.5} />
+ <EdgeLabelRenderer>
+ {label && routed.label && (
+ <div
+ className="nodrag nopan absolute flex items-center justify-center whitespace-nowrap rounded-full border bg-surface-primary px-2 text-xs font-semibold"
+ style={{
+ transform: `translate(-50%, -50%) translate(${routed.label.x}px, ${routed.label.y}px)`,
+ height: EDGE_LABEL_HEIGHT,
+ minWidth: edgeLabelWidth(label),
+ }}
+ >
+ {label}
+ </div>
+ )}
+ {edge.insertEdge && (
+ <QuickAddButton
+ edge={edge.insertEdge}
+ at={{ x: at.x + (label ? edgeLabelWidth(label) / 2 + QUICK_ADD_GAP : 0), y: at.y }}
+ />
+ )}
+ </EdgeLabelRenderer>
+ </>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileFace.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileFace.tsx
new file mode 100644
index 000000000000..dac65f1403cf
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileFace.tsx
@@ -0,0 +1,78 @@
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { EmailPreviewThumbnail } from 'lib/components/EmailPreviewThumbnail/EmailPreviewThumbnail'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
+
+import type { HogFlowAction } from '../../types'
+import { emailContent } from './stepValues'
+import { TileBadge } from './TileBadge'
+import { TILE_SIZE } from './tileCanvasLayout'
+import type { TileShape, TileStep } from './useTileStep'
+
+const CORNER = 12
+
+function tileRadius(shape: TileShape): string {
+ const round = `${TILE_SIZE / 2}px`
+ return shape === 'start'
+ ? `${round} ${round} ${CORNER}px ${CORNER}px`
+ : shape === 'end'
+ ? `${CORNER}px ${CORNER}px ${round} ${round}`
+ : `${CORNER}px`
+}
+
+export function TileFace({
+ action,
+ tile,
+ count,
+ showEmail,
+ emailPlaceholder = false,
+}: {
+ action: HogFlowAction
+ tile: TileStep
+ count: number | undefined
+ showEmail: boolean
+ /** Holds the thumbnail's size without loading the email, for copies that are only measured. */
+ emailPlaceholder?: boolean
+}): JSX.Element {
+ const html = showEmail ? emailContent(action)?.html : undefined
+ return (
+ <div className="relative" data-tile-anchor>
+ {html ? (
+ <div
+ className="overflow-hidden rounded-xl border-2 bg-surface-primary shadow-sm"
+ style={{ borderColor: tile.color }}
+ >
+ {emailPlaceholder ? (
+ <span className="block h-28 w-40" />
+ ) : (
+ <EmailPreviewThumbnail html={html} title={`${action.name} preview`} size="card" />
+ )}
+ </div>
+ ) : (
+ <div
+ className="flex items-center justify-center border-2 bg-surface-primary text-[30px] shadow-sm"
+ style={{
+ width: TILE_SIZE,
+ height: TILE_SIZE,
+ borderRadius: tileRadius(tile.shape),
+ borderColor: tile.color,
+ color: tile.color,
+ }}
+ >
+ {tile.icon}
+ </div>
+ )}
+ {count !== undefined && <TileBadge placement="count">{humanFriendlyLargeNumber(count)}</TileBadge>}
+ {tile.badge && (
+ <TileBadge placement="setting" color={tile.color}>
+ {tile.badge}
+ </TileBadge>
+ )}
+ {tile.invalid && (
+ <Tooltip title="This step needs attention. Open it to see what is missing.">
+ <span className="absolute -left-1 -top-1 size-2.5 rounded-full border-2 border-primary bg-warning" />
+ </Tooltip>
+ )}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileFlowNode.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileFlowNode.tsx
new file mode 100644
index 000000000000..63438effabb4
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileFlowNode.tsx
@@ -0,0 +1,36 @@
+import { Handle, NodeProps, Position } from '@xyflow/react'
+
+import { cn } from 'lib/utils/css-classes'
+
+import { motionProps } from './motionProps'
+import type { TileFlowNodeType } from './tileCanvasNodes'
+import { TileStackNode } from './TileStackNode'
+import { TileStepNode } from './TileStepNode'
+
+export function TileFlowNode({ data }: NodeProps<TileFlowNodeType>): JSX.Element {
+ const { node, workflow, motion, count, selected, menuOpen, countOf, templateNameOf } = data
+ const motionStyle = motionProps(motion)
+
+ return (
+ <div className={cn(motionStyle.className)} style={motionStyle.style}>
+ <Handle type="target" position={Position.Top} className="!opacity-0" isConnectable={false} />
+ {node.kind === 'step' ? (
+ <TileStepNode
+ action={node.action}
+ workflow={workflow}
+ count={count}
+ selected={selected}
+ menuOpen={menuOpen}
+ />
+ ) : (
+ <TileStackNode
+ group={node.group}
+ workflow={workflow}
+ countOf={countOf}
+ templateNameOf={templateNameOf}
+ />
+ )}
+ <Handle type="source" position={Position.Bottom} className="!opacity-0" isConnectable={false} />
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileHoverCard.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileHoverCard.tsx
new file mode 100644
index 000000000000..e7efb10650ba
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileHoverCard.tsx
@@ -0,0 +1,108 @@
+import { useRef } from 'react'
+
+import type { HogFlowAction } from '../../types'
+import { StepPreview } from './step-preview/StepPreview'
+import { StepCountLine } from './StepCountLine'
+import { StepFieldList } from './StepFieldList'
+import type { StepPresentationKind } from './stepPresentation'
+import { TILE_SIZE } from './tileCanvasLayout'
+import { FIT_MARGIN } from './tileCanvasModel'
+import { CAPTION_WIDTH, TileCaption } from './TileCaption'
+import { TileFace } from './TileFace'
+import { useKeepInView } from './useKeepInView'
+import type { TileStep } from './useTileStep'
+
+const PADDING = 14
+const MIN_WIDTH = 440
+const KIND_LABEL_ROOM = 72
+const NAME_ROW_HEIGHT = 26
+const EMAIL_FACE = { width: 164, height: 116 }
+export const HOVER_CARD_CLOSE_MS = 200
+// The border snaps to whole device pixels but the card's edge can fall between them, so a clip on the
+// edge itself can shave the bottom border off. Clipping just outside the card keeps the whole border.
+const OPEN_CLIP = 'inset(-2px round 18px)'
+const PREVIEWS_THAT_SHOW_SETTINGS = new Set<StepPresentationKind>([
+ 'slack',
+ 'ai-task',
+ 'scout',
+ 'ticket-message',
+ 'ticket-update',
+ 'person',
+ 'webhook',
+ 'branch',
+ 'wait',
+ 'window',
+])
+
+/** The card starts clipped to the tile's own box, so the icon and caption stay put as it opens around them. */
+export function TileHoverCard({
+ open,
+ action,
+ tile,
+ count,
+ showEmail,
+}: {
+ open: boolean
+ action: HogFlowAction
+ tile: TileStep
+ count: number | undefined
+ showEmail: boolean
+}): JSX.Element {
+ const face = showEmail ? EMAIL_FACE : { width: TILE_SIZE, height: TILE_SIZE }
+ const width = Math.max(MIN_WIDTH, face.width + 12 + CAPTION_WIDTH + PADDING * 2 + KIND_LABEL_ROOM)
+ const nameRow = tile.customName ? NAME_ROW_HEIGHT : 0
+ const faceTop = PADDING + nameRow
+ const closedClip = `inset(${faceTop}px ${width - PADDING - face.width}px calc(100% - ${faceTop + face.height}px) ${PADDING}px round 12px)`
+ const kind = tile.presentation.kind
+ const showPreview = kind !== 'fields' && !(showEmail && kind === 'email')
+ const ref = useRef<HTMLDivElement>(null)
+ const shift = useKeepInView(ref, open, FIT_MARGIN.bottom)
+ return (
+ <div
+ ref={ref}
+ className="absolute z-10 rounded-2xl border bg-surface-primary text-primary shadow-xl transition-[clip-path,transform] ease-[cubic-bezier(0.2,0.8,0.2,1)] motion-reduce:transition-none"
+ style={{
+ left: -PADDING,
+ top: -faceTop,
+ transform: `translate(${shift.x}px, ${shift.y}px)`,
+ width,
+ padding: PADDING,
+ borderColor: tile.color,
+ clipPath: open ? OPEN_CLIP : closedClip,
+ transitionDuration: open ? '240ms' : `${HOVER_CARD_CLOSE_MS}ms`,
+ }}
+ >
+ {tile.customName && (
+ <div className="truncate text-[13px] font-semibold leading-tight" style={{ height: nameRow }}>
+ {tile.customName}
+ </div>
+ )}
+ <div className="relative flex items-start gap-3">
+ <TileFace action={action} tile={tile} count={count} showEmail={showEmail} />
+ <TileCaption facts={tile.facts} size="card" />
+ <div
+ className="absolute right-0 top-0 text-[10px] font-semibold uppercase tracking-wider"
+ style={{ color: tile.color }}
+ >
+ {tile.label}
+ </div>
+ </div>
+ <div
+ className="mt-3 flex flex-col transition-opacity motion-reduce:transition-none"
+ style={{
+ opacity: open ? 1 : 0,
+ transitionDuration: open ? '180ms' : '80ms',
+ transitionDelay: open ? '90ms' : '0ms',
+ }}
+ >
+ {/* Each part returns null when it has nothing to show, so empty:hidden drops the section and its divider. */}
+ <div className="flex flex-col gap-2.5 border-t py-3 empty:hidden">
+ {showPreview && <StepPreview action={action} tile={tile} />}
+ {(!showPreview || !PREVIEWS_THAT_SHOW_SETTINGS.has(kind)) && <StepFieldList facts={tile.facts} />}
+ <StepCountLine count={count} />
+ </div>
+ <div className="border-t pt-2 text-[11px] text-secondary">Click to open the step</div>
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStackNode.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStackNode.tsx
new file mode 100644
index 000000000000..66ddabf901d9
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStackNode.tsx
@@ -0,0 +1,89 @@
+import { useEffect, useRef, useState } from 'react'
+
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
+
+import type { HogFlow } from '../../types'
+import { StackCoverIcon } from './StackCoverIcon'
+import { StackPeek } from './StackPeek'
+import { pathSummary } from './stepFacts'
+import { TileBadge } from './TileBadge'
+import { TILE_SIZE } from './tileCanvasLayout'
+import { pathActions, PathGroup, pathColor } from './tileCanvasModel'
+import { isPointerMove } from './useHoverIntent'
+import { useRaisedNode } from './useRaisedNode'
+
+const PEEK_CLOSE_MS = 220
+const STACK_OFFSETS = [8, 4]
+
+export function TileStackNode({
+ group,
+ workflow,
+ countOf,
+ templateNameOf,
+ interactive = true,
+}: {
+ group: PathGroup
+ workflow: HogFlow
+ countOf: (actionId: string) => number | undefined
+ templateNameOf: (templateId: string) => string | undefined
+ interactive?: boolean
+}): JSX.Element {
+ const ref = useRef<HTMLDivElement>(null)
+ const [peek, setPeek] = useState(false)
+ const closeTimer = useRef<number>()
+ useEffect(() => () => window.clearTimeout(closeTimer.current), [])
+ useRaisedNode(ref, peek)
+
+ const color = pathColor(group.entryEdge)
+ const members = pathActions(workflow, group)
+ const count = countOf(group.entryEdge.to)
+
+ return (
+ <div
+ ref={ref}
+ className="flex cursor-pointer items-start gap-3 text-primary"
+ title={peek ? undefined : 'Open this path'}
+ data-attr={interactive ? 'workflow-tile-stack' : undefined}
+ onMouseMove={(event) => {
+ if (interactive && isPointerMove(event)) {
+ window.clearTimeout(closeTimer.current)
+ setPeek(true)
+ }
+ }}
+ onMouseLeave={() => {
+ closeTimer.current = window.setTimeout(() => setPeek(false), PEEK_CLOSE_MS)
+ }}
+ >
+ <div className="relative" data-tile-anchor style={{ width: TILE_SIZE, height: TILE_SIZE }}>
+ {STACK_OFFSETS.map((offset) => (
+ <div
+ key={offset}
+ className="absolute inset-0 rounded-xl border-2 bg-surface-primary opacity-50"
+ style={{ transform: `translate(${offset}px, ${-offset}px)`, borderColor: color }}
+ />
+ ))}
+ <div
+ className="absolute inset-0 grid grid-cols-2 place-items-center gap-0.5 rounded-xl border-2 border-dashed bg-surface-primary p-1.5"
+ style={{ borderColor: color }}
+ >
+ {members.slice(0, 4).map((action) => (
+ <StackCoverIcon key={action.id} action={action} workflow={workflow} />
+ ))}
+ </div>
+ {count !== undefined && <TileBadge placement="count">{humanFriendlyLargeNumber(count)}</TileBadge>}
+ {interactive && (
+ <StackPeek group={group} workflow={workflow} color={color} open={peek} countOf={countOf} />
+ )}
+ </div>
+ <div className="flex w-57.5 flex-col gap-0.5 pt-1 text-left">
+ <div className="break-words text-[13px] font-semibold leading-tight" style={{ color }}>
+ {group.label}
+ </div>
+ <div className="ph-no-capture break-words text-xs leading-snug">
+ {pathSummary(workflow, group, templateNameOf)}
+ </div>
+ <div className="text-[11px] text-secondary">{members.length} steps</div>
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepMenu.test.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepMenu.test.tsx
new file mode 100644
index 000000000000..fb3a763b047f
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepMenu.test.tsx
@@ -0,0 +1,106 @@
+import '@testing-library/jest-dom'
+
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { BindLogic, Provider } from 'kea'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { workflowLogic } from '../../../workflowLogic'
+import { hogFlowEditorLogic } from '../../hogFlowEditorLogic'
+import type { HogFlow, HogFlowAction } from '../../types'
+import { tileCanvasLogic } from './tileCanvasLogic'
+import { TileStepMenu } from './TileStepMenu'
+
+jest.mock('lib/components/AppMetrics/appMetricsLogic', () => ({
+ ...jest.requireActual('lib/components/AppMetrics/appMetricsLogic'),
+ loadAppMetricsTotals: () => new Promise(() => {}),
+}))
+
+const WORKFLOW_ID = 'wf-menu-1'
+const SYNC = { id: 'sync', type: 'delay', name: 'Wait', config: { delay_duration: '1d' } } as unknown as HogFlowAction
+
+const WORKFLOW = {
+ id: WORKFLOW_ID,
+ name: 'Menu test',
+ version: 1,
+ status: 'draft',
+ team_id: 1,
+ exit_condition: 'exit_only_at_end',
+ trigger: { type: 'event', filters: {} },
+ actions: [
+ { id: 'trigger_node', type: 'trigger', name: 'Trigger', config: { type: 'event', filters: {} } },
+ SYNC,
+ { id: 'exit_node', type: 'exit', name: 'Exit', config: { reason: '' } },
+ ],
+ edges: [
+ { from: 'trigger_node', to: 'sync', type: 'continue' },
+ { from: 'sync', to: 'exit_node', type: 'continue' },
+ ],
+ created_at: '2026-10-01T00:00:00.000Z',
+ updated_at: '2026-10-01T00:00:00.000Z',
+} as unknown as HogFlow
+
+describe('TileStepMenu', () => {
+ let canvasLogic: ReturnType<typeof tileCanvasLogic.build>
+
+ beforeEach(async () => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/hog_flows/:id/': WORKFLOW,
+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },
+ },
+ })
+ initKeaTests()
+ const flowLogic = workflowLogic({ id: WORKFLOW_ID })
+ flowLogic.mount()
+ await act(async () => {
+ await flowLogic.asyncActions.loadWorkflow()
+ })
+ canvasLogic = tileCanvasLogic({ id: WORKFLOW_ID })
+ canvasLogic.mount()
+ render(
+ <Provider>
+ <BindLogic logic={workflowLogic} props={{ id: WORKFLOW_ID }}>
+ <BindLogic logic={tileCanvasLogic} props={{ id: WORKFLOW_ID }}>
+ {/* React Flow puts keyboard focus on the node wrapper, which carries the node id. */}
+ <div className="react-flow__node" data-id="sync" tabIndex={0}>
+ <TileStepMenu action={SYNC}>
+ <div>Wait</div>
+ </TileStepMenu>
+ </div>
+ <button type="button">Elsewhere</button>
+ </BindLogic>
+ </BindLogic>
+ </Provider>
+ )
+ })
+
+ afterEach(() => cleanup())
+
+ const openFromKeyboard = async (): Promise<HTMLElement> => {
+ const tile = document.querySelector<HTMLElement>('[data-id="sync"]')!
+ await waitFor(() => expect(hogFlowEditorLogic({ id: WORKFLOW_ID }).values.edges.length).toBeGreaterThan(0))
+ tile.focus()
+ act(() => canvasLogic.actions.openStepMenu('sync', true))
+ await waitFor(() => expect(screen.getByText('Copy').closest('button')).toHaveFocus())
+ return tile
+ }
+
+ it('moves focus to the first item when the menu opens from the keyboard, and back to the tile on Escape', async () => {
+ const tile = await openFromKeyboard()
+
+ fireEvent.keyDown(document.activeElement!, { key: 'Escape' })
+
+ await waitFor(() => expect(tile).toHaveFocus())
+ expect(canvasLogic.values.stepMenuActionId).toBeNull()
+ })
+
+ it('closes the menu when focus leaves it', async () => {
+ await openFromKeyboard()
+
+ act(() => screen.getByText('Elsewhere').focus())
+
+ await waitFor(() => expect(canvasLogic.values.stepMenuActionId).toBeNull())
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepMenu.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepMenu.tsx
new file mode 100644
index 000000000000..90b34d9c10d6
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepMenu.tsx
@@ -0,0 +1,128 @@
+import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
+import { useEffect } from 'react'
+
+import { IconCopy, IconDrag, IconTrash } from '@posthog/icons'
+
+import { LemonMenu } from 'lib/lemon-ui/LemonMenu'
+
+import type { HogFlowAction } from '../../types'
+import { tileCanvasLogic } from './tileCanvasLogic'
+import { hasStepMenu } from './tileCanvasModel'
+
+const MENU_CLASS = 'TileStepMenu'
+
+function captureMenuUse(choice: 'copy' | 'move' | 'delete'): void {
+ posthog.capture('workflows tile canvas step menu used', { choice })
+}
+
+const tileOf = (actionId: string): HTMLElement | undefined =>
+ [...document.querySelectorAll<HTMLElement>('.react-flow__node')].find((node) => node.dataset.id === actionId)
+
+/**
+ * A menu opened from the keyboard takes focus, so its items can be reached, and hands it back to the tile when it
+ * closes. Escape closes it, and so does moving focus out of it.
+ */
+function useKeyboardMenuFocus(open: boolean, actionId: string, close: () => void): void {
+ useEffect(() => {
+ if (!open) {
+ return
+ }
+ const tile = tileOf(actionId)
+ const menu = (): HTMLElement | null => document.querySelector<HTMLElement>(`.${MENU_CLASS}`)
+ const frame = requestAnimationFrame(() =>
+ menu()?.querySelector<HTMLElement>('button:not(:disabled):not([aria-disabled="true"])')?.focus()
+ )
+ const onKeyDown = (event: KeyboardEvent): void => {
+ if (event.key === 'Escape' && menu()?.contains(event.target as Node)) {
+ event.preventDefault()
+ close()
+ }
+ }
+ const onFocusIn = (event: FocusEvent): void => {
+ const target = event.target as Node
+ if (!menu()?.contains(target) && target !== tile) {
+ close()
+ }
+ }
+ document.addEventListener('keydown', onKeyDown, true)
+ document.addEventListener('focusin', onFocusIn)
+ return () => {
+ cancelAnimationFrame(frame)
+ document.removeEventListener('keydown', onKeyDown, true)
+ document.removeEventListener('focusin', onFocusIn)
+ const focusIsLost = !document.activeElement || document.activeElement === document.body
+ if (focusIsLost || menu()?.contains(document.activeElement)) {
+ tile?.focus()
+ }
+ }
+ }, [open, actionId, close])
+}
+
+export function TileStepMenu({ action, children }: { action: HogFlowAction; children: JSX.Element }): JSX.Element {
+ const {
+ stepMenuActionId,
+ stepMenuFromKeyboard,
+ selectedNode,
+ selectedNodeCanBeDeleted,
+ selectedNodeCanBeCopiedOrMoved,
+ } = useValues(tileCanvasLogic)
+ const { closeStepMenu, startCopyingNode, startMovingNode, onNodesDelete } = useActions(tileCanvasLogic)
+ const node = selectedNode?.id === action.id ? selectedNode : null
+ const visible = stepMenuActionId === action.id && !!node
+ useKeyboardMenuFocus(visible && stepMenuFromKeyboard, action.id, closeStepMenu)
+
+ if (!hasStepMenu(action)) {
+ return children
+ }
+
+ return (
+ <LemonMenu
+ visible={visible}
+ className={MENU_CLASS}
+ onVisibilityChange={(visible) => !visible && closeStepMenu()}
+ placement="right-start"
+ items={
+ node
+ ? [
+ selectedNodeCanBeCopiedOrMoved
+ ? {
+ label: 'Copy',
+ icon: <IconCopy />,
+ 'data-attr': 'workflow-tile-step-copy',
+ onClick: () => {
+ captureMenuUse('copy')
+ startCopyingNode(node)
+ },
+ }
+ : null,
+ selectedNodeCanBeCopiedOrMoved
+ ? {
+ label: 'Move',
+ icon: <IconDrag />,
+ 'data-attr': 'workflow-tile-step-move',
+ onClick: () => {
+ captureMenuUse('move')
+ startMovingNode(node)
+ },
+ }
+ : null,
+ {
+ label: 'Delete',
+ status: 'danger',
+ icon: <IconTrash />,
+ 'data-attr': 'workflow-tile-step-delete',
+ onClick: () => {
+ captureMenuUse('delete')
+ onNodesDelete([node])
+ },
+ disabledReason: selectedNodeCanBeDeleted ? undefined : 'Clean up branching steps first',
+ },
+ ]
+ : []
+ }
+ >
+ {children}
+ </LemonMenu>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepNode.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepNode.tsx
new file mode 100644
index 000000000000..b6dfb55bc2f6
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepNode.tsx
@@ -0,0 +1,76 @@
+import { useActions } from 'kea'
+import { useRef } from 'react'
+
+import { cn } from 'lib/utils/css-classes'
+
+import type { HogFlow, HogFlowAction } from '../../types'
+import { emailContent } from './stepValues'
+import { tileCanvasLogic } from './tileCanvasLogic'
+import { hasStepMenu } from './tileCanvasModel'
+import { TileCaption } from './TileCaption'
+import { TileFace } from './TileFace'
+import { HOVER_CARD_CLOSE_MS, TileHoverCard } from './TileHoverCard'
+import { TileStepMenu } from './TileStepMenu'
+import { useHoverIntent } from './useHoverIntent'
+import { useRaisedNode } from './useRaisedNode'
+import { useTileStep } from './useTileStep'
+
+const HOVER_OPEN_DELAY_MS = 260
+
+export function TileStepNode({
+ action,
+ workflow,
+ count,
+ selected = false,
+ menuOpen = false,
+ interactive = true,
+}: {
+ action: HogFlowAction
+ workflow: HogFlow
+ count: number | undefined
+ selected?: boolean
+ menuOpen?: boolean
+ interactive?: boolean
+}): JSX.Element {
+ const ref = useRef<HTMLDivElement>(null)
+ const tile = useTileStep(action, workflow)
+ const showEmail = !!emailContent(action)?.html
+ const hover = useHoverIntent(interactive && !selected && !menuOpen, HOVER_OPEN_DELAY_MS, HOVER_CARD_CLOSE_MS)
+ const { openStepMenu } = useActions(tileCanvasLogic)
+ useRaisedNode(ref, hover.mounted)
+ const face = (
+ <div
+ className={cn(
+ 'relative rounded-xl',
+ (selected || menuOpen) && 'ring-2 ring-[var(--color-accent)] ring-offset-4'
+ )}
+ >
+ <TileFace action={action} tile={tile} count={count} showEmail={showEmail} emailPlaceholder={!interactive} />
+ {hover.mounted && (
+ <TileHoverCard open={hover.open} action={action} tile={tile} count={count} showEmail={showEmail} />
+ )}
+ </div>
+ )
+
+ return (
+ <div
+ ref={ref}
+ className="flex cursor-pointer items-start gap-3 text-primary"
+ title={hover.mounted ? undefined : action.name}
+ onMouseMove={hover.onMouseMove}
+ onMouseLeave={hover.onMouseLeave}
+ data-attr={interactive ? 'workflow-tile-step' : undefined}
+ onContextMenu={
+ interactive && hasStepMenu(action)
+ ? (event) => {
+ event.preventDefault()
+ openStepMenu(action.id)
+ }
+ : undefined
+ }
+ >
+ {interactive ? <TileStepMenu action={action}>{face}</TileStepMenu> : face}
+ <TileCaption facts={tile.facts} />
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepPanelHead.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepPanelHead.tsx
new file mode 100644
index 000000000000..b5470e183436
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepPanelHead.tsx
@@ -0,0 +1,61 @@
+import { useActions, useValues } from 'kea'
+
+import { IconTrash } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { HogFlowStepNameFields } from '../../panel/HogFlowStepNameFields'
+import type { HogFlowAction } from '../../types'
+import { emailContent } from './stepValues'
+import { tileCanvasLogic } from './tileCanvasLogic'
+import { TileCaption } from './TileCaption'
+import { TileFace } from './TileFace'
+import { useTileStep } from './useTileStep'
+
+const KIND_BORDER_WIDTH = 3
+
+export function TileStepPanelHead({ action }: { action: HogFlowAction }): JSX.Element {
+ const { workflow, countOf, selectedNode, selectedNodeCanBeDeleted } = useValues(tileCanvasLogic)
+ const { onNodesDelete, closePanel } = useActions(tileCanvasLogic)
+ const tile = useTileStep(action, workflow)
+ return (
+ <div
+ className="relative z-10 flex shrink-0 flex-col gap-3 border-b bg-surface-primary px-3 pb-3 pt-3"
+ style={{ borderTop: `${KIND_BORDER_WIDTH}px solid ${tile.color}` }}
+ data-attr="workflow-tile-panel-head"
+ >
+ <div className="relative flex items-start gap-3">
+ <TileFace
+ action={action}
+ tile={tile}
+ count={countOf(action.id)}
+ showEmail={!!emailContent(action)?.html}
+ />
+ <TileCaption facts={tile.facts} />
+ <div
+ className="absolute right-0 top-0 text-[10px] font-semibold uppercase tracking-wider"
+ style={{ color: tile.color }}
+ >
+ {tile.label}
+ </div>
+ </div>
+ <div className="flex items-start gap-2">
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <HogFlowStepNameFields action={action} />
+ </div>
+ {selectedNode?.deletable && (
+ <LemonButton
+ size="small"
+ status="danger"
+ icon={<IconTrash />}
+ tooltip="Delete this step"
+ onClick={() => {
+ onNodesDelete([selectedNode])
+ closePanel()
+ }}
+ disabledReason={selectedNodeCanBeDeleted ? undefined : 'Clean up branching steps first'}
+ />
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/motionProps.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/motionProps.ts
new file mode 100644
index 000000000000..163d843e22b4
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/motionProps.ts
@@ -0,0 +1,11 @@
+import type { NodeMotion } from './tileCanvasModel'
+
+export function motionProps(motion: NodeMotion | undefined): { className?: string; style?: React.CSSProperties } {
+ if (!motion) {
+ return {}
+ }
+ return {
+ className: `TileCanvas__motion--${motion.type}`,
+ style: { '--tile-canvas-dx': `${motion.dx}px`, '--tile-canvas-dy': `${motion.dy}px` } as React.CSSProperties,
+ }
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/AiPreview.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/AiPreview.tsx
new file mode 100644
index 000000000000..21a7b6b07205
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/AiPreview.tsx
@@ -0,0 +1,57 @@
+import { tint } from '../tileCanvasModel'
+import { TextWithVariables } from './TextWithVariables'
+
+export function AiPreview({
+ prompt,
+ tools,
+ writes,
+ color,
+}: {
+ prompt?: string
+ tools: string[]
+ writes: string[]
+ color: string
+}): JSX.Element | null {
+ if (!prompt && !tools.length && !writes.length) {
+ return null
+ }
+ return (
+ <div className="flex flex-col gap-2 text-left text-[12.5px] leading-snug">
+ {prompt && (
+ <div
+ className="rounded-md border p-2.5"
+ style={{ borderColor: tint(color, 30), backgroundColor: tint(color, 6) }}
+ >
+ <div className="mb-1 text-[10px] font-semibold uppercase tracking-wider" style={{ color }}>
+ Instructions
+ </div>
+ <TextWithVariables text={prompt} color={color} />
+ </div>
+ )}
+ {tools.length > 0 && (
+ <div className="flex flex-wrap items-center gap-1">
+ <span className="text-[11px] text-secondary">Can use</span>
+ {tools.map((tool) => (
+ <span key={tool} className="rounded-full border px-1.5 text-[11px]">
+ {tool}
+ </span>
+ ))}
+ </div>
+ )}
+ {writes.length > 0 && (
+ <div className="flex flex-wrap items-center gap-1">
+ <span className="text-[11px] text-secondary">Writes</span>
+ {writes.map((output) => (
+ <span
+ key={output}
+ className="rounded px-1 py-px font-mono text-[11px]"
+ style={{ color, backgroundColor: tint(color, 10) }}
+ >
+ {output}
+ </span>
+ ))}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/BranchPreview.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/BranchPreview.tsx
new file mode 100644
index 000000000000..98390149b7a9
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/BranchPreview.tsx
@@ -0,0 +1,19 @@
+import type { BranchPath } from '../stepPresentation'
+import { pathColor } from '../tileCanvasModel'
+
+export function BranchPreview({ paths }: { paths: BranchPath[] }): JSX.Element | null {
+ if (!paths.length) {
+ return null
+ }
+ return (
+ <div className="flex flex-col gap-1 text-left text-[12.5px]">
+ {paths.map((path) => (
+ <div key={path.name} className="flex items-baseline gap-2 rounded-md border px-2.5 py-1">
+ <span className="size-2 shrink-0 rounded-full" style={{ backgroundColor: pathColor(path.edge) }} />
+ <span className="font-semibold">{path.name}</span>
+ <span className="min-w-0 break-words text-secondary">{path.rule}</span>
+ </div>
+ ))}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/EmailPreview.test.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/EmailPreview.test.tsx
new file mode 100644
index 000000000000..7fc5abfcce2d
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/EmailPreview.test.tsx
@@ -0,0 +1,34 @@
+import '@testing-library/jest-dom'
+
+import { render, screen } from '@testing-library/react'
+
+import type { HogFlowAction } from '../../../types'
+import { emailContent } from '../stepValues'
+import { EmailPreview } from './EmailPreview'
+
+const plainTextEmail = {
+ id: 'invite',
+ type: 'function_email',
+ name: 'Invite',
+ description: '',
+ config: {
+ template_id: 'template-email',
+ inputs: {
+ email: {
+ value: {
+ subject: 'Invite your team',
+ html: '',
+ text: 'Hi {{ person.properties.first_name }},\n\nYou can invite three people for free.',
+ },
+ },
+ },
+ },
+} as unknown as HogFlowAction
+
+describe('EmailPreview', () => {
+ it('shows the text of an email that has no design', () => {
+ render(<EmailPreview email={emailContent(plainTextEmail)!} title="Invite preview" />)
+
+ expect(screen.getByText(/You can invite three people for free/)).toBeInTheDocument()
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/EmailPreview.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/EmailPreview.tsx
new file mode 100644
index 000000000000..00f12e05d3f8
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/EmailPreview.tsx
@@ -0,0 +1,18 @@
+import { EmailPreviewThumbnail } from 'lib/components/EmailPreviewThumbnail/EmailPreviewThumbnail'
+
+import { EmailContent, plainVariables } from '../stepValues'
+
+export function EmailPreview({ email, title }: { email: EmailContent; title: string }): JSX.Element | null {
+ if (email.html) {
+ return (
+ <div className="flex justify-center overflow-hidden rounded-md border bg-white">
+ <EmailPreviewThumbnail html={email.html} title={title} size="card" />
+ </div>
+ )
+ }
+ return email.text ? (
+ <div className="rounded-md border p-2.5 text-left text-[12.5px] leading-snug">
+ <div className="line-clamp-6 whitespace-pre-line break-words">{plainVariables(email.text)}</div>
+ </div>
+ ) : null
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/PersonPreview.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/PersonPreview.tsx
new file mode 100644
index 000000000000..1e6501d67296
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/PersonPreview.tsx
@@ -0,0 +1,14 @@
+export function PersonPreview({ properties }: { properties: [key: string, value: string][] }): JSX.Element | null {
+ if (!properties.length) {
+ return null
+ }
+ return (
+ <div className="flex flex-col gap-1 rounded-md border p-2.5 text-left font-mono text-[12px]">
+ {properties.map(([key, value]) => (
+ <div key={key}>
+ <span className="text-secondary">{key}</span> to <span className="font-semibold">{value}</span>
+ </div>
+ ))}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/SlackPreview.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/SlackPreview.tsx
new file mode 100644
index 000000000000..7d1d7e378919
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/SlackPreview.tsx
@@ -0,0 +1,15 @@
+import { TextWithVariables } from './TextWithVariables'
+
+export function SlackPreview({ text, color }: { text: string; color: string }): JSX.Element {
+ return (
+ <div className="rounded-md border p-2.5 text-left text-[12.5px] leading-snug">
+ <div className="whitespace-pre-wrap break-words">
+ {text ? (
+ <TextWithVariables text={text} color={color} />
+ ) : (
+ <span className="text-secondary">No message yet</span>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/StepPreview.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/StepPreview.tsx
new file mode 100644
index 000000000000..a62542b6cd95
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/StepPreview.tsx
@@ -0,0 +1,49 @@
+import type { HogFlowAction } from '../../../types'
+import { StepFieldList } from '../StepFieldList'
+import type { TileStep } from '../useTileStep'
+import { AiPreview } from './AiPreview'
+import { BranchPreview } from './BranchPreview'
+import { EmailPreview } from './EmailPreview'
+import { PersonPreview } from './PersonPreview'
+import { SlackPreview } from './SlackPreview'
+import { TicketMessagePreview } from './TicketMessagePreview'
+import { TicketUpdatePreview } from './TicketUpdatePreview'
+import { TimeWindowPreview } from './TimeWindowPreview'
+import { WaitPreview } from './WaitPreview'
+import { WebhookPreview } from './WebhookPreview'
+
+// Previews show prompts, messages and payloads, which can hold customer content and credentials.
+export function StepPreview({ action, tile }: { action: HogFlowAction; tile: TileStep }): JSX.Element | null {
+ const preview = previewOf(action, tile)
+ return preview && <div className="ph-no-capture contents">{preview}</div>
+}
+
+function previewOf(action: HogFlowAction, tile: TileStep): JSX.Element | null {
+ const { presentation, color } = tile
+ switch (presentation.kind) {
+ case 'email':
+ return <EmailPreview email={presentation.email} title={`${action.name} preview`} />
+ case 'slack':
+ return <SlackPreview text={presentation.text} color={color} />
+ case 'ai-task':
+ return <AiPreview {...presentation} color={color} />
+ case 'scout':
+ return <AiPreview tools={[]} writes={presentation.writes} color={color} />
+ case 'webhook':
+ return <WebhookPreview {...presentation} />
+ case 'ticket-message':
+ return <TicketMessagePreview {...presentation} color={color} />
+ case 'ticket-update':
+ return <TicketUpdatePreview {...presentation} color={color} />
+ case 'person':
+ return <PersonPreview properties={presentation.properties} />
+ case 'branch':
+ return <BranchPreview paths={presentation.paths} />
+ case 'wait':
+ return <WaitPreview wait={presentation.wait} />
+ case 'window':
+ return <TimeWindowPreview spans={presentation.window.spans} color={color} />
+ case 'fields':
+ return <StepFieldList facts={tile.facts} />
+ }
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/TextWithVariables.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/TextWithVariables.tsx
new file mode 100644
index 000000000000..7324c28b7283
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/TextWithVariables.tsx
@@ -0,0 +1,25 @@
+import { plainVariables } from '../stepValues'
+import { tint } from '../tileCanvasModel'
+
+const VARIABLE_SPLIT = /(\{\{?[^}]+\}?\})/g
+const IS_VARIABLE = /^\{\{?[^}]+\}?\}$/
+
+export function TextWithVariables({ text, color }: { text: string; color: string }): JSX.Element {
+ return (
+ <>
+ {text.split(VARIABLE_SPLIT).map((part, index) =>
+ IS_VARIABLE.test(part) ? (
+ <span
+ key={index}
+ className="rounded px-1 py-px font-mono text-[11px]"
+ style={{ color, backgroundColor: tint(color, 10) }}
+ >
+ {plainVariables(part)}
+ </span>
+ ) : (
+ <span key={index}>{part}</span>
+ )
+ )}
+ </>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/TicketMessagePreview.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/TicketMessagePreview.tsx
new file mode 100644
index 000000000000..8473d4a67c3c
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/TicketMessagePreview.tsx
@@ -0,0 +1,20 @@
+import { TextWithVariables } from './TextWithVariables'
+
+export function TicketMessagePreview({
+ message,
+ isNote,
+ color,
+}: {
+ message?: string
+ isNote: boolean
+ color: string
+}): JSX.Element | null {
+ return message ? (
+ <div className="rounded-md border p-2.5 text-left text-[12.5px] leading-snug">
+ <div className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-secondary">
+ {isNote ? 'Private note, only agents see it' : 'Reply, the customer sees it'}
+ </div>
+ <TextWithVariables text={message} color={color} />
+ </div>
+ ) : null
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/TicketUpdatePreview.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/TicketUpdatePreview.tsx
new file mode 100644
index 000000000000..15442f2599ef
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/TicketUpdatePreview.tsx
@@ -0,0 +1,23 @@
+import { tint } from '../tileCanvasModel'
+
+export function TicketUpdatePreview({
+ status,
+ tags,
+ color,
+}: {
+ status?: string
+ tags: string[]
+ color: string
+}): JSX.Element {
+ return (
+ <div className="flex flex-wrap items-center gap-1.5 rounded-md border p-2.5 text-left text-[12.5px]">
+ <span className="text-secondary">Ticket</span>
+ {tags.map((tag) => (
+ <span key={tag} className="rounded-full px-2" style={{ color, backgroundColor: tint(color, 10) }}>
+ {tag}
+ </span>
+ ))}
+ {status && <span>Status: {status}</span>}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/TimeWindowPreview.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/TimeWindowPreview.tsx
new file mode 100644
index 000000000000..27e5d329e25d
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/TimeWindowPreview.tsx
@@ -0,0 +1,28 @@
+import type { TimeSpan } from '../stepPresentation'
+
+const WEEK = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
+
+export function TimeWindowPreview({ spans, color }: { spans: TimeSpan[][]; color: string }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-1 text-left text-[11px]">
+ {WEEK.map((name, index) => (
+ <div key={name} className="flex items-center gap-1.5">
+ <span className="w-7 text-secondary">{name}</span>
+ <span className="relative h-2 flex-1 rounded-full bg-surface-secondary">
+ {spans[index].map(({ start, end }) => (
+ <span
+ key={start}
+ className="absolute inset-y-0 rounded-full"
+ style={{
+ backgroundColor: color,
+ left: `${(start / 24) * 100}%`,
+ width: `${((end - start) / 24) * 100}%`,
+ }}
+ />
+ ))}
+ </span>
+ </div>
+ ))}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/WaitPreview.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/WaitPreview.tsx
new file mode 100644
index 000000000000..7fd6ae408835
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/WaitPreview.tsx
@@ -0,0 +1,47 @@
+import { waitText } from '../stepFacts'
+import type { WaitPresentation } from '../stepPresentation'
+
+function WaitOutcome({ wait }: { wait: WaitPresentation }): JSX.Element {
+ const text = waitText(wait)
+ switch (wait.kind) {
+ case 'condition':
+ return (
+ <div className="grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5">
+ <span className="font-semibold text-success">If</span>
+ <span>{wait.name ?? 'the condition'} happens, continue right away</span>
+ <span className="font-semibold text-secondary">Else</span>
+ <span>after {text}, take the other path</span>
+ </div>
+ )
+ case 'date':
+ return (
+ <div className="text-secondary">
+ {text
+ ? `Everyone waits until ${text}, then continues (${wait.timezone})`
+ : 'Choose a date to wait for'}
+ </div>
+ )
+ case 'duration':
+ return (
+ <div className="text-secondary">
+ {text ? `Everyone waits ${text}, then continues` : 'Set how long people wait'}
+ </div>
+ )
+ }
+}
+
+export function WaitPreview({ wait }: { wait: WaitPresentation }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-1.5 text-left text-[12.5px]">
+ <div className="flex items-center gap-2">
+ <span className="size-2 rounded-full bg-[var(--color-text-secondary)]" />
+ <span className="h-px flex-1 border-t-2 border-dashed" />
+ <span className="rounded-full border px-2 text-[11px] font-semibold">
+ {waitText(wait) ?? 'Not set'}
+ </span>
+ <span className="h-px flex-1 border-t-2 border-dashed" />
+ </div>
+ <WaitOutcome wait={wait} />
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/WebhookPreview.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/WebhookPreview.tsx
new file mode 100644
index 000000000000..01e7b8b576a4
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/step-preview/WebhookPreview.tsx
@@ -0,0 +1,20 @@
+export function WebhookPreview({
+ method,
+ url,
+ body,
+}: {
+ method: string
+ url?: string
+ body: Record<string, unknown>
+}): JSX.Element {
+ return (
+ <div className="rounded-md border bg-surface-secondary p-2.5 text-left font-mono text-[11.5px] leading-relaxed">
+ <div className="break-all">
+ <span className="font-semibold">{method}</span> {url ?? 'URL not set'}
+ </div>
+ {Object.keys(body).length > 0 && (
+ <div className="whitespace-pre-wrap text-secondary">{JSON.stringify(body, null, 2)}</div>
+ )}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/stepFacts.test.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/stepFacts.test.ts
new file mode 100644
index 000000000000..94a5d58d8dfc
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/stepFacts.test.ts
@@ -0,0 +1,397 @@
+import type { HogFlow, HogFlowAction } from '../../types'
+import { pathSummary, stepBadge, stepFacts, stepView } from './stepFacts'
+import { timeWindowSpans } from './stepPresentation'
+import { computePathGroups } from './tileCanvasModel'
+
+type Config = Record<string, unknown>
+
+const step = (id: string, type: string, config: Config, name = id): HogFlowAction =>
+ ({ id, type, name, description: '', config }) as HogFlowAction
+
+const inputs = (values: Config): Record<string, { value: unknown }> =>
+ Object.fromEntries(Object.entries(values).map(([key, value]) => [key, { value }]))
+
+const fn = (id: string, templateId: string, values: Config, extra: Partial<HogFlowAction> = {}): HogFlowAction =>
+ ({ ...step(id, 'function', { template_id: templateId, inputs: inputs(values) }), ...extra }) as HogFlowAction
+
+const email = step('welcome', 'function_email', {
+ template_id: 'template-email',
+ inputs: inputs({
+ email: {
+ to: { email: '{{ person.properties.email }}' },
+ subject: 'Welcome to Example Co.',
+ preheader: 'Your first doc takes two minutes',
+ html: '<p>Hi</p>',
+ },
+ }),
+})
+
+const workflow = (actions: HogFlowAction[], extra: Partial<HogFlow> = {}): HogFlow =>
+ ({
+ id: 'flow',
+ team_id: 1,
+ version: 1,
+ name: 'Flow',
+ status: 'draft',
+ exit_condition: 'exit_only_at_end',
+ actions,
+ edges: [],
+ created_at: '',
+ updated_at: '',
+ ...extra,
+ }) as HogFlow
+
+const eventTrigger = step('trigger', 'trigger', {
+ type: 'event',
+ filters: { events: [{ id: 'Signed up', name: 'Signed up', type: 'events' }] },
+})
+
+const split = step('by_plan', 'conditional_branch', {
+ conditions: [
+ {
+ name: 'Paid',
+ filters: { properties: [{ key: 'plan', type: 'person', value: ['paid'], operator: 'exact' }] },
+ },
+ {
+ name: 'Trial',
+ filters: { properties: [{ key: 'plan', type: 'person', value: ['trial'], operator: 'exact' }] },
+ },
+ ],
+})
+
+const aiTask = fn(
+ 'draft_reply',
+ 'template-posthog-create-task',
+ {
+ title: 'Answer the question',
+ prompt: 'Answer with links to the docs. Say how sure you are.',
+ connectors: ['docs-mcp'],
+ skills: ['tone-of-voice', 'support-macros'],
+ },
+ { output_variable: [{ key: 'reply', result_path: 'reply' }] }
+)
+
+describe('stepFacts', () => {
+ it.each<[string, HogFlowAction, string, string | undefined]>([
+ ['an email', email, 'Welcome to Example Co.', 'Your first doc takes two minutes'],
+ [
+ 'an email that greets the person by name',
+ step('greet', 'function_email', {
+ template_id: 'template-email',
+ inputs: inputs({
+ email: {
+ subject: 'Three tricks for {{ person.properties.first_name }}',
+ preheader: 'Picked for {{person.properties.first_name}} and the team',
+ },
+ }),
+ }),
+ 'Three tricks for first name',
+ 'Picked for first name and the team',
+ ],
+ [
+ 'a Slack message',
+ fn('notify', 'template-slack', {
+ channel: 'C123|#support',
+ text: 'New ticket: {event.properties.subject}\nOpen it',
+ }),
+ 'Post to #support',
+ 'New ticket: subject',
+ ],
+ [
+ 'a webhook',
+ fn('call', 'template-webhook', {
+ url: 'https://hooks.example.com/v1/page',
+ method: 'POST',
+ body: { severity: 'high' },
+ }),
+ 'Call hooks.example.com',
+ 'Sends severity',
+ ],
+ ['an AI task', aiTask, 'Answer the question', 'Answer with links to the docs.'],
+ [
+ 'a scout',
+ fn('investigate', 'template-posthog-run-scout', { skill_name: 'incident-investigator' }),
+ 'Run the incident investigator scout',
+ undefined,
+ ],
+ [
+ 'a ticket reply',
+ fn('reply', 'template-posthog-send-ticket-message', { message: 'Thanks, we are on it', is_private: false }),
+ 'Reply to the customer',
+ 'Thanks, we are on it',
+ ],
+ [
+ 'a ticket note that sends an earlier answer',
+ fn('note', 'template-posthog-send-ticket-message', { message: '{variables.ai_reply}', is_private: true }),
+ 'Save a note for an agent',
+ 'Sends the ai reply from earlier',
+ ],
+ [
+ 'a ticket update',
+ fn('route', 'template-posthog-update-ticket', { status: 'pending', tags: ['bug', 'p1'] }),
+ 'Set status to pending',
+ 'Tag bug, p1',
+ ],
+ [
+ 'a person update',
+ fn('mark', 'template-posthog-update-person-properties', { set_properties: { billing_status: 'past_due' } }),
+ 'Set billing status to past_due',
+ 'On the person',
+ ],
+ ['a delay', step('pause', 'delay', { delay_duration: '3d' }), 'Wait 3 days', 'Then continue'],
+ [
+ 'a delay until a date on the person',
+ step('remind', 'delay', {
+ delay_until: {
+ expression: 'person.properties.trial_expires_at',
+ offset: '-1d',
+ use_person_timezone: true,
+ },
+ }),
+ 'Wait until 1 day before trial expires at',
+ "Then continue (the person's time zone)",
+ ],
+ [
+ 'a delay until a date not chosen yet',
+ step('remind', 'delay', { delay_until: { expression: '' } }),
+ 'Wait until a date',
+ 'Then continue (UTC)',
+ ],
+ [
+ 'a wait for an event',
+ step('wait', 'wait_until_condition', { condition: { name: 'Upgraded' }, max_wait_duration: '4d' }),
+ 'Wait for Upgraded',
+ 'Gives up after 4 days',
+ ],
+ [
+ 'a wait for an event it has not named yet',
+ step('wait', 'wait_until_condition', { condition: { name: '' }, max_wait_duration: '4d' }),
+ 'Wait for a condition',
+ 'Gives up after 4 days',
+ ],
+ [
+ 'a time window',
+ step('hours', 'wait_until_time_window', {
+ timezone: 'Europe/Berlin',
+ day: 'weekday',
+ time: ['09:00', '17:00'],
+ }),
+ 'Next weekday, 09:00 to 17:00',
+ 'Holds people until then (Europe/Berlin)',
+ ],
+ ['a split', split, 'Split by plan', 'Paid, Trial, or no match'],
+ [
+ 'a random split',
+ step('ab', 'random_cohort_branch', { cohorts: [{ percentage: 50 }, { percentage: 50 }] }),
+ 'Random split',
+ '50% / 50%',
+ ],
+ [
+ 'a random split whose weights do not add up to 100',
+ step('ab', 'random_cohort_branch', {
+ cohorts: [{ percentage: 10 }, { percentage: 10 }, { percentage: 20 }],
+ }),
+ 'Random split',
+ '25% / 25% / 50%',
+ ],
+ ['an event trigger', eventTrigger, 'Signed up', 'Starts when someone does this'],
+ [
+ 'a trigger on a PostHog action',
+ step('trigger', 'trigger', {
+ type: 'event',
+ filters: {
+ events: [{ id: 'Signed up', name: 'Signed up', type: 'events' }],
+ actions: [{ id: 12, name: 'Checked out', type: 'actions' }],
+ },
+ }),
+ 'Signed up or Checked out',
+ 'Starts when someone does this',
+ ],
+ [
+ 'an exit',
+ step('exit', 'exit', { reason: 'Trial ended' }),
+ 'Trial ended',
+ 'Nobody leaves early: everyone runs to the end',
+ ],
+ ])('leads %s with its own data', (_, action, headline, detail) => {
+ expect(stepFacts(workflow([action]), action)).toMatchObject({ headline, detail })
+ })
+
+ it.each([
+ ['a split', step('draft_split', 'conditional_branch', {}), 'Split by condition', 'No conditions yet'],
+ ['a random split', step('draft_random', 'random_cohort_branch', {}), 'Random split', undefined],
+ [
+ 'an event trigger',
+ step('trigger', 'trigger', { type: 'event' }),
+ 'Any event',
+ 'Starts when someone does this',
+ ],
+ ])('reads a draft %s that has no paths set up yet', (_, action, headline, detail) => {
+ expect(stepFacts(workflow([action]), action)).toMatchObject({ headline, detail })
+ })
+
+ it.each([
+ ['only events', [{ filters: { events: [{ id: 'Upgraded', name: 'Upgraded' }] } }], {}, 'did Upgraded'],
+ [
+ 'events or a property condition',
+ [{ filters: { events: [{ id: 'Upgraded', name: 'Upgraded' }] } }],
+ { properties: [{ key: 'plan', type: 'person', value: ['paid'], operator: 'exact' }] },
+ 'did Upgraded or plan is paid',
+ ],
+ ['nothing yet', undefined, {}, 'everyone'],
+ ])('says what a wait waits for when it has %s', (_, events, filters, waitsFor) => {
+ const action = step('wait', 'wait_until_condition', { condition: { filters }, events, max_wait_duration: '4d' })
+
+ expect(stepFacts(workflow([action]), action).fields).toContainEqual(['Waits for', waitsFor])
+ })
+
+ it.each([
+ ['a yes or no', 'beta', true, 'Set beta to true'],
+ ['a number', 'seats', 3, 'Set seats to 3'],
+ ['a text', 'billing_status', 'past_due', 'Set billing status to past_due'],
+ ])('writes %s person property value as someone would type it', (_, key, value, headline) => {
+ const action = fn('mark', 'template-posthog-update-person-properties', { set_properties: { [key]: value } })
+
+ expect(stepFacts(workflow([action]), action).headline).toBe(headline)
+ })
+
+ it('reads a step once for all its tiles, and again when its paths change', () => {
+ const twoPaths = workflow([split], {
+ edges: [
+ { from: 'by_plan', to: 'a', type: 'branch', index: 0 },
+ { from: 'by_plan', to: 'b', type: 'continue' },
+ ],
+ })
+ const threePaths = workflow([split], {
+ edges: [...twoPaths.edges, { from: 'by_plan', to: 'c', type: 'branch', index: 1 }],
+ })
+
+ expect(stepView(twoPaths, split)).toBe(stepView(workflow([split], { edges: twoPaths.edges }), split))
+ expect(stepView(threePaths, split).badge).toBe('3 paths')
+ })
+
+ it('falls back to the template name for a template it does not know', () => {
+ const action = fn('hubspot', 'template-hubspot', { email: 'x' })
+
+ expect(stepFacts(workflow([action]), action, 'HubSpot').headline).toBe('HubSpot')
+ })
+
+ it.each<[string, HogFlowAction, string | undefined]>([
+ ['a delay shows its length', step('pause', 'delay', { delay_duration: '3d' }), '3d'],
+ [
+ 'a delay until a date shows that it waits for a date',
+ step('remind', 'delay', { delay_until: { expression: 'person.properties.renews_at' } }),
+ 'Date',
+ ],
+ [
+ 'a wait shows its longest wait',
+ step('wait', 'wait_until_condition', { condition: {}, max_wait_duration: '4d' }),
+ '≤ 4d',
+ ],
+ [
+ 'a time window shows its hours',
+ step('hours', 'wait_until_time_window', { timezone: null, day: 'any', time: ['09:00', '17:00'] }),
+ '09-17',
+ ],
+ [
+ 'a time window keeps minutes that are not on the hour',
+ step('hours', 'wait_until_time_window', { timezone: null, day: 'any', time: ['09:30', '17:45'] }),
+ '09:30-17:45',
+ ],
+ ['a split shows its paths', split, '2 paths'],
+ ['an AI task shows its tools', aiTask, '3 tools'],
+ ['a trigger shows its source', eventTrigger, 'Event'],
+ ['an email shows nothing', email, undefined],
+ ])('badges the key setting: %s', (_, action, badge) => {
+ const edges =
+ action.type === 'conditional_branch'
+ ? [
+ { from: action.id, to: 'a', type: 'branch' as const, index: 0 },
+ { from: action.id, to: 'b', type: 'continue' as const },
+ ]
+ : []
+
+ expect(stepBadge(workflow([action], { edges }), action)).toBe(badge)
+ })
+
+ it('sums up a collapsed path with its first three steps', () => {
+ const flow = workflow(
+ [
+ split,
+ email,
+ step('pause', 'delay', { delay_duration: '1d' }),
+ fn('notify', 'template-slack', { channel: '#sales', text: 'Hi' }),
+ step('exit', 'exit', {}),
+ step('other', 'delay', { delay_duration: '2h' }),
+ ],
+ {
+ edges: [
+ { from: 'by_plan', to: 'welcome', type: 'branch', index: 0 },
+ { from: 'welcome', to: 'pause', type: 'continue' },
+ { from: 'pause', to: 'notify', type: 'continue' },
+ { from: 'notify', to: 'exit', type: 'continue' },
+ { from: 'by_plan', to: 'other', type: 'continue' },
+ { from: 'other', to: 'exit', type: 'continue' },
+ ],
+ }
+ )
+ const [group] = computePathGroups(flow)
+
+ expect(pathSummary(flow, group)).toBe('Welcome to Example Co., then Wait 1 day, then Post to #sales')
+ })
+
+ it('sums up a path in flow order, and stops at a split inside it', () => {
+ const innerSplit = step('inner', 'random_cohort_branch', { cohorts: [{ percentage: 50 }, { percentage: 50 }] })
+ const flow = workflow(
+ [
+ step('x', 'delay', { delay_duration: '2h' }),
+ innerSplit,
+ fn('notify', 'template-slack', { channel: '#sales', text: 'Hi' }),
+ step('y', 'delay', { delay_duration: '3h' }),
+ step('exit', 'exit', {}),
+ step('other', 'delay', { delay_duration: '2h' }),
+ split,
+ ],
+ {
+ edges: [
+ { from: 'by_plan', to: 'notify', type: 'branch', index: 0 },
+ { from: 'notify', to: 'inner', type: 'continue' },
+ { from: 'inner', to: 'x', type: 'branch', index: 0 },
+ { from: 'inner', to: 'y', type: 'continue' },
+ { from: 'x', to: 'exit', type: 'continue' },
+ { from: 'y', to: 'exit', type: 'continue' },
+ { from: 'by_plan', to: 'other', type: 'continue' },
+ { from: 'other', to: 'exit', type: 'continue' },
+ ],
+ }
+ )
+ const group = computePathGroups(flow).find((candidate) => candidate.branchActionId === 'by_plan')!
+
+ expect(pathSummary(flow, group)).toBe('Post to #sales, then Random split')
+ })
+
+ it.each([
+ {
+ name: 'keeps the minutes of a short window',
+ config: { day: 'weekday', time: ['09:30', '09:45'] },
+ expected: [...Array(5).fill([{ start: 9.5, end: 9.75 }]), [], []],
+ },
+ {
+ name: 'splits an overnight window, carrying the morning part to the next day',
+ config: { day: ['friday'], time: ['23:00', '01:00'] },
+ expected: [[], [], [], [], [{ start: 23, end: 24 }], [{ start: 0, end: 1 }], []],
+ },
+ {
+ name: 'fills a whole open day',
+ config: { day: 'weekend', time: 'any' },
+ expected: [[], [], [], [], [], [{ start: 0, end: 24 }], [{ start: 0, end: 24 }]],
+ },
+ ])('maps a time window onto the week: $name', ({ config, expected }) => {
+ const action = step('window', 'wait_until_time_window', config) as Extract<
+ HogFlowAction,
+ { type: 'wait_until_time_window' }
+ >
+
+ expect(timeWindowSpans(action.config)).toEqual(expected)
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/stepFacts.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/stepFacts.ts
new file mode 100644
index 000000000000..a1e5db25ff59
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/stepFacts.ts
@@ -0,0 +1,478 @@
+import { isBranchingAction } from '../../tree/workflowTree'
+import type { HogFlow, HogFlowAction } from '../../types'
+import { StepPresentation, stepPresentation, TimeWindowPresentation, WaitPresentation } from './stepPresentation'
+import {
+ ActionOf,
+ asRecord,
+ conditionText,
+ EmailContent,
+ eventNames,
+ firstLine,
+ firstSentence,
+ humanDuration,
+ humanKey,
+ joinList,
+ plainVariables,
+ templateIdOf,
+} from './stepValues'
+import { outgoingEdges, pathActions, PathGroup } from './tileCanvasModel'
+
+type Field = [label: string, value: string]
+
+export interface StepFacts {
+ headline: string
+ detail?: string
+ fields: Field[]
+}
+
+type PresentationOf<Kind extends StepPresentation['kind']> = Extract<StepPresentation, { kind: Kind }>
+
+const fieldIf = (label: string, value: string | undefined): Field[] => (value ? [[label, value]] : [])
+
+function emailFacts(email: EmailContent, action: HogFlowAction): StepFacts {
+ const isTransactional = action.type === 'function_email' && action.config.message_category_type === 'transactional'
+ const preheader = email.preheader && plainVariables(email.preheader)
+ return {
+ headline: plainVariables(email.subject),
+ detail: preheader,
+ fields: [
+ ['Preview', preheader ?? 'None'],
+ ['To', email.to],
+ ['Type', isTransactional ? 'Transactional' : 'Marketing'],
+ ],
+ }
+}
+
+function slackFacts({ channel, text }: PresentationOf<'slack'>): StepFacts {
+ const message = plainVariables(text)
+ return {
+ headline: `Post to ${channel}`,
+ detail: firstLine(message) || undefined,
+ fields: [
+ ['Channel', channel],
+ ['Message', message || 'Not set'],
+ ],
+ }
+}
+
+function webhookFacts({ method, url, body }: PresentationOf<'webhook'>): StepFacts {
+ const sends = joinList(Object.keys(body))
+ return {
+ headline: url ? `Call ${url.replace(/^https?:\/\//, '').split('/')[0]}` : 'Call a URL',
+ detail: sends ? `Sends ${sends}` : undefined,
+ fields: [['Request', `${method} ${url ?? 'URL not set'}`], ...fieldIf('Sends', sends)],
+ }
+}
+
+function aiTaskFacts({ title, prompt, repository, writes }: PresentationOf<'ai-task'>): StepFacts {
+ const instructions = plainVariables(prompt ?? '')
+ return {
+ headline: title ? plainVariables(title) : firstSentence(instructions) || 'AI task',
+ detail: firstSentence(instructions) || undefined,
+ fields: [
+ ['Instructions', instructions || 'Not set'],
+ ...fieldIf('Repository', repository),
+ ...fieldIf('Writes', joinList(writes)),
+ ],
+ }
+}
+
+function scoutFacts({ scout, writes }: PresentationOf<'scout'>): StepFacts {
+ const written = joinList(writes)
+ return {
+ headline: scout ? `Run the ${scout} scout` : 'Run a scout',
+ detail: written ? `Writes ${written}` : undefined,
+ fields: [['Scout', scout || 'Not set'], ...fieldIf('Writes', written)],
+ }
+}
+
+const isLoneVariable = (text: string): boolean => /^\{\{?[^}]+\}?\}$/.test(text.trim())
+
+function ticketMessageFacts({ message = '', isNote }: PresentationOf<'ticket-message'>): StepFacts {
+ const text = plainVariables(message)
+ return {
+ headline: isNote ? 'Save a note for an agent' : 'Reply to the customer',
+ detail: isLoneVariable(message) ? `Sends the ${text} from earlier` : text || undefined,
+ fields: [
+ ['Posts', isNote ? 'A private note on the ticket' : 'A reply the customer sees'],
+ ['Message', text || 'Not set'],
+ ],
+ }
+}
+
+function ticketUpdateFacts({ status, priority, tags }: PresentationOf<'ticket-update'>): StepFacts {
+ const tagList = tags.join(', ')
+ const changes = [
+ ...(status ? [`Set status to ${status}`] : []),
+ ...(priority ? [`Set priority to ${priority}`] : []),
+ ...(tagList ? [`Tag ${tagList}`] : []),
+ ]
+ return {
+ headline: changes[0] ?? 'Update the ticket',
+ detail: changes.slice(1).join(', ') || undefined,
+ fields: [...fieldIf('Status', status), ...fieldIf('Priority', priority), ...fieldIf('Tags', tagList)],
+ }
+}
+
+function personFacts({ properties }: PresentationOf<'person'>): StepFacts {
+ return {
+ headline: properties.length
+ ? properties.map(([key, value]) => `Set ${humanKey(key)} to ${value}`).join(', ')
+ : 'Update person properties',
+ detail: 'On the person',
+ fields: properties.map(([key, value]) => [humanKey(key), value]),
+ }
+}
+
+function conditionalSplitFacts({ key, paths }: PresentationOf<'branch'>): StepFacts {
+ const conditionNames = paths.filter((path) => path.edge.type === 'branch').map((path) => path.name)
+ return {
+ headline: key ? `Split by ${key}` : 'Split by condition',
+ detail: conditionNames.length ? `${conditionNames.join(', ')}, or no match` : 'No conditions yet',
+ fields: paths.map((path) => [path.name, path.rule]),
+ }
+}
+
+function randomSplitFacts({ paths }: PresentationOf<'branch'>): StepFacts {
+ return {
+ headline: 'Random split',
+ detail: paths.map((path) => `${path.share}%`).join(' / ') || undefined,
+ fields: paths.map((path) => [path.name, path.rule]),
+ }
+}
+
+/** How long a wait lasts or what it waits for, in the words its caption, card and preview all use. */
+export function waitText(wait: WaitPresentation): string | undefined {
+ switch (wait.kind) {
+ case 'duration':
+ return wait.duration ? humanDuration(wait.duration) : undefined
+ case 'date':
+ if (!wait.date) {
+ return undefined
+ }
+ return wait.offset
+ ? `${humanDuration(wait.offset.duration)} ${wait.offset.direction} ${wait.date}`
+ : wait.date
+ case 'condition':
+ return humanDuration(wait.maxWait)
+ }
+}
+
+function waitFacts(wait: WaitPresentation): StepFacts {
+ const text = waitText(wait) ?? 'Not set'
+ switch (wait.kind) {
+ case 'duration':
+ return { headline: `Wait ${text}`, detail: 'Then continue', fields: [['Wait', text]] }
+ case 'date':
+ return {
+ headline: wait.date ? `Wait until ${text}` : 'Wait until a date',
+ detail: `Then continue (${wait.timezone})`,
+ fields: [
+ ['Waits until', text],
+ ['Time zone', wait.timezone],
+ ],
+ }
+ case 'condition':
+ return {
+ headline: `Wait for ${wait.name ?? 'a condition'}`,
+ detail: `Gives up after ${text}`,
+ fields: [
+ ['Waits for', wait.condition],
+ ['Gives up', `After ${text}`],
+ ],
+ }
+ }
+}
+
+function windowFacts({ day, time, timezone }: TimeWindowPresentation): StepFacts {
+ return {
+ headline: `Next ${day}, ${time}`,
+ detail: `Holds people until then (${timezone})`,
+ fields: [
+ ['Day', day],
+ ['Time', time],
+ ['Time zone', timezone],
+ ],
+ }
+}
+
+function otherStepFacts(action: HogFlowAction, templateName: string | undefined): StepFacts {
+ return templateName
+ ? { headline: templateName, fields: [['Runs', templateName]] }
+ : { headline: action.name, detail: action.description || undefined, fields: [['Runs', action.name]] }
+}
+
+function presentationFacts(
+ presentation: StepPresentation,
+ action: HogFlowAction,
+ templateName: string | undefined
+): StepFacts {
+ switch (presentation.kind) {
+ case 'email':
+ return emailFacts(presentation.email, action)
+ case 'slack':
+ return slackFacts(presentation)
+ case 'webhook':
+ return webhookFacts(presentation)
+ case 'ai-task':
+ return aiTaskFacts(presentation)
+ case 'scout':
+ return scoutFacts(presentation)
+ case 'ticket-message':
+ return ticketMessageFacts(presentation)
+ case 'ticket-update':
+ return ticketUpdateFacts(presentation)
+ case 'person':
+ return personFacts(presentation)
+ case 'branch':
+ return presentation.split === 'condition'
+ ? conditionalSplitFacts(presentation)
+ : randomSplitFacts(presentation)
+ case 'wait':
+ return waitFacts(presentation.wait)
+ case 'window':
+ return windowFacts(presentation.window)
+ case 'fields':
+ return otherStepFacts(action, templateName)
+ }
+}
+
+type TriggerConfig = ActionOf<'trigger'>['config']
+
+function eventTriggerFacts(filters: Extract<TriggerConfig, { type: 'event' }>['filters']): StepFacts {
+ // A saved draft can hold no filters at all.
+ const { events: triggerEvents, actions, properties: triggerProperties } = asRecord(filters)
+ const events = [...eventNames(triggerEvents), ...eventNames(actions)]
+ const properties = Array.isArray(triggerProperties) ? triggerProperties : []
+ const who = properties.length ? conditionText({ properties }) : 'Anyone'
+ return {
+ headline: events.join(' or ') || 'Any event',
+ detail: properties.length ? `Starts when someone does this, if ${who}` : 'Starts when someone does this',
+ fields: [
+ ['Starts on', events.join(', ') || 'Any event'],
+ ['Who', who],
+ ],
+ }
+}
+
+function audienceTriggerFacts(filters: Extract<TriggerConfig, { type: 'batch' }>['filters']): StepFacts {
+ const audience = conditionText({ properties: filters?.properties })
+ return {
+ headline: audience === 'everyone' ? 'Everyone' : audience.charAt(0).toUpperCase() + audience.slice(1),
+ detail: `Audience, starts once for every ${filters?.audience_type === 'accounts' ? 'account' : 'person'}`,
+ fields: [['Who', audience]],
+ }
+}
+
+function triggerFacts(trigger: TriggerConfig, templateName: string | undefined): StepFacts {
+ switch (trigger.type) {
+ case 'event':
+ case 'internal-event':
+ return eventTriggerFacts(trigger.filters)
+ case 'batch':
+ return audienceTriggerFacts(trigger.filters)
+ case 'schedule':
+ return {
+ headline: 'On a schedule',
+ detail: 'Runs at the times you set',
+ fields: [['Starts', 'On a schedule']],
+ }
+ case 'manual':
+ return {
+ headline: 'Run by hand',
+ detail: 'Someone starts it',
+ fields: [['Starts', 'When someone runs it']],
+ }
+ case 'webhook':
+ return {
+ headline: templateName ?? 'Webhook call',
+ detail: 'Starts when the webhook is called',
+ fields: [['Starts on', templateName ?? 'A webhook call']],
+ }
+ case 'tracking_pixel':
+ return {
+ headline: 'Tracking pixel',
+ detail: 'Starts when the pixel loads',
+ fields: [['Starts on', 'A tracking pixel load']],
+ }
+ case 'api':
+ return {
+ headline: 'Transactional email',
+ detail: 'Starts each time the send endpoint is called',
+ fields: [['Starts on', 'A send API call']],
+ }
+ case 'cohort': {
+ const change = trigger.transition === 'left' ? 'leaves' : 'joins'
+ return {
+ headline: 'Cohort membership',
+ detail: `Starts when a person ${change} the cohort`,
+ fields: [['Starts on', `A person ${change} the cohort`]],
+ }
+ }
+ default:
+ return {
+ headline: trigger.table_name,
+ detail: 'Starts for every new row',
+ fields: [['Table', trigger.table_name]],
+ }
+ }
+}
+
+const EXIT_RULES: Record<string, string> = {
+ exit_on_conversion: 'they convert',
+ exit_on_trigger_not_matched: 'they stop matching the trigger',
+ exit_on_trigger_not_matched_or_conversion: 'they convert or stop matching the trigger',
+}
+
+function exitFacts(workflow: Pick<HogFlow, 'exit_condition'>, action: ActionOf<'exit'>): StepFacts {
+ const earlyExit = EXIT_RULES[workflow.exit_condition]
+ return {
+ headline: action.config.reason || 'End of workflow',
+ detail: earlyExit
+ ? `People also leave early when ${earlyExit}`
+ : 'Nobody leaves early: everyone runs to the end',
+ fields: [
+ ['Ends when', action.config.reason || 'The path runs out'],
+ ['Also ends', earlyExit ? `When ${earlyExit}` : 'Nobody leaves early: everyone runs to the end'],
+ ],
+ }
+}
+
+function factsOf(
+ workflow: Pick<HogFlow, 'exit_condition'>,
+ action: HogFlowAction,
+ presentation: StepPresentation,
+ templateName: string | undefined
+): StepFacts {
+ switch (action.type) {
+ case 'trigger':
+ return triggerFacts(action.config, templateName)
+ case 'exit':
+ return exitFacts(workflow, action)
+ default:
+ return presentationFacts(presentation, action, templateName)
+ }
+}
+
+const TRIGGER_SOURCES: Record<string, string> = {
+ event: 'Event',
+ 'internal-event': 'Event',
+ webhook: 'Webhook',
+ manual: 'Manual',
+ tracking_pixel: 'Pixel',
+ schedule: 'Schedule',
+ batch: 'Audience',
+ 'data-warehouse-table': 'Warehouse',
+ 'data-warehouse-view': 'Warehouse',
+}
+
+const shortTime = (time: string): string => (time.endsWith(':00') ? time.slice(0, -3) : time)
+
+function waitBadge(wait: WaitPresentation): string | undefined {
+ switch (wait.kind) {
+ case 'duration':
+ return wait.duration
+ case 'date':
+ return 'Date'
+ case 'condition':
+ return `≤ ${wait.maxWait}`
+ }
+}
+
+const countText = (count: number, one: string, many: string): string => `${count} ${count === 1 ? one : many}`
+
+function badgeOf(action: HogFlowAction, presentation: StepPresentation, pathCount: number): string | undefined {
+ if (action.type === 'trigger') {
+ return TRIGGER_SOURCES[action.config.type]
+ }
+ switch (presentation.kind) {
+ case 'wait':
+ return waitBadge(presentation.wait)
+ case 'window': {
+ const hours = presentation.window.hours
+ return hours ? `${shortTime(hours[0])}-${shortTime(hours[1])}` : undefined
+ }
+ case 'branch':
+ return `${pathCount} paths`
+ case 'webhook':
+ return presentation.method
+ case 'ai-task':
+ return presentation.tools.length ? countText(presentation.tools.length, 'tool', 'tools') : undefined
+ default:
+ return undefined
+ }
+}
+
+export interface StepView {
+ presentation: StepPresentation
+ facts: StepFacts
+ badge?: string
+}
+
+interface CachedStepView {
+ inputs: unknown[]
+ view: StepView
+}
+
+const stepViews = new WeakMap<HogFlowAction, CachedStepView>()
+
+const sameInputs = (a: unknown[], b: unknown[]): boolean =>
+ a.length === b.length && a.every((value, i) => value === b[i])
+
+/**
+ * What a tile shows for a step: read once per step object and kept until the step or the few workflow facts it
+ * reads change, however many tiles, cards and previews show it.
+ */
+export function stepView(
+ workflow: Pick<HogFlow, 'edges' | 'exit_condition' | 'actions'>,
+ action: HogFlowAction,
+ templateName?: string
+): StepView {
+ const pathCount = outgoingEdges(workflow, action.id).length
+ const inputs = [pathCount, action.type === 'exit' ? workflow.exit_condition : undefined, templateName]
+ const cached = stepViews.get(action)
+ if (cached && sameInputs(cached.inputs, inputs)) {
+ return cached.view
+ }
+ const presentation: StepPresentation =
+ action.type === 'trigger' || action.type === 'exit' ? { kind: 'fields' } : stepPresentation(action)
+ const view = {
+ presentation,
+ facts: factsOf(workflow, action, presentation, templateName),
+ badge: badgeOf(action, presentation, pathCount),
+ }
+ stepViews.set(action, { inputs, view })
+ return view
+}
+
+export function stepFacts(workflow: HogFlow, action: HogFlowAction, templateName?: string): StepFacts {
+ return stepView(workflow, action, templateName).facts
+}
+
+export function stepBadge(
+ workflow: Pick<HogFlow, 'edges' | 'exit_condition' | 'actions'>,
+ action: HogFlowAction
+): string | undefined {
+ return stepView(workflow, action).badge
+}
+
+const SUMMARY_LENGTH = 3
+
+/** The steps after a split inside the path run on only some of its people, so the summary stops at the split. */
+function summarizedSteps(actions: HogFlowAction[]): HogFlowAction[] {
+ const split = actions.findIndex(isBranchingAction)
+ return actions.slice(0, split === -1 ? SUMMARY_LENGTH : Math.min(split + 1, SUMMARY_LENGTH))
+}
+
+export function pathSummary(
+ workflow: HogFlow,
+ group: PathGroup,
+ templateNameOf?: (id: string) => string | undefined
+): string {
+ return summarizedSteps(pathActions(workflow, group))
+ .map((action) => {
+ const templateId = templateIdOf(action)
+ return stepFacts(workflow, action, templateId ? templateNameOf?.(templateId) : undefined).headline
+ })
+ .join(', then ')
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/stepPresentation.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/stepPresentation.ts
new file mode 100644
index 000000000000..bf5f74e966be
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/stepPresentation.ts
@@ -0,0 +1,296 @@
+import { parseDelayExpression, parseDelayOffset } from '../../steps/stepDelayLogic'
+import type { HogFlowAction, HogFlowEdge } from '../../types'
+import {
+ ActionOf,
+ asRecord,
+ asText,
+ asTextList,
+ conditionText,
+ EmailContent,
+ emailContent,
+ humanKey,
+ inputValue,
+ outputKeys,
+ propertyValueText,
+ templateIdOf,
+} from './stepValues'
+
+export interface TimeSpan {
+ start: number
+ end: number
+}
+
+export type WaitPresentation =
+ | { kind: 'duration'; duration?: string }
+ | { kind: 'date'; date?: string; offset?: { duration: string; direction: 'before' | 'after' }; timezone: string }
+ | { kind: 'condition'; name?: string; condition: string; maxWait: string }
+
+export interface TimeWindowPresentation {
+ day: string
+ time: string
+ hours?: [start: string, end: string]
+ timezone: string
+ spans: TimeSpan[][]
+}
+
+export interface BranchPath {
+ name: string
+ rule: string
+ edge: Pick<HogFlowEdge, 'type' | 'index'>
+ share?: number
+}
+
+export type StepPresentation =
+ | { kind: 'email'; email: EmailContent }
+ | { kind: 'slack'; channel: string; text: string }
+ | { kind: 'webhook'; method: string; url?: string; body: Record<string, unknown> }
+ | { kind: 'ai-task'; title?: string; prompt?: string; repository?: string; tools: string[]; writes: string[] }
+ | { kind: 'scout'; scout?: string; writes: string[] }
+ | { kind: 'ticket-message'; message?: string; isNote: boolean }
+ | { kind: 'ticket-update'; status?: string; priority?: string; tags: string[] }
+ | { kind: 'person'; properties: [key: string, value: string][] }
+ | { kind: 'branch'; split: 'condition' | 'random'; key?: string; paths: BranchPath[] }
+ | { kind: 'wait'; wait: WaitPresentation }
+ | { kind: 'window'; window: TimeWindowPresentation }
+ | { kind: 'fields' }
+
+export type StepPresentationKind = StepPresentation['kind']
+
+type BranchCondition = ActionOf<'conditional_branch'>['config']['conditions'][number]
+type BranchCohort = ActionOf<'random_cohort_branch'>['config']['cohorts'][number]
+
+/** A draft split can be saved before its paths are set up, so its list can be missing. */
+function branchConditions(action: ActionOf<'conditional_branch'>): BranchCondition[] {
+ return action.config.conditions ?? []
+}
+
+function branchCohorts(action: ActionOf<'random_cohort_branch'>): BranchCohort[] {
+ return action.config.cohorts ?? []
+}
+
+function splitKey(conditions: BranchCondition[]): string | undefined {
+ const keys = new Set(
+ conditions.flatMap((condition) =>
+ (condition.filters?.properties ?? []).flatMap((filter) => asText(asRecord(filter).key) ?? [])
+ )
+ )
+ return keys.size === 1 ? humanKey([...keys][0]) : undefined
+}
+
+const branchEdge = (index: number): BranchPath['edge'] => ({ type: 'branch', index })
+
+function conditionalSplit(action: ActionOf<'conditional_branch'>): StepPresentation {
+ const conditions = branchConditions(action)
+ return {
+ kind: 'branch',
+ split: 'condition',
+ key: splitKey(conditions),
+ paths: [
+ ...conditions.map((condition, index) => ({
+ name: condition.name || `Condition ${index + 1}`,
+ rule: conditionText(condition.filters),
+ edge: branchEdge(index),
+ })),
+ { name: 'No match', rule: 'Everyone else', edge: { type: 'continue' } },
+ ],
+ }
+}
+
+/** The runner picks a group by its weight against the sum of all weights, so the weights read as shares of 100. */
+function randomSplit(action: ActionOf<'random_cohort_branch'>): StepPresentation {
+ const cohorts = branchCohorts(action)
+ const total = cohorts.reduce((sum, cohort) => sum + (cohort.percentage || 0), 0)
+ return {
+ kind: 'branch',
+ split: 'random',
+ paths: cohorts.map((cohort, index) => {
+ const share = total ? Math.round(((cohort.percentage || 0) / total) * 100) : 0
+ return {
+ name: cohort.name || `Group ${index + 1}`,
+ rule: `${share}% of people`,
+ edge: branchEdge(index),
+ share,
+ }
+ }),
+ }
+}
+
+function timezoneText(config: { use_person_timezone?: boolean; timezone?: string | null }): string {
+ return config.use_person_timezone ? "the person's time zone" : (config.timezone ?? 'UTC')
+}
+
+function delayUntilDate(until: NonNullable<ActionOf<'delay'>['config']['delay_until']>): WaitPresentation {
+ const expression = until.expression.trim()
+ const offset = parseDelayOffset(until.offset)
+ return {
+ kind: 'date',
+ date: expression ? humanKey(parseDelayExpression(expression)?.key ?? expression) : undefined,
+ offset: offset.direction === 'on' ? undefined : { duration: offset.duration, direction: offset.direction },
+ timezone: timezoneText(until),
+ }
+}
+
+function delayWait(action: ActionOf<'delay'>): WaitPresentation {
+ return action.config.delay_until
+ ? delayUntilDate(action.config.delay_until)
+ : { kind: 'duration', duration: action.config.delay_duration || undefined }
+}
+
+export const waitConditionName = (action: ActionOf<'wait_until_condition'>): string | undefined =>
+ action.config.condition.name?.trim() || undefined
+
+function waitConditionText(action: ActionOf<'wait_until_condition'>): string {
+ const parts = [...(action.config.events ?? []).map((event) => event.filters), action.config.condition.filters]
+ .map(conditionText)
+ .filter((text) => text !== 'everyone')
+ return parts.length ? parts.join(' or ') : 'everyone'
+}
+
+function conditionWait(action: ActionOf<'wait_until_condition'>): WaitPresentation {
+ return {
+ kind: 'condition',
+ name: waitConditionName(action),
+ condition: waitConditionText(action),
+ maxWait: action.config.max_wait_duration,
+ }
+}
+
+type TimeWindowConfig = ActionOf<'wait_until_time_window'>['config']
+
+const WEEKDAY_NAMES = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
+
+function isWindowDay(day: TimeWindowConfig['day'], weekday: number): boolean {
+ return (
+ day === 'any' ||
+ (day === 'weekday' && weekday < 5) ||
+ (day === 'weekend' && weekday >= 5) ||
+ (Array.isArray(day) && (day as string[]).includes(WEEKDAY_NAMES[weekday]))
+ )
+}
+
+function hoursOf(time: string): number {
+ const [hours, minutes] = time.split(':').map(Number)
+ return hours + (minutes || 0) / 60
+}
+
+/** The open hours of each weekday, Monday first. Matches the workflow runner: a window whose end is not after
+ * its start runs past midnight, and that morning part belongs to the day the window started. */
+export function timeWindowSpans(config: TimeWindowConfig): TimeSpan[][] {
+ return WEEKDAY_NAMES.map((_, weekday) => {
+ const isOpenOn = (offset: number): boolean => isWindowDay(config.day, (weekday + 7 - offset) % 7)
+ if (config.time === 'any') {
+ return isOpenOn(0) ? [{ start: 0, end: 24 }] : []
+ }
+ const start = hoursOf(config.time[0])
+ const end = hoursOf(config.time[1])
+ if (end > start) {
+ return isOpenOn(0) ? [{ start, end }] : []
+ }
+ return [...(isOpenOn(1) && end > 0 ? [{ start: 0, end }] : []), ...(isOpenOn(0) ? [{ start, end: 24 }] : [])]
+ })
+}
+
+function windowDayText(day: TimeWindowConfig['day']): string {
+ if (Array.isArray(day)) {
+ return day.map((name) => name.charAt(0).toUpperCase() + name.slice(1, 3)).join(', ')
+ }
+ return day === 'any' ? 'day' : day
+}
+
+function timeWindow(config: TimeWindowConfig): TimeWindowPresentation {
+ return {
+ day: windowDayText(config.day),
+ time: config.time === 'any' ? 'any time' : `${config.time[0]} to ${config.time[1]}`,
+ hours: config.time === 'any' ? undefined : [config.time[0], config.time[1]],
+ timezone: timezoneText(config),
+ spans: timeWindowSpans(config),
+ }
+}
+
+function textInput(action: HogFlowAction, key: string): string | undefined {
+ return asText(inputValue(action, key))
+}
+
+/** Slack stores a picked channel as `<id>|#<name>`; show the name when it is there. */
+function slackChannelName(value: unknown): string {
+ const channel = asText(value) ?? ''
+ return channel.includes('|') ? channel.split('|')[1] : channel || 'a channel'
+}
+
+function functionPresentation(action: HogFlowAction): StepPresentation {
+ switch (templateIdOf(action)) {
+ case 'template-email': {
+ const email = emailContent(action)
+ return email ? { kind: 'email', email } : { kind: 'fields' }
+ }
+ case 'template-slack':
+ return {
+ kind: 'slack',
+ channel: slackChannelName(inputValue(action, 'channel')),
+ text: textInput(action, 'text') ?? '',
+ }
+ case 'template-webhook':
+ return {
+ kind: 'webhook',
+ method: textInput(action, 'method') ?? 'POST',
+ url: textInput(action, 'url'),
+ body: asRecord(inputValue(action, 'body')),
+ }
+ case 'template-posthog-create-task':
+ return {
+ kind: 'ai-task',
+ title: textInput(action, 'title'),
+ prompt: textInput(action, 'prompt'),
+ repository: textInput(action, 'repository'),
+ tools: [...asTextList(inputValue(action, 'connectors')), ...asTextList(inputValue(action, 'skills'))],
+ writes: outputKeys(action),
+ }
+ case 'template-posthog-run-scout':
+ return {
+ kind: 'scout',
+ scout: textInput(action, 'skill_name')?.replace(/-/g, ' '),
+ writes: outputKeys(action),
+ }
+ case 'template-posthog-send-ticket-message':
+ return {
+ kind: 'ticket-message',
+ message: textInput(action, 'message'),
+ isNote: inputValue(action, 'is_private') === true,
+ }
+ case 'template-posthog-update-ticket':
+ return {
+ kind: 'ticket-update',
+ status: textInput(action, 'status'),
+ priority: textInput(action, 'priority'),
+ tags: asTextList(inputValue(action, 'tags')),
+ }
+ case 'template-posthog-update-person-properties':
+ return {
+ kind: 'person',
+ properties: Object.entries(asRecord(inputValue(action, 'set_properties'))).map(([key, value]) => [
+ key,
+ propertyValueText(value),
+ ]),
+ }
+ default:
+ return { kind: 'fields' }
+ }
+}
+
+/** What a step does, read once from its config, so its caption, its facts and its preview tell the same story. */
+export function stepPresentation(action: HogFlowAction): StepPresentation {
+ switch (action.type) {
+ case 'conditional_branch':
+ return conditionalSplit(action)
+ case 'random_cohort_branch':
+ return randomSplit(action)
+ case 'delay':
+ return { kind: 'wait', wait: delayWait(action) }
+ case 'wait_until_condition':
+ return { kind: 'wait', wait: conditionWait(action) }
+ case 'wait_until_time_window':
+ return { kind: 'window', window: timeWindow(action.config) }
+ default:
+ return functionPresentation(action)
+ }
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/stepValues.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/stepValues.ts
new file mode 100644
index 000000000000..fba146eb200c
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/stepValues.ts
@@ -0,0 +1,113 @@
+import { isFunctionAction } from '../../steps/types'
+import type { HogFlowAction } from '../../types'
+
+export type ActionOf<T extends HogFlowAction['type']> = Extract<HogFlowAction, { type: T }>
+
+const DURATION_UNITS: Record<string, [string, string]> = {
+ s: ['second', 'seconds'],
+ m: ['minute', 'minutes'],
+ h: ['hour', 'hours'],
+ d: ['day', 'days'],
+ w: ['week', 'weeks'],
+}
+
+export function humanDuration(raw: string | undefined | null): string {
+ const parts = /^(\d+(?:\.\d+)?)\s*([smhdw])$/.exec(raw ?? '')
+ if (!parts) {
+ return raw ?? ''
+ }
+ const count = Number(parts[1])
+ const [one, many] = DURATION_UNITS[parts[2]]
+ return `${count} ${count === 1 ? one : many}`
+}
+
+export const asText = (value: unknown): string | undefined =>
+ typeof value === 'string' && value.trim() ? value : typeof value === 'number' ? String(value) : undefined
+
+export const asTextList = (value: unknown): string[] =>
+ Array.isArray(value) ? value.flatMap((item) => asText(item) ?? []) : []
+
+export const asRecord = (value: unknown): Record<string, unknown> =>
+ value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {}
+
+/** A person or event property value as someone would type it: true, 42, or the text itself. */
+export function propertyValueText(value: unknown): string {
+ if (typeof value === 'string') {
+ return value
+ }
+ if (typeof value === 'boolean' || typeof value === 'number') {
+ return String(value)
+ }
+ return value === null || value === undefined ? '' : JSON.stringify(value)
+}
+
+export function inputValue(action: HogFlowAction, key: string): unknown {
+ return isFunctionAction(action) ? action.config.inputs?.[key]?.value : undefined
+}
+
+export function templateIdOf(action: HogFlowAction): string | undefined {
+ return isFunctionAction(action) ? action.config.template_id : undefined
+}
+
+export function plainVariables(text: string): string {
+ return text.replace(/\{\{?\s*(?:[a-z_]+\.)*([a-z_]+)\s*\}?\}/gi, (_, key: string) => key.replace(/_/g, ' '))
+}
+
+export const firstLine = (text: string): string => text.split('\n')[0]
+export const firstSentence = (text: string): string => text.split(/(?<=[.!?])\s/)[0]
+export const humanKey = (key: string): string => key.replace(/^\$/, '').replace(/_/g, ' ')
+export const joinList = (items: string[]): string => items.map(humanKey).join(', ')
+
+function propertyFilterText(filter: unknown): string {
+ const { key, value, operator } = asRecord(filter)
+ const values = Array.isArray(value)
+ ? value.map(propertyValueText).filter(Boolean).join(' or ')
+ : propertyValueText(value)
+ const verb = typeof operator === 'string' && operator !== 'exact' ? operator.replace(/_/g, ' ') : 'is'
+ return `${humanKey(asText(key) ?? 'property')} ${verb} ${values}`.trim()
+}
+
+export function eventNames(events: unknown): string[] {
+ return (Array.isArray(events) ? events : []).flatMap((event) => {
+ const { name, id } = asRecord(event)
+ return asText(name) ?? asText(id) ?? []
+ })
+}
+
+export function conditionText(filters: unknown): string {
+ const { events, properties } = asRecord(filters)
+ const parts = [
+ ...eventNames(events).map((name) => `did ${name}`),
+ ...(Array.isArray(properties) ? properties : []).map(propertyFilterText),
+ ]
+ return parts.length ? parts.join(' and ') : 'everyone'
+}
+
+export function outputKeys(action: HogFlowAction): string[] {
+ const output = action.output_variable
+ const list = Array.isArray(output) ? output : output ? [output] : []
+ return list.map((variable) => variable.key)
+}
+
+export interface EmailContent {
+ subject: string
+ preheader?: string
+ to: string
+ html?: string
+ text?: string
+}
+
+export function emailContent(action: HogFlowAction): EmailContent | undefined {
+ if (templateIdOf(action) !== 'template-email') {
+ return undefined
+ }
+ const email = asRecord(inputValue(action, 'email'))
+ const toEmail = asText(asRecord(email.to).email) ?? ''
+ return {
+ subject: asText(email.subject) ?? 'No subject yet',
+ preheader: asText(email.preheader),
+ to: /person\.properties\.email/.test(toEmail) ? 'Their email address' : toEmail || 'Not set',
+ html: asText(email.html),
+ text: asText(email.text),
+ }
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLayout.test.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLayout.test.ts
new file mode 100644
index 000000000000..7a2202cbb700
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLayout.test.ts
@@ -0,0 +1,107 @@
+import type { HogFlowAction, HogFlowEdge } from '../../types'
+import { layoutTileCanvas, NodeSize, pathFrameSpecs } from './tileCanvasLayout'
+import { computePathGroups, computeVisibleGraph, PathGroup } from './tileCanvasModel'
+
+const step = (id: string, type: HogFlowAction['type'] = 'function'): HogFlowAction =>
+ ({ id, type, name: id, description: '', config: {} }) as HogFlowAction
+
+const pathEdge = (from: string, to: string, index: number, count: number): HogFlowEdge =>
+ index < count - 1 ? { from, to, type: 'branch', index } : { from, to, type: 'continue' }
+
+/** A split whose paths hold two steps each, and one step for an arm in `single`, and join again at `join`. */
+function fanOut(
+ split: string,
+ arms: string[],
+ join: string,
+ single: string[] = []
+): { actions: HogFlowAction[]; edges: HogFlowEdge[] } {
+ const stepsOf = (arm: string): string[] => (single.includes(arm) ? [`${arm}1`] : [`${arm}1`, `${arm}2`])
+ return {
+ actions: [step(split, 'conditional_branch'), ...arms.flatMap((arm) => stepsOf(arm).map((id) => step(id)))],
+ edges: arms.flatMap((arm, index) => {
+ const ids = stepsOf(arm)
+ return [
+ pathEdge(split, ids[0], index, arms.length),
+ ...ids.slice(1).map((id, at): HogFlowEdge => ({ from: ids[at], to: id, type: 'continue' })),
+ { from: ids[ids.length - 1], to: join, type: 'continue' },
+ ]
+ }),
+ }
+}
+
+const OUTER = ['a', 'b', 'c', 'd', 'e', 'f']
+const INNER = ['x', 'y', 'z']
+
+// trigger -> split with six paths; the middle path starts with its own three-way split, and the last holds one step
+const outer = fanOut('split', OUTER, 'exit', ['f'])
+const inner = fanOut('c1', INNER, 'c2')
+const workflow = {
+ actions: [
+ step('trigger', 'trigger'),
+ ...outer.actions.map((action) => (action.id === 'c1' ? step('c1', 'conditional_branch') : action)),
+ ...inner.actions.filter((action) => action.id !== 'c1'),
+ step('exit', 'exit'),
+ ],
+ edges: [
+ { from: 'trigger', to: 'split', type: 'continue' } as HogFlowEdge,
+ ...outer.edges.filter((edge) => edge.from !== 'c1'),
+ ...inner.edges,
+ ],
+}
+
+const groups = computePathGroups(workflow)
+const outerArms = groups.filter((group) => group.branchActionId === 'split')
+const innerArms = groups.filter((group) => group.branchActionId === 'c1')
+
+async function layoutWith(openIds: string[]): Promise<(group: PathGroup) => { x: number; top: number }> {
+ const graph = computeVisibleGraph(workflow, groups, openIds)
+ const sizes: Record<string, NodeSize> = Object.fromEntries(
+ graph.nodes.map((node) => [
+ node.id,
+ node.kind === 'stack' ? { width: 180, height: 90 } : { width: 64, height: 64 },
+ ])
+ )
+ const layout = await layoutTileCanvas(sizes, graph.edges, pathFrameSpecs(groups, openIds, graph.nodes))
+ return (group) => {
+ const frame = layout.frames[`frame:${group.id}`]
+ return frame
+ ? { x: frame.x + frame.width / 2, top: frame.y }
+ : { x: layout.positions[group.id].x + sizes[group.id].width / 2, top: layout.positions[group.id].y }
+ }
+}
+
+/** The arms of a split from left to right, by the centre of each one's stack or open frame. */
+async function leftToRight(arms: PathGroup[], openIds: string[]): Promise<string[]> {
+ const placeOf = await layoutWith(openIds)
+ return [...arms].sort((one, other) => placeOf(one).x - placeOf(other).x).map((group) => group.memberIds[0])
+}
+
+const OUTER_ORDER = OUTER.slice(0, -1).map((arm) => `${arm}1`)
+const INNER_ORDER = INNER.map((arm) => `${arm}1`)
+
+describe('layoutTileCanvas', () => {
+ it.each([
+ ['nothing open', [] as PathGroup[], outerArms, OUTER_ORDER],
+ ['the middle path open', [outerArms[2]], outerArms, OUTER_ORDER],
+ ['the middle path open, for its inner paths', [outerArms[2]], innerArms, INNER_ORDER],
+ ['an inner path open', [outerArms[2], innerArms[1]], outerArms, OUTER_ORDER],
+ ['an inner path open, for its inner paths', [outerArms[2], innerArms[1]], innerArms, INNER_ORDER],
+ ])('keeps each path between the same neighbours with %s', async (_, open, arms, expected) => {
+ expect(
+ await leftToRight(
+ arms,
+ open.map((group) => group.id)
+ )
+ ).toEqual(expected)
+ })
+
+ it.each([
+ ['a path of plain steps', 1],
+ ['a path with paths of its own', 2],
+ ])('keeps the other paths level with %s that opens', async (_, opened) => {
+ const placeOf = await layoutWith([outerArms[opened].id])
+ const tops = outerArms.map((arm) => placeOf(arm).top)
+
+ expect(tops).toEqual(tops.map(() => placeOf(outerArms[opened]).top))
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLayout.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLayout.ts
new file mode 100644
index 000000000000..b0566b11cb74
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLayout.ts
@@ -0,0 +1,385 @@
+import type { ElkExtendedEdge, ElkNode } from 'elkjs/lib/elk.bundled.js'
+
+import { getElk } from 'lib/elk'
+
+import { getEdgeId } from '../../edgeId'
+import { isInPathGroup, openPathFrames, PathGroup, Point, VisibleEdge, VisibleNode } from './tileCanvasModel'
+
+export const TILE_SIZE = 64
+export const EDGE_LABEL_HEIGHT = 22
+const BADGE_ROOM = 10
+const PORT_SPREAD = 14
+const FRAME_PADDING = { top: 30, side: 16, bottom: 16 }
+
+export interface Box {
+ x: number
+ y: number
+ width: number
+ height: number
+}
+
+export interface NodeSize {
+ width: number
+ height: number
+ anchor?: Box
+}
+
+export interface RoutedEdge {
+ points: Point[]
+ label?: Point
+ labelBox?: Box
+}
+
+export interface CanvasLayout {
+ positions: Record<string, Point>
+ edges: Record<string, RoutedEdge>
+ frames: Record<string, Box>
+ width: number
+ height: number
+}
+
+export interface PathFrameSpec {
+ id: string
+ group: PathGroup
+ parentId: string | null
+ memberIds: string[]
+ minWidth: number
+}
+
+export const edgeLabelWidth = (text: string): number => Math.ceil(text.length * 6.6) + 20
+export const frameChipWidth = (label: string): number => Math.ceil(label.length * 7.6) + 64
+
+export const frameId = (group: PathGroup): string => `frame:${group.id}`
+
+export function pathFrameSpecs(
+ groups: PathGroup[],
+ openGroupIds: readonly string[],
+ nodes: VisibleNode[]
+): PathFrameSpec[] {
+ return openPathFrames(groups, openGroupIds).map((group) => ({
+ id: frameId(group),
+ group,
+ parentId: group.parentId ? `frame:${group.parentId}` : null,
+ memberIds: nodes.filter((node) => isInPathGroup(group, node)).map((node) => node.id),
+ minWidth: frameChipWidth(group.label) + 32,
+ }))
+}
+
+/** Where the arrow into a laid-out tile or stack meets it. */
+export function tileEntry(position: Point, size: NodeSize): Point {
+ return { x: position.x + (size.anchor ? size.anchor.x : size.width / 2), y: position.y }
+}
+
+function tilePorts(size: NodeSize, count: number): { in: Point; out: Point[] } {
+ const centerX = tileEntry({ x: 0, y: 0 }, size).x
+ return {
+ in: { x: centerX, y: 0 },
+ out: Array.from({ length: count }, (_, index) => ({
+ x: centerX + (index - (count - 1) / 2) * PORT_SPREAD,
+ y: size.height,
+ })),
+ }
+}
+
+const LAYOUT_OPTIONS: Record<string, string> = {
+ 'elk.algorithm': 'layered',
+ 'elk.direction': 'DOWN',
+ 'elk.edgeRouting': 'ORTHOGONAL',
+ 'elk.layered.spacing.nodeNodeBetweenLayers': '44',
+ 'elk.spacing.nodeNode': '56',
+ 'elk.spacing.edgeNode': '24',
+ 'elk.spacing.edgeEdge': '14',
+ 'elk.spacing.edgeLabel': '4',
+ 'elk.layered.spacing.edgeNodeBetweenLayers': '20',
+ 'elk.layered.nodePlacement.strategy': 'BRANDES_KOEPF',
+ 'elk.layered.nodePlacement.bk.fixedAlignment': 'BALANCED',
+ 'elk.layered.crossingMinimization.forceNodeModelOrder': 'true',
+ // Each path starts in the row under its split, so a path that opens does not push the paths beside it down.
+ 'elk.layered.layering.strategy': 'LONGEST_PATH_SOURCE',
+ 'elk.edgeLabels.placement': 'CENTER',
+}
+
+// ELK's model-order strategy crashes on nested graphs. Forced node order still keeps the paths in order.
+const FLAT_ONLY_OPTIONS: Record<string, string> = {
+ 'elk.layered.considerModelOrder.strategy': 'NODES_AND_EDGES',
+}
+
+/** An open frame is taller than the stacks in its row, and they line up with its top, not its middle. */
+const ROW_ALIGNMENT = { 'elk.alignment': 'TOP' }
+
+function leafNode(id: string, size: NodeSize, portCount: number): ElkNode {
+ const ports = tilePorts(size, portCount)
+ return {
+ id,
+ width: size.width,
+ height: size.height,
+ layoutOptions: { 'elk.portConstraints': 'FIXED_POS', ...ROW_ALIGNMENT },
+ ports: [
+ { id: `${id}:in`, ...ports.in, width: 1, height: 1, layoutOptions: { 'elk.port.side': 'NORTH' } },
+ ...ports.out.map((point, index) => ({
+ id: `${id}:out:${index}`,
+ ...point,
+ width: 1,
+ height: 1,
+ layoutOptions: { 'elk.port.side': 'SOUTH' },
+ })),
+ ],
+ }
+}
+
+const FRAME_PADDING_OPTION = `[left=${FRAME_PADDING.side}, top=${FRAME_PADDING.top}, right=${FRAME_PADDING.side}, bottom=${FRAME_PADDING.bottom}]`
+
+function elkRootOptions(nested: boolean): Record<string, string> {
+ return {
+ ...LAYOUT_OPTIONS,
+ ...(nested
+ ? {
+ 'elk.hierarchyHandling': 'INCLUDE_CHILDREN',
+ 'elk.json.shapeCoords': 'ROOT',
+ 'elk.json.edgeCoords': 'ROOT',
+ }
+ : FLAT_ONLY_OPTIONS),
+ 'elk.padding': '[left=0, top=0, right=0, bottom=0]',
+ }
+}
+
+/**
+ * ELK gives an arrow's label a row of its own. A path whose name shows on its stack or frame has no label on its
+ * arrow, so it gets a blank one, and every path of a split starts in the same row. ELK skips a label with no text.
+ */
+function elkLabels(edge: VisibleEdge): ElkExtendedEdge['labels'] {
+ if (edge.label) {
+ return [
+ { id: `${edge.id}:label`, text: edge.label, width: edgeLabelWidth(edge.label), height: EDGE_LABEL_HEIGHT },
+ ]
+ }
+ return edge.portCount > 1 ? [{ id: `${edge.id}:label`, text: ' ', width: 1, height: EDGE_LABEL_HEIGHT }] : []
+}
+
+function elkEdge(edge: VisibleEdge): ElkExtendedEdge {
+ return {
+ id: edge.id,
+ sources: [`${edge.source}:out:${edge.portIndex}`],
+ targets: [`${edge.target}:in`],
+ labels: elkLabels(edge),
+ }
+}
+
+function elkFrame(frame: PathFrameSpec): ElkNode {
+ return {
+ id: frame.id,
+ children: [],
+ layoutOptions: {
+ ...LAYOUT_OPTIONS,
+ 'elk.padding': FRAME_PADDING_OPTION,
+ 'elk.nodeSize.constraints': 'MINIMUM_SIZE',
+ 'elk.nodeSize.minimum': `(${frame.minWidth}, 40)`,
+ ...ROW_ALIGNMENT,
+ },
+ }
+}
+
+/**
+ * Each node goes into the deepest open frame that holds it, and each frame into its parent frame.
+ * ELK keeps the children in the order they are given, so a frame takes the place of its first step: an opened path
+ * stays between the same neighbours instead of moving to the end of its row.
+ */
+function assignFrameChildren(
+ root: ElkNode,
+ sizes: Record<string, NodeSize>,
+ edges: VisibleEdge[],
+ frames: PathFrameSpec[]
+): void {
+ const containers = new Map(frames.map((frame) => [frame.id, elkFrame(frame)]))
+ const specs = new Map(frames.map((frame) => [frame.id, frame]))
+ const containerOf = (id: string | null | undefined): ElkNode => containers.get(id ?? '') ?? root
+ const deepestFrameOf = new Map<string, string>()
+ const framesStartingAt = new Map<string, PathFrameSpec[]>()
+ ;[...frames]
+ .sort((a, b) => a.group.depth - b.group.depth)
+ .forEach((frame) => {
+ frame.memberIds.forEach((id) => deepestFrameOf.set(id, frame.id))
+ const first = frame.memberIds[0] ?? ''
+ framesStartingAt.set(first, [...(framesStartingAt.get(first) ?? []), frame])
+ })
+ const placed = new Set<string>()
+ const placeFrame = (frame: PathFrameSpec): void => {
+ if (placed.has(frame.id)) {
+ return
+ }
+ placed.add(frame.id)
+ const parent = specs.get(frame.parentId ?? '')
+ if (parent) {
+ placeFrame(parent)
+ }
+ containerOf(frame.parentId).children?.push(containers.get(frame.id) as ElkNode)
+ }
+ const portCounts = new Map(edges.map((edge) => [edge.source, edge.portCount]))
+ Object.entries(sizes).forEach(([id, size]) => {
+ framesStartingAt.get(id)?.forEach(placeFrame)
+ containerOf(deepestFrameOf.get(id)).children?.push(leafNode(id, size, portCounts.get(id) ?? 1))
+ })
+ frames.forEach(placeFrame)
+}
+
+function buildElkGraph(sizes: Record<string, NodeSize>, edges: VisibleEdge[], frames: PathFrameSpec[]): ElkNode {
+ const root: ElkNode = {
+ id: 'root',
+ layoutOptions: elkRootOptions(frames.length > 0),
+ children: [],
+ edges: edges.filter((edge) => sizes[edge.source] && sizes[edge.target]).map(elkEdge),
+ }
+ assignFrameChildren(root, sizes, edges, frames)
+ return root
+}
+
+function readLayout(result: ElkNode, frameIds: Set<string>): CanvasLayout {
+ const positions: CanvasLayout['positions'] = {}
+ const frames: CanvasLayout['frames'] = {}
+ const elkEdges: ElkExtendedEdge[] = []
+ const walk = (node: ElkNode): void => {
+ elkEdges.push(...(node.edges ?? []))
+ node.children?.forEach((child) => {
+ if (frameIds.has(child.id)) {
+ frames[child.id] = {
+ x: child.x ?? 0,
+ y: child.y ?? 0,
+ width: child.width ?? 0,
+ height: child.height ?? 0,
+ }
+ } else {
+ positions[child.id] = { x: child.x ?? 0, y: child.y ?? 0 }
+ }
+ walk(child)
+ })
+ }
+ walk(result)
+ const edges: CanvasLayout['edges'] = {}
+ elkEdges.forEach((edge) => {
+ const section = edge.sections?.[0]
+ if (!section) {
+ return
+ }
+ const label = edge.labels?.[0]
+ const labelBox =
+ label?.x !== undefined && label.y !== undefined
+ ? { x: label.x, y: label.y, width: label.width ?? 0, height: label.height ?? 0 }
+ : undefined
+ edges[edge.id] = {
+ points: [section.startPoint, ...(section.bendPoints ?? []), section.endPoint],
+ labelBox,
+ label: labelBox ? { x: labelBox.x + labelBox.width / 2, y: labelBox.y + labelBox.height / 2 } : undefined,
+ }
+ })
+ return { positions, edges, frames, width: result.width ?? 0, height: result.height ?? 0 }
+}
+
+/** ELK ends an arrow at the node box. Pull its start up to the tile, so no arrow floats beside the caption. */
+function attachToTiles(layout: CanvasLayout, edges: VisibleEdge[], sizes: Record<string, NodeSize>): CanvasLayout {
+ const sourceOf = new Map(edges.map((edge) => [edge.id, edge.source]))
+ const attached = Object.fromEntries(
+ Object.entries(layout.edges).map(([id, routed]) => {
+ const source = sourceOf.get(id)
+ const anchor = source ? sizes[source]?.anchor : undefined
+ const position = source ? layout.positions[source] : undefined
+ if (!anchor || !position) {
+ return [id, routed]
+ }
+ const points = routed.points.map((point) => ({ ...point }))
+ points[0].y = position.y + anchor.y + anchor.height / 2 + (anchor.height === TILE_SIZE ? BADGE_ROOM : 0)
+ return [id, { ...routed, points }]
+ })
+ )
+ return { ...layout, edges: attached }
+}
+
+export async function layoutTileCanvas(
+ sizes: Record<string, NodeSize>,
+ edges: VisibleEdge[],
+ frames: PathFrameSpec[]
+): Promise<CanvasLayout> {
+ const elk = await getElk()
+ const result = await elk.layout(buildElkGraph(sizes, edges, frames))
+ return attachToTiles(readLayout(result, new Set(frames.map((frame) => frame.id))), edges, sizes)
+}
+
+export function roundedPath(points: Point[]): string {
+ if (points.length < 2) {
+ return ''
+ }
+ const radius = 8
+ const corners = points.slice(1, -1).map((point, index) => {
+ const previous = points[index]
+ const next = points[index + 2]
+ const inLength = Math.hypot(point.x - previous.x, point.y - previous.y) || 1
+ const outLength = Math.hypot(next.x - point.x, next.y - point.y) || 1
+ const r = Math.min(radius, inLength / 2, outLength / 2)
+ const before = {
+ x: point.x - ((point.x - previous.x) / inLength) * r,
+ y: point.y - ((point.y - previous.y) / inLength) * r,
+ }
+ const after = {
+ x: point.x + ((next.x - point.x) / outLength) * r,
+ y: point.y + ((next.y - point.y) / outLength) * r,
+ }
+ return `L ${before.x} ${before.y} Q ${point.x} ${point.y} ${after.x} ${after.y}`
+ })
+ const last = points[points.length - 1]
+ return [`M ${points[0].x} ${points[0].y}`, ...corners, `L ${last.x} ${last.y}`].join(' ')
+}
+
+export function arrowHead(points: Point[]): string {
+ const end = points[points.length - 1]
+ const before = points[points.length - 2] ?? { x: end.x, y: end.y - 1 }
+ const length = Math.hypot(end.x - before.x, end.y - before.y) || 1
+ const [dx, dy] = [(end.x - before.x) / length, (end.y - before.y) / length]
+ const back = { x: end.x - dx * 7, y: end.y - dy * 7 }
+ return `M ${back.x - dy * 4} ${back.y + dx * 4} L ${end.x} ${end.y} L ${back.x + dy * 4} ${back.y - dx * 4}`
+}
+
+export function insertPoint(points: Point[]): Point {
+ let best = { length: -1, point: points[0] }
+ points.slice(1).forEach((b, index) => {
+ const a = points[index]
+ const length = Math.abs(b.y - a.y) + Math.abs(b.x - a.x)
+ if ((a.x === b.x || a.y === b.y) && length > best.length) {
+ best = { length, point: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 } }
+ }
+ })
+ return best.point
+}
+
+export function entryX(points: Point[] | undefined, top: number, fallback: number): number {
+ const crossing = (points ?? []).slice(1).find((b, index) => {
+ const a = (points ?? [])[index]
+ return a.x === b.x && Math.min(a.y, b.y) <= top && Math.max(a.y, b.y) >= top
+ })
+ return crossing?.x ?? fallback
+}
+
+/** Where the arrow into an open path crosses the top of its frame. */
+export function frameEntryX(group: PathGroup, box: Box, layout: CanvasLayout, edges: VisibleEdge[]): number {
+ const entry = edges.find((edge) => edge.originalEdgeKeys.includes(getEdgeId(group.entryEdge)))
+ return entryX(entry ? layout.edges[entry.id]?.points : undefined, box.y, box.x + box.width / 2)
+}
+
+export function canvasBounds(layout: CanvasLayout, sizes: Record<string, NodeSize>): Box | undefined {
+ const boxes: Box[] = [
+ ...Object.entries(layout.positions).flatMap(([id, position]) =>
+ sizes[id] ? [{ ...position, width: sizes[id].width, height: sizes[id].height }] : []
+ ),
+ ...Object.values(layout.frames),
+ ...Object.values(layout.edges).flatMap((edge) => [
+ ...edge.points.map((point) => ({ ...point, width: 0, height: 0 })),
+ ...(edge.labelBox ? [edge.labelBox] : []),
+ ]),
+ ]
+ if (!boxes.length) {
+ return undefined
+ }
+ const left = Math.min(...boxes.map((box) => box.x))
+ const top = Math.min(...boxes.map((box) => box.y))
+ const right = Math.max(...boxes.map((box) => box.x + box.width))
+ const bottom = Math.max(...boxes.map((box) => box.y + box.height))
+ return { x: left, y: top, width: right - left, height: bottom - top }
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.test.ts
new file mode 100644
index 000000000000..ee9520329003
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.test.ts
@@ -0,0 +1,434 @@
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import { loadAppMetricsTotals } from 'lib/components/AppMetrics/appMetricsLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { workflowLogic } from '../../../workflowLogic'
+import { hogFlowEditorLogic } from '../../hogFlowEditorLogic'
+import type { HogFlowActionNode } from '../../types'
+import * as tileCanvasLayout from './tileCanvasLayout'
+import { tileCanvasLogic } from './tileCanvasLogic'
+import { stepCount } from './tileCanvasModel'
+
+jest.mock('lib/components/AppMetrics/appMetricsLogic', () => ({
+ ...jest.requireActual('lib/components/AppMetrics/appMetricsLogic'),
+ loadAppMetricsTotals: jest.fn(),
+}))
+
+const WORKFLOW_ID = 'flow-1'
+
+const step = (id: string, type = 'delay', config: Record<string, unknown> = { delay_duration: '1d' }): object => ({
+ id,
+ type,
+ name: id,
+ config,
+})
+
+// trigger -> split, whose two paths hold two steps each, both ending at exit
+const savedWorkflow = {
+ id: WORKFLOW_ID,
+ name: 'Onboarding',
+ version: 1,
+ status: 'active',
+ trigger: { type: 'event', filters: {} },
+ actions: [
+ step('trigger_node', 'trigger', { type: 'event', filters: {} }),
+ step('split', 'conditional_branch', { conditions: [{ filters: {} }] }),
+ step('pause'),
+ step('a2'),
+ step('b1'),
+ step('b2'),
+ step('exit_node', 'exit', { reason: 'Done' }),
+ ],
+ edges: [
+ { from: 'trigger_node', to: 'split', type: 'continue' },
+ { from: 'split', to: 'pause', type: 'branch', index: 0 },
+ { from: 'pause', to: 'a2', type: 'continue' },
+ { from: 'a2', to: 'exit_node', type: 'continue' },
+ { from: 'split', to: 'b1', type: 'continue' },
+ { from: 'b1', to: 'b2', type: 'continue' },
+ { from: 'b2', to: 'exit_node', type: 'continue' },
+ ],
+ updated_at: '2026-10-01T00:00:00.000Z',
+}
+
+async function mountSavedCanvas(): Promise<ReturnType<typeof tileCanvasLogic.build>> {
+ initKeaTests()
+ const flowLogic = workflowLogic({ id: WORKFLOW_ID })
+ flowLogic.mount()
+ await expectLogic(flowLogic).toDispatchActions(['loadWorkflowSuccess'])
+ const canvasLogic = tileCanvasLogic({ id: WORKFLOW_ID })
+ canvasLogic.mount()
+ await expectLogic(canvasLogic).toDispatchActions(['loadStepCountsSuccess'])
+ return canvasLogic
+}
+
+const totals = (rows: [instanceId: string, metric: string, total: number][]): Record<string, unknown> =>
+ Object.fromEntries(
+ rows.map(([instanceId, metric, total]) => [
+ `${instanceId}_${metric}`,
+ { total, breakdowns: [instanceId, metric] },
+ ])
+ )
+
+describe('tileCanvasLogic', () => {
+ let logic: ReturnType<typeof tileCanvasLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/hog_flows/:id/': savedWorkflow,
+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },
+ },
+ })
+ })
+
+ describe('panels', () => {
+ beforeEach(() => {
+ initKeaTests()
+ logic = tileCanvasLogic()
+ logic.mount()
+ })
+
+ it('opens a panel mode and closes it again from the same command', async () => {
+ await expectLogic(logic, () => logic.actions.togglePanel('logs')).toMatchValues({ panelMode: 'logs' })
+ await expectLogic(logic, () => logic.actions.togglePanel('logs')).toMatchValues({
+ panelMode: null,
+ isPanelOpen: false,
+ })
+ })
+
+ it('keeps the selected step when the panel switches mode', async () => {
+ const stepId = logic.values.workflow.actions[0].id
+ logic.actions.selectStep(stepId)
+
+ await expectLogic(logic, () => logic.actions.togglePanel('logs')).toMatchValues({
+ panelMode: 'logs',
+ selectedNodeId: stepId,
+ })
+ })
+
+ it('leaves history for the build mode of a step picked on the canvas', async () => {
+ const stepId = logic.values.workflow.actions[0].id
+ await expectLogic(logic, () => logic.actions.togglePanel('history')).toMatchValues({
+ panelMode: 'history',
+ })
+
+ await expectLogic(logic, () => logic.actions.selectStep(stepId)).toMatchValues({
+ panelMode: 'build',
+ selectedNodeId: stepId,
+ })
+ })
+ })
+
+ describe('step menu', () => {
+ beforeEach(async () => {
+ jest.mocked(loadAppMetricsTotals).mockResolvedValue({})
+ logic = await mountSavedCanvas()
+ })
+
+ it('selects the step under the menu without opening the panel', async () => {
+ await expectLogic(logic, () => logic.actions.openStepMenu('b1')).toMatchValues({
+ selectedNodeId: 'b1',
+ stepMenuActionId: 'b1',
+ isPanelOpen: false,
+ })
+ })
+
+ it('opens the step panel for a step and the path for a stack, from a click or the keyboard', async () => {
+ const [stack] = logic.values.visibleGraph.nodes.filter((node) => node.kind === 'stack')
+
+ await expectLogic(logic, () => logic.actions.activateNode('split')).toMatchValues({
+ selectedNodeId: 'split',
+ isPanelOpen: true,
+ })
+ await expectLogic(logic, () => logic.actions.activateNode(stack.id)).toMatchValues({
+ openPathIds: [stack.id],
+ })
+ })
+
+ it.each([
+ { name: 'clears the step a closed menu picked', panelOpen: false, selected: null },
+ { name: 'keeps the step the open panel shows', panelOpen: true, selected: 'b1' },
+ ])('$name', async ({ panelOpen, selected }) => {
+ if (panelOpen) {
+ logic.actions.selectStep('b1')
+ }
+ logic.actions.openStepMenu('b1')
+
+ await expectLogic(logic, () => logic.actions.closeStepMenu()).toMatchValues({ selectedNodeId: selected })
+ })
+
+ it('opens the panel for a step picked on the canvas', async () => {
+ await expectLogic(logic, () => logic.actions.selectStep('b1')).toMatchValues({
+ selectedNodeId: 'b1',
+ isPanelOpen: true,
+ })
+ })
+ })
+
+ describe('typing anywhere', () => {
+ let scene: HTMLElement
+ let canvas: HTMLElement
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = tileCanvasLogic()
+ logic.mount()
+ scene = document.body.appendChild(document.createElement('main'))
+ canvas = scene.appendChild(document.createElement('div'))
+ canvas.className = 'TileCanvas__flow'
+ })
+
+ afterEach(() => {
+ document.body.innerHTML = ''
+ })
+
+ it.each([
+ { name: 'the page itself', place: (): HTMLElement => document.body, opens: true },
+ { name: 'the scene that holds the canvas', place: (): HTMLElement => scene, opens: true },
+ {
+ name: 'the canvas',
+ place: (): HTMLElement => canvas.appendChild(document.createElement('div')),
+ opens: true,
+ },
+ {
+ name: 'a button in the step panel',
+ place: (): HTMLElement => scene.appendChild(document.createElement('button')),
+ opens: false,
+ },
+ ])('opens the command palette from a key typed on $name: $opens', ({ place, opens }) => {
+ place().dispatchEvent(new KeyboardEvent('keydown', { key: 'd', bubbles: true }))
+
+ expect(logic.values.commandPaletteQuery).toBe(opens ? 'd' : null)
+ })
+ })
+
+ describe('placing a step', () => {
+ const delayStep = { type: 'delay', name: 'Delay', description: '', config: { delay_duration: '1h' } } as const
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = tileCanvasLogic()
+ logic.mount()
+ })
+
+ it.each([
+ {
+ source: 'palette',
+ add: (): void => {
+ logic.actions.openCommandPalette('d')
+ logic.actions.startPlacing(delayStep)
+ logic.actions.placeAt(logic.values.workflow.edges[0])
+ },
+ },
+ {
+ source: 'command bar',
+ add: (): void => {
+ logic.actions.openCommandPalette()
+ logic.actions.startPlacing(delayStep)
+ logic.actions.placeAt(logic.values.workflow.edges[0])
+ },
+ },
+ {
+ source: 'quick add',
+ add: (): void => logic.actions.addStepAt(delayStep, logic.values.workflow.edges[0]),
+ },
+ ])('counts a step added from the $source', ({ source, add }) => {
+ const capture = jest.spyOn(posthog, 'capture')
+
+ add()
+
+ expect(capture).toHaveBeenCalledWith('workflows tile canvas step added', { source, step_type: 'delay' })
+ })
+
+ it.each(['startMovingNode', 'startCopyingNode'] as const)(
+ 'drops a pending %s when someone starts adding a step',
+ async (startPending) => {
+ const editorLogic = hogFlowEditorLogic()
+ const pendingNode = { id: 'exit_node', data: logic.values.workflow.actions[1] } as HogFlowActionNode
+ editorLogic.actions[startPending](pendingNode)
+
+ await expectLogic(logic, () => logic.actions.startPlacing(delayStep)).toMatchValues({
+ isMovingNode: false,
+ isCopyingNode: false,
+ nodeToBeAdded: delayStep,
+ })
+ }
+ )
+
+ it('forgets a copied step when a click on the canvas stops the copy', async () => {
+ const editorLogic = hogFlowEditorLogic()
+ editorLogic.actions.startCopyingNode({
+ id: 'exit_node',
+ data: logic.values.workflow.actions[1],
+ } as HogFlowActionNode)
+
+ await expectLogic(logic, () => logic.actions.handlePaneClick()).toMatchValues({
+ isCopyingNode: false,
+ nodeToBeAdded: null,
+ isPlacing: false,
+ })
+ })
+ })
+
+ describe('paths', () => {
+ let layoutSpy: jest.SpyInstance
+
+ beforeEach(async () => {
+ jest.mocked(loadAppMetricsTotals).mockResolvedValue({})
+ logic = await mountSavedCanvas()
+ jest.useFakeTimers()
+ // The tests hand the canvas its layouts, so a real one must not land in between.
+ layoutSpy = jest.spyOn(tileCanvasLayout, 'layoutTileCanvas').mockReturnValue(new Promise(() => {}))
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ layoutSpy.mockRestore()
+ })
+
+ const stackSize = { width: 180, height: 90, anchor: { x: 32, y: 32, width: 64, height: 64 } }
+ const stackAt = { x: 200, y: 300 }
+ const stack = { ...stackAt, width: 180, height: 90, entry: { x: 232, y: 300 } }
+ const frame = { x: 40, y: 300, width: 520, height: 260 }
+ const framePlace = { ...frame, entry: { x: 300, y: 300 } }
+ const layoutWith = (
+ positions: Record<string, { x: number; y: number }>,
+ frames: Record<string, typeof frame>
+ ): tileCanvasLayout.CanvasLayout => ({ positions, edges: {}, frames, width: 600, height: 600 })
+
+ it('opens a path where its stack was on screen', () => {
+ const [group] = logic.values.pathGroups
+ logic.actions.setMeasuredSizes({ [group.id]: stackSize })
+ logic.actions.setLayout(layoutWith({ [group.id]: stackAt }, {}))
+
+ logic.actions.openPath(group.id)
+ logic.actions.setLayout(layoutWith({}, { [`frame:${group.id}`]: frame }))
+
+ expect(logic.values.viewportFocus).toEqual({ place: framePlace, anchor: stack, request: 1 })
+ })
+
+ it('collapses a path into a stack where its frame was on screen', () => {
+ const [group] = logic.values.pathGroups
+ logic.actions.setOpenPathIds([group.id])
+ logic.actions.setLayout(layoutWith({}, { [`frame:${group.id}`]: frame }))
+
+ logic.actions.collapsePath(group.id)
+ jest.advanceTimersByTime(1000)
+ logic.actions.setMeasuredSizes({ [group.id]: stackSize })
+ logic.actions.setLayout(layoutWith({ [group.id]: stackAt }, {}))
+
+ expect(logic.values.viewportFocus).toEqual({ place: stack, anchor: framePlace, request: 1 })
+ })
+
+ it('keeps an opening stack on the canvas, opened once, until the layout that opens it lands', () => {
+ const [group] = logic.values.pathGroups
+ const drawnIds = (): string[] => logic.values.drawnGraph.nodes.map((node) => node.id)
+ logic.actions.setLayout(layoutWith({ [group.id]: stackAt }, {}), logic.values.visibleGraph)
+
+ logic.actions.openPath(group.id)
+ const whileLayingOut = drawnIds()
+ logic.actions.activateNode(group.id)
+ logic.actions.setLayout(layoutWith({}, { [`frame:${group.id}`]: frame }), logic.values.visibleGraph)
+
+ expect(whileLayingOut).toContain(group.id)
+ expect(logic.values.openPathIds).toEqual([group.id])
+ expect(drawnIds()).not.toContain(group.id)
+ })
+
+ it('brings the path of a step picked elsewhere into view', () => {
+ const group = logic.values.pathGroups.find((candidate) => candidate.memberIds.includes('a2'))!
+
+ logic.actions.setSelectedNodeId('a2')
+ logic.actions.setLayout(layoutWith({}, { [`frame:${group.id}`]: frame }))
+
+ expect(logic.values.viewportFocus).toEqual({ place: framePlace, anchor: null, request: 1 })
+ })
+
+ it('collapses every path someone collapses in quick succession', () => {
+ const pathIds = logic.values.pathGroups.map((group) => group.id)
+ logic.actions.setOpenPathIds(pathIds)
+
+ pathIds.forEach((pathId) => logic.actions.collapsePath(pathId))
+ jest.advanceTimersByTime(1000)
+
+ expect(logic.values.openPathIds).toEqual([])
+ })
+ })
+
+ describe('layout failure', () => {
+ beforeEach(async () => {
+ jest.mocked(loadAppMetricsTotals).mockResolvedValue({})
+ logic = await mountSavedCanvas()
+ })
+
+ it('shows why the canvas could not lay out the workflow, and clears it once a layout works', async () => {
+ const layout = jest
+ .spyOn(tileCanvasLayout, 'layoutTileCanvas')
+ .mockRejectedValueOnce(new RangeError('Maximum call stack size exceeded'))
+ const size = { width: 300, height: 80 }
+
+ await expectLogic(logic, () =>
+ logic.actions.setMeasuredSizes({ trigger_node: size })
+ ).toFinishAllListeners()
+ expect(logic.values.layoutError).toBe('Maximum call stack size exceeded')
+
+ await expectLogic(logic, () =>
+ logic.actions.setMeasuredSizes({ trigger_node: size, split: size })
+ ).toFinishAllListeners()
+ expect(logic.values.layoutError).toBeNull()
+ layout.mockRestore()
+ })
+
+ it('keeps a valid canvas when an older layout fails after the sizes went back to it', async () => {
+ const size = { width: 300, height: 80 }
+ const valid = { trigger_node: size }
+ const layout = jest.spyOn(tileCanvasLayout, 'layoutTileCanvas')
+ await expectLogic(logic, () => logic.actions.setMeasuredSizes(valid)).toFinishAllListeners()
+ let failOlder: (error: Error) => void = () => {}
+ layout.mockReturnValueOnce(new Promise((_, reject) => (failOlder = reject)))
+
+ logic.actions.setMeasuredSizes({ trigger_node: size, split: size })
+ await new Promise((resolve) => setTimeout(resolve, 20))
+ logic.actions.setMeasuredSizes(valid)
+ await new Promise((resolve) => setTimeout(resolve, 20))
+ failOlder(new RangeError('Maximum call stack size exceeded'))
+ await new Promise((resolve) => setTimeout(resolve, 0))
+
+ expect(logic.values.layoutError).toBeNull()
+ layout.mockRestore()
+ })
+ })
+
+ describe('step counts', () => {
+ beforeEach(async () => {
+ jest.mocked(loadAppMetricsTotals).mockResolvedValue(
+ totals([
+ ['pause', 'succeeded', 40],
+ ['pause', 'filtered', 8],
+ ]) as any
+ )
+ logic = await mountSavedCanvas()
+ })
+
+ it('counts the people a step filtered out', () => {
+ expect(stepCount(logic.values.stepMetrics, 'pause')).toBe(48)
+ })
+
+ it('keeps the canvas counts when the Metrics panel loads another date range', async () => {
+ const editorLogic = hogFlowEditorLogic({ id: WORKFLOW_ID })
+
+ await expectLogic(logic, () =>
+ editorLogic.actions.loadActionMetricsByIdSuccess({
+ pause: { actionId: 'pause', succeeded: 3, failed: 0, filtered: 0 },
+ })
+ )
+
+ expect(stepCount(logic.values.stepMetrics, 'pause')).toBe(48)
+ })
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.ts
new file mode 100644
index 000000000000..63f36aba7e39
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.ts
@@ -0,0 +1,917 @@
+import {
+ actions,
+ afterMount,
+ connect,
+ isBreakpoint,
+ kea,
+ key,
+ listeners,
+ MakeLogicType,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+import { loaders } from 'kea-loaders'
+import { subscriptions } from 'kea-subscriptions'
+import posthog from 'posthog-js'
+import type { DragEvent } from 'react'
+
+import { loadAppMetricsTotals } from 'lib/components/AppMetrics/appMetricsLogic'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { objectsEqual } from 'lib/utils/objects'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { sceneLayoutLogic } from '~/layout/scenes/sceneLayoutLogic'
+import { HogFunctionTemplateType, TeamPublicType, TeamType } from '~/types'
+
+import { WorkflowLogicProps, workflowLogic } from '../../../workflowLogic'
+import { getEdgeId } from '../../edgeId'
+import {
+ actionMetricsFromTotals,
+ CreateActionType,
+ HogFlowEditorActionMetrics,
+ HogFlowEditorMode,
+ hogFlowEditorLogic,
+} from '../../hogFlowEditorLogic'
+import type { DropzoneNode, HogFlow, HogFlowActionNode, HogFlowEdge } from '../../types'
+import { destinationSteps, workflowStepSections } from '../../workflowStepCatalog'
+import {
+ CanvasLayout,
+ frameEntryX,
+ frameId,
+ layoutTileCanvas,
+ NodeSize,
+ PathFrameSpec,
+ pathFrameSpecs,
+ tileEntry,
+} from './tileCanvasLayout'
+import {
+ CanvasMotion,
+ collapsedPathStacks,
+ computePathGroups,
+ computeVisibleGraph,
+ countableStepMetrics,
+ PaletteSection,
+ PathGroup,
+ PathPlace,
+ Point,
+ stepCount,
+ stepCountsRequest,
+ VisibleEdge,
+ VisibleGraph,
+} from './tileCanvasModel'
+import { withLeavingStacks } from './tileCanvasNodes'
+
+export type TileCanvasPanelMode = HogFlowEditorMode | 'history'
+
+export type StepAddSource = 'palette' | 'command bar' | 'quick add'
+export type StepCountOf = (actionId: string) => number | undefined
+export type TemplateNameOf = (templateId: string) => string | undefined
+
+const PATH_LEAVE_MS = 260
+const PATH_MOTION_MS = 1100
+
+export interface PendingPathFocus {
+ groupId: string
+ shows: 'frame' | 'stack'
+ /** Where the path was before it opened or collapsed. Absent for a path opened from elsewhere, such as a link. */
+ anchor: PathPlace | null
+}
+
+export interface ViewportFocus {
+ place: PathPlace
+ anchor: PathPlace | null
+ request: number
+}
+
+function stackPlace(
+ layout: CanvasLayout | null,
+ sizes: Record<string, NodeSize> | null,
+ groupId: string
+): PathPlace | null {
+ const position = layout?.positions[groupId]
+ const size = sizes?.[groupId]
+ return position && size
+ ? { ...position, width: size.width, height: size.height, entry: tileEntry(position, size) }
+ : null
+}
+
+function framePlace(layout: CanvasLayout | null, group: PathGroup, edges: VisibleEdge[]): PathPlace | null {
+ const box = layout?.frames[frameId(group)]
+ return layout && box ? { ...box, entry: { x: frameEntryX(group, box, layout, edges), y: box.y } } : null
+}
+
+/** Where steps fly out of when a path opens: the middle of the stack's tile. */
+function stackOrigin(layout: CanvasLayout | null, sizes: Record<string, NodeSize> | null, groupId: string): Point {
+ const position = layout?.positions[groupId]
+ const size = sizes?.[groupId]
+ return position
+ ? { x: position.x + (size?.anchor?.x ?? (size?.width ?? 0) / 2), y: position.y + (size?.anchor?.y ?? 0) }
+ : { x: 0, y: 0 }
+}
+
+/** Where steps fly back to when a path collapses: the top of its open frame, where the stack will be. */
+function frameOrigin(layout: CanvasLayout | null, group: PathGroup): Point {
+ const box = layout?.frames[frameId(group)]
+ return box ? { x: box.x + box.width / 2, y: box.y + 40 } : { x: 0, y: 0 }
+}
+
+function captureStepAdded(source: StepAddSource, stepType: string): void {
+ posthog.capture('workflows tile canvas step added', { source, step_type: stepType })
+}
+
+const SURFACES_WITH_THEIR_OWN_KEYS = [
+ 'input',
+ 'textarea',
+ 'select',
+ '[contenteditable="true"]',
+ '.LemonModal',
+ '[role="dialog"]',
+ '.Popover',
+].join(', ')
+
+function belongsToAnotherSurface(event: KeyboardEvent): boolean {
+ return (
+ event.defaultPrevented ||
+ (event.target instanceof HTMLElement && !!event.target.closest(SURFACES_WITH_THEIR_OWN_KEYS))
+ )
+}
+
+const isPrintableKey = (event: KeyboardEvent): boolean =>
+ !event.metaKey && !event.ctrlKey && !event.altKey && event.key.length === 1 && /\S/.test(event.key)
+
+const CANVAS_SELECTOR = '.TileCanvas__flow'
+
+/** Typing starts a search on the canvas, or on the page or scene around it, never on the panel, bar or tabs. */
+function isTypedOnCanvas(event: KeyboardEvent): boolean {
+ const target = event.target
+ return (
+ target instanceof HTMLElement && (!!target.closest(CANVAS_SELECTOR) || !!target.querySelector(CANVAS_SELECTOR))
+ )
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface tileCanvasLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ dropzoneNodes: DropzoneNode[] // hogFlowEditorLogic
+ isCopyingNode: boolean // hogFlowEditorLogic
+ isMovingNode: boolean // hogFlowEditorLogic
+ mode: HogFlowEditorMode // hogFlowEditorLogic
+ nodeToBeAdded: CreateActionType | HogFlowActionNode | null // hogFlowEditorLogic
+ selectedNode: HogFlowActionNode | null // hogFlowEditorLogic
+ selectedNodeCanBeCopiedOrMoved: boolean // hogFlowEditorLogic
+ selectedNodeCanBeDeleted: boolean // hogFlowEditorLogic
+ selectedNodeId: string | null // hogFlowEditorLogic
+ sceneTakeoverActive: boolean // sceneLayoutLogic
+ currentTeam: TeamPublicType | TeamType | null // teamLogic
+ hasUnsavedChanges: boolean // workflowLogic
+ hogFunctionTemplatesById: Record<string, HogFunctionTemplateType> // workflowLogic
+ isRowScopedTrigger: boolean // workflowLogic
+ originalWorkflow: HogFlow | null // workflowLogic
+ workflow: HogFlow // workflowLogic
+ allPathsCollapsed: boolean
+ commandPaletteQuery: string | null
+ countOf: StepCountOf
+ drawnGraph: VisibleGraph
+ fitRequest: number
+ fitsNextLayout: boolean
+ frameSpecs: PathFrameSpec[]
+ isHistoryOpen: boolean
+ isPanelOpen: boolean
+ isPlacing: boolean
+ isSavedWorkflow: boolean
+ laidOutGraph: VisibleGraph | null
+ layout: CanvasLayout | null
+ layoutError: string | null
+ measuredSizes: Record<string, NodeSize> | null
+ motion: CanvasMotion | null
+ openPathIds: string[]
+ paletteSections: PaletteSection[]
+ panelMode: TileCanvasPanelMode | null
+ pathGroups: PathGroup[]
+ pendingPathFocus: PendingPathFocus | null
+ placingSource: StepAddSource
+ quickAddEdgeKey: string | null
+ selectedStepId: string | null
+ stepCounts: Record<string, HogFlowEditorActionMetrics> | null
+ stepCountsLoading: boolean
+ stepMenuActionId: string | null
+ stepMenuFromKeyboard: boolean
+ stepMetrics: Record<string, HogFlowEditorActionMetrics> | null
+ templateNameOf: TemplateNameOf
+ viewportFocus: ViewportFocus | null
+ visibleGraph: VisibleGraph
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface tileCanvasLogicActions {
+ copyNodeToHighlightedDropzone: () => {
+ value: true
+ } // hogFlowEditorLogic
+ handlePaneClick: () => {
+ value: true
+ } // hogFlowEditorLogic
+ moveNodeToHighlightedDropzone: () => {
+ value: true
+ } // hogFlowEditorLogic
+ onDrop: (
+ event?: DragEvent<Element> | undefined,
+ targetEdge?: HogFlowEdge | undefined,
+ joinEdges?: HogFlowEdge[] | undefined
+ ) => {
+ event: DragEvent<Element> | undefined
+ joinEdges: HogFlowEdge[] | undefined
+ targetEdge: HogFlowEdge | undefined
+ } // hogFlowEditorLogic
+ onNodesDelete: (deleted: HogFlowActionNode[]) => {
+ deleted: HogFlowActionNode[]
+ } // hogFlowEditorLogic
+ setHighlightedDropzoneNodeId: (highlightedDropzoneNodeId: string | null) => {
+ highlightedDropzoneNodeId: string | null
+ } // hogFlowEditorLogic
+ setMode: (mode: 'build' | 'logs' | 'metrics' | 'test' | 'variables') => {
+ mode: 'build' | 'logs' | 'metrics' | 'test' | 'variables'
+ } // hogFlowEditorLogic
+ setNodeToBeAdded: (nodeToBeAdded: CreateActionType | HogFlowActionNode | null) => {
+ nodeToBeAdded: CreateActionType | HogFlowActionNode | null
+ } // hogFlowEditorLogic
+ setSelectedNodeId: (selectedNodeId: string | null) => {
+ selectedNodeId: string | null
+ } // hogFlowEditorLogic
+ startCopyingNode: (node: HogFlowActionNode) => {
+ node: HogFlowActionNode
+ } // hogFlowEditorLogic
+ startMovingNode: (node: HogFlowActionNode) => {
+ node: HogFlowActionNode
+ } // hogFlowEditorLogic
+ stopCopyingNode: () => {
+ value: true
+ } // hogFlowEditorLogic
+ stopMovingNode: () => {
+ value: true
+ } // hogFlowEditorLogic
+ discardChanges: () => {
+ value: true
+ } // workflowLogic
+ activateNode: (nodeId: string) => {
+ nodeId: string
+ }
+ addStepAt: (
+ step: CreateActionType,
+ edge: HogFlowEdge
+ ) => {
+ edge: HogFlowEdge
+ step: CreateActionType
+ }
+ cancel: () => {
+ value: true
+ }
+ closeCommandPalette: () => {
+ value: true
+ }
+ closePanel: () => {
+ value: true
+ }
+ closeQuickAdd: () => {
+ value: true
+ }
+ closeStepMenu: () => {
+ value: true
+ }
+ collapsePath: (groupId: string) => {
+ groupId: string
+ }
+ fitNextLayout: () => {
+ value: true
+ }
+ focusPath: (
+ place: PathPlace,
+ anchor?: PathPlace | null
+ ) => {
+ anchor: PathPlace | null
+ place: PathPlace
+ }
+ focusPathAfterLayout: (groupId: string) => {
+ groupId: string
+ }
+ loadStepCounts: () => {
+ value: true
+ }
+ loadStepCountsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadStepCountsSuccess: (
+ stepCounts: Record<string, HogFlowEditorActionMetrics> | null,
+ payload?: {
+ value: true
+ }
+ ) => {
+ stepCounts: Record<string, HogFlowEditorActionMetrics> | null
+ payload?: {
+ value: true
+ }
+ }
+ openCommandPalette: (query?: string) => {
+ query: string
+ }
+ openPanel: (mode: TileCanvasPanelMode) => {
+ mode: TileCanvasPanelMode
+ }
+ openPath: (groupId: string) => {
+ groupId: string
+ }
+ openQuickAdd: (edgeKey: string) => {
+ edgeKey: string
+ }
+ openStepMenu: (
+ actionId: string,
+ fromKeyboard?: any
+ ) => {
+ actionId: string
+ fromKeyboard: any
+ }
+ placeAt: (edge: HogFlowEdge) => {
+ edge: HogFlowEdge
+ }
+ requestFit: () => {
+ value: true
+ }
+ revealStep: (
+ actionId: string,
+ openPanel?: boolean
+ ) => {
+ actionId: string
+ openPanel: boolean
+ }
+ selectStep: (actionId: string) => {
+ actionId: string
+ }
+ setLayout: (
+ layout: CanvasLayout,
+ laidOutGraph?: VisibleGraph | null
+ ) => {
+ laidOutGraph: VisibleGraph | null
+ layout: CanvasLayout
+ }
+ setLayoutError: (message: string) => {
+ message: string
+ }
+ setMeasuredSizes: (sizes: Record<string, NodeSize>) => {
+ sizes: Record<string, NodeSize>
+ }
+ setMotion: (motion: CanvasMotion | null) => {
+ motion: CanvasMotion | null
+ }
+ setOpenPathIds: (openPathIds: string[]) => {
+ openPathIds: string[]
+ }
+ setPendingPathFocus: (pendingPathFocus: PendingPathFocus | null) => {
+ pendingPathFocus: PendingPathFocus | null
+ }
+ startPlacing: (step: CreateActionType) => {
+ step: CreateActionType
+ }
+ toggleAllPaths: () => {
+ value: true
+ }
+ togglePanel: (mode: TileCanvasPanelMode) => {
+ mode: TileCanvasPanelMode
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface tileCanvasLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ pathGroups: (workflow: HogFlow) => PathGroup[]
+ stepMetrics: (
+ workflow: HogFlow,
+ stepCounts: Record<string, HogFlowEditorActionMetrics> | null
+ ) => Record<string, HogFlowEditorActionMetrics> | null
+ countOf: (stepMetrics: Record<string, HogFlowEditorActionMetrics> | null) => StepCountOf
+ templateNameOf: (hogFunctionTemplatesById: Record<string, HogFunctionTemplateType>) => TemplateNameOf
+ selectedStepId: (isPanelOpen: boolean, selectedNodeId: string | null) => string | null
+ visibleGraph: (workflow: HogFlow, pathGroups: PathGroup[], openPathIds: string[]) => VisibleGraph
+ frameSpecs: (pathGroups: PathGroup[], openPathIds: string[], visibleGraph: VisibleGraph) => PathFrameSpec[]
+ drawnGraph: (visibleGraph: VisibleGraph, laidOutGraph: VisibleGraph | null) => VisibleGraph
+ allPathsCollapsed: (pathGroups: PathGroup[], openPathIds: string[]) => boolean
+ isSavedWorkflow: (workflow: HogFlow) => boolean
+ panelMode: (
+ isPanelOpen: boolean,
+ isHistoryOpen: boolean,
+ mode: 'build' | 'logs' | 'metrics' | 'test' | 'variables'
+ ) => TileCanvasPanelMode | null
+ isPlacing: (
+ nodeToBeAdded: CreateActionType | HogFlowActionNode | null,
+ isMovingNode: boolean,
+ isCopyingNode: boolean
+ ) => boolean
+ paletteSections: (
+ featureFlags: FeatureFlagsSet,
+ currentTeam: TeamPublicType | TeamType | null,
+ isRowScopedTrigger: boolean,
+ hogFunctionTemplatesById: Record<string, HogFunctionTemplateType>
+ ) => PaletteSection[]
+ }
+}
+
+export type tileCanvasLogicType = MakeLogicType<
+ tileCanvasLogicValues,
+ tileCanvasLogicActions,
+ WorkflowLogicProps,
+ tileCanvasLogicMeta
+>
+
+export const tileCanvasLogic = kea<tileCanvasLogicType>([
+ props({} as WorkflowLogicProps),
+ key((props) => `tile-canvas-${props.id}-${props.templateId || 'default'}-${props.editTemplateId || 'default'}`),
+ path((key) => ['products', 'workflows', 'tileCanvasLogic', key]),
+ connect(() => ({
+ values: [
+ workflowLogic,
+ ['workflow', 'originalWorkflow', 'hasUnsavedChanges', 'isRowScopedTrigger', 'hogFunctionTemplatesById'],
+ hogFlowEditorLogic,
+ [
+ 'nodeToBeAdded',
+ 'isMovingNode',
+ 'isCopyingNode',
+ 'dropzoneNodes',
+ 'selectedNodeId',
+ 'selectedNode',
+ 'selectedNodeCanBeDeleted',
+ 'selectedNodeCanBeCopiedOrMoved',
+ 'mode',
+ ],
+ featureFlagLogic,
+ ['featureFlags'],
+ sceneLayoutLogic,
+ ['sceneTakeoverActive'],
+ teamLogic,
+ ['currentTeam'],
+ ],
+ actions: [
+ workflowLogic,
+ ['discardChanges'],
+ hogFlowEditorLogic,
+ [
+ 'setSelectedNodeId',
+ 'setMode',
+ 'setNodeToBeAdded',
+ 'onDrop',
+ 'stopMovingNode',
+ 'stopCopyingNode',
+ 'setHighlightedDropzoneNodeId',
+ 'moveNodeToHighlightedDropzone',
+ 'copyNodeToHighlightedDropzone',
+ 'handlePaneClick',
+ 'startCopyingNode',
+ 'startMovingNode',
+ 'onNodesDelete',
+ ],
+ ],
+ })),
+ actions({
+ activateNode: (nodeId: string) => ({ nodeId }),
+ openPath: (groupId: string) => ({ groupId }),
+ focusPath: (place: PathPlace, anchor: PathPlace | null = null) => ({ place, anchor }),
+ focusPathAfterLayout: (groupId: string) => ({ groupId }),
+ setPendingPathFocus: (pendingPathFocus: PendingPathFocus | null) => ({ pendingPathFocus }),
+ collapsePath: (groupId: string) => ({ groupId }),
+ toggleAllPaths: true,
+ setOpenPathIds: (openPathIds: string[]) => ({ openPathIds }),
+ setMotion: (motion: CanvasMotion | null) => ({ motion }),
+ openCommandPalette: (query: string = '') => ({ query }),
+ closeCommandPalette: true,
+ openQuickAdd: (edgeKey: string) => ({ edgeKey }),
+ closeQuickAdd: true,
+ openStepMenu: (actionId: string, fromKeyboard = false) => ({ actionId, fromKeyboard }),
+ closeStepMenu: true,
+ startPlacing: (step: CreateActionType) => ({ step }),
+ addStepAt: (step: CreateActionType, edge: HogFlowEdge) => ({ step, edge }),
+ placeAt: (edge: HogFlowEdge) => ({ edge }),
+ selectStep: (actionId: string) => ({ actionId }),
+ revealStep: (actionId: string, openPanel: boolean = true) => ({ actionId, openPanel }),
+ openPanel: (mode: TileCanvasPanelMode) => ({ mode }),
+ togglePanel: (mode: TileCanvasPanelMode) => ({ mode }),
+ closePanel: true,
+ cancel: true,
+ setMeasuredSizes: (sizes: Record<string, NodeSize>) => ({ sizes }),
+ setLayout: (layout: CanvasLayout, laidOutGraph: VisibleGraph | null = null) => ({ layout, laidOutGraph }),
+ setLayoutError: (message: string) => ({ message }),
+ requestFit: true,
+ fitNextLayout: true,
+ loadStepCounts: true,
+ }),
+ reducers({
+ openPathIds: [[] as string[], { setOpenPathIds: (_, { openPathIds }) => openPathIds }],
+ pendingPathFocus: [
+ null as PendingPathFocus | null,
+ {
+ setPendingPathFocus: (_, { pendingPathFocus }) => pendingPathFocus,
+ focusPathAfterLayout: (_, { groupId }) => ({ groupId, shows: 'frame', anchor: null }),
+ focusPath: () => null,
+ toggleAllPaths: () => null,
+ },
+ ],
+ viewportFocus: [
+ null as ViewportFocus | null,
+ { focusPath: (state, { place, anchor }) => ({ place, anchor, request: (state?.request ?? 0) + 1 }) },
+ ],
+ motion: [null as CanvasMotion | null, { setMotion: (_, { motion }) => motion }],
+ placingSource: [
+ 'command bar' as StepAddSource,
+ { openCommandPalette: (_, { query }) => (query ? 'palette' : 'command bar') },
+ ],
+ commandPaletteQuery: [
+ null as string | null,
+ {
+ openCommandPalette: (_, { query }) => query,
+ closeCommandPalette: () => null,
+ openQuickAdd: () => null,
+ cancel: () => null,
+ },
+ ],
+ quickAddEdgeKey: [
+ null as string | null,
+ {
+ openQuickAdd: (_, { edgeKey }) => edgeKey,
+ closeQuickAdd: () => null,
+ openCommandPalette: () => null,
+ cancel: () => null,
+ },
+ ],
+ isPanelOpen: [
+ false,
+ {
+ openPanel: () => true,
+ closePanel: () => false,
+ cancel: () => false,
+ revealStep: (state, { openPanel }) => openPanel || state,
+ },
+ ],
+ isHistoryOpen: [
+ false,
+ {
+ openPanel: (_, { mode }) => mode === 'history',
+ selectStep: () => false,
+ closePanel: () => false,
+ cancel: () => false,
+ setSelectedNodeId: (state, { selectedNodeId }) => (selectedNodeId ? false : state),
+ },
+ ],
+ stepMenuFromKeyboard: [
+ false,
+ { openStepMenu: (_, { fromKeyboard }) => fromKeyboard, closeStepMenu: () => false, cancel: () => false },
+ ],
+ stepMenuActionId: [
+ null as string | null,
+ {
+ openStepMenu: (_, { actionId }) => actionId,
+ closeStepMenu: () => null,
+ cancel: () => null,
+ setSelectedNodeId: (state, { selectedNodeId }) => (selectedNodeId === state ? state : null),
+ },
+ ],
+ measuredSizes: [null as Record<string, NodeSize> | null, { setMeasuredSizes: (_, { sizes }) => sizes }],
+ layout: [null as CanvasLayout | null, { setLayout: (_, { layout }) => layout }],
+ laidOutGraph: [null as VisibleGraph | null, { setLayout: (_, { laidOutGraph }) => laidOutGraph }],
+ layoutError: [null as string | null, { setLayoutError: (_, { message }) => message, setLayout: () => null }],
+ fitRequest: [0, { requestFit: (count) => count + 1 }],
+ fitsNextLayout: [true, { fitNextLayout: () => true, requestFit: () => false, focusPath: () => false }],
+ }),
+ loaders(({ values }) => ({
+ stepCounts: [
+ null as Record<string, HogFlowEditorActionMetrics> | null,
+ {
+ loadStepCounts: async (_, breakpoint) => {
+ const request = stepCountsRequest(values.workflow, new Date())
+ if (!request) {
+ return null
+ }
+ await breakpoint(10)
+ const response = await loadAppMetricsTotals(request, values.currentTeam?.timezone ?? 'UTC')
+ breakpoint()
+ return actionMetricsFromTotals(response)
+ },
+ },
+ ],
+ })),
+ selectors({
+ pathGroups: [(s) => [s.workflow], (workflow: HogFlow): PathGroup[] => computePathGroups(workflow)],
+ stepMetrics: [
+ (s) => [s.workflow, s.stepCounts],
+ (
+ workflow: HogFlow,
+ stepCounts: Record<string, HogFlowEditorActionMetrics> | null
+ ): Record<string, HogFlowEditorActionMetrics> | null => countableStepMetrics(workflow, stepCounts),
+ ],
+ countOf: [
+ (s) => [s.stepMetrics],
+ (stepMetrics: Record<string, HogFlowEditorActionMetrics> | null): StepCountOf =>
+ (actionId) =>
+ stepCount(stepMetrics, actionId),
+ ],
+ templateNameOf: [
+ (s) => [s.hogFunctionTemplatesById],
+ (templates: Record<string, HogFunctionTemplateType>): TemplateNameOf =>
+ (templateId) =>
+ templates[templateId]?.name,
+ ],
+ selectedStepId: [
+ (s) => [s.isPanelOpen, s.selectedNodeId],
+ (isPanelOpen: boolean, selectedNodeId: string | null): string | null =>
+ isPanelOpen ? selectedNodeId : null,
+ ],
+ visibleGraph: [
+ (s) => [s.workflow, s.pathGroups, s.openPathIds],
+ (workflow: HogFlow, groups: PathGroup[], openPathIds: string[]): VisibleGraph =>
+ computeVisibleGraph(workflow, groups, openPathIds),
+ ],
+ frameSpecs: [
+ (s) => [s.pathGroups, s.openPathIds, s.visibleGraph],
+ (groups: PathGroup[], openPathIds: string[], graph: VisibleGraph): PathFrameSpec[] =>
+ pathFrameSpecs(groups, openPathIds, graph.nodes),
+ ],
+ drawnGraph: [
+ (s) => [s.visibleGraph, s.laidOutGraph],
+ (graph: VisibleGraph, laidOutGraph: VisibleGraph | null): VisibleGraph =>
+ withLeavingStacks(graph, laidOutGraph),
+ ],
+ allPathsCollapsed: [
+ (s) => [s.pathGroups, s.openPathIds],
+ (groups: PathGroup[], openPathIds: string[]): boolean =>
+ groups.length > 0 && groups.every((group) => !openPathIds.includes(group.id)),
+ ],
+ isSavedWorkflow: [(s) => [s.workflow], (workflow: HogFlow): boolean => !!workflow.id && workflow.id !== 'new'],
+ panelMode: [
+ (s) => [s.isPanelOpen, s.isHistoryOpen, s.mode],
+ (isPanelOpen: boolean, isHistoryOpen: boolean, mode: HogFlowEditorMode): TileCanvasPanelMode | null =>
+ isPanelOpen ? (isHistoryOpen ? 'history' : mode) : null,
+ ],
+ isPlacing: [
+ (s) => [s.nodeToBeAdded, s.isMovingNode, s.isCopyingNode],
+ (
+ nodeToBeAdded: CreateActionType | HogFlowActionNode | null,
+ isMovingNode: boolean,
+ isCopyingNode: boolean
+ ): boolean => !!nodeToBeAdded || isMovingNode || isCopyingNode,
+ ],
+ paletteSections: [
+ (s) => [s.featureFlags, s.currentTeam, s.isRowScopedTrigger, s.hogFunctionTemplatesById],
+ (
+ featureFlags: FeatureFlagsSet,
+ currentTeam: TeamPublicType | TeamType | null,
+ isRowScopedTrigger: boolean,
+ hogFunctionTemplatesById: Record<string, HogFunctionTemplateType>
+ ): PaletteSection[] => {
+ const destinations = destinationSteps(Object.values(hogFunctionTemplatesById))
+ return [
+ ...workflowStepSections({ featureFlags, currentTeam, isRowScopedTrigger }),
+ ...(destinations.length ? [{ title: 'More destinations', steps: destinations }] : []),
+ ]
+ },
+ ],
+ }),
+ listeners(({ actions, values, cache }) => {
+ const beginPathMotion = (motion: CanvasMotion): void => {
+ actions.setMotion(motion)
+ cache.disposables.add(() => {
+ const timer = window.setTimeout(() => actions.setMotion(null), PATH_MOTION_MS)
+ return () => window.clearTimeout(timer)
+ }, 'motion')
+ }
+ const capturePathToggled = (change: 'opened' | 'collapsed', groupId: string): void => {
+ const depth = values.pathGroups.find((group) => group.id === groupId)?.depth ?? 0
+ posthog.capture(`workflows tile canvas path ${change}`, { depth })
+ }
+ const dropPendingMoveOrCopy = (): void => {
+ if (values.isMovingNode) {
+ actions.stopMovingNode()
+ }
+ if (values.isCopyingNode) {
+ actions.stopCopyingNode()
+ }
+ }
+ /** A step that was just added or picked elsewhere must not stay hidden inside a stack. */
+ const revealContainingPaths = (actionId: string): void => {
+ const isHidden = collapsedPathStacks(values.pathGroups, values.openPathIds).some((group) =>
+ group.members.has(actionId)
+ )
+ if (!isHidden) {
+ return
+ }
+ const containing = values.pathGroups.filter((group) => group.members.has(actionId))
+ const innermost = containing.reduce((deepest, group) => (group.depth > deepest.depth ? group : deepest))
+ actions.setOpenPathIds([...new Set([...values.openPathIds, ...containing.map((group) => group.id)])])
+ actions.focusPathAfterLayout(innermost.id)
+ }
+ const placeExistingStep = (edge: HogFlowEdge): void => {
+ const dropzone = values.dropzoneNodes.find((zone) => zone.data.edge.id === getEdgeId(edge))
+ if (!dropzone) {
+ return
+ }
+ actions.setHighlightedDropzoneNodeId(dropzone.id)
+ if (values.isMovingNode) {
+ actions.moveNodeToHighlightedDropzone()
+ } else {
+ actions.copyNodeToHighlightedDropzone()
+ }
+ }
+ const placeNewStep = (edge: HogFlowEdge, step: CreateActionType | HogFlowActionNode): void => {
+ actions.onDrop(undefined, edge)
+ captureStepAdded(values.placingSource, 'data' in step ? step.data.type : step.type)
+ }
+ return {
+ activateNode: ({ nodeId }) => {
+ const node = values.visibleGraph.nodes.find((candidate) => candidate.id === nodeId)
+ if (node?.kind === 'step') {
+ actions.selectStep(nodeId)
+ } else if (node?.kind === 'stack') {
+ actions.openPath(nodeId)
+ }
+ },
+ openPath: ({ groupId }) => {
+ capturePathToggled('opened', groupId)
+ actions.setPendingPathFocus({
+ groupId,
+ shows: 'frame',
+ anchor: stackPlace(values.layout, values.measuredSizes, groupId),
+ })
+ beginPathMotion({
+ kind: 'expand',
+ groupId,
+ origin: stackOrigin(values.layout, values.measuredSizes, groupId),
+ })
+ actions.setOpenPathIds([...values.openPathIds, groupId])
+ },
+ collapsePath: ({ groupId }) => {
+ const group = values.pathGroups.find((candidate) => candidate.id === groupId)
+ if (!group) {
+ return
+ }
+ const origin = frameOrigin(values.layout, group)
+ capturePathToggled('collapsed', groupId)
+ actions.setPendingPathFocus({
+ groupId,
+ shows: 'stack',
+ anchor: framePlace(values.layout, group, values.visibleGraph.edges),
+ })
+ beginPathMotion({ kind: 'collapse', groupId, origin })
+ cache.disposables.add(() => {
+ const timer = window.setTimeout(() => {
+ actions.setOpenPathIds(values.openPathIds.filter((id) => id !== groupId))
+ beginPathMotion({ kind: 'settle', groupId, origin })
+ }, PATH_LEAVE_MS)
+ return () => window.clearTimeout(timer)
+ }, `collapse:${groupId}`)
+ },
+ toggleAllPaths: () => {
+ actions.fitNextLayout()
+ actions.setOpenPathIds(values.allPathsCollapsed ? values.pathGroups.map((group) => group.id) : [])
+ },
+ setSelectedNodeId: ({ selectedNodeId }) => {
+ if (selectedNodeId) {
+ actions.revealStep(selectedNodeId, values.stepMenuActionId !== selectedNodeId)
+ }
+ },
+ revealStep: ({ actionId }) => revealContainingPaths(actionId),
+ startPlacing: ({ step }) => {
+ dropPendingMoveOrCopy()
+ actions.setNodeToBeAdded(step)
+ },
+ addStepAt: ({ step, edge }) => {
+ dropPendingMoveOrCopy()
+ actions.setNodeToBeAdded(step)
+ actions.onDrop(undefined, edge)
+ captureStepAdded('quick add', step.type)
+ },
+ placeAt: ({ edge }) => {
+ if (values.isMovingNode || values.isCopyingNode) {
+ placeExistingStep(edge)
+ } else if (values.nodeToBeAdded) {
+ placeNewStep(edge, values.nodeToBeAdded)
+ }
+ },
+ openStepMenu: ({ actionId }) => {
+ // The copy, move and delete rules read the selected step, so the step under the menu must be the selected one.
+ actions.setSelectedNodeId(actionId)
+ },
+ closeStepMenu: () => {
+ // The menu picked the step only for its own rules, so the next panel must not open scoped to it.
+ if (!values.isPanelOpen) {
+ actions.setSelectedNodeId(null)
+ }
+ },
+ selectStep: ({ actionId }) => {
+ actions.setMode('build')
+ actions.setSelectedNodeId(actionId)
+ },
+ openPanel: ({ mode }) => {
+ if (mode === 'history') {
+ actions.setSelectedNodeId(null)
+ } else {
+ actions.setMode(mode)
+ }
+ },
+ togglePanel: ({ mode }) => {
+ posthog.capture('workflows tile canvas panel toggled', { mode, open: values.panelMode !== mode })
+ if (values.panelMode === mode) {
+ actions.closePanel()
+ } else {
+ actions.openPanel(mode)
+ }
+ },
+ closePanel: () => {
+ actions.setSelectedNodeId(null)
+ },
+ handlePaneClick: () => {
+ actions.closePanel()
+ // The editor stops copying on a pane click but keeps the copied step, which would make the next + place it.
+ actions.setNodeToBeAdded(null)
+ },
+ cancel: () => {
+ actions.setSelectedNodeId(null)
+ actions.setNodeToBeAdded(null)
+ dropPendingMoveOrCopy()
+ },
+ setMeasuredSizes: async ({ sizes }, breakpoint) => {
+ await breakpoint(10)
+ const graph = values.visibleGraph
+ const input = { sizes, edges: graph.edges, frames: values.frameSpecs }
+ // Measuring again after fonts load or a re-render often finds nothing new, and a fresh layout would restart the motion.
+ if (objectsEqual(input, cache.layoutInput)) {
+ return
+ }
+ try {
+ const layout = await layoutTileCanvas(sizes, input.edges, input.frames)
+ breakpoint()
+ cache.layoutInput = input
+ actions.setLayout(layout, graph)
+ } catch (error) {
+ if (isBreakpoint(error as Error)) {
+ throw error
+ }
+ breakpoint()
+ cache.layoutInput = input
+ actions.setLayoutError(error instanceof Error ? error.message : String(error))
+ }
+ },
+ setLayout: ({ layout }) => {
+ const focus = values.pendingPathFocus
+ const group = focus && values.pathGroups.find((candidate) => candidate.id === focus.groupId)
+ const place =
+ group &&
+ (focus.shows === 'frame'
+ ? framePlace(layout, group, values.visibleGraph.edges)
+ : stackPlace(layout, values.measuredSizes, group.id))
+ if (focus && place) {
+ actions.focusPath(place, focus.anchor)
+ } else if (values.fitsNextLayout) {
+ actions.requestFit()
+ }
+ },
+ }
+ }),
+ subscriptions(({ actions, values }) => ({
+ originalWorkflow: (workflow: HogFlow | null, previous: HogFlow | null | undefined): void => {
+ if (workflow && !previous) {
+ posthog.capture('workflows tile canvas opened', {
+ step_count: workflow.actions.length,
+ path_count: values.pathGroups.length,
+ })
+ }
+ },
+ workflow: (workflow: HogFlow, previous: HogFlow | undefined): void => {
+ if (workflow.id !== previous?.id || workflow.trigger?.type !== previous?.trigger?.type) {
+ actions.loadStepCounts()
+ }
+ },
+ })),
+ afterMount(({ actions, values, cache }) => {
+ // The step can be picked before the canvas mounts, from the tree view or a link to the step.
+ if (values.selectedNodeId) {
+ actions.revealStep(values.selectedNodeId)
+ }
+ cache.disposables.add(() => {
+ const onKeyDown = (event: KeyboardEvent): void => {
+ // A takeover such as the email editor covers the canvas, and Escape there must not close the panel it lives in.
+ if (values.sceneTakeoverActive || belongsToAnotherSurface(event)) {
+ return
+ }
+ if (event.key === 'Escape') {
+ actions.cancel()
+ } else if (isPrintableKey(event) && isTypedOnCanvas(event) && values.commandPaletteQuery === null) {
+ event.preventDefault()
+ actions.openCommandPalette(event.key)
+ }
+ }
+ window.addEventListener('keydown', onKeyDown)
+ return () => window.removeEventListener('keydown', onKeyDown)
+ })
+ }),
+])
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasModel.test.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasModel.test.ts
new file mode 100644
index 000000000000..8daa4a3fbd7c
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasModel.test.ts
@@ -0,0 +1,582 @@
+import type { HogFlow, HogFlowAction, HogFlowEdge } from '../../types'
+import {
+ computePathGroups,
+ computeVisibleGraph,
+ countableStepMetrics,
+ filterPaletteItems,
+ isHeadingToRect,
+ layoutMiniFlow,
+ PaletteCommand,
+ PaletteSection,
+ PathPlace,
+ stepCount,
+ stepCountsRequest,
+ viewportAfterResize,
+ readableFitViewport,
+ viewportAnchoredOn,
+ viewportToFit,
+} from './tileCanvasModel'
+
+const step = (id: string, type: HogFlowAction['type'] = 'function'): HogFlowAction =>
+ ({ id, type, name: id, description: '', config: {} }) as HogFlowAction
+
+const next = (from: string, to: string): HogFlowEdge => ({ from, to, type: 'continue' })
+const branch = (from: string, to: string, index = 0): HogFlowEdge => ({ from, to, type: 'branch', index })
+
+const flow = (actions: HogFlowAction[], edges: HogFlowEdge[]): Pick<HogFlow, 'actions' | 'edges'> => ({
+ actions,
+ edges,
+})
+
+// trigger -> split, whose branch path holds two steps and whose other path holds one, both joining at exit
+const splitWithLongAndShortPath = (splitType: HogFlowAction['type']): Pick<HogFlow, 'actions' | 'edges'> =>
+ flow(
+ [
+ step('trigger', 'trigger'),
+ step('split', splitType),
+ step('a1'),
+ step('a2'),
+ step('b1'),
+ step('exit', 'exit'),
+ ],
+ [
+ next('trigger', 'split'),
+ branch('split', 'a1'),
+ next('a1', 'a2'),
+ next('a2', 'exit'),
+ next('split', 'b1'),
+ next('b1', 'exit'),
+ ]
+ )
+
+// The outer split's branch path holds an inner split with two paths of two steps each
+const nestedSplits = flow(
+ [
+ step('trigger', 'trigger'),
+ step('outer', 'conditional_branch'),
+ step('inner', 'conditional_branch'),
+ step('x1'),
+ step('x2'),
+ step('y1'),
+ step('y2'),
+ step('other'),
+ step('exit', 'exit'),
+ ],
+ [
+ next('trigger', 'outer'),
+ branch('outer', 'inner'),
+ branch('inner', 'x1'),
+ next('x1', 'x2'),
+ next('x2', 'exit'),
+ next('inner', 'y1'),
+ next('y1', 'y2'),
+ next('y2', 'exit'),
+ next('outer', 'other'),
+ next('other', 'exit'),
+ ]
+)
+
+describe('tileCanvasModel', () => {
+ it.each(['conditional_branch', 'random_cohort_branch', 'wait_until_condition'] as const)(
+ 'groups a %s path only when it holds two or more steps',
+ (splitType) => {
+ const groups = computePathGroups(splitWithLongAndShortPath(splitType))
+
+ expect(groups.map((group) => ({ branch: group.branchActionId, members: group.memberIds }))).toEqual([
+ { branch: 'split', members: ['a1', 'a2'] },
+ ])
+ }
+ )
+
+ it('gives a nested path its enclosing path as parent', () => {
+ const groups = computePathGroups(nestedSplits)
+ const outer = groups.find((group) => group.branchActionId === 'outer')
+ const inner = groups.filter((group) => group.branchActionId === 'inner')
+
+ expect(outer?.memberIds).toEqual(expect.arrayContaining(['inner', 'x1', 'x2', 'y1', 'y2']))
+ expect(inner.map((group) => [group.memberIds, group.parentId, group.depth])).toEqual([
+ [['x1', 'x2'], outer?.id, 1],
+ [['y1', 'y2'], outer?.id, 1],
+ ])
+ })
+
+ it.each([
+ {
+ name: 'steps stored out of flow order',
+ workflow: flow(
+ [
+ step('exit', 'exit'),
+ step('a2'),
+ step('b1'),
+ step('a1'),
+ step('split', 'conditional_branch'),
+ step('trigger', 'trigger'),
+ ],
+ splitWithLongAndShortPath('conditional_branch').edges
+ ),
+ splitId: 'split',
+ members: ['a1', 'a2'],
+ },
+ {
+ name: 'a step inserted before the first step of the path',
+ workflow: flow(
+ [...splitWithLongAndShortPath('conditional_branch').actions, step('first')],
+ [
+ next('trigger', 'split'),
+ branch('split', 'first'),
+ next('first', 'a1'),
+ next('a1', 'a2'),
+ next('a2', 'exit'),
+ next('split', 'b1'),
+ next('b1', 'exit'),
+ ]
+ ),
+ splitId: 'split',
+ members: ['first', 'a1', 'a2'],
+ },
+ {
+ name: 'a nested split, one inner path after the other',
+ workflow: flow([...nestedSplits.actions].reverse(), nestedSplits.edges),
+ splitId: 'outer',
+ members: ['inner', 'x1', 'x2', 'y1', 'y2'],
+ },
+ ])('orders a path the way people move through it: $name', ({ workflow, splitId, members }) => {
+ const group = computePathGroups(workflow).find((candidate) => candidate.branchActionId === splitId)
+
+ expect(group?.memberIds).toEqual(members)
+ })
+
+ it('lists the visible steps in flow order, whatever order they are stored in', () => {
+ const workflow = flow([...nestedSplits.actions].reverse(), nestedSplits.edges)
+
+ const graph = computeVisibleGraph(workflow, [], [])
+
+ expect(graph.nodes.map((node) => node.id)).toEqual([
+ 'trigger',
+ 'outer',
+ 'inner',
+ 'x1',
+ 'x2',
+ 'y1',
+ 'y2',
+ 'other',
+ 'exit',
+ ])
+ })
+
+ it('folds the paths of a split inside a retry loop, while the retry path itself stays open', () => {
+ const retry = flow(
+ [
+ step('trigger', 'trigger'),
+ step('start'),
+ step('split', 'conditional_branch'),
+ step('a1'),
+ step('a2'),
+ step('b1'),
+ step('b2'),
+ step('check', 'conditional_branch'),
+ step('exit', 'exit'),
+ ],
+ [
+ next('trigger', 'start'),
+ next('start', 'split'),
+ branch('split', 'a1'),
+ next('a1', 'a2'),
+ next('a2', 'check'),
+ next('split', 'b1'),
+ next('b1', 'b2'),
+ next('b2', 'check'),
+ branch('check', 'start'),
+ next('check', 'exit'),
+ ]
+ )
+
+ expect(computePathGroups(retry).map((group) => group.memberIds)).toEqual([
+ ['a1', 'a2'],
+ ['b1', 'b2'],
+ ])
+ })
+
+ it('leaves paths that loop back into each other ungrouped', () => {
+ const loop = flow(
+ [
+ step('trigger', 'trigger'),
+ step('s', 'conditional_branch'),
+ step('a'),
+ step('t', 'conditional_branch'),
+ step('b'),
+ step('exit', 'exit'),
+ ],
+ [
+ next('trigger', 's'),
+ branch('s', 'a'),
+ next('a', 't'),
+ next('s', 'exit'),
+ branch('t', 'b'),
+ next('b', 's'),
+ next('t', 'exit'),
+ ]
+ )
+
+ const groups = computePathGroups(loop)
+
+ expect(groups).toEqual([])
+ expect(computeVisibleGraph(loop, groups, []).nodes.map((node) => node.id)).toEqual([
+ 'trigger',
+ 's',
+ 'a',
+ 't',
+ 'b',
+ 'exit',
+ ])
+ })
+
+ it('draws a collapsed path as one stack that takes over its arrows', () => {
+ const workflow = splitWithLongAndShortPath('conditional_branch')
+ const [group] = computePathGroups(workflow)
+
+ const graph = computeVisibleGraph(workflow, [group], [])
+
+ expect(graph.nodes.map((node) => node.id)).toEqual(['trigger', 'split', group.id, 'b1', 'exit'])
+ expect(graph.edges.map((edge) => [edge.source, edge.target])).toEqual(
+ expect.arrayContaining([
+ ['split', group.id],
+ [group.id, 'exit'],
+ ])
+ )
+ })
+
+ it('hides the paths inside a collapsed path, and shows the steps of an open one', () => {
+ const groups = computePathGroups(nestedSplits)
+ const outer = groups.find((group) => group.branchActionId === 'outer')!
+ const inner = groups.filter((group) => group.branchActionId === 'inner')
+
+ const outerCollapsed = computeVisibleGraph(nestedSplits, groups, [])
+ expect(outerCollapsed.nodes.filter((node) => node.kind === 'stack').map((node) => node.id)).toEqual([outer.id])
+
+ const outerOpen = computeVisibleGraph(nestedSplits, groups, [outer.id])
+ expect(outerOpen.nodes.map((node) => node.id)).toEqual(
+ expect.arrayContaining(['inner', inner[0].id, inner[1].id])
+ )
+ expect(outerOpen.nodes.map((node) => node.id)).not.toContain('x1')
+ })
+
+ it('lays a path out left to right, stacking a fork in one column around its split', () => {
+ const workflow = flow(
+ [step('split', 'conditional_branch'), step('yes'), step('no'), step('after')],
+ [branch('split', 'yes'), next('split', 'no'), next('yes', 'after')]
+ )
+
+ const layout = layoutMiniFlow(workflow, ['split', 'yes', 'no', 'after'], { tile: 32, gapX: 30, gapY: 50 })
+ const at = Object.fromEntries(layout.nodes.map((node) => [node.actionId, { x: node.x, y: node.y }]))
+
+ expect(at).toEqual({
+ split: { x: 0, y: 25 },
+ yes: { x: 62, y: 0 },
+ no: { x: 62, y: 50 },
+ after: { x: 124, y: 25 },
+ })
+ expect(layout.edges).toHaveLength(3)
+ expect(layout.width).toBe(156)
+ })
+
+ it.each([
+ ['straight toward the preview', { x: 100, y: 150 }, true],
+ ['sideways away from the preview', { x: 10, y: 110 }, false],
+ ['past the side of the preview', { x: 400, y: 190 }, false],
+ ])('keeps the open preview while the pointer moves %s', (_, pointer, expected) => {
+ const apex = { x: 100, y: 100 }
+ const preview = { left: 40, right: 260, top: 200 }
+
+ expect(isHeadingToRect(pointer, apex, preview, 12)).toBe(expected)
+ })
+
+ it.each([
+ ['an empty search lists commands first', '', ['Fit to screen', 'Email', 'Delay']],
+ ['a search matches step descriptions and section names', 'wait', ['Delay']],
+ ['a search matches commands too', 'screen', ['Fit to screen']],
+ ['a search with no match lists nothing', 'zebra', []],
+ ])('filters the palette: %s', (_, query, expected) => {
+ const sections: PaletteSection[] = [
+ {
+ title: 'Send',
+ steps: [
+ {
+ type: 'function_email',
+ name: 'Email',
+ description: 'Send an email.',
+ config: { template_id: 'template-email', inputs: {} },
+ },
+ ],
+ },
+ {
+ title: 'Wait',
+ steps: [{ type: 'delay', name: 'Delay', description: 'Pause.', config: { delay_duration: '1h' } }],
+ },
+ ]
+ const commands: PaletteCommand[] = [{ id: 'fit', label: 'Fit to screen', hint: 'Show every step' }]
+
+ expect(filterPaletteItems(query, sections, commands).map((item) => item.label)).toEqual(expected)
+ })
+
+ it('keeps two destinations that share a name apart in the palette', () => {
+ const destination = (templateId: string): PaletteSection['steps'][number] => ({
+ type: 'function',
+ name: 'Hubspot',
+ description: '',
+ config: { template_id: templateId, inputs: {} },
+ })
+ const sections = [
+ { title: 'More destinations', steps: [destination('hubspot'), destination('hubspot-contacts')] },
+ ]
+
+ const keys = filterPaletteItems('', sections, []).map((item) => item.key)
+
+ expect(new Set(keys).size).toBe(2)
+ })
+
+ it('counts every person a step handled once metrics load', () => {
+ const metrics = { email: { actionId: 'email', succeeded: 40, failed: 2, filtered: 8 } }
+
+ expect(stepCount(metrics, 'email')).toBe(50)
+ expect(stepCount(metrics, 'delay')).toBe(0)
+ expect(stepCount(null, 'email')).toBeUndefined()
+ expect(stepCount({}, 'email')).toBeUndefined()
+ })
+
+ it.each([
+ {
+ name: 'keeps the middle of the view when the panel opens',
+ startX: 100,
+ previousWidth: 1200,
+ nextWidth: 600,
+ focus: undefined,
+ expected: { x: -200, y: 50, zoom: 0.5 },
+ },
+ {
+ name: 'gives the view back when the panel closes',
+ startX: -200,
+ previousWidth: 600,
+ nextWidth: 1200,
+ focus: undefined,
+ expected: { x: 100, y: 50, zoom: 0.5 },
+ },
+ {
+ name: 'leaves a selected step that is still in view alone',
+ startX: 100,
+ previousWidth: 1200,
+ nextWidth: 600,
+ focus: { x: 1000, y: 0, width: 64, height: 64 },
+ expected: { x: -200, y: 50, zoom: 0.5 },
+ },
+ {
+ name: 'pulls a selected step back in from the right edge',
+ startX: 100,
+ previousWidth: 1200,
+ nextWidth: 600,
+ focus: { x: 1600, y: 0, width: 64, height: 64 },
+ expected: { x: -256, y: 50, zoom: 0.5 },
+ },
+ {
+ name: 'pulls a selected step back in from the left edge',
+ startX: 100,
+ previousWidth: 1200,
+ nextWidth: 600,
+ focus: { x: 0, y: 0, width: 64, height: 64 },
+ expected: { x: 24, y: 50, zoom: 0.5 },
+ },
+ ])('moves the viewport on a canvas resize: $name', ({ startX, previousWidth, nextWidth, focus, expected }) => {
+ const viewport = { x: startX, y: 50, zoom: 0.5 }
+
+ expect(
+ viewportAfterResize(
+ viewport,
+ { width: previousWidth, height: 800 },
+ { width: nextWidth, height: 800 },
+ focus
+ )
+ ).toEqual(expected)
+ })
+})
+
+describe('viewportToFit', () => {
+ const canvas = { width: 1000, height: 700 }
+
+ it.each([
+ {
+ name: 'centres a frame that already fits, at the zoom the person chose',
+ frame: { x: 100, y: 200, width: 400, height: 300 },
+ zoom: 0.8,
+ expected: { x: 260, y: 32 + (572 - 240) / 2 - 200 * 0.8, zoom: 0.8 },
+ },
+ {
+ name: 'zooms out until a wide frame fits, then centres it',
+ frame: { x: 0, y: 0, width: 1904, height: 300 },
+ zoom: 1,
+ expected: { x: 24, y: 32 + (572 - 150) / 2, zoom: 0.5 },
+ },
+ {
+ name: 'never zooms out further than the canvas allows',
+ frame: { x: 0, y: 0, width: 20000, height: 300 },
+ zoom: 1,
+ expected: { x: 500 - 10000 * 0.15, y: 32 + (572 - 45) / 2, zoom: 0.15 },
+ },
+ ])('$name', ({ frame, zoom, expected }) => {
+ const viewport = viewportToFit(frame, canvas, zoom)
+
+ expect(viewport.zoom).toBeCloseTo(expected.zoom)
+ expect(viewport.x).toBeCloseTo(expected.x)
+ expect(viewport.y).toBeCloseTo(expected.y)
+ })
+})
+
+describe('viewportAnchoredOn', () => {
+ const canvas = { width: 1000, height: 700 }
+ const place = (x: number, y: number, width: number, height: number, entryX = x + width / 2): PathPlace => ({
+ x,
+ y,
+ width,
+ height,
+ entry: { x: entryX, y },
+ })
+ const stack = place(400, 600, 180, 90, 430)
+ const entryOnScreen = (
+ of: PathPlace,
+ viewport: { x: number; y: number; zoom: number }
+ ): { x: number; y: number } => ({
+ x: viewport.x + of.entry.x * viewport.zoom,
+ y: viewport.y + of.entry.y * viewport.zoom,
+ })
+
+ it.each([
+ {
+ name: 'opens a path where the arrow met its stack, at the same zoom',
+ next: place(300, 620, 520, 300),
+ zoom: 1,
+ },
+ {
+ name: 'collapses a path into a stack where the arrow met its frame, even zoomed far out',
+ next: place(380, 1400, 180, 90, 410),
+ zoom: 0.2,
+ },
+ ])('$name', ({ next, zoom }) => {
+ const viewport = { x: 500 - 430 * zoom, y: 150 - 600 * zoom, zoom }
+
+ const anchored = viewportAnchoredOn(stack, next, viewport, canvas)
+
+ expect(anchored.zoom).toBe(zoom)
+ expect(entryOnScreen(next, anchored)).toEqual(entryOnScreen(stack, viewport))
+ })
+
+ it.each([
+ { name: 'zooms out just enough to show a tall frame from where its stack was', height: 692.5, zoom: 0.8 },
+ { name: 'stops zooming out at a readable zoom', height: 5000, zoom: 0.66 },
+ ])('$name', ({ height, zoom }) => {
+ const viewport = { x: 500 - 430, y: 50 - 600, zoom: 1 }
+ const frame = place(300, 620, 520, height)
+
+ const anchored = viewportAnchoredOn(stack, frame, viewport, canvas)
+
+ expect(anchored.zoom).toBeCloseTo(zoom)
+ expect(entryOnScreen(frame, anchored)).toEqual(entryOnScreen(stack, viewport))
+ })
+
+ it('keeps a zoom the person set below the readable one', () => {
+ const anchored = viewportAnchoredOn(stack, place(300, 620, 520, 5000), { x: 0, y: 0, zoom: 0.3 }, canvas)
+
+ expect(anchored.zoom).toBe(0.3)
+ })
+
+ it('slides a frame sideways into view when it would open past the edge of the canvas', () => {
+ const frame = place(300, 620, 520, 300, 750)
+
+ const anchored = viewportAnchoredOn(stack, frame, { x: 100 - 430, y: 150 - 600, zoom: 1 }, canvas)
+
+ expect(anchored.zoom).toBe(1)
+ expect({ left: anchored.x + frame.x, top: anchored.y + frame.y }).toEqual({ left: 24, top: 150 })
+ })
+
+ it('brings a stack into view when the frame it replaces started above the canvas', () => {
+ const frame = place(300, 0, 520, 3000)
+ const next = place(470, 0, 180, 90)
+
+ const anchored = viewportAnchoredOn(frame, next, { x: 0, y: -1000, zoom: 1 }, canvas)
+
+ expect(entryOnScreen(next, anchored)).toEqual({ x: 560, y: 32 })
+ })
+
+ it('centres a path that opens from a stack out of view', () => {
+ const frame = place(300, 620, 520, 300)
+
+ expect(viewportAnchoredOn(stack, frame, { x: 0, y: -5000, zoom: 1 }, canvas)).toEqual(
+ viewportToFit(frame, canvas, 1)
+ )
+ })
+})
+
+describe('readableFitViewport', () => {
+ const canvas = { width: 1000, height: 700 }
+ const entryOnScreen = (entry: { x: number; y: number }, viewport: { x: number; y: number; zoom: number }): number =>
+ viewport.x + entry.x * viewport.zoom
+
+ it.each([
+ { name: 'fits a small workflow at full size', bounds: { x: 0, y: 0, width: 400, height: 300 }, zoom: 1 },
+ {
+ name: 'keeps a wide workflow readable, for people to pan',
+ bounds: { x: 0, y: 0, width: 4000, height: 300 },
+ zoom: 0.66,
+ },
+ { name: 'keeps a long workflow readable too', bounds: { x: 0, y: 0, width: 400, height: 6000 }, zoom: 0.66 },
+ ])('$name', ({ bounds, zoom }) => {
+ expect(readableFitViewport(bounds, canvas, { x: bounds.width / 2, y: 0 }).zoom).toBeCloseTo(zoom)
+ })
+
+ it('starts a workflow too wide to fit at its trigger, in the middle of the canvas', () => {
+ const trigger = { x: 2000, y: 0 }
+
+ const viewport = readableFitViewport({ x: 0, y: 0, width: 4000, height: 300 }, canvas, trigger)
+
+ expect(entryOnScreen(trigger, viewport)).toBeCloseTo(500)
+ })
+
+ it('keeps the left edge of a wide workflow in view when its trigger sits near that edge', () => {
+ const viewport = readableFitViewport({ x: 0, y: 0, width: 4000, height: 300 }, canvas, { x: 100, y: 0 })
+
+ expect(viewport.x).toBeCloseTo(24)
+ })
+})
+
+describe('stepCountsRequest', () => {
+ const now = new Date('2026-10-13T12:00:00Z')
+
+ it('asks for every step and metric of the last seven days of a saved workflow', () => {
+ const workflow = { id: 'flow-1', trigger: { type: 'event' }, actions: Array(40).fill(step('a')) } as HogFlow
+
+ expect(stepCountsRequest(workflow, now)).toEqual({
+ appSource: 'hog_flow',
+ appSourceId: 'flow-1',
+ dateFrom: '2026-10-06T12:00:00.000Z',
+ dateTo: '2026-10-13T12:00:00.000Z',
+ breakdownBy: ['instance_id', 'metric_name'],
+ metricName: ['succeeded', 'failed', 'filtered', 'rate_limited', 'triggered'],
+ limit: 205,
+ })
+ })
+
+ it.each([
+ { name: 'an unsaved workflow', workflow: { id: 'new', trigger: { type: 'event' } } },
+ { name: 'a batch workflow', workflow: { id: 'flow-1', trigger: { type: 'batch' } } },
+ ])('skips $name', ({ workflow }) => {
+ expect(stepCountsRequest(workflow as HogFlow, now)).toBeNull()
+ })
+
+ it.each([
+ { name: 'keeps the counts of a saved workflow', trigger: 'event', expected: 50 },
+ { name: 'drops counts loaded before the trigger became a batch', trigger: 'batch', expected: undefined },
+ ])('$name', ({ trigger, expected }) => {
+ const metrics = { email: { actionId: 'email', succeeded: 40, failed: 2, filtered: 8 } }
+ const workflow = { id: 'flow-1', trigger: { type: trigger } } as HogFlow
+
+ expect(stepCount(countableStepMetrics(workflow, metrics), 'email')).toBe(expected)
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasModel.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasModel.ts
new file mode 100644
index 000000000000..26a42b2c8a8d
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasModel.ts
@@ -0,0 +1,878 @@
+import type { AppMetricsTotalsRequest } from 'lib/components/AppMetrics/appMetricsLogic'
+
+import { getEdgeId } from '../../edgeId'
+import type { CreateActionType, HogFlowEditorActionMetrics } from '../../hogFlowEditorLogic'
+import { getWorkflowBranchLabel, isBranchingAction } from '../../tree/workflowTree'
+import type { HogFlow, HogFlowAction, HogFlowEdge } from '../../types'
+
+export type FlowGraph = Pick<HogFlow, 'actions' | 'edges'>
+
+interface EdgeIndex {
+ outgoing: Map<string, HogFlowEdge[]>
+ /** The step every path out of a step passes through next, where its paths join again. */
+ joinOf: Map<string, string>
+}
+
+const edgeIndexes = new WeakMap<HogFlowEdge[], EdgeIndex>()
+const actionIndexes = new WeakMap<HogFlowAction[], Map<string, HogFlowAction>>()
+
+function byPathOrder(a: HogFlowEdge, b: HogFlowEdge): number {
+ return a.type !== b.type ? (a.type === 'branch' ? -1 : 1) : (a.index ?? 0) - (b.index ?? 0)
+}
+
+function outgoingIndex(edges: HogFlowEdge[]): Map<string, HogFlowEdge[]> {
+ const outgoing = new Map<string, HogFlowEdge[]>()
+ edges.forEach((edge) => {
+ const list = outgoing.get(edge.from)
+ if (list) {
+ list.push(edge)
+ } else {
+ outgoing.set(edge.from, [edge])
+ }
+ })
+ outgoing.forEach((list) => list.sort(byPathOrder))
+ return outgoing
+}
+
+const END_OF_FLOW = '\u0000end'
+
+function postorderToEnd(edges: HogFlowEdge[], outgoing: Map<string, HogFlowEdge[]>): string[] {
+ const incoming = new Map<string, string[]>()
+ const steps = new Set<string>()
+ edges.forEach((edge) => {
+ steps.add(edge.from).add(edge.to)
+ incoming.set(edge.to, [...(incoming.get(edge.to) ?? []), edge.from])
+ })
+ const lastSteps = [...steps].filter((id) => !outgoing.has(id))
+ const seen = new Set<string>([END_OF_FLOW])
+ const postorder: string[] = []
+ const pending: [id: string, isDone: boolean][] = [
+ [END_OF_FLOW, true],
+ ...lastSteps.map((id): [string, boolean] => [id, false]),
+ ]
+ while (pending.length) {
+ const [id, isDone] = pending.pop() as [string, boolean]
+ if (isDone) {
+ postorder.push(id)
+ } else if (!seen.has(id)) {
+ seen.add(id)
+ pending.push([id, true], ...(incoming.get(id) ?? []).map((from): [string, boolean] => [from, false]))
+ }
+ }
+ return postorder
+}
+
+/**
+ * Post-dominators, by the iterative algorithm of Cooper, Harvey and Kennedy on the reversed graph, with one end
+ * after every last step. A split's paths join at its immediate post-dominator.
+ */
+function joinSteps(edges: HogFlowEdge[], outgoing: Map<string, HogFlowEdge[]>): Map<string, string> {
+ const postorder = postorderToEnd(edges, outgoing)
+ const rank = new Map(postorder.map((id, index) => [id, index]))
+ const idom = new Map<string, string>([[END_OF_FLOW, END_OF_FLOW]])
+ const nextSteps = (id: string): string[] => outgoing.get(id)?.map((edge) => edge.to) ?? [END_OF_FLOW]
+ const intersect = (first: string, second: string): string => {
+ let [a, b] = [first, second]
+ while (a !== b) {
+ while ((rank.get(a) ?? 0) < (rank.get(b) ?? 0)) {
+ a = idom.get(a) as string
+ }
+ while ((rank.get(b) ?? 0) < (rank.get(a) ?? 0)) {
+ b = idom.get(b) as string
+ }
+ }
+ return a
+ }
+ const reversePostorder = postorder.slice(0, -1).reverse()
+ let changed = true
+ while (changed) {
+ changed = false
+ reversePostorder.forEach((id) => {
+ const processed = nextSteps(id).filter((next) => idom.has(next))
+ const dominator = processed.slice(1).reduce(intersect, processed[0])
+ if (dominator !== undefined && idom.get(id) !== dominator) {
+ idom.set(id, dominator)
+ changed = true
+ }
+ })
+ }
+ idom.forEach((dominator, id) => dominator === END_OF_FLOW && idom.delete(id))
+ return idom
+}
+
+function edgeIndex(workflow: FlowGraph): EdgeIndex {
+ let index = edgeIndexes.get(workflow.edges)
+ if (!index) {
+ const outgoing = outgoingIndex(workflow.edges)
+ index = { outgoing, joinOf: joinSteps(workflow.edges, outgoing) }
+ edgeIndexes.set(workflow.edges, index)
+ }
+ return index
+}
+
+export function actionsById(workflow: Pick<HogFlow, 'actions'>): Map<string, HogFlowAction> {
+ let index = actionIndexes.get(workflow.actions)
+ if (!index) {
+ index = new Map(workflow.actions.map((action) => [action.id, action]))
+ actionIndexes.set(workflow.actions, index)
+ }
+ return index
+}
+
+export function outgoingEdges(workflow: FlowGraph, actionId: string): HogFlowEdge[] {
+ return edgeIndex(workflow).outgoing.get(actionId) ?? []
+}
+
+/**
+ * Every step reachable from the starts, each before the steps it leads to. The paths of a split follow each
+ * other in path order, so one path's steps stay together and the step where they join comes after all of them.
+ */
+export function executionOrder(
+ workflow: FlowGraph,
+ startIds: readonly string[],
+ canVisit: (id: string) => boolean = () => true
+): string[] {
+ const seen = new Set<string>()
+ return startIds.flatMap((startId) => {
+ const finished: string[] = []
+ const pending: [id: string, isDone: boolean][] = [[startId, false]]
+ while (pending.length) {
+ const [id, isDone] = pending.pop() as [string, boolean]
+ if (isDone) {
+ finished.push(id)
+ } else if (!seen.has(id) && canVisit(id)) {
+ seen.add(id)
+ pending.push(
+ [id, true],
+ ...outgoingEdges(workflow, id).map((edge): [string, boolean] => [edge.to, false])
+ )
+ }
+ }
+ return finished.reverse()
+ })
+}
+
+function workflowOrder(workflow: FlowGraph): Map<string, number> {
+ const starts = [
+ ...workflow.actions.filter((action) => action.type === 'trigger'),
+ ...workflow.actions.filter((action) => action.type !== 'trigger'),
+ ].map((action) => action.id)
+ return new Map(executionOrder(workflow, starts).map((id, index) => [id, index]))
+}
+
+export interface PathGroup {
+ id: string
+ branchActionId: string
+ entryEdge: HogFlowEdge
+ label: string
+ memberIds: string[]
+ members: ReadonlySet<string>
+ parentId: string | null
+ depth: number
+}
+
+const PATH_COLORS = [
+ 'var(--data-color-1)',
+ 'var(--data-color-13)',
+ 'var(--data-color-7)',
+ 'var(--data-color-4)',
+ 'var(--data-color-3)',
+]
+
+export function pathColor(edge: Pick<HogFlowEdge, 'type' | 'index'>): string {
+ return edge.type === 'branch' ? PATH_COLORS[(edge.index ?? 0) % PATH_COLORS.length] : 'var(--color-text-secondary)'
+}
+
+export function tint(color: string, percent: number): string {
+ return `color-mix(in srgb, ${color} ${percent}%, transparent)`
+}
+
+export function pathGroupId(edge: HogFlowEdge): string {
+ return `path:${edge.from}:${edge.type}:${edge.index ?? ''}`
+}
+
+const SHARED = -1
+
+/**
+ * Which path of a split reaches each step before the paths join: its index, or SHARED when more than one does.
+ * Each step changes its label at most twice, so one pass over the edges between the split and the join does.
+ */
+function pathOfStep(workflow: FlowGraph, entries: string[], joinId: string | undefined): Map<string, number> {
+ const label = new Map<string, number>()
+ const pending: [id: string, path: number][] = entries.map((id, path) => [id, path])
+ while (pending.length) {
+ const [id, path] = pending.pop() as [string, number]
+ const current = label.get(id)
+ if (id === joinId || current === path || current === SHARED) {
+ continue
+ }
+ const next = current === undefined ? path : SHARED
+ label.set(id, next)
+ outgoingEdges(workflow, id).forEach((edge) => pending.push([edge.to, next]))
+ }
+ return label
+}
+
+function pathsOf(workflow: FlowGraph, splitAction: HogFlowAction): PathGroup[] {
+ const outgoing = outgoingEdges(workflow, splitAction.id)
+ if (outgoing.length < 2) {
+ return []
+ }
+ const label = pathOfStep(
+ workflow,
+ outgoing.map((edge) => edge.to),
+ edgeIndex(workflow).joinOf.get(splitAction.id)
+ )
+ return outgoing.flatMap((edge, path) => {
+ const memberIds = executionOrder(workflow, [edge.to], (id) => label.get(id) === path)
+ // A single step reads better on the canvas as itself than inside a group of one.
+ if (memberIds.length < 2) {
+ return []
+ }
+ return [
+ {
+ id: pathGroupId(edge),
+ branchActionId: splitAction.id,
+ entryEdge: edge,
+ label: getWorkflowBranchLabel(splitAction, edge),
+ memberIds,
+ members: new Set(memberIds),
+ parentId: null,
+ depth: 0,
+ },
+ ]
+ })
+}
+
+function loopsBackToItsSplit(group: PathGroup): boolean {
+ return group.members.has(group.branchActionId)
+}
+
+function encloses(outer: PathGroup, inner: PathGroup): boolean {
+ return outer.memberIds.length > inner.memberIds.length && inner.memberIds.every((id) => outer.members.has(id))
+}
+
+/** A path's parent is the smallest other path that holds its split and all of its steps. */
+function parentsOf(groups: PathGroup[]): Map<string, string> {
+ const holding = new Map<string, PathGroup[]>()
+ ;[...groups]
+ .sort((a, b) => a.memberIds.length - b.memberIds.length)
+ .forEach((group) =>
+ group.memberIds.forEach((id) => {
+ const holders = holding.get(id)
+ holders ? holders.push(group) : holding.set(id, [group])
+ })
+ )
+ const parents = new Map<string, string>()
+ groups.forEach((group) => {
+ const parent = holding.get(group.branchActionId)?.find((other) => encloses(other, group))
+ if (parent) {
+ parents.set(group.id, parent.id)
+ }
+ })
+ return parents
+}
+
+export function computePathGroups(workflow: FlowGraph): PathGroup[] {
+ // A path that leads back to its own split has no end to fold into a stack, so its steps stay plain tiles.
+ const groups = workflow.actions
+ .filter(isBranchingAction)
+ .flatMap((action) => pathsOf(workflow, action))
+ .filter((group) => !loopsBackToItsSplit(group))
+ // A parent holds strictly more steps than its child, so the parent chain can never loop.
+ const parents = parentsOf(groups)
+ const depths = new Map<string, number>()
+ const depthOf = (id: string): number => {
+ const parentId = parents.get(id)
+ if (!parentId) {
+ return 0
+ }
+ if (!depths.has(id)) {
+ depths.set(id, depthOf(parentId) + 1)
+ }
+ return depths.get(id) as number
+ }
+ return groups.map((group) => ({ ...group, parentId: parents.get(group.id) ?? null, depth: depthOf(group.id) }))
+}
+
+function ancestorsOf(groups: PathGroup[], group: PathGroup): PathGroup[] {
+ const byId = new Map(groups.map((other) => [other.id, other]))
+ const ancestors: PathGroup[] = []
+ for (let parent = byId.get(group.parentId ?? ''); parent; parent = byId.get(parent.parentId ?? '')) {
+ ancestors.push(parent)
+ }
+ return ancestors
+}
+
+function hasOpenAncestors(groups: PathGroup[], open: ReadonlySet<string>): (group: PathGroup) => boolean {
+ const byId = new Map(groups.map((group) => [group.id, group]))
+ return (group) => {
+ for (let parent = byId.get(group.parentId ?? ''); parent; parent = byId.get(parent.parentId ?? '')) {
+ if (!open.has(parent.id)) {
+ return false
+ }
+ }
+ return true
+ }
+}
+
+export function openPathFrames(groups: PathGroup[], openGroupIds: readonly string[]): PathGroup[] {
+ const open = new Set(openGroupIds)
+ const isShown = hasOpenAncestors(groups, open)
+ return groups.filter((group) => open.has(group.id) && isShown(group))
+}
+
+export function collapsedPathStacks(groups: PathGroup[], openGroupIds: readonly string[]): PathGroup[] {
+ const open = new Set(openGroupIds)
+ const isShown = hasOpenAncestors(groups, open)
+ return groups.filter((group) => !open.has(group.id) && isShown(group))
+}
+
+export function pathActions(workflow: Pick<HogFlow, 'actions'>, group: PathGroup): HogFlowAction[] {
+ const byId = actionsById(workflow)
+ return group.memberIds.flatMap((id) => byId.get(id) ?? [])
+}
+
+/** The start and end of a workflow cannot be copied, moved or deleted, so they have no step menu. */
+export function hasStepMenu(action: Pick<HogFlowAction, 'type'>): boolean {
+ return action.type !== 'trigger' && action.type !== 'exit'
+}
+
+export function isInPathGroup(group: PathGroup, node: VisibleNode): boolean {
+ return group.members.has(node.kind === 'step' ? node.id : node.group.branchActionId)
+}
+
+export type VisibleNode =
+ | { kind: 'step'; id: string; action: HogFlowAction }
+ | { kind: 'stack'; id: string; group: PathGroup }
+
+export interface VisibleEdge {
+ id: string
+ source: string
+ target: string
+ portIndex: number
+ portCount: number
+ label?: string
+ /** The workflow edge a step can be inserted into. Absent where the arrow leads into or out of a stack. */
+ insertEdge?: HogFlowEdge
+ originalEdgeKeys: string[]
+}
+
+export interface VisibleGraph {
+ nodes: VisibleNode[]
+ edges: VisibleEdge[]
+}
+
+interface Collapsed {
+ stackOf: Map<string, string>
+ namedElsewhere: Set<string>
+ actionsById: Map<string, HogFlowAction>
+}
+
+function visibleNodes(workflow: FlowGraph, stacks: PathGroup[], { stackOf }: Collapsed): VisibleNode[] {
+ const order = workflowOrder(workflow)
+ const orderOf = (node: VisibleNode): number =>
+ order.get(node.kind === 'step' ? node.id : node.group.memberIds[0]) ?? 0
+ return [
+ ...workflow.actions
+ .filter((action) => !stackOf.has(action.id))
+ .map((action): VisibleNode => ({ kind: 'step', id: action.id, action })),
+ ...stacks.map((group): VisibleNode => ({ kind: 'stack', id: group.id, group })),
+ ].sort((a, b) => orderOf(a) - orderOf(b))
+}
+
+function edgeLabel(workflow: FlowGraph, edge: HogFlowEdge, collapsed: Collapsed): string | undefined {
+ const isPathChoice = outgoingEdges(workflow, edge.from).length > 1
+ return isPathChoice && !collapsed.namedElsewhere.has(getEdgeId(edge))
+ ? getWorkflowBranchLabel(collapsed.actionsById.get(edge.from), edge)
+ : undefined
+}
+
+/** Arrows that a collapsed path turns into the same arrow become one, which no step can be inserted into. */
+function mergeVisibleEdges(workflow: FlowGraph, collapsed: Collapsed): VisibleEdge[] {
+ const shown = (id: string): string => collapsed.stackOf.get(id) ?? id
+ const edgesById = new Map<string, VisibleEdge>()
+ workflow.edges.forEach((edge) => {
+ const source = shown(edge.from)
+ const target = shown(edge.to)
+ if (source === target) {
+ return
+ }
+ const fromStack = source !== edge.from
+ const id = fromStack ? `${source}->${target}` : `${getEdgeId(edge)}${target !== edge.to ? `=>${target}` : ''}`
+ const existing = edgesById.get(id)
+ if (existing) {
+ existing.originalEdgeKeys.push(getEdgeId(edge))
+ existing.insertEdge = undefined
+ return
+ }
+ edgesById.set(id, {
+ id,
+ source,
+ target,
+ portIndex: 0,
+ portCount: 1,
+ label: fromStack ? undefined : edgeLabel(workflow, edge, collapsed),
+ insertEdge: fromStack || target !== edge.to ? undefined : edge,
+ originalEdgeKeys: [getEdgeId(edge)],
+ })
+ })
+ return [...edgesById.values()]
+}
+
+/** Each arrow leaves its step from its own port, in path order, so the arrows of a split never cross. */
+function assignSourcePorts(workflow: FlowGraph, edges: VisibleEdge[]): VisibleEdge[] {
+ const bySource = new Map<string, VisibleEdge[]>()
+ edges.forEach((edge) => bySource.set(edge.source, [...(bySource.get(edge.source) ?? []), edge]))
+ bySource.forEach((fromSource, sourceId) => {
+ const order = outgoingEdges(workflow, sourceId).map(getEdgeId)
+ fromSource
+ .sort((a, b) => order.indexOf(a.originalEdgeKeys[0]) - order.indexOf(b.originalEdgeKeys[0]))
+ .forEach((edge, index) => {
+ edge.portIndex = index
+ edge.portCount = fromSource.length
+ })
+ })
+ return edges
+}
+
+export function computeVisibleGraph(
+ workflow: FlowGraph,
+ groups: PathGroup[],
+ openGroupIds: readonly string[]
+): VisibleGraph {
+ const stacks = collapsedPathStacks(groups, openGroupIds)
+ const frames = openPathFrames(groups, openGroupIds)
+ const collapsed: Collapsed = {
+ stackOf: new Map(stacks.flatMap((group) => group.memberIds.map((id): [string, string] => [id, group.id]))),
+ namedElsewhere: new Set([...stacks, ...frames].map((group) => getEdgeId(group.entryEdge))),
+ actionsById: actionsById(workflow),
+ }
+ return {
+ nodes: visibleNodes(workflow, stacks, collapsed),
+ edges: assignSourcePorts(workflow, mergeVisibleEdges(workflow, collapsed)),
+ }
+}
+
+/** The people a step handled. Unknown until the metrics load, so the tile shows no number rather than a wrong one.
+ * A workflow with no runs in the window shows no numbers either, so a draft is not covered in zeros. */
+export function stepCount(
+ metrics: Record<string, HogFlowEditorActionMetrics> | null,
+ actionId: string
+): number | undefined {
+ if (!metrics || Object.keys(metrics).length === 0) {
+ return undefined
+ }
+ const entry = metrics[actionId]
+ return entry ? entry.succeeded + entry.failed + entry.filtered : 0
+}
+
+const STEP_COUNT_WINDOW_MS = 7 * 24 * 60 * 60 * 1000
+const STEP_COUNT_METRICS = ['succeeded', 'failed', 'filtered', 'rate_limited', 'triggered']
+
+/** Batch workflows report metrics per run, not per step, so they get no step counts. */
+function canCountSteps(workflow: Pick<HogFlow, 'id' | 'trigger'>): boolean {
+ return !!workflow.id && workflow.id !== 'new' && workflow.trigger?.type !== 'batch'
+}
+
+/** Metrics loaded earlier, or answered late, must not show once the workflow stops qualifying for step counts. */
+export function countableStepMetrics(
+ workflow: Pick<HogFlow, 'id' | 'trigger'>,
+ metrics: Record<string, HogFlowEditorActionMetrics> | null
+): Record<string, HogFlowEditorActionMetrics> | null {
+ return canCountSteps(workflow) ? metrics : null
+}
+
+/** One row per step and metric, plus the trigger and exit rows that have no step. Without a limit the query
+ * stops at 100 rows, and a big workflow loses the counts of its last steps. */
+function stepCountRowLimit(workflow: Pick<HogFlow, 'actions'>): number {
+ return (workflow.actions.length + 1) * STEP_COUNT_METRICS.length
+}
+
+export function stepCountsRequest(
+ workflow: Pick<HogFlow, 'id' | 'trigger' | 'actions'>,
+ now: Date
+): AppMetricsTotalsRequest | null {
+ if (!canCountSteps(workflow)) {
+ return null
+ }
+ return {
+ appSource: 'hog_flow',
+ appSourceId: workflow.id,
+ dateFrom: new Date(now.getTime() - STEP_COUNT_WINDOW_MS).toISOString(),
+ dateTo: now.toISOString(),
+ breakdownBy: ['instance_id', 'metric_name'],
+ metricName: STEP_COUNT_METRICS,
+ limit: stepCountRowLimit(workflow),
+ }
+}
+
+export interface Point {
+ x: number
+ y: number
+}
+
+export interface Viewport {
+ x: number
+ y: number
+ zoom: number
+}
+
+export interface Size {
+ width: number
+ height: number
+}
+
+const VIEWPORT_MARGIN = 24
+
+function shiftIntoView(offset: number, start: number, length: number, zoom: number, extent: number): number {
+ const near = start * zoom + offset
+ const far = (start + length) * zoom + offset
+ if (near < VIEWPORT_MARGIN) {
+ return offset + VIEWPORT_MARGIN - near
+ }
+ if (far > extent - VIEWPORT_MARGIN) {
+ return offset - Math.min(far - (extent - VIEWPORT_MARGIN), near - VIEWPORT_MARGIN)
+ }
+ return offset
+}
+
+export function viewportAfterResize(viewport: Viewport, previous: Size, next: Size, focus?: Point & Size): Viewport {
+ const x = viewport.x + (next.width - previous.width) / 2
+ const y = viewport.y + (next.height - previous.height) / 2
+ if (!focus) {
+ return { x, y, zoom: viewport.zoom }
+ }
+ return {
+ x: shiftIntoView(x, focus.x, focus.width, viewport.zoom, next.width),
+ y: shiftIntoView(y, focus.y, focus.height, viewport.zoom, next.height),
+ zoom: viewport.zoom,
+ }
+}
+
+export const CANVAS_MIN_ZOOM = 0.15
+export const FIT_MARGIN = { side: 24, top: 32, bottom: 96 }
+
+/** The command bar floats over the bottom of the canvas, so the room to show things in ends above it. */
+function roomInView(canvas: Size): Size {
+ return {
+ width: canvas.width - FIT_MARGIN.side * 2,
+ height: canvas.height - FIT_MARGIN.top - FIT_MARGIN.bottom,
+ }
+}
+
+/** Centres a frame in view. Zooms out only when the frame does not fit at the zoom the person chose. */
+export function viewportToFit(frame: Point & Size, canvas: Size, zoom: number): Viewport {
+ const room = roomInView(canvas)
+ const fits = frame.width * zoom <= room.width && frame.height * zoom <= room.height
+ const nextZoom = fits
+ ? zoom
+ : Math.max(CANVAS_MIN_ZOOM, Math.min(room.width / frame.width, room.height / frame.height))
+ return {
+ x: FIT_MARGIN.side + (room.width - frame.width * nextZoom) / 2 - frame.x * nextZoom,
+ y: FIT_MARGIN.top + (room.height - frame.height * nextZoom) / 2 - frame.y * nextZoom,
+ zoom: nextZoom,
+ }
+}
+
+const MIN_READABLE_ZOOM = 0.66
+/** How much of a path must show around where its arrow enters, in canvas pixels. */
+const ANCHOR_HEAD = 120
+
+/** Where a path sits on the canvas, and where the arrow into it meets it. */
+export interface PathPlace extends Point, Size {
+ entry: Point
+}
+
+interface ScreenBounds {
+ left: number
+ top: number
+ right: number
+ bottom: number
+}
+
+function roomBounds(canvas: Size): ScreenBounds {
+ return {
+ left: FIT_MARGIN.side,
+ top: FIT_MARGIN.top,
+ right: canvas.width - FIT_MARGIN.side,
+ bottom: canvas.height - FIT_MARGIN.bottom,
+ }
+}
+
+const onScreen = (point: Point, viewport: Viewport): Point => ({
+ x: viewport.x + point.x * viewport.zoom,
+ y: viewport.y + point.y * viewport.zoom,
+})
+
+function isOnScreen(box: Point & Size, viewport: Viewport, room: ScreenBounds): boolean {
+ const topLeft = onScreen(box, viewport)
+ return (
+ topLeft.x < room.right &&
+ topLeft.x + box.width * viewport.zoom > room.left &&
+ topLeft.y < room.bottom &&
+ topLeft.y + box.height * viewport.zoom > room.top
+ )
+}
+
+const clamp = (value: number, low: number, high: number): number => Math.min(Math.max(value, low), Math.max(low, high))
+
+/** How far a place reaches from its entry to each side, in canvas pixels. */
+function reach(place: PathPlace): ScreenBounds {
+ return {
+ left: place.entry.x - place.x,
+ top: place.entry.y - place.y,
+ right: place.x + place.width - place.entry.x,
+ bottom: place.y + place.height - place.entry.y,
+ }
+}
+
+/** Moves the anchor only as far as needed for the part of the next place around its entry to show. */
+function anchorInRoom(anchor: Point, next: PathPlace, zoom: number, room: ScreenBounds): Point {
+ const around = reach(next)
+ return {
+ x: clamp(
+ anchor.x,
+ room.left + Math.min(around.left, ANCHOR_HEAD) * zoom,
+ room.right - Math.min(around.right, ANCHOR_HEAD) * zoom
+ ),
+ y: clamp(anchor.y, room.top, room.bottom - Math.min(around.bottom, ANCHOR_HEAD) * zoom),
+ }
+}
+
+function zoomToShowFrom(anchor: Point, next: PathPlace, room: ScreenBounds, zoom: number): number {
+ const fitting = Math.min(
+ (room.right - room.left) / Math.max(next.width, 1),
+ (room.bottom - anchor.y) / Math.max(reach(next).bottom, 1)
+ )
+ return fitting >= zoom ? zoom : Math.max(fitting, Math.min(zoom, MIN_READABLE_ZOOM))
+}
+
+/** Slides the view sideways only as far as needed for a box as wide as the canvas or narrower to show whole. */
+function slideIntoRoom(x: number, box: Point & Size, zoom: number, room: ScreenBounds): number {
+ const left = x + box.x * zoom
+ const right = left + box.width * zoom
+ if (right - left > room.right - room.left) {
+ return x
+ }
+ return x + Math.max(0, room.left - left) - Math.max(0, right - room.right)
+}
+
+/**
+ * Keeps a path where the person saw it as it opens or collapses: the arrow into the path stays where it was on screen,
+ * and everything else moves around it. A frame that would open past the side of the canvas slides in just enough to
+ * show whole. Zooms out only as far as the new place needs, never below a readable zoom, and never zooms in. A path
+ * opened from a stack out of view is centred instead.
+ */
+export function viewportAnchoredOn(previous: PathPlace, next: PathPlace, viewport: Viewport, canvas: Size): Viewport {
+ const room = roomBounds(canvas)
+ if (!isOnScreen(previous, viewport, room)) {
+ return viewportToFit(next, canvas, viewport.zoom)
+ }
+ const anchor = anchorInRoom(onScreen(previous.entry, viewport), next, viewport.zoom, room)
+ const zoom = zoomToShowFrom(anchor, next, room, viewport.zoom)
+ const x = slideIntoRoom(anchor.x - next.entry.x * zoom, next, zoom, room)
+ return { x, y: anchor.y - next.entry.y * zoom, zoom }
+}
+
+/**
+ * Fits the workflow, but never shrinks it below a readable zoom: people pan to see the rest of a big one. A workflow
+ * too wide to fit starts at its trigger, in the middle of the canvas, since it usually sits above the middle of its
+ * paths and the left edge would show only empty canvas.
+ */
+export function readableFitViewport(bounds: Point & Size, canvas: Size, trigger: Point): Viewport {
+ const width = bounds.width + FIT_MARGIN.side * 2
+ const height = bounds.height + FIT_MARGIN.top + FIT_MARGIN.bottom
+ const zoom = Math.min(1, Math.max(MIN_READABLE_ZOOM, Math.min(canvas.width / width, canvas.height / height)))
+ const room = roomBounds(canvas)
+ const fitsWidth = bounds.width * zoom <= room.right - room.left
+ const x = fitsWidth
+ ? (canvas.width - bounds.width * zoom) / 2 - bounds.x * zoom
+ : clamp(
+ canvas.width / 2 - trigger.x * zoom,
+ room.right - (bounds.x + bounds.width) * zoom,
+ room.left - bounds.x * zoom
+ )
+ return { x, y: FIT_MARGIN.top - bounds.y * zoom, zoom }
+}
+
+export interface MiniFlowLayout {
+ nodes: { actionId: string; x: number; y: number; layer: number }[]
+ edges: { from: Point; to: Point }[]
+ width: number
+ height: number
+}
+
+export function layoutMiniFlow(
+ workflow: FlowGraph,
+ memberIds: string[],
+ spacing: { tile: number; gapX: number; gapY: number }
+): MiniFlowLayout {
+ const rank = new Map(memberIds.map((id, index) => [id, index]))
+ const inner = memberIds.flatMap((id) => outgoingEdges(workflow, id).filter((edge) => rank.has(edge.to)))
+ // Members come in flow order, so one pass over the edges that point forward places every step after the ones before it.
+ const layer = new Map(memberIds.map((id) => [id, 0]))
+ inner
+ .filter((edge) => (rank.get(edge.to) as number) > (rank.get(edge.from) as number))
+ .forEach((edge) => layer.set(edge.to, Math.max(layer.get(edge.to) ?? 0, (layer.get(edge.from) ?? 0) + 1)))
+ const columns: string[][] = []
+ memberIds.forEach((id) => (columns[layer.get(id) ?? 0] ??= []).push(id))
+ const tallest = Math.max(...columns.map((column) => column?.length ?? 0))
+ const nodes = columns.flatMap((column, index) =>
+ (column ?? []).map((actionId, row) => ({
+ actionId,
+ layer: index,
+ x: index * (spacing.tile + spacing.gapX),
+ y: (row - (column.length - 1) / 2 + (tallest - 1) / 2) * spacing.gapY,
+ }))
+ )
+ const at = new Map(nodes.map((node) => [node.actionId, node]))
+ const center = spacing.tile / 2
+ return {
+ nodes,
+ edges: inner.map((edge) => {
+ const from = at.get(edge.from) as Point
+ const to = at.get(edge.to) as Point
+ return { from: { x: from.x + spacing.tile, y: from.y + center }, to: { x: to.x, y: to.y + center } }
+ }),
+ width: columns.length * (spacing.tile + spacing.gapX) - spacing.gapX,
+ height: (tallest - 1) * spacing.gapY + spacing.tile,
+ }
+}
+
+function isInTriangle(point: Point, a: Point, b: Point, c: Point): boolean {
+ const side = (p1: Point, p2: Point, p3: Point): number =>
+ (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y)
+ const sides = [side(point, a, b), side(point, b, c), side(point, c, a)]
+ return !(sides.some((value) => value < 0) && sides.some((value) => value > 0))
+}
+
+/**
+ * True while the pointer stays inside the triangle between where it left a step and the top edge of
+ * that step's open preview. Steps it crosses on the way there must not take the hover away.
+ */
+export function isHeadingToRect(
+ pointer: Point,
+ apex: Point,
+ rect: { left: number; right: number; top: number },
+ slack: number
+): boolean {
+ return isInTriangle(pointer, apex, { x: rect.left - slack, y: rect.top }, { x: rect.right + slack, y: rect.top })
+}
+
+export interface PaletteSection {
+ title: string
+ steps: CreateActionType[]
+}
+
+export interface PaletteCommand {
+ id: string
+ label: string
+ hint?: string
+}
+
+export type PaletteItem<Command extends PaletteCommand = PaletteCommand> =
+ | { kind: 'step'; key: string; section: string; label: string; description?: string; step: CreateActionType }
+ | { kind: 'command'; key: string; section: string; label: string; description?: string; command: Command }
+
+/** Two destinations can share a name, so the key also carries the template the step runs. */
+function paletteStepKey(section: string, step: CreateActionType): string {
+ const templateId = 'template_id' in step.config ? step.config.template_id : undefined
+ return `${section}:${step.type}:${templateId ?? ''}:${step.name}`
+}
+
+const matches = (query: string, texts: (string | undefined)[]): boolean =>
+ !query || texts.some((text) => text?.toLowerCase().includes(query.toLowerCase()))
+
+// With an empty search, commands lead. Once someone types, they are probably after a step, so steps lead.
+export function filterPaletteItems<Command extends PaletteCommand>(
+ query: string,
+ sections: PaletteSection[],
+ commands: Command[]
+): PaletteItem<Command>[] {
+ const trimmed = query.trim()
+ const steps = sections.flatMap(({ title, steps }) =>
+ steps
+ .filter((step) => matches(trimmed, [step.name, step.description, title]))
+ .map(
+ (step): PaletteItem<Command> => ({
+ kind: 'step',
+ key: paletteStepKey(title, step),
+ section: title,
+ label: step.name,
+ description: step.description,
+ step,
+ })
+ )
+ )
+ const commandItems = commands
+ .filter((command) => matches(trimmed, [command.label, command.hint]))
+ .map(
+ (command): PaletteItem<Command> => ({
+ kind: 'command',
+ key: command.id,
+ section: 'Commands',
+ label: command.label,
+ description: command.hint,
+ command,
+ })
+ )
+ return trimmed ? [...steps, ...commandItems] : [...commandItems, ...steps]
+}
+
+export interface CanvasMotion {
+ kind: 'expand' | 'collapse' | 'settle'
+ groupId: string
+ origin: Point
+}
+
+export interface NodeMotion {
+ type: 'enter' | 'leave' | 'pop' | 'fade-in' | 'fade-out'
+ dx: number
+ dy: number
+}
+
+function movingPathGroup(motion: CanvasMotion, groups: PathGroup[]): PathGroup | undefined {
+ return groups.find((candidate) => candidate.id === motion.groupId)
+}
+
+/** Steps fly out of the stack's tile when a path opens, and back into it when the path collapses. */
+function motionTowardStack(
+ motion: CanvasMotion,
+ box: { x: number; y: number; width: number; height: number }
+): NodeMotion {
+ return {
+ type: motion.kind === 'expand' ? 'enter' : 'leave',
+ dx: motion.origin.x - (box.x + box.width / 2),
+ dy: motion.origin.y - (box.y + box.height / 2),
+ }
+}
+
+export function nodeMotion(
+ motion: CanvasMotion | null,
+ node: VisibleNode,
+ groups: PathGroup[],
+ box: { x: number; y: number; width: number; height: number } | undefined
+): NodeMotion | undefined {
+ if (!motion || !box) {
+ return undefined
+ }
+ if (motion.kind === 'settle') {
+ return node.id === motion.groupId ? { type: 'pop', dx: 0, dy: 0 } : undefined
+ }
+ const group = movingPathGroup(motion, groups)
+ return group && isInPathGroup(group, node) ? motionTowardStack(motion, box) : undefined
+}
+
+export function frameMotion(
+ motion: CanvasMotion | null,
+ group: PathGroup,
+ groups: PathGroup[]
+): NodeMotion | undefined {
+ if (!motion || motion.kind === 'settle') {
+ return undefined
+ }
+ const isMoving =
+ group.id === motion.groupId || ancestorsOf(groups, group).some((other) => other.id === motion.groupId)
+ return isMoving ? { type: motion.kind === 'expand' ? 'fade-in' : 'fade-out', dx: 0, dy: 0 } : undefined
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.test.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.test.ts
new file mode 100644
index 000000000000..fd740983d575
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.test.ts
@@ -0,0 +1,58 @@
+import type { HogFlow, HogFlowAction } from '../../types'
+import { CanvasLayout } from './tileCanvasLayout'
+import { computeVisibleGraph } from './tileCanvasModel'
+import { buildCanvasNodes, CanvasNodeState, keepUnchangedNodes } from './tileCanvasNodes'
+
+const step = (id: string): HogFlowAction => ({ id, type: 'delay', name: id, config: {} }) as unknown as HogFlowAction
+
+const workflow = {
+ actions: [step('a'), step('b')],
+ edges: [{ from: 'a', to: 'b', type: 'continue' }],
+} as unknown as HogFlow
+
+const graph = computeVisibleGraph(workflow, [], [])
+
+const layoutWith = (bY: number): CanvasLayout => ({
+ positions: { a: { x: 0, y: 0 }, b: { x: 0, y: bY } },
+ edges: {},
+ frames: {},
+ width: 300,
+ height: 300,
+})
+
+const state: CanvasNodeState = {
+ workflow,
+ groups: [],
+ motion: null,
+ sizes: null,
+ selectedStepId: null,
+ menuStepId: null,
+ countOf: () => undefined,
+ templateNameOf: () => undefined,
+}
+
+describe('keepUnchangedNodes', () => {
+ it('keeps the node objects that did not change, so React Flow redraws only the rest', () => {
+ const before = buildCanvasNodes(layoutWith(120), [], graph, state)
+
+ const after = keepUnchangedNodes(
+ before,
+ buildCanvasNodes(layoutWith(200), [], graph, { ...state, selectedStepId: 'a' })
+ )
+ const moved = keepUnchangedNodes(before, buildCanvasNodes(layoutWith(200), [], graph, state))
+
+ expect(after.map((node, index) => node === before[index])).toEqual([false, false])
+ expect(moved.map((node, index) => node === before[index])).toEqual([true, false])
+ })
+
+ it('tells React Flow the size of each tile, so a replaced tile stays visible', () => {
+ const sizes = { a: { width: 306, height: 84 }, b: { width: 306, height: 120 } }
+
+ const nodes = buildCanvasNodes(layoutWith(120), [], graph, { ...state, sizes })
+
+ expect(nodes.map((node) => node.measured)).toEqual([
+ { width: 306, height: 84 },
+ { width: 306, height: 120 },
+ ])
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.ts
new file mode 100644
index 000000000000..3017901147cd
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.ts
@@ -0,0 +1,188 @@
+import type { Edge, Node } from '@xyflow/react'
+
+import type { HogFlow } from '../../types'
+import { Box, CanvasLayout, frameChipWidth, frameEntryX, NodeSize, PathFrameSpec, RoutedEdge } from './tileCanvasLayout'
+import type { StepCountOf, TemplateNameOf } from './tileCanvasLogic'
+import {
+ CanvasMotion,
+ frameMotion,
+ nodeMotion,
+ NodeMotion,
+ PathGroup,
+ VisibleEdge,
+ VisibleGraph,
+ VisibleNode,
+} from './tileCanvasModel'
+
+export interface TileNodeData extends Record<string, unknown> {
+ node: VisibleNode
+ workflow: HogFlow
+ motion?: NodeMotion
+ count?: number
+ selected: boolean
+ menuOpen: boolean
+ countOf: StepCountOf
+ templateNameOf: TemplateNameOf
+}
+
+export interface PathNodeData extends Record<string, unknown> {
+ group: PathGroup
+ motion?: NodeMotion
+}
+
+export type TileFlowNodeType = Node<TileNodeData, 'tile'>
+export type PathFrameNodeType = Node<PathNodeData, 'frame'>
+export type PathChipNodeType = Node<PathNodeData, 'chip'>
+export type TileCanvasNode = TileFlowNodeType | PathFrameNodeType | PathChipNodeType
+
+export type TileEdgeType = Edge<{ edge: VisibleEdge; routed?: RoutedEdge }, 'tile'>
+
+/** What every node shows besides its place: the parts of the canvas state a node needs to draw itself. */
+export interface CanvasNodeState {
+ workflow: HogFlow
+ groups: PathGroup[]
+ motion: CanvasMotion | null
+ sizes: Record<string, NodeSize> | null
+ selectedStepId: string | null
+ menuStepId: string | null
+ countOf: StepCountOf
+ templateNameOf: TemplateNameOf
+}
+
+const CHIP_INSET = 8
+const STATIC = { selectable: false, draggable: false } as const
+
+function frameNode(frame: PathFrameSpec, box: Box, motion: NodeMotion | undefined): TileCanvasNode {
+ return {
+ id: frame.id,
+ type: 'frame',
+ position: { x: box.x, y: box.y },
+ width: box.width,
+ height: box.height,
+ data: { group: frame.group, motion },
+ zIndex: -10 + frame.group.depth,
+ ...STATIC,
+ }
+}
+
+/** The chip sits where the arrow into the path crosses the frame's top edge, kept inside the frame. */
+function chipNode(
+ frame: PathFrameSpec,
+ box: Box,
+ layout: CanvasLayout,
+ graph: VisibleGraph,
+ motion: NodeMotion | undefined
+): TileCanvasNode {
+ const x = frameEntryX(frame.group, box, layout, graph.edges)
+ const width = frameChipWidth(frame.group.label)
+ const left = Math.min(Math.max(x - width / 2, box.x + CHIP_INSET), box.x + box.width - width - CHIP_INSET)
+ return {
+ id: `chip:${frame.group.id}`,
+ type: 'chip',
+ position: { x: left, y: box.y },
+ data: { group: frame.group, motion },
+ zIndex: 5,
+ ...STATIC,
+ }
+}
+
+function tileNode(node: VisibleNode, layout: CanvasLayout, state: CanvasNodeState): TileCanvasNode[] {
+ const position = layout.positions[node.id]
+ if (!position) {
+ return []
+ }
+ const size = state.sizes?.[node.id]
+ const data: TileNodeData = {
+ node,
+ workflow: state.workflow,
+ motion: nodeMotion(state.motion, node, state.groups, size && { ...position, ...size }),
+ count: node.kind === 'step' ? state.countOf(node.id) : undefined,
+ selected: state.selectedStepId === node.id,
+ menuOpen: state.menuStepId === node.id,
+ countOf: state.countOf,
+ templateNameOf: state.templateNameOf,
+ }
+ // React Flow hides a replaced node until it measures it again, unless the node says its size.
+ const measured = size && { width: size.width, height: size.height }
+ return [{ id: node.id, type: 'tile', position, data, measured, ...STATIC }]
+}
+
+const missingFrom = <Item extends { id: string }>(items: Item[], present: Item[]): Item[] => {
+ const ids = new Set(present.map((item) => item.id))
+ return items.filter((item) => !ids.has(item.id))
+}
+
+/**
+ * Laying out the canvas takes a moment. Until the new layout lands, a stack that opens stays where the last layout put
+ * it, with its arrows, so its steps can fly out of it instead of out of an empty gap. The steps and frame of a path
+ * that collapses have already faded out, so they do not come back.
+ */
+export function withLeavingStacks(current: VisibleGraph, laidOut: VisibleGraph | null): VisibleGraph {
+ const leaving = laidOut ? missingFrom(laidOut.nodes, current.nodes).filter((node) => node.kind === 'stack') : []
+ if (!laidOut || !leaving.length) {
+ return current
+ }
+ const nodes = [...current.nodes, ...leaving]
+ const drawnIds = new Set(nodes.map((node) => node.id))
+ const edges = missingFrom(laidOut.edges, current.edges).filter(
+ (edge) => drawnIds.has(edge.source) && drawnIds.has(edge.target)
+ )
+ return { nodes, edges: [...current.edges, ...edges] }
+}
+
+export function buildCanvasNodes(
+ layout: CanvasLayout | null,
+ frameSpecs: PathFrameSpec[],
+ graph: VisibleGraph,
+ state: CanvasNodeState
+): TileCanvasNode[] {
+ if (!layout) {
+ return []
+ }
+ const framed = frameSpecs.flatMap((frame) => {
+ const box = layout.frames[frame.id]
+ return box ? [{ frame, box, motion: frameMotion(state.motion, frame.group, state.groups) }] : []
+ })
+ return [
+ ...framed.map(({ frame, box, motion }) => frameNode(frame, box, motion)),
+ ...framed.map(({ frame, box, motion }) => chipNode(frame, box, layout, graph, motion)),
+ ...graph.nodes.flatMap((node) => tileNode(node, layout, state)),
+ ]
+}
+
+const shallowEqual = (a: Record<string, unknown>, b: Record<string, unknown>): boolean => {
+ const keys = Object.keys(a)
+ return keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key])
+}
+
+function isUnchanged(previous: TileCanvasNode, next: TileCanvasNode): boolean {
+ return (
+ previous.type === next.type &&
+ previous.position.x === next.position.x &&
+ previous.position.y === next.position.y &&
+ previous.width === next.width &&
+ previous.height === next.height &&
+ previous.zIndex === next.zIndex &&
+ shallowEqual(previous.data, next.data)
+ )
+}
+
+/** React Flow redraws a node whose object changed, so a node that looks the same keeps its old object. */
+export function keepUnchangedNodes(previous: TileCanvasNode[], next: TileCanvasNode[]): TileCanvasNode[] {
+ const previousById = new Map(previous.map((node) => [node.id, node]))
+ return next.map((node) => {
+ const old = previousById.get(node.id)
+ return old && isUnchanged(old, node) ? old : node
+ })
+}
+
+export function buildCanvasEdges(graph: VisibleGraph, layout: CanvasLayout | null): TileEdgeType[] {
+ return graph.edges.map((edge) => ({
+ id: edge.id,
+ source: edge.source,
+ target: edge.target,
+ type: 'tile',
+ data: { edge, routed: layout?.edges[edge.id] },
+ selectable: false,
+ }))
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasStoryFixtures.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasStoryFixtures.ts
new file mode 100644
index 000000000000..f855e3031f26
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasStoryFixtures.ts
@@ -0,0 +1,368 @@
+import type { HogFlowEditorActionMetrics } from '../../hogFlowEditorLogic'
+import type { HogFlow, HogFlowAction, HogFlowEdge } from '../../types'
+
+// Invented companies, people, and content. Every step uses a real step type or template and its real inputs.
+
+type Config = Record<string, unknown>
+
+const step = (id: string, type: HogFlowAction['type'], name: string, config: Config): HogFlowAction =>
+ ({ id, type, name, description: '', config }) as HogFlowAction
+
+const template = (
+ id: string,
+ name: string,
+ templateId: string,
+ inputs: Config,
+ extra: Partial<HogFlowAction> = {}
+): HogFlowAction =>
+ ({
+ ...step(id, 'function', name, {
+ template_id: templateId,
+ inputs: Object.fromEntries(Object.entries(inputs).map(([key, value]) => [key, { value }])),
+ }),
+ ...extra,
+ }) as HogFlowAction
+
+const slack = (id: string, name: string, channel: string, text: string): HogFlowAction =>
+ template(id, name, 'template-slack', { slack_workspace: 1, channel, text })
+
+const aiTask = (id: string, title: string, prompt: string, outputs: string[], skills: string[] = []): HogFlowAction =>
+ template(
+ id,
+ title,
+ 'template-posthog-create-task',
+ { title, prompt, skills },
+ { output_variable: outputs.map((key) => ({ key, result_path: key })) }
+ )
+
+const emailHtml = (accent: string, heading: string, body: string, cta: string): string =>
+ [
+ '<html><body style="margin:0;background:#f5f5f4;font-family:Helvetica,Arial,sans-serif;color:#1f2937">',
+ '<table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tr><td align="center" style="padding:32px 16px">',
+ '<table role="presentation" width="560" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:10px">',
+ `<tr><td style="padding:28px 40px 4px;font-size:14px;font-weight:700;color:${accent}">Example Co.</td></tr>`,
+ `<tr><td style="padding:8px 40px"><h1 style="margin:0;font-size:26px;line-height:1.3">${heading}</h1></td></tr>`,
+ `<tr><td style="padding:8px 40px;font-size:16px;line-height:1.6">${body}</td></tr>`,
+ `<tr><td style="padding:24px 40px 40px"><a href="https://example.com" style="background:${accent};color:#ffffff;padding:12px 24px;border-radius:6px;text-decoration:none">${cta}</a></td></tr>`,
+ '</table></td></tr></table></body></html>',
+ ].join('')
+
+const email = (id: string, subject: string, preheader: string, body: string, cta: string): HogFlowAction =>
+ step(id, 'function_email', subject, {
+ template_id: 'template-email',
+ message_category_type: 'marketing',
+ inputs: {
+ email: {
+ value: {
+ to: { name: '', email: '{{ person.properties.email }}' },
+ from: { integrationId: 1 },
+ subject,
+ preheader,
+ html: emailHtml('#6d28d9', subject, body, cta),
+ text: body,
+ },
+ },
+ },
+ })
+
+const emailStep = (id: string, subject: string, preheader: string, html: string, text: string): HogFlowAction =>
+ step(id, 'function_email', subject, {
+ template_id: 'template-email',
+ message_category_type: 'marketing',
+ inputs: {
+ email: {
+ value: {
+ to: { name: '', email: '{{ person.properties.email }}' },
+ from: { integrationId: 1 },
+ subject,
+ preheader,
+ html,
+ text,
+ },
+ },
+ },
+ })
+
+const FIRST_NAME = '{{ person.properties.first_name }}'
+const LONG_LINK =
+ 'https://example.com/templates/onboarding/checklists/2026/q4/engineering-team-handbook-template-with-sections-for-architecture-decision-records-and-runbooks?utm_source=email&utm_medium=lifecycle'
+
+const newsletterHtml = [
+ '<html><body style="margin:0;background:#f5f5f4;font-family:Helvetica,Arial,sans-serif;color:#1f2937">',
+ '<table role="presentation" width="560" cellpadding="0" cellspacing="0" style="background:#ffffff">',
+ `<tr><td style="padding:24px 40px"><h1 style="margin:0;font-size:26px">Hi ${FIRST_NAME}, here is your October digest</h1></td></tr>`,
+ '<tr><td style="padding:8px 40px"><div role="img" aria-label="A desk with a laptop" style="height:180px;background:#ede9fe">Image: a desk with a laptop</div></td></tr>',
+ '<tr><td style="padding:8px 40px"><h2 style="font-size:20px">Shared templates</h2><p>Any doc can now become a template for the whole workspace. <a href="https://example.com/docs/templates">Read how templates work</a>.</p></td></tr>',
+ '<tr><td style="padding:8px 40px"><h2 style="font-size:20px">What your team read most</h2><ul><li>Quarterly planning notes</li><li>Onboarding checklist for new engineers</li><li>Design review: settings page</li></ul></td></tr>',
+ `<tr><td style="padding:8px 40px"><p>Reply to this email if there is something you want us to build next, ${FIRST_NAME}.</p></td></tr>`,
+ '<tr><td style="padding:20px 40px"><a href="https://example.com/workspace" style="background:#6d28d9;color:#ffffff;padding:12px 24px">Open your workspace</a></td></tr>',
+ '</table></body></html>',
+].join('')
+
+const eventTrigger = (event: string): Config => ({
+ type: 'event',
+ filters: { events: [{ id: event, name: event, type: 'events' }], properties: [], actions: [] },
+})
+
+const delay = (id: string, duration: string): HogFlowAction =>
+ step(id, 'delay', `Wait ${duration}`, { delay_duration: duration })
+
+const waitFor = (id: string, event: string, maxWait: string): HogFlowAction =>
+ step(id, 'wait_until_condition', `Wait for ${event}`, {
+ condition: { name: event, filters: { events: [{ id: event, name: event, type: 'events' }] } },
+ max_wait_duration: maxWait,
+ })
+
+const split = (id: string, key: string, type: string, paths: [string, string, string?][]): HogFlowAction =>
+ step(id, 'conditional_branch', `By ${key}`, {
+ conditions: paths.map(([name, value, operator]) => ({
+ name,
+ filters: { properties: [{ key, type, value: [value], operator: operator ?? 'exact' }] },
+ })),
+ })
+
+const exit = (id: string, reason: string): HogFlowAction => step(id, 'exit', 'Exit', { reason })
+
+const next = (from: string, to: string): HogFlowEdge => ({ from, to, type: 'continue' })
+const branch = (from: string, to: string, index: number): HogFlowEdge => ({ from, to, type: 'branch', index })
+
+const flow = (id: string, name: string, actions: HogFlowAction[], edges: HogFlowEdge[]): HogFlow =>
+ ({
+ id,
+ team_id: 1,
+ version: 1,
+ name,
+ status: 'draft',
+ exit_condition: 'exit_only_at_end',
+ trigger: actions[0].config,
+ variables: [],
+ actions,
+ edges,
+ created_at: '2026-10-01T09:00:00.000Z',
+ updated_at: '2026-10-10T12:00:00.000Z',
+ }) as HogFlow
+
+export const AI_SUPPORT_TRIAGE = flow(
+ 'storybook-tile-ai-triage',
+ 'AI support triage',
+ [
+ step('trigger_node', 'trigger', 'Ticket created', eventTrigger('Ticket created')),
+ aiTask(
+ 'classify',
+ 'Sort the ticket',
+ 'Read the ticket. Pick a category (how_to, bug, billing) and an urgency from 1 to 3.',
+ ['category', 'urgency'],
+ ['support-categories']
+ ),
+ split('by_category', 'category', 'workflow_variable', [
+ ['How-to', 'how_to'],
+ ['Bug', 'bug'],
+ ['Billing', 'billing'],
+ ]),
+ aiTask(
+ 'draft_reply',
+ 'Answer the question',
+ 'Answer the question with links to the docs. Say how sure you are from 0 to 1.',
+ ['reply', 'confidence'],
+ ['docs-search', 'tone-of-voice']
+ ),
+ split('by_confidence', 'confidence', 'workflow_variable', [['Sure', '0.8', 'gte']]),
+ template('send_reply', 'Send reply', 'template-posthog-send-ticket-message', {
+ ticket_id: '{event.properties.ticket_id}',
+ message: '{variables.reply}',
+ is_private: false,
+ }),
+ template('save_note', 'Save as note', 'template-posthog-send-ticket-message', {
+ ticket_id: '{event.properties.ticket_id}',
+ message: '{variables.reply}',
+ is_private: true,
+ }),
+ template('tag_bug', 'Route to engineering', 'template-posthog-update-ticket', {
+ ticket_id: '{event.properties.ticket_id}',
+ priority: 'high',
+ tags: ['bug'],
+ }),
+ slack('bug_slack', 'Tell engineering', 'C0123|#bugs', 'New bug ticket: {event.properties.subject}'),
+ template('tag_billing', 'Route to billing', 'template-posthog-update-ticket', {
+ ticket_id: '{event.properties.ticket_id}',
+ status: 'pending',
+ tags: ['billing'],
+ }),
+ exit('exit_node', 'Ticket triaged'),
+ ],
+ [
+ next('trigger_node', 'classify'),
+ next('classify', 'by_category'),
+ branch('by_category', 'draft_reply', 0),
+ next('draft_reply', 'by_confidence'),
+ branch('by_confidence', 'send_reply', 0),
+ next('by_confidence', 'save_note'),
+ branch('by_category', 'tag_bug', 1),
+ next('tag_bug', 'bug_slack'),
+ branch('by_category', 'tag_billing', 2),
+ next('by_category', 'exit_node'),
+ next('send_reply', 'exit_node'),
+ next('save_note', 'exit_node'),
+ next('bug_slack', 'exit_node'),
+ next('tag_billing', 'exit_node'),
+ ]
+)
+
+export const TRIAL_TO_PAID = flow(
+ 'storybook-tile-trial-to-paid',
+ 'Convert trials to paid',
+ [
+ step('trigger_node', 'trigger', 'Trial started', eventTrigger('Trial started')),
+ delay('wait_ten_days', '10d'),
+ split('by_activation', 'docs_created', 'person', [['Active', '3', 'gte']]),
+ email(
+ 'upgrade',
+ 'Keep your team’s docs after the trial',
+ 'Upgrade now and keep everything',
+ 'Your team wrote a lot this week. Upgrade to keep every doc and comment.',
+ 'Upgrade'
+ ),
+ split('by_seats', 'seats', 'person', [['10+ seats', '10', 'gte']]),
+ slack('sales_slack', 'Tell sales', 'C0456|#sales-trials', 'Big trial is stuck: {person.properties.company}'),
+ email(
+ 'help',
+ 'Need a hand getting started?',
+ 'Book 15 minutes with us',
+ 'It looks like you have not written many docs yet. We are happy to help.',
+ 'Book a call'
+ ),
+ waitFor('wait_upgrade', 'Upgraded', '4d'),
+ exit('exit_converted', 'Converted to paid'),
+ email(
+ 'last_day',
+ 'Your trial ends tomorrow',
+ 'Pick a plan to keep your docs',
+ 'Your trial ends tomorrow. Pick a plan so your team keeps working.',
+ 'Pick a plan'
+ ),
+ template('mark_churn_risk', 'Mark churn risk', 'template-posthog-update-person-properties', {
+ set_properties: { churn_risk: 'high' },
+ }),
+ exit('exit_node', 'Trial ended'),
+ ],
+ [
+ next('trigger_node', 'wait_ten_days'),
+ next('wait_ten_days', 'by_activation'),
+ branch('by_activation', 'upgrade', 0),
+ next('by_activation', 'by_seats'),
+ branch('by_seats', 'sales_slack', 0),
+ next('by_seats', 'help'),
+ next('sales_slack', 'wait_upgrade'),
+ next('help', 'wait_upgrade'),
+ next('upgrade', 'wait_upgrade'),
+ branch('wait_upgrade', 'exit_converted', 0),
+ next('wait_upgrade', 'last_day'),
+ next('last_day', 'mark_churn_risk'),
+ next('mark_churn_risk', 'exit_node'),
+ ]
+)
+
+export const TICKET_TO_SLACK = flow(
+ 'storybook-tile-ticket-to-slack',
+ 'New support ticket to Slack',
+ [
+ step('trigger_node', 'trigger', 'Ticket created', eventTrigger('Ticket created')),
+ split('by_priority', 'priority', 'event', [['Urgent', 'urgent']]),
+ slack(
+ 'urgent_slack',
+ 'Urgent ticket',
+ 'C0789|#support-urgent',
+ '@here Urgent ticket from {person.properties.email}: {event.properties.subject}'
+ ),
+ template('page_oncall', 'Page on-call', 'template-webhook', {
+ url: 'https://events.example.com/v2/enqueue',
+ method: 'POST',
+ body: { severity: 'critical', summary: '{event.properties.subject}' },
+ }),
+ step('business_hours', 'wait_until_time_window', 'Business hours', {
+ timezone: 'Europe/Berlin',
+ day: 'weekday',
+ time: ['09:00', '17:00'],
+ }),
+ slack(
+ 'ticket_slack',
+ 'New ticket',
+ 'C0790|#support',
+ 'New ticket from {person.properties.email}: {event.properties.subject}'
+ ),
+ exit('exit_node', 'Team notified'),
+ ],
+ [
+ next('trigger_node', 'by_priority'),
+ branch('by_priority', 'urgent_slack', 0),
+ next('urgent_slack', 'page_oncall'),
+ next('page_oncall', 'exit_node'),
+ next('by_priority', 'business_hours'),
+ next('business_hours', 'ticket_slack'),
+ next('ticket_slack', 'exit_node'),
+ ]
+)
+
+export const LONG_EMAILS = flow(
+ 'storybook-tile-long-emails',
+ 'Long emails',
+ [
+ step('trigger_node', 'trigger', 'Signed up', eventTrigger('Signed up')),
+ emailStep(
+ 'newsletter',
+ 'Your October digest: shared templates, faster search, offline drafts, and the twelve docs your team opened most this month',
+ `Everything new this month, the docs ${FIRST_NAME}'s team keeps coming back to, the shortcuts power users swear by, and a first look at November`,
+ newsletterHtml,
+ 'Your October digest.'
+ ),
+ emailStep(
+ 'long_link',
+ 'Start from a template: example.com/templates/engineering-team-handbook-with-architecture-decision-records',
+ 'Supercalifragilisticdocumentationtemplategallerylaunchweekeditionforengineeringteams',
+ emailHtml(
+ '#6d28d9',
+ 'Start from a template',
+ `The most copied template this week: <a href="${LONG_LINK}">${LONG_LINK}</a>`,
+ 'Browse the gallery'
+ ),
+ `The most copied template this week: ${LONG_LINK}`
+ ),
+ emailStep(
+ 'plain_text',
+ 'A quick note from the team about inviting your teammates',
+ '',
+ '',
+ `Hi ${FIRST_NAME},\n\nDocs get better when two people look at them. You can invite three people for free from Settings, then Members.\n\nReply to this email if you have questions. A person reads every reply.`
+ ),
+ exit('exit_node', 'Welcome finished'),
+ ],
+ [
+ next('trigger_node', 'newsletter'),
+ next('newsletter', 'long_link'),
+ next('long_link', 'plain_text'),
+ next('plain_text', 'exit_node'),
+ ]
+)
+
+export const TILE_CANVAS_WORKFLOWS: Record<string, HogFlow> = Object.fromEntries(
+ [AI_SUPPORT_TRIAGE, TRIAL_TO_PAID, TICKET_TO_SLACK, LONG_EMAILS].map((workflow) => [workflow.id, workflow])
+)
+
+export const TRIAL_TO_PAID_METRICS: Record<string, HogFlowEditorActionMetrics> = Object.fromEntries(
+ (
+ [
+ ['trigger_node', 4800, 0, 0],
+ ['wait_ten_days', 4790, 0, 10],
+ ['by_activation', 4790, 0, 0],
+ ['upgrade', 3120, 12, 48],
+ ['by_seats', 1610, 0, 0],
+ ['sales_slack', 210, 0, 0],
+ ['help', 1380, 8, 12],
+ ['wait_upgrade', 4790, 0, 0],
+ ['exit_converted', 960, 0, 0],
+ ['last_day', 3790, 20, 20],
+ ['mark_churn_risk', 3830, 0, 0],
+ ['exit_node', 3830, 0, 0],
+ ] as const
+ ).map(([actionId, succeeded, failed, filtered]) => [actionId, { actionId, succeeded, failed, filtered }])
+)
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useCanvasCommands.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useCanvasCommands.tsx
new file mode 100644
index 000000000000..cb13d6254652
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useCanvasCommands.tsx
@@ -0,0 +1,119 @@
+import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
+import { useMemo } from 'react'
+
+import {
+ IconBrackets,
+ IconClock,
+ IconCollapse,
+ IconExpand,
+ IconGraph,
+ IconList,
+ IconPlay,
+ IconScreen,
+} from '@posthog/icons'
+
+import { tileCanvasLogic, TileCanvasPanelMode } from './tileCanvasLogic'
+import type { PaletteCommand } from './tileCanvasModel'
+
+export interface CanvasCommand extends PaletteCommand {
+ icon: JSX.Element
+ run: () => void
+}
+
+export interface PanelCommand extends CanvasCommand {
+ mode: TileCanvasPanelMode
+}
+
+export interface CanvasCommands {
+ panel: PanelCommand[]
+ morePanels: PanelCommand[]
+ view: CanvasCommand[]
+}
+
+type PanelDefinition = Omit<PanelCommand, 'run'> & { needsSavedWorkflow?: boolean }
+
+const PANELS: PanelDefinition[] = [
+ {
+ id: 'test',
+ mode: 'test',
+ label: 'Test',
+ hint: 'Run the workflow for one person',
+ icon: <IconPlay />,
+ needsSavedWorkflow: true,
+ },
+ {
+ id: 'logs',
+ mode: 'logs',
+ label: 'Logs',
+ hint: 'Recent runs, newest first',
+ icon: <IconList />,
+ needsSavedWorkflow: true,
+ },
+ {
+ id: 'variables',
+ mode: 'variables',
+ label: 'Variables',
+ hint: 'Values the steps can read and write',
+ icon: <IconBrackets />,
+ },
+]
+
+const METRICS_PANEL: PanelDefinition = {
+ id: 'metrics',
+ mode: 'metrics',
+ label: 'Metrics',
+ hint: 'How many people each step reached',
+ icon: <IconGraph />,
+ needsSavedWorkflow: true,
+}
+
+const HISTORY_PANEL: PanelDefinition = {
+ id: 'history',
+ mode: 'history',
+ label: 'History',
+ hint: 'See and restore previous versions',
+ icon: <IconClock />,
+ needsSavedWorkflow: true,
+}
+
+function tracked<Command extends CanvasCommand>(command: Command): Command {
+ return {
+ ...command,
+ run: () => {
+ posthog.capture('workflows tile canvas command run', { command: command.id })
+ command.run()
+ },
+ }
+}
+
+export function useCanvasCommands(): CanvasCommands {
+ const { pathGroups, allPathsCollapsed, isSavedWorkflow } = useValues(tileCanvasLogic)
+ const { openPanel, toggleAllPaths, requestFit } = useActions(tileCanvasLogic)
+ const hasPaths = pathGroups.length > 0
+
+ return useMemo((): CanvasCommands => {
+ const available = (panels: PanelDefinition[]): PanelCommand[] =>
+ panels
+ .filter((panel) => isSavedWorkflow || !panel.needsSavedWorkflow)
+ .map(({ needsSavedWorkflow: _, ...panel }) => tracked({ ...panel, run: () => openPanel(panel.mode) }))
+ const pathsCommand: CanvasCommand = {
+ id: 'paths',
+ label: allPathsCollapsed ? 'Open all paths' : 'Collapse all paths',
+ icon: allPathsCollapsed ? <IconExpand /> : <IconCollapse />,
+ run: toggleAllPaths,
+ }
+ const fitCommand: CanvasCommand = {
+ id: 'fit',
+ label: 'Fit to screen',
+ hint: 'Show the whole workflow',
+ icon: <IconScreen />,
+ run: requestFit,
+ }
+ return {
+ panel: available(PANELS),
+ morePanels: available([METRICS_PANEL, HISTORY_PANEL]),
+ view: [...(hasPaths ? [pathsCommand] : []), fitCommand].map(tracked),
+ }
+ }, [openPanel, isSavedWorkflow, hasPaths, allPathsCollapsed, toggleAllPaths, requestFit])
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useCanvasViewport.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useCanvasViewport.ts
new file mode 100644
index 000000000000..09add0d2541b
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useCanvasViewport.ts
@@ -0,0 +1,100 @@
+import { useReactFlow } from '@xyflow/react'
+import { useValues } from 'kea'
+import { MutableRefObject, RefObject, useEffect, useRef } from 'react'
+
+import { canvasBounds, tileEntry } from './tileCanvasLayout'
+import { tileCanvasLogic } from './tileCanvasLogic'
+import {
+ Point,
+ readableFitViewport,
+ Size,
+ viewportAfterResize,
+ viewportAnchoredOn,
+ viewportToFit,
+} from './tileCanvasModel'
+
+const FOCUS_MS = 400
+
+const sizeOf = (element: HTMLElement): Size => ({ width: element.clientWidth, height: element.clientHeight })
+
+function useSelectedStepBox(): MutableRefObject<(Point & Size) | undefined> {
+ const { layout, measuredSizes, selectedNodeId } = useValues(tileCanvasLogic)
+ const box = useRef<(Point & Size) | undefined>()
+ const position = selectedNodeId ? layout?.positions[selectedNodeId] : undefined
+ const size = selectedNodeId ? measuredSizes?.[selectedNodeId] : undefined
+ box.current = position && size ? { ...position, width: size.width, height: size.height } : undefined
+ return box
+}
+
+/** Without this, the graph stays pinned to the left edge as the docked panel opens and closes, so it
+ * slides out of view or off centre. */
+function useViewportFollowsResize(wrapperRef: RefObject<HTMLDivElement>): void {
+ const reactFlow = useReactFlow()
+ const selectedStepBox = useSelectedStepBox()
+ useEffect(() => {
+ const wrapper = wrapperRef.current
+ if (!wrapper) {
+ return
+ }
+ let previous = sizeOf(wrapper)
+ const observer = new ResizeObserver(() => {
+ const next = sizeOf(wrapper)
+ if (next.width === previous.width && next.height === previous.height) {
+ return
+ }
+ if (previous.width > 0 && previous.height > 0) {
+ void reactFlow.setViewport(
+ viewportAfterResize(reactFlow.getViewport(), previous, next, selectedStepBox.current)
+ )
+ }
+ previous = next
+ })
+ observer.observe(wrapper)
+ return () => observer.disconnect()
+ }, [reactFlow, wrapperRef, selectedStepBox])
+}
+
+/** Edits keep the viewport the person panned or zoomed to; only an explicit fit request moves it. */
+function useFitOnRequest(wrapperRef: RefObject<HTMLDivElement>): void {
+ const reactFlow = useReactFlow()
+ const { fitRequest, layout, measuredSizes, visibleGraph } = useValues(tileCanvasLogic)
+ useEffect(() => {
+ const wrapper = wrapperRef.current
+ const bounds = layout && measuredSizes ? canvasBounds(layout, measuredSizes) : undefined
+ if (wrapper && layout && measuredSizes && bounds) {
+ const trigger = visibleGraph.nodes.find((node) => node.kind === 'step' && node.action.type === 'trigger')
+ const position = trigger && layout.positions[trigger.id]
+ const size = trigger && measuredSizes[trigger.id]
+ const entry = position && size ? tileEntry(position, size) : { x: bounds.x + bounds.width / 2, y: bounds.y }
+ void reactFlow.setViewport(readableFitViewport(bounds, sizeOf(wrapper), entry))
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fitRequest])
+}
+
+function useFocusOnPath(wrapperRef: RefObject<HTMLDivElement>): void {
+ const reactFlow = useReactFlow()
+ const { viewportFocus } = useValues(tileCanvasLogic)
+ useEffect(() => {
+ const wrapper = wrapperRef.current
+ if (!wrapper || !viewportFocus) {
+ return
+ }
+ const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ const viewport = reactFlow.getViewport()
+ const canvas = sizeOf(wrapper)
+ const target = viewportFocus.anchor
+ ? viewportAnchoredOn(viewportFocus.anchor, viewportFocus.place, viewport, canvas)
+ : viewportToFit(viewportFocus.place, canvas, viewport.zoom)
+ // An anchored move runs while the path motion moves the nodes, and the canvas's own transition then moves the
+ // view in step with them. A second, animated move on top would let the path drift away from its anchor.
+ void reactFlow.setViewport(target, { duration: reduceMotion || viewportFocus.anchor ? 0 : FOCUS_MS })
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [viewportFocus?.request])
+}
+
+export function useCanvasViewport(wrapperRef: RefObject<HTMLDivElement>): void {
+ useViewportFollowsResize(wrapperRef)
+ useFitOnRequest(wrapperRef)
+ useFocusOnPath(wrapperRef)
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useComboboxInput.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useComboboxInput.ts
new file mode 100644
index 000000000000..6de453eb2eac
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useComboboxInput.ts
@@ -0,0 +1,24 @@
+import { RefObject, useEffect } from 'react'
+
+/** LemonInput takes no ARIA props, so the combobox roles go on its input directly. */
+export function useComboboxInput(
+ inputRef: RefObject<HTMLInputElement>,
+ listId: string,
+ activeOptionId: string | undefined
+): void {
+ useEffect(() => {
+ const input = inputRef.current
+ if (!input) {
+ return
+ }
+ input.setAttribute('role', 'combobox')
+ input.setAttribute('aria-expanded', 'true')
+ input.setAttribute('aria-autocomplete', 'list')
+ input.setAttribute('aria-controls', listId)
+ if (activeOptionId) {
+ input.setAttribute('aria-activedescendant', activeOptionId)
+ } else {
+ input.removeAttribute('aria-activedescendant')
+ }
+ }, [inputRef, listId, activeOptionId])
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useHoverIntent.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useHoverIntent.ts
new file mode 100644
index 000000000000..5aa854ebd61d
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useHoverIntent.ts
@@ -0,0 +1,57 @@
+import { MouseEvent, useEffect, useRef, useState } from 'react'
+
+/**
+ * The browser also reports the pointer entering a tile when the tile moves under a pointer at rest, as when a path
+ * opens or collapses in place. Only a pointer that moved means someone is pointing at the tile.
+ */
+export function isPointerMove(event: MouseEvent): boolean {
+ return event.movementX !== 0 || event.movementY !== 0
+}
+
+/** `open` turns on a frame after `mounted`, so the card's CSS transition runs from its closed state. */
+export function useHoverIntent(
+ enabled: boolean,
+ openDelayMs: number,
+ closeMs: number
+): { mounted: boolean; open: boolean; onMouseMove: (event: MouseEvent) => void; onMouseLeave: () => void } {
+ const [mounted, setMounted] = useState(false)
+ const [open, setOpen] = useState(false)
+ const timer = useRef<number>()
+ const pending = useRef(false)
+
+ useEffect(() => () => window.clearTimeout(timer.current), [])
+ useEffect(() => {
+ if (!enabled) {
+ window.clearTimeout(timer.current)
+ pending.current = false
+ setOpen(false)
+ setMounted(false)
+ }
+ }, [enabled])
+
+ return {
+ mounted: enabled && mounted,
+ open: enabled && open,
+ onMouseMove: (event) => {
+ if (!enabled || open || pending.current || !isPointerMove(event)) {
+ return
+ }
+ pending.current = true
+ window.clearTimeout(timer.current)
+ timer.current = window.setTimeout(
+ () => {
+ pending.current = false
+ setMounted(true)
+ requestAnimationFrame(() => requestAnimationFrame(() => setOpen(true)))
+ },
+ mounted ? 0 : openDelayMs
+ )
+ },
+ onMouseLeave: () => {
+ pending.current = false
+ window.clearTimeout(timer.current)
+ setOpen(false)
+ timer.current = window.setTimeout(() => setMounted(false), closeMs)
+ },
+ }
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useKeepInView.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useKeepInView.ts
new file mode 100644
index 000000000000..f43abaf29e80
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useKeepInView.ts
@@ -0,0 +1,41 @@
+import { RefObject, useEffect, useState } from 'react'
+
+import type { Point } from './tileCanvasModel'
+
+const VIEW_MARGIN = 12
+
+/** Shifts a card back inside the canvas. `bottomMargin` keeps it clear of what floats over the canvas bottom. */
+export function useKeepInView(ref: RefObject<HTMLElement>, active: boolean, bottomMargin: number = VIEW_MARGIN): Point {
+ const [shift, setShift] = useState<Point>({ x: 0, y: 0 })
+ useEffect(() => {
+ const card = ref.current
+ if (!card || !active) {
+ setShift({ x: 0, y: 0 })
+ return
+ }
+ const measure = (): void => {
+ const canvas = card.closest('.react-flow')?.getBoundingClientRect()
+ const box = card.getBoundingClientRect()
+ if (!canvas || !card.offsetWidth) {
+ return
+ }
+ // The canvas may be zoomed, so the card's screen size differs from its layout size.
+ const scale = box.width / card.offsetWidth
+ setShift((current) => {
+ const left = box.left - current.x * scale
+ const top = box.top - current.y * scale
+ const overRight = left + box.width - (canvas.right - VIEW_MARGIN)
+ const overBottom = top + box.height - (canvas.bottom - bottomMargin)
+ const x = overRight > 0 ? -Math.min(overRight, left - canvas.left - VIEW_MARGIN) : 0
+ const y = overBottom > 0 ? -Math.min(overBottom, top - canvas.top - VIEW_MARGIN) : 0
+ const next = { x: x / scale, y: y / scale }
+ return Math.abs(next.x - current.x) < 1 && Math.abs(next.y - current.y) < 1 ? current : next
+ })
+ }
+ const observer = new ResizeObserver(measure)
+ observer.observe(card)
+ measure()
+ return () => observer.disconnect()
+ }, [ref, active, bottomMargin])
+ return shift
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useMiniFlowSpotlight.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useMiniFlowSpotlight.ts
new file mode 100644
index 000000000000..f34507934a8c
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useMiniFlowSpotlight.ts
@@ -0,0 +1,95 @@
+import { MouseEvent, RefObject, useEffect, useRef, useState } from 'react'
+
+import { isHeadingToRect, Point } from './tileCanvasModel'
+
+const PREVIEW_DWELL_MS = 650
+const SAFE_TRIANGLE_SLACK = 12
+const SWITCH_AFTER_MS = 140
+
+export interface MiniFlowSpotlight {
+ spotlightId: string | null
+ showPreview: boolean
+ previewRef: RefObject<HTMLDivElement>
+ enterStep: (actionId: string) => void
+ leaveStep: (actionId: string) => void
+ enterPreview: () => void
+ trackPointer: (event: MouseEvent) => void
+ leaveFlow: () => void
+}
+
+/**
+ * Which step of a peek shows its card. A step the pointer crosses on its way down to the open card must not
+ * take the card away, so a new step wins only once the pointer leaves the path toward the card.
+ */
+export function useMiniFlowSpotlight(open: boolean): MiniFlowSpotlight {
+ const [spotlightId, setSpotlightId] = useState<string | null>(null)
+ const [showPreview, setShowPreview] = useState(false)
+ const pointer = useRef<Point>({ x: 0, y: 0 })
+ const apex = useRef<Point | null>(null)
+ const overId = useRef<string | null>(null)
+ const switchTimer = useRef<number>()
+ const previewRef = useRef<HTMLDivElement>(null)
+
+ useEffect(() => {
+ setShowPreview(false)
+ if (!spotlightId) {
+ return
+ }
+ const timer = window.setTimeout(() => setShowPreview(true), PREVIEW_DWELL_MS)
+ return () => window.clearTimeout(timer)
+ }, [spotlightId])
+
+ useEffect(() => {
+ if (!open) {
+ setSpotlightId(null)
+ }
+ }, [open])
+
+ useEffect(() => () => window.clearTimeout(switchTimer.current), [])
+
+ const isHeadingToPreview = (): boolean => {
+ const preview = previewRef.current?.getBoundingClientRect()
+ return (
+ !!preview && !!apex.current && isHeadingToRect(pointer.current, apex.current, preview, SAFE_TRIANGLE_SLACK)
+ )
+ }
+
+ return {
+ spotlightId,
+ showPreview,
+ previewRef,
+ enterStep: (actionId) => {
+ overId.current = actionId
+ window.clearTimeout(switchTimer.current)
+ if (spotlightId && spotlightId !== actionId && isHeadingToPreview()) {
+ switchTimer.current = window.setTimeout(() => {
+ if (overId.current === actionId) {
+ setSpotlightId(actionId)
+ }
+ }, SWITCH_AFTER_MS)
+ return
+ }
+ setSpotlightId(actionId)
+ },
+ leaveStep: (actionId) => {
+ if (overId.current === actionId) {
+ overId.current = null
+ }
+ },
+ enterPreview: () => {
+ overId.current = spotlightId
+ window.clearTimeout(switchTimer.current)
+ },
+ trackPointer: (event) => {
+ pointer.current = { x: event.clientX, y: event.clientY }
+ if (overId.current && overId.current === spotlightId) {
+ apex.current = pointer.current
+ }
+ },
+ leaveFlow: () => {
+ window.clearTimeout(switchTimer.current)
+ overId.current = null
+ setSpotlightId(null)
+ },
+ }
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useRaisedNode.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useRaisedNode.ts
new file mode 100644
index 000000000000..4035a53705ee
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useRaisedNode.ts
@@ -0,0 +1,15 @@
+import { RefObject, useEffect } from 'react'
+
+export function useRaisedNode(ref: RefObject<HTMLElement>, raised: boolean): void {
+ useEffect(() => {
+ const node = ref.current?.closest<HTMLElement>('.react-flow__node')
+ if (!node || !raised) {
+ return
+ }
+ const previous = node.style.zIndex
+ node.style.zIndex = '1000'
+ return () => {
+ node.style.zIndex = previous
+ }
+ }, [ref, raised])
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useTileStep.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useTileStep.tsx
new file mode 100644
index 000000000000..dd8365075839
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/useTileStep.tsx
@@ -0,0 +1,87 @@
+import { useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { IconChat, IconPerson, IconSearch, IconSparkles } from '@posthog/icons'
+
+import { IconSlack } from 'lib/lemon-ui/icons'
+
+import { themeLogic } from '~/layout/navigation-3000/themeLogic'
+
+import { workflowLogic } from '../../../workflowLogic'
+import { useHogFlowStep } from '../../steps/HogFlowSteps'
+import { isFunctionAction } from '../../steps/types'
+import type { HogFlow, HogFlowAction } from '../../types'
+import { customStepName, stepKindName } from '../../workflowStepCatalog'
+import { StepFacts, stepView } from './stepFacts'
+import type { StepPresentation } from './stepPresentation'
+
+export type TileShape = 'start' | 'end' | 'step'
+
+export interface TileStep {
+ label: string
+ customName?: string
+ icon: React.ReactNode
+ color: string
+ badge?: string
+ facts: StepFacts
+ presentation: StepPresentation
+ invalid: boolean
+ shape: TileShape
+}
+
+interface TemplateLook {
+ icon?: JSX.Element
+ color?: [light: string, dark: string]
+}
+
+const AI_COLOR: [string, string] = ['#7c3aed', '#a78bfa']
+const TICKET_COLOR: [string, string] = ['#0e7490', '#22d3ee']
+
+const TEMPLATE_LOOKS: Record<string, TemplateLook> = {
+ 'template-slack': { icon: <IconSlack />, color: ['#611f69', '#e8a6e0'] },
+ 'template-posthog-create-task': { icon: <IconSparkles />, color: AI_COLOR },
+ 'template-posthog-run-scout': { icon: <IconSearch />, color: AI_COLOR },
+ 'template-posthog-send-ticket-message': { icon: <IconChat />, color: TICKET_COLOR },
+ 'template-posthog-update-ticket': { icon: <IconChat />, color: TICKET_COLOR },
+ 'template-posthog-update-person-properties': { icon: <IconPerson />, color: ['#475569', '#94a3b8'] },
+}
+
+/** The start and end of a workflow are not steps anyone adds, so the step picker has no name for them. */
+const ENDPOINT_LABELS: Partial<Record<HogFlowAction['type'], string>> = {
+ trigger: 'Trigger',
+ exit: 'End',
+}
+
+/** Some step colors are dark in both themes, so dark mode lifts them to stay readable on a dark tile. */
+function readableStepColor(color: string | undefined, isDarkModeOn: boolean): string {
+ if (!color) {
+ return 'var(--color-text-secondary)'
+ }
+ return isDarkModeOn ? `color-mix(in srgb, ${color} 65%, white)` : color
+}
+
+export function useTileStep(action: HogFlowAction, workflow: HogFlow): TileStep {
+ const step = useHogFlowStep(action)
+ const { hogFunctionTemplatesById, actionValidationErrorsById } = useValues(workflowLogic)
+ const { isDarkModeOn } = useValues(themeLogic)
+
+ return useMemo(() => {
+ const templateId = isFunctionAction(action) ? action.config.template_id : undefined
+ const triggerTemplateId =
+ action.type === 'trigger' && 'template_id' in action.config ? action.config.template_id : undefined
+ const templateName = hogFunctionTemplatesById[templateId ?? triggerTemplateId ?? '']?.name
+ const look = templateId ? TEMPLATE_LOOKS[templateId] : undefined
+ const view = stepView(workflow, action, templateName)
+ return {
+ label: ENDPOINT_LABELS[action.type] ?? stepKindName(action) ?? templateName ?? 'Step',
+ customName: customStepName(action, [templateName, view.facts.headline]),
+ icon: look?.icon ?? step?.icon,
+ color: look?.color?.[isDarkModeOn ? 1 : 0] ?? readableStepColor(step?.color, isDarkModeOn),
+ badge: view.badge,
+ facts: view.facts,
+ presentation: view.presentation,
+ invalid: actionValidationErrorsById[action.id]?.valid === false,
+ shape: action.type === 'trigger' ? 'start' : action.type === 'exit' ? 'end' : 'step',
+ }
+ }, [action, workflow, step, hogFunctionTemplatesById, actionValidationErrorsById, isDarkModeOn])
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/workflowEditorStoryFixtures.ts b/products/workflows/frontend/Workflows/hogflows/editor/workflowEditorStoryFixtures.ts
index 0f2928d41011..55ecde689265 100644
--- a/products/workflows/frontend/Workflows/hogflows/editor/workflowEditorStoryFixtures.ts
+++ b/products/workflows/frontend/Workflows/hogflows/editor/workflowEditorStoryFixtures.ts
@@ -277,48 +277,56 @@ const PICKABLE_WORKFLOWS: Record<string, HogFlow> = {
...EXAMPLE_WORKFLOWS,
}
-export const workflowEditorStoryDecorator = mswDecorator({
- get: {
- '/api/projects/:team_id/hog_flow_templates/': { count: 0, results: [] },
- // nosemgrep: no-environments-api-urls-frontend -- api.hogFlows has not migrated to generated project routes.
- '/api/environments/:team_id/hog_flows/:id/': ({ params }) => [
- 200,
- PICKABLE_WORKFLOWS[String(params.id)] ?? CUSTOMER_ONBOARDING_AND_RETENTION_WORKFLOW,
- ],
- // nosemgrep: no-environments-api-urls-frontend -- api.messaging has not migrated to generated project routes.
- '/api/environments/:team_id/messaging_categories': { count: 0, results: [] },
- },
- patch: {
- // nosemgrep: no-environments-api-urls-frontend -- api.hogFlows has not migrated to generated project routes.
- '/api/environments/:team_id/hog_flows/:id/': async ({ request, params }) => [
- 200,
- {
- ...(PICKABLE_WORKFLOWS[String(params.id)] ?? CUSTOMER_ONBOARDING_AND_RETENTION_WORKFLOW),
- ...((await request.json()) as Partial<HogFlow>),
- updated_at: '2026-09-04T12:01:00.000Z',
- },
- ],
- },
- post: {
- // nosemgrep: no-environments-api-urls-frontend -- api.hogFlows has not migrated to generated project routes.
- '/api/environments/:team_id/hog_flows/': async ({ request }) => [
- 201,
- {
- ...NEW_WORKFLOW,
- ...((await request.json()) as Partial<HogFlow>),
- id: 'storybook-new-workflow',
- team_id: 1,
- created_at: '2026-09-04T12:01:00.000Z',
- updated_at: '2026-09-04T12:01:00.000Z',
+/** Pass more workflows to make them loadable by id in a story. */
+export function createWorkflowEditorStoryDecorator(
+ extraWorkflows: Record<string, HogFlow> = {}
+): ReturnType<typeof mswDecorator> {
+ const workflowsById: Record<string, HogFlow> = { ...PICKABLE_WORKFLOWS, ...extraWorkflows }
+ return mswDecorator({
+ get: {
+ '/api/projects/:team_id/hog_flow_templates/': { count: 0, results: [] },
+ // nosemgrep: no-environments-api-urls-frontend -- api.hogFlows has not migrated to generated project routes.
+ '/api/environments/:team_id/hog_flows/:id/': ({ params }) => [
+ 200,
+ workflowsById[String(params.id)] ?? CUSTOMER_ONBOARDING_AND_RETENTION_WORKFLOW,
+ ],
+ // nosemgrep: no-environments-api-urls-frontend -- api.messaging has not migrated to generated project routes.
+ '/api/environments/:team_id/messaging_categories': { count: 0, results: [] },
+ },
+ patch: {
+ // nosemgrep: no-environments-api-urls-frontend -- api.hogFlows has not migrated to generated project routes.
+ '/api/environments/:team_id/hog_flows/:id/': async ({ request, params }) => [
+ 200,
+ {
+ ...(workflowsById[String(params.id)] ?? CUSTOMER_ONBOARDING_AND_RETENTION_WORKFLOW),
+ ...((await request.json()) as Partial<HogFlow>),
+ updated_at: '2026-09-04T12:01:00.000Z',
+ },
+ ],
+ },
+ post: {
+ // nosemgrep: no-environments-api-urls-frontend -- api.hogFlows has not migrated to generated project routes.
+ '/api/environments/:team_id/hog_flows/': async ({ request }) => [
+ 201,
+ {
+ ...NEW_WORKFLOW,
+ ...((await request.json()) as Partial<HogFlow>),
+ id: 'storybook-new-workflow',
+ team_id: 1,
+ created_at: '2026-09-04T12:01:00.000Z',
+ updated_at: '2026-09-04T12:01:00.000Z',
+ },
+ ],
+ // nosemgrep: no-environments-api-urls-frontend -- api.hogFlows has not migrated to generated project routes.
+ '/api/environments/:team_id/hog_flows/user_blast_radius/': {
+ affected: 240,
+ total: 1200,
+ limit: 100000,
+ dedupe_key: null,
+ confirm_token: 'storybook-confirm-token',
},
- ],
- // nosemgrep: no-environments-api-urls-frontend -- api.hogFlows has not migrated to generated project routes.
- '/api/environments/:team_id/hog_flows/user_blast_radius/': {
- affected: 240,
- total: 1200,
- limit: 100000,
- dedupe_key: null,
- confirm_token: 'storybook-confirm-token',
},
- },
-})
+ })
+}
+
+export const workflowEditorStoryDecorator = createWorkflowEditorStoryDecorator()
diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.ts
index d62b8571509e..fd4b89d69b42 100644
--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.ts
@@ -1,9 +1,13 @@
import { expectLogic } from 'kea-test-utils'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
import { initKeaTests } from '~/test/init'
import { EXIT_NODE_ID, NEW_WORKFLOW, TRIGGER_NODE_ID, workflowLogic } from '../workflowLogic'
import { computeInsertEdges, computeMoveEdges, hogFlowEditorLogic } from './hogFlowEditorLogic'
+import * as autolayout from './react_flow_utils/autolayout'
import { HogFlow, HogFlowAction, HogFlowActionEdge, HogFlowActionNode } from './types'
type Edge = HogFlow['edges'][0]
@@ -176,6 +180,40 @@ describe('hogFlowEditorLogic', () => {
logic.mount()
})
+ it.each([
+ { name: 'the tile canvas', flags: ['tile'], layout: 'advanced', id: 'flow-1', expected: true },
+ {
+ name: 'the list view of both flags',
+ flags: ['tile', 'linear'],
+ layout: 'simple',
+ id: 'flow-1',
+ expected: true,
+ },
+ {
+ name: 'the graph view of both flags',
+ flags: ['tile', 'linear'],
+ layout: 'advanced',
+ id: 'flow-1',
+ expected: true,
+ },
+ { name: 'the graph editor', flags: [], layout: 'advanced', id: 'flow-1', expected: false },
+ { name: 'the tile canvas of a new workflow', flags: ['tile'], layout: 'advanced', id: 'new', expected: true },
+ ] as const)(
+ 'moves the workflow header into the workflow bar only for $name: $expected',
+ ({ flags, layout, id, expected }) => {
+ const flagKeys = { tile: FEATURE_FLAGS.WORKFLOWS_TILE_CANVAS, linear: FEATURE_FLAGS.WORKFLOWS_LINEAR_VIEW }
+ featureFlagLogic.actions.setFeatureFlags(
+ flags.map((flag) => flagKeys[flag]),
+ Object.fromEntries(flags.map((flag) => [flagKeys[flag], true]))
+ )
+ const editorLogic = hogFlowEditorLogic({ id })
+ editorLogic.mount()
+ editorLogic.actions.setEditorLayout(layout)
+
+ expect(editorLogic.values.showsHeaderInWorkflowBar).toBe(expected)
+ }
+ )
+
it('resolves the selected action while React Flow nodes are still laying out', () => {
const action = logic.values.workflow.actions[0]
logic.actions.setNodesRaw([])
@@ -583,6 +621,45 @@ describe('hogFlowEditorLogic', () => {
})
})
+ describe('legacy graph layout under the tile canvas', () => {
+ const delay: HogFlowAction = {
+ id: 'delay',
+ name: 'Delay',
+ description: '',
+ type: 'delay',
+ created_at: 0,
+ updated_at: 0,
+ config: { delay_duration: '1d' },
+ }
+
+ it.each([
+ {
+ name: 'skips the layout while the tile canvas shows',
+ flags: [FEATURE_FLAGS.WORKFLOWS_TILE_CANVAS],
+ laysOut: false,
+ },
+ { name: 'lays out the graph editor', flags: [], laysOut: true },
+ ])('$name, and keeps the steps the canvas reads', async ({ flags, laysOut }) => {
+ featureFlagLogic.actions.setFeatureFlags(flags, Object.fromEntries(flags.map((flag) => [flag, true])))
+ const editorLogic = hogFlowEditorLogic()
+ editorLogic.mount()
+ editorLogic.actions.setEditorLayout('advanced')
+ await expectLogic(editorLogic).toFinishAllListeners()
+ const layout = jest.spyOn(autolayout, 'getFormattedNodes')
+
+ await expectLogic(editorLogic, () =>
+ 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')],
+ })
+ ).toFinishAllListeners()
+
+ expect(layout.mock.calls.length > 0).toBe(laysOut)
+ expect(editorLogic.values.nodes.map((node) => node.id)).toEqual([TRIGGER_NODE_ID, delay.id, EXIT_NODE_ID])
+ layout.mockRestore()
+ })
+ })
+
describe('graph identity across rebuilds', () => {
// Auto-save round-trips rebuild the graph from the workflow; without id-based
// reconciliation every node and edge object is recreated each time and every ReactFlow
diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
index ad15efbc1793..a5e17368ede8 100644
--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
@@ -19,8 +19,14 @@ import type { DragEvent, RefObject } from 'react'
import { lemonToast } from '@posthog/lemon-ui'
-import { AppMetricsTotalsRequest, loadAppMetricsTotals } from 'lib/components/AppMetrics/appMetricsLogic'
+import {
+ AppMetricsTotalsRequest,
+ AppMetricsTotalsResponse,
+ loadAppMetricsTotals,
+} from 'lib/components/AppMetrics/appMetricsLogic'
+import { FEATURE_FLAGS } from 'lib/constants'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { uuid } from 'lib/utils/dom'
import { objectsEqual, reconcileById } from 'lib/utils/objects'
@@ -190,6 +196,47 @@ export type HogFlowEditorActionMetrics = {
filtered: number
}
+/** Turns metric totals broken down by step and metric into one entry per step. */
+export function actionMetricsFromTotals(
+ response: AppMetricsTotalsResponse
+): Record<string, HogFlowEditorActionMetrics> {
+ const res: Record<string, HogFlowEditorActionMetrics> = {}
+ Object.values(response).forEach((value) => {
+ let [instanceId, metricName] = value.breakdowns
+
+ if (!metricName) {
+ return
+ }
+
+ if (!instanceId) {
+ // TRICKY: Trigger and exit dont get their own metrics so we pull from the overall metrics
+ if (['succeeded', 'failed'].includes(metricName)) {
+ instanceId = EXIT_NODE_ID
+ } else if (['rate_limited', 'triggered'].includes(metricName)) {
+ instanceId = TRIGGER_NODE_ID
+ if (['rate_limited'].includes(metricName)) {
+ metricName = 'failed'
+ }
+ if (['triggered'].includes(metricName)) {
+ metricName = 'succeeded'
+ }
+ }
+ }
+
+ res[instanceId] = res[instanceId] || {
+ actionId: instanceId,
+ succeeded: 0,
+ failed: 0,
+ filtered: 0,
+ }
+ if (metricName in res[instanceId]) {
+ ;(res[instanceId] as any)[metricName] = value.total
+ }
+ })
+
+ return res
+}
+
export type OutputMappingSuggestion = {
key: string
result_path: string
@@ -205,6 +252,7 @@ export type CreateActionType = Pick<HogFlowAction, 'type' | 'config' | 'name' |
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface hogFlowEditorLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
integrations: IntegrationType[] | null // integrationsLogic
categories: MessageCategory[] // optOutCategoriesLogic
categoriesLoading: boolean // optOutCategoriesLogic
@@ -221,6 +269,8 @@ export interface hogFlowEditorLogicValues {
highlightedDropzoneNodeId: string | null
isCopyingNode: boolean
isMovingNode: boolean
+ isTileCanvas: boolean
+ isTreeView: boolean
isZoomedOutFar: boolean
mode: HogFlowEditorMode
movingNodeId: string | null
@@ -234,6 +284,7 @@ export interface hogFlowEditorLogicValues {
selectedNodeCanBeCopiedOrMoved: boolean
selectedNodeCanBeDeleted: boolean
selectedNodeId: string | null
+ showsHeaderInWorkflowBar: boolean
treePathsCollapsedByDefault: boolean
}
@@ -2193,6 +2244,9 @@ export interface hogFlowEditorLogicActions {
export interface hogFlowEditorLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ isTileCanvas: (featureFlags: FeatureFlagsSet) => boolean
+ isTreeView: (featureFlags: FeatureFlagsSet, editorLayout: HogFlowEditorLayout, isTileCanvas: boolean) => boolean
+ showsHeaderInWorkflowBar: (isTileCanvas: boolean) => boolean
nodesById: (nodes: HogFlowActionNode[]) => Record<string, HogFlowActionNode>
selectedNode: (
nodes: HogFlowActionNode[],
@@ -2232,6 +2286,8 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
['integrations'],
teamLogic,
['currentTeam'],
+ featureFlagLogic,
+ ['featureFlags'],
],
actions: [
workflowLogic,
@@ -2417,6 +2473,18 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
})),
selectors({
+ /** The tile canvas replaces both the graph and the list view. */
+ isTileCanvas: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.WORKFLOWS_TILE_CANVAS],
+ ],
+ isTreeView: [
+ (s) => [s.featureFlags, s.editorLayout, s.isTileCanvas],
+ (featureFlags: FeatureFlagsSet, editorLayout: HogFlowEditorLayout, isTileCanvas: boolean): boolean =>
+ !isTileCanvas && !!featureFlags[FEATURE_FLAGS.WORKFLOWS_LINEAR_VIEW] && editorLayout === 'simple',
+ ],
+ /** The tile canvas carries the workflow header in its own bar, saved or not. */
+ showsHeaderInWorkflowBar: [(s) => [s.isTileCanvas], (isTileCanvas: boolean): boolean => isTileCanvas],
nodesById: [
(s) => [s.nodes],
(nodes: HogFlowActionNode[]): Record<string, HogFlowActionNode> => {
@@ -2497,41 +2565,7 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
const response = await loadAppMetricsTotals(_params, timezone)
await breakpoint(10)
- const res: Record<string, HogFlowEditorActionMetrics> = {}
- Object.values(response).forEach((value) => {
- let [instanceId, metricName] = value.breakdowns
-
- if (!metricName) {
- return
- }
-
- if (!instanceId) {
- // TRICKY: Trigger and exit dont get their own metrics so we pull from the overall metrics
- if (['succeeded', 'failed'].includes(metricName)) {
- instanceId = EXIT_NODE_ID
- } else if (['rate_limited', 'triggered'].includes(metricName)) {
- instanceId = TRIGGER_NODE_ID
- if (['rate_limited'].includes(metricName)) {
- metricName = 'failed'
- }
- if (['triggered'].includes(metricName)) {
- metricName = 'succeeded'
- }
- }
- }
-
- res[instanceId] = res[instanceId] || {
- actionId: instanceId,
- succeeded: 0,
- failed: 0,
- filtered: 0,
- }
- if (metricName in res[instanceId]) {
- ;(res[instanceId] as any)[metricName] = value.total
- }
- })
-
- return res
+ return actionMetricsFromTotals(response)
},
},
],
@@ -2659,7 +2693,8 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
},
setNodes: async ({ nodes }, breakpoint) => {
- const formattedNodes = await getFormattedNodes(nodes, values.edges)
+ // The tile canvas lays out its own tiles and reads only the steps and edges, so skip ELK under it.
+ const formattedNodes = values.isTileCanvas ? nodes : await getFormattedNodes(nodes, values.edges)
// Drop this layout run if a newer setNodes was dispatched while elk was working,
// so overlapping rebuilds can't finish out of order and let a stale layout win.
breakpoint()
@@ -2736,14 +2771,17 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
const sourceHandle = sourceNode.handles?.find((h) => h.id === edge.sourceHandle)
const targetHandle = targetNode.handles?.find((h) => h.id === edge.targetHandle)
- const [, labelX, labelY] = getSmartStepPath({
- sourceX: sourceNode.position.x + (sourceHandle?.x || 0),
- sourceY: sourceNode.position.y + (sourceHandle?.y || 0),
- targetX: targetNode.position.x + (targetHandle?.x || 0),
- targetY: targetNode.position.y + (targetHandle?.y || 0),
- edges,
- currentEdgeId: edge.id,
- })
+ // The tile canvas finds a dropzone by its edge and draws its own +, so it needs no position.
+ const [, labelX, labelY] = values.isTileCanvas
+ ? [undefined, 0, 0]
+ : getSmartStepPath({
+ sourceX: sourceNode.position.x + (sourceHandle?.x || 0),
+ sourceY: sourceNode.position.y + (sourceHandle?.y || 0),
+ targetX: targetNode.position.x + (targetHandle?.x || 0),
+ targetY: targetNode.position.y + (targetHandle?.y || 0),
+ edges,
+ currentEdgeId: edge.id,
+ })
dropzoneNodes.push({
id: `dropzone_edge_${edge.id}`,
@@ -3126,6 +3164,12 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
}),
subscriptions(({ actions, values }) => ({
+ isTileCanvas: (isTileCanvas: boolean, wasTileCanvas: boolean | undefined) => {
+ // Leaving the tile canvas needs the positions it skipped.
+ if (wasTileCanvas && !isTileCanvas) {
+ actions.resetFlowFromHogFlow(values.workflow)
+ }
+ },
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.
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.tsx
index f67419e33ae9..dc80fa668c57 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.tsx
@@ -2,7 +2,7 @@ import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import { useRef } from 'react'
-import { IconArrowLeft } from '@posthog/icons'
+import { IconArrowLeft, IconX } from '@posthog/icons'
import { LemonBadge, LemonButton, LemonTab, LemonTabs } from '@posthog/lemon-ui'
import { Resizer } from 'lib/components/Resizer/Resizer'
@@ -25,9 +25,20 @@ import { HogFlowEditorPanelVariables } from './HogFlowEditorPanelVariables'
import { EmailActionTestContent } from './testing/HogFlowEditorNotificationPanelTest'
import { HogFlowEditorPanelTest } from './testing/HogFlowEditorPanelTest'
+export interface HogFlowEditorPanelProps {
+ layout?: 'floating' | 'panel' | 'docked'
+ onClose?: () => void
+ view?: { title: string; content: JSX.Element }
+ /** Replaces the selected step's head, for a canvas that draws steps its own way. */
+ stepHead?: JSX.Element
+}
+
export function HogFlowEditorPanel({
layout = 'floating',
-}: { layout?: 'floating' | 'panel' } = {}): JSX.Element | null {
+ onClose,
+ view,
+ stepHead,
+}: HogFlowEditorPanelProps = {}): JSX.Element | null {
const { panelWidth, selectedNode, mode, workflow } = useValues(hogFlowEditorLogic)
const { clearPanelWidth, setMode, setPanelWidth, setSelectedNodeId } = useActions(hogFlowEditorLogic)
const panelRef = useRef<HTMLDivElement>(null)
@@ -40,6 +51,7 @@ export function HogFlowEditorPanel({
const { desiredSize: panelLayoutWidth } = useValues(resizerLogic(resizerProps))
const variablesCount = workflow?.variables?.length || 0
+ const width = panelWidth ?? HOG_FLOW_EDITOR_DEFAULT_PANEL_WIDTH
const tabs: LemonTab<HogFlowEditorMode>[] = HOG_FLOW_EDITOR_MODES.map((mode) => ({
label: (
@@ -65,22 +77,20 @@ export function HogFlowEditorPanel({
data-attr="workflow-editor-panel"
className={clsx(
'flex min-h-0 max-h-full flex-col justify-end overflow-hidden @max-[48rem]/workflow-editor:!relative @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:shrink-0',
- layout === 'floating'
- ? 'absolute right-0 max-w-full p-2'
- : 'relative h-full shrink-0 bg-surface-primary @max-[48rem]/workflow-editor:border-t'
+ layout === 'floating' && 'absolute right-0 max-w-full p-2',
+ layout === 'panel' &&
+ 'relative h-full shrink-0 bg-surface-primary @max-[48rem]/workflow-editor:border-t',
+ layout === 'docked' &&
+ 'relative h-full min-w-80 max-w-[calc(100%-30rem)] shrink-0 border-l bg-surface-primary @max-[48rem]/workflow-editor:border-t @max-[48rem]/workflow-editor:border-l-0'
)}
style={
- layout === 'floating'
- ? { width: panelWidth ?? HOG_FLOW_EDITOR_DEFAULT_PANEL_WIDTH }
- : { width: panelLayoutWidth ?? '50%', minWidth: '20rem', maxWidth: '70%' }
+ layout === 'panel'
+ ? { width: panelLayoutWidth ?? '50%', minWidth: '20rem', maxWidth: '70%' }
+ : { width }
}
>
- {layout === 'floating' ? (
- <HogFlowEditorPanelResizeHandle
- width={panelWidth ?? HOG_FLOW_EDITOR_DEFAULT_PANEL_WIDTH}
- onResize={setPanelWidth}
- onReset={clearPanelWidth}
- />
+ {layout !== 'panel' ? (
+ <HogFlowEditorPanelResizeHandle width={width} onResize={setPanelWidth} onReset={clearPanelWidth} />
) : (
<div className="@max-[48rem]/workflow-editor:hidden">
<Resizer {...resizerProps} />
@@ -111,30 +121,53 @@ export function HogFlowEditorPanel({
</div>
<div className="min-w-0 flex-1">
- <LemonTabs
- activeKey={mode}
- onChange={(key) => setMode(key)}
- tabs={tabs}
- barClassName="-mb-px "
- />
+ {layout === 'docked' ? (
+ <h3 className="m-0 truncate py-2 text-sm font-semibold">
+ {view?.title ?? capitalizeFirstLetter(mode)}
+ </h3>
+ ) : (
+ <LemonTabs
+ activeKey={mode}
+ onChange={(key) => setMode(key)}
+ tabs={tabs}
+ barClassName="-mb-px "
+ />
+ )}
</div>
+ {onClose && (
+ <div className="shrink-0 p-1">
+ <LemonButton
+ size="small"
+ icon={<IconX />}
+ tooltip="Close the panel (Esc)"
+ data-attr="workflow-tile-close-panel"
+ onClick={onClose}
+ />
+ </div>
+ )}
</div>
- {selectedNode && ['build', 'metrics', 'test', 'logs'].includes(mode) && (
- <HogFlowEditorPanelSelectedStep />
- )}
- {mode === 'build' && (
- <>{!selectedNode ? <HogFlowEditorPanelBuild /> : <HogFlowEditorPanelBuildDetail />}</>
+ {view ? (
+ view.content
+ ) : (
+ <>
+ {selectedNode &&
+ ['build', 'metrics', 'test', 'logs'].includes(mode) &&
+ (stepHead ?? <HogFlowEditorPanelSelectedStep />)}
+ {mode === 'build' && (
+ <>{!selectedNode ? <HogFlowEditorPanelBuild /> : <HogFlowEditorPanelBuildDetail />}</>
+ )}
+ {mode === 'variables' && <HogFlowEditorPanelVariables />}
+ {mode === 'test' &&
+ (selectedNode?.data?.type === 'function_email' ? (
+ <EmailActionTestContent />
+ ) : (
+ <HogFlowEditorPanelTest />
+ ))}
+ {mode === 'metrics' && <HogFlowEditorPanelMetrics />}
+ {mode === 'logs' && <HogFlowEditorPanelLogs />}
+ </>
)}
- {mode === 'variables' && <HogFlowEditorPanelVariables />}
- {mode === 'test' &&
- (selectedNode?.data?.type === 'function_email' ? (
- <EmailActionTestContent />
- ) : (
- <HogFlowEditorPanelTest />
- ))}
- {mode === 'metrics' && <HogFlowEditorPanelMetrics />}
- {mode === 'logs' && <HogFlowEditorPanelLogs />}
</div>
</div>
)
diff --git a/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.test.ts b/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.test.ts
index 8c17918294fc..98b806ff89ef 100644
--- a/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.test.ts
@@ -2,7 +2,14 @@ import { FEATURE_FLAGS } from 'lib/constants'
import type { HogFunctionTemplateType } from '~/types'
-import { isPickableDestination, StepCatalogContext, workflowStepSections } from './workflowStepCatalog'
+import type { HogFlowAction } from './types'
+import {
+ customStepName,
+ destinationSteps,
+ StepCatalogContext,
+ stepKindName,
+ workflowStepSections,
+} from './workflowStepCatalog'
const mainEnvironment = { id: 1, project_id: 1 }
@@ -69,8 +76,43 @@ describe('workflowStepCatalog', () => {
const template = (id: string, name: string): HogFunctionTemplateType =>
({ id, name, type: 'destination', status: 'stable', description: '' }) as HogFunctionTemplateType
- const templates = [template('template-slack', 'Slack'), template('template-hubspot', 'HubSpot')]
+ const steps = destinationSteps([template('template-slack', 'Slack'), template('template-hubspot', 'HubSpot')])
- expect(templates.filter(isPickableDestination).map((template) => template.name)).toEqual(['HubSpot'])
+ expect(steps.map((step) => step.name)).toEqual(['HubSpot'])
+ })
+
+ it.each([
+ ['a conditional branch', { type: 'conditional_branch', config: {} }, 'Conditional branch'],
+ ['a wait for a condition', { type: 'wait_until_condition', config: {} }, 'Wait until'],
+ ['a Slack step', { type: 'function', config: { template_id: 'template-slack' } }, 'Slack'],
+ [
+ 'a ticket reply',
+ { type: 'function', config: { template_id: 'template-posthog-send-ticket-message' } },
+ 'Send message',
+ ],
+ [
+ 'a Replay Vision step',
+ { type: 'function', config: { template_id: 'template-posthog-replay-vision' } },
+ 'Replay Vision',
+ ],
+ [
+ 'a destination it does not list',
+ { type: 'function', config: { template_id: 'template-hubspot' } },
+ undefined,
+ ],
+ ])('names %s the way the step picker does', (_, action, name) => {
+ expect(stepKindName(action as HogFlowAction)).toBe(name)
+ })
+
+ it.each([
+ ['keeps a name someone gave the step', 'Nudge trial users', [], 'Nudge trial users'],
+ ['skips the name the step picker gave it', 'Delay', [], undefined],
+ ['skips the name of the destination it runs', 'HubSpot', ['HubSpot'], undefined],
+ ['skips a name the caption already shows', 'Wait 1 day', ['Wait 1 day'], undefined],
+ ['skips an empty name', ' ', [], undefined],
+ ])('%s', (_, name, shownElsewhere, expected) => {
+ const action = { type: 'delay', name, config: { delay_duration: '1h' } } as HogFlowAction
+
+ expect(customStepName(action, shownElsewhere)).toBe(expected)
})
})
diff --git a/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.ts b/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.ts
index 3a7fa47055a8..33cdd9f71c3d 100644
--- a/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.ts
+++ b/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.ts
@@ -11,6 +11,7 @@ import type { CreateActionType } from './hogFlowEditorLogic'
import { destinationPickerFilter } from './panel/destinationPickerFilter'
import { getRegisteredActionNodeCategories } from './registry/actions/actionNodeRegistry'
import { DEFAULT_DELAY_DURATION, getDelayDescription } from './steps/stepDelayLogic'
+import type { HogFlowAction } from './types'
const ACTION_NODES_TO_SHOW: CreateActionType[] = [
{
@@ -258,6 +259,15 @@ const ALWAYS_LISTED_STEPS: CreateActionType[] = [
...getRegisteredActionNodeCategories().flatMap((category) => category.nodes),
]
+const ALL_CATALOG_STEPS: CreateActionType[] = [
+ ...ALWAYS_LISTED_STEPS,
+ PUSH_NOTIFICATION_ACTION_NODE,
+ AI_TASK_ACTION_NODE,
+ RUN_SCOUT_ACTION_NODE,
+ CLASSIFY_ACTION_NODE,
+ REPLAY_VISION_ACTION_NODE,
+]
+
/** Destinations already offered as their own step stay out of the destination list. */
const TEMPLATE_IDS_AT_TOP_LEVEL = ALWAYS_LISTED_STEPS.flatMap((step) => templateIdOf(step) ?? [])
@@ -271,3 +281,27 @@ export function destinationStep(template: HogFunctionTemplateType): CreateAction
config: { template_id: template.id, inputs: {} },
}
}
+
+/** Destination templates that are not already a step of their own, as steps, by name. */
+export function destinationSteps(templates: HogFunctionTemplateType[]): CreateActionType[] {
+ return templates
+ .filter(isPickableDestination)
+ .sort((a, b) => a.name.localeCompare(b.name))
+ .map(destinationStep)
+}
+
+const kindKey = (type: string, templateId: string | undefined): string => `${type}:${templateId ?? ''}`
+
+const STEP_KIND_NAMES = new Map(ALL_CATALOG_STEPS.map((step) => [kindKey(step.type, templateIdOf(step)), step.name]))
+
+/** The name the step picker gives this kind of step, so one kind of step has one name everywhere. */
+export function stepKindName(action: HogFlowAction): string | undefined {
+ const templateId = 'template_id' in action.config ? (action.config.template_id as string | undefined) : undefined
+ return STEP_KIND_NAMES.get(kindKey(action.type, templateId)) ?? STEP_KIND_NAMES.get(kindKey(action.type, undefined))
+}
+
+/** The step's own name, unless it is still the name the step picker gave it or reads the same as a text shown beside it. */
+export function customStepName(action: HogFlowAction, shownElsewhere: (string | undefined)[]): string | undefined {
+ const name = action.name?.trim()
+ return name && name !== stepKindName(action) && !shownElsewhere.includes(name) ? name : undefined
+}
diff --git a/products/workflows/frontend/Workflows/workflowBackTo.ts b/products/workflows/frontend/Workflows/workflowBackTo.ts
new file mode 100644
index 000000000000..3709fb1f782d
--- /dev/null
+++ b/products/workflows/frontend/Workflows/workflowBackTo.ts
@@ -0,0 +1,12 @@
+import { urls } from 'scenes/urls'
+
+import { Breadcrumb } from '~/types'
+
+import { HogFlow } from './hogflows/types'
+
+/** A broadcast isn't in the workflows list, so going back from its editor returns to the broadcast. */
+export function workflowBackTo(workflow: HogFlow | null | undefined, id: string | undefined): Breadcrumb | undefined {
+ return workflow?.origin_product === 'broadcasts' && id && id !== 'new'
+ ? { key: 'broadcast', name: workflow.name || 'the broadcast', path: urls.broadcast(id) }
+ : undefined
+}