Sha256: ecb07e1fa98d7d0193eed18c749eba5439b18de79fbf9d32a56d30b94761f511

Contents?: true

Size: 1.77 KB

Versions: 6

Compression:

Stored size: 1.77 KB

Contents

import { getCookie, setCookie } from "./util";

const consentCategories = ["essential", "targeting", "statistic"] as const;
export type ConsentCategory = typeof consentCategories[number];

export class Consent {
  #consentListeners: Record<ConsentCategory, Array<() => void>> = {
    essential: [],
    targeting: [],
    statistic: [],
  };

  get permitted(): ConsentCategory[] {
    return (getCookie("consent") ?? "").split(",") as ConsentCategory[];
  }

  set permitted(settings: ConsentCategory[]) {
    setCookie("consent", settings.join(","));
    settings.forEach((category) => {
      this.#consentListeners[category].forEach((e) => e());
    });
  }

  get given(): boolean {
    return getCookie("consent") !== undefined;
  }

  permitAll(): void {
    this.permitted = consentCategories.slice();
  }

  denyAll(): void {
    this.permitted = ["essential"];
  }

  showSettings(): void {
    const element = document.getElementById("personalization-settings");
    if (element) element.hidden = false;
  }

  consentFor(category: ConsentCategory): Promise<void> {
    return new Promise((res) => {
      if (this.permitted.includes(category)) {
        res();
      } else {
        this.#consentListeners[category].push(res);
      }
    });
  }

  async enableGoogleAnalytics(
    id: string,
    role: ConsentCategory = "statistic"
  ): Promise<void> {
    await this.consentFor(role);
    window.gtag("js", new Date());
    window.gtag("config", id, { send_page_view: false }); // page view is disabled because it's tracked via the analytics stimulus controller already
    const script = document.createElement("script");
    script.async = true;
    script.setAttribute(
      "src",
      `https://www.googletagmanager.com/gtag/js?id=${id}`
    );
    document.head.prepend(script);
  }
}

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
shimmer-0.0.31 src/consent.ts
shimmer-0.0.30 src/consent.ts
shimmer-0.0.29 src/consent.ts
shimmer-0.0.28 src/consent.ts
shimmer-0.0.27 src/consent.ts
shimmer-0.0.26 src/consent.ts