pixel: refactor to separate files
This commit is contained in:
68
src/lib/metapixel/MetaPixel.svelte
Normal file
68
src/lib/metapixel/MetaPixel.svelte
Normal file
@@ -0,0 +1,68 @@
|
||||
<!-- @component
|
||||
MetaPixel integrates the Meta (Facebook) Pixel into your Svelte application,
|
||||
allowing you to track page views and custom events while respecting user consent
|
||||
for tracking. The component manages the lifecycle of the Meta Pixel script and
|
||||
PixelControl interface.
|
||||
-->
|
||||
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
import type { TrackingManager } from '../tracking.svelte.ts';
|
||||
import { onNavigate } from '$app/navigation';
|
||||
import { PixelControl, type PixelControlOptions } from './pixel-control.ts';
|
||||
|
||||
interface Props {
|
||||
/**
|
||||
* Tracking manager to handle user consent for tracking. If omitted
|
||||
* tracking is disabled by default until consent is granted via
|
||||
* PixelControl.grantConsent().
|
||||
*/
|
||||
trackingManager?: TrackingManager;
|
||||
|
||||
/** Meta Pixel ID */
|
||||
pixelID: string;
|
||||
|
||||
/** Meta Pixel Options */
|
||||
pixelOptions?: PixelControlOptions;
|
||||
|
||||
/**
|
||||
* Controls whether page views are automatically tracked by this
|
||||
* component (default: true).
|
||||
*/
|
||||
autoPageView?: boolean;
|
||||
}
|
||||
|
||||
let { pixelID, pixelOptions, autoPageView = true, trackingManager }: Props = $props();
|
||||
|
||||
let pixel = $state<PixelControl | null>(null);
|
||||
|
||||
onMount(() => {
|
||||
if (!trackingManager) {
|
||||
throw new Error('MetaPixel component requires a TrackingManager to manage consent.');
|
||||
}
|
||||
PixelControl.load();
|
||||
pixel = PixelControl.initialize(trackingManager, pixelID, pixelOptions);
|
||||
|
||||
trackingManager.runWithConsent(() => {
|
||||
if (autoPageView && pixel) {
|
||||
pixel.pageView();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
onNavigate(() => {
|
||||
trackingManager?.runWithConsent(() => {
|
||||
if (autoPageView && pixel) {
|
||||
pixel.pageView();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
export const getPixelControl = (): PixelControl => {
|
||||
if (!pixel) {
|
||||
throw new Error('MetaPixel component has not been initialized yet, wait for onMount.');
|
||||
}
|
||||
return pixel;
|
||||
};
|
||||
</script>
|
||||
Reference in New Issue
Block a user