@ethicly/react-native 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +75 -0
- package/LICENSE +21 -0
- package/README.md +313 -2
- package/core/package.json +6 -0
- package/interstitial/package.json +6 -0
- package/lib/commonjs/core/adapters.js +287 -0
- package/lib/commonjs/core/beacons.js +70 -0
- package/lib/commonjs/core/cache.js +206 -0
- package/lib/commonjs/core/click.js +19 -0
- package/lib/commonjs/core/client.js +489 -0
- package/lib/commonjs/core/config.js +113 -0
- package/lib/commonjs/core/http.js +115 -0
- package/lib/commonjs/core/index.js +20 -0
- package/lib/commonjs/core/outbox.js +192 -0
- package/lib/commonjs/core/tracker.js +374 -0
- package/lib/commonjs/core/types.js +4 -0
- package/lib/commonjs/index.js +22 -0
- package/lib/commonjs/interstitial.js +7 -0
- package/lib/commonjs/react/EthiclyInterstitial.js +286 -0
- package/lib/commonjs/react/useEthiclyInterstitial.js +54 -0
- package/lib/commonjs/version.js +5 -0
- package/lib/module/core/adapters.js +276 -0
- package/lib/module/core/beacons.js +64 -0
- package/lib/module/core/cache.js +202 -0
- package/lib/module/core/click.js +15 -0
- package/lib/module/core/client.js +485 -0
- package/lib/module/core/config.js +104 -0
- package/lib/module/core/http.js +105 -0
- package/lib/module/core/index.js +6 -0
- package/lib/module/core/outbox.js +186 -0
- package/lib/module/core/tracker.js +370 -0
- package/lib/module/core/types.js +3 -0
- package/lib/module/index.js +4 -0
- package/lib/module/interstitial.js +3 -0
- package/lib/module/react/EthiclyInterstitial.js +260 -0
- package/lib/module/react/useEthiclyInterstitial.js +51 -0
- package/lib/module/version.js +2 -0
- package/lib/typescript/core/adapters.d.ts +138 -0
- package/lib/typescript/core/beacons.d.ts +32 -0
- package/lib/typescript/core/cache.d.ts +53 -0
- package/lib/typescript/core/click.d.ts +8 -0
- package/lib/typescript/core/client.d.ts +58 -0
- package/lib/typescript/core/config.d.ts +24 -0
- package/lib/typescript/core/http.d.ts +34 -0
- package/lib/typescript/core/index.d.ts +8 -0
- package/lib/typescript/core/outbox.d.ts +56 -0
- package/lib/typescript/core/tracker.d.ts +95 -0
- package/lib/typescript/core/types.d.ts +170 -0
- package/lib/typescript/index.d.ts +3 -0
- package/lib/typescript/interstitial.d.ts +2 -0
- package/lib/typescript/react/EthiclyInterstitial.d.ts +39 -0
- package/lib/typescript/react/useEthiclyInterstitial.d.ts +20 -0
- package/lib/typescript/version.d.ts +2 -0
- package/package.json +101 -4
- package/src/core/adapters.ts +337 -0
- package/src/core/beacons.ts +81 -0
- package/src/core/cache.ts +216 -0
- package/src/core/click.ts +16 -0
- package/src/core/client.ts +547 -0
- package/src/core/config.ts +111 -0
- package/src/core/http.ts +115 -0
- package/src/core/index.ts +14 -0
- package/src/core/outbox.ts +193 -0
- package/src/core/tracker.ts +371 -0
- package/src/core/types.ts +180 -0
- package/src/index.ts +5 -0
- package/src/interstitial.ts +4 -0
- package/src/react/EthiclyInterstitial.tsx +386 -0
- package/src/react/useEthiclyInterstitial.ts +74 -0
- package/src/version.ts +2 -0
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// Public and wire types for the headless core. Wire names (snake_case) follow
|
|
2
|
+
// docs/APP_API_V1.md; public names are camelCase.
|
|
3
|
+
|
|
4
|
+
export type Platform = 'ios' | 'android';
|
|
5
|
+
export type AudioPolicy = 'none' | 'optional' | 'on';
|
|
6
|
+
|
|
7
|
+
/** The /config body (doc "GET /config"). Unknown fields are ignored. */
|
|
8
|
+
export interface EthiclyConfig {
|
|
9
|
+
enabled: boolean;
|
|
10
|
+
min_sdk: { ios: string; android: string };
|
|
11
|
+
formats: string[];
|
|
12
|
+
interstitial: {
|
|
13
|
+
skip_after_ms: number;
|
|
14
|
+
max_per_session: number;
|
|
15
|
+
min_gap_s: number;
|
|
16
|
+
audio: AudioPolicy;
|
|
17
|
+
};
|
|
18
|
+
prefetch: { max_cached_creatives: number; max_cache_mb: number };
|
|
19
|
+
beacon: { viewable_after_ms: number; flush_interval_s: number };
|
|
20
|
+
endpoints: { serve: string };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** AsyncStorage-shaped key-value store. */
|
|
24
|
+
export interface KeyValueStorage {
|
|
25
|
+
getItem(key: string): Promise<string | null>;
|
|
26
|
+
setItem(key: string, value: string): Promise<void>;
|
|
27
|
+
removeItem?(key: string): Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** expo-file-system-shaped creative store. */
|
|
31
|
+
export interface FileCacheAdapter {
|
|
32
|
+
/**
|
|
33
|
+
* Download `url` into the cache under `fileName`; resolve the local uri.
|
|
34
|
+
* Should abort (reject, leaving no file) once more than `maxBytes` would be written.
|
|
35
|
+
*/
|
|
36
|
+
download(url: string, fileName: string, opts?: { maxBytes?: number }): Promise<{ uri: string; bytes?: number }>;
|
|
37
|
+
exists(uri: string): Promise<boolean>;
|
|
38
|
+
delete(uri: string): Promise<void>;
|
|
39
|
+
/** Size in bytes, 0 when unknown. */
|
|
40
|
+
size(uri: string): Promise<number>;
|
|
41
|
+
/** Every file in the SDK's cache directory. Lets the cache sweep files it no longer indexes. */
|
|
42
|
+
list?(): Promise<string[]>;
|
|
43
|
+
/** The uri `download(url, fileName)` writes to, so an unfinished download can be deleted. */
|
|
44
|
+
uriFor?(fileName: string): string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface Logger {
|
|
48
|
+
debug?(message: string, ...rest: unknown[]): void;
|
|
49
|
+
info?(message: string, ...rest: unknown[]): void;
|
|
50
|
+
warn?(message: string, ...rest: unknown[]): void;
|
|
51
|
+
error?(message: string, ...rest: unknown[]): void;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The subset of a fetch Response the SDK reads. */
|
|
55
|
+
export interface ResponseLike {
|
|
56
|
+
status: number;
|
|
57
|
+
headers: { get(name: string): string | null };
|
|
58
|
+
text(): Promise<string>;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface RequestInitLike {
|
|
62
|
+
method?: string;
|
|
63
|
+
headers?: Record<string, string>;
|
|
64
|
+
body?: string;
|
|
65
|
+
signal?: unknown;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export type FetchLike = (url: string, init?: RequestInitLike) => Promise<ResponseLike>;
|
|
69
|
+
|
|
70
|
+
/** 64-bit impression id. A string when the value is beyond 2^53. */
|
|
71
|
+
export type ImpressionId = number | string;
|
|
72
|
+
|
|
73
|
+
/** Server no-ad reasons (doc "No-ad responses") plus the SDK's own. */
|
|
74
|
+
export type NoFillReason =
|
|
75
|
+
| 'publisher_not_approved'
|
|
76
|
+
| 'publisher_paused'
|
|
77
|
+
| 'publisher_blackout'
|
|
78
|
+
| 'app_disabled'
|
|
79
|
+
| 'sdk_unsupported'
|
|
80
|
+
| 'interstitial_disabled'
|
|
81
|
+
| 'classic_disabled'
|
|
82
|
+
| 'no_approved_ads'
|
|
83
|
+
| 'ads_query_error'
|
|
84
|
+
| 'no_matching_ad'
|
|
85
|
+
| 'publisher_mix'
|
|
86
|
+
| 'test_unavailable'
|
|
87
|
+
// SDK-side reasons
|
|
88
|
+
| 'ads_disabled'
|
|
89
|
+
| 'frequency_capped'
|
|
90
|
+
| 'unknown_key'
|
|
91
|
+
| 'invalid_key'
|
|
92
|
+
| 'rate_limited'
|
|
93
|
+
| 'network_error'
|
|
94
|
+
| 'server_error'
|
|
95
|
+
| 'invalid_response'
|
|
96
|
+
| (string & {});
|
|
97
|
+
|
|
98
|
+
export interface EthiclyAdMedia {
|
|
99
|
+
kind: 'video' | 'image';
|
|
100
|
+
/** The file to show: local file when cached, else the remote URL. */
|
|
101
|
+
uri: string;
|
|
102
|
+
/** Same as `uri` for a video, null for a still. */
|
|
103
|
+
videoUri: string | null;
|
|
104
|
+
/** Local or remote poster, null when the ad has none. */
|
|
105
|
+
posterUri: string | null;
|
|
106
|
+
durationMs: number | null;
|
|
107
|
+
mime: string | null;
|
|
108
|
+
width: number;
|
|
109
|
+
height: number;
|
|
110
|
+
/** True when `uri` points at a local cached file. */
|
|
111
|
+
cached: boolean;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface EthiclyAd {
|
|
115
|
+
id: number;
|
|
116
|
+
/** Button text: ad.cta_label, or "Learn more" when the server sends none. */
|
|
117
|
+
ctaLabel: string;
|
|
118
|
+
destinationUrl: string;
|
|
119
|
+
/** When the skip control may appear. The ad's value wins over /config. */
|
|
120
|
+
skipAfterMs: number;
|
|
121
|
+
media: EthiclyAdMedia;
|
|
122
|
+
/** interstitial.audio from /config. */
|
|
123
|
+
audio: AudioPolicy;
|
|
124
|
+
title: string | null;
|
|
125
|
+
/** True for a test-mode serve: nothing is stored or billed. */
|
|
126
|
+
test: boolean;
|
|
127
|
+
/** Epoch ms when the serve response arrived. */
|
|
128
|
+
servedAt: number;
|
|
129
|
+
/** Epoch ms after which the ad must not be shown (served + token_ttl_s). */
|
|
130
|
+
expiresAt: number;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export interface Tracker {
|
|
134
|
+
/** Call the moment the ad is rendered. Sends /impression immediately. */
|
|
135
|
+
shown(size?: { width?: number; height?: number }): Promise<void>;
|
|
136
|
+
/** Call on every player time update. */
|
|
137
|
+
progress(positionMs: number, opts: { visible: boolean; durationMs?: number }): void;
|
|
138
|
+
complete(): void;
|
|
139
|
+
skipped(positionMs: number): void;
|
|
140
|
+
error(): void;
|
|
141
|
+
/** POST /click (500 ms budget), then open the destination. Resolves with the URL opened. */
|
|
142
|
+
clicked(): Promise<string>;
|
|
143
|
+
/** Call when the ad screen goes away. Sends queued video events. */
|
|
144
|
+
closed(): Promise<void>;
|
|
145
|
+
/** True once the ad is older than token_ttl_s: it must not be shown. */
|
|
146
|
+
isExpired(): boolean;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export type InterstitialResult =
|
|
150
|
+
| { ad: EthiclyAd; tracker: Tracker; reason?: undefined }
|
|
151
|
+
| { ad: null; tracker: null; reason: NoFillReason };
|
|
152
|
+
|
|
153
|
+
/** Raw serve-response ad (only the fields the SDK reads). */
|
|
154
|
+
export interface WireAd {
|
|
155
|
+
id: number;
|
|
156
|
+
title?: string | null;
|
|
157
|
+
destination_url?: string | null;
|
|
158
|
+
skip_after_ms?: number | null;
|
|
159
|
+
cta_label?: string | null;
|
|
160
|
+
media?: {
|
|
161
|
+
kind?: string;
|
|
162
|
+
url?: string | null;
|
|
163
|
+
poster_url?: string | null;
|
|
164
|
+
duration_ms?: number | null;
|
|
165
|
+
width?: number | null;
|
|
166
|
+
height?: number | null;
|
|
167
|
+
mime?: string | null;
|
|
168
|
+
} | null;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export interface WireServe {
|
|
172
|
+
ad: WireAd | null;
|
|
173
|
+
reason?: string;
|
|
174
|
+
publisher_site_id?: number;
|
|
175
|
+
country_code?: string;
|
|
176
|
+
impression_token?: string;
|
|
177
|
+
token_ttl_s?: number;
|
|
178
|
+
test?: boolean;
|
|
179
|
+
request_id?: string;
|
|
180
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @ethicly/react-native: the headless core and the React hook. The ready-made
|
|
2
|
+
// screen, which needs expo-video, is at '@ethicly/react-native/interstitial'.
|
|
3
|
+
export * from './core';
|
|
4
|
+
export { useEthiclyInterstitial } from './react/useEthiclyInterstitial';
|
|
5
|
+
export type { EthiclyInterstitialState, UseEthiclyInterstitialOptions } from './react/useEthiclyInterstitial';
|
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
// Optional ready-made fullscreen screen. Needs expo-video (Expo SDK 52+).
|
|
2
|
+
// Layout follows a typical in-app video player: 9:16 video, a skip control that counts
|
|
3
|
+
// down then reads "Skip Ad", a white call-to-action button, an optional
|
|
4
|
+
// "Remove ads" slot and a small "Sponsored by Ethicly.ch" line under it.
|
|
5
|
+
// Video starts with sound unless interstitial.audio is 'none' or 'optional'.
|
|
6
|
+
// The controls keep clear of the notch, status bar and home indicator: see
|
|
7
|
+
// useSafeInsets below.
|
|
8
|
+
|
|
9
|
+
import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
|
|
10
|
+
import {
|
|
11
|
+
AppState, BackHandler, Image, Modal, Platform, Pressable, StatusBar, StyleSheet, Text, View,
|
|
12
|
+
type AppStateStatus, type StyleProp, type TextStyle, type ViewStyle,
|
|
13
|
+
} from 'react-native';
|
|
14
|
+
import { useVideoPlayer, VideoView } from 'expo-video';
|
|
15
|
+
import type { EthiclyAd, Tracker } from '../core/types';
|
|
16
|
+
|
|
17
|
+
/** Safe-area insets in points, as react-native-safe-area-context reports them. */
|
|
18
|
+
export interface EthiclyInsets { top: number; bottom: number; left: number; right: number }
|
|
19
|
+
|
|
20
|
+
export interface EthiclyInterstitialProps {
|
|
21
|
+
ad: EthiclyAd;
|
|
22
|
+
tracker: Tracker;
|
|
23
|
+
/** Called after the ad is skipped or closed. Hide the screen here. */
|
|
24
|
+
onClose(): void;
|
|
25
|
+
/** Shows a "Remove ads" link under the button that calls this. */
|
|
26
|
+
onRemoveAds?(): void;
|
|
27
|
+
removeAdsLabel?: string;
|
|
28
|
+
/** Replaces the "Remove ads" link with anything the app wants. */
|
|
29
|
+
renderBelowButton?(): React.ReactNode;
|
|
30
|
+
/** Default true: wraps the screen in a fullscreen Modal. */
|
|
31
|
+
modal?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Overrides for the skip control, merged over the default: a solid black
|
|
34
|
+
* pill reading "Skip in N", then "Skip Ad" with a skip-to-end icon.
|
|
35
|
+
*/
|
|
36
|
+
skipStyle?: StyleProp<ViewStyle>;
|
|
37
|
+
/** Overrides for the skip label (default white, "Skip in N" then "Skip Ad"). */
|
|
38
|
+
skipTextStyle?: StyleProp<TextStyle>;
|
|
39
|
+
/**
|
|
40
|
+
* Safe-area insets, for example `useSafeAreaInsets()`. Optional: without
|
|
41
|
+
* them the screen reads react-native-safe-area-context itself when the app
|
|
42
|
+
* has it, else the status bar height on Android. The controls never sit
|
|
43
|
+
* higher or lower than in 0.1 (56 from the top, 44 from the bottom); insets
|
|
44
|
+
* only move them inward.
|
|
45
|
+
*/
|
|
46
|
+
insets?: EthiclyInsets;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const TICK_MS = 250;
|
|
50
|
+
|
|
51
|
+
/** Space between the safe area and the controls. */
|
|
52
|
+
const TOP_GAP = 12;
|
|
53
|
+
const BOTTOM_GAP = 10;
|
|
54
|
+
const SIDE_GAP_TOP = 16;
|
|
55
|
+
const SIDE_GAP_BOTTOM = 20;
|
|
56
|
+
/**
|
|
57
|
+
* The 0.1 layout (controls 56 from the top, 44 from the bottom) is a floor:
|
|
58
|
+
* insets only ever move the controls inward, so a phone without a notch or a
|
|
59
|
+
* tall status bar looks exactly as before.
|
|
60
|
+
*/
|
|
61
|
+
const MIN_TOP = 56;
|
|
62
|
+
const MIN_BOTTOM = 44;
|
|
63
|
+
|
|
64
|
+
interface SafeAreaModule {
|
|
65
|
+
SafeAreaInsetsContext?: React.Context<EthiclyInsets | null>;
|
|
66
|
+
initialWindowMetrics?: { insets?: EthiclyInsets } | null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* react-native-safe-area-context when the app has it, else null. Metro treats
|
|
71
|
+
* a require inside try/catch as an optional dependency (the React Native and
|
|
72
|
+
* Expo Metro configs set allowOptionalDependencies), so an app without the
|
|
73
|
+
* package still builds.
|
|
74
|
+
*/
|
|
75
|
+
function loadSafeArea(): SafeAreaModule | null {
|
|
76
|
+
try {
|
|
77
|
+
// @ts-ignore: the build compiles without Node's types, where require is undeclared.
|
|
78
|
+
return typeof require === 'function' ? (require('react-native-safe-area-context') as SafeAreaModule) : null;
|
|
79
|
+
} catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const safeArea = loadSafeArea();
|
|
85
|
+
const noInsets = React.createContext<EthiclyInsets | null>(null);
|
|
86
|
+
// Read with useContext, which returns null without a SafeAreaProvider instead
|
|
87
|
+
// of throwing like useSafeAreaInsets(). Fixed at load, so hook order never changes.
|
|
88
|
+
const InsetsContext: React.Context<EthiclyInsets | null> =
|
|
89
|
+
safeArea && safeArea.SafeAreaInsetsContext && typeof safeArea.SafeAreaInsetsContext === 'object'
|
|
90
|
+
? safeArea.SafeAreaInsetsContext
|
|
91
|
+
: noInsets;
|
|
92
|
+
|
|
93
|
+
function validInsets(v: unknown): EthiclyInsets | null {
|
|
94
|
+
const i = v as Partial<EthiclyInsets> | null | undefined;
|
|
95
|
+
if (!i || typeof i !== 'object') return null;
|
|
96
|
+
const n = (x: unknown) => (typeof x === 'number' && Number.isFinite(x) && x >= 0 ? x : 0);
|
|
97
|
+
if (typeof i.top !== 'number' && typeof i.bottom !== 'number') return null;
|
|
98
|
+
return { top: n(i.top), bottom: n(i.bottom), left: n(i.left), right: n(i.right) };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The `insets` prop, else the provider's insets, else the window's first metrics, else the status bar. */
|
|
102
|
+
function useSafeInsets(prop: EthiclyInsets | undefined): EthiclyInsets {
|
|
103
|
+
const fromProvider = useContext(InsetsContext);
|
|
104
|
+
return validInsets(prop)
|
|
105
|
+
?? validInsets(fromProvider)
|
|
106
|
+
?? validInsets(safeArea?.initialWindowMetrics?.insets)
|
|
107
|
+
?? { top: Platform.OS === 'android' ? StatusBar.currentHeight ?? 0 : 0, bottom: 0, left: 0, right: 0 };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function EthiclyInterstitial(props: EthiclyInterstitialProps): React.ReactElement {
|
|
111
|
+
// Android back: a Modal receives it through onRequestClose, an inline screen
|
|
112
|
+
// through BackHandler. Either way it closes the ad only once Skip is allowed,
|
|
113
|
+
// and is swallowed before that.
|
|
114
|
+
const backRef = useRef<(() => void) | null>(null);
|
|
115
|
+
const inline = props.modal === false;
|
|
116
|
+
useEffect(() => {
|
|
117
|
+
if (!inline) return undefined;
|
|
118
|
+
const sub = BackHandler.addEventListener('hardwareBackPress', () => {
|
|
119
|
+
backRef.current?.();
|
|
120
|
+
return true;
|
|
121
|
+
});
|
|
122
|
+
return () => sub.remove();
|
|
123
|
+
}, [inline]);
|
|
124
|
+
|
|
125
|
+
const body = <InterstitialBody {...props} backRef={backRef} />;
|
|
126
|
+
if (inline) return body;
|
|
127
|
+
return (
|
|
128
|
+
<Modal visible animationType="fade" presentationStyle="fullScreen" statusBarTranslucent onRequestClose={() => backRef.current?.()}>
|
|
129
|
+
{body}
|
|
130
|
+
</Modal>
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function useAppActive(): boolean {
|
|
135
|
+
const [active, setActive] = useState(AppState.currentState === 'active');
|
|
136
|
+
useEffect(() => {
|
|
137
|
+
const sub = AppState.addEventListener('change', (s: AppStateStatus) => setActive(s === 'active'));
|
|
138
|
+
return () => sub.remove();
|
|
139
|
+
}, []);
|
|
140
|
+
return active;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
interface BodyProps extends EthiclyInterstitialProps {
|
|
144
|
+
backRef: React.MutableRefObject<(() => void) | null>;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function InterstitialBody({
|
|
148
|
+
ad, tracker, onClose, onRemoveAds, removeAdsLabel, renderBelowButton, skipStyle, skipTextStyle, insets, backRef,
|
|
149
|
+
}: BodyProps) {
|
|
150
|
+
const safe = useSafeInsets(insets);
|
|
151
|
+
const isVideo = ad.media.kind === 'video' && !!ad.media.videoUri;
|
|
152
|
+
const appActive = useAppActive();
|
|
153
|
+
const activeRef = useRef(appActive);
|
|
154
|
+
activeRef.current = appActive;
|
|
155
|
+
|
|
156
|
+
const [positionMs, setPositionMs] = useState(0);
|
|
157
|
+
const [ended, setEnded] = useState(false);
|
|
158
|
+
const [failed, setFailed] = useState(false);
|
|
159
|
+
const [muted, setMuted] = useState(ad.audio !== 'on');
|
|
160
|
+
/** Wall-clock time on screen with the app in the foreground. */
|
|
161
|
+
const [onScreenMs, setOnScreenMs] = useState(0);
|
|
162
|
+
const [clicked, setClicked] = useState(false);
|
|
163
|
+
const positionRef = useRef(0);
|
|
164
|
+
const closedRef = useRef(false);
|
|
165
|
+
|
|
166
|
+
const player = useVideoPlayer(isVideo ? ad.media.videoUri : null, (p) => {
|
|
167
|
+
p.loop = false;
|
|
168
|
+
p.muted = ad.audio !== 'on';
|
|
169
|
+
p.timeUpdateEventInterval = TICK_MS / 1000;
|
|
170
|
+
p.play();
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
const onCloseRef = useRef(onClose);
|
|
174
|
+
onCloseRef.current = onClose;
|
|
175
|
+
|
|
176
|
+
// The impression goes out the moment the ad is on screen. shown() refuses an
|
|
177
|
+
// ad past its token lifetime (nothing is recorded), so the screen closes
|
|
178
|
+
// itself instead of playing an ad nobody is paid for.
|
|
179
|
+
useEffect(() => {
|
|
180
|
+
const expired = tracker.isExpired();
|
|
181
|
+
void tracker.shown();
|
|
182
|
+
if (expired && !closedRef.current) {
|
|
183
|
+
closedRef.current = true;
|
|
184
|
+
void tracker.closed();
|
|
185
|
+
onCloseRef.current();
|
|
186
|
+
}
|
|
187
|
+
}, [tracker]);
|
|
188
|
+
|
|
189
|
+
// Video: playback position drives viewability, quartiles and the skip countdown.
|
|
190
|
+
useEffect(() => {
|
|
191
|
+
if (!isVideo) return undefined;
|
|
192
|
+
const subs = [
|
|
193
|
+
player.addListener('timeUpdate', ({ currentTime }) => {
|
|
194
|
+
const ms = Math.max(0, currentTime * 1000);
|
|
195
|
+
positionRef.current = ms;
|
|
196
|
+
setPositionMs(ms);
|
|
197
|
+
const durationMs = player.duration > 0 ? player.duration * 1000 : undefined;
|
|
198
|
+
tracker.progress(ms, { visible: activeRef.current && player.playing, durationMs });
|
|
199
|
+
}),
|
|
200
|
+
player.addListener('playToEnd', () => {
|
|
201
|
+
setEnded(true);
|
|
202
|
+
tracker.complete();
|
|
203
|
+
}),
|
|
204
|
+
player.addListener('statusChange', ({ status }) => {
|
|
205
|
+
if (status === 'error') {
|
|
206
|
+
setFailed(true);
|
|
207
|
+
tracker.error();
|
|
208
|
+
}
|
|
209
|
+
}),
|
|
210
|
+
];
|
|
211
|
+
return () => subs.forEach((s) => s.remove());
|
|
212
|
+
}, [isVideo, player, tracker]);
|
|
213
|
+
|
|
214
|
+
// Time on screen while the app is in the foreground. For a still image it is
|
|
215
|
+
// the playback position; for a video it is the skip countdown's fallback, so
|
|
216
|
+
// Skip still appears after skipAfterMs if the video stalls or never starts.
|
|
217
|
+
useEffect(() => {
|
|
218
|
+
let shownMs = 0;
|
|
219
|
+
const id = setInterval(() => {
|
|
220
|
+
if (activeRef.current) shownMs += TICK_MS;
|
|
221
|
+
setOnScreenMs(shownMs);
|
|
222
|
+
if (isVideo) return;
|
|
223
|
+
positionRef.current = shownMs;
|
|
224
|
+
setPositionMs(shownMs);
|
|
225
|
+
tracker.progress(shownMs, { visible: activeRef.current });
|
|
226
|
+
}, TICK_MS);
|
|
227
|
+
return () => clearInterval(id);
|
|
228
|
+
}, [isVideo, tracker]);
|
|
229
|
+
|
|
230
|
+
useEffect(() => {
|
|
231
|
+
if (!isVideo) return;
|
|
232
|
+
if (appActive && !ended) player.play();
|
|
233
|
+
else player.pause();
|
|
234
|
+
}, [appActive, ended, isVideo, player]);
|
|
235
|
+
|
|
236
|
+
// Leaving the foreground ends continuous visibility right away, without
|
|
237
|
+
// waiting for the next player tick (which may never come while paused).
|
|
238
|
+
useEffect(() => {
|
|
239
|
+
if (appActive) return;
|
|
240
|
+
const durationMs = isVideo && player.duration > 0 ? player.duration * 1000 : undefined;
|
|
241
|
+
tracker.progress(positionRef.current, { visible: false, durationMs });
|
|
242
|
+
}, [appActive, isVideo, player, tracker]);
|
|
243
|
+
|
|
244
|
+
// The tracker is closed only from close() below (or by the hook's dismiss()),
|
|
245
|
+
// never from an effect cleanup: React StrictMode runs every cleanup once on
|
|
246
|
+
// mount, and a closed tracker drops /viewable and the video events.
|
|
247
|
+
|
|
248
|
+
const close = useCallback(() => {
|
|
249
|
+
if (closedRef.current) return;
|
|
250
|
+
closedRef.current = true;
|
|
251
|
+
if (isVideo && !ended && !failed) tracker.skipped(positionRef.current);
|
|
252
|
+
void tracker.closed();
|
|
253
|
+
onClose();
|
|
254
|
+
}, [ended, failed, isVideo, onClose, tracker]);
|
|
255
|
+
|
|
256
|
+
const onCta = useCallback(() => {
|
|
257
|
+
if (isVideo) player.pause();
|
|
258
|
+
// Once the user has visited the advertiser, they can always close the ad
|
|
259
|
+
// when they come back.
|
|
260
|
+
setClicked(true);
|
|
261
|
+
void tracker.clicked();
|
|
262
|
+
}, [isVideo, player, tracker]);
|
|
263
|
+
|
|
264
|
+
const toggleSound = useCallback(() => {
|
|
265
|
+
setMuted((m) => {
|
|
266
|
+
player.muted = !m;
|
|
267
|
+
return !m;
|
|
268
|
+
});
|
|
269
|
+
}, [player]);
|
|
270
|
+
|
|
271
|
+
const remainingS = Math.ceil(Math.max(0, ad.skipAfterMs - Math.max(positionMs, onScreenMs)) / 1000);
|
|
272
|
+
const canSkip = remainingS === 0 || ended || failed || clicked;
|
|
273
|
+
backRef.current = canSkip ? close : null;
|
|
274
|
+
|
|
275
|
+
return (
|
|
276
|
+
<View style={styles.root}>
|
|
277
|
+
{isVideo ? (
|
|
278
|
+
<>
|
|
279
|
+
{ad.media.posterUri ? <Image source={{ uri: ad.media.posterUri }} style={StyleSheet.absoluteFill} resizeMode="cover" /> : null}
|
|
280
|
+
<VideoView player={player} style={StyleSheet.absoluteFill} contentFit="cover" nativeControls={false} allowsFullscreen={false} allowsPictureInPicture={false} />
|
|
281
|
+
</>
|
|
282
|
+
) : (
|
|
283
|
+
<Image source={{ uri: ad.media.uri }} style={StyleSheet.absoluteFill} resizeMode="cover" />
|
|
284
|
+
)}
|
|
285
|
+
|
|
286
|
+
<View
|
|
287
|
+
style={[styles.topRow, { top: Math.max(safe.top + TOP_GAP, MIN_TOP), left: safe.left + SIDE_GAP_TOP, right: safe.right + SIDE_GAP_TOP }]}
|
|
288
|
+
pointerEvents="box-none"
|
|
289
|
+
>
|
|
290
|
+
<View style={styles.leftGroup}>
|
|
291
|
+
<Text style={styles.adLabel} accessibilityRole="text">Ad</Text>
|
|
292
|
+
{isVideo && ad.audio !== 'none' ? (
|
|
293
|
+
<Pressable onPress={toggleSound} style={styles.soundButton} accessibilityRole="button" accessibilityLabel={muted ? 'Turn sound on' : 'Mute'} hitSlop={8}>
|
|
294
|
+
<Text style={styles.soundText}>{muted ? 'Sound off' : 'Sound on'}</Text>
|
|
295
|
+
</Pressable>
|
|
296
|
+
) : null}
|
|
297
|
+
</View>
|
|
298
|
+
<Pressable
|
|
299
|
+
onPress={canSkip ? close : undefined}
|
|
300
|
+
disabled={!canSkip}
|
|
301
|
+
style={[styles.skip, skipStyle]}
|
|
302
|
+
accessibilityRole="button"
|
|
303
|
+
accessibilityLabel={canSkip ? 'Skip ad' : `Skip in ${remainingS} seconds`}
|
|
304
|
+
hitSlop={8}
|
|
305
|
+
>
|
|
306
|
+
{canSkip ? (
|
|
307
|
+
<View style={styles.skipRow}>
|
|
308
|
+
<Text style={[styles.skipText, skipTextStyle]}>Skip Ad</Text>
|
|
309
|
+
<SkipIcon />
|
|
310
|
+
</View>
|
|
311
|
+
) : (
|
|
312
|
+
<Text style={[styles.skipText, styles.skipTextWaiting, skipTextStyle]}>{`Skip in ${remainingS}`}</Text>
|
|
313
|
+
)}
|
|
314
|
+
</Pressable>
|
|
315
|
+
</View>
|
|
316
|
+
|
|
317
|
+
<View
|
|
318
|
+
style={[styles.bottom, {
|
|
319
|
+
bottom: Math.max(safe.bottom + BOTTOM_GAP, MIN_BOTTOM), left: safe.left + SIDE_GAP_BOTTOM, right: safe.right + SIDE_GAP_BOTTOM,
|
|
320
|
+
}]}
|
|
321
|
+
pointerEvents="box-none"
|
|
322
|
+
>
|
|
323
|
+
<Pressable onPress={onCta} style={({ pressed }) => [styles.cta, pressed && styles.ctaPressed]} accessibilityRole="link">
|
|
324
|
+
<Text style={styles.ctaText} numberOfLines={1}>{ad.ctaLabel || 'Learn more'}</Text>
|
|
325
|
+
</Pressable>
|
|
326
|
+
{renderBelowButton ? renderBelowButton() : onRemoveAds ? (
|
|
327
|
+
<Pressable onPress={onRemoveAds} accessibilityRole="button" hitSlop={8}>
|
|
328
|
+
<Text style={styles.removeAds}>{removeAdsLabel || 'Remove ads'}</Text>
|
|
329
|
+
</Pressable>
|
|
330
|
+
) : null}
|
|
331
|
+
<Text style={styles.sponsor}>Sponsored by Ethicly.ch</Text>
|
|
332
|
+
</View>
|
|
333
|
+
</View>
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Skip-to-end mark (a play triangle against a bar), drawn so it never depends on a font glyph. */
|
|
338
|
+
function SkipIcon() {
|
|
339
|
+
return (
|
|
340
|
+
<View style={styles.skipIcon} accessibilityElementsHidden importantForAccessibility="no-hide-descendants">
|
|
341
|
+
<View style={styles.skipTriangle} />
|
|
342
|
+
<View style={styles.skipBar} />
|
|
343
|
+
</View>
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const styles = StyleSheet.create({
|
|
348
|
+
root: { flex: 1, backgroundColor: '#000' },
|
|
349
|
+
topRow: {
|
|
350
|
+
position: 'absolute',
|
|
351
|
+
flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center',
|
|
352
|
+
},
|
|
353
|
+
leftGroup: { flexDirection: 'row', alignItems: 'center' },
|
|
354
|
+
adLabel: {
|
|
355
|
+
color: '#fff', fontSize: 11, fontWeight: '600', letterSpacing: 0.5,
|
|
356
|
+
backgroundColor: 'rgba(0,0,0,0.45)', paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4, overflow: 'hidden',
|
|
357
|
+
},
|
|
358
|
+
soundButton: { marginLeft: 8, backgroundColor: 'rgba(0,0,0,0.45)', paddingHorizontal: 8, paddingVertical: 4, borderRadius: 6 },
|
|
359
|
+
soundText: { color: '#fff', fontSize: 12, fontWeight: '500' },
|
|
360
|
+
// Solid black, no blur or translucency. The faint hairline keeps the edge
|
|
361
|
+
// visible over a dark frame.
|
|
362
|
+
skip: {
|
|
363
|
+
backgroundColor: '#000', paddingHorizontal: 18, height: 40, borderRadius: 20,
|
|
364
|
+
justifyContent: 'center', alignItems: 'center',
|
|
365
|
+
borderWidth: StyleSheet.hairlineWidth, borderColor: 'rgba(255,255,255,0.22)',
|
|
366
|
+
},
|
|
367
|
+
skipRow: { flexDirection: 'row', alignItems: 'center' },
|
|
368
|
+
skipText: { color: '#fff', fontSize: 15, fontWeight: '500', letterSpacing: 0.2 },
|
|
369
|
+
skipTextWaiting: { opacity: 0.75 },
|
|
370
|
+
skipIcon: { flexDirection: 'row', alignItems: 'center', marginLeft: 10 },
|
|
371
|
+
skipTriangle: {
|
|
372
|
+
width: 0, height: 0,
|
|
373
|
+
borderTopWidth: 6, borderBottomWidth: 6, borderLeftWidth: 10,
|
|
374
|
+
borderTopColor: 'transparent', borderBottomColor: 'transparent', borderLeftColor: '#fff',
|
|
375
|
+
},
|
|
376
|
+
skipBar: { width: 2, height: 12, backgroundColor: '#fff', marginLeft: 2, borderRadius: 1 },
|
|
377
|
+
bottom: { position: 'absolute', alignItems: 'center' },
|
|
378
|
+
cta: {
|
|
379
|
+
alignSelf: 'stretch', backgroundColor: '#fff', borderRadius: 12, paddingVertical: 15,
|
|
380
|
+
alignItems: 'center', justifyContent: 'center',
|
|
381
|
+
},
|
|
382
|
+
ctaPressed: { opacity: 0.85 },
|
|
383
|
+
ctaText: { color: '#000', fontSize: 17, fontWeight: '600' },
|
|
384
|
+
removeAds: { color: '#fff', fontSize: 14, marginTop: 14, textDecorationLine: 'underline', opacity: 0.9 },
|
|
385
|
+
sponsor: { color: '#fff', fontSize: 12, marginTop: 10, opacity: 0.6 },
|
|
386
|
+
});
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// React hook over the headless core. No React Native or Expo imports, so it
|
|
2
|
+
// works with any player the host app already has.
|
|
3
|
+
|
|
4
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
5
|
+
import type { Ethicly } from '../core/client';
|
|
6
|
+
import type { EthiclyAd, NoFillReason, Tracker } from '../core/types';
|
|
7
|
+
|
|
8
|
+
export interface UseEthiclyInterstitialOptions {
|
|
9
|
+
/** Preload on mount and after each dismiss. Default true. */
|
|
10
|
+
preload?: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface EthiclyInterstitialState {
|
|
14
|
+
/** The ad to render, set by a successful show(). */
|
|
15
|
+
ad: EthiclyAd | null;
|
|
16
|
+
tracker: Tracker | null;
|
|
17
|
+
/** Why the last show() found no ad (show your house ad). */
|
|
18
|
+
reason: NoFillReason | null;
|
|
19
|
+
loading: boolean;
|
|
20
|
+
/** Load the ad to show now. Resolves true when `ad` is set, false on no fill. */
|
|
21
|
+
show(): Promise<boolean>;
|
|
22
|
+
/** Close the current ad: flushes queued events and preloads the next one. */
|
|
23
|
+
dismiss(): void;
|
|
24
|
+
canShow(): boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function useEthiclyInterstitial(
|
|
28
|
+
ethicly: Ethicly,
|
|
29
|
+
options: UseEthiclyInterstitialOptions = {},
|
|
30
|
+
): EthiclyInterstitialState {
|
|
31
|
+
const preload = options.preload !== false;
|
|
32
|
+
const [current, setCurrent] = useState<{ ad: EthiclyAd; tracker: Tracker } | null>(null);
|
|
33
|
+
const [reason, setReason] = useState<NoFillReason | null>(null);
|
|
34
|
+
const [loading, setLoading] = useState(false);
|
|
35
|
+
const mounted = useRef(true);
|
|
36
|
+
const currentRef = useRef(current);
|
|
37
|
+
currentRef.current = current;
|
|
38
|
+
|
|
39
|
+
useEffect(() => {
|
|
40
|
+
mounted.current = true;
|
|
41
|
+
if (preload) void ethicly.preload();
|
|
42
|
+
return () => {
|
|
43
|
+
mounted.current = false;
|
|
44
|
+
void currentRef.current?.tracker.closed();
|
|
45
|
+
};
|
|
46
|
+
}, [ethicly, preload]);
|
|
47
|
+
|
|
48
|
+
const show = useCallback(async (): Promise<boolean> => {
|
|
49
|
+
setLoading(true);
|
|
50
|
+
try {
|
|
51
|
+
const r = await ethicly.loadInterstitial();
|
|
52
|
+
if (!mounted.current) return false;
|
|
53
|
+
if (r.ad) {
|
|
54
|
+
setCurrent({ ad: r.ad, tracker: r.tracker });
|
|
55
|
+
setReason(null);
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
setReason(r.reason);
|
|
59
|
+
return false;
|
|
60
|
+
} finally {
|
|
61
|
+
if (mounted.current) setLoading(false);
|
|
62
|
+
}
|
|
63
|
+
}, [ethicly]);
|
|
64
|
+
|
|
65
|
+
const dismiss = useCallback(() => {
|
|
66
|
+
void currentRef.current?.tracker.closed();
|
|
67
|
+
setCurrent(null);
|
|
68
|
+
if (preload) void ethicly.preload();
|
|
69
|
+
}, [ethicly, preload]);
|
|
70
|
+
|
|
71
|
+
const canShow = useCallback(() => ethicly.canShow(), [ethicly]);
|
|
72
|
+
|
|
73
|
+
return { ad: current?.ad ?? null, tracker: current?.tracker ?? null, reason, loading, show, dismiss, canShow };
|
|
74
|
+
}
|
package/src/version.ts
ADDED