import React from 'react' import { type Meta } from '@storybook/react-vite' import { createMonthAgoData } from '../../services/GraphHelperServiceTyped' import { DocsTemplate } from '../../../.storybook' type DataPoint = { date: number revenue?: number visitors?: number conversions?: number } const generateSampleData = (): DataPoint[] => { const data: DataPoint[] = [] for (let i = 90; i >= 0; i--) { const currentDate = new Date() currentDate.setDate(currentDate.getDate() - i) const baseRevenue = 10000 + i * 50 const randomVariance = Math.random() * 2000 - 1000 const weekendBoost = [0, 6].includes(currentDate.getDay()) ? 2000 : 0 data.push({ date: currentDate.getTime(), revenue: baseRevenue + randomVariance + weekendBoost, visitors: Math.round(baseRevenue / 10 + Math.random() * 100), conversions: Math.round((baseRevenue / 10000) * (5 + Math.random() * 2)), }) } return data } export const Example = (args: { data: DataPoint[] keyName: string | string[] weeklyDataPoints: boolean }): React.JSX.Element => { const { data, keyName, weeklyDataPoints } = args const parsedKeyName = typeof keyName === 'string' && keyName.trim().startsWith('[') && keyName.trim().endsWith(']') ? keyName .trim() .slice(1, -1) .split(',') .map((item) => item.trim().replace(/^['"]|['"]$/g, '')) .filter((item) => item.length > 0) : keyName const isValidKey = (key: string) => data.some((item) => key in item && item[key] !== undefined) const validKeys = Array.isArray(parsedKeyName) ? parsedKeyName.filter(isValidKey) : parsedKeyName if ( (Array.isArray(validKeys) && validKeys.length === 0) || (!Array.isArray(validKeys) && !isValidKey(validKeys)) ) { return ( <> Error: No valid data keys provided. > ) } const result = createMonthAgoData(data, validKeys, weeklyDataPoints) || { value: '', } return ( <>
{JSON.stringify(result, null, 2)}
>
)
}
Example.storyName = 'createMonthAgoData'
Example.args = {
data: generateSampleData(),
keyName: 'revenue',
weeklyDataPoints: false,
}
export default {
title: 'Helper Functions/createMonthAgoData',
component: Example,
argTypes: {
data: {
control: 'object',
description: 'The array of data points with date properties',
},
keyName: {
control: 'text',
description: 'Property name(s) to extract values from data points. ',
},
weeklyDataPoints: {
control: 'boolean',
description: 'Whether to use weekly-based calculations for interpolation',
},
},
parameters: {
viewMode: 'docs',
previewTabs: {
canvas: { hidden: true },
},
docs: {
page: () => (
<>
createMonthAgoData is used for historical
comparison in graphs/charts, particularly for "compared to last
month" metrics.
,
The function takes three arguments:
date{' '}
property as timestamp)
date: Timestamp of exactly one month ago
(normalized)
value: The corresponding data value, either
exact or interpolated