: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import clsx from 'clsx'
import DOMPurify from 'dompurify'
import { type ReactNode } from 'react'
import { formatCurrency } from 'lib/utils/currency'
import { percentage } from 'lib/utils/numbers'
import { CurrencyCode } from '~/queries/schema/schema-general'
import { Group } from '~/types'
type AnsiState = {
fgClassName?: string
isBold?: boolean
}
const ANSI_FG_CLASSNAMES: Record<number, string> = {
30: 'text-muted',
31: 'text-red',
32: 'text-green',
33: 'text-yellow',
34: 'text-blue',
35: 'text-purple',
36: 'text-blue',
37: 'text-default',
90: 'text-muted',
91: 'text-red',
92: 'text-green',
93: 'text-yellow',
94: 'text-blue',
95: 'text-purple',
96: 'text-blue',
97: 'text-default',
}
const applyAnsiCodes = (codes: number[], state: AnsiState): AnsiState => {
let nextState: AnsiState = { ...state }
for (const code of codes) {
if (code === 0) {
nextState = {}
continue
}
if (code === 1) {
nextState.isBold = true
continue
}
if (code === 22) {
nextState.isBold = false
continue
}
if (code === 39) {
delete nextState.fgClassName
continue
}
const fgClassName = ANSI_FG_CLASSNAMES[code]
if (fgClassName) {
nextState.fgClassName = fgClassName
}
}
return nextState
}
export const renderAnsiText = (value: string): ReactNode => {
if (!value.includes('\u001b[')) {
return value
}
const segments: ReactNode[] = []
const ansiRegex = /\u001b\[([0-9;]*)m/g
let lastIndex = 0
let match = ansiRegex.exec(value)
let state: AnsiState = {}
const pushSegment = (text: string): void => {
if (!text) {
return
}
const className = clsx(state.fgClassName, state.isBold && 'font-semibold')
if (className) {
segments.push(
<span key={`${segments.length}-${lastIndex}`} className={className}>
{text}
</span>
)
} else {
segments.push(text)
}
}
while (match) {
pushSegment(value.slice(lastIndex, match.index))
const codes = match[1]
? match[1]
.split(';')
.map((code) => Number.parseInt(code, 10))
.filter((code) => Number.isFinite(code))
: [0]
state = applyAnsiCodes(codes, state)
lastIndex = match.index + match[0].length
match = ansiRegex.exec(value)
}
pushSegment(value.slice(lastIndex))
return segments
}
export const sanitizeSvgContent = (svg: string): string => {
return DOMPurify.sanitize(svg, { USE_PROFILES: { svg: true, svgFilters: true } })
}
export const buildMediaSource = (media: { mimeType: string; data: string }): string | null => {
if (media.mimeType === 'image/png') {
return `data:image/png;base64,${media.data}`
}
if (media.mimeType === 'image/jpeg') {
return `data:image/jpeg;base64,${media.data}`
}
if (media.mimeType === 'image/svg+xml') {
return `data:image/svg+xml;utf8,${encodeURIComponent(sanitizeSvgContent(media.data))}`
}
return null
}
// nodeId/__-prefixed are internal
// null/undefined would otherwise serialize as the literal strings "null"/"undefined".
export function shouldOmitFromClipboardHTML(key: string, value: unknown): boolean {
return key === 'nodeId' || key.startsWith('__') || value == null
}
// Builds the HTML that the explicit "Copy" action writes to the clipboard.
// Each attribute is JSON.stringified to mirror the per-attribute renderHTML in
// `createPostHogWidgetNode`, so paste round-trips through `JSON.parse` regardless of which
// copy path produced the HTML. Building via the DOM lets the browser handle attribute escaping.
export function buildNotebookNodeClipboardHTML(nodeType: string, attrs: Record<string, any>): string {
const element = document.createElement(nodeType)
element.setAttribute('data-pm-slice', '0 0 []')
for (const [key, value] of Object.entries(attrs)) {
if (shouldOmitFromClipboardHTML(key, value)) {
continue
}
element.setAttribute(key, JSON.stringify(value))
}
return element.outerHTML
}
export const getLogicKey = ({
tabId,
personId,
groupKey,
}: {
tabId: string
personId?: string
groupKey?: string
}): string => {
const entityKey = personId || groupKey
return `${tabId}-${entityKey}`
}
export function sortProperties(entries: [string, any][], pinnedProperties: string[]): [string, any][] {
const pinnedSet = new Set(pinnedProperties)
const pinnedIndexMap = new Map(pinnedProperties.map((key, index) => [key, index]))
return entries.sort(([aKey], [bKey]) => {
const aIsPinned = pinnedSet.has(aKey)
const bIsPinned = pinnedSet.has(bKey)
if (aIsPinned && !bIsPinned) {
return -1
}
if (!aIsPinned && bIsPinned) {
return 1
}
// If both are pinned or both aren't, maintain their relative order
// based on the pinnedProperties array order for pinned items
if (aIsPinned && bIsPinned) {
return pinnedIndexMap.get(aKey)! - pinnedIndexMap.get(bKey)!
}
return aKey.localeCompare(bKey)
})
}
// Group revenue-related utilities
/**
* Represents MRR data with forecasted trend
*/
export interface MRRData {
mrr: number
forecastedMrr: number | null
percentageDiff: number | null
tooltipText: string | null
trendDirection: 'up' | 'down' | 'flat' | null
}
/**
* Calculates MRR data with trend analysis and tooltip text
* @param group Group data containing MRR information
* @param baseCurrency Currency code for formatting
* @returns MRRData object or null if no valid MRR
*/
export function calculateMRRData(group: Group, baseCurrency: CurrencyCode): MRRData | null {
const mrrValue = group.group_properties.mrr
const mrr: number | null = typeof mrrValue === 'number' && !isNaN(mrrValue) ? mrrValue : null
const forecastedMrrValue = group.group_properties.forecasted_mrr
const forecastedMrr: number | null =
typeof forecastedMrrValue === 'number' && !isNaN(forecastedMrrValue) ? forecastedMrrValue : null
if (mrr === null) {
return null
}
const percentageDiff = forecastedMrr === null || mrr === 0 ? null : (forecastedMrr - mrr) / mrr
let tooltipText: string | null = null
let trendDirection: 'up' | 'down' | 'flat' | null = null
if (percentageDiff !== null && forecastedMrr !== null) {
if (percentageDiff > 0) {
tooltipText = `${percentage(percentageDiff)} MRR growth forecasted to ${formatCurrency(forecastedMrr, baseCurrency)}`
trendDirection = 'up'
} else if (percentageDiff < 0) {
tooltipText = `${percentage(-percentageDiff)} MRR decrease forecasted to ${formatCurrency(forecastedMrr, baseCurrency)}`
trendDirection = 'down'
} else {
tooltipText = `No MRR change forecasted, flat at ${formatCurrency(mrr, baseCurrency)}`
trendDirection = 'flat'
}
}
return {
mrr,
forecastedMrr,
percentageDiff,
tooltipText,
trendDirection,
}
}
/**
* Gets paid products with formatted names from group MRR data
* @param group Group data containing MRR per product
* @returns Array of formatted product names with positive MRR
*/
export function getPaidProducts(group: Group): string[] {
const mrrPerProduct: Record<string, number> = group.group_properties.mrr_per_product || {}
return Object.entries(mrrPerProduct)
.filter(([, mrr]) => typeof mrr === 'number' && mrr > 0)
.map(([product]) =>
product
.replaceAll('_', ' ')
.split(' ')
.map((word, index) => (index === 0 ? word.charAt(0).toUpperCase() + word.slice(1) : word))
.join(' ')
)
}
/**
* Extracts customer lifetime value from group properties
* @param group Group data containing customer lifetime value
* @returns Lifetime value as number or null if invalid/missing
*/
export function getLifetimeValue(group: Group): number | null {
const value = group.group_properties.customer_lifetime_value
return typeof value === 'number' && !isNaN(value) ? value : null
}