@leisuresaas/react 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) LeisureSaaS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,14 @@
1
+ # @leisuresaas/react
2
+
3
+ 浏览器产品前端 SDK:产品账号、OAuth PKCE、Public Ads、Drive。
4
+
5
+ 没有 Expo,也没有 Integration Key。App 用 `@leisuresaas/react-native`。
6
+
7
+ ```ts
8
+ import { loginProductAccount } from "@leisuresaas/react/auth";
9
+ import { beginPlatformLogin } from "@leisuresaas/react/oauth";
10
+ ```
11
+
12
+ 环境变量:`NEXT_PUBLIC_GATEWAY_URL`、`NEXT_PUBLIC_PUBLISHABLE_KEY`、`NEXT_PUBLIC_OAUTH_ISSUER`。
13
+
14
+ 说明见 `AGENTS.md`。
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@leisuresaas/react",
3
+ "version": "0.1.0",
4
+ "description": "Browser SDK for LeisureSaas: product auth, OAuth PKCE, Public Ads, Drive. No Expo or Integration Key.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/leisuresaas/react.git"
9
+ },
10
+ "main": "src/index.ts",
11
+ "types": "src/index.ts",
12
+ "sideEffects": false,
13
+ "files": [
14
+ "src",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "exports": {
19
+ ".": "./src/index.ts",
20
+ "./auth": "./src/auth.ts",
21
+ "./oauth": "./src/oauth.ts",
22
+ "./ads": "./src/ads-ui.tsx",
23
+ "./drive": "./src/drive.ts",
24
+ "./app-config": "./src/app-config.ts"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public",
28
+ "registry": "https://registry.npmjs.org"
29
+ },
30
+ "scripts": {
31
+ "typecheck": "tsc --noEmit"
32
+ },
33
+ "peerDependencies": {
34
+ "react": ">=18.0.0"
35
+ },
36
+ "devDependencies": {
37
+ "@types/node": "^20.19.43",
38
+ "@types/react": "~19.2.2",
39
+ "typescript": "~5.9.2"
40
+ }
41
+ }
@@ -0,0 +1,55 @@
1
+ export type AdType = "text" | "image";
2
+
3
+ export type TextLayout = "text_inline" | "text_callout" | "text_footer" | "text_sidebar" | "text_minimal";
4
+
5
+ export type ImageLayout = "image_hero" | "image_card" | "image_strip" | "image_thumbnail" | "image_inline";
6
+
7
+ export type AdLayout = TextLayout | ImageLayout;
8
+
9
+ export type AdRotationMode = "none" | "fade" | "slide" | "stack";
10
+
11
+ export const AD_TYPES: readonly AdType[] = ["text", "image"] as const;
12
+ export const TEXT_LAYOUTS: readonly TextLayout[] = [
13
+ "text_inline", "text_callout", "text_footer", "text_sidebar", "text_minimal",
14
+ ] as const;
15
+ export const IMAGE_LAYOUTS: readonly ImageLayout[] = [
16
+ "image_hero", "image_card", "image_strip", "image_thumbnail", "image_inline",
17
+ ] as const;
18
+ export const AD_ROTATION_MODES: readonly AdRotationMode[] = ["none", "fade", "slide", "stack"] as const;
19
+
20
+ export const IMPRESSION_MIN_DWELL_MS = 300;
21
+
22
+ export function layoutsForType(type: AdType): readonly AdLayout[] {
23
+ return type === "text" ? TEXT_LAYOUTS : IMAGE_LAYOUTS;
24
+ }
25
+
26
+ export function defaultLayoutForType(type: AdType): AdLayout {
27
+ return type === "text" ? "text_inline" : "image_hero";
28
+ }
29
+
30
+ export function normalizeAdType(raw?: string): AdType {
31
+ return (raw ?? "").trim() === "image" ? "image" : "text";
32
+ }
33
+
34
+ export function normalizeLayout(type: AdType, raw?: string): AdLayout {
35
+ const key = (raw ?? "").trim();
36
+ const allowed = layoutsForType(type);
37
+ if (allowed.includes(key as AdLayout)) {
38
+ return key as AdLayout;
39
+ }
40
+ return defaultLayoutForType(type);
41
+ }
42
+
43
+ export function normalizeRotationMode(raw?: string, enabled?: boolean): AdRotationMode {
44
+ if (!enabled) return "none";
45
+ const key = (raw ?? "").trim() as AdRotationMode;
46
+ return AD_ROTATION_MODES.includes(key) ? key : "fade";
47
+ }
48
+
49
+ export function effectiveRotationMode(
50
+ rotation?: { enabled?: boolean; mode?: string },
51
+ adCount = 0,
52
+ ): AdRotationMode {
53
+ if (adCount <= 1 || !rotation?.enabled) return "none";
54
+ return normalizeRotationMode(rotation.mode, true);
55
+ }
@@ -0,0 +1,62 @@
1
+ "use client";
2
+
3
+ import { createContext, useContext, useMemo, type ReactNode } from "react";
4
+
5
+ import type { PublicAdsRequestContext } from "./ads-http";
6
+ import { resolveGatewayUrlFromEnv } from "./gateway-url";
7
+ import { resolvePublishableKeyFromEnv } from "./publishable-key";
8
+
9
+ export type InAppNavigate = (path: string) => void;
10
+
11
+ export type AdsProviderProps = {
12
+ publishableKey?: string;
13
+ gatewayUrl?: string;
14
+ origin?: string;
15
+ resolveAccessToken?: () => Promise<string | null>;
16
+ onInAppNavigate?: InAppNavigate;
17
+ children: ReactNode;
18
+ };
19
+
20
+ type AdsContextValue = {
21
+ resolveAccessToken?: () => Promise<string | null>;
22
+ onInAppNavigate?: InAppNavigate;
23
+ publicAds?: PublicAdsRequestContext;
24
+ };
25
+
26
+ const AdsContext = createContext<AdsContextValue | null>(null);
27
+
28
+ export function AdsProvider({
29
+ publishableKey,
30
+ gatewayUrl,
31
+ origin,
32
+ resolveAccessToken,
33
+ onInAppNavigate,
34
+ children,
35
+ }: AdsProviderProps) {
36
+ const value = useMemo((): AdsContextValue => {
37
+ const key = publishableKey?.trim() || resolvePublishableKeyFromEnv();
38
+ const base = gatewayUrl?.trim() || resolveGatewayUrlFromEnv() || "";
39
+ const site = origin?.trim()
40
+ || (typeof window !== "undefined" ? window.location.origin : "")
41
+ || process.env.NEXT_PUBLIC_APP_URL?.trim()
42
+ || "";
43
+ const publicAds = key && base && site
44
+ ? { gatewayUrl: base, publishableKey: key, origin: site }
45
+ : undefined;
46
+ return { resolveAccessToken, onInAppNavigate, publicAds };
47
+ }, [publishableKey, gatewayUrl, origin, resolveAccessToken, onInAppNavigate]);
48
+
49
+ return <AdsContext.Provider value={value}>{children}</AdsContext.Provider>;
50
+ }
51
+
52
+ export function useAdsContext(): AdsContextValue {
53
+ const ctx = useContext(AdsContext);
54
+ if (!ctx) {
55
+ throw new Error("useAdsContext must be used within AdsProvider");
56
+ }
57
+ return ctx;
58
+ }
59
+
60
+ export function useOptionalAdsContext(): AdsContextValue | null {
61
+ return useContext(AdsContext);
62
+ }
@@ -0,0 +1,143 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useRef, useState } from "react";
4
+
5
+ import { getPublicAdsFeed, recordPublicAdEvents, type AdFeedItem, type AdFeedRotation, type AdsFeedResponse } from "./ads-http";
6
+ import { IMPRESSION_MIN_DWELL_MS } from "./ads-constants";
7
+ import { useAdsContext, useOptionalAdsContext } from "./ads-context";
8
+
9
+ const SESSION_KEY = "leisuresaas_ads_session_id";
10
+ const impressionRecorded = new Set<string>();
11
+
12
+ function adsSessionId(): string {
13
+ if (typeof sessionStorage === "undefined") {
14
+ return "web";
15
+ }
16
+ const existing = sessionStorage.getItem(SESSION_KEY)?.trim();
17
+ if (existing) return existing;
18
+ const id = crypto.randomUUID();
19
+ sessionStorage.setItem(SESSION_KEY, id);
20
+ return id;
21
+ }
22
+
23
+ export type UseAdsFeedResult = {
24
+ feed: AdsFeedResponse | null;
25
+ ad: AdFeedItem | null;
26
+ ads: AdFeedItem[];
27
+ layout?: string;
28
+ rotation?: AdFeedRotation;
29
+ loading: boolean;
30
+ error: Error | null;
31
+ refresh: () => Promise<void>;
32
+ };
33
+
34
+ export function useAdsFeed(options: { placement?: string; enabled?: boolean } = {}): UseAdsFeedResult {
35
+ const { publicAds } = useAdsContext();
36
+ const placement = options.placement ?? "home_banner";
37
+ const enabled = options.enabled ?? true;
38
+ const [feed, setFeed] = useState<AdsFeedResponse | null>(null);
39
+ const [loading, setLoading] = useState(enabled);
40
+ const [error, setError] = useState<Error | null>(null);
41
+
42
+ const refresh = useCallback(async () => {
43
+ if (!enabled) {
44
+ setFeed(null);
45
+ setLoading(false);
46
+ return;
47
+ }
48
+ setLoading(true);
49
+ setError(null);
50
+ try {
51
+ if (!publicAds) {
52
+ setFeed(null);
53
+ setError(new Error("AdsProvider: publishableKey, gatewayUrl, and origin are required"));
54
+ return;
55
+ }
56
+ setFeed(await getPublicAdsFeed(publicAds, placement));
57
+ } catch (err) {
58
+ setError(err instanceof Error ? err : new Error(String(err)));
59
+ setFeed(null);
60
+ } finally {
61
+ setLoading(false);
62
+ }
63
+ }, [publicAds, placement, enabled]);
64
+
65
+ useEffect(() => {
66
+ void refresh();
67
+ }, [refresh]);
68
+
69
+ const ads = feed?.ads ?? [];
70
+ return {
71
+ feed, ad: ads[0] ?? null, ads, layout: feed?.layout, rotation: feed?.rotation,
72
+ loading, error, refresh,
73
+ };
74
+ }
75
+
76
+ export function useAdRotation(ads: AdFeedItem[], rotation?: AdFeedRotation) {
77
+ const [index, setIndex] = useState(0);
78
+ const paused = useRef(false);
79
+ const autoplay = Boolean(rotation?.enabled) && rotation?.autoplay !== false && ads.length > 1;
80
+ const intervalMs = Math.max(1000, (rotation?.interval_sec ?? 5) * 1000);
81
+
82
+ useEffect(() => {
83
+ setIndex(0);
84
+ }, [ads]);
85
+
86
+ useEffect(() => {
87
+ if (!autoplay) return;
88
+ const timer = setInterval(() => {
89
+ if (paused.current) return;
90
+ setIndex((prev) => {
91
+ const next = prev + 1;
92
+ if (next >= ads.length) return rotation?.loop === false ? prev : 0;
93
+ return next;
94
+ });
95
+ }, intervalMs);
96
+ return () => clearInterval(timer);
97
+ }, [ads, autoplay, intervalMs, rotation?.loop]);
98
+
99
+ useEffect(() => {
100
+ const onVis = () => {
101
+ paused.current = document.hidden;
102
+ };
103
+ document.addEventListener("visibilitychange", onVis);
104
+ return () => document.removeEventListener("visibilitychange", onVis);
105
+ }, []);
106
+
107
+ return { index, setIndex, current: ads[index] ?? null, count: ads.length };
108
+ }
109
+
110
+ export function useAdImpression(ad: AdFeedItem | null, placement: string, lineupId: string, element: HTMLElement | null) {
111
+ const optional = useOptionalAdsContext();
112
+ const resolveAccessToken = optional?.resolveAccessToken;
113
+ const publicAds = optional?.publicAds;
114
+ useEffect(() => {
115
+ if (!ad || !publicAds || !element || typeof IntersectionObserver === "undefined") return;
116
+ const key = `${placement}:${lineupId}:${ad.id}`;
117
+ if (impressionRecorded.has(key)) return;
118
+ let timer: ReturnType<typeof setTimeout> | null = null;
119
+ const observer = new IntersectionObserver((entries) => {
120
+ const visible = entries.some((entry) => entry.isIntersecting);
121
+ if (!visible) {
122
+ if (timer) clearTimeout(timer);
123
+ timer = null;
124
+ return;
125
+ }
126
+ if (timer || impressionRecorded.has(key)) return;
127
+ timer = setTimeout(() => {
128
+ impressionRecorded.add(key);
129
+ void (async () => {
130
+ const token = resolveAccessToken ? await resolveAccessToken() : null;
131
+ await recordPublicAdEvents(publicAds, adsSessionId(), [{
132
+ adId: ad.id, eventType: "impression", placementKey: placement, lineupId,
133
+ }], token);
134
+ })();
135
+ }, IMPRESSION_MIN_DWELL_MS);
136
+ }, { threshold: 0.5 });
137
+ observer.observe(element);
138
+ return () => {
139
+ observer.disconnect();
140
+ if (timer) clearTimeout(timer);
141
+ };
142
+ }, [ad, placement, lineupId, element, publicAds, resolveAccessToken]);
143
+ }
@@ -0,0 +1,134 @@
1
+ import { LeisureSaasHttpError } from "./errors";
2
+ import { applyPublishableKeyHeaders } from "./publishable-key";
3
+
4
+ export type AdFeedItem = {
5
+ id: string;
6
+ scope?: string;
7
+ type: string;
8
+ placement?: string;
9
+ priority?: number;
10
+ title?: string;
11
+ body_text?: string;
12
+ image_url?: string;
13
+ click_url?: string;
14
+ };
15
+
16
+ export type AdFeedRotation = {
17
+ enabled: boolean;
18
+ mode: string;
19
+ interval_sec: number;
20
+ loop: boolean;
21
+ autoplay: boolean;
22
+ show_indicators: boolean;
23
+ };
24
+
25
+ export type AdFeedSource = {
26
+ kind: string;
27
+ lineup_id?: string;
28
+ scope: string;
29
+ overridden?: boolean;
30
+ };
31
+
32
+ export type AdsFeedResponse = {
33
+ placement: string;
34
+ surface_key?: string;
35
+ type?: string;
36
+ layout?: string;
37
+ source?: AdFeedSource;
38
+ rotation?: AdFeedRotation;
39
+ ads: AdFeedItem[];
40
+ };
41
+
42
+ export type AdEventInput = {
43
+ adId: string;
44
+ eventType: "impression";
45
+ placementKey?: string;
46
+ lineupId?: string;
47
+ };
48
+
49
+ export type PublicAdsRequestContext = {
50
+ gatewayUrl: string;
51
+ publishableKey: string;
52
+ origin: string;
53
+ };
54
+
55
+ function trimSlash(url: string): string {
56
+ return url.replace(/\/$/, "");
57
+ }
58
+
59
+ function publicAdsHeaders(ctx: PublicAdsRequestContext, accessToken?: string): Record<string, string> {
60
+ const headers: Record<string, string> = {
61
+ Accept: "application/json",
62
+ "X-Ads-Surface-Key": "web",
63
+ "X-Client-Platform": "web",
64
+ };
65
+ applyPublishableKeyHeaders(headers, ctx.publishableKey);
66
+ if (ctx.origin.trim()) {
67
+ headers.Origin = ctx.origin.trim();
68
+ }
69
+ if (accessToken?.trim()) {
70
+ headers.Authorization = `Bearer ${accessToken.trim()}`;
71
+ }
72
+ return headers;
73
+ }
74
+
75
+ async function publicAdsRequest<T>(
76
+ ctx: PublicAdsRequestContext,
77
+ method: "GET" | "POST",
78
+ path: string,
79
+ body?: unknown,
80
+ accessToken?: string,
81
+ ): Promise<T> {
82
+ const base = `${trimSlash(ctx.gatewayUrl)}/v1/public/ads`;
83
+ const url = `${base}${path.startsWith("/") ? path : `/${path}`}`;
84
+ const headers = publicAdsHeaders(ctx, accessToken);
85
+ let payload: string | undefined;
86
+ if (body !== undefined) {
87
+ headers["Content-Type"] = "application/json";
88
+ payload = JSON.stringify(body);
89
+ }
90
+ const res = await fetch(url, { method, headers, body: payload });
91
+ const text = await res.text();
92
+ if (!res.ok) {
93
+ throw new LeisureSaasHttpError(res.status, text.trim());
94
+ }
95
+ if (!text) {
96
+ return {} as T;
97
+ }
98
+ return JSON.parse(text) as T;
99
+ }
100
+
101
+ export async function getPublicAdsFeed(ctx: PublicAdsRequestContext, placement = "home_banner"): Promise<AdsFeedResponse> {
102
+ const q = encodeURIComponent(placement.trim());
103
+ const resp = await publicAdsRequest<AdsFeedResponse>(ctx, "GET", `/feed?placement=${q}`);
104
+ return { ...resp, ads: resp.ads ?? [] };
105
+ }
106
+
107
+ export async function recordPublicAdEvents(
108
+ ctx: PublicAdsRequestContext,
109
+ sessionId: string,
110
+ events: AdEventInput[],
111
+ accessToken?: string | null,
112
+ ): Promise<number> {
113
+ if (events.length === 0) {
114
+ return 0;
115
+ }
116
+ const payload = {
117
+ session_id: sessionId.trim(),
118
+ events: events.map((ev) => {
119
+ const lineupId = ev.lineupId?.trim() ?? "";
120
+ return {
121
+ ad_id: ev.adId,
122
+ event_type: ev.eventType,
123
+ ...(ev.placementKey ? { placement_key: ev.placementKey } : {}),
124
+ ...(lineupId ? { lineup_id: lineupId } : {}),
125
+ };
126
+ }),
127
+ };
128
+ const resp = await publicAdsRequest<{ recorded: number }>(ctx, "POST", "/events", payload, accessToken ?? undefined);
129
+ return resp.recorded ?? 0;
130
+ }
131
+
132
+ export function lineupIdFromSource(source?: AdFeedSource | null): string {
133
+ return source?.lineup_id?.trim() ?? "";
134
+ }
package/src/ads-ui.tsx ADDED
@@ -0,0 +1,215 @@
1
+ "use client";
2
+
3
+ import { useEffect, useState, type CSSProperties, type ReactNode } from "react";
4
+
5
+ import {
6
+ effectiveRotationMode,
7
+ normalizeAdType,
8
+ normalizeLayout,
9
+ type AdLayout,
10
+ type AdType,
11
+ } from "./ads-constants";
12
+ import { useAdsContext, type InAppNavigate } from "./ads-context";
13
+ import { useAdImpression, useAdRotation, useAdsFeed } from "./ads-hooks";
14
+ import { lineupIdFromSource, type AdFeedItem, type AdsFeedResponse } from "./ads-http";
15
+
16
+ export { AdsProvider, useAdsContext } from "./ads-context";
17
+ export type { AdsProviderProps, InAppNavigate } from "./ads-context";
18
+ export { useAdsFeed, useAdRotation } from "./ads-hooks";
19
+ export {
20
+ AD_TYPES,
21
+ IMAGE_LAYOUTS,
22
+ TEXT_LAYOUTS,
23
+ defaultLayoutForType,
24
+ effectiveRotationMode,
25
+ layoutsForType,
26
+ normalizeAdType,
27
+ normalizeLayout,
28
+ normalizeRotationMode,
29
+ } from "./ads-constants";
30
+ export type { AdLayout, AdRotationMode, AdType, ImageLayout, TextLayout } from "./ads-constants";
31
+ export { getPublicAdsFeed, lineupIdFromSource, recordPublicAdEvents } from "./ads-http";
32
+ export type { AdEventInput, AdFeedItem, AdFeedRotation, AdFeedSource, AdsFeedResponse, PublicAdsRequestContext } from "./ads-http";
33
+
34
+ async function openAdClick(url: string, onInAppNavigate?: InAppNavigate) {
35
+ if (!url) return;
36
+ try {
37
+ const res = await fetch(url, {
38
+ method: "GET",
39
+ headers: { Accept: "application/json", "X-Ads-Click": "resolve" },
40
+ });
41
+ const contentType = res.headers.get("content-type") ?? "";
42
+ if (res.ok && contentType.includes("application/json")) {
43
+ const data = (await res.json()) as { kind?: string; path?: string; url?: string };
44
+ if (data.kind === "in_app" && data.path?.startsWith("/")) {
45
+ onInAppNavigate?.(data.path);
46
+ return;
47
+ }
48
+ if (data.kind === "external" && data.url?.startsWith("https://")) {
49
+ window.open(data.url, "_blank", "noopener,noreferrer");
50
+ return;
51
+ }
52
+ }
53
+ } catch {
54
+ /* fall through */
55
+ }
56
+ window.open(url, "_blank", "noopener,noreferrer");
57
+ }
58
+
59
+ function layoutStyle(layout: AdLayout): CSSProperties {
60
+ if (layout === "text_footer" || layout === "image_strip") {
61
+ return { display: "flex", gap: 12, alignItems: "center" };
62
+ }
63
+ if (layout === "text_sidebar" || layout === "image_thumbnail") {
64
+ return { display: "grid", gridTemplateColumns: "72px 1fr", gap: 12, alignItems: "center" };
65
+ }
66
+ if (layout === "text_minimal") {
67
+ return { fontSize: 13 };
68
+ }
69
+ return { display: "grid", gap: 8 };
70
+ }
71
+
72
+ function Creative({
73
+ ad,
74
+ layout,
75
+ onClick,
76
+ }: {
77
+ ad: AdFeedItem;
78
+ layout: AdLayout;
79
+ onClick: () => void;
80
+ }) {
81
+ const image = ad.image_url?.trim();
82
+ return (
83
+ <button
84
+ type="button"
85
+ onClick={onClick}
86
+ style={{
87
+ ...layoutStyle(layout),
88
+ width: "100%",
89
+ textAlign: "left",
90
+ border: "1px solid #e2e8f0",
91
+ borderRadius: 12,
92
+ background: "#fff",
93
+ padding: layout === "text_minimal" ? 8 : 12,
94
+ cursor: "pointer",
95
+ }}
96
+ >
97
+ {image ? (
98
+ <img
99
+ src={image}
100
+ alt=""
101
+ style={{
102
+ width: layout === "image_thumbnail" || layout === "text_sidebar" ? 72 : "100%",
103
+ height: layout === "image_hero" ? 160 : layout === "image_strip" ? 72 : 96,
104
+ objectFit: "cover",
105
+ borderRadius: 8,
106
+ }}
107
+ />
108
+ ) : null}
109
+ <span>
110
+ {ad.title ? <strong style={{ display: "block" }}>{ad.title}</strong> : null}
111
+ {ad.body_text ? <span style={{ display: "block", color: "#64748b" }}>{ad.body_text}</span> : null}
112
+ </span>
113
+ </button>
114
+ );
115
+ }
116
+
117
+ export type AdPreviewProps = {
118
+ ad: AdFeedItem;
119
+ placement?: string;
120
+ type?: string;
121
+ layout?: string;
122
+ lineupId?: string;
123
+ onInAppNavigate?: InAppNavigate;
124
+ };
125
+
126
+ export function AdPreview({ ad, placement = "home_banner", type, layout, lineupId = "", onInAppNavigate }: AdPreviewProps) {
127
+ const adType = normalizeAdType(type ?? ad.type);
128
+ const resolved = normalizeLayout(adType, layout);
129
+ const [node, setNode] = useState<HTMLDivElement | null>(null);
130
+ useAdImpression(ad, placement, lineupId, node);
131
+ return (
132
+ <div ref={setNode}>
133
+ <Creative ad={ad} layout={resolved} onClick={() => void openAdClick(ad.click_url ?? "", onInAppNavigate)} />
134
+ </div>
135
+ );
136
+ }
137
+
138
+ export function AdSlotView({
139
+ feed,
140
+ placement,
141
+ showIndicators,
142
+ }: {
143
+ feed: AdsFeedResponse;
144
+ placement: string;
145
+ showIndicators?: boolean;
146
+ }) {
147
+ const { onInAppNavigate } = useAdsContext();
148
+ const ads = feed.ads ?? [];
149
+ const rotation = useAdRotation(ads, feed.rotation);
150
+ const ad = rotation.current;
151
+ const adType = normalizeAdType(feed.type ?? ad?.type);
152
+ const layout = normalizeLayout(adType, feed.layout);
153
+ const lineupId = lineupIdFromSource(feed.source);
154
+ const [node, setNode] = useState<HTMLDivElement | null>(null);
155
+ useAdImpression(ad, placement, lineupId, node);
156
+ const mode = effectiveRotationMode(feed.rotation, ads.length);
157
+ const indicators = showIndicators ?? feed.rotation?.show_indicators ?? mode !== "none";
158
+ if (!ad) return null;
159
+ return (
160
+ <div ref={setNode}>
161
+ <Creative ad={ad} layout={layout} onClick={() => void openAdClick(ad.click_url ?? "", onInAppNavigate)} />
162
+ {indicators && rotation.count > 1 ? (
163
+ <div style={{ display: "flex", gap: 6, marginTop: 8 }}>
164
+ {ads.map((item, i) => (
165
+ <button
166
+ key={item.id}
167
+ type="button"
168
+ aria-label={`广告 ${i + 1}`}
169
+ onClick={() => rotation.setIndex(i)}
170
+ style={{
171
+ width: 8, height: 8, borderRadius: 99, border: 0, padding: 0,
172
+ background: i === rotation.index ? "#2563eb" : "#cbd5e1",
173
+ }}
174
+ />
175
+ ))}
176
+ </div>
177
+ ) : null}
178
+ </div>
179
+ );
180
+ }
181
+
182
+ export type AdProps = {
183
+ placement?: string;
184
+ showEmpty?: boolean;
185
+ showIndicators?: boolean;
186
+ onError?: (error: Error) => void;
187
+ renderAd?: (ad: AdFeedItem) => ReactNode;
188
+ };
189
+
190
+ export function Ad({ placement = "home_banner", showEmpty = false, showIndicators, onError, renderAd }: AdProps) {
191
+ const { feed, loading, error } = useAdsFeed({ placement });
192
+ useEffect(() => {
193
+ if (error) onError?.(error);
194
+ }, [error, onError]);
195
+ if (loading) return null;
196
+ if (error) return <p style={{ color: "#dc2626", fontSize: 13 }}>广告加载失败: {error.message}</p>;
197
+ if (!feed?.ads?.length) {
198
+ return showEmpty ? <p style={{ color: "#64748b", fontSize: 13 }}>(当前无 {placement} 广告)</p> : null;
199
+ }
200
+ if (renderAd && feed.ads[0]) return <>{renderAd(feed.ads[0])}</>;
201
+ return <AdSlotView feed={feed} placement={placement} showIndicators={showIndicators} />;
202
+ }
203
+
204
+ export function AdBanner(props: Omit<AdProps, "placement">) {
205
+ return <Ad placement="home_banner" {...props} />;
206
+ }
207
+ export function AdSidebar(props: Omit<AdProps, "placement">) {
208
+ return <Ad placement="sidebar" {...props} />;
209
+ }
210
+ export function AdFooter(props: Omit<AdProps, "placement">) {
211
+ return <Ad placement="footer" {...props} />;
212
+ }
213
+ export function AdInline(props: Omit<AdProps, "placement">) {
214
+ return <Ad placement="inline" {...props} />;
215
+ }