@10x-media/analytics 1.0.0-beta.8 → 1.0.0-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +70 -0
- package/LICENSE +21 -21
- package/README.md +3 -3
- package/dist/adapters/ga4/eventName.d.ts +15 -0
- package/dist/adapters/ga4/eventName.js +19 -0
- package/dist/adapters/ga4/eventName.js.map +1 -0
- package/dist/adapters/ga4/ga4.d.ts +5 -0
- package/dist/adapters/ga4/ga4.js +178 -70
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/ga4/measurementId.js +15 -0
- package/dist/adapters/ga4/measurementId.js.map +1 -0
- package/dist/adapters/goalRead.js +126 -0
- package/dist/adapters/goalRead.js.map +1 -0
- package/dist/adapters/plausible/plausible.d.ts +15 -0
- package/dist/adapters/plausible/plausible.js +110 -42
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/posthog.js +47 -25
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.d.ts +8 -0
- package/dist/adapters/umami/umami.js +237 -28
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/charts/BarList.js +8 -2
- package/dist/charts/BarList.js.map +1 -1
- package/dist/core/cacheKey.js +11 -1
- package/dist/core/cacheKey.js.map +1 -1
- package/dist/core/capabilities.js +7 -2
- package/dist/core/capabilities.js.map +1 -1
- package/dist/core/capture.d.ts +1 -1
- package/dist/core/contract.d.ts +32 -2
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +8 -2
- package/dist/core/options.js +4 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/serverEvent.d.ts +4 -2
- package/dist/core/serverEvent.js.map +1 -1
- package/dist/exports/adapters/ga4.d.ts +2 -1
- package/dist/exports/adapters/ga4.js +2 -1
- package/dist/exports/client.d.ts +5 -2
- package/dist/exports/client.js +4 -1
- package/dist/exports/rsc.d.ts +2 -1
- package/dist/exports/tracker.d.ts +3 -2
- package/dist/exports/tracker.js +2 -1
- package/dist/exports/types.d.ts +2 -1
- package/dist/exports/types.js +2 -1
- package/dist/fields/config/FilterDimensionSelectField.d.ts +14 -0
- package/dist/fields/config/FilterDimensionSelectField.js +77 -0
- package/dist/fields/config/FilterDimensionSelectField.js.map +1 -0
- package/dist/fields/config/FilterOperatorSelectField.d.ts +14 -0
- package/dist/fields/config/FilterOperatorSelectField.js +75 -0
- package/dist/fields/config/FilterOperatorSelectField.js.map +1 -0
- package/dist/fields/config/MetricSelectField.js +1 -1
- package/dist/fields/config/SourceSelectField.js +1 -1
- package/dist/fields/config/sourcesState.js +19 -3
- package/dist/fields/config/sourcesState.js.map +1 -1
- package/dist/fields/config/useAnalyticsSources.d.ts +8 -3
- package/dist/fields/config/useAnalyticsSources.js +9 -6
- package/dist/fields/config/useAnalyticsSources.js.map +1 -1
- package/dist/fields/config/useFilterCapabilities.d.ts +28 -0
- package/dist/fields/config/useFilterCapabilities.js +52 -0
- package/dist/fields/config/useFilterCapabilities.js.map +1 -0
- package/dist/fields/readForDocument.js +16 -4
- package/dist/fields/readForDocument.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/native/collections/events.js +36 -0
- package/dist/native/collections/events.js.map +1 -1
- package/dist/native/eventScan.js +25 -0
- package/dist/native/eventScan.js.map +1 -0
- package/dist/native/ingest/browser.js +47 -0
- package/dist/native/ingest/browser.js.map +1 -0
- package/dist/native/ingest/flushBatch.js +26 -26
- package/dist/native/ingest/flushBatch.js.map +1 -1
- package/dist/native/ingest/language.js +14 -0
- package/dist/native/ingest/language.js.map +1 -0
- package/dist/native/ingest/normalizeEvent.d.ts +6 -0
- package/dist/native/ingest/normalizeEvent.js +32 -5
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/ingest/referrer.js +48 -0
- package/dist/native/ingest/referrer.js.map +1 -0
- package/dist/native/ingest/serverTrack.js +1 -0
- package/dist/native/ingest/serverTrack.js.map +1 -1
- package/dist/native/ingest/source.d.ts +7 -0
- package/dist/native/ingest/source.js +139 -14
- package/dist/native/ingest/source.js.map +1 -1
- package/dist/native/ingest/utm.js +33 -0
- package/dist/native/ingest/utm.js.map +1 -0
- package/dist/native/nativeAdapter.js +32 -26
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/query/eventAgg.js +14 -1
- package/dist/native/query/eventAgg.js.map +1 -1
- package/dist/native/rollups/bucketKey.js +15 -0
- package/dist/native/rollups/bucketKey.js.map +1 -0
- package/dist/native/rollups/bumpRollups.js +116 -0
- package/dist/native/rollups/bumpRollups.js.map +1 -0
- package/dist/native/rollups/deltas.js +30 -15
- package/dist/native/rollups/deltas.js.map +1 -1
- package/dist/native/rollups/insertManyIfNew.js +93 -0
- package/dist/native/rollups/insertManyIfNew.js.map +1 -0
- package/dist/next/captureRewrites.d.ts +3 -2
- package/dist/next/captureRewrites.js +3 -2
- package/dist/next/captureRewrites.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +26 -7
- package/dist/plugin/documentEndpoint.js.map +1 -1
- package/dist/plugin/goalHint.d.ts +1 -0
- package/dist/plugin/goalHint.js +24 -0
- package/dist/plugin/goalHint.js.map +1 -0
- package/dist/plugin/queryEndpoint.js +19 -12
- package/dist/plugin/queryEndpoint.js.map +1 -1
- package/dist/plugin/realtimeEndpoint.js +40 -15
- package/dist/plugin/realtimeEndpoint.js.map +1 -1
- package/dist/plugin/responses.js +17 -0
- package/dist/plugin/responses.js.map +1 -0
- package/dist/plugin/sourcesEndpoint.js +10 -3
- package/dist/plugin/sourcesEndpoint.js.map +1 -1
- package/dist/providers/collection.js +14 -4
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.js +4 -2
- package/dist/providers/factory.js.map +1 -1
- package/dist/query/response.d.ts +4 -1
- package/dist/query/response.js +11 -0
- package/dist/query/response.js.map +1 -0
- package/dist/surfacing/engine.js +1 -1
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/testing/memoryAdapter.js +0 -1
- package/dist/testing/memoryAdapter.js.map +1 -1
- package/dist/tracker/createTracker.js +13 -1
- package/dist/tracker/createTracker.js.map +1 -1
- package/dist/tracker/sinks/ga4.d.ts +21 -0
- package/dist/tracker/sinks/ga4.js +26 -0
- package/dist/tracker/sinks/ga4.js.map +1 -0
- package/dist/tracker/types.d.ts +5 -0
- package/dist/translations/ar.js +30 -1
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +30 -1
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +30 -1
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +30 -1
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +30 -1
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +30 -1
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +29 -0
- package/dist/translations/keys.js +30 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +30 -1
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/metricKeys.js +7 -1
- package/dist/translations/metricKeys.js.map +1 -1
- package/dist/translations/pt.js +30 -1
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +30 -1
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/server.js.map +1 -1
- package/dist/translations/uk.js +30 -1
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +30 -1
- package/dist/translations/zh.js.map +1 -1
- package/dist/view/AnalyticsViewClient.js +13 -2
- package/dist/view/AnalyticsViewClient.js.map +1 -1
- package/dist/view/gating.js +40 -3
- package/dist/view/gating.js.map +1 -1
- package/dist/view/labels.js +21 -1
- package/dist/view/labels.js.map +1 -1
- package/dist/view/sections/Breakdowns.js +78 -38
- package/dist/view/sections/Breakdowns.js.map +1 -1
- package/dist/view/sections/FilterChips.js +8 -3
- package/dist/view/sections/FilterChips.js.map +1 -1
- package/dist/view/sections/GoalsPanel.js +2 -1
- package/dist/view/sections/GoalsPanel.js.map +1 -1
- package/dist/view/sections/RealtimeStrip.js +4 -1
- package/dist/view/sections/RealtimeStrip.js.map +1 -1
- package/dist/view/sections/Toolbar.js +10 -3
- package/dist/view/sections/Toolbar.js.map +1 -1
- package/dist/view/sections/Trend.js +8 -2
- package/dist/view/sections/Trend.js.map +1 -1
- package/dist/view/state.js +7 -2
- package/dist/view/state.js.map +1 -1
- package/dist/view/useViewQueries.js +6 -3
- package/dist/view/useViewQueries.js.map +1 -1
- package/dist/widgets/AnalyticsBreakdownWidget.js +59 -10
- package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
- package/dist/widgets/AnalyticsGoalsWidget.js +10 -2
- package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -1
- package/dist/widgets/AnalyticsMetricWidget.js +30 -3
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +3 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
- package/dist/widgets/AnalyticsTrendWidget.js +30 -3
- package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
- package/dist/widgets/RealtimeCounter.d.ts +4 -0
- package/dist/widgets/RealtimeCounter.js +10 -1
- package/dist/widgets/RealtimeCounter.js.map +1 -1
- package/dist/widgets/breakdownTypes.js.map +1 -1
- package/dist/widgets/comparison.js +15 -1
- package/dist/widgets/comparison.js.map +1 -1
- package/dist/widgets/defaults.d.ts +6 -2
- package/dist/widgets/defaults.js +72 -25
- package/dist/widgets/defaults.js.map +1 -1
- package/dist/widgets/filterCaption.js +27 -0
- package/dist/widgets/filterCaption.js.map +1 -0
- package/dist/widgets/filterField.d.ts +19 -0
- package/dist/widgets/filterField.js +75 -0
- package/dist/widgets/filterField.js.map +1 -0
- package/dist/widgets/prepareWidgetRead.d.ts +7 -0
- package/dist/widgets/prepareWidgetRead.js +74 -0
- package/dist/widgets/prepareWidgetRead.js.map +1 -0
- package/dist/widgets/readForWidget.d.ts +12 -2
- package/dist/widgets/readForWidget.js +34 -49
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.d.ts +17 -1
- package/dist/widgets/readForWidgetBreakdown.js +29 -42
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetGoals.d.ts +11 -1
- package/dist/widgets/readForWidgetGoals.js +44 -30
- package/dist/widgets/readForWidgetGoals.js.map +1 -1
- package/dist/widgets/readForWidgetRealtime.d.ts +8 -0
- package/dist/widgets/readForWidgetRealtime.js +21 -20
- package/dist/widgets/readForWidgetRealtime.js.map +1 -1
- package/dist/widgets/readForWidgetSeries.d.ts +11 -1
- package/dist/widgets/readForWidgetSeries.js +38 -49
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/readMeta.js +18 -0
- package/dist/widgets/readMeta.js.map +1 -0
- package/dist/widgets/registerWidgets.js +5 -2
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/dist/widgets/types.d.ts +15 -0
- package/dist/widgets/types.js.map +1 -1
- package/dist/widgets/viewLink.js +5 -2
- package/dist/widgets/viewLink.js.map +1 -1
- package/package.json +5 -5
- package/dist/native/rollups/applyDistinctDeltas.js +0 -9
- package/dist/native/rollups/applyDistinctDeltas.js.map +0 -1
- package/dist/native/rollups/bumpRollup.js +0 -73
- package/dist/native/rollups/bumpRollup.js.map +0 -1
- package/dist/native/rollups/insertIfNew.js +0 -53
- package/dist/native/rollups/insertIfNew.js.map +0 -1
package/dist/view/state.js
CHANGED
|
@@ -119,6 +119,7 @@ const parseViewState = (search, defaults) => {
|
|
|
119
119
|
const metric = read(search, "metric");
|
|
120
120
|
const granularity = read(search, "granularity");
|
|
121
121
|
const tab = read(search, "tab");
|
|
122
|
+
const dim = read(search, "dim");
|
|
122
123
|
const source = read(search, "source");
|
|
123
124
|
const limit = Number(read(search, "limit"));
|
|
124
125
|
const compare = read(search, "compare");
|
|
@@ -130,6 +131,7 @@ const parseViewState = (search, defaults) => {
|
|
|
130
131
|
metric: metric !== null && KNOWN_METRICS.has(metric) ? metric : defaults.metric,
|
|
131
132
|
...granularity !== null && KNOWN_GRANULARITIES.has(granularity) ? { granularity } : {},
|
|
132
133
|
tab: tab !== null && BREAKDOWN_TABS.includes(tab) ? tab : DEFAULT_VIEW_TAB,
|
|
134
|
+
...dim !== null && KNOWN_DIMENSIONS.has(dim) ? { dim } : {},
|
|
133
135
|
filters: parseFilters(search),
|
|
134
136
|
limit: VIEW_LIMITS.includes(limit) ? limit : 10,
|
|
135
137
|
...order === void 0 ? {} : { order }
|
|
@@ -151,6 +153,7 @@ const serializeViewState = (state, defaults) => {
|
|
|
151
153
|
if (state.metric !== defaults.metric) params.set("metric", state.metric);
|
|
152
154
|
if (state.granularity !== void 0) params.set("granularity", state.granularity);
|
|
153
155
|
if (state.tab !== "pages") params.set("tab", state.tab);
|
|
156
|
+
if (state.dim !== void 0) params.set("dim", state.dim);
|
|
154
157
|
if (state.filters.length > 0) params.set("filters", JSON.stringify(state.filters));
|
|
155
158
|
if (state.limit !== 10) params.set("limit", String(state.limit));
|
|
156
159
|
if (state.order !== void 0) params.set("order", `${state.order.metric}:${state.order.direction}`);
|
|
@@ -158,18 +161,19 @@ const serializeViewState = (state, defaults) => {
|
|
|
158
161
|
};
|
|
159
162
|
/**
|
|
160
163
|
* The nearest state the selected source can actually serve. The URL outlives a source
|
|
161
|
-
* switch, so a metric, tab, filter, comparison, bucket or sort the new source lacks is
|
|
164
|
+
* switch, so a metric, tab, grouping, filter, comparison, bucket or sort the new source lacks is
|
|
162
165
|
* replaced or dropped here rather than sent to the endpoint to be rejected. Returns the
|
|
163
166
|
* same object when the gate forbids nothing, so a render can compare by identity.
|
|
164
167
|
*/
|
|
165
168
|
const coerceState = (state, gate) => {
|
|
166
169
|
const metric = gate.metrics.includes(state.metric) ? state.metric : gate.metrics[0] ?? state.metric;
|
|
167
170
|
const tab = gate.tabs.includes(state.tab) ? state.tab : gate.tabs[0] ?? state.tab;
|
|
171
|
+
const dim = state.dim !== void 0 && gate.dimensionsFor(tab).includes(state.dim) ? state.dim : void 0;
|
|
168
172
|
const compare = state.compare && gate.canCompare;
|
|
169
173
|
const filters = state.filters.filter((filter) => gate.canFilter(filter.dimension) && gate.operators.includes(filter.operator));
|
|
170
174
|
const granularity = state.granularity !== void 0 && gate.granularities.includes(state.granularity) ? state.granularity : void 0;
|
|
171
175
|
const order = state.order !== void 0 && gate.metrics.includes(state.order.metric) ? state.order : void 0;
|
|
172
|
-
if (metric === state.metric && tab === state.tab && compare === state.compare && filters.length === state.filters.length && granularity === state.granularity && order === state.order) return state;
|
|
176
|
+
if (metric === state.metric && tab === state.tab && dim === state.dim && compare === state.compare && filters.length === state.filters.length && granularity === state.granularity && order === state.order) return state;
|
|
173
177
|
return {
|
|
174
178
|
range: state.range,
|
|
175
179
|
...state.from === void 0 ? {} : { from: state.from },
|
|
@@ -179,6 +183,7 @@ const coerceState = (state, gate) => {
|
|
|
179
183
|
metric,
|
|
180
184
|
...granularity === void 0 ? {} : { granularity },
|
|
181
185
|
tab,
|
|
186
|
+
...dim === void 0 ? {} : { dim },
|
|
182
187
|
filters,
|
|
183
188
|
limit: state.limit,
|
|
184
189
|
...order === void 0 ? {} : { order }
|
package/dist/view/state.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.js","names":[],"sources":["../../src/view/state.ts"],"sourcesContent":["import {\n\ttype AnalyticsFilter,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\tFILTER_OPERATORS,\n\ttype FilterOperator,\n\ttype Granularity,\n\ttype MetricKey,\n} from '../core/contract'\nimport { GRANULARITY_ORDER } from '../core/granularity'\nimport {\n\tMAX_QUERY_FILTER_VALUE_LENGTH,\n\tMAX_QUERY_FILTERS,\n\tMAX_QUERY_RANGE_DAYS,\n} from '../query/limits'\nimport { resolveTimeframe, TIMEFRAME_PRESETS, type TimeframePreset } from '../timeframe/presets'\nimport { zonedCalendarDay } from '../timeframe/tz'\nimport {\n\tBREAKDOWN_TABS,\n\ttype BreakdownTab,\n\ttype DayRange,\n\tVIEW_METRIC_ORDER,\n\ttype ViewGate,\n} from './gating'\n\n/**\n * The presets the toolbar offers. `allTime` is deliberately absent: it is unbounded, and\n * the query endpoint refuses any window longer than a year.\n */\nexport const VIEW_RANGE_PRESETS: TimeframePreset[] = [\n\t'today',\n\t'last7days',\n\t'last30days',\n\t'last90days',\n\t'lastYear',\n]\n\nexport const DEFAULT_VIEW_RANGE: TimeframePreset = 'last30days'\n\nexport const VIEW_LIMITS = [10, 25, 50, 100] as const\n\nexport type ViewLimit = (typeof VIEW_LIMITS)[number]\n\nexport const DEFAULT_VIEW_LIMIT: ViewLimit = 10\n\nexport const DEFAULT_VIEW_TAB: BreakdownTab = 'pages'\n\n/** Everything the view reads from the URL. A view is its state, so a link is a view. */\nexport interface ViewState {\n\trange: TimeframePreset | 'custom'\n\t/** Set only on a custom range: an inclusive `YYYY-MM-DD` day in the reporting timezone. */\n\tfrom?: string\n\tto?: string\n\tcompare: boolean\n\tsource?: string\n\tmetric: MetricKey\n\t/** Absent means automatic; {@link autoGranularity} picks one from the range. */\n\tgranularity?: Granularity\n\ttab: BreakdownTab\n\tfilters: AnalyticsFilter[]\n\tlimit: ViewLimit\n\torder?: { metric: MetricKey; direction: 'asc' | 'desc' }\n}\n\n/** The install's configured starting point, as `AnalyticsViewClientProps.defaults` carries it. */\nexport interface ViewDefaults {\n\trange: TimeframePreset\n\tmetric: MetricKey\n}\n\nconst KNOWN_METRICS = new Set<string>(VIEW_METRIC_ORDER)\nconst KNOWN_DIMENSIONS = new Set<string>(DIMENSION_KEYS)\nconst KNOWN_OPERATORS = new Set<string>(FILTER_OPERATORS)\nconst KNOWN_GRANULARITIES = new Set<string>(GRANULARITY_ORDER)\nconst KNOWN_PRESETS = new Set<string>(TIMEFRAME_PRESETS)\nconst DAY_MS = 86_400_000\nconst DAY_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst read = (search: URLSearchParams, name: string): string | null => {\n\tconst raw = search.get(name)?.trim()\n\treturn raw ? raw : null\n}\n\n/**\n * Epoch ms of a `YYYY-MM-DD` day, or null when it names no real calendar day. The\n * round trip is the validation: `Date.parse` rolls February 30 forward instead of failing.\n */\nconst dayValue = (raw: string | null): number | null => {\n\tif (raw === null || !DAY_PATTERN.test(raw)) {\n\t\treturn null\n\t}\n\tconst ms = Date.parse(`${raw}T00:00:00.000Z`)\n\tif (Number.isNaN(ms) || new Date(ms).toISOString().slice(0, 10) !== raw) {\n\t\treturn null\n\t}\n\treturn ms\n}\n\n/** A configured default the view cannot serve falls back to the built-in range. */\nconst defaultRange = (defaults: ViewDefaults): TimeframePreset =>\n\tdefaults.range === 'allTime' ? DEFAULT_VIEW_RANGE : defaults.range\n\nconst parseRange = (\n\tsearch: URLSearchParams,\n\tdefaults: ViewDefaults\n): Pick<ViewState, 'range' | 'from' | 'to'> => {\n\tconst fallback = { range: defaultRange(defaults) }\n\tconst raw = read(search, 'range')\n\tif (raw === null) {\n\t\treturn fallback\n\t}\n\tif (raw === 'custom') {\n\t\tconst from = dayValue(read(search, 'from'))\n\t\tconst to = dayValue(read(search, 'to'))\n\t\tif (from === null || to === null || to < from) {\n\t\t\treturn fallback\n\t\t}\n\t\t// Beyond the endpoint's own cap the read would only ever answer `range_too_long`.\n\t\tif (Math.round((to - from) / DAY_MS) + 1 > MAX_QUERY_RANGE_DAYS) {\n\t\t\treturn fallback\n\t\t}\n\t\treturn {\n\t\t\trange: 'custom',\n\t\t\tfrom: new Date(from).toISOString().slice(0, 10),\n\t\t\tto: new Date(to).toISOString().slice(0, 10),\n\t\t}\n\t}\n\tif (!KNOWN_PRESETS.has(raw) || raw === 'allTime') {\n\t\treturn fallback\n\t}\n\treturn { range: raw as TimeframePreset }\n}\n\n/**\n * Filters as the endpoint's own parser would accept them, minus its errors: an entry\n * naming a dimension, operator or value outside the contract is dropped rather than\n * failing the whole URL, since a hand-edited link should still open a working view.\n */\nconst parseFilters = (search: URLSearchParams): AnalyticsFilter[] => {\n\tconst raw = read(search, 'filters')\n\tif (raw === null) {\n\t\treturn []\n\t}\n\tlet decoded: unknown\n\ttry {\n\t\tdecoded = JSON.parse(raw)\n\t} catch {\n\t\treturn []\n\t}\n\tif (!Array.isArray(decoded)) {\n\t\treturn []\n\t}\n\tconst filters: AnalyticsFilter[] = []\n\tfor (const item of decoded) {\n\t\tif (filters.length === MAX_QUERY_FILTERS) {\n\t\t\tbreak\n\t\t}\n\t\tif (!isRecord(item)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst { dimension, operator, value } = item\n\t\tif (typeof dimension !== 'string' || !KNOWN_DIMENSIONS.has(dimension)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (typeof operator !== 'string' || !KNOWN_OPERATORS.has(operator)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (typeof value !== 'string') {\n\t\t\tcontinue\n\t\t}\n\t\tconst trimmed = value.trim()\n\t\tif (trimmed.length < 1 || trimmed.length > MAX_QUERY_FILTER_VALUE_LENGTH) {\n\t\t\tcontinue\n\t\t}\n\t\tfilters.push({\n\t\t\tdimension: dimension as DimensionKey,\n\t\t\toperator: operator as FilterOperator,\n\t\t\tvalue: trimmed,\n\t\t})\n\t}\n\treturn filters\n}\n\nconst parseOrder = (search: URLSearchParams): ViewState['order'] => {\n\tconst raw = read(search, 'order')\n\tif (raw === null) {\n\t\treturn undefined\n\t}\n\tconst parts = raw.split(':')\n\tconst metric = parts[0] ?? ''\n\tconst direction = parts[1] ?? ''\n\tif (parts.length !== 2 || !KNOWN_METRICS.has(metric)) {\n\t\treturn undefined\n\t}\n\tif (direction !== 'asc' && direction !== 'desc') {\n\t\treturn undefined\n\t}\n\treturn { metric: metric as MetricKey, direction }\n}\n\n/**\n * Total by construction: every value the URL cannot justify falls back to the install\n * default, so a truncated, stale or hand-edited link always opens a working view.\n */\nexport const parseViewState = (search: URLSearchParams, defaults: ViewDefaults): ViewState => {\n\tconst metric = read(search, 'metric')\n\tconst granularity = read(search, 'granularity')\n\tconst tab = read(search, 'tab')\n\tconst source = read(search, 'source')\n\tconst limit = Number(read(search, 'limit'))\n\tconst compare = read(search, 'compare')\n\tconst order = parseOrder(search)\n\treturn {\n\t\t...parseRange(search, defaults),\n\t\tcompare: compare === '1' || compare === 'true',\n\t\t...(source === null ? {} : { source }),\n\t\tmetric: metric !== null && KNOWN_METRICS.has(metric) ? (metric as MetricKey) : defaults.metric,\n\t\t...(granularity !== null && KNOWN_GRANULARITIES.has(granularity)\n\t\t\t? { granularity: granularity as Granularity }\n\t\t\t: {}),\n\t\ttab:\n\t\t\ttab !== null && BREAKDOWN_TABS.includes(tab as BreakdownTab)\n\t\t\t\t? (tab as BreakdownTab)\n\t\t\t\t: DEFAULT_VIEW_TAB,\n\t\tfilters: parseFilters(search),\n\t\tlimit: VIEW_LIMITS.includes(limit as ViewLimit) ? (limit as ViewLimit) : DEFAULT_VIEW_LIMIT,\n\t\t...(order === undefined ? {} : { order }),\n\t}\n}\n\n/**\n * The shortest URL that parses back to `state`: anything equal to a default is left out,\n * and the keys are written in one fixed order so an unchanged view never rewrites history.\n */\nexport const serializeViewState = (state: ViewState, defaults: ViewDefaults): URLSearchParams => {\n\tconst params = new URLSearchParams()\n\tif (state.range !== defaultRange(defaults)) {\n\t\tparams.set('range', state.range)\n\t}\n\tif (state.range === 'custom' && state.from !== undefined && state.to !== undefined) {\n\t\tparams.set('from', state.from)\n\t\tparams.set('to', state.to)\n\t}\n\tif (state.compare) {\n\t\tparams.set('compare', '1')\n\t}\n\tif (state.source !== undefined) {\n\t\tparams.set('source', state.source)\n\t}\n\tif (state.metric !== defaults.metric) {\n\t\tparams.set('metric', state.metric)\n\t}\n\tif (state.granularity !== undefined) {\n\t\tparams.set('granularity', state.granularity)\n\t}\n\tif (state.tab !== DEFAULT_VIEW_TAB) {\n\t\tparams.set('tab', state.tab)\n\t}\n\tif (state.filters.length > 0) {\n\t\tparams.set('filters', JSON.stringify(state.filters))\n\t}\n\tif (state.limit !== DEFAULT_VIEW_LIMIT) {\n\t\tparams.set('limit', String(state.limit))\n\t}\n\tif (state.order !== undefined) {\n\t\tparams.set('order', `${state.order.metric}:${state.order.direction}`)\n\t}\n\treturn params\n}\n\n/**\n * The nearest state the selected source can actually serve. The URL outlives a source\n * switch, so a metric, tab, filter, comparison, bucket or sort the new source lacks is\n * replaced or dropped here rather than sent to the endpoint to be rejected. Returns the\n * same object when the gate forbids nothing, so a render can compare by identity.\n */\nexport const coerceState = (state: ViewState, gate: ViewGate): ViewState => {\n\tconst metric = gate.metrics.includes(state.metric)\n\t\t? state.metric\n\t\t: (gate.metrics[0] ?? state.metric)\n\tconst tab = gate.tabs.includes(state.tab) ? state.tab : (gate.tabs[0] ?? state.tab)\n\tconst compare = state.compare && gate.canCompare\n\tconst filters = state.filters.filter(\n\t\t(filter) => gate.canFilter(filter.dimension) && gate.operators.includes(filter.operator)\n\t)\n\tconst granularity =\n\t\tstate.granularity !== undefined && gate.granularities.includes(state.granularity)\n\t\t\t? state.granularity\n\t\t\t: undefined\n\tconst order =\n\t\tstate.order !== undefined && gate.metrics.includes(state.order.metric) ? state.order : undefined\n\tconst unchanged =\n\t\tmetric === state.metric &&\n\t\ttab === state.tab &&\n\t\tcompare === state.compare &&\n\t\tfilters.length === state.filters.length &&\n\t\tgranularity === state.granularity &&\n\t\torder === state.order\n\tif (unchanged) {\n\t\treturn state\n\t}\n\treturn {\n\t\trange: state.range,\n\t\t...(state.from === undefined ? {} : { from: state.from }),\n\t\t...(state.to === undefined ? {} : { to: state.to }),\n\t\tcompare,\n\t\t...(state.source === undefined ? {} : { source: state.source }),\n\t\tmetric,\n\t\t...(granularity === undefined ? {} : { granularity }),\n\t\ttab,\n\t\tfilters,\n\t\tlimit: state.limit,\n\t\t...(order === undefined ? {} : { order }),\n\t}\n}\n\n/**\n * The inclusive day window a state reads, in the reporting timezone. The endpoint reads\n * `from`/`to` in that same timezone, so the toolbar caption and every request share one\n * answer. `now` is injected to keep callers deterministic.\n */\nexport const rangeFor = (state: ViewState, timezone: string, now: Date): DayRange => {\n\tif (state.range === 'custom' && state.from !== undefined && state.to !== undefined) {\n\t\treturn { from: state.from, to: state.to }\n\t}\n\tconst preset = state.range === 'custom' ? DEFAULT_VIEW_RANGE : state.range\n\tconst { start, end } = resolveTimeframe(preset, now, timezone)\n\treturn { from: zonedCalendarDay(start, timezone), to: zonedCalendarDay(end, timezone) }\n}\n"],"mappings":";;;;;;;;;;AA6BA,MAAa,qBAAwC;CACpD;CACA;CACA;CACA;CACA;AACD;AAEA,MAAa,qBAAsC;AAEnD,MAAa,cAAc;CAAC;CAAI;CAAI;CAAI;AAAG;AAM3C,MAAa,mBAAiC;AAyB9C,MAAM,gBAAgB,IAAI,IAAY,iBAAiB;AACvD,MAAM,mBAAmB,IAAI,IAAY,cAAc;AACvD,MAAM,kBAAkB,IAAI,IAAY,gBAAgB;AACxD,MAAM,sBAAsB,IAAI,IAAY,iBAAiB;AAC7D,MAAM,gBAAgB,IAAI,IAAY,iBAAiB;AACvD,MAAM,SAAS;AACf,MAAM,cAAc;AAEpB,MAAM,YAAY,UACjB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAEpE,MAAM,QAAQ,QAAyB,SAAgC;CACtE,MAAM,MAAM,OAAO,IAAI,IAAI,GAAG,KAAK;CACnC,OAAO,MAAM,MAAM;AACpB;;;;;AAMA,MAAM,YAAY,QAAsC;CACvD,IAAI,QAAQ,QAAQ,CAAC,YAAY,KAAK,GAAG,GACxC,OAAO;CAER,MAAM,KAAK,KAAK,MAAM,GAAG,IAAI,eAAe;CAC5C,IAAI,OAAO,MAAM,EAAE,KAAK,IAAI,KAAK,EAAE,EAAE,YAAY,EAAE,MAAM,GAAG,EAAE,MAAM,KACnE,OAAO;CAER,OAAO;AACR;;AAGA,MAAM,gBAA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"sourcesContent":["import {\n\ttype AnalyticsFilter,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\tFILTER_OPERATORS,\n\ttype FilterOperator,\n\ttype Granularity,\n\ttype MetricKey,\n} from '../core/contract'\nimport { GRANULARITY_ORDER } from '../core/granularity'\nimport {\n\tMAX_QUERY_FILTER_VALUE_LENGTH,\n\tMAX_QUERY_FILTERS,\n\tMAX_QUERY_RANGE_DAYS,\n} from '../query/limits'\nimport { resolveTimeframe, TIMEFRAME_PRESETS, type TimeframePreset } from '../timeframe/presets'\nimport { zonedCalendarDay } from '../timeframe/tz'\nimport {\n\tBREAKDOWN_TABS,\n\ttype BreakdownTab,\n\ttype DayRange,\n\tVIEW_METRIC_ORDER,\n\ttype ViewGate,\n} from './gating'\n\n/**\n * The presets the toolbar offers. `allTime` is deliberately absent: it is unbounded, and\n * the query endpoint refuses any window longer than a year.\n */\nexport const VIEW_RANGE_PRESETS: TimeframePreset[] = [\n\t'today',\n\t'last7days',\n\t'last30days',\n\t'last90days',\n\t'lastYear',\n]\n\nexport const DEFAULT_VIEW_RANGE: TimeframePreset = 'last30days'\n\nexport const VIEW_LIMITS = [10, 25, 50, 100] as const\n\nexport type ViewLimit = (typeof VIEW_LIMITS)[number]\n\nexport const DEFAULT_VIEW_LIMIT: ViewLimit = 10\n\nexport const DEFAULT_VIEW_TAB: BreakdownTab = 'pages'\n\n/** Everything the view reads from the URL. A view is its state, so a link is a view. */\nexport interface ViewState {\n\trange: TimeframePreset | 'custom'\n\t/** Set only on a custom range: an inclusive `YYYY-MM-DD` day in the reporting timezone. */\n\tfrom?: string\n\tto?: string\n\tcompare: boolean\n\tsource?: string\n\tmetric: MetricKey\n\t/** Absent means automatic; {@link autoGranularity} picks one from the range. */\n\tgranularity?: Granularity\n\ttab: BreakdownTab\n\t/** The dimension the tab groups by. Absent means its default, the first one served. */\n\tdim?: DimensionKey\n\tfilters: AnalyticsFilter[]\n\tlimit: ViewLimit\n\torder?: { metric: MetricKey; direction: 'asc' | 'desc' }\n}\n\n/** The install's configured starting point, as `AnalyticsViewClientProps.defaults` carries it. */\nexport interface ViewDefaults {\n\trange: TimeframePreset\n\tmetric: MetricKey\n}\n\nconst KNOWN_METRICS = new Set<string>(VIEW_METRIC_ORDER)\nconst KNOWN_DIMENSIONS = new Set<string>(DIMENSION_KEYS)\nconst KNOWN_OPERATORS = new Set<string>(FILTER_OPERATORS)\nconst KNOWN_GRANULARITIES = new Set<string>(GRANULARITY_ORDER)\nconst KNOWN_PRESETS = new Set<string>(TIMEFRAME_PRESETS)\nconst DAY_MS = 86_400_000\nconst DAY_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst read = (search: URLSearchParams, name: string): string | null => {\n\tconst raw = search.get(name)?.trim()\n\treturn raw ? raw : null\n}\n\n/**\n * Epoch ms of a `YYYY-MM-DD` day, or null when it names no real calendar day. The\n * round trip is the validation: `Date.parse` rolls February 30 forward instead of failing.\n */\nconst dayValue = (raw: string | null): number | null => {\n\tif (raw === null || !DAY_PATTERN.test(raw)) {\n\t\treturn null\n\t}\n\tconst ms = Date.parse(`${raw}T00:00:00.000Z`)\n\tif (Number.isNaN(ms) || new Date(ms).toISOString().slice(0, 10) !== raw) {\n\t\treturn null\n\t}\n\treturn ms\n}\n\n/** A configured default the view cannot serve falls back to the built-in range. */\nconst defaultRange = (defaults: ViewDefaults): TimeframePreset =>\n\tdefaults.range === 'allTime' ? DEFAULT_VIEW_RANGE : defaults.range\n\nconst parseRange = (\n\tsearch: URLSearchParams,\n\tdefaults: ViewDefaults\n): Pick<ViewState, 'range' | 'from' | 'to'> => {\n\tconst fallback = { range: defaultRange(defaults) }\n\tconst raw = read(search, 'range')\n\tif (raw === null) {\n\t\treturn fallback\n\t}\n\tif (raw === 'custom') {\n\t\tconst from = dayValue(read(search, 'from'))\n\t\tconst to = dayValue(read(search, 'to'))\n\t\tif (from === null || to === null || to < from) {\n\t\t\treturn fallback\n\t\t}\n\t\t// Beyond the endpoint's own cap the read would only ever answer `range_too_long`.\n\t\tif (Math.round((to - from) / DAY_MS) + 1 > MAX_QUERY_RANGE_DAYS) {\n\t\t\treturn fallback\n\t\t}\n\t\treturn {\n\t\t\trange: 'custom',\n\t\t\tfrom: new Date(from).toISOString().slice(0, 10),\n\t\t\tto: new Date(to).toISOString().slice(0, 10),\n\t\t}\n\t}\n\tif (!KNOWN_PRESETS.has(raw) || raw === 'allTime') {\n\t\treturn fallback\n\t}\n\treturn { range: raw as TimeframePreset }\n}\n\n/**\n * Filters as the endpoint's own parser would accept them, minus its errors: an entry\n * naming a dimension, operator or value outside the contract is dropped rather than\n * failing the whole URL, since a hand-edited link should still open a working view.\n */\nconst parseFilters = (search: URLSearchParams): AnalyticsFilter[] => {\n\tconst raw = read(search, 'filters')\n\tif (raw === null) {\n\t\treturn []\n\t}\n\tlet decoded: unknown\n\ttry {\n\t\tdecoded = JSON.parse(raw)\n\t} catch {\n\t\treturn []\n\t}\n\tif (!Array.isArray(decoded)) {\n\t\treturn []\n\t}\n\tconst filters: AnalyticsFilter[] = []\n\tfor (const item of decoded) {\n\t\tif (filters.length === MAX_QUERY_FILTERS) {\n\t\t\tbreak\n\t\t}\n\t\tif (!isRecord(item)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst { dimension, operator, value } = item\n\t\tif (typeof dimension !== 'string' || !KNOWN_DIMENSIONS.has(dimension)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (typeof operator !== 'string' || !KNOWN_OPERATORS.has(operator)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (typeof value !== 'string') {\n\t\t\tcontinue\n\t\t}\n\t\tconst trimmed = value.trim()\n\t\tif (trimmed.length < 1 || trimmed.length > MAX_QUERY_FILTER_VALUE_LENGTH) {\n\t\t\tcontinue\n\t\t}\n\t\tfilters.push({\n\t\t\tdimension: dimension as DimensionKey,\n\t\t\toperator: operator as FilterOperator,\n\t\t\tvalue: trimmed,\n\t\t})\n\t}\n\treturn filters\n}\n\nconst parseOrder = (search: URLSearchParams): ViewState['order'] => {\n\tconst raw = read(search, 'order')\n\tif (raw === null) {\n\t\treturn undefined\n\t}\n\tconst parts = raw.split(':')\n\tconst metric = parts[0] ?? ''\n\tconst direction = parts[1] ?? ''\n\tif (parts.length !== 2 || !KNOWN_METRICS.has(metric)) {\n\t\treturn undefined\n\t}\n\tif (direction !== 'asc' && direction !== 'desc') {\n\t\treturn undefined\n\t}\n\treturn { metric: metric as MetricKey, direction }\n}\n\n/**\n * Total by construction: every value the URL cannot justify falls back to the install\n * default, so a truncated, stale or hand-edited link always opens a working view.\n */\nexport const parseViewState = (search: URLSearchParams, defaults: ViewDefaults): ViewState => {\n\tconst metric = read(search, 'metric')\n\tconst granularity = read(search, 'granularity')\n\tconst tab = read(search, 'tab')\n\tconst dim = read(search, 'dim')\n\tconst source = read(search, 'source')\n\tconst limit = Number(read(search, 'limit'))\n\tconst compare = read(search, 'compare')\n\tconst order = parseOrder(search)\n\treturn {\n\t\t...parseRange(search, defaults),\n\t\tcompare: compare === '1' || compare === 'true',\n\t\t...(source === null ? {} : { source }),\n\t\tmetric: metric !== null && KNOWN_METRICS.has(metric) ? (metric as MetricKey) : defaults.metric,\n\t\t...(granularity !== null && KNOWN_GRANULARITIES.has(granularity)\n\t\t\t? { granularity: granularity as Granularity }\n\t\t\t: {}),\n\t\ttab:\n\t\t\ttab !== null && BREAKDOWN_TABS.includes(tab as BreakdownTab)\n\t\t\t\t? (tab as BreakdownTab)\n\t\t\t\t: DEFAULT_VIEW_TAB,\n\t\t...(dim !== null && KNOWN_DIMENSIONS.has(dim) ? { dim: dim as DimensionKey } : {}),\n\t\tfilters: parseFilters(search),\n\t\tlimit: VIEW_LIMITS.includes(limit as ViewLimit) ? (limit as ViewLimit) : DEFAULT_VIEW_LIMIT,\n\t\t...(order === undefined ? {} : { order }),\n\t}\n}\n\n/**\n * The shortest URL that parses back to `state`: anything equal to a default is left out,\n * and the keys are written in one fixed order so an unchanged view never rewrites history.\n */\nexport const serializeViewState = (state: ViewState, defaults: ViewDefaults): URLSearchParams => {\n\tconst params = new URLSearchParams()\n\tif (state.range !== defaultRange(defaults)) {\n\t\tparams.set('range', state.range)\n\t}\n\tif (state.range === 'custom' && state.from !== undefined && state.to !== undefined) {\n\t\tparams.set('from', state.from)\n\t\tparams.set('to', state.to)\n\t}\n\tif (state.compare) {\n\t\tparams.set('compare', '1')\n\t}\n\tif (state.source !== undefined) {\n\t\tparams.set('source', state.source)\n\t}\n\tif (state.metric !== defaults.metric) {\n\t\tparams.set('metric', state.metric)\n\t}\n\tif (state.granularity !== undefined) {\n\t\tparams.set('granularity', state.granularity)\n\t}\n\tif (state.tab !== DEFAULT_VIEW_TAB) {\n\t\tparams.set('tab', state.tab)\n\t}\n\tif (state.dim !== undefined) {\n\t\tparams.set('dim', state.dim)\n\t}\n\tif (state.filters.length > 0) {\n\t\tparams.set('filters', JSON.stringify(state.filters))\n\t}\n\tif (state.limit !== DEFAULT_VIEW_LIMIT) {\n\t\tparams.set('limit', String(state.limit))\n\t}\n\tif (state.order !== undefined) {\n\t\tparams.set('order', `${state.order.metric}:${state.order.direction}`)\n\t}\n\treturn params\n}\n\n/**\n * The nearest state the selected source can actually serve. The URL outlives a source\n * switch, so a metric, tab, grouping, filter, comparison, bucket or sort the new source lacks is\n * replaced or dropped here rather than sent to the endpoint to be rejected. Returns the\n * same object when the gate forbids nothing, so a render can compare by identity.\n */\nexport const coerceState = (state: ViewState, gate: ViewGate): ViewState => {\n\tconst metric = gate.metrics.includes(state.metric)\n\t\t? state.metric\n\t\t: (gate.metrics[0] ?? state.metric)\n\tconst tab = gate.tabs.includes(state.tab) ? state.tab : (gate.tabs[0] ?? state.tab)\n\tconst dim =\n\t\tstate.dim !== undefined && gate.dimensionsFor(tab).includes(state.dim) ? state.dim : undefined\n\tconst compare = state.compare && gate.canCompare\n\tconst filters = state.filters.filter(\n\t\t(filter) => gate.canFilter(filter.dimension) && gate.operators.includes(filter.operator)\n\t)\n\tconst granularity =\n\t\tstate.granularity !== undefined && gate.granularities.includes(state.granularity)\n\t\t\t? state.granularity\n\t\t\t: undefined\n\tconst order =\n\t\tstate.order !== undefined && gate.metrics.includes(state.order.metric) ? state.order : undefined\n\tconst unchanged =\n\t\tmetric === state.metric &&\n\t\ttab === state.tab &&\n\t\tdim === state.dim &&\n\t\tcompare === state.compare &&\n\t\tfilters.length === state.filters.length &&\n\t\tgranularity === state.granularity &&\n\t\torder === state.order\n\tif (unchanged) {\n\t\treturn state\n\t}\n\treturn {\n\t\trange: state.range,\n\t\t...(state.from === undefined ? {} : { from: state.from }),\n\t\t...(state.to === undefined ? {} : { to: state.to }),\n\t\tcompare,\n\t\t...(state.source === undefined ? {} : { source: state.source }),\n\t\tmetric,\n\t\t...(granularity === undefined ? {} : { granularity }),\n\t\ttab,\n\t\t...(dim === undefined ? {} : { dim }),\n\t\tfilters,\n\t\tlimit: state.limit,\n\t\t...(order === undefined ? {} : { order }),\n\t}\n}\n\n/**\n * The inclusive day window a state reads, in the reporting timezone. The endpoint reads\n * `from`/`to` in that same timezone, so the toolbar caption and every request share one\n * answer. `now` is injected to keep callers deterministic.\n */\nexport const rangeFor = (state: ViewState, timezone: string, now: Date): DayRange => {\n\tif (state.range === 'custom' && state.from !== undefined && state.to !== undefined) {\n\t\treturn { from: state.from, to: state.to }\n\t}\n\tconst preset = state.range === 'custom' ? DEFAULT_VIEW_RANGE : state.range\n\tconst { start, end } = resolveTimeframe(preset, now, timezone)\n\treturn { from: zonedCalendarDay(start, timezone), to: zonedCalendarDay(end, timezone) }\n}\n"],"mappings":";;;;;;;;;;AA6BA,MAAa,qBAAwC;CACpD;CACA;CACA;CACA;CACA;AACD;AAEA,MAAa,qBAAsC;AAEnD,MAAa,cAAc;CAAC;CAAI;CAAI;CAAI;AAAG;AAM3C,MAAa,mBAAiC;AA2B9C,MAAM,gBAAgB,IAAI,IAAY,iBAAiB;AACvD,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AA;CASxF,IAPC,WAAW,MAAM,UACjB,QAAQ,MAAM,OACd,QAAQ,MAAM,OACd,YAAY,MAAM,WAClB,QAAQ,WAAW,MAAM,QAAQ,UACjC,gBAAgB,MAAM,eACtB,UAAU,MAAM,OAEhB,OAAO;CAER,OAAO;EACN,OAAO,MAAM;EACb,GAAI,MAAM,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,MAAM,KAAK;EACvD,GAAI,MAAM,OAAO,KAAA,IAAY,CAAC,IAAI,EAAE,IAAI,MAAM,GAAG;EACjD;EACA,GAAI,MAAM,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,MAAM,OAAO;EAC7D;EACA,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;EACnD;EACA,GAAI,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,IAAI;EACnC;EACA,OAAO,MAAM;EACb,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM;CACxC;AACD;;;;;;AAOA,MAAa,YAAY,OAAkB,UAAkB,QAAwB;CACpF,IAAI,MAAM,UAAU,YAAY,MAAM,SAAS,KAAA,KAAa,MAAM,OAAO,KAAA,GACxE,OAAO;EAAE,MAAM,MAAM;EAAM,IAAI,MAAM;CAAG;CAGzC,MAAM,EAAE,OAAO,QAAQ,iBADR,MAAM,UAAU,WAAW,qBAAqB,MAAM,OACrB,KAAK,QAAQ;CAC7D,OAAO;EAAE,MAAM,iBAAiB,OAAO,QAAQ;EAAG,IAAI,iBAAiB,KAAK,QAAQ;CAAE;AACvF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { fetchQuery } from "../query/fetchQuery.js";
|
|
3
|
-
import { autoGranularity, gate, resolveSource } from "./gating.js";
|
|
3
|
+
import { autoGranularity, canCompareRange, gate, resolveSource } from "./gating.js";
|
|
4
4
|
import { coerceState, rangeFor } from "./state.js";
|
|
5
5
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
6
6
|
//#region src/view/useViewQueries.ts
|
|
@@ -36,9 +36,12 @@ const buildViewRequests = (props, state, now) => {
|
|
|
36
36
|
source: source.id,
|
|
37
37
|
timezone: props.timezone
|
|
38
38
|
};
|
|
39
|
-
const compare = view.compare
|
|
39
|
+
const compare = view.compare && canCompareRange(served, range, {
|
|
40
|
+
timezone: props.timezone,
|
|
41
|
+
now
|
|
42
|
+
}) ? { compare: "previous" } : {};
|
|
40
43
|
const breakdownMetrics = [view.metric, ...served.metrics.includes("visitors") && view.metric !== "visitors" ? ["visitors"] : []];
|
|
41
|
-
const dimension = served.dimensionsFor(view.tab)[0];
|
|
44
|
+
const dimension = view.dim ?? served.dimensionsFor(view.tab)[0];
|
|
42
45
|
const order = view.order !== void 0 && breakdownMetrics.includes(view.order.metric) ? view.order : {
|
|
43
46
|
metric: view.metric,
|
|
44
47
|
direction: "desc"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useViewQueries.js","names":[],"sources":["../../src/view/useViewQueries.ts"],"sourcesContent":["'use client'\n\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport type { MetricKey } from '../core/contract'\nimport { fetchQuery, type QueryRequest } from '../query/fetchQuery'\nimport type { QueryResponse } from '../query/response'\nimport { autoGranularity, gate, resolveSource } from './gating'\nimport { coerceState, rangeFor, type ViewState } from './state'\nimport type { AnalyticsViewClientProps } from './viewProps'\n\n/**\n * One section's read. `error` is a `QueryFetchError` whenever the endpoint answered.\n *\n * `data` survives into the next `loading` and into an `error`, so changing the range or\n * hitting a transient failure dims or annotates the chart it already shows instead of\n * blanking it; `isRefetching` is the loading half of that, and is the flag to render a\n * subtle busy affordance on. `status === 'loading'` with no `data` is the only real empty\n * load, and the only one that earns a skeleton. A section that stops being servable at all\n * drops its data, since it belongs to a source or tab the view is no longer showing.\n */\nexport interface QueryState<T> {\n\tstatus: 'loading' | 'ok' | 'error'\n\t/** May be the previous read's answer while `status` is `loading` or `error`. */\n\tdata?: T\n\terror?: Error\n\tisRefetching: boolean\n\trefetch: () => void\n}\n\nexport interface ViewQueries {\n\tcards: QueryState<QueryResponse>\n\ttrend: QueryState<QueryResponse>\n\tbreakdown: QueryState<QueryResponse>\n\t/** Null when the source serves no goal breakdown, so the panel is not rendered at all. */\n\tgoals: QueryState<QueryResponse> | null\n}\n\n/** The four reads a view state implies; a null section is one this source cannot serve. */\nexport interface ViewRequests {\n\tcards: QueryRequest | null\n\ttrend: QueryRequest | null\n\tbreakdown: QueryRequest | null\n\tgoals: QueryRequest | null\n}\n\n/**\n * `QueryState.error.message` for a section with nothing to ask for: the scope has no\n * readable source, or the source serves no metric or dimension the section needs. It is\n * never an endpoint failure, so a caller can tell the two apart without a `QueryFetchError`.\n */\nexport const SECTION_UNAVAILABLE = 'analytics: this source serves no data for this section'\n\nconst NO_REQUESTS: ViewRequests = { cards: null, trend: null, breakdown: null, goals: null }\n\n/**\n * Derives the four reads from the view state and the selected source's capabilities.\n * Pure and total: the state is coerced to what the source serves first, so no request\n * here can carry a metric, dimension, filter, bucket or comparison the endpoint would\n * reject. `now` is injected to keep callers deterministic.\n */\nexport const buildViewRequests = (\n\tprops: AnalyticsViewClientProps,\n\tstate: ViewState,\n\tnow: Date\n): ViewRequests => {\n\tconst source = resolveSource(props.sources, state.source)\n\tif (!source) {\n\t\treturn NO_REQUESTS\n\t}\n\tconst served = gate(source.capabilities)\n\tif (served.metrics.length === 0) {\n\t\treturn NO_REQUESTS\n\t}\n\tconst view = coerceState(state, served)\n\tconst range = rangeFor(view, props.timezone, now)\n\t// The resolved id, not the state's: a stale one in the URL would otherwise ask the\n\t// endpoint for a source that is gone while the gate describes the fallback.\n\tconst shared = {\n\t\tfrom: range.from,\n\t\tto: range.to,\n\t\t...(view.filters.length > 0 ? { filters: view.filters } : {}),\n\t\tsource: source.id,\n\t\ttimezone: props.timezone,\n\t}\n\tconst compare = view.compare ? ({ compare: 'previous' } as const) : {}\n\tconst breakdownMetrics: MetricKey[] = [\n\t\tview.metric,\n\t\t...(served.metrics.includes('visitors') && view.metric !== 'visitors'\n\t\t\t? (['visitors'] as const)\n\t\t\t: []),\n\t]\n\tconst dimension = served.dimensionsFor(view.tab)[0]\n\tconst order: QueryRequest['order'] =\n\t\tview.order !== undefined && breakdownMetrics.includes(view.order.metric)\n\t\t\t? view.order\n\t\t\t: { metric: view.metric, direction: 'desc' }\n\treturn {\n\t\tcards: { metrics: served.metrics, ...shared, ...compare },\n\t\ttrend: {\n\t\t\tmetrics: [view.metric],\n\t\t\t...shared,\n\t\t\tgranularity: view.granularity ?? autoGranularity(range, source.capabilities),\n\t\t\t...compare,\n\t\t},\n\t\tbreakdown:\n\t\t\tdimension === undefined\n\t\t\t\t? null\n\t\t\t\t: {\n\t\t\t\t\t\tmetrics: breakdownMetrics,\n\t\t\t\t\t\tdimensions: [dimension],\n\t\t\t\t\t\t...shared,\n\t\t\t\t\t\tlimit: view.limit,\n\t\t\t\t\t\torder,\n\t\t\t\t\t},\n\t\tgoals: served.goals\n\t\t\t? {\n\t\t\t\t\tmetrics: [\n\t\t\t\t\t\t'conversions',\n\t\t\t\t\t\t...(served.metrics.includes('revenue') ? (['revenue'] as const) : []),\n\t\t\t\t\t\t...(served.metrics.includes('visitors') ? (['visitors'] as const) : []),\n\t\t\t\t\t],\n\t\t\t\t\tdimensions: ['goal'],\n\t\t\t\t\t...shared,\n\t\t\t\t}\n\t\t\t: null,\n\t}\n}\n\nconst asError = (err: unknown): Error => (err instanceof Error ? err : new Error(String(err)))\n\ntype SectionState = Omit<QueryState<QueryResponse>, 'isRefetching' | 'refetch'>\n\n/**\n * Runs one section's read. The request is keyed by its serialized form, so a state change\n * that leaves a section's query identical never refetches it, and one that changes it\n * aborts the in-flight read before issuing the new one.\n */\nconst useQuerySection = (\n\tapiRoute: string,\n\trequest: QueryRequest | null\n): QueryState<QueryResponse> => {\n\tconst [section, setSection] = useState<SectionState>({ status: 'loading' })\n\tconst pending = useRef<AbortController | null>(null)\n\tconst key = request === null ? null : JSON.stringify(request)\n\n\tconst run = useCallback(\n\t\t(serialized: string | null) => {\n\t\t\tpending.current?.abort()\n\t\t\tif (serialized === null) {\n\t\t\t\tpending.current = null\n\t\t\t\tsetSection({ status: 'error', error: new Error(SECTION_UNAVAILABLE) })\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst controller = new AbortController()\n\t\t\tpending.current = controller\n\t\t\t// Returning `prev` unchanged makes the first read a no-op update rather than a\n\t\t\t// second render; any later one keeps what is on screen until the answer lands.\n\t\t\tsetSection((prev) =>\n\t\t\t\tprev.status === 'loading'\n\t\t\t\t\t? prev\n\t\t\t\t\t: { status: 'loading', ...(prev.data === undefined ? {} : { data: prev.data }) }\n\t\t\t)\n\t\t\tfetchQuery(apiRoute, JSON.parse(serialized) as QueryRequest, {\n\t\t\t\tsignal: controller.signal,\n\t\t\t}).then(\n\t\t\t\t(data) => {\n\t\t\t\t\tif (!controller.signal.aborted) setSection({ status: 'ok', data })\n\t\t\t\t},\n\t\t\t\t(err: unknown) => {\n\t\t\t\t\t// The failure is reported beside whatever is on screen: a transient 503 on a\n\t\t\t\t\t// refetch shows a retry banner over the last good read instead of a blank panel.\n\t\t\t\t\tif (!controller.signal.aborted) {\n\t\t\t\t\t\tsetSection((prev) => ({\n\t\t\t\t\t\t\tstatus: 'error',\n\t\t\t\t\t\t\terror: asError(err),\n\t\t\t\t\t\t\t...(prev.data === undefined ? {} : { data: prev.data }),\n\t\t\t\t\t\t}))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\t\t},\n\t\t[apiRoute]\n\t)\n\n\tconst refetch = useCallback(() => {\n\t\trun(key)\n\t}, [run, key])\n\n\tuseEffect(() => {\n\t\trun(key)\n\t\treturn () => {\n\t\t\tpending.current?.abort()\n\t\t}\n\t}, [run, key])\n\n\treturn {\n\t\t...section,\n\t\tisRefetching: section.status === 'loading' && section.data !== undefined,\n\t\trefetch,\n\t}\n}\n\n/**\n * The view's four reads for one state, each with its own lifecycle: a section refetches\n * only when its own request changes, and an in-flight read is aborted when it does.\n */\nexport const useViewQueries = (props: AnalyticsViewClientProps, state: ViewState): ViewQueries => {\n\tconst requests = buildViewRequests(props, state, new Date())\n\tconst cards = useQuerySection(props.apiRoute, requests.cards)\n\tconst trend = useQuerySection(props.apiRoute, requests.trend)\n\tconst breakdown = useQuerySection(props.apiRoute, requests.breakdown)\n\tconst goals = useQuerySection(props.apiRoute, requests.goals)\n\treturn { cards, trend, breakdown, goals: requests.goals === null ? null : goals }\n}\n"],"mappings":";;;;;;;;;;;AAkDA,MAAa,sBAAsB;AAEnC,MAAM,cAA4B;CAAE,OAAO;CAAM,OAAO;CAAM,WAAW;CAAM,OAAO;AAAK;;;;;;;AAQ3F,MAAa,qBACZ,OACA,OACA,QACkB;CAClB,MAAM,SAAS,cAAc,MAAM,SAAS,MAAM,MAAM;CACxD,IAAI,CAAC,QACJ,OAAO;CAER,MAAM,SAAS,KAAK,OAAO,YAAY;CACvC,IAAI,OAAO,QAAQ,WAAW,GAC7B,OAAO;CAER,MAAM,OAAO,YAAY,OAAO,MAAM;CACtC,MAAM,QAAQ,SAAS,MAAM,MAAM,UAAU,GAAG;CAGhD,MAAM,SAAS;EACd,MAAM,MAAM;EACZ,IAAI,MAAM;EACV,GAAI,KAAK,QAAQ,SAAS,IAAI,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;EAC3D,QAAQ,OAAO;EACf,UAAU,MAAM;CACjB;CACA,MAAM,UAAU,KAAK,UAAW,EAAE,SAAS,WAAW,IAAc,CAAC;CACrE,MAAM,mBAAgC,CACrC,KAAK,QACL,GAAI,OAAO,QAAQ,SAAS,UAAU,KAAK,KAAK,WAAW,aACvD,CAAC,UAAU,IACZ,CAAC,CACL;CACA,MAAM,YAAY,OAAO,cAAc,KAAK,GAAG,EAAE;CACjD,MAAM,QACL,KAAK,UAAU,KAAA,KAAa,iBAAiB,SAAS,KAAK,MAAM,MAAM,IACpE,KAAK,QACL;EAAE,QAAQ,KAAK;EAAQ,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Q,WAAW,OACpB,CAAC,EAAE,MACD,SAAS;GACT,IAAI,CAAC,WAAW,OAAO,SAAS,WAAW;IAAE,QAAQ;IAAM;GAAK,CAAC;EAClE,IACC,QAAiB;GAGjB,IAAI,CAAC,WAAW,OAAO,SACtB,YAAY,UAAU;IACrB,QAAQ;IACR,OAAO,QAAQ,GAAG;IAClB,GAAI,KAAK,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,KAAK,KAAK;GACtD,EAAE;EAEJ,CACD;CACD,GACA,CAAC,QAAQ,CACV;CAEA,MAAM,UAAU,kBAAkB;EACjC,IAAI,GAAG;CACR,GAAG,CAAC,KAAK,GAAG,CAAC;CAEb,gBAAgB;EACf,IAAI,GAAG;EACP,aAAa;GACZ,QAAQ,SAAS,MAAM;EACxB;CACD,GAAG,CAAC,KAAK,GAAG,CAAC;CAEb,OAAO;EACN,GAAG;EACH,cAAc,QAAQ,WAAW,aAAa,QAAQ,SAAS,KAAA;EAC/D;CACD;AACD;;;;;AAMA,MAAa,kBAAkB,OAAiC,UAAkC;CACjG,MAAM,WAAW,kBAAkB,OAAO,uBAAO,IAAI,KAAK,CAAC;CAC3D,MAAM,QAAQ,gBAAgB,MAAM,UAAU,SAAS,KAAK;CAC5D,MAAM,QAAQ,gBAAgB,MAAM,UAAU,SAAS,KAAK;CAC5D,MAAM,YAAY,gBAAgB,MAAM,UAAU,SAAS,SAAS;CACpE,MAAM,QAAQ,gBAAgB,MAAM,UAAU,SAAS,KAAK;CAC5D,OAAO;EAAE;EAAO;EAAO;EAAW,OAAO,SAAS,UAAU,OAAO,OAAO;CAAM;AACjF"}
|
|
1
|
+
{"version":3,"file":"useViewQueries.js","names":[],"sources":["../../src/view/useViewQueries.ts"],"sourcesContent":["'use client'\n\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport type { MetricKey } from '../core/contract'\nimport { fetchQuery, type QueryRequest } from '../query/fetchQuery'\nimport type { QueryResponse } from '../query/response'\nimport { autoGranularity, canCompareRange, gate, resolveSource } from './gating'\nimport { coerceState, rangeFor, type ViewState } from './state'\nimport type { AnalyticsViewClientProps } from './viewProps'\n\n/**\n * One section's read. `error` is a `QueryFetchError` whenever the endpoint answered.\n *\n * `data` survives into the next `loading` and into an `error`, so changing the range or\n * hitting a transient failure dims or annotates the chart it already shows instead of\n * blanking it; `isRefetching` is the loading half of that, and is the flag to render a\n * subtle busy affordance on. `status === 'loading'` with no `data` is the only real empty\n * load, and the only one that earns a skeleton. A section that stops being servable at all\n * drops its data, since it belongs to a source or tab the view is no longer showing.\n */\nexport interface QueryState<T> {\n\tstatus: 'loading' | 'ok' | 'error'\n\t/** May be the previous read's answer while `status` is `loading` or `error`. */\n\tdata?: T\n\terror?: Error\n\tisRefetching: boolean\n\trefetch: () => void\n}\n\nexport interface ViewQueries {\n\tcards: QueryState<QueryResponse>\n\ttrend: QueryState<QueryResponse>\n\tbreakdown: QueryState<QueryResponse>\n\t/** Null when the source serves no goal breakdown, so the panel is not rendered at all. */\n\tgoals: QueryState<QueryResponse> | null\n}\n\n/** The four reads a view state implies; a null section is one this source cannot serve. */\nexport interface ViewRequests {\n\tcards: QueryRequest | null\n\ttrend: QueryRequest | null\n\tbreakdown: QueryRequest | null\n\tgoals: QueryRequest | null\n}\n\n/**\n * `QueryState.error.message` for a section with nothing to ask for: the scope has no\n * readable source, or the source serves no metric or dimension the section needs. It is\n * never an endpoint failure, so a caller can tell the two apart without a `QueryFetchError`.\n */\nexport const SECTION_UNAVAILABLE = 'analytics: this source serves no data for this section'\n\nconst NO_REQUESTS: ViewRequests = { cards: null, trend: null, breakdown: null, goals: null }\n\n/**\n * Derives the four reads from the view state and the selected source's capabilities.\n * Pure and total: the state is coerced to what the source serves first, so no request\n * here can carry a metric, dimension, filter, bucket or comparison the endpoint would\n * reject. `now` is injected to keep callers deterministic.\n */\nexport const buildViewRequests = (\n\tprops: AnalyticsViewClientProps,\n\tstate: ViewState,\n\tnow: Date\n): ViewRequests => {\n\tconst source = resolveSource(props.sources, state.source)\n\tif (!source) {\n\t\treturn NO_REQUESTS\n\t}\n\tconst served = gate(source.capabilities)\n\tif (served.metrics.length === 0) {\n\t\treturn NO_REQUESTS\n\t}\n\tconst view = coerceState(state, served)\n\tconst range = rangeFor(view, props.timezone, now)\n\t// The resolved id, not the state's: a stale one in the URL would otherwise ask the\n\t// endpoint for a source that is gone while the gate describes the fallback.\n\tconst shared = {\n\t\tfrom: range.from,\n\t\tto: range.to,\n\t\t...(view.filters.length > 0 ? { filters: view.filters } : {}),\n\t\tsource: source.id,\n\t\ttimezone: props.timezone,\n\t}\n\tconst compare =\n\t\tview.compare && canCompareRange(served, range, { timezone: props.timezone, now })\n\t\t\t? ({ compare: 'previous' } as const)\n\t\t\t: {}\n\tconst breakdownMetrics: MetricKey[] = [\n\t\tview.metric,\n\t\t...(served.metrics.includes('visitors') && view.metric !== 'visitors'\n\t\t\t? (['visitors'] as const)\n\t\t\t: []),\n\t]\n\t// The coerced state only carries a `dim` the tab actually offers, so the picked one can\n\t// be taken as-is and the tab's default is the fallback.\n\tconst dimension = view.dim ?? served.dimensionsFor(view.tab)[0]\n\tconst order: QueryRequest['order'] =\n\t\tview.order !== undefined && breakdownMetrics.includes(view.order.metric)\n\t\t\t? view.order\n\t\t\t: { metric: view.metric, direction: 'desc' }\n\treturn {\n\t\tcards: { metrics: served.metrics, ...shared, ...compare },\n\t\ttrend: {\n\t\t\tmetrics: [view.metric],\n\t\t\t...shared,\n\t\t\tgranularity: view.granularity ?? autoGranularity(range, source.capabilities),\n\t\t\t...compare,\n\t\t},\n\t\tbreakdown:\n\t\t\tdimension === undefined\n\t\t\t\t? null\n\t\t\t\t: {\n\t\t\t\t\t\tmetrics: breakdownMetrics,\n\t\t\t\t\t\tdimensions: [dimension],\n\t\t\t\t\t\t...shared,\n\t\t\t\t\t\tlimit: view.limit,\n\t\t\t\t\t\torder,\n\t\t\t\t\t},\n\t\tgoals: served.goals\n\t\t\t? {\n\t\t\t\t\tmetrics: [\n\t\t\t\t\t\t'conversions',\n\t\t\t\t\t\t...(served.metrics.includes('revenue') ? (['revenue'] as const) : []),\n\t\t\t\t\t\t...(served.metrics.includes('visitors') ? (['visitors'] as const) : []),\n\t\t\t\t\t],\n\t\t\t\t\tdimensions: ['goal'],\n\t\t\t\t\t...shared,\n\t\t\t\t}\n\t\t\t: null,\n\t}\n}\n\nconst asError = (err: unknown): Error => (err instanceof Error ? err : new Error(String(err)))\n\ntype SectionState = Omit<QueryState<QueryResponse>, 'isRefetching' | 'refetch'>\n\n/**\n * Runs one section's read. The request is keyed by its serialized form, so a state change\n * that leaves a section's query identical never refetches it, and one that changes it\n * aborts the in-flight read before issuing the new one.\n */\nconst useQuerySection = (\n\tapiRoute: string,\n\trequest: QueryRequest | null\n): QueryState<QueryResponse> => {\n\tconst [section, setSection] = useState<SectionState>({ status: 'loading' })\n\tconst pending = useRef<AbortController | null>(null)\n\tconst key = request === null ? null : JSON.stringify(request)\n\n\tconst run = useCallback(\n\t\t(serialized: string | null) => {\n\t\t\tpending.current?.abort()\n\t\t\tif (serialized === null) {\n\t\t\t\tpending.current = null\n\t\t\t\tsetSection({ status: 'error', error: new Error(SECTION_UNAVAILABLE) })\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst controller = new AbortController()\n\t\t\tpending.current = controller\n\t\t\t// Returning `prev` unchanged makes the first read a no-op update rather than a\n\t\t\t// second render; any later one keeps what is on screen until the answer lands.\n\t\t\tsetSection((prev) =>\n\t\t\t\tprev.status === 'loading'\n\t\t\t\t\t? prev\n\t\t\t\t\t: { status: 'loading', ...(prev.data === undefined ? {} : { data: prev.data }) }\n\t\t\t)\n\t\t\tfetchQuery(apiRoute, JSON.parse(serialized) as QueryRequest, {\n\t\t\t\tsignal: controller.signal,\n\t\t\t}).then(\n\t\t\t\t(data) => {\n\t\t\t\t\tif (!controller.signal.aborted) setSection({ status: 'ok', data })\n\t\t\t\t},\n\t\t\t\t(err: unknown) => {\n\t\t\t\t\t// The failure is reported beside whatever is on screen: a transient 503 on a\n\t\t\t\t\t// refetch shows a retry banner over the last good read instead of a blank panel.\n\t\t\t\t\tif (!controller.signal.aborted) {\n\t\t\t\t\t\tsetSection((prev) => ({\n\t\t\t\t\t\t\tstatus: 'error',\n\t\t\t\t\t\t\terror: asError(err),\n\t\t\t\t\t\t\t...(prev.data === undefined ? {} : { data: prev.data }),\n\t\t\t\t\t\t}))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\t\t},\n\t\t[apiRoute]\n\t)\n\n\tconst refetch = useCallback(() => {\n\t\trun(key)\n\t}, [run, key])\n\n\tuseEffect(() => {\n\t\trun(key)\n\t\treturn () => {\n\t\t\tpending.current?.abort()\n\t\t}\n\t}, [run, key])\n\n\treturn {\n\t\t...section,\n\t\tisRefetching: section.status === 'loading' && section.data !== undefined,\n\t\trefetch,\n\t}\n}\n\n/**\n * The view's four reads for one state, each with its own lifecycle: a section refetches\n * only when its own request changes, and an in-flight read is aborted when it does.\n */\nexport const useViewQueries = (props: AnalyticsViewClientProps, state: ViewState): ViewQueries => {\n\tconst requests = buildViewRequests(props, state, new Date())\n\tconst cards = useQuerySection(props.apiRoute, requests.cards)\n\tconst trend = useQuerySection(props.apiRoute, requests.trend)\n\tconst breakdown = useQuerySection(props.apiRoute, requests.breakdown)\n\tconst goals = useQuerySection(props.apiRoute, requests.goals)\n\treturn { cards, trend, breakdown, goals: requests.goals === null ? null : goals }\n}\n"],"mappings":";;;;;;;;;;;AAkDA,MAAa,sBAAsB;AAEnC,MAAM,cAA4B;CAAE,OAAO;CAAM,OAAO;CAAM,WAAW;CAAM,OAAO;AAAK;;;;;;;AAQ3F,MAAa,qBACZ,OACA,OACA,QACkB;CAClB,MAAM,SAAS,cAAc,MAAM,SAAS,MAAM,MAAM;CACxD,IAAI,CAAC,QACJ,OAAO;CAER,MAAM,SAAS,KAAK,OAAO,YAAY;CACvC,IAAI,OAAO,QAAQ,WAAW,GAC7B,OAAO;CAER,MAAM,OAAO,YAAY,OAAO,MAAM;CAC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KAAA;EAC/D;CACD;AACD;;;;;AAMA,MAAa,kBAAkB,OAAiC,UAAkC;CACjG,MAAM,WAAW,kBAAkB,OAAO,uBAAO,IAAI,KAAK,CAAC;CAC3D,MAAM,QAAQ,gBAAgB,MAAM,UAAU,SAAS,KAAK;CAC5D,MAAM,QAAQ,gBAAgB,MAAM,UAAU,SAAS,KAAK;CAC5D,MAAM,YAAY,gBAAgB,MAAM,UAAU,SAAS,SAAS;CACpE,MAAM,QAAQ,gBAAgB,MAAM,UAAU,SAAS,KAAK;CAC5D,OAAO;EAAE;EAAO;EAAO;EAAW,OAAO,SAAS,UAAU,OAAO,OAAO;CAAM;AACjF"}
|
|
@@ -5,16 +5,20 @@ import { TIMEFRAME_KEYS } from "../translations/metricKeys.js";
|
|
|
5
5
|
import { breakdownSpecBySlug } from "./breakdownTypes.js";
|
|
6
6
|
import { formatRangeCaption, resolveCustomRange } from "./range.js";
|
|
7
7
|
import { readForWidgetBreakdown } from "./readForWidgetBreakdown.js";
|
|
8
|
+
import { widgetFilters } from "./filterField.js";
|
|
8
9
|
import { BarList } from "../charts/BarList.js";
|
|
10
|
+
import { valueLabel } from "../view/labels.js";
|
|
9
11
|
import { formatMetricValue } from "../fields/format.js";
|
|
10
12
|
import { cardStyle, labelStyle } from "./cardChrome.js";
|
|
13
|
+
import { captionWithFilter } from "./filterCaption.js";
|
|
11
14
|
import { viewTabForDimension, widgetViewHref } from "./viewLink.js";
|
|
12
15
|
import { WidgetViewLink } from "./WidgetViewLink.js";
|
|
13
16
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
14
17
|
//#region src/widgets/AnalyticsBreakdownWidget.tsx
|
|
15
18
|
const STATE_KEY = {
|
|
16
19
|
"not-configured": keys.stateNotConfigured,
|
|
17
|
-
unavailable: keys.stateUnavailable
|
|
20
|
+
unavailable: keys.stateUnavailable,
|
|
21
|
+
"filter-unsupported": keys.stateFilterUnsupported
|
|
18
22
|
};
|
|
19
23
|
async function AnalyticsBreakdownWidget(props) {
|
|
20
24
|
const spec = breakdownSpecBySlug(props.widgetSlug);
|
|
@@ -36,6 +40,7 @@ async function AnalyticsBreakdownWidget(props) {
|
|
|
36
40
|
})
|
|
37
41
|
});
|
|
38
42
|
const tab = viewTabForDimension(spec.dimension);
|
|
43
|
+
const filters = widgetFilters(data);
|
|
39
44
|
const result = await readForWidgetBreakdown({
|
|
40
45
|
req: props.req,
|
|
41
46
|
metric,
|
|
@@ -45,6 +50,7 @@ async function AnalyticsBreakdownWidget(props) {
|
|
|
45
50
|
adapterId: data.dataSource,
|
|
46
51
|
now: /* @__PURE__ */ new Date(),
|
|
47
52
|
range: customRange,
|
|
53
|
+
filters,
|
|
48
54
|
...timezone ? { timezone } : {}
|
|
49
55
|
});
|
|
50
56
|
const href = widgetViewHref(props.view, props.req, {
|
|
@@ -52,12 +58,15 @@ async function AnalyticsBreakdownWidget(props) {
|
|
|
52
58
|
timezone: timezone ?? "UTC",
|
|
53
59
|
...customRange ? { range: customRange } : {},
|
|
54
60
|
...result.adapterId ? { source: result.adapterId } : {},
|
|
55
|
-
...tab ? {
|
|
56
|
-
|
|
61
|
+
...tab ? {
|
|
62
|
+
tab,
|
|
63
|
+
dim: spec.dimension
|
|
64
|
+
} : {},
|
|
65
|
+
metric,
|
|
66
|
+
filters
|
|
57
67
|
});
|
|
58
68
|
const locale = props.req.i18n.language ?? "en-US";
|
|
59
|
-
|
|
60
|
-
return /* @__PURE__ */ jsxs("div", {
|
|
69
|
+
if (result.status !== "ok") return /* @__PURE__ */ jsxs("div", {
|
|
61
70
|
className: "analytics-breakdown-widget",
|
|
62
71
|
style: cardStyle,
|
|
63
72
|
children: [
|
|
@@ -65,16 +74,42 @@ async function AnalyticsBreakdownWidget(props) {
|
|
|
65
74
|
style: labelStyle,
|
|
66
75
|
children: title
|
|
67
76
|
}),
|
|
68
|
-
|
|
77
|
+
/* @__PURE__ */ jsx("span", {
|
|
69
78
|
style: { color: "var(--theme-elevation-400)" },
|
|
70
79
|
children: t(STATE_KEY[result.status])
|
|
71
|
-
})
|
|
80
|
+
}),
|
|
81
|
+
/* @__PURE__ */ jsx(WidgetViewLink, {
|
|
82
|
+
href,
|
|
83
|
+
label: t(keys.widgetOpenInView)
|
|
84
|
+
})
|
|
85
|
+
]
|
|
86
|
+
});
|
|
87
|
+
const caption = captionWithFilter(customRange && timezone ? formatRangeCaption(customRange, locale, timezone) : t(TIMEFRAME_KEYS[timeframe]), filters[0], t);
|
|
88
|
+
const emptyKey = () => {
|
|
89
|
+
if (spec.dimension !== "goal") return keys.stateNoBreakdown;
|
|
90
|
+
if (result.goalsUnresolved) return keys.stateGoalsUnresolved;
|
|
91
|
+
return result.noGoals ? keys.stateNoGoals : keys.stateNoBreakdown;
|
|
92
|
+
};
|
|
93
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
94
|
+
className: "analytics-breakdown-widget",
|
|
95
|
+
style: cardStyle,
|
|
96
|
+
children: [
|
|
97
|
+
/* @__PURE__ */ jsx("span", {
|
|
98
|
+
style: labelStyle,
|
|
99
|
+
children: title
|
|
100
|
+
}),
|
|
101
|
+
/* @__PURE__ */ jsx(BarList, {
|
|
72
102
|
data: result.rows.map((row) => ({
|
|
73
|
-
label:
|
|
103
|
+
label: valueLabel({
|
|
104
|
+
dimension: spec.dimension,
|
|
105
|
+
value: row.label,
|
|
106
|
+
provider: result.provider ?? "",
|
|
107
|
+
t
|
|
108
|
+
}),
|
|
74
109
|
value: row.value,
|
|
75
110
|
display: formatMetricValue(metric, row.value, locale)
|
|
76
111
|
})),
|
|
77
|
-
emptyLabel: t(
|
|
112
|
+
emptyLabel: t(emptyKey())
|
|
78
113
|
}),
|
|
79
114
|
/* @__PURE__ */ jsx("span", {
|
|
80
115
|
style: {
|
|
@@ -83,13 +118,27 @@ async function AnalyticsBreakdownWidget(props) {
|
|
|
83
118
|
},
|
|
84
119
|
children: caption
|
|
85
120
|
}),
|
|
86
|
-
result.
|
|
121
|
+
result.clamped ? /* @__PURE__ */ jsx("span", {
|
|
87
122
|
style: {
|
|
88
123
|
fontSize: "0.6875rem",
|
|
89
124
|
color: "var(--theme-elevation-400)"
|
|
90
125
|
},
|
|
91
126
|
children: t(keys.stateClamped)
|
|
92
127
|
}) : null,
|
|
128
|
+
result.filtersUnapplied ? /* @__PURE__ */ jsx("span", {
|
|
129
|
+
style: {
|
|
130
|
+
fontSize: "0.6875rem",
|
|
131
|
+
color: "var(--theme-elevation-400)"
|
|
132
|
+
},
|
|
133
|
+
children: t(keys.stateFiltersUnapplied)
|
|
134
|
+
}) : null,
|
|
135
|
+
result.sampled ? /* @__PURE__ */ jsx("span", {
|
|
136
|
+
style: {
|
|
137
|
+
fontSize: "0.6875rem",
|
|
138
|
+
color: "var(--theme-elevation-400)"
|
|
139
|
+
},
|
|
140
|
+
children: t(keys.stateSampled)
|
|
141
|
+
}) : null,
|
|
93
142
|
/* @__PURE__ */ jsx(WidgetViewLink, {
|
|
94
143
|
href,
|
|
95
144
|
label: t(keys.widgetOpenInView)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AnalyticsBreakdownWidget.js","names":[],"sources":["../../src/widgets/AnalyticsBreakdownWidget.tsx"],"sourcesContent":["import type { WidgetServerProps } from 'payload'\nimport { BarList } from '../charts/BarList'\nimport type { MetricKey } from '../core/contract'\nimport { formatMetricValue } from '../fields/format'\nimport { requestTimezone } from '../plugin/runtime'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { asTranslate } from '../translations/server'\nimport { type BreakdownWidgetData, breakdownSpecBySlug } from './breakdownTypes'\nimport { cardStyle, labelStyle } from './cardChrome'\nimport { formatRangeCaption, resolveCustomRange } from './range'\nimport type { WidgetReadStatus } from './readForWidget'\nimport { readForWidgetBreakdown } from './readForWidgetBreakdown'\nimport { viewTabForDimension, type WidgetViewProps, widgetViewHref } from './viewLink'\nimport { WidgetViewLink } from './WidgetViewLink'\n\nconst STATE_KEY: Record<Exclude<WidgetReadStatus, 'ok'>, TranslationKey> = {\n\t'not-configured': keys.stateNotConfigured,\n\tunavailable: keys.stateUnavailable,\n}\n\nexport default async function AnalyticsBreakdownWidget(props: WidgetServerProps & WidgetViewProps) {\n\tconst spec = breakdownSpecBySlug(props.widgetSlug)\n\tconst t = asTranslate(props.req.i18n.t)\n\tconst data = (props.widgetData ?? {}) as BreakdownWidgetData\n\tconst metric: MetricKey = data.metric ?? 'pageviews'\n\tconst rawTimeframe = data.timeframe ?? 'last30days'\n\t// Only a custom range needs the reporting timezone before the read; a preset window\n\t// resolves inside the read path, which resolves the timezone there as it always has.\n\tconst timezone = rawTimeframe === 'custom' ? await requestTimezone(props.req) : undefined\n\tconst customRange = timezone ? resolveCustomRange(rawTimeframe, data.range, timezone) : undefined\n\tconst timeframe: TimeframePreset = rawTimeframe === 'custom' ? 'last30days' : rawTimeframe\n\tconst limit = data.limit ?? 5\n\tconst title = data.title?.trim() || (spec ? t(spec.label) : '')\n\n\tif (!spec) {\n\t\treturn (\n\t\t\t<div className=\"analytics-breakdown-widget\" style={cardStyle}>\n\t\t\t\t<span style={{ color: 'var(--theme-elevation-400)' }}>{t(keys.stateUnavailable)}</span>\n\t\t\t</div>\n\t\t)\n\t}\n\n\tconst tab = viewTabForDimension(spec.dimension)\n\tconst result = await readForWidgetBreakdown({\n\t\treq: props.req,\n\t\tmetric,\n\t\tdimension: spec.dimension,\n\t\ttimeframe,\n\t\tlimit,\n\t\tadapterId: data.dataSource,\n\t\tnow: new Date(),\n\t\trange: customRange,\n\t\t...(timezone ? { timezone } : {}),\n\t})\n\t// The adapter that answered, which on a scoped or runtime-provider install is not the\n\t// id the widget asked for.\n\tconst href = widgetViewHref(props.view, props.req, {\n\t\ttimeframe: rawTimeframe,\n\t\ttimezone: timezone ?? DEFAULT_TIMEZONE,\n\t\t...(customRange ? { range: customRange } : {}),\n\t\t...(result.adapterId ? { source: result.adapterId } : {}),\n\t\t...(tab ? { tab } : {}),\n\t\tmetric,\n\t})\n\n\tconst locale = props.req.i18n.language ?? 'en-US'\n\
|
|
1
|
+
{"version":3,"file":"AnalyticsBreakdownWidget.js","names":[],"sources":["../../src/widgets/AnalyticsBreakdownWidget.tsx"],"sourcesContent":["import type { WidgetServerProps } from 'payload'\nimport { BarList } from '../charts/BarList'\nimport type { MetricKey } from '../core/contract'\nimport { formatMetricValue } from '../fields/format'\nimport { requestTimezone } from '../plugin/runtime'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { asTranslate } from '../translations/server'\nimport { valueLabel } from '../view/labels'\nimport { type BreakdownWidgetData, breakdownSpecBySlug } from './breakdownTypes'\nimport { cardStyle, labelStyle } from './cardChrome'\nimport { captionWithFilter } from './filterCaption'\nimport { widgetFilters } from './filterField'\nimport { formatRangeCaption, resolveCustomRange } from './range'\nimport type { WidgetReadStatus } from './readForWidget'\nimport { readForWidgetBreakdown } from './readForWidgetBreakdown'\nimport { viewTabForDimension, type WidgetViewProps, widgetViewHref } from './viewLink'\nimport { WidgetViewLink } from './WidgetViewLink'\n\nconst STATE_KEY: Record<Exclude<WidgetReadStatus, 'ok'>, TranslationKey> = {\n\t'not-configured': keys.stateNotConfigured,\n\tunavailable: keys.stateUnavailable,\n\t'filter-unsupported': keys.stateFilterUnsupported,\n}\n\nexport default async function AnalyticsBreakdownWidget(props: WidgetServerProps & WidgetViewProps) {\n\tconst spec = breakdownSpecBySlug(props.widgetSlug)\n\tconst t = asTranslate(props.req.i18n.t)\n\tconst data = (props.widgetData ?? {}) as BreakdownWidgetData\n\tconst metric: MetricKey = data.metric ?? 'pageviews'\n\tconst rawTimeframe = data.timeframe ?? 'last30days'\n\t// Only a custom range needs the reporting timezone before the read; a preset window\n\t// resolves inside the read path, which resolves the timezone there as it always has.\n\tconst timezone = rawTimeframe === 'custom' ? await requestTimezone(props.req) : undefined\n\tconst customRange = timezone ? resolveCustomRange(rawTimeframe, data.range, timezone) : undefined\n\tconst timeframe: TimeframePreset = rawTimeframe === 'custom' ? 'last30days' : rawTimeframe\n\tconst limit = data.limit ?? 5\n\tconst title = data.title?.trim() || (spec ? t(spec.label) : '')\n\n\tif (!spec) {\n\t\treturn (\n\t\t\t<div className=\"analytics-breakdown-widget\" style={cardStyle}>\n\t\t\t\t<span style={{ color: 'var(--theme-elevation-400)' }}>{t(keys.stateUnavailable)}</span>\n\t\t\t</div>\n\t\t)\n\t}\n\n\tconst tab = viewTabForDimension(spec.dimension)\n\tconst filters = widgetFilters(data)\n\tconst result = await readForWidgetBreakdown({\n\t\treq: props.req,\n\t\tmetric,\n\t\tdimension: spec.dimension,\n\t\ttimeframe,\n\t\tlimit,\n\t\tadapterId: data.dataSource,\n\t\tnow: new Date(),\n\t\trange: customRange,\n\t\tfilters,\n\t\t...(timezone ? { timezone } : {}),\n\t})\n\t// The adapter that answered, which on a scoped or runtime-provider install is not the\n\t// id the widget asked for.\n\tconst href = widgetViewHref(props.view, props.req, {\n\t\ttimeframe: rawTimeframe,\n\t\ttimezone: timezone ?? DEFAULT_TIMEZONE,\n\t\t...(customRange ? { range: customRange } : {}),\n\t\t...(result.adapterId ? { source: result.adapterId } : {}),\n\t\t...(tab ? { tab, dim: spec.dimension } : {}),\n\t\tmetric,\n\t\tfilters,\n\t})\n\n\tconst locale = props.req.i18n.language ?? 'en-US'\n\n\tif (result.status !== 'ok') {\n\t\treturn (\n\t\t\t<div className=\"analytics-breakdown-widget\" style={cardStyle}>\n\t\t\t\t<span style={labelStyle}>{title}</span>\n\t\t\t\t<span style={{ color: 'var(--theme-elevation-400)' }}>{t(STATE_KEY[result.status])}</span>\n\t\t\t\t<WidgetViewLink href={href} label={t(keys.widgetOpenInView)} />\n\t\t\t</div>\n\t\t)\n\t}\n\n\tconst windowCaption =\n\t\tcustomRange && timezone\n\t\t\t? formatRangeCaption(customRange, locale, timezone)\n\t\t\t: t(TIMEFRAME_KEYS[timeframe])\n\tconst caption = captionWithFilter(windowCaption, filters[0], t)\n\t// A goal read has three empty states: the source could not answer about the goals, the\n\t// scope configures none, or nobody converted. The plain one reads as the last of them.\n\tconst emptyKey = (): TranslationKey => {\n\t\tif (spec.dimension !== 'goal') {\n\t\t\treturn keys.stateNoBreakdown\n\t\t}\n\t\tif (result.goalsUnresolved) {\n\t\t\treturn keys.stateGoalsUnresolved\n\t\t}\n\t\treturn result.noGoals ? keys.stateNoGoals : keys.stateNoBreakdown\n\t}\n\treturn (\n\t\t<div className=\"analytics-breakdown-widget\" style={cardStyle}>\n\t\t\t<span style={labelStyle}>{title}</span>\n\t\t\t<BarList\n\t\t\t\tdata={result.rows.map((row) => ({\n\t\t\t\t\tlabel: valueLabel({\n\t\t\t\t\t\tdimension: spec.dimension,\n\t\t\t\t\t\tvalue: row.label,\n\t\t\t\t\t\tprovider: result.provider ?? '',\n\t\t\t\t\t\tt,\n\t\t\t\t\t}),\n\t\t\t\t\tvalue: row.value,\n\t\t\t\t\tdisplay: formatMetricValue(metric, row.value, locale),\n\t\t\t\t}))}\n\t\t\t\temptyLabel={t(emptyKey())}\n\t\t\t/>\n\t\t\t<span style={{ fontSize: '0.75rem', color: 'var(--theme-elevation-400)' }}>{caption}</span>\n\t\t\t{result.clamped ? (\n\t\t\t\t<span style={{ fontSize: '0.6875rem', color: 'var(--theme-elevation-400)' }}>\n\t\t\t\t\t{t(keys.stateClamped)}\n\t\t\t\t</span>\n\t\t\t) : null}\n\t\t\t{result.filtersUnapplied ? (\n\t\t\t\t<span style={{ fontSize: '0.6875rem', color: 'var(--theme-elevation-400)' }}>\n\t\t\t\t\t{t(keys.stateFiltersUnapplied)}\n\t\t\t\t</span>\n\t\t\t) : null}\n\t\t\t{result.sampled ? (\n\t\t\t\t<span style={{ fontSize: '0.6875rem', color: 'var(--theme-elevation-400)' }}>\n\t\t\t\t\t{t(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OAAO;IAA6B;cAAI;GAAc,CAAA;GACzF,OAAO,UACP,oBAAC,QAAD;IAAM,OAAO;KAAE,UAAU;KAAa,OAAO;IAA6B;cACxE,EAAE,KAAK,YAAY;GACf,CAAA,IACH;GACH,OAAO,mBACP,oBAAC,QAAD;IAAM,OAAO;KAAE,UAAU;KAAa,OAAO;IAA6B;cACxE,EAAE,KAAK,qBAAqB;GACxB,CAAA,IACH;GACH,OAAO,UACP,oBAAC,QAAD;IAAM,OAAO;KAAE,UAAU;KAAa,OAAO;IAA6B;cACxE,EAAE,KAAK,YAAY;GACf,CAAA,IACH;GACJ,oBAAC,gBAAD;IAAsB;IAAM,OAAO,EAAE,KAAK,gBAAgB;GAAI,CAAA;EAC1D;;AAEP"}
|
|
@@ -14,7 +14,8 @@ import { jsx, jsxs } from "react/jsx-runtime";
|
|
|
14
14
|
//#region src/widgets/AnalyticsGoalsWidget.tsx
|
|
15
15
|
const STATE_KEY = {
|
|
16
16
|
"not-configured": keys.stateNotConfigured,
|
|
17
|
-
unavailable: keys.stateUnavailable
|
|
17
|
+
unavailable: keys.stateUnavailable,
|
|
18
|
+
"filter-unsupported": keys.stateFilterUnsupported
|
|
18
19
|
};
|
|
19
20
|
const tableStyle = {
|
|
20
21
|
width: "100%",
|
|
@@ -104,9 +105,12 @@ async function AnalyticsGoalsWidget(props) {
|
|
|
104
105
|
result.status !== "ok" ? /* @__PURE__ */ jsx("span", {
|
|
105
106
|
style: { color: "var(--theme-elevation-400)" },
|
|
106
107
|
children: t(STATE_KEY[result.status])
|
|
108
|
+
}) : result.goalsUnresolved ? /* @__PURE__ */ jsx("span", {
|
|
109
|
+
style: { color: "var(--theme-elevation-400)" },
|
|
110
|
+
children: t(keys.stateGoalsUnresolved)
|
|
107
111
|
}) : result.rows.length === 0 ? /* @__PURE__ */ jsx("span", {
|
|
108
112
|
style: { color: "var(--theme-elevation-400)" },
|
|
109
|
-
children: t(keys.stateNoBreakdown)
|
|
113
|
+
children: t(result.noGoals ? keys.stateNoGoals : keys.stateNoBreakdown)
|
|
110
114
|
}) : /* @__PURE__ */ jsxs("table", {
|
|
111
115
|
style: tableStyle,
|
|
112
116
|
children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [
|
|
@@ -175,6 +179,10 @@ async function AnalyticsGoalsWidget(props) {
|
|
|
175
179
|
style: noteStyle,
|
|
176
180
|
children: t(keys.stateClamped)
|
|
177
181
|
}) : null,
|
|
182
|
+
result.sampled ? /* @__PURE__ */ jsx("span", {
|
|
183
|
+
style: noteStyle,
|
|
184
|
+
children: t(keys.stateSampled)
|
|
185
|
+
}) : null,
|
|
178
186
|
/* @__PURE__ */ jsx(WidgetViewLink, {
|
|
179
187
|
href,
|
|
180
188
|
label: t(keys.widgetOpenInView)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AnalyticsGoalsWidget.js","names":[],"sources":["../../src/widgets/AnalyticsGoalsWidget.tsx"],"sourcesContent":["import type { WidgetServerProps } from 'payload'\nimport type { CSSProperties } from 'react'\nimport { formatMetricValue } from '../fields/format'\nimport { requestTimezone } from '../plugin/runtime'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { METRIC_KEYS, TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { asTranslate } from '../translations/server'\nimport { ComparisonDelta } from './ComparisonDelta'\nimport { cardStyle, labelStyle } from './cardChrome'\nimport { formatRangeCaption, resolveCustomRange } from './range'\nimport type { WidgetReadStatus } from './readForWidget'\nimport { readForWidgetGoals } from './readForWidgetGoals'\nimport { type GoalsWidgetData, resolveGoalRowLimit } from './types'\nimport { type WidgetViewProps, widgetViewHref } from './viewLink'\nimport { WidgetViewLink } from './WidgetViewLink'\n\nconst STATE_KEY: Record<Exclude<WidgetReadStatus, 'ok'>, TranslationKey> = {\n\t'not-configured': keys.stateNotConfigured,\n\tunavailable: keys.stateUnavailable,\n}\n\nconst tableStyle: CSSProperties = {\n\twidth: '100%',\n\tborderCollapse: 'collapse',\n\tfontSize: '0.8125rem',\n\tcolor: 'var(--theme-elevation-800)',\n}\n\nconst headStyle: CSSProperties = {\n\t...labelStyle,\n\ttextAlign: 'left',\n\tpadding: '0 0 0.25rem',\n\tborderBottom: '1px solid var(--theme-elevation-150)',\n}\n\nconst cellStyle: CSSProperties = {\n\tpadding: '0.375rem 0',\n\tborderBottom: '1px solid var(--theme-elevation-100)',\n\ttextAlign: 'left',\n}\n\nconst numericStyle: CSSProperties = { ...cellStyle, textAlign: 'right' }\nconst numericHeadStyle: CSSProperties = { ...headStyle, textAlign: 'right' }\n/** Stands in for a cell the source served no number for, in a column other rows fill. */\nconst MISSING = '-'\n\nconst captionStyle: CSSProperties = { fontSize: '0.75rem', color: 'var(--theme-elevation-400)' }\nconst noteStyle: CSSProperties = { fontSize: '0.6875rem', color: 'var(--theme-elevation-400)' }\n\n/**\n * Conversions per goal over the widget's window, with the period-over-period delta, the\n * share of the site's visitors each goal converted, and revenue as a bare number: a goal's\n * currency is its own, so one formatted column would state a currency the rows do not\n * share. Columns the source cannot fill are left out rather than rendered empty.\n */\nexport default async function AnalyticsGoalsWidget(props: WidgetServerProps & WidgetViewProps) {\n\tconst t = asTranslate(props.req.i18n.t)\n\tconst data = (props.widgetData ?? {}) as GoalsWidgetData\n\tconst rawTimeframe = data.timeframe ?? 'last30days'\n\t// Only a custom range needs the reporting timezone before the read; a preset window\n\t// resolves inside the read path, which resolves the timezone there as it always has.\n\tconst timezone = rawTimeframe === 'custom' ? await requestTimezone(props.req) : undefined\n\tconst customRange = timezone ? resolveCustomRange(rawTimeframe, data.range, timezone) : undefined\n\tconst timeframe: TimeframePreset = rawTimeframe === 'custom' ? 'last30days' : rawTimeframe\n\tconst title = data.title?.trim() || t(keys.widgetGoals)\n\tconst compare = data.compare === true\n\tconst result = await readForWidgetGoals({\n\t\treq: props.req,\n\t\ttimeframe,\n\t\tlimit: resolveGoalRowLimit(data.limit),\n\t\tcompare,\n\t\tadapterId: data.dataSource,\n\t\tnow: new Date(),\n\t\trange: customRange,\n\t\t...(timezone ? { timezone } : {}),\n\t})\n\t// The adapter that answered, which on a scoped or runtime-provider install is not the\n\t// id the widget asked for. The metric rides along because the view's goals tab ranks by\n\t// it: without it the tab opens ranked by the view's default rather than by conversions.\n\tconst href = widgetViewHref(props.view, props.req, {\n\t\ttimeframe: rawTimeframe,\n\t\ttimezone: timezone ?? DEFAULT_TIMEZONE,\n\t\t...(customRange ? { range: customRange } : {}),\n\t\t...(result.adapterId ? { source: result.adapterId } : {}),\n\t\tmetric: 'conversions',\n\t\tcompare,\n\t\ttab: 'goals',\n\t})\n\n\tconst locale = props.req.i18n.language ?? 'en-US'\n\tconst caption =\n\t\tcustomRange && timezone\n\t\t\t? formatRangeCaption(customRange, locale, timezone)\n\t\t\t: t(TIMEFRAME_KEYS[timeframe])\n\tconst percent = new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 })\n\tconst showsRate = result.rows.some((row) => row.rate !== undefined)\n\tconst showsRevenue = result.rows.some((row) => row.revenue !== undefined)\n\n\treturn (\n\t\t<div className=\"analytics-goals-widget\" style={cardStyle}>\n\t\t\t<span style={labelStyle}>{title}</span>\n\t\t\t{result.status !== 'ok' ? (\n\t\t\t\t<span style={{ color: 'var(--theme-elevation-400)' }}>{t(STATE_KEY[result.status])}</span>\n\t\t\t) : result.rows.length === 0 ? (\n\t\t\t\t<span style={{ color: 'var(--theme-elevation-400)' }}>{t(keys.stateNoBreakdown)}</span>\n\t\t\t) : (\n\t\t\t\t<table style={tableStyle}>\n\t\t\t\t\t<thead>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th scope=\"col\" style={headStyle}>\n\t\t\t\t\t\t\t\t{t(keys.fieldGoalLabel)}\n\t\t\t\t\t\t\t</th>\n\t\t\t\t\t\t\t<th scope=\"col\" style={numericHeadStyle}>\n\t\t\t\t\t\t\t\t{t(METRIC_KEYS.conversions)}\n\t\t\t\t\t\t\t</th>\n\t\t\t\t\t\t\t{showsRevenue ? (\n\t\t\t\t\t\t\t\t<th scope=\"col\" style={numericHeadStyle}>\n\t\t\t\t\t\t\t\t\t{t(METRIC_KEYS.revenue)}\n\t\t\t\t\t\t\t\t</th>\n\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t{showsRate ? (\n\t\t\t\t\t\t\t\t<th scope=\"col\" style={numericHeadStyle}>\n\t\t\t\t\t\t\t\t\t{t(keys.viewConversionRate)}\n\t\t\t\t\t\t\t\t</th>\n\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</thead>\n\t\t\t\t\t<tbody>\n\t\t\t\t\t\t{result.rows.map((row) => (\n\t\t\t\t\t\t\t<tr key={row.slug}>\n\t\t\t\t\t\t\t\t<td style={cellStyle}>{row.name}</td>\n\t\t\t\t\t\t\t\t<td style={numericStyle}>\n\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\t\t\tdisplay: 'inline-flex',\n\t\t\t\t\t\t\t\t\t\t\talignItems: 'center',\n\t\t\t\t\t\t\t\t\t\t\tgap: '0.5rem',\n\t\t\t\t\t\t\t\t\t\t\tjustifyContent: 'flex-end',\n\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{formatMetricValue('conversions', row.conversions, locale)}\n\t\t\t\t\t\t\t\t\t\t<ComparisonDelta\n\t\t\t\t\t\t\t\t\t\t\tcurrent={row.conversions}\n\t\t\t\t\t\t\t\t\t\t\tprevious={row.previousConversions}\n\t\t\t\t\t\t\t\t\t\t\tmetric=\"conversions\"\n\t\t\t\t\t\t\t\t\t\t\tlocale={locale}\n\t\t\t\t\t\t\t\t\t\t\tt={t}\n\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t{showsRevenue ? (\n\t\t\t\t\t\t\t\t\t<td style={numericStyle}>\n\t\t\t\t\t\t\t\t\t\t{row.revenue === undefined\n\t\t\t\t\t\t\t\t\t\t\t? MISSING\n\t\t\t\t\t\t\t\t\t\t\t: formatMetricValue('revenue', row.revenue, locale)}\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t\t{showsRate ? (\n\t\t\t\t\t\t\t\t\t<td style={numericStyle}>\n\t\t\t\t\t\t\t\t\t\t{row.rate === undefined ? MISSING : percent.format(row.rate)}\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t))}\n\t\t\t\t\t</tbody>\n\t\t\t\t</table>\n\t\t\t)}\n\t\t\t<span style={captionStyle}>{caption}</span>\n\t\t\t{result.stale ? <span style={noteStyle}>{t(keys.viewStale)}</span> : null}\n\t\t\t{result.clamped ? <span style={noteStyle}>{t(keys.stateClamped)}</span> : null}\n\t\t\t<WidgetViewLink href={href} label={t(keys.widgetOpenInView)} />\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;AAkBA,MAAM,YAAqE;CAC1E,kBAAkB,KAAK;CACvB,aAAa,KAAK;AACnB;AAEA,MAAM,aAA4B;CACjC,OAAO;CACP,gBAAgB;CAChB,UAAU;CACV,OAAO;AACR;AAEA,MAAM,YAA2B;CAChC,GAAG;CACH,WAAW;CACX,SAAS;CACT,cAAc;AACf;AAEA,MAAM,YAA2B;CAChC,SAAS;CACT,cAAc;CACd,WAAW;AACZ;AAEA,MAAM,eAA8B;CAAE,GAAG;CAAW,WAAW;AAAQ;AACvE,MAAM,mBAAkC;CAAE,GAAG;CAAW,WAAW;AAAQ;;AAE3E,MAAM,UAAU;AAEhB,MAAM,eAA8B;CAAE,UAAU;CAAW,OAAO;AAA6B;AAC/F,MAAM,YAA2B;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YAAY,KAAA,IACd,UACA,kBAAkB,WAAW,IAAI,SAAS,MAAM;KAChD,CAAA,IACD;KACH,YACA,oBAAC,MAAD;MAAI,OAAO;gBACT,IAAI,SAAS,KAAA,IAAY,UAAU,QAAQ,OAAO,IAAI,IAAI;KACxD,CAAA,IACD;IACD,EAAA,GAjCK,IAAI,IAiCT,CACJ,EACK,CAAA,CACD;;GAER,oBAAC,QAAD;IAAM,OAAO;cAAe;GAAc,CAAA;GACzC,OAAO,QAAQ,oBAAC,QAAD;IAAM,OAAO;cAAY,EAAE,KAAK,SAAS;GAAQ,CAAA,IAAI;GACpE,OAAO,UAAU,oBAAC,QAAD;IAAM,OAAO;cAAY,EAAE,KAAK,YAAY;GAAQ,CAAA,IAAI;GAC1E,oBAAC,gBAAD;IAAsB;IAAM,OAAO,EAAE,KAAK,gBAAgB;GAAI,CAAA;EAC1D;;AAEP"}
|
|
1
|
+
{"version":3,"file":"AnalyticsGoalsWidget.js","names":[],"sources":["../../src/widgets/AnalyticsGoalsWidget.tsx"],"sourcesContent":["import type { WidgetServerProps } from 'payload'\nimport type { CSSProperties } from 'react'\nimport { formatMetricValue } from '../fields/format'\nimport { requestTimezone } from '../plugin/runtime'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { METRIC_KEYS, TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { asTranslate } from '../translations/server'\nimport { ComparisonDelta } from './ComparisonDelta'\nimport { cardStyle, labelStyle } from './cardChrome'\nimport { formatRangeCaption, resolveCustomRange } from './range'\nimport type { WidgetReadStatus } from './readForWidget'\nimport { readForWidgetGoals } from './readForWidgetGoals'\nimport { type GoalsWidgetData, resolveGoalRowLimit } from './types'\nimport { type WidgetViewProps, widgetViewHref } from './viewLink'\nimport { WidgetViewLink } from './WidgetViewLink'\n\n// The goals widget carries no filter, so `filter-unsupported` is unreachable here; the map\n// stays total so the status union cannot grow without every widget answering for it.\nconst STATE_KEY: Record<Exclude<WidgetReadStatus, 'ok'>, TranslationKey> = {\n\t'not-configured': keys.stateNotConfigured,\n\tunavailable: keys.stateUnavailable,\n\t'filter-unsupported': keys.stateFilterUnsupported,\n}\n\nconst tableStyle: CSSProperties = {\n\twidth: '100%',\n\tborderCollapse: 'collapse',\n\tfontSize: '0.8125rem',\n\tcolor: 'var(--theme-elevation-800)',\n}\n\nconst headStyle: CSSProperties = {\n\t...labelStyle,\n\ttextAlign: 'left',\n\tpadding: '0 0 0.25rem',\n\tborderBottom: '1px solid var(--theme-elevation-150)',\n}\n\nconst cellStyle: CSSProperties = {\n\tpadding: '0.375rem 0',\n\tborderBottom: '1px solid var(--theme-elevation-100)',\n\ttextAlign: 'left',\n}\n\nconst numericStyle: CSSProperties = { ...cellStyle, textAlign: 'right' }\nconst numericHeadStyle: CSSProperties = { ...headStyle, textAlign: 'right' }\n/** Stands in for a cell the source served no number for, in a column other rows fill. */\nconst MISSING = '-'\n\nconst captionStyle: CSSProperties = { fontSize: '0.75rem', color: 'var(--theme-elevation-400)' }\nconst noteStyle: CSSProperties = { fontSize: '0.6875rem', color: 'var(--theme-elevation-400)' }\n\n/**\n * Conversions per goal over the widget's window, with the period-over-period delta, the\n * share of the site's visitors each goal converted, and revenue as a bare number: a goal's\n * currency is its own, so one formatted column would state a currency the rows do not\n * share. Columns the source cannot fill are left out rather than rendered empty.\n */\nexport default async function AnalyticsGoalsWidget(props: WidgetServerProps & WidgetViewProps) {\n\tconst t = asTranslate(props.req.i18n.t)\n\tconst data = (props.widgetData ?? {}) as GoalsWidgetData\n\tconst rawTimeframe = data.timeframe ?? 'last30days'\n\t// Only a custom range needs the reporting timezone before the read; a preset window\n\t// resolves inside the read path, which resolves the timezone there as it always has.\n\tconst timezone = rawTimeframe === 'custom' ? await requestTimezone(props.req) : undefined\n\tconst customRange = timezone ? resolveCustomRange(rawTimeframe, data.range, timezone) : undefined\n\tconst timeframe: TimeframePreset = rawTimeframe === 'custom' ? 'last30days' : rawTimeframe\n\tconst title = data.title?.trim() || t(keys.widgetGoals)\n\tconst compare = data.compare === true\n\tconst result = await readForWidgetGoals({\n\t\treq: props.req,\n\t\ttimeframe,\n\t\tlimit: resolveGoalRowLimit(data.limit),\n\t\tcompare,\n\t\tadapterId: data.dataSource,\n\t\tnow: new Date(),\n\t\trange: customRange,\n\t\t...(timezone ? { timezone } : {}),\n\t})\n\t// The adapter that answered, which on a scoped or runtime-provider install is not the\n\t// id the widget asked for. The metric rides along because the view's goals tab ranks by\n\t// it: without it the tab opens ranked by the view's default rather than by conversions.\n\tconst href = widgetViewHref(props.view, props.req, {\n\t\ttimeframe: rawTimeframe,\n\t\ttimezone: timezone ?? DEFAULT_TIMEZONE,\n\t\t...(customRange ? { range: customRange } : {}),\n\t\t...(result.adapterId ? { source: result.adapterId } : {}),\n\t\tmetric: 'conversions',\n\t\tcompare,\n\t\ttab: 'goals',\n\t})\n\n\tconst locale = props.req.i18n.language ?? 'en-US'\n\tconst caption =\n\t\tcustomRange && timezone\n\t\t\t? formatRangeCaption(customRange, locale, timezone)\n\t\t\t: t(TIMEFRAME_KEYS[timeframe])\n\tconst percent = new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 })\n\tconst showsRate = result.rows.some((row) => row.rate !== undefined)\n\tconst showsRevenue = result.rows.some((row) => row.revenue !== undefined)\n\n\treturn (\n\t\t<div className=\"analytics-goals-widget\" style={cardStyle}>\n\t\t\t<span style={labelStyle}>{title}</span>\n\t\t\t{result.status !== 'ok' ? (\n\t\t\t\t<span style={{ color: 'var(--theme-elevation-400)' }}>{t(STATE_KEY[result.status])}</span>\n\t\t\t) : result.goalsUnresolved ? (\n\t\t\t\t// The source never answered about the goals, which the plain empty state would\n\t\t\t\t// read as \"nobody converted\".\n\t\t\t\t<span style={{ color: 'var(--theme-elevation-400)' }}>{t(keys.stateGoalsUnresolved)}</span>\n\t\t\t) : result.rows.length === 0 ? (\n\t\t\t\t// A scope that configures no goals has nothing to convert on, which is a setup\n\t\t\t\t// step rather than a window in which nobody converted.\n\t\t\t\t<span style={{ color: 'var(--theme-elevation-400)' }}>\n\t\t\t\t\t{t(result.noGoals ? keys.stateNoGoals : keys.stateNoBreakdown)}\n\t\t\t\t</span>\n\t\t\t) : (\n\t\t\t\t<table style={tableStyle}>\n\t\t\t\t\t<thead>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th scope=\"col\" style={headStyle}>\n\t\t\t\t\t\t\t\t{t(keys.fieldGoalLabel)}\n\t\t\t\t\t\t\t</th>\n\t\t\t\t\t\t\t<th scope=\"col\" style={numericHeadStyle}>\n\t\t\t\t\t\t\t\t{t(METRIC_KEYS.conversions)}\n\t\t\t\t\t\t\t</th>\n\t\t\t\t\t\t\t{showsRevenue ? (\n\t\t\t\t\t\t\t\t<th scope=\"col\" style={numericHeadStyle}>\n\t\t\t\t\t\t\t\t\t{t(METRIC_KEYS.revenue)}\n\t\t\t\t\t\t\t\t</th>\n\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t{showsRate ? (\n\t\t\t\t\t\t\t\t<th scope=\"col\" style={numericHeadStyle}>\n\t\t\t\t\t\t\t\t\t{t(keys.viewConversionRate)}\n\t\t\t\t\t\t\t\t</th>\n\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</thead>\n\t\t\t\t\t<tbody>\n\t\t\t\t\t\t{result.rows.map((row) => (\n\t\t\t\t\t\t\t<tr key={row.slug}>\n\t\t\t\t\t\t\t\t<td style={cellStyle}>{row.name}</td>\n\t\t\t\t\t\t\t\t<td style={numericStyle}>\n\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\t\t\tdisplay: 'inline-flex',\n\t\t\t\t\t\t\t\t\t\t\talignItems: 'center',\n\t\t\t\t\t\t\t\t\t\t\tgap: '0.5rem',\n\t\t\t\t\t\t\t\t\t\t\tjustifyContent: 'flex-end',\n\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{formatMetricValue('conversions', row.conversions, locale)}\n\t\t\t\t\t\t\t\t\t\t<ComparisonDelta\n\t\t\t\t\t\t\t\t\t\t\tcurrent={row.conversions}\n\t\t\t\t\t\t\t\t\t\t\tprevious={row.previousConversions}\n\t\t\t\t\t\t\t\t\t\t\tmetric=\"conversions\"\n\t\t\t\t\t\t\t\t\t\t\tlocale={locale}\n\t\t\t\t\t\t\t\t\t\t\tt={t}\n\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t{showsRevenue ? (\n\t\t\t\t\t\t\t\t\t<td style={numericStyle}>\n\t\t\t\t\t\t\t\t\t\t{row.revenue === undefined\n\t\t\t\t\t\t\t\t\t\t\t? MISSING\n\t\t\t\t\t\t\t\t\t\t\t: formatMetricValue('revenue', row.revenue, locale)}\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t\t{showsRate ? (\n\t\t\t\t\t\t\t\t\t<td style={numericStyle}>\n\t\t\t\t\t\t\t\t\t\t{row.rate === undefined ? MISSING : percent.format(row.rate)}\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t))}\n\t\t\t\t\t</tbody>\n\t\t\t\t</table>\n\t\t\t)}\n\t\t\t<span style={captionStyle}>{caption}</span>\n\t\t\t{result.stale ? <span style={noteStyle}>{t(keys.viewStale)}</span> : null}\n\t\t\t{result.clamped ? <span style={noteStyle}>{t(keys.stateClamped)}</span> : null}\n\t\t\t{result.sampled ? <span style={noteStyle}>{t(keys.stateSampled)}</span> : null}\n\t\t\t<WidgetViewLink href={href} label={t(keys.widgetOpenInView)} />\n\t\t</div>\n\t)\n}\n"],"mappings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gB;GAAI,CAAA;EAC1D;;AAEP"}
|
|
@@ -4,16 +4,19 @@ import { asTranslate } from "../translations/server.js";
|
|
|
4
4
|
import { METRIC_KEYS, TIMEFRAME_KEYS } from "../translations/metricKeys.js";
|
|
5
5
|
import { formatRangeCaption, resolveCustomRange } from "./range.js";
|
|
6
6
|
import { readForWidget } from "./readForWidget.js";
|
|
7
|
+
import { widgetFilters } from "./filterField.js";
|
|
7
8
|
import { formatMetricValue } from "../fields/format.js";
|
|
8
9
|
import { ComparisonDelta } from "./ComparisonDelta.js";
|
|
9
10
|
import { cardStyle, labelStyle } from "./cardChrome.js";
|
|
11
|
+
import { captionWithFilter } from "./filterCaption.js";
|
|
10
12
|
import { widgetViewHref } from "./viewLink.js";
|
|
11
13
|
import { WidgetViewLink } from "./WidgetViewLink.js";
|
|
12
14
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
13
15
|
//#region src/widgets/AnalyticsMetricWidget.tsx
|
|
14
16
|
const STATE_KEY = {
|
|
15
17
|
"not-configured": keys.stateNotConfigured,
|
|
16
|
-
unavailable: keys.stateUnavailable
|
|
18
|
+
unavailable: keys.stateUnavailable,
|
|
19
|
+
"filter-unsupported": keys.stateFilterUnsupported
|
|
17
20
|
};
|
|
18
21
|
async function AnalyticsMetricWidget(props) {
|
|
19
22
|
const data = props.widgetData ?? {};
|
|
@@ -25,7 +28,7 @@ async function AnalyticsMetricWidget(props) {
|
|
|
25
28
|
const t = asTranslate(props.req.i18n.t);
|
|
26
29
|
const locale = props.req.i18n.language ?? "en-US";
|
|
27
30
|
const title = data.title?.trim() || t(METRIC_KEYS[metric]);
|
|
28
|
-
const
|
|
31
|
+
const filters = widgetFilters(data);
|
|
29
32
|
const result = await readForWidget({
|
|
30
33
|
req: props.req,
|
|
31
34
|
metrics: [metric],
|
|
@@ -33,6 +36,7 @@ async function AnalyticsMetricWidget(props) {
|
|
|
33
36
|
adapterId: data.dataSource,
|
|
34
37
|
now: /* @__PURE__ */ new Date(),
|
|
35
38
|
range: customRange,
|
|
39
|
+
filters,
|
|
36
40
|
...timezone ? { timezone } : {}
|
|
37
41
|
});
|
|
38
42
|
const href = widgetViewHref(props.view, props.req, {
|
|
@@ -40,7 +44,8 @@ async function AnalyticsMetricWidget(props) {
|
|
|
40
44
|
timezone: timezone ?? "UTC",
|
|
41
45
|
...customRange ? { range: customRange } : {},
|
|
42
46
|
...result.adapterId ? { source: result.adapterId } : {},
|
|
43
|
-
metric
|
|
47
|
+
metric,
|
|
48
|
+
filters
|
|
44
49
|
});
|
|
45
50
|
if (result.status !== "ok") return /* @__PURE__ */ jsxs("div", {
|
|
46
51
|
className: "analytics-metric-widget",
|
|
@@ -60,6 +65,7 @@ async function AnalyticsMetricWidget(props) {
|
|
|
60
65
|
})
|
|
61
66
|
]
|
|
62
67
|
});
|
|
68
|
+
const caption = captionWithFilter(customRange && timezone ? formatRangeCaption(customRange, locale, timezone) : t(TIMEFRAME_KEYS[timeframe]), filters[0], t);
|
|
63
69
|
const value = result.metrics[metric];
|
|
64
70
|
return /* @__PURE__ */ jsxs("div", {
|
|
65
71
|
className: "analytics-metric-widget",
|
|
@@ -99,6 +105,27 @@ async function AnalyticsMetricWidget(props) {
|
|
|
99
105
|
},
|
|
100
106
|
children: t(keys.stateClamped)
|
|
101
107
|
}) : null,
|
|
108
|
+
result.filtersUnapplied ? /* @__PURE__ */ jsx("span", {
|
|
109
|
+
style: {
|
|
110
|
+
fontSize: "0.6875rem",
|
|
111
|
+
color: "var(--theme-elevation-400)"
|
|
112
|
+
},
|
|
113
|
+
children: t(keys.stateFiltersUnapplied)
|
|
114
|
+
}) : null,
|
|
115
|
+
result.sampled ? /* @__PURE__ */ jsx("span", {
|
|
116
|
+
style: {
|
|
117
|
+
fontSize: "0.6875rem",
|
|
118
|
+
color: "var(--theme-elevation-400)"
|
|
119
|
+
},
|
|
120
|
+
children: t(keys.stateSampled)
|
|
121
|
+
}) : null,
|
|
122
|
+
result.goalsUnresolved || result.noGoals ? /* @__PURE__ */ jsx("span", {
|
|
123
|
+
style: {
|
|
124
|
+
fontSize: "0.6875rem",
|
|
125
|
+
color: "var(--theme-elevation-400)"
|
|
126
|
+
},
|
|
127
|
+
children: t(result.goalsUnresolved ? keys.stateGoalsUnresolved : keys.stateNoGoals)
|
|
128
|
+
}) : null,
|
|
102
129
|
/* @__PURE__ */ jsx(WidgetViewLink, {
|
|
103
130
|
href,
|
|
104
131
|
label: t(keys.widgetOpenInView)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AnalyticsMetricWidget.js","names":[],"sources":["../../src/widgets/AnalyticsMetricWidget.tsx"],"sourcesContent":["import type { WidgetServerProps } from 'payload'\nimport type { MetricKey } from '../core/contract'\nimport { formatMetricValue } from '../fields/format'\nimport { requestTimezone } from '../plugin/runtime'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { METRIC_KEYS, TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { asTranslate } from '../translations/server'\nimport { ComparisonDelta } from './ComparisonDelta'\nimport { cardStyle, labelStyle } from './cardChrome'\nimport { formatRangeCaption, resolveCustomRange } from './range'\nimport { readForWidget, type WidgetReadStatus } from './readForWidget'\nimport type { MetricWidgetData } from './types'\nimport { type WidgetViewProps, widgetViewHref } from './viewLink'\nimport { WidgetViewLink } from './WidgetViewLink'\n\nconst STATE_KEY: Record<Exclude<WidgetReadStatus, 'ok'>, TranslationKey> = {\n\t'not-configured': keys.stateNotConfigured,\n\tunavailable: keys.stateUnavailable,\n}\n\nexport default async function AnalyticsMetricWidget(props: WidgetServerProps & WidgetViewProps) {\n\tconst data = (props.widgetData ?? {}) as MetricWidgetData\n\tconst metric: MetricKey = data.metric ?? 'pageviews'\n\tconst rawTimeframe = data.timeframe ?? 'last30days'\n\t// Only a custom range needs the reporting timezone before the read; a preset window\n\t// resolves inside the read path, which resolves the timezone there as it always has.\n\tconst timezone = rawTimeframe === 'custom' ? await requestTimezone(props.req) : undefined\n\tconst customRange = timezone ? resolveCustomRange(rawTimeframe, data.range, timezone) : undefined\n\tconst timeframe: TimeframePreset = rawTimeframe === 'custom' ? 'last30days' : rawTimeframe\n\tconst t = asTranslate(props.req.i18n.t)\n\tconst locale = props.req.i18n.language ?? 'en-US'\n\tconst title = data.title?.trim() || t(METRIC_KEYS[metric])\n\tconst
|
|
1
|
+
{"version":3,"file":"AnalyticsMetricWidget.js","names":[],"sources":["../../src/widgets/AnalyticsMetricWidget.tsx"],"sourcesContent":["import type { WidgetServerProps } from 'payload'\nimport type { MetricKey } from '../core/contract'\nimport { formatMetricValue } from '../fields/format'\nimport { requestTimezone } from '../plugin/runtime'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { METRIC_KEYS, TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { asTranslate } from '../translations/server'\nimport { ComparisonDelta } from './ComparisonDelta'\nimport { cardStyle, labelStyle } from './cardChrome'\nimport { captionWithFilter } from './filterCaption'\nimport { widgetFilters } from './filterField'\nimport { formatRangeCaption, resolveCustomRange } from './range'\nimport { readForWidget, type WidgetReadStatus } from './readForWidget'\nimport type { MetricWidgetData } from './types'\nimport { type WidgetViewProps, widgetViewHref } from './viewLink'\nimport { WidgetViewLink } from './WidgetViewLink'\n\nconst STATE_KEY: Record<Exclude<WidgetReadStatus, 'ok'>, TranslationKey> = {\n\t'not-configured': keys.stateNotConfigured,\n\tunavailable: keys.stateUnavailable,\n\t'filter-unsupported': keys.stateFilterUnsupported,\n}\n\nexport default async function AnalyticsMetricWidget(props: WidgetServerProps & WidgetViewProps) {\n\tconst data = (props.widgetData ?? {}) as MetricWidgetData\n\tconst metric: MetricKey = data.metric ?? 'pageviews'\n\tconst rawTimeframe = data.timeframe ?? 'last30days'\n\t// Only a custom range needs the reporting timezone before the read; a preset window\n\t// resolves inside the read path, which resolves the timezone there as it always has.\n\tconst timezone = rawTimeframe === 'custom' ? await requestTimezone(props.req) : undefined\n\tconst customRange = timezone ? resolveCustomRange(rawTimeframe, data.range, timezone) : undefined\n\tconst timeframe: TimeframePreset = rawTimeframe === 'custom' ? 'last30days' : rawTimeframe\n\tconst t = asTranslate(props.req.i18n.t)\n\tconst locale = props.req.i18n.language ?? 'en-US'\n\tconst title = data.title?.trim() || t(METRIC_KEYS[metric])\n\tconst filters = widgetFilters(data)\n\tconst result = await readForWidget({\n\t\treq: props.req,\n\t\tmetrics: [metric],\n\t\ttimeframe,\n\t\tadapterId: data.dataSource,\n\t\tnow: new Date(),\n\t\trange: customRange,\n\t\tfilters,\n\t\t...(timezone ? { timezone } : {}),\n\t})\n\t// The adapter that answered, which on a scoped or runtime-provider install is not the\n\t// id the widget asked for.\n\tconst href = widgetViewHref(props.view, props.req, {\n\t\ttimeframe: rawTimeframe,\n\t\ttimezone: timezone ?? DEFAULT_TIMEZONE,\n\t\t...(customRange ? { range: customRange } : {}),\n\t\t...(result.adapterId ? { source: result.adapterId } : {}),\n\t\tmetric,\n\t\tfilters,\n\t})\n\n\tif (result.status !== 'ok') {\n\t\treturn (\n\t\t\t<div className=\"analytics-metric-widget\" style={cardStyle}>\n\t\t\t\t<span style={labelStyle}>{title}</span>\n\t\t\t\t<span style={{ color: 'var(--theme-elevation-400)' }}>{t(STATE_KEY[result.status])}</span>\n\t\t\t\t<WidgetViewLink href={href} label={t(keys.widgetOpenInView)} />\n\t\t\t</div>\n\t\t)\n\t}\n\n\tconst windowCaption =\n\t\tcustomRange && timezone\n\t\t\t? formatRangeCaption(customRange, locale, timezone)\n\t\t\t: t(TIMEFRAME_KEYS[timeframe])\n\tconst caption = captionWithFilter(windowCaption, filters[0], t)\n\tconst value = result.metrics[metric]\n\treturn (\n\t\t<div className=\"analytics-metric-widget\" style={cardStyle}>\n\t\t\t<span style={labelStyle}>{title}</span>\n\t\t\t<span\n\t\t\t\tstyle={{\n\t\t\t\t\tfontSize: '2rem',\n\t\t\t\t\tfontWeight: 700,\n\t\t\t\t\tlineHeight: 1.1,\n\t\t\t\t\tcolor: 'var(--theme-elevation-800)',\n\t\t\t\t}}\n\t\t\t>\n\t\t\t\t{value === undefined ? '–' : formatMetricValue(metric, value, locale)}\n\t\t\t</span>\n\t\t\t<span style={{ fontSize: '0.75rem', color: 'var(--theme-elevation-400)' }}>{caption}</span>\n\t\t\t{result.comparisonRange ? (\n\t\t\t\t<ComparisonDelta\n\t\t\t\t\tcurrent={value}\n\t\t\t\t\tprevious={result.previousMetrics?.[metric]}\n\t\t\t\t\tmetric={metric}\n\t\t\t\t\tlocale={locale}\n\t\t\t\t\tt={t}\n\t\t\t\t/>\n\t\t\t) : null}\n\t\t\t{result.clamped ? (\n\t\t\t\t<span style={{ fontSize: '0.6875rem', color: 'var(--theme-elevation-400)' }}>\n\t\t\t\t\t{t(keys.stateClamped)}\n\t\t\t\t</span>\n\t\t\t) : null}\n\t\t\t{result.filtersUnapplied ? (\n\t\t\t\t<span style={{ fontSize: '0.6875rem', color: 'var(--theme-elevation-400)' }}>\n\t\t\t\t\t{t(keys.stateFiltersUnapplied)}\n\t\t\t\t</span>\n\t\t\t) : null}\n\t\t\t{result.sampled ? (\n\t\t\t\t<span style={{ fontSize: '0.6875rem', color: 'var(--theme-elevation-400)' }}>\n\t\t\t\t\t{t(keys.stateSampled)}\n\t\t\t\t</span>\n\t\t\t) : null}\n\t\t\t{result.goalsUnresolved || result.noGoals ? (\n\t\t\t\t// A conversions total with no goals behind it is a number about nothing, which\n\t\t\t\t// the plain caption would read as \"nobody converted\".\n\t\t\t\t<span style={{ fontSize: '0.6875rem', color: 'var(--theme-elevation-400)' }}>\n\t\t\t\t\t{t(result.goalsUnresolved ? keys.stateGoalsUnresolved : keys.stateNoGoals)}\n\t\t\t\t</span>\n\t\t\t) : null}\n\t\t\t<WidgetViewLink href={href} label={t(keys.widgetOpenInView)} />\n\t\t</div>\n\t)\n}\n"],"mappings":";;;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AEP"}
|
|
@@ -67,9 +67,11 @@ async function AnalyticsRealtimeWidget(props) {
|
|
|
67
67
|
dataSource: data.dataSource,
|
|
68
68
|
initialActiveNow: result.activeNow,
|
|
69
69
|
initialSeries: result.series,
|
|
70
|
+
initialSampled: result.sampled,
|
|
70
71
|
locale,
|
|
71
72
|
caption,
|
|
72
|
-
pausedLabel: t(keys.widgetRealtimePaused)
|
|
73
|
+
pausedLabel: t(keys.widgetRealtimePaused),
|
|
74
|
+
sampledLabel: t(keys.stateSampled)
|
|
73
75
|
}),
|
|
74
76
|
/* @__PURE__ */ jsx(WidgetViewLink, {
|
|
75
77
|
href,
|