import pricingAddOn from '~/data/PricingAddOnTable.json' import { Plus, Trash2 } from 'lucide-react' import { AnimatePresence, motion, MotionConfig, useReducedMotion } from 'motion/react' import { useCallback, useEffect, useState, type PointerEvent, type ReactNode } from 'react' import { plans as allPlans } from 'shared-data/plans' import { Button, cn, Slider, ToggleGroup, ToggleGroupItem } from 'ui' import { ComputeBadge } from 'ui-patterns/ComputeBadge' import { InfoTooltip } from 'ui-patterns/info-tooltip' const STANDALONE_PLANS = allPlans .filter((plan) => plan.planId === 'pro' || plan.planId === 'team') .map((plan) => ({ name: plan.name, price: plan.priceMonthly as number })) const TICKS_PER_STEP = 4 const findInstanceValueByColumn = (instance: any, column: string) => instance.columns?.find((col: any) => col.key === column)?.value const formatUsd = (amount: number) => `$${amount.toLocaleString('en-US')}` const parsePrice = (price: string) => { const n = parseInt(price?.toString().replace('$', '').replace(',', ''), 10) return Number.isNaN(n) ? 0 : n } interface ComputePricingCalculatorProps { activePlan?: { name: string price: number } disableInteractivity?: boolean } const ComputePricingCalculator = ({ activePlan, disableInteractivity, }: ComputePricingCalculatorProps) => { // When activePlan is not provided, manage plan selection internally const [internalPlan, setInternalPlan] = useState(STANDALONE_PLANS[0]) const effectivePlan = activePlan ?? internalPlan const isStandalone = activePlan === undefined // Filter out rows with no specific pricing const computeInstances = pricingAddOn.database.rows.filter((row) => row.columns.some((it) => it.key === 'pricing' && it.value !== 'Contact Us') ) const priceSteps = computeInstances.map((instance) => parsePrice(findInstanceValueByColumn(instance, 'pricing')) ) // Base discount credits that come with every paid plan const COMPUTE_CREDITS = 10 const [activeInstances, setActiveInstances] = useState([{ ...computeInstances[0], position: 0 }]) // Final calculated price: plan cost + compute aggregate - compute credits const [activePrice, setActivePrice] = useState( effectivePlan.price + priceSteps[0] - COMPUTE_CREDITS ) const handleUpdateInstance = (position: number, value: number[]) => { const newArray = activeInstances.map((activeInstance) => { // only update the instance corresponding to the correct slider if (activeInstance.position === position) { return { ...computeInstances[value[0] - 1], position } } else { return activeInstance } }) setActiveInstances(newArray) } const calculateComputeAggregate = (price: number) => { return activeInstances.reduce( (acc, activeInstance: any) => acc + parsePrice(findInstanceValueByColumn(activeInstance, 'pricing')), price ) } useEffect(() => { const computeAggregate = activeInstances.reduce( (acc, activeInstance: any) => acc + parsePrice(findInstanceValueByColumn(activeInstance, 'pricing')), 0 ) setActivePrice(Math.max(0, computeAggregate + effectivePlan.price - COMPUTE_CREDITS)) }, [activeInstances, effectivePlan]) const removeInstance = (position: number) => { const newArray = activeInstances .filter((activeInstance) => activeInstance.position !== position) .map((instance, index) => ({ ...instance, position: index })) setActiveInstances(newArray) } const [stepPreview, setStepPreview] = useState<{ position: number; step: number } | null>(null) const handleStepPreview = (position: number) => (step: number | null) => setStepPreview(step === null ? null : { position, step }) const getDisplayedInstance = (activeInstance: any) => stepPreview !== null && stepPreview.position === activeInstance.position ? computeInstances[stepPreview.step] : activeInstance const findSliderComputeValue = (activeInstance: any) => { // find index of compute based on active compute name const selectedCompute = computeInstances .map((compute) => findInstanceValueByColumn(compute, 'plan')) .indexOf(findInstanceValueByColumn(activeInstance, 'plan')) return [selectedCompute + 1] } return (
{isStandalone && ( { const selected = STANDALONE_PLANS.find((p) => p.name === value) if (selected) setInternalPlan(selected) }} className="grid grid-cols-2 gap-1 w-full bg-surface-200 rounded-md" > {STANDALONE_PLANS.map((plan) => ( {plan.name} ))} )}

Monthly estimate:

Plan subscription {formatUsd(effectivePlan.price)}
Total Compute $
Compute Credits −{formatUsd(COMPUTE_CREDITS)}
Total This estimate only includes Plan and Compute add-on monthly costs. Other resources might incur additional costs in the final invoice. $
{activeInstances.map((activeInstance, index) => (

Project {activeInstance.position + 1}

{findInstanceValueByColumn(getDisplayedInstance(activeInstance), 'plan')}
$
handleUpdateInstance(activeInstance.position, [Math.max(1, value[0])]) } value={findSliderComputeValue(activeInstance)} min={0} key={`${index}-${activeInstance.position}`} max={priceSteps.length} step={1} className={cn( 'w-full min-h-12 cursor-pointer', "**:data-[slot='slider-track']:bg-transparent **:data-[slot='slider-range']:bg-transparent", "**:data-[slot='slider-thumb']:slider-split-thumb", "**:data-[slot='slider-thumb']:relative **:data-[slot='slider-thumb']:before:absolute **:data-[slot='slider-thumb']:before:-inset-y-2 **:data-[slot='slider-thumb']:before:-inset-x-3" )} />
{findInstanceValueByColumn(getDisplayedInstance(activeInstance), 'memory')} RAM / {findInstanceValueByColumn(getDisplayedInstance(activeInstance), 'cpu')} / Connections: Direct{' '} {findInstanceValueByColumn( getDisplayedInstance(activeInstance), 'directConnections' )} , Pooler{' '} {findInstanceValueByColumn( getDisplayedInstance(activeInstance), 'poolerConnections' )}
{activeInstances.length > 1 && ( )}
))}
) } const SliderSteps = ({ stepCount, activeStep, onStepPreview, children, }: { stepCount: number activeStep: number onStepPreview: (step: number | null) => void children: ReactNode }) => { const [hoveredTick, setHoveredTick] = useState(null) const [isPointerFocus, setIsPointerFocus] = useState(false) // the track starts one step before the first size, so the slider reads as a track at micro const tickCount = stepCount * TICKS_PER_STEP + 1 const hoveredStep = hoveredTick === null ? null : Math.round(hoveredTick / TICKS_PER_STEP) - 1 const previewStep = hoveredStep === activeStep || hoveredStep === -1 ? null : hoveredStep const [fillChange, setFillChange] = useState({ from: activeStep, to: activeStep }) if (fillChange.to !== activeStep) { setFillChange({ from: fillChange.to, to: activeStep }) } const handlePointerMove = (event: PointerEvent) => { if (event.pointerType !== 'mouse') return const rect = event.currentTarget.getBoundingClientRect() const ratio = Math.min(Math.max((event.clientX - rect.left) / rect.width, 0), 1) const tick = Math.round(ratio * (tickCount - 1)) const step = Math.round(tick / TICKS_PER_STEP) - 1 setHoveredTick(tick) onStepPreview(step === activeStep || step === -1 ? null : step) // a pointer move ends the fill delays, so hover changes stay instant if (fillChange.from !== fillChange.to) setFillChange({ from: activeStep, to: activeStep }) } const handlePointerLeave = () => { setHoveredTick(null) onStepPreview(null) } const handlePointerDown = () => setIsPointerFocus(true) const handleBlur = () => setIsPointerFocus(false) const handleKeyDown = () => { setIsPointerFocus(false) setHoveredTick(null) onStepPreview(null) } return (
{children}
) } const RollingValue = ({ value, trend = 1, delay = 0, children, }: { value: string trend?: number delay?: number children: ReactNode }) => { const [width, setWidth] = useState() const measureRef = useCallback((node: HTMLSpanElement | null) => { if (node) setWidth(node.offsetWidth) }, []) return ( ({ y: `${rollTrend * 100}%`, opacity: 0 }), center: { y: 0, opacity: 1 }, exit: (rollTrend: number) => ({ y: `${rollTrend * -100}%`, opacity: 0 }), }} initial="enter" animate="center" exit="exit" transition={{ type: 'spring', duration: 0.3, bounce: 0, delay }} className="inline-flex w-max" > {children} ) } const RollingNumber = ({ value }: { value: number }) => { const shouldReduceMotion = useReducedMotion() const [roll, setRoll] = useState({ value, trend: 1 }) if (roll.value !== value) setRoll({ value, trend: value < roll.value ? -1 : 1 }) const text = value.toLocaleString('en-US') return ( <> {text} ) } export default ComputePricingCalculator