1
0
mirror of https://github.com/bitwarden/browser synced 2026-02-26 09:33:22 +00:00

feat: add analytics service & directive

This commit is contained in:
William Martin
2024-12-09 11:13:51 -05:00
parent 69800d01ab
commit 1d492083e0
8 changed files with 91 additions and 1 deletions

View File

@@ -0,0 +1,48 @@
import { inject, Injectable } from "@angular/core";
import Plausible from "plausible-tracker";
// import { firstValueFrom } from "rxjs";
import { ANALYTICS, GlobalStateProvider, KeyDefinition } from "@bitwarden/common/platform/state";
const ANALYTICS_ENABLED_KEY_DEF = new KeyDefinition<boolean>(ANALYTICS, "analytics_enabled", {
deserializer: (s) => s,
});
@Injectable({ providedIn: "root" })
export class AnalyticsService {
private plausible: ReturnType<typeof Plausible>;
private plausibleCleanup?: () => any;
private readonly _enabledState = inject(GlobalStateProvider).get(ANALYTICS_ENABLED_KEY_DEF);
readonly enabled$ = this._enabledState.state$;
async init() {
this.plausible = Plausible({
domain: "bitwarden",
trackLocalhost: true,
hashMode: true,
});
// TODO: uncomment when a toggle is added to settings page
// const enabled = await firstValueFrom(this._enabledState.state$);
// if (!enabled) {
// return;
// }
await this.enable();
}
async enable() {
await this._enabledState.update((_prevState) => true);
this.plausibleCleanup = this.plausible.enableAutoPageviews();
}
async disable() {
await this._enabledState.update((_prevState) => false);
this?.plausibleCleanup();
}
trackEvent(eventName: string) {
this.plausible.trackEvent(eventName);
}
}

View File

@@ -0,0 +1,22 @@
import { Directive, HostListener, inject, Input } from "@angular/core";
import { AnalyticsService } from "./analytics.service";
@Directive({
selector: "[track-event]",
standalone: true,
})
export class TrackEventDirective {
private analyticsService = inject(AnalyticsService);
@Input({
alias: "track-event",
required: true,
})
eventName!: string;
@HostListener("click")
handleClick() {
this.analyticsService.trackEvent(this.eventName);
}
}

View File

@@ -27,6 +27,7 @@ import {
TypographyModule,
} from "@bitwarden/components";
import { TrackEventDirective } from "./analytics/track-event.directive";
import { TwoFactorIconComponent } from "./auth/components/two-factor-icon.component";
import { DeprecatedCalloutComponent } from "./components/callout.component";
import { A11yInvalidDirective } from "./directives/a11y-invalid.directive";
@@ -81,6 +82,7 @@ import { IconComponent } from "./vault/components/icon.component";
IconModule,
LinkModule,
IconModule,
TrackEventDirective,
],
declarations: [
A11yInvalidDirective,