@10x-media/analytics 0.1.0-beta.1 → 0.1.0-beta.2
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 +56 -0
- package/README.md +1 -0
- package/dist/adapters/ga4/ga4.js +17 -7
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/plausible/plausible.js +5 -0
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/posthog.js +28 -17
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.js +1 -1
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/binding/types.d.ts +9 -7
- package/dist/charts/TrendChart.js +17 -8
- package/dist/charts/TrendChart.js.map +1 -1
- package/dist/charts/bucket.js +31 -24
- package/dist/charts/bucket.js.map +1 -1
- package/dist/core/cacheKey.js +4 -7
- package/dist/core/cacheKey.js.map +1 -1
- package/dist/core/contract.d.ts +12 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +27 -2
- package/dist/core/options.js +15 -8
- package/dist/core/options.js.map +1 -1
- package/dist/exports/rsc.d.ts +6 -3
- package/dist/exports/rsc.js +5 -2
- package/dist/fields/AnalyticsPanelClient.js +193 -0
- package/dist/fields/AnalyticsPanelClient.js.map +1 -0
- package/dist/fields/AnalyticsPanelField.d.ts +28 -0
- package/dist/fields/AnalyticsPanelField.js +54 -0
- package/dist/fields/AnalyticsPanelField.js.map +1 -0
- package/dist/fields/AnalyticsStatField.d.ts +1 -1
- package/dist/fields/AnalyticsStatField.js +14 -3
- package/dist/fields/AnalyticsStatField.js.map +1 -1
- package/dist/fields/emptyState.js +46 -0
- package/dist/fields/emptyState.js.map +1 -0
- package/dist/fields/factories.d.ts +10 -2
- package/dist/fields/factories.js +33 -4
- package/dist/fields/factories.js.map +1 -1
- package/dist/fields/readForDocument.d.ts +57 -0
- package/dist/fields/readForDocument.js +50 -10
- package/dist/fields/readForDocument.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +29 -4
- package/dist/index.js.map +1 -1
- package/dist/native/ingest/endpoint.js +5 -2
- package/dist/native/ingest/endpoint.js.map +1 -1
- package/dist/native/ingest/normalizeEvent.js +3 -2
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/ingest/writeEvent.js +2 -1
- package/dist/native/ingest/writeEvent.js.map +1 -1
- package/dist/native/nativeAdapter.js +7 -4
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/rollupAcc.js +9 -6
- package/dist/native/rollupAcc.js.map +1 -1
- package/dist/native/rollups/deltas.js +2 -2
- package/dist/native/rollups/deltas.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +80 -0
- package/dist/plugin/documentEndpoint.js.map +1 -0
- package/dist/plugin/paths.js +11 -0
- package/dist/plugin/paths.js.map +1 -0
- package/dist/plugin/runtime.js +2 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/plugin/warmTask.js +1 -1
- package/dist/surfacing/engine.js +5 -5
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/sync/collection.js +11 -6
- package/dist/sync/collection.js.map +1 -1
- package/dist/sync/syncTask.js +1 -1
- package/dist/timeframe/presets.js +12 -16
- package/dist/timeframe/presets.js.map +1 -1
- package/dist/timeframe/tz.js +110 -0
- package/dist/timeframe/tz.js.map +1 -0
- package/dist/translations/de.js +78 -0
- package/dist/translations/de.js.map +1 -0
- package/dist/translations/en.js +5 -2
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/index.d.ts +2 -1
- package/dist/translations/index.js +6 -2
- package/dist/translations/index.js.map +1 -1
- package/dist/translations/keys.d.ts +5 -2
- package/dist/translations/keys.js +5 -2
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/metricKeys.js +0 -2
- package/dist/translations/metricKeys.js.map +1 -1
- package/dist/widgets/AnalyticsBreakdownWidget.js +1 -1
- package/dist/widgets/AnalyticsMetricWidget.js +9 -1
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +1 -1
- package/dist/widgets/AnalyticsTrendWidget.js +10 -2
- package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
- package/dist/widgets/ComparisonDelta.js +83 -0
- package/dist/widgets/ComparisonDelta.js.map +1 -0
- package/dist/widgets/cardChrome.d.ts +8 -0
- package/dist/widgets/comparison.js +43 -0
- package/dist/widgets/comparison.js.map +1 -0
- package/dist/widgets/readForWidget.d.ts +4 -0
- package/dist/widgets/readForWidget.js +26 -11
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.js +13 -8
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetRealtime.js +1 -1
- package/dist/widgets/readForWidgetRealtime.js.map +1 -1
- package/dist/widgets/readForWidgetSeries.d.ts +6 -0
- package/dist/widgets/readForWidgetSeries.js +60 -40
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/registerWidgets.js +148 -169
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readForWidgetBreakdown.js","names":[],"sources":["../../src/widgets/readForWidgetBreakdown.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, DateRange, DimensionKey, MetricKey } from '../core/contract'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { getRuntime } from '../plugin/runtime'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport type { WidgetReadStatus } from './readForWidget'\n\nexport interface BreakdownRow {\n\tlabel: string\n\tvalue: number\n}\n\nexport interface WidgetBreakdownResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\trows: BreakdownRow[]\n\tclamped?: boolean\n}\n\nexport interface ReadForWidgetBreakdownArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\tdimension: DimensionKey\n\ttimeframe: TimeframePreset\n\tlimit: number\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n}\n\n/**\n * Site-wide ranked breakdown of one metric by one dimension, read through the engine.\n * Mirrors `readForWidget` but gates on the dimension too and maps each result row to a\n * `{ label, value }` pair the bar list renders. The adapter owns sorting and limiting.\n */\nexport const readForWidgetBreakdown = async (\n\targs: ReadForWidgetBreakdownArgs\n): Promise<WidgetBreakdownResult> => {\n\tconst { req, metric, dimension, timeframe, limit, adapterId, now, range } = args\n\tconst
|
|
1
|
+
{"version":3,"file":"readForWidgetBreakdown.js","names":[],"sources":["../../src/widgets/readForWidgetBreakdown.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, DateRange, DimensionKey, MetricKey } from '../core/contract'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { getRuntime, resolveTimezoneFor } from '../plugin/runtime'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport type { WidgetReadStatus } from './readForWidget'\n\nexport interface BreakdownRow {\n\tlabel: string\n\tvalue: number\n}\n\nexport interface WidgetBreakdownResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\trows: BreakdownRow[]\n\tclamped?: boolean\n}\n\nexport interface ReadForWidgetBreakdownArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\tdimension: DimensionKey\n\ttimeframe: TimeframePreset\n\tlimit: number\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n}\n\n/**\n * Site-wide ranked breakdown of one metric by one dimension, read through the engine.\n * Mirrors `readForWidget` but gates on the dimension too and maps each result row to a\n * `{ label, value }` pair the bar list renders. The adapter owns sorting and limiting.\n */\nexport const readForWidgetBreakdown = async (\n\targs: ReadForWidgetBreakdownArgs\n): Promise<WidgetBreakdownResult> => {\n\tconst { req, metric, dimension, timeframe, limit, adapterId, now, range } = args\n\tconst emptyRows = [] as BreakdownRow[]\n\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn {\n\t\t\tstatus: 'unavailable',\n\t\t\tadapterId: adapterId ?? '',\n\t\t\tdateRange: range ?? resolveTimeframe(timeframe, now),\n\t\t\trows: emptyRows,\n\t\t}\n\t}\n\tconst ctx = await resolveReadContext({ runtime, req, adapterId, scope: args.scope })\n\tif (!ctx.ok) {\n\t\treturn {\n\t\t\tstatus: 'unavailable',\n\t\t\tadapterId: adapterId ?? '',\n\t\t\tdateRange: range ?? resolveTimeframe(timeframe, now),\n\t\t\trows: emptyRows,\n\t\t}\n\t}\n\tconst tz = await resolveTimezoneFor(runtime, req, ctx.scope)\n\tconst dateRange = range ?? resolveTimeframe(timeframe, now, tz)\n\tconst base = { dateRange, rows: emptyRows }\n\tconst adapter: AnalyticsAdapter = ctx.adapter\n\tif (!adapter.isConfigured()) {\n\t\treturn { status: 'not-configured', adapterId: adapter.id, ...base }\n\t}\n\tif (\n\t\t!satisfiesCapabilities(adapter.capabilities, { metrics: [metric], dimensions: [dimension] })\n\t) {\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst result = await runtime.engine.read(adapter, {\n\t\tmetrics: [metric],\n\t\tdimensions: [dimension],\n\t\tdateRange,\n\t\tlimit,\n\t\torder: { metric, direction: 'desc' },\n\t\ttimezone: tz,\n\t\tscope: ctx.queryScope,\n\t})\n\tconst rows = result.rows.map((row) => ({\n\t\tlabel: row.dimensions?.[dimension] ?? '(none)',\n\t\tvalue: row.metrics[metric] ?? 0,\n\t}))\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\trows,\n\t\tclamped: result.meta.clamped ?? false,\n\t}\n}\n"],"mappings":";;;;;;;;;;AAuCA,MAAa,yBAAyB,OACrC,SACoC;CACpC,MAAM,EAAE,KAAK,QAAQ,WAAW,WAAW,OAAO,WAAW,KAAK,UAAU;CAC5E,MAAM,YAAY,CAAC;CAEnB,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SACJ,OAAO;EACN,QAAQ;EACR,WAAW,aAAa;EACxB,WAAW,SAAS,iBAAiB,WAAW,GAAG;EACnD,MAAM;CACP;CAED,MAAM,MAAM,MAAM,mBAAmB;EAAE;EAAS;EAAK;EAAW,OAAO,KAAK;CAAM,CAAC;CACnF,IAAI,CAAC,IAAI,IACR,OAAO;EACN,QAAQ;EACR,WAAW,aAAa;EACxB,WAAW,SAAS,iBAAiB,WAAW,GAAG;EACnD,MAAM;CACP;CAED,MAAM,KAAK,MAAM,mBAAmB,SAAS,KAAK,IAAI,KAAK;CAC3D,MAAM,YAAY,SAAS,iBAAiB,WAAW,KAAK,EAAE;CAC9D,MAAM,OAAO;EAAE;EAAW,MAAM;CAAU;CAC1C,MAAM,UAA4B,IAAI;CACtC,IAAI,CAAC,QAAQ,aAAa,GACzB,OAAO;EAAE,QAAQ;EAAkB,WAAW,QAAQ;EAAI,GAAG;CAAK;CAEnE,IACC,CAAC,sBAAsB,QAAQ,cAAc;EAAE,SAAS,CAAC,MAAM;EAAG,YAAY,CAAC,SAAS;CAAE,CAAC,GAE3F,OAAO;EAAE,QAAQ;EAAe,WAAW,QAAQ;EAAI,GAAG;CAAK;CAEhE,MAAM,SAAS,MAAM,QAAQ,OAAO,KAAK,SAAS;EACjD,SAAS,CAAC,MAAM;EAChB,YAAY,CAAC,SAAS;EACtB;EACA;EACA,OAAO;GAAE;GAAQ,WAAW;EAAO;EACnC,UAAU;EACV,OAAO,IAAI;CACZ,CAAC;CACD,MAAM,OAAO,OAAO,KAAK,KAAK,SAAS;EACtC,OAAO,IAAI,aAAa,cAAc;EACtC,OAAO,IAAI,QAAQ,WAAW;CAC/B,EAAE;CACF,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB;EACA;EACA,SAAS,OAAO,KAAK,WAAW;CACjC;AACD"}
|
|
@@ -29,7 +29,7 @@ const readForWidgetRealtime = async (args) => {
|
|
|
29
29
|
const adapter = ctx.adapter;
|
|
30
30
|
if (!adapter.isConfigured()) return empty("not-configured", adapter.id);
|
|
31
31
|
if (!adapter.realtime || !satisfiesCapabilities(adapter.capabilities, { realtime: true })) return empty("unavailable", adapter.id);
|
|
32
|
-
const ttlSeconds =
|
|
32
|
+
const ttlSeconds = runtime.ttl.realtime ?? adapter.capabilities.recommendedTtl.realtime;
|
|
33
33
|
const bucket = Math.floor(now.getTime() / 1e3 / Math.max(1, ttlSeconds));
|
|
34
34
|
const scopeKey = ctx.queryScope === void 0 ? "" : `:${encodeURIComponent(ctx.queryScope)}`;
|
|
35
35
|
const key = `rt:${adapter.id}:${metric}:${windowMinutes}:${bucket}${scopeKey}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readForWidgetRealtime.js","names":[],"sources":["../../src/widgets/readForWidgetRealtime.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, MetricKey } from '../core/contract'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { getRuntime } from '../plugin/runtime'\nimport { kvCacheStore } from '../surfacing/cacheStore'\n\nexport type WidgetRealtimeStatus = 'ok' | 'not-configured' | 'unavailable'\n\nexport interface RealtimePoint {\n\tdate: string\n\tvalue: number\n}\n\nexport interface WidgetRealtimeResult {\n\tstatus: WidgetRealtimeStatus\n\tadapterId: string\n\tactiveNow: number\n\tseries: RealtimePoint[]\n}\n\nexport interface ReadForWidgetRealtimeArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\twindowMinutes: number\n\tadapterId?: string\n\tnow: Date\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n}\n\nconst empty = (status: WidgetRealtimeStatus, adapterId: string): WidgetRealtimeResult => ({\n\tstatus,\n\tadapterId,\n\tactiveNow: 0,\n\tseries: [],\n})\n\n/**\n * Site-wide realtime read for the \"active now\" widget. The window arrives as a\n * dateRange (now - windowMinutes -> now). Cached under a realtime-specific key bucketed\n * to the realtime TTL: it is deliberately NOT routed through the engine, whose key\n * day-snaps the range (so a \"last 30 min\" read would collide with a \"today\" aggregate).\n */\nexport const readForWidgetRealtime = async (\n\targs: ReadForWidgetRealtimeArgs\n): Promise<WidgetRealtimeResult> => {\n\tconst { req, metric, windowMinutes, adapterId, now } = args\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn empty('unavailable', adapterId ?? '')\n\t}\n\tconst ctx = await resolveReadContext({ runtime, req, adapterId, scope: args.scope })\n\tif (!ctx.ok) {\n\t\treturn empty('unavailable', adapterId ?? '')\n\t}\n\tconst adapter: AnalyticsAdapter = ctx.adapter\n\tif (!adapter.isConfigured()) {\n\t\treturn empty('not-configured', adapter.id)\n\t}\n\tif (!adapter.realtime || !satisfiesCapabilities(adapter.capabilities, { realtime: true })) {\n\t\treturn empty('unavailable', adapter.id)\n\t}\n\n\tconst ttlSeconds =
|
|
1
|
+
{"version":3,"file":"readForWidgetRealtime.js","names":[],"sources":["../../src/widgets/readForWidgetRealtime.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, MetricKey } from '../core/contract'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { getRuntime } from '../plugin/runtime'\nimport { kvCacheStore } from '../surfacing/cacheStore'\n\nexport type WidgetRealtimeStatus = 'ok' | 'not-configured' | 'unavailable'\n\nexport interface RealtimePoint {\n\tdate: string\n\tvalue: number\n}\n\nexport interface WidgetRealtimeResult {\n\tstatus: WidgetRealtimeStatus\n\tadapterId: string\n\tactiveNow: number\n\tseries: RealtimePoint[]\n}\n\nexport interface ReadForWidgetRealtimeArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\twindowMinutes: number\n\tadapterId?: string\n\tnow: Date\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n}\n\nconst empty = (status: WidgetRealtimeStatus, adapterId: string): WidgetRealtimeResult => ({\n\tstatus,\n\tadapterId,\n\tactiveNow: 0,\n\tseries: [],\n})\n\n/**\n * Site-wide realtime read for the \"active now\" widget. The window arrives as a\n * dateRange (now - windowMinutes -> now). Cached under a realtime-specific key bucketed\n * to the realtime TTL: it is deliberately NOT routed through the engine, whose key\n * day-snaps the range (so a \"last 30 min\" read would collide with a \"today\" aggregate).\n */\nexport const readForWidgetRealtime = async (\n\targs: ReadForWidgetRealtimeArgs\n): Promise<WidgetRealtimeResult> => {\n\tconst { req, metric, windowMinutes, adapterId, now } = args\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn empty('unavailable', adapterId ?? '')\n\t}\n\tconst ctx = await resolveReadContext({ runtime, req, adapterId, scope: args.scope })\n\tif (!ctx.ok) {\n\t\treturn empty('unavailable', adapterId ?? '')\n\t}\n\tconst adapter: AnalyticsAdapter = ctx.adapter\n\tif (!adapter.isConfigured()) {\n\t\treturn empty('not-configured', adapter.id)\n\t}\n\tif (!adapter.realtime || !satisfiesCapabilities(adapter.capabilities, { realtime: true })) {\n\t\treturn empty('unavailable', adapter.id)\n\t}\n\n\tconst ttlSeconds = runtime.ttl.realtime ?? adapter.capabilities.recommendedTtl.realtime\n\tconst bucket = Math.floor(now.getTime() / 1000 / Math.max(1, ttlSeconds))\n\tconst scopeKey = ctx.queryScope === undefined ? '' : `:${encodeURIComponent(ctx.queryScope)}`\n\tconst key = `rt:${adapter.id}:${metric}:${windowMinutes}:${bucket}${scopeKey}`\n\tconst store = kvCacheStore(req.payload.kv)\n\tconst cached = await store.get<WidgetRealtimeResult>(key)\n\tif (cached) {\n\t\treturn cached\n\t}\n\n\tconst dateRange = { start: new Date(now.getTime() - windowMinutes * 60_000), end: now }\n\tconst result = await adapter.realtime({ metrics: [metric], dateRange, scope: ctx.queryScope }, {})\n\tconst out: WidgetRealtimeResult = {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tactiveNow: result.totals?.[metric] ?? 0,\n\t\tseries: result.rows.map((r) => ({ date: r.timestamp ?? '', value: r.metrics[metric] ?? 0 })),\n\t}\n\tawait store.set(key, out, ttlSeconds)\n\treturn out\n}\n"],"mappings":";;;;;AA+BA,MAAM,SAAS,QAA8B,eAA6C;CACzF;CACA;CACA,WAAW;CACX,QAAQ,CAAC;AACV;;;;;;;AAQA,MAAa,wBAAwB,OACpC,SACmC;CACnC,MAAM,EAAE,KAAK,QAAQ,eAAe,WAAW,QAAQ;CACvD,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SACJ,OAAO,MAAM,eAAe,aAAa,EAAE;CAE5C,MAAM,MAAM,MAAM,mBAAmB;EAAE;EAAS;EAAK;EAAW,OAAO,KAAK;CAAM,CAAC;CACnF,IAAI,CAAC,IAAI,IACR,OAAO,MAAM,eAAe,aAAa,EAAE;CAE5C,MAAM,UAA4B,IAAI;CACtC,IAAI,CAAC,QAAQ,aAAa,GACzB,OAAO,MAAM,kBAAkB,QAAQ,EAAE;CAE1C,IAAI,CAAC,QAAQ,YAAY,CAAC,sBAAsB,QAAQ,cAAc,EAAE,UAAU,KAAK,CAAC,GACvF,OAAO,MAAM,eAAe,QAAQ,EAAE;CAGvC,MAAM,aAAa,QAAQ,IAAI,YAAY,QAAQ,aAAa,eAAe;CAC/E,MAAM,SAAS,KAAK,MAAM,IAAI,QAAQ,IAAI,MAAO,KAAK,IAAI,GAAG,UAAU,CAAC;CACxE,MAAM,WAAW,IAAI,eAAe,KAAA,IAAY,KAAK,IAAI,mBAAmB,IAAI,UAAU;CAC1F,MAAM,MAAM,MAAM,QAAQ,GAAG,GAAG,OAAO,GAAG,cAAc,GAAG,SAAS;CACpE,MAAM,QAAQ,aAAa,IAAI,QAAQ,EAAE;CACzC,MAAM,SAAS,MAAM,MAAM,IAA0B,GAAG;CACxD,IAAI,QACH,OAAO;CAGR,MAAM,YAAY;EAAE,uBAAO,IAAI,KAAK,IAAI,QAAQ,IAAI,gBAAgB,GAAM;EAAG,KAAK;CAAI;CACtF,MAAM,SAAS,MAAM,QAAQ,SAAS;EAAE,SAAS,CAAC,MAAM;EAAG;EAAW,OAAO,IAAI;CAAW,GAAG,CAAC,CAAC;CACjG,MAAM,MAA4B;EACjC,QAAQ;EACR,WAAW,QAAQ;EACnB,WAAW,OAAO,SAAS,WAAW;EACtC,QAAQ,OAAO,KAAK,KAAK,OAAO;GAAE,MAAM,EAAE,aAAa;GAAI,OAAO,EAAE,QAAQ,WAAW;EAAE,EAAE;CAC5F;CACA,MAAM,MAAM,IAAI,KAAK,KAAK,UAAU;CACpC,OAAO;AACR"}
|
|
@@ -12,9 +12,15 @@ interface WidgetSeriesResult {
|
|
|
12
12
|
status: WidgetReadStatus;
|
|
13
13
|
adapterId: string;
|
|
14
14
|
dateRange: DateRange;
|
|
15
|
+
/** Reporting timezone the read resolved in; the trend axis buckets in it. */
|
|
16
|
+
timezone: string;
|
|
15
17
|
points: SeriesPoint[];
|
|
16
18
|
total: number;
|
|
17
19
|
clamped?: boolean;
|
|
20
|
+
/** Previous-window headline total, present only when the adapter supports comparison. */
|
|
21
|
+
previousTotal?: number;
|
|
22
|
+
/** The previous comparable window, present only when comparison ran. */
|
|
23
|
+
comparisonRange?: DateRange;
|
|
18
24
|
}
|
|
19
25
|
interface ReadForWidgetSeriesArgs {
|
|
20
26
|
req: PayloadRequest;
|
|
@@ -1,38 +1,40 @@
|
|
|
1
1
|
import { satisfiesCapabilities } from "../core/capabilities.js";
|
|
2
|
-
import {
|
|
2
|
+
import { supportsGranularity } from "../core/granularity.js";
|
|
3
|
+
import { addDaysInTz, startOfDayInTz, zonedDayIso } from "../timeframe/tz.js";
|
|
4
|
+
import { getRuntime, resolveTimezoneFor } from "../plugin/runtime.js";
|
|
3
5
|
import { resolveReadContext } from "../core/scopedRead.js";
|
|
4
6
|
import { resolveTimeframe } from "../timeframe/presets.js";
|
|
5
|
-
import {
|
|
7
|
+
import { previousWindow } from "./comparison.js";
|
|
6
8
|
//#region src/widgets/readForWidgetSeries.ts
|
|
7
|
-
const DAY_MS = 864e5;
|
|
8
9
|
const MAX_SERIES_DAYS = 366;
|
|
9
|
-
const startOfUtcDay = (d) => new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
|
|
10
10
|
/**
|
|
11
|
-
* Project time-series rows onto a contiguous daily axis, zero-filling gaps.
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* range
|
|
11
|
+
* Project time-series rows onto a contiguous daily axis, zero-filling gaps. Days are
|
|
12
|
+
* counted in `tz` (defaulting to UTC), so a reporting-timezone read aligns each bucket
|
|
13
|
+
* to that zone's midnight. The axis is capped at the most recent `MAX_SERIES_DAYS` so
|
|
14
|
+
* an unbounded range (all time) stays a bounded, drawable sparkline; the headline total
|
|
15
|
+
* still reflects the full range.
|
|
15
16
|
*/
|
|
16
|
-
const fillDailySeries = (
|
|
17
|
-
const
|
|
18
|
-
const
|
|
19
|
-
const
|
|
20
|
-
const
|
|
17
|
+
const fillDailySeries = (args) => {
|
|
18
|
+
const { rows, dateRange, metric } = args;
|
|
19
|
+
const tz = args.tz ?? "UTC";
|
|
20
|
+
const lastDay = startOfDayInTz(dateRange.end, tz);
|
|
21
|
+
const requestedStart = startOfDayInTz(dateRange.start, tz);
|
|
21
22
|
const byDay = /* @__PURE__ */ new Map();
|
|
22
23
|
for (const row of rows) {
|
|
23
24
|
if (!row.timestamp) continue;
|
|
24
|
-
const day =
|
|
25
|
+
const day = zonedDayIso(new Date(row.timestamp), tz);
|
|
25
26
|
byDay.set(day, (byDay.get(day) ?? 0) + (row.metrics[metric] ?? 0));
|
|
26
27
|
}
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
value: byDay.get(date) ?? 0
|
|
33
|
-
});
|
|
28
|
+
const isoDays = [];
|
|
29
|
+
let cursor = lastDay;
|
|
30
|
+
for (let i = 0; i < MAX_SERIES_DAYS && cursor.getTime() >= requestedStart.getTime(); i += 1) {
|
|
31
|
+
isoDays.push(cursor.toISOString());
|
|
32
|
+
cursor = addDaysInTz(cursor, -1, tz);
|
|
34
33
|
}
|
|
35
|
-
return
|
|
34
|
+
return isoDays.reverse().map((date) => ({
|
|
35
|
+
date,
|
|
36
|
+
value: byDay.get(date) ?? 0
|
|
37
|
+
}));
|
|
36
38
|
};
|
|
37
39
|
/**
|
|
38
40
|
* Site-wide time-series read for a trend widget: resolve the timeframe, pick the
|
|
@@ -42,28 +44,30 @@ const fillDailySeries = (rows, dateRange, metric) => {
|
|
|
42
44
|
*/
|
|
43
45
|
const readForWidgetSeries = async (args) => {
|
|
44
46
|
const { req, metric, timeframe, adapterId, now, range } = args;
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
47
|
+
const fallback = (status, id) => ({
|
|
48
|
+
status,
|
|
49
|
+
adapterId: id,
|
|
50
|
+
dateRange: range ?? resolveTimeframe(timeframe, now),
|
|
51
|
+
timezone: "UTC",
|
|
48
52
|
points: [],
|
|
49
53
|
total: 0
|
|
50
|
-
};
|
|
54
|
+
});
|
|
51
55
|
const runtime = getRuntime(req.payload);
|
|
52
|
-
if (!runtime) return
|
|
53
|
-
status: "unavailable",
|
|
54
|
-
adapterId: adapterId ?? "",
|
|
55
|
-
...base
|
|
56
|
-
};
|
|
56
|
+
if (!runtime) return fallback("unavailable", adapterId ?? "");
|
|
57
57
|
const ctx = await resolveReadContext({
|
|
58
58
|
runtime,
|
|
59
59
|
req,
|
|
60
60
|
adapterId,
|
|
61
61
|
scope: args.scope
|
|
62
62
|
});
|
|
63
|
-
if (!ctx.ok) return
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
63
|
+
if (!ctx.ok) return fallback("unavailable", adapterId ?? "");
|
|
64
|
+
const tz = await resolveTimezoneFor(runtime, req, ctx.scope);
|
|
65
|
+
const dateRange = range ?? resolveTimeframe(timeframe, now, tz);
|
|
66
|
+
const base = {
|
|
67
|
+
dateRange,
|
|
68
|
+
timezone: tz,
|
|
69
|
+
points: [],
|
|
70
|
+
total: 0
|
|
67
71
|
};
|
|
68
72
|
const adapter = ctx.adapter;
|
|
69
73
|
if (!adapter.isConfigured()) return {
|
|
@@ -76,22 +80,38 @@ const readForWidgetSeries = async (args) => {
|
|
|
76
80
|
adapterId: adapter.id,
|
|
77
81
|
...base
|
|
78
82
|
};
|
|
79
|
-
const
|
|
83
|
+
const comparisonRange = runtime.comparison && adapter.capabilities.comparison ? previousWindow(dateRange, tz) ?? void 0 : void 0;
|
|
84
|
+
const [result, previous] = await Promise.all([runtime.engine.read(adapter, {
|
|
80
85
|
metrics: [metric],
|
|
81
86
|
dateRange,
|
|
82
87
|
granularity: "day",
|
|
88
|
+
timezone: tz,
|
|
83
89
|
scope: ctx.queryScope
|
|
84
|
-
})
|
|
90
|
+
}), comparisonRange ? runtime.engine.read(adapter, {
|
|
91
|
+
metrics: [metric],
|
|
92
|
+
dateRange: comparisonRange,
|
|
93
|
+
timezone: tz,
|
|
94
|
+
scope: ctx.queryScope
|
|
95
|
+
}) : void 0]);
|
|
96
|
+
const previousTotal = previous ? previous.totals?.[metric] : void 0;
|
|
85
97
|
return {
|
|
86
98
|
status: "ok",
|
|
87
99
|
adapterId: adapter.id,
|
|
88
100
|
dateRange,
|
|
89
|
-
|
|
101
|
+
timezone: tz,
|
|
102
|
+
points: fillDailySeries({
|
|
103
|
+
rows: result.rows,
|
|
104
|
+
dateRange,
|
|
105
|
+
metric,
|
|
106
|
+
tz
|
|
107
|
+
}),
|
|
90
108
|
total: result.totals?.[metric] ?? 0,
|
|
91
|
-
clamped: result.meta.clamped ?? false
|
|
109
|
+
clamped: result.meta.clamped ?? false,
|
|
110
|
+
previousTotal,
|
|
111
|
+
comparisonRange
|
|
92
112
|
};
|
|
93
113
|
};
|
|
94
114
|
//#endregion
|
|
95
|
-
export { readForWidgetSeries };
|
|
115
|
+
export { fillDailySeries, readForWidgetSeries };
|
|
96
116
|
|
|
97
117
|
//# sourceMappingURL=readForWidgetSeries.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readForWidgetSeries.js","names":[],"sources":["../../src/widgets/readForWidgetSeries.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, AnalyticsRow, DateRange, MetricKey } from '../core/contract'\nimport { supportsGranularity } from '../core/granularity'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { getRuntime } from '../plugin/runtime'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport type { WidgetReadStatus } from './readForWidget'\n\nexport interface SeriesPoint {\n\tdate: string\n\tvalue: number\n}\n\nexport interface WidgetSeriesResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\tpoints: SeriesPoint[]\n\ttotal: number\n\tclamped?: boolean\n}\n\nexport interface ReadForWidgetSeriesArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\ttimeframe: TimeframePreset\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n}\n\nconst
|
|
1
|
+
{"version":3,"file":"readForWidgetSeries.js","names":[],"sources":["../../src/widgets/readForWidgetSeries.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, AnalyticsRow, DateRange, MetricKey } from '../core/contract'\nimport { supportsGranularity } from '../core/granularity'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { getRuntime, resolveTimezoneFor } from '../plugin/runtime'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport { addDaysInTz, DEFAULT_TIMEZONE, startOfDayInTz, zonedDayIso } from '../timeframe/tz'\nimport { previousWindow } from './comparison'\nimport type { WidgetReadStatus } from './readForWidget'\n\nexport interface SeriesPoint {\n\tdate: string\n\tvalue: number\n}\n\nexport interface WidgetSeriesResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\t/** Reporting timezone the read resolved in; the trend axis buckets in it. */\n\ttimezone: string\n\tpoints: SeriesPoint[]\n\ttotal: number\n\tclamped?: boolean\n\t/** Previous-window headline total, present only when the adapter supports comparison. */\n\tpreviousTotal?: number\n\t/** The previous comparable window, present only when comparison ran. */\n\tcomparisonRange?: DateRange\n}\n\nexport interface ReadForWidgetSeriesArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\ttimeframe: TimeframePreset\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n}\n\nconst MAX_SERIES_DAYS = 366\n\n/**\n * Project time-series rows onto a contiguous daily axis, zero-filling gaps. Days are\n * counted in `tz` (defaulting to UTC), so a reporting-timezone read aligns each bucket\n * to that zone's midnight. The axis is capped at the most recent `MAX_SERIES_DAYS` so\n * an unbounded range (all time) stays a bounded, drawable sparkline; the headline total\n * still reflects the full range.\n */\nexport const fillDailySeries = (args: {\n\trows: AnalyticsRow[]\n\tdateRange: DateRange\n\tmetric: MetricKey\n\ttz?: string\n}): SeriesPoint[] => {\n\tconst { rows, dateRange, metric } = args\n\tconst tz = args.tz ?? DEFAULT_TIMEZONE\n\tconst lastDay = startOfDayInTz(dateRange.end, tz)\n\tconst requestedStart = startOfDayInTz(dateRange.start, tz)\n\tconst byDay = new Map<string, number>()\n\tfor (const row of rows) {\n\t\tif (!row.timestamp) {\n\t\t\tcontinue\n\t\t}\n\t\tconst day = zonedDayIso(new Date(row.timestamp), tz)\n\t\tbyDay.set(day, (byDay.get(day) ?? 0) + (row.metrics[metric] ?? 0))\n\t}\n\t// Walk calendar days back from the last day so DST-length days never mis-step, capping\n\t// the axis at MAX_SERIES_DAYS or the requested start, whichever is more recent.\n\tconst isoDays: string[] = []\n\tlet cursor = lastDay\n\tfor (let i = 0; i < MAX_SERIES_DAYS && cursor.getTime() >= requestedStart.getTime(); i += 1) {\n\t\tisoDays.push(cursor.toISOString())\n\t\tcursor = addDaysInTz(cursor, -1, tz)\n\t}\n\treturn isoDays.reverse().map((date) => ({ date, value: byDay.get(date) ?? 0 }))\n}\n\n/**\n * Site-wide time-series read for a trend widget: resolve the timeframe, pick the\n * adapter, gate on the metric and day-granularity support, read through the engine,\n * then return a zero-filled daily series plus the headline total. Mirrors\n * `readForWidget` but yields points instead of a single value.\n */\nexport const readForWidgetSeries = async (\n\targs: ReadForWidgetSeriesArgs\n): Promise<WidgetSeriesResult> => {\n\tconst { req, metric, timeframe, adapterId, now, range } = args\n\tconst fallback = (status: WidgetReadStatus, id: string): WidgetSeriesResult => ({\n\t\tstatus,\n\t\tadapterId: id,\n\t\tdateRange: range ?? resolveTimeframe(timeframe, now),\n\t\ttimezone: DEFAULT_TIMEZONE,\n\t\tpoints: [],\n\t\ttotal: 0,\n\t})\n\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn fallback('unavailable', adapterId ?? '')\n\t}\n\tconst ctx = await resolveReadContext({ runtime, req, adapterId, scope: args.scope })\n\tif (!ctx.ok) {\n\t\treturn fallback('unavailable', adapterId ?? '')\n\t}\n\tconst tz = await resolveTimezoneFor(runtime, req, ctx.scope)\n\tconst dateRange = range ?? resolveTimeframe(timeframe, now, tz)\n\tconst base = { dateRange, timezone: tz, points: [] as SeriesPoint[], total: 0 }\n\tconst adapter: AnalyticsAdapter = ctx.adapter\n\tif (!adapter.isConfigured()) {\n\t\treturn { status: 'not-configured', adapterId: adapter.id, ...base }\n\t}\n\tif (\n\t\t!satisfiesCapabilities(adapter.capabilities, { metrics: [metric] }) ||\n\t\t!supportsGranularity(adapter.capabilities, 'day')\n\t) {\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst comparisonRange =\n\t\truntime.comparison && adapter.capabilities.comparison\n\t\t\t? (previousWindow(dateRange, tz) ?? undefined)\n\t\t\t: undefined\n\tconst [result, previous] = await Promise.all([\n\t\truntime.engine.read(adapter, {\n\t\t\tmetrics: [metric],\n\t\t\tdateRange,\n\t\t\tgranularity: 'day',\n\t\t\ttimezone: tz,\n\t\t\tscope: ctx.queryScope,\n\t\t}),\n\t\tcomparisonRange\n\t\t\t? runtime.engine.read(adapter, {\n\t\t\t\t\tmetrics: [metric],\n\t\t\t\t\tdateRange: comparisonRange,\n\t\t\t\t\ttimezone: tz,\n\t\t\t\t\tscope: ctx.queryScope,\n\t\t\t\t})\n\t\t\t: undefined,\n\t])\n\tconst previousTotal = previous ? previous.totals?.[metric] : undefined\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\tpoints: fillDailySeries({ rows: result.rows, dateRange, metric, tz }),\n\t\ttotal: result.totals?.[metric] ?? 0,\n\t\tclamped: result.meta.clamped ?? false,\n\t\tpreviousTotal,\n\t\tcomparisonRange,\n\t}\n}\n"],"mappings":"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"}
|
|
@@ -1,15 +1,64 @@
|
|
|
1
1
|
import { keys } from "../translations/keys.js";
|
|
2
2
|
import { labelForKey } from "../translations/server.js";
|
|
3
3
|
import { satisfiesCapabilities } from "../core/capabilities.js";
|
|
4
|
-
import { en } from "../translations/en.js";
|
|
5
4
|
import { TIMEFRAME_PRESETS } from "../timeframe/presets.js";
|
|
5
|
+
import { METRIC_KEYS, TIMEFRAME_KEYS } from "../translations/metricKeys.js";
|
|
6
|
+
import { de } from "../translations/de.js";
|
|
7
|
+
import { en } from "../translations/en.js";
|
|
6
8
|
import { BREAKDOWN_SPECS } from "./breakdownTypes.js";
|
|
7
9
|
import { WIDGET_METRICS } from "./types.js";
|
|
8
10
|
import { dateRangeField } from "../fields/dateRange/field.js";
|
|
9
|
-
import { METRIC_KEYS, TIMEFRAME_KEYS } from "../translations/metricKeys.js";
|
|
10
11
|
import { buildCustomWidgets } from "./customWidget.js";
|
|
11
12
|
//#region src/widgets/registerWidgets.ts
|
|
13
|
+
/**
|
|
14
|
+
* Select options must carry static labels: `filterOptions` results are serialized
|
|
15
|
+
* into client form state at request time, where a label function cannot cross the
|
|
16
|
+
* server/client boundary.
|
|
17
|
+
*/
|
|
18
|
+
const staticLabel = (key) => ({
|
|
19
|
+
de: de[key],
|
|
20
|
+
en: en[key]
|
|
21
|
+
});
|
|
12
22
|
const widgetIsSupported = (requires, adapters) => !requires || adapters.some((a) => satisfiesCapabilities(a.capabilities, requires));
|
|
23
|
+
/**
|
|
24
|
+
* The widget metric select. Options are limited to metrics at least one configured
|
|
25
|
+
* adapter can serve, mirroring the OR-across-adapters gating used to hide whole widgets;
|
|
26
|
+
* `extra` layers on further requirements (a breakdown widget's dimension, realtime) so
|
|
27
|
+
* the picker never offers a metric the read path would report as unavailable. In
|
|
28
|
+
* multi-provider installs `filterOptions` additionally narrows the picker to the selected
|
|
29
|
+
* `dataSource`'s capabilities; an id not known at config time (a runtime/DB provider)
|
|
30
|
+
* keeps the union. The default clamps to the first option when the preferred metric is
|
|
31
|
+
* not servable, and options can come out empty for exotic adapter sets, which
|
|
32
|
+
* {@link registerWidgets} treats as "skip this widget".
|
|
33
|
+
*/
|
|
34
|
+
const metricSelectField = (candidates, args, opts = {}) => {
|
|
35
|
+
const { extra, preferredDefault = "pageviews" } = opts;
|
|
36
|
+
const supports = (adapter, metric) => satisfiesCapabilities(adapter.capabilities, {
|
|
37
|
+
...extra,
|
|
38
|
+
metrics: [metric]
|
|
39
|
+
});
|
|
40
|
+
const options = candidates.filter((m) => args.adapters.some((a) => supports(a, m))).map((m) => ({
|
|
41
|
+
value: m,
|
|
42
|
+
label: staticLabel(METRIC_KEYS[m])
|
|
43
|
+
}));
|
|
44
|
+
const defaultValue = options.some((o) => o.value === preferredDefault) ? preferredDefault : options[0]?.value;
|
|
45
|
+
const filterOptions = ({ options: opts, siblingData }) => {
|
|
46
|
+
const sourceId = siblingData?.dataSource;
|
|
47
|
+
const adapter = typeof sourceId === "string" ? args.adapters.find((a) => a.id === sourceId) : void 0;
|
|
48
|
+
if (!adapter) return opts;
|
|
49
|
+
return opts.filter((o) => typeof o === "object" && supports(adapter, o.value));
|
|
50
|
+
};
|
|
51
|
+
return {
|
|
52
|
+
name: "metric",
|
|
53
|
+
type: "select",
|
|
54
|
+
required: true,
|
|
55
|
+
...defaultValue !== void 0 ? { defaultValue } : {},
|
|
56
|
+
label: labelForKey(keys.widgetFieldMetric),
|
|
57
|
+
options,
|
|
58
|
+
admin: { isClearable: false },
|
|
59
|
+
...args.multiProvider ? { filterOptions } : {}
|
|
60
|
+
};
|
|
61
|
+
};
|
|
13
62
|
const titleField = (args, placeholder) => ({
|
|
14
63
|
name: "title",
|
|
15
64
|
type: "text",
|
|
@@ -17,174 +66,101 @@ const titleField = (args, placeholder) => ({
|
|
|
17
66
|
...args.localizeText ? { localized: true } : {},
|
|
18
67
|
admin: { placeholder }
|
|
19
68
|
});
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
...f.admin,
|
|
56
|
-
condition: (_data, siblingData) => siblingData?.timeframe === "custom"
|
|
57
|
-
}
|
|
58
|
-
})
|
|
59
|
-
})
|
|
60
|
-
];
|
|
61
|
-
if (args.multiProvider) fields.push({
|
|
62
|
-
name: "dataSource",
|
|
63
|
-
type: "select",
|
|
64
|
-
label: labelForKey(keys.widgetFieldDataSource),
|
|
65
|
-
defaultValue: args.adapters[0]?.id,
|
|
66
|
-
options: args.adapters.map((a) => ({
|
|
67
|
-
value: a.id,
|
|
68
|
-
label: a.label
|
|
69
|
-
}))
|
|
70
|
-
});
|
|
71
|
-
return fields;
|
|
72
|
-
};
|
|
73
|
-
const breakdownWidgetFields = (args, spec) => {
|
|
74
|
-
const fields = [
|
|
75
|
-
titleField(args, en[spec.label]),
|
|
76
|
-
{
|
|
77
|
-
name: "metric",
|
|
78
|
-
type: "select",
|
|
79
|
-
required: true,
|
|
80
|
-
defaultValue: "pageviews",
|
|
81
|
-
label: labelForKey(keys.widgetFieldMetric),
|
|
82
|
-
options: WIDGET_METRICS.map((m) => ({
|
|
83
|
-
value: m,
|
|
84
|
-
label: labelForKey(METRIC_KEYS[m])
|
|
85
|
-
}))
|
|
86
|
-
},
|
|
87
|
-
{
|
|
88
|
-
name: "timeframe",
|
|
89
|
-
type: "select",
|
|
90
|
-
required: true,
|
|
91
|
-
defaultValue: "last30days",
|
|
92
|
-
label: labelForKey(keys.widgetFieldTimeframe),
|
|
93
|
-
options: [...TIMEFRAME_PRESETS.map((p) => ({
|
|
94
|
-
value: p,
|
|
95
|
-
label: labelForKey(TIMEFRAME_KEYS[p])
|
|
96
|
-
})), {
|
|
97
|
-
value: "custom",
|
|
98
|
-
label: labelForKey(keys.widgetTimeframeCustom)
|
|
99
|
-
}]
|
|
100
|
-
},
|
|
101
|
-
dateRangeField({
|
|
102
|
-
name: "range",
|
|
103
|
-
label: labelForKey(keys.widgetFieldRange),
|
|
104
|
-
pickerAppearance: "dayOnly",
|
|
105
|
-
overrides: (f) => ({
|
|
106
|
-
...f,
|
|
107
|
-
admin: {
|
|
108
|
-
...f.admin,
|
|
109
|
-
condition: (_data, siblingData) => siblingData?.timeframe === "custom"
|
|
110
|
-
}
|
|
111
|
-
})
|
|
112
|
-
}),
|
|
113
|
-
{
|
|
114
|
-
name: "limit",
|
|
115
|
-
type: "number",
|
|
116
|
-
defaultValue: 5,
|
|
117
|
-
min: 1,
|
|
118
|
-
max: 20,
|
|
119
|
-
label: labelForKey(keys.widgetFieldLimit)
|
|
120
|
-
}
|
|
121
|
-
];
|
|
122
|
-
if (args.multiProvider) fields.push({
|
|
123
|
-
name: "dataSource",
|
|
124
|
-
type: "select",
|
|
125
|
-
label: labelForKey(keys.widgetFieldDataSource),
|
|
126
|
-
defaultValue: args.adapters[0]?.id,
|
|
127
|
-
options: args.adapters.map((a) => ({
|
|
128
|
-
value: a.id,
|
|
129
|
-
label: a.label
|
|
130
|
-
}))
|
|
131
|
-
});
|
|
132
|
-
return fields;
|
|
133
|
-
};
|
|
134
|
-
const realtimeWidgetFields = (args) => {
|
|
135
|
-
const fields = [
|
|
136
|
-
titleField(args, en[keys.widgetFieldTitlePlaceholder]),
|
|
137
|
-
{
|
|
138
|
-
name: "metric",
|
|
139
|
-
type: "select",
|
|
140
|
-
required: true,
|
|
141
|
-
defaultValue: "visitors",
|
|
142
|
-
label: labelForKey(keys.widgetFieldMetric),
|
|
143
|
-
options: [{
|
|
144
|
-
value: "visitors",
|
|
145
|
-
label: labelForKey(METRIC_KEYS.visitors)
|
|
146
|
-
}, {
|
|
147
|
-
value: "pageviews",
|
|
148
|
-
label: labelForKey(METRIC_KEYS.pageviews)
|
|
149
|
-
}]
|
|
150
|
-
},
|
|
151
|
-
{
|
|
152
|
-
name: "windowMinutes",
|
|
153
|
-
type: "select",
|
|
154
|
-
defaultValue: "30",
|
|
155
|
-
label: labelForKey(keys.widgetFieldWindow),
|
|
156
|
-
options: [
|
|
157
|
-
{
|
|
158
|
-
value: "5",
|
|
159
|
-
label: "5 min"
|
|
160
|
-
},
|
|
161
|
-
{
|
|
162
|
-
value: "15",
|
|
163
|
-
label: "15 min"
|
|
164
|
-
},
|
|
165
|
-
{
|
|
166
|
-
value: "30",
|
|
167
|
-
label: "30 min"
|
|
168
|
-
},
|
|
169
|
-
{
|
|
170
|
-
value: "60",
|
|
171
|
-
label: "60 min"
|
|
172
|
-
}
|
|
173
|
-
]
|
|
69
|
+
const timeframeSelectField = () => ({
|
|
70
|
+
name: "timeframe",
|
|
71
|
+
type: "select",
|
|
72
|
+
required: true,
|
|
73
|
+
defaultValue: "last30days",
|
|
74
|
+
label: labelForKey(keys.widgetFieldTimeframe),
|
|
75
|
+
admin: { isClearable: false },
|
|
76
|
+
options: [...TIMEFRAME_PRESETS.map((p) => ({
|
|
77
|
+
value: p,
|
|
78
|
+
label: labelForKey(TIMEFRAME_KEYS[p])
|
|
79
|
+
})), {
|
|
80
|
+
value: "custom",
|
|
81
|
+
label: labelForKey(keys.widgetTimeframeCustom)
|
|
82
|
+
}]
|
|
83
|
+
});
|
|
84
|
+
const dataSourceField = (args) => ({
|
|
85
|
+
name: "dataSource",
|
|
86
|
+
type: "select",
|
|
87
|
+
label: labelForKey(keys.widgetFieldDataSource),
|
|
88
|
+
defaultValue: args.adapters[0]?.id,
|
|
89
|
+
admin: { isClearable: false },
|
|
90
|
+
options: args.adapters.map((a) => ({
|
|
91
|
+
value: a.id,
|
|
92
|
+
label: a.label
|
|
93
|
+
}))
|
|
94
|
+
});
|
|
95
|
+
const customRangeField = () => dateRangeField({
|
|
96
|
+
name: "range",
|
|
97
|
+
label: labelForKey(keys.widgetFieldRange),
|
|
98
|
+
pickerAppearance: "dayOnly",
|
|
99
|
+
overrides: (f) => ({
|
|
100
|
+
...f,
|
|
101
|
+
admin: {
|
|
102
|
+
...f.admin,
|
|
103
|
+
condition: (_data, siblingData) => siblingData?.timeframe === "custom"
|
|
174
104
|
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
105
|
+
})
|
|
106
|
+
});
|
|
107
|
+
/** The metric select in a widget's field list. */
|
|
108
|
+
const findMetricField = (fields) => fields.find((field) => "name" in field && field.name === "metric");
|
|
109
|
+
const metricWidgetFields = (args) => [
|
|
110
|
+
titleField(args, en[keys.widgetFieldTitlePlaceholder]),
|
|
111
|
+
metricSelectField(WIDGET_METRICS, args),
|
|
112
|
+
timeframeSelectField(),
|
|
113
|
+
customRangeField(),
|
|
114
|
+
...args.multiProvider ? [dataSourceField(args)] : []
|
|
115
|
+
];
|
|
116
|
+
const breakdownWidgetFields = (args, spec) => [
|
|
117
|
+
titleField(args, en[spec.label]),
|
|
118
|
+
metricSelectField(WIDGET_METRICS, args, { extra: { dimensions: [spec.dimension] } }),
|
|
119
|
+
timeframeSelectField(),
|
|
120
|
+
customRangeField(),
|
|
121
|
+
{
|
|
122
|
+
name: "limit",
|
|
123
|
+
type: "number",
|
|
124
|
+
defaultValue: 5,
|
|
125
|
+
min: 1,
|
|
126
|
+
max: 20,
|
|
127
|
+
label: labelForKey(keys.widgetFieldLimit)
|
|
128
|
+
},
|
|
129
|
+
...args.multiProvider ? [dataSourceField(args)] : []
|
|
130
|
+
];
|
|
131
|
+
const realtimeWidgetFields = (args) => [
|
|
132
|
+
titleField(args, en[keys.widgetFieldTitlePlaceholder]),
|
|
133
|
+
metricSelectField(["visitors", "pageviews"], args, {
|
|
134
|
+
extra: { realtime: true },
|
|
135
|
+
preferredDefault: "visitors"
|
|
136
|
+
}),
|
|
137
|
+
{
|
|
138
|
+
name: "windowMinutes",
|
|
178
139
|
type: "select",
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
140
|
+
defaultValue: "30",
|
|
141
|
+
label: labelForKey(keys.widgetFieldWindow),
|
|
142
|
+
admin: { isClearable: false },
|
|
143
|
+
options: [
|
|
144
|
+
{
|
|
145
|
+
value: "5",
|
|
146
|
+
label: "5 min"
|
|
147
|
+
},
|
|
148
|
+
{
|
|
149
|
+
value: "15",
|
|
150
|
+
label: "15 min"
|
|
151
|
+
},
|
|
152
|
+
{
|
|
153
|
+
value: "30",
|
|
154
|
+
label: "30 min"
|
|
155
|
+
},
|
|
156
|
+
{
|
|
157
|
+
value: "60",
|
|
158
|
+
label: "60 min"
|
|
159
|
+
}
|
|
160
|
+
]
|
|
161
|
+
},
|
|
162
|
+
...args.multiProvider ? [dataSourceField(args)] : []
|
|
163
|
+
];
|
|
188
164
|
const WIDGET_DEFS = [
|
|
189
165
|
{
|
|
190
166
|
slug: "analytics-metric",
|
|
@@ -227,11 +203,14 @@ const registerWidgets = (config, args) => {
|
|
|
227
203
|
for (const def of WIDGET_DEFS) {
|
|
228
204
|
if (args.disabled.includes(def.slug)) continue;
|
|
229
205
|
if (!widgetIsSupported(def.requires, args.adapters)) continue;
|
|
206
|
+
const fields = def.fields(args);
|
|
207
|
+
const metricField = findMetricField(fields);
|
|
208
|
+
if (metricField && "options" in metricField && metricField.options.length === 0) continue;
|
|
230
209
|
built.push({
|
|
231
210
|
slug: def.slug,
|
|
232
211
|
Component: def.component,
|
|
233
212
|
label: labelForKey(def.label),
|
|
234
|
-
fields
|
|
213
|
+
fields,
|
|
235
214
|
minWidth: def.minWidth,
|
|
236
215
|
maxWidth: def.maxWidth
|
|
237
216
|
});
|