@gravity-ai/react

中文文档
1.7.0发布于 2026/11/15MITTypeScriptESM + CJS零依赖近 30 天下载 63.9万

React components for rendering Gravity AI advertisements

原始使用文档
文档目录15 节
  1. Installation
  2. Quick Start
  3. API Response Shape
  4. Components
  5. <GravityAd />
  6. MCP connect ads
  7. Server-delivered placement designs
  8. Data-drawn units
  9. Styling with style and slotProps
  10. <GravityLeadFormAd /> (deprecated)
  11. <AdText />
  12. Impression Tracking
  13. Hooks
  14. useAdTracking
  15. License

@gravity-ai/react

React components for rendering Gravity ads with automatic impression and click tracking.

For composer insertion with host consent, see Prompt action ads.

Installation

npm install @gravity-ai/react

Peer dependency: React 17+

Quick Start

import { GravityAd } from '@gravity-ai/react';

function ChatResponse({ ads }) {
  return ads.map((ad, i) => <GravityAd key={i} ad={ad} />);
}

That's it. When the response contains a server-delivered renderer_spec, the component validates and renders that placement design. Otherwise it falls back to its bundled card. It automatically fires the impression pixel when the ad scrolls into view.

API Response Shape

The components expect the objects returned by the Gravity API:

interface AdResponse {
  adText: string;
  title?: string;
  cta?: string;
  brandName?: string;
  url?: string;
  favicon?: string;
  impUrl?: string;    // impression tracking pixel
  clickUrl?: string;  // tracked click-through URL
  renderer_spec?: RendererSpec | string; // optional server-delivered placement design
}

Components

<GravityAd />

Full-featured ad renderer with automatic impression/click tracking. Bundled variants use inline styles; server-delivered designs use validated inline declarations plus optional semantic CSS variables. No CSS-in-JS runtime is required.

<GravityAd
  ad={ad}
  // Leave `variant` unset to accept the placement's server-delivered design.
  showLabel={true}
  labelText="Sponsored"
  openInNewTab={true}
  onImpression={() => console.log('seen')}
  onClickTracked={() => console.log('clicked')}
/>

Variants:

VariantDescription
cardDefault. Vertical card with border, shadow, and padding.
inlineHorizontal layout for sidebars or toolbars.
minimalNo border, shadow, or background. Blends with host content.

Passing variant deliberately pins one of these bundled looks and ignores renderer_spec. Use that only when the publisher must own the layout locally.

MCP connect ads

Pass onConnect when your app has an MCP client. An ad that carries a valid connect payload (type: 'mcp', an https serverUrl, a name, an optional https iconUrl) and button copy in cta then renders as a connect card: brand, title, body and one button labelled with cta. The card adds no text of its own.

<GravityAd
  ad={ad}
  onConnect={(request) => connectMcpServer(request.serverUrl, request.name)}
/>

onConnect receives { id, serverUrl, name, iconUrl? } and returns { status: 'connected' | 'declined' | 'failed' }, directly or as a promise. It runs synchronously inside the click, so open your OAuth popup before any await. The tracked click fires in the background on every connect click. There is no website fallback: when the result is declined or failed, or the callback throws, nothing opens and the card stays as it is, so the user can try again. Repeated clicks while a connect is pending reuse the pending call. Without onConnect, or with an invalid payload, the ad renders as an ordinary ad. When an ad carries both a usable prompt action and a usable connect, the connect card wins only when onConnect is set.

This component only renders: declare supportsMcpConnect: true on the matching placement of your ad request (@gravity-ai/ui's self-fetching GravityAd does this for you when onConnect is set).

Let the SDK run the sign-in

createMcpConnectHandler builds an onConnect handler that runs the whole MCP authorization in the browser and hands you the connection to add to your own MCP client. It opens a popup inside the click, discovers the server's authorization server (RFC 9728 protected-resource metadata, then RFC 8414 authorization-server metadata), registers your app by dynamic client registration under clientName, sends the user to the advertiser's consent screen with PKCE (S256), a random state and the RFC 8707 resource, and exchanges the returned code for tokens.

import { GravityAd, createMcpConnectHandler, type McpConnection } from '@gravity-ai/react';

const onConnect = createMcpConnectHandler({
  clientName: 'Acme Chat',
  redirectUri: `${window.location.origin}/mcp/callback`,
  attribution: () => ({ utm_source: 'acme-chat', utm_medium: 'chat' }),
  onConnected: async (connection: McpConnection) => {
    await mcpHub.add({
      name: connection.name,
      url: connection.serverUrl,
      headers: connection.headers,
      oauth: connection.oauth,
    });
  },
});

<GravityAd ad={ad} onConnect={onConnect} />

Each connect runs in its own popup and only accepts the callback from that popup. The protected-resource metadata must name the MCP server itself (the same origin, with the server's path equal to or under the metadata's resource path), so a server cannot have a token issued for another server's resource. Each request gives up after 15 seconds.

The result is connected once onConnected resolves, declined when the user closes the popup (at any point before the callback, which also cancels requests still running) or denies consent, and failed otherwise (no OAuth metadata, a resource that does not match the server, a blocked popup, a refused registration or token exchange, a state mismatch, or onConnected throwing). The connection is:

{
  serverUrl: string;
  name: string;
  headers: { Authorization: 'Bearer …' };
  oauth: { tokenEndpoint: string; clientId: string; refreshToken?: string; expiresAt?: number; resource: string };
}

Options:

OptionPurpose
clientNameYour app's name, shown on the advertiser's consent screen.
redirectUriA page on your own origin that calls completeMcpConnectCallback().
clientIdA client id you registered with the advertiser; skips dynamic client registration.
attributionReturns tracking parameters for the authorize URL. Only utm_source, utm_medium, utm_campaign, utm_content, utm_term and grclid are kept, so it can never override an OAuth parameter.
fetchReplaces fetch for discovery, registration and token calls (see CORS below).
onConnectedReceives the connection and the original request.

The redirect page only needs to call completeMcpConnectCallback() once it loads. It posts the code, state and any error to the opener at the same origin, removes them from the address bar and closes the popup:

// app/mcp/callback/page.tsx
'use client';
import { useEffect } from 'react';
import { completeMcpConnectCallback } from '@gravity-ai/react';

export default function McpCallback() {
  useEffect(() => { completeMcpConnectCallback(); }, []);
  return <p>Connecting…</p>;
}

Refresh the access token before oauth.expiresAt with refreshMcpConnection, which uses the refresh-token grant and returns an updated connection (it rejects when there is no refresh token or the server refuses):

import { refreshMcpConnection } from '@gravity-ai/react';

if (connection.oauth.expiresAt && connection.oauth.expiresAt - Date.now() < 60_000) {
  connection = await refreshMcpConnection(connection);
  await mcpHub.update(connection);
}

The handler never logs tokens, codes or URLs that carry them. Store headers and oauth the way you store any other credential.

CORS. The browser calls the MCP server's metadata, the registration endpoint and the token endpoint directly, so they must allow cross-origin requests. Many do (the MCP reference server and Exa's token endpoint do), but some do not: Exa's registration endpoint (https://auth.exa.ai/api/oauth/register) sends no CORS headers, so registering from the browser fails there. For such servers, pass a clientId you registered ahead of time, or pass a fetch that relays the calls through your own server:

const relayFetch: typeof fetch = (input, init) =>
  fetch('/api/mcp-oauth-relay', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({
      url: String(input),
      method: init?.method ?? 'GET',
      headers: init?.headers,
      body: init?.body,
    }),
  });

const onConnect = createMcpConnectHandler({ clientName: 'Acme Chat', redirectUri, fetch: relayFetch, onConnected });
const refreshed = await refreshMcpConnection(connection, { fetch: relayFetch });

The relay forwards the request to url and returns the upstream status, WWW-Authenticate header and body. The URLs come from the advertiser's metadata, so let the relay reach only public https hosts and never forward your own cookies or credentials.

Server-delivered placement designs

Gravity can attach a versioned renderer_spec to an ad response. When variant is unset, <GravityAd>:

  1. Parses and structurally validates the spec.
  2. Resolves its content bindings (title, adText, cta, brandName, favicon, url).
  3. Applies the publisher's semantic theme variables.
  4. Renders through a safe node whitelist (box, text, image, link).
  5. Falls back to the bundled card renderer if the spec is malformed or resolves to no content.

The standard card spec uses one root link bound to url, so the whole visible ad routes through clickUrl; it never nests anchors. Specs must include a visible disclosure such as AD, Sponsored, Promoted, or Paid. If disclosure is missing, the SDK overlays its built-in ad badge.

Web ad requests should send specCapabilities: "web1" (and must not send supportsSpec: false). Existing integrations that send neither field remain backward-compatible and are treated as web-capable for publisher placement defaults.

Server designs adopt these optional host variables, falling back to the SDK palette:

VariablePurpose
--gravity-bgCard/background surface
--gravity-textPrimary text
--gravity-text-mutedSecondary text
--gravity-accentCTA/accent
--gravity-accent-foregroundText on the accent
--gravity-mutedMuted surface
--gravity-borderBorders
--gravity-radiusCard radius

When a --gravity-* variable is absent, the renderer uses the matching host variable (--card, --foreground, --primary, etc.) before its literal fallback.

Data-drawn units

When an ad carries a unit and variant is unset, <GravityAd> draws it with the layout that fits the container's live width, and re-flows when the width crosses a layout boundary. The unit picks up the host page's light or dark surface, text colour and font; --gravity-accent and --gravity-radius set its button colour and corner radius. rich_frame units render in the frame host, an action_card button runs onPrompt, and a connect_card button runs onConnect. A unit type or version the SDK doesn't know draws as a plain text card. Impression and click tracking work as for every other ad, and ads without unit render as before.

If you fetch ads yourself, add what the component needs to fit a unit to each placement of the request with getPlacementContext:

import { getPlacementContext } from '@gravity-ai/react';

const placements = [{
  placement: 'below_response',
  placement_id: 'main',
  ...getPlacementContext(slotRef.current, { promptAction: !!onPrompt, mcpConnect: !!onConnect }),
}];

It returns the slot width, the host font and theme, and the capabilities <GravityAd> draws (frames defaults to true, matching enableFrames). It never throws; on the server it returns only capabilities.

Styling with style and slotProps

Override the outer container with the style prop:

<GravityAd ad={ad} style={{ maxWidth: 400, borderRadius: 16 }} />

Override any inner element with slotProps:

<GravityAd
  ad={ad}
  slotProps={{
    cta: { style: { background: '#E11D48', borderRadius: 999 } },
    label: { style: { display: 'none' } },
    title: { style: { fontSize: 16 } },
  }}
/>

Each slotProps key maps to a DOM element:

KeyElementWhat it controls
containerOuter <a>Same as top-level style prop
innerPadding wrapper <div>Layout, padding, gap
headerHeader row <div>Favicon + brand + label row
faviconFavicon <img>Size, border-radius
brandBrand name <span>Font, color
label"Sponsored" <span>Pill styling, visibility
bodyBody wrapper <div>Title + text layout
titleTitle <p>Font, color
textAd text <p>Font, color
ctaCTA button <span>Background, border-radius, padding

Each slot accepts { style?: CSSProperties; className?: string }.

For the full styling guide with DOM structure and common recipes, see STYLING.md.

<GravityLeadFormAd /> (deprecated)

Lead forms are retired. The server no longer returns leadForm on ads, and <GravityLeadFormAd /> renders nothing. Use <GravityAd /> instead.

<AdText />

Unstyled text-only renderer. Use when you want full control over presentation.

<AdText
  ad={ad}
  className="my-custom-style"
  style={{ fontSize: 14 }}
/>

Renders ad.adText as a link (if clickUrl exists) or a span. No built-in styles beyond text-decoration: none; color: inherit.

Impression Tracking

Both components use IntersectionObserver to fire the impression pixel only when the ad is actually visible to the user (50% of the element in the viewport). This is a significant improvement over fire-on-mount — publishers won't report impressions for ads rendered below the fold that were never seen.

The impression fires exactly once per ad. If the ad object changes (different impUrl), the tracking resets for the new ad.

Billing is unchanged: the impression pixel (impUrl) fires exactly as before. The pixel still fires the instant 50% of the ad enters the viewport (or on mount where IntersectionObserver is unavailable). Separately, the SDK sends a shadow viewability beacon to the same URL with ev=measured, sdk and sv query parameters when the pixel fires, and ev=viewable once at least 50% of the ad has been in view for 1 continuous second (MRC viewable impression). The beacons are measurement only and never affect billing. Dropping below 50% or hiding the tab restarts the 1 second; no beacon is sent where IntersectionObserver is unavailable.

To disable automatic tracking:

<GravityAd ad={ad} disableImpressionTracking />

Hooks

useAdTracking

Low-level hook for building fully custom ad components:

import { useAdTracking } from '@gravity-ai/react';

function CustomAd({ ad }) {
  const { containerRef, handleClick } = useAdTracking({
    ad,
    onImpression: () => console.log('impression fired'),
    onClickTracked: () => console.log('click tracked'),
  });

  return (
    <a ref={containerRef} href={ad.clickUrl} onClick={handleClick}>
      {ad.adText}
    </a>
  );
}

The hook returns:

  • containerRef — attach to the DOM element for IntersectionObserver-based impression tracking
  • handleClick — call on click to fire the click tracking callback
  • impressionFired — boolean indicating whether the impression has already been fired

License

MIT

版本与发布记录

@gravity-ai/react 共发布 22 个版本,首次发布于 2025/11/27;过去 12 个月发布了 22 个版本。

版本发布日期距今
1.7.0latest2026/11/151 天前
1.6.02026/11/142 天前
1.5.12026/11/142 天前
1.5.02026/11/143 天前
1.4.02026/11/133 天前
1.3.22026/10/081 个月前

关于 @gravity-ai/react 的常见问题

@gravity-ai/react 是什么?

React components for rendering Gravity AI advertisements

如何安装 @gravity-ai/react?

在项目目录运行 npm install @gravity-ai/react,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=17.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@gravity-ai/react 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gravity-ai/react 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@gravity-ai/react 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@gravity-ai/react 可以商用吗?

@gravity-ai/react 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gravity-ai/react 的下载量有多少?

根据 npm 官方下载统计,@gravity-ai/react 在 2026/10/17 – 2026/11/15 这 30 天内被下载 639,083 次,日均约 21,303 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gravity-ai/react 还在维护吗?

最新版本 1.7.0 发布于 2026/11/15(1 天前);至今共发布 22 个版本,其中过去 12 个月发布了 22 个;首次发布于 2025/11/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。