import type { Poool } from 'poool-access'; import { type ComponentPropsWithoutRef, type RefObject, useEffect, useMemo, useRef, useImperativeHandle, forwardRef, } from 'react'; import { classNames } from '@junipero/core'; import type { AccessEvents, EventCallbackFunction } from '../types'; import type { AccessContextValue } from '../contexts'; import type { RestrictedContentRef } from '../RestrictedContent'; import { generateId } from '../utils'; import { useAccess } from '../hooks'; export declare interface PaywallRef { containerRef: RefObject; recreate: () => void; create: () => void; destroy: (container: HTMLElement) => void; } export declare interface PaywallProps extends Pick< AccessContextValue, 'events' | 'config' | 'texts' | 'styles' | 'variables' >, ComponentPropsWithoutRef<'div'> { /** * Ref to the paywall */ ref?: RefObject; /** * Ref to the content */ contentRef?: RefObject; /** * Custom wrapper component ID */ id?: string; /** * The current page type * * More infos: * https://www.poool.dev/docs/access/javascript/access/installation */ pageType?: Parameters[0]['pageType']; } const Paywall = forwardRef(({ id, events, contentRef, children, className, config, texts, styles, variables, pageType = 'premium', ...rest }, ref) => { const paywallRef = useRef(null); const containerRef = useRef(null); const { lib, createFactory, destroyFactory, config: globalConfig, } = useAccess(); useImperativeHandle(ref, () => ({ containerRef, recreate, create, destroy, })); useEffect(() => { create(); const container = containerRef.current; return () => { destroy(container); }; // eslint-disable-next-line react-hooks/exhaustive-deps,@eslint-react/exhaustive-deps }, [lib, globalConfig?.cookies_enabled]); const create = () => { paywallRef.current = createFactory?.({ events, config, texts, styles, variables, }); if (!paywallRef.current) { return; } paywallRef.current.once('identityAvailable', onIdentityAvailable); paywallRef.current.createPaywall({ pageType, target: containerRef.current, content: contentRef?.current?.contentRef?.current, mode: contentRef?.current?.mode, percent: contentRef?.current?.percent, }); }; const destroy = async (container: HTMLElement) => { if (!paywallRef.current) { return; } container.innerHTML = ''; const factory = paywallRef.current; factory.off('identityAvailable', onIdentityAvailable); paywallRef.current = null; await destroyFactory?.(factory); }; const recreate = async () => { await destroy(containerRef.current); create(); }; const onIdentityAvailable = ( e: Parameters< Extract> >[0] ) => { try { globalThis.document.dispatchEvent(new CustomEvent('$_poool.onMessage', { detail: { type: '$_poool.setUser', data: e, }, })); } catch {} }; const customId = useMemo(() => generateId(), []); return ( <>
{ children } ); }); Paywall.displayName = 'Paywall'; export default Paywall;