@antglobal/copilot-cards-web
v1.0.10
Published
Web Component renderer for copilot bot card SDK — PC + Mobile + WebView unified rendering via Custom Elements
Readme
@antglobal/copilot-cards-web
Web renderer for schema-driven cards in AI conversations. It turns one JSON schema into interactive Custom Elements for desktop browsers, mobile browsers, and WebViews.
The package includes the core schema and action APIs, responsive rendering, Shadow DOM style isolation, streaming updates, and extensible component registration.
Installation
npm install @antglobal/[email protected]@antglobal/copilot-cards-core is installed automatically.
Quick start
import { renderCard } from "@antglobal/copilot-cards-web";
const container = document.getElementById("card");
if (!container) throw new Error("Missing #card container");
const schema = {
version: "1.0",
rootID: "root",
elements: {
root: {
id: "root",
type: "Text",
props: {
content: { type: "static", value: "Hello, Copilot Cards!" },
},
},
},
variables: {},
};
const card = renderCard(container, schema, {
emit: (eventName, payload) => {
console.log(eventName, payload);
},
showToast: (message, level) => {
console.log(`[${level ?? "info"}] ${message}`);
},
});
card.updateVariables({ userName: "Alice" });
// Dispose when the host view is removed.
card.dispose();Stable host updates
Create the card once and keep its CardInstance. Input events should update
only the variables that changed. Do not call renderCard() again for input updates,
because remounting the card recreates image elements and can cause visible flicker.
import {
renderCard,
type CardInstance,
type CardSchema,
} from "@antglobal/copilot-cards-web";
let card: CardInstance | null = null;
export function mountDataRechargeCard(
container: HTMLElement,
schema: CardSchema,
): void {
card?.dispose();
card = renderCard(container, schema, {
emit: (eventName, payload) => {
if (eventName !== "dataRecharge.phone.input") return;
const value = String(
(payload as { value?: unknown } | undefined)?.value ?? "",
);
if (!card) return;
card.updateVariables({ phoneNumber: value });
},
});
}
export function unmountDataRechargeCard(): void {
card?.dispose();
card = null;
}Keep skuOptions and isSkuLoading out of each keystroke patch unless their
values actually changed. Fetching or filtering SKU data can run from the
dataRecharge.phone.commit event instead of remounting the card on every
dataRecharge.phone.input event.
Framework usage
The renderer accesses browser APIs and should be loaded on the client in frameworks that perform server-side rendering.
const { renderCard } = await import("@antglobal/copilot-cards-web");In React or Next.js, run the dynamic import inside a client component effect. In Vue, run it after the component is mounted.
Main API
renderCard(container, schema, options?)
Renders a complete schema and returns a CardInstance:
interface CardInstance {
updateVariables(variables: Record<string, unknown>): void;
onScroll(nodeId: string, listener: CardScrollListener): () => void;
dispose(): void;
}CardScrollEvent and CardScrollListener are top-level package exports. The
event contains readonly node, scrollTop, scrollLeft, scrollHeight,
scrollWidth, clientHeight, and clientWidth values:
import type {
CardScrollEvent,
CardScrollListener,
} from "@antglobal/copilot-cards-web";
const unsubscribe = card.onScroll("friendsList", event => {
const remaining =
event.scrollHeight - event.clientHeight - event.scrollTop;
});
unsubscribe(); // Idempotent; card.dispose() also removes the subscription.The subscription follows the logical node ID across physical replacement and
reports native-frequency values. It does not emit an initial, render, resize,
or updateVariables callback. Generated internal scroll tracks and scroll
ports inside Shadow DOM are not observed. Thresholds, throttling, requests,
locks, cursors, retries, and deduplication remain host responsibilities.
For pagination, continue passing the complete next array to updateVariables.
The SDK retains the Repeat owner and old prefix only when it can strictly prove
a structurally equal tail extension whose retained rendering is unchanged, on
a default-rendered Container with an unambiguous direct-child default or
flex layout. Every unproven case uses the existing replacement behavior; this
is not a general keyed diff or public append API. A trailing control object is
eligible only when it does not change retained rows. Put temporary loading UI
outside the Repeat owner when scroll identity matters.
Common render options include:
| Option | Purpose |
| --- | --- |
| variables | Overrides initial schema variables |
| botId | Optionally selects bot-scoped custom action handlers |
| isMobile | Explicitly enables mobile component layout; defaults to false |
| responsive | Explicitly enables mobile px-to-rem conversion when configured |
| fetch | Supplies a custom request implementation |
| showToast | Connects toast actions to the host UI |
| navigate | Connects URL actions to host navigation |
| emit | Receives events emitted by a card |
| copyText | Connects copy actions to the host clipboard |
The SDK does not infer mobile mode or CSS units from viewport width. Pass only
isMobile: true for mobile layout with px output. To opt into REM conversion,
also pass responsive: { mobile: { unit: "rem", rootValue: 100 } }.
Streaming
Use renderStreamingCard when the card arrives incrementally from an AI model or server:
import { renderStreamingCard } from "@antglobal/copilot-cards-web";
const stream = renderStreamingCard(container);
stream.feed(chunk);
stream.flush();
stream.dispose();The package also exports connectStreaming and connectSSE helpers, plus partial-schema and A2UI adapters.
BotSDK
BotSDK groups card instances, bot-scoped action handlers, and declarative action providers behind one host-facing API.
import { BotSDK } from "@antglobal/copilot-cards-web";
const bot = new BotSDK({
botId: "support-bot",
onAction: {
trackEvent: async (step) => {
console.log(step.params);
},
},
});
await bot.renderCard(container, schema);botId is optional. Omit it when the application uses only one default action scope; provide it when isolating custom handlers or loading per-bot action configuration.
Built-in components
The renderer includes:
- Text, Button, Input, Image, Divider
- Rate, Tag, Select, PasscodeInput
- Icon, Form, Loading, Progress
- Steps, Collapse, and sanitized HTML
Components render as isolated ai-card-* Custom Elements.
Custom components
import {
registerComponent,
type ComponentRenderer,
} from "@antglobal/copilot-cards-web";
const renderStatus: ComponentRenderer = (_node, props) => {
const element = document.createElement("div");
element.textContent = String(props.label ?? "");
return element;
};
registerComponent("Status", renderStatus);Actions
Cards can declaratively request emit, request, setVariable, toast, url, and copy actions. The host remains in control of network access, navigation, notifications, clipboard behavior, and custom business actions.
Browser requirements
- Custom Elements
- Shadow DOM
AbortController- Modern JavaScript with ES2020 support
Provide appropriate polyfills when targeting older WebViews.
Related packages
@antglobal/copilot-cards-core— UI-independent schema, expression, action, lifecycle, and streaming logic.@antglobal/copilot-cards-mini-program— native renderer for Alipay and WeChat mini-programs.
License
MIT
