Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/SDK/Language/Flutter.php
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,16 @@ public function getFiles(): array
'destination' => '/lib/src/realtime_response_connected.dart',
'template' => 'flutter/lib/src/realtime_response_connected.dart.twig',
],
[
'scope' => 'default',
'destination' => '/lib/src/analytics_observer.dart',
'template' => 'flutter/lib/src/analytics_observer.dart.twig',
],
[
'scope' => 'default',
'destination' => '/lib/src/analytics_tracking.dart',
'template' => 'flutter/lib/src/analytics_tracking.dart.twig',
],
[
'scope' => 'default',
'destination' => '/lib/src/cookie_manager.dart',
Expand Down
5 changes: 5 additions & 0 deletions src/SDK/Language/Web.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ public function getFiles(): array
'destination' => 'src/services/realtime.ts',
'template' => 'web/src/services/realtime.ts.twig',
],
[
'scope' => 'default',
'destination' => 'src/services/analytics-tracking.ts',
'template' => 'web/src/services/analytics-tracking.ts.twig',
],
[
'scope' => 'default',
'destination' => 'src/models.ts',
Expand Down
2 changes: 2 additions & 0 deletions templates/flutter/lib/package.dart.twig
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ export 'src/upload_progress.dart';
export 'src/realtime_subscription.dart';
export 'src/realtime_message.dart';
export 'src/input_file.dart';
export 'src/analytics_observer.dart';
export 'src/analytics_tracking.dart';

part 'query.dart';
part 'permission.dart';
Expand Down
140 changes: 140 additions & 0 deletions templates/flutter/lib/src/analytics_observer.dart.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import 'package:flutter/widgets.dart';

/// Signature used to emit an analytics event from an [AnalyticsObserver] or
/// [AnalyticsTracking] instance.
///
/// The generated `Analytics` service exposes `event({required String name, ...})`,
/// so the typical wiring is:
///
/// ```dart
/// final analytics = Analytics(client);
/// final observer = AnalyticsObserver(
/// (name, {props, propertyId, engagementTime}) => analytics.event(
/// name: name,
/// props: props,
/// propertyId: propertyId,
/// engagementTime: engagementTime,
/// ),
/// propertyId: '<PROPERTY_ID>',
/// );
/// ```
///
/// [propertyId] and [engagementTime] map to the endpoint's top-level params of
/// the same name; both are null unless the helper has something to say about
/// them, so a closure is free to ignore either.
typedef AnalyticsEventEmitter = void Function(
String name, {
Map<String, dynamic>? props,
String? propertyId,
int? engagementTime,
});

/// Signature used to derive a screen name from a [Route].
///
/// Return `null` to skip tracking the route entirely (for example, dialogs or
/// bottom sheets that shouldn't count as screen views).
typedef ScreenNameExtractor = String? Function(Route<dynamic> route);

/// Default [ScreenNameExtractor] — uses [RouteSettings.name] when present and
/// falls back to `null` (route is skipped) otherwise. Anonymous routes are
/// generally noise for analytics, so opting out by default keeps dashboards
/// clean.
String? defaultScreenNameExtractor(Route<dynamic> route) {
return route.settings.name;
}

/// [NavigatorObserver] that fires an analytics event every time a named route
/// is pushed, popped-back-to, replaced or removed.
///
/// Attach to a `MaterialApp` (or `CupertinoApp`, `WidgetsApp`) via
/// `navigatorObservers`:
///
/// ```dart
/// MaterialApp(
/// navigatorObservers: [
/// AnalyticsObserver(
/// (name, {props, propertyId, engagementTime}) => analytics.event(
/// name: name,
/// props: props,
/// propertyId: propertyId,
/// engagementTime: engagementTime,
/// ),
/// propertyId: '<PROPERTY_ID>',
/// ),
/// ],
/// ...
/// );
/// ```
class AnalyticsObserver extends NavigatorObserver {
/// Callback used to send the resulting `screen_view` event.
final AnalyticsEventEmitter emit;

/// Optional route-name extractor. Defaults to [defaultScreenNameExtractor]
/// which reads [RouteSettings.name].
final ScreenNameExtractor nameExtractor;

/// Event name used for screen views. Defaults to `screen_view`.
final String eventName;

/// Analytics property (or snippet) ID forwarded with every emitted event.
/// Optional — leave null when the emitter closure already supplies one.
final String? propertyId;

AnalyticsObserver(
this.emit, {
ScreenNameExtractor? nameExtractor,
this.eventName = 'screen_view',
this.propertyId,
}) : nameExtractor = nameExtractor ?? defaultScreenNameExtractor;

@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
_sendScreenView(route, previousRoute, trigger: 'push');
}

@override
void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
if (newRoute != null) {
_sendScreenView(newRoute, oldRoute, trigger: 'replace');
}
}

@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (previousRoute != null) {
_sendScreenView(previousRoute, route, trigger: 'pop');
}
}

@override
void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (previousRoute != null) {
_sendScreenView(previousRoute, route, trigger: 'remove');
}
}

void _sendScreenView(
Route<dynamic> route,
Route<dynamic>? previousRoute, {
required String trigger,
}) {
final name = nameExtractor(route);
if (name == null || name.isEmpty) {
return;
}
final props = <String, dynamic>{
'screen': name,
'trigger': trigger,
};
final previousName = previousRoute == null ? null : nameExtractor(previousRoute);
if (previousName != null && previousName.isNotEmpty) {
props['previous'] = previousName;
}
try {
emit(eventName, props: props, propertyId: propertyId);
} catch (_) {
// Emitter failures must never propagate into the navigator stack —
// swallow so analytics can't crash the app.
}
}
}
181 changes: 181 additions & 0 deletions templates/flutter/lib/src/analytics_tracking.dart.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import 'package:flutter/widgets.dart';

import 'analytics_observer.dart';

export 'analytics_observer.dart' show AnalyticsEventEmitter, AnalyticsObserver, ScreenNameExtractor;

/// Companion class for the generated `Analytics` service that wires up the
/// mobile-idiomatic auto-tracking primitives: app-lifecycle events (backgrounded
/// / foregrounded) and manual `screenView` calls.
///
/// Auto-emitted event names follow `snake_case` + lowercase (`pageview`,
/// `screen_view`, `app_backgrounded`, `app_foregrounded`, etc.). Prop keys use
/// camelCase to match the endpoint's parameter naming.
///
/// Attach an [AnalyticsObserver] to your `MaterialApp` for automatic route
/// tracking; use [AnalyticsTracking] on top for lifecycle events and the
/// convenience `screenView` / `event` shortcuts.
///
/// [enableAutoLifecycleEvents] calls [WidgetsFlutterBinding.ensureInitialized]
/// internally, so it is safe to invoke before [runApp] without wiring up the
/// binding manually. Callers who need the binding for their own initialization
/// (async setup, plugin channels, etc.) can still call `ensureInitialized()`
/// themselves — the call is idempotent.
///
/// Engagement time is reported the same way the Web helper reports it: as a
/// **delta** attached to each `app_backgrounded` event, covering only the
/// foreground time accrued since the last resume. Backgrounding is the mobile
/// equivalent of a browser tab going hidden, and it is where the Web helper
/// flushes too, so the two platforms feed the same additive `engagementTime`
/// column. The seconds ride on the lifecycle event that is already being sent
/// at that exact moment rather than adding a second request for a single
/// number.
///
/// Typical wiring:
///
/// ```dart
/// final analytics = Analytics(client);
/// final emit = (String name, {Map<String, dynamic>? props, String? propertyId, int? engagementTime}) =>
/// analytics.event(
/// name: name,
/// props: props,
/// propertyId: propertyId,
/// engagementTime: engagementTime,
/// );
///
/// final tracking = AnalyticsTracking(emit, propertyId: '<PROPERTY_ID>');
/// tracking.enableAllAutoTracking();
///
/// runApp(MaterialApp(
/// navigatorObservers: [
/// AnalyticsObserver(emit, propertyId: '<PROPERTY_ID>'),
/// ],
/// home: MyApp(),
/// ));
/// ```
class AnalyticsTracking with WidgetsBindingObserver {
final AnalyticsEventEmitter _emit;

/// Analytics property (or snippet) ID forwarded with every emitted event.
/// Optional — leave null when the emitter closure already supplies one.
final String? propertyId;

bool _lifecycleAttached = false;
DateTime? _foregroundSince;

/// Sub-second engagement left over from the previous flush. Carried forward
/// so a session made of many short foreground stretches does not lose a
/// fraction of a second to truncation on every one of them.
Duration _engagementCarry = Duration.zero;

AnalyticsTracking(AnalyticsEventEmitter emit, {this.propertyId}) : _emit = emit;

/// Enable the opinionated default auto-tracking set. Currently this covers
/// lifecycle events; route tracking is opt-in via [AnalyticsObserver].
void enableAllAutoTracking() {
enableAutoLifecycleEvents();
}

/// Start emitting `app_backgrounded` and `app_foregrounded` events when the
/// host app changes lifecycle state. Idempotent — repeat calls no-op.
///
/// Calls [WidgetsFlutterBinding.ensureInitialized] internally so this is
/// safe to invoke before [runApp] without the caller having to bootstrap
/// the binding themselves.
void enableAutoLifecycleEvents() {
if (_lifecycleAttached) {
return;
}
// WidgetsBinding.instance throws StateError if the binding has not been
// set up yet. The docstring example wires this call before runApp(), so
// ensure the binding here — the call is idempotent.
WidgetsFlutterBinding.ensureInitialized();
_lifecycleAttached = true;
_foregroundSince = DateTime.now();
_engagementCarry = Duration.zero;
WidgetsBinding.instance.addObserver(this);
}
Comment thread
greptile-apps[bot] marked this conversation as resolved.

/// Stop emitting lifecycle events. Safe to call when auto-lifecycle was
/// never enabled.
void disableAutoLifecycleEvents() {
if (!_lifecycleAttached) {
return;
}
_lifecycleAttached = false;
_foregroundSince = null;
_engagementCarry = Duration.zero;
WidgetsBinding.instance.removeObserver(this);
}

/// Emit an ad-hoc analytics event. Emitter exceptions are swallowed so
/// analytics failures never surface to the host app.
void event(
String name, {
Map<String, dynamic>? props,
int? engagementTime,
}) {
try {
_emit(
name,
props: props,
propertyId: propertyId,
engagementTime: engagementTime,
);
} catch (_) {
// Silent — see class docs.
}
}

/// Mobile-idiomatic screen-view shortcut. Renders as a `screen_view`
/// analytics event with `screen`, optional `screenClass` and any
/// caller-supplied properties.
void screenView(
String name, {
String? className,
Map<String, dynamic>? props,
}) {
final merged = <String, dynamic>{'screen': name};
if (className != null) {
merged['screenClass'] = className;
}
if (props != null) {
merged.addAll(props);
}
event('screen_view', props: merged);
}

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch (state) {
case AppLifecycleState.paused:
case AppLifecycleState.hidden:
// On Flutter desktop and web the lifecycle transitions through both
// `hidden` and `paused` when the window is minimised / closed. Guard
// on `_foregroundSince` so we emit `app_backgrounded` exactly once
// per background transition instead of firing a second empty event —
// which is also what keeps the engagement delta from being billed
// twice for one transition.
final since = _foregroundSince;
if (since == null) {
break;
}
_foregroundSince = null;
final elapsed = _engagementCarry + DateTime.now().difference(since);
final seconds = elapsed.inSeconds;
_engagementCarry = elapsed - Duration(seconds: seconds);
event(
'app_backgrounded',
engagementTime: seconds > 0 ? seconds : null,
);
break;
Comment thread
greptile-apps[bot] marked this conversation as resolved.
case AppLifecycleState.resumed:
_foregroundSince = DateTime.now();
event('app_foregrounded');
break;
case AppLifecycleState.inactive:
case AppLifecycleState.detached:
break;
}
}
}
8 changes: 8 additions & 0 deletions templates/web/src/index.ts.twig
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,16 @@ export { Client, Query, {{spec.title | caseUcfirst}}Exception } from './client';
export { {{service.name | caseUcfirst}} } from './services/{{service.name | caseKebab}}';
{% endfor %}
export { Realtime } from './services/realtime';
export { AnalyticsTracking } from './services/analytics-tracking';
export type { Models, Payload, RealtimeResponseEvent, UploadProgress } from './client';
export type { RealtimeSubscription } from './services/realtime';
export type {
AnalyticsEventEmitter,
AnalyticsEventOptions,
AnalyticsTrackingOptions,
DownloadTrackingOptions,
OutboundTrackingOptions
} from './services/analytics-tracking';
export type { QueryTypes, QueryTypesList } from './query';
export { Permission } from './permission';
export { Role } from './role';
Expand Down
Loading
Loading