Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

feat: ability to hide series when using formula

Carl-Gerhard Lindesvärdd8f9474c8c5b
diff --git a/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx b/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx
index eaef982c9..e4d5c673e 100644
--- a/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx
+++ b/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx
@@ -32,6 +32,7 @@ interface PropertiesComboboxProps {
description: string;
}) => void;
exclude?: string[];
+ include?: string[];
mode?: 'events' | 'profile';
}
@@ -67,6 +68,7 @@ export function PropertiesCombobox({
onSelect,
mode,
exclude = [],
+ include = [],
}: PropertiesComboboxProps) {
const { projectId } = useAppParams();
const trpc = useTRPC();
@@ -90,15 +92,19 @@ export function PropertiesCombobox({
}
}, [open, mode]);
+ const matchesPropertyPattern = (property: string, pattern: string) => {
+ if (pattern.endsWith('*')) {
+ return property.startsWith(pattern.slice(0, -1));
+ }
+ return property === pattern;
+ };
+
const shouldShowProperty = (property: string) => {
- return !exclude.find((ex) => {
- if (ex.endsWith('*')) {
- return property.startsWith(ex.slice(0, -1));
- }
- return property === ex;
- });
+ return !exclude.some((pattern) => matchesPropertyPattern(property, pattern));
};
+ const allProperties = Array.from(new Set([...properties, ...include]));
+
// Fixed group properties: name, type, plus dynamic property keys
const groupActions = [
{ value: 'group.name', label: 'name', description: 'group' },
@@ -110,7 +116,7 @@ export function PropertiesCombobox({
})),
].filter((a) => shouldShowProperty(a.value));
- const profileActions = properties
+ const profileActions = allProperties
.filter(
(property) =>
property.startsWith('profile') && shouldShowProperty(property)
@@ -120,7 +126,7 @@ export function PropertiesCombobox({
label: property.split('.').pop() ?? property,
description: property.split('.').slice(0, -1).join('.'),
}));
- const eventActions = properties
+ const eventActions = allProperties
.filter(
(property) =>
!property.startsWith('profile') && shouldShowProperty(property)
diff --git a/apps/start/src/components/report/sidebar/ReportSeries.tsx b/apps/start/src/components/report/sidebar/ReportSeries.tsx
index e7bd29555..6f29306a4 100644
--- a/apps/start/src/components/report/sidebar/ReportSeries.tsx
+++ b/apps/start/src/components/report/sidebar/ReportSeries.tsx
@@ -1,5 +1,6 @@
import { ColorSquare } from '@/components/color-square';
import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
import { ComboboxEvents } from '@/components/ui/combobox-events';
import { Input } from '@/components/ui/input';
import { InputEnter } from '@/components/ui/input-enter';
@@ -44,6 +45,35 @@ import {
type ReportSeriesItemProps,
} from './ReportSeriesItem';
+// Matches a single uppercase letter that isn't part of a larger identifier,
+// which is how mathjs treats series references in formulas (A, B, C, ...).
+const ALPHA_REFERENCE_REGEX = /(?<![a-zA-Z0-9_])[A-Z](?![a-zA-Z0-9_])/g;
+
+function getReferencedAlphaIds(
+ formula: string,
+ formulaIndex: number,
+): string[] {
+ if (!formula) {
+ return [];
+ }
+ const matches = formula.match(ALPHA_REFERENCE_REGEX) ?? [];
+ const seen = new Set<string>();
+ const result: string[] = [];
+ for (const match of matches) {
+ if (seen.has(match)) {
+ continue;
+ }
+ const idx = alphabetIds.indexOf(match as (typeof alphabetIds)[number]);
+ // Only include references to series that exist before this formula
+ if (idx === -1 || idx >= formulaIndex) {
+ continue;
+ }
+ seen.add(match);
+ result.push(match);
+ }
+ return result;
+}
+
function SortableReportSeriesItem({
event,
index,
@@ -218,6 +248,52 @@ export function ReportSeries() {
}}
/>
)}
+ {(() => {
+ const referencedAlphaIds = getReferencedAlphaIds(
+ event.formula,
+ index,
+ );
+ if (referencedAlphaIds.length === 0) {
+ return null;
+ }
+ const hideSeries = event.hideSeries ?? [];
+ return (
+ <div className="flex flex-wrap gap-x-3 gap-y-1.5 pt-1">
+ {referencedAlphaIds.map((alphaId) => {
+ const isHidden = hideSeries.includes(alphaId);
+ return (
+ <label
+ key={alphaId}
+ className="flex items-center gap-1.5 text-xs font-medium select-none cursor-pointer"
+ >
+ <Checkbox
+ checked={isHidden}
+ onCheckedChange={(checked) => {
+ const next = checked
+ ? [
+ ...hideSeries.filter(
+ (id) => id !== alphaId,
+ ),
+ alphaId,
+ ]
+ : hideSeries.filter(
+ (id) => id !== alphaId,
+ );
+ dispatch(
+ changeEvent({
+ ...event,
+ hideSeries: next,
+ }),
+ );
+ }}
+ />
+ Hide series {alphaId} from chart
+ </label>
+ );
+ })}
+ </div>
+ );
+ })()}
</div>
<ReportEventMore onClick={handleMore(event)} />
</>
diff --git a/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx b/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx
index e6f70aa22..18e038158 100644
--- a/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx
+++ b/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx
@@ -101,6 +101,7 @@ export function ReportSeriesItem({
{showSegment && chartEvent.segment.startsWith('property_') && (
<PropertiesCombobox
+ include={chartEvent.name === 'session_end' ? ['duration'] : []}
event={chartEvent}
onSelect={(item) => {
dispatch(
diff --git a/packages/db/src/engine/format.ts b/packages/db/src/engine/format.ts
index b376d0b9a..d569b06ab 100644
--- a/packages/db/src/engine/format.ts
+++ b/packages/db/src/engine/format.ts
@@ -23,12 +23,36 @@ export function format(
displayName?: string;
formula?: string;
name?: string;
+ hideSeries?: string[];
}>,
includeAlphaIds: boolean,
previousSeries: ConcreteSeries[] | null = null,
limit: number | undefined = undefined
): FinalChart {
- const series = concreteSeries.map((cs) => {
+ // Collect definition indices that should be hidden from the chart.
+ // A formula can opt to hide any of the series it references (by alpha ID)
+ // so the chart only shows the formula result without the input series.
+ const hiddenDefinitionIndices = new Set<number>();
+ for (const definition of definitions) {
+ if (definition.type !== 'formula' || !definition.hideSeries?.length) {
+ continue;
+ }
+ for (const alphaId of definition.hideSeries) {
+ const index = alphabetIds.indexOf(alphaId as (typeof alphabetIds)[number]);
+ if (index >= 0) {
+ hiddenDefinitionIndices.add(index);
+ }
+ }
+ }
+
+ const visibleConcreteSeries =
+ hiddenDefinitionIndices.size > 0
+ ? concreteSeries.filter(
+ (cs) => !hiddenDefinitionIndices.has(cs.definitionIndex)
+ )
+ : concreteSeries;
+
+ const series = visibleConcreteSeries.map((cs) => {
// Find definition for this series
const definition = definitions[cs.definitionIndex];
const alphaId = includeAlphaIds
@@ -128,8 +152,10 @@ export function format(
// Sort series by sum (biggest first)
series.sort((a, b) => b.metrics.sum - a.metrics.sum);
- // Calculate global metrics
- const allValues = concreteSeries.flatMap((cs) => cs.data.map((d) => d.count));
+ // Calculate global metrics (excluding hidden series)
+ const allValues = visibleConcreteSeries.flatMap((cs) =>
+ cs.data.map((d) => d.count)
+ );
const globalMetrics = {
sum: sum(allValues),
average: round(average(allValues), 2),
diff --git a/packages/validation/src/index.ts b/packages/validation/src/index.ts
index 0b48c6bc6..67a41956b 100644
--- a/packages/validation/src/index.ts
+++ b/packages/validation/src/index.ts
@@ -69,6 +69,12 @@ export const zChartFormula = z.object({
.string()
.optional()
.describe('A user-friendly name for display purposes'),
+ hideSeries: z
+ .array(z.string())
+ .optional()
+ .describe(
+ 'Alpha IDs (e.g. ["A", "B"]) of series referenced by this formula that should be hidden from the chart while still being used in the formula computation',
+ ),
});
// Event with type field for discriminated union