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.

refactor(workflows): fold the builder duration grammar into one module (#104001)

Daniel Marchuk900075f8bc2a
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.tsx
index 95f2ea6ef1b9..917a82a87e96 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.tsx
@@ -2,8 +2,7 @@ import { useEffect, useRef, useState } from 'react'
import { LemonInput, LemonSelect } from '@posthog/lemon-ui'
-// Allow an empty numeric part so a cleared input keeps its unit instead of resetting to a default.
-const DURATION_REGEX = /^(\d*\.?\d*)([dhms])$/
+import { splitPartialDuration } from '../durations'
const MAX_VALUE_FOR_DURATION_UNIT: Record<string, number> = {
d: 30,
@@ -47,12 +46,10 @@ export function HogFlowDuration({
maxValueForUnit?: Record<string, number>
}): JSX.Element {
const inputRef = useRef<HTMLInputElement>(null)
- const parts = value.match(DURATION_REGEX)
- const numberValueString = parts?.[1] ?? ''
- const unit = parts?.[2] ?? 'm'
+ const { amountText, unit } = splitPartialDuration(value)
// Keep undefined (empty field) distinct from a real number so clearing doesn't snap back to a default.
- const parsedNumber = parseFloat(numberValueString)
+ const parsedNumber = parseFloat(amountText)
const numberValue = Number.isFinite(parsedNumber) ? parsedNumber : undefined
// The parent commits config through an async kea listener, so binding the field straight to the derived
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/durations.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/durations.test.ts
new file mode 100644
index 000000000000..2e0cb986c130
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/durations.test.ts
@@ -0,0 +1,45 @@
+import { isDuration, isSignedDuration, parseDuration, splitPartialDuration } from './durations'
+
+describe('durations', () => {
+ // A cleared field emits the unit on its own. That once reached the API as conversion.window and
+ // failed the save, so the storable-value matchers have to keep rejecting it.
+ test.each([
+ ['7d', true],
+ ['12h', true],
+ ['45s', true],
+ ['1.5h', true],
+ ['.5m', true],
+ ['d', false],
+ ['', false],
+ ['5.d', false],
+ ['-5d', false],
+ ['7 d', false],
+ ['7dd', false],
+ ['P30D', false],
+ ['٥d', false],
+ ])('isDuration(%p) is %p', (value, expected) => {
+ expect(isDuration(value)).toBe(expected)
+ })
+
+ test.each([
+ ['-5d', true],
+ ['5d', true],
+ ['-.5m', true],
+ ['-d', false],
+ ['--5d', false],
+ ])('isSignedDuration(%p) is %p', (value, expected) => {
+ expect(isSignedDuration(value)).toBe(expected)
+ })
+
+ it('keeps the amount as written so a round trip does not restyle it', () => {
+ expect(parseDuration('1.50d')).toMatchObject({ amountText: '1.50', amount: 1.5, unit: 'd', negative: false })
+ expect(parseDuration('-7h')).toMatchObject({ amountText: '7', unit: 'h', negative: true })
+ expect(parseDuration('d')).toBeNull()
+ })
+
+ it('splits a field mid-edit, including the cleared amount', () => {
+ expect(splitPartialDuration('d')).toEqual({ amountText: '', unit: 'd' })
+ expect(splitPartialDuration('12h')).toEqual({ amountText: '12', unit: 'h' })
+ expect(splitPartialDuration('nonsense')).toEqual({ amountText: '', unit: 'm' })
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/durations.ts b/products/workflows/frontend/Workflows/hogflows/steps/durations.ts
new file mode 100644
index 000000000000..2680f338e951
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/durations.ts
@@ -0,0 +1,50 @@
+// The one duration grammar the builder validates against. The executor and the API enforce the same
+// one (products/workflows/backend/utils/durations.py), so a value this accepts is a value they accept.
+// The alternation is linear; `\d*\.?\d+` backtracks quadratically on a long run of digits.
+const DURATION_BODY = '(?:[0-9]+(?:\\.[0-9]+)?|\\.[0-9]+)'
+
+export const DURATION_UNITS = ['d', 'h', 'm', 's'] as const
+export type DurationUnit = (typeof DURATION_UNITS)[number]
+
+const DURATION_REGEX = new RegExp(`^${DURATION_BODY}[dhms]$`)
+const SIGNED_DURATION_REGEX = new RegExp(`^(-?)(${DURATION_BODY})([dhms])$`)
+
+// An amount is allowed to be empty here, which no other matcher permits: a field the user has cleared
+// still has to keep its unit rather than snap back to a default. The result is an edit in progress,
+// never a duration to store.
+const PARTIAL_DURATION_REGEX = /^([0-9]*\.?[0-9]*)([dhms])$/
+
+export interface ParsedDuration {
+ amount: number
+ /** The amount exactly as written, so round-tripping a value does not restyle it. */
+ amountText: string
+ unit: DurationUnit
+ negative: boolean
+}
+
+export function isDuration(value: string): boolean {
+ return DURATION_REGEX.test(value)
+}
+
+export function isSignedDuration(value: string): boolean {
+ return SIGNED_DURATION_REGEX.test(value)
+}
+
+export function parseDuration(value: string): ParsedDuration | null {
+ const parts = SIGNED_DURATION_REGEX.exec(value)
+ if (!parts) {
+ return null
+ }
+ return {
+ amount: parseFloat(parts[2]),
+ amountText: parts[2],
+ unit: parts[3] as DurationUnit,
+ negative: parts[1] === '-',
+ }
+}
+
+/** Splits a field the user is still editing. Says nothing about whether the value is storable. */
+export function splitPartialDuration(value: string): { amountText: string; unit: DurationUnit } {
+ const parts = PARTIAL_DURATION_REGEX.exec(value)
+ return { amountText: parts?.[1] ?? '', unit: (parts?.[2] as DurationUnit) ?? 'm' }
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts
index 78d9d4cca497..3b0050207b1a 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts
@@ -2,9 +2,8 @@ import { MakeLogicType, actions, connect, kea, key, listeners, path, props } fro
import { WorkflowLogicProps, workflowLogic } from '../../workflowLogic'
import type { HogFlow, HogFlowAction } from '../types'
+import { isDuration, parseDuration, splitPartialDuration } from './durations'
-const DURATION_REGEX = /^(\d*\.?\d*)([dhms])$/
-const OFFSET_REGEX = /^(-?)(\d*\.?\d+)([dhms])$/
const AUTO_DESCRIPTION_REGEX = /^Wait for \d*\.?\d+ (second|minute|hour|day)s?\.$/
const LEGACY_DEFAULT_DESCRIPTION = 'Wait for a specified duration.'
const UNCONFIGURED_UNTIL_DESCRIPTION = 'Wait until a date on the person or event.'
@@ -84,30 +83,30 @@ export function parseDelayExpression(expression: string): DelayProperty | null {
/** Undefined for direction 'on', so "wait for the date itself" saves no offset at all. */
export function buildDelayOffset({ duration, direction }: DelayOffset): string | undefined {
- if (direction === 'on' || !DURATION_REGEX.test(duration) || !Number.isFinite(parseFloat(duration))) {
+ if (direction === 'on' || !isDuration(duration)) {
return undefined
}
return `${direction === 'before' ? '-' : ''}${duration}`
}
export function parseDelayOffset(offset: string | undefined): DelayOffset {
- const parts = offset?.match(OFFSET_REGEX)
- if (!parts) {
+ const parsed = offset ? parseDuration(offset) : null
+ if (!parsed) {
// A day is the offset almost every reminder uses, so it is the amount to start from once
// someone switches off 'on'.
return { duration: '1d', direction: 'on' }
}
- return { duration: `${parts[2]}${parts[3]}`, direction: parts[1] === '-' ? 'before' : 'after' }
+ return { duration: `${parsed.amountText}${parsed.unit}`, direction: parsed.negative ? 'before' : 'after' }
}
/** "2 days" for '2d'. Null when there is no number to read, e.g. a cleared duration input. */
export function getDurationText(duration: string): string | null {
- const parts = duration.match(DURATION_REGEX)
- const number = parseFloat(parts?.[1] ?? '')
+ const { amountText, unit } = splitPartialDuration(duration)
+ const number = parseFloat(amountText)
if (!Number.isFinite(number)) {
return null
}
- const unitLabel = UNIT_LABELS[parts?.[2] ?? 'm'] ?? 'minute'
+ const unitLabel = UNIT_LABELS[unit] ?? 'minute'
return `${number} ${unitLabel}${number !== 1 ? 's' : ''}`
}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/types.ts b/products/workflows/frontend/Workflows/hogflows/steps/types.ts
index d657744cd80c..80281ad8c82c 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/types.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/types.ts
@@ -5,6 +5,7 @@ import { Optional } from 'lib/utils/types'
import { LogEntry } from 'scenes/hog-functions/logs/logsViewerLogic'
import { HogFlowAction } from '../types'
+import { isDuration, isSignedDuration } from './durations'
export type HogFlowStepNodeProps = NodeProps & {
data: HogFlowAction
@@ -24,7 +25,7 @@ const DURATION_STRING = z.string().superRefine((v, ctx) => {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Please enter a duration' })
return
}
- if (!/^\d*\.?\d+[dhms]$/.test(v)) {
+ if (!isDuration(v)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Duration must be a number followed by s, m, h, or d' })
return
}
@@ -35,7 +36,7 @@ const DURATION_STRING = z.string().superRefine((v, ctx) => {
// A delay offset points either side of the date it offsets, so unlike DURATION_STRING it is signed.
const OFFSET_DURATION_STRING = z.string().superRefine((v, ctx) => {
- if (!/^-?\d*\.?\d+[dhms]$/.test(v)) {
+ if (!isSignedDuration(v)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Offset must be a number followed by s, m, h, or d' })
}
})