@collective-intelligence/ui-react

中文文档
0.2.2发布于 2026/11/09TypeScriptES Module近 30 天下载 5645

Public React primitives, design-system components, icons, illustrations, and utilities for Collective Intelligence applications.

原始使用文档
文档目录6 节
  1. Controlled entity presentation
  2. Error alerts
  3. Failed write toast
  4. Card options
  5. Video player
  6. Enum value migration

@collective-intelligence/ui-react

Public, accessible React primitives and the Collective Intelligence design system for Collective Intelligence applications.

The package preserves the design-system source structure under src/components/, including ui, ui-extensions, icons, and illustrations, plus shared hooks, utilities, and theme tokens. The /resources entrypoint contains generic table, list, filter, pagination, dialog, and action primitives.

All components accept display-ready props and do not fetch data, own authentication, or depend on private CI packages. React and React DOM remain peer dependencies.

react-hook-form is also a peer dependency and is excluded from the browser prebundle. Consumers must provide it so the public Form provider and their form hooks share the same context.

bun run build produces production JSX for the published entrypoints while keeping React and React DOM external. These artifacts support consumers using either production or development React. After building, bun run test test/built-runtime.test.ts verifies rendering with both modes.

react-markdown remains a regular runtime dependency and is excluded only from this package's browser prebundle. Browser and server-side rendering consumers resolve its dependencies for their own runtime, keeping browser-only DOM code out of server imports.

Published entrypoints share runtime chunks inside dist; distribute that directory intact. This keeps modal focus and pointer-lock state shared when composing primitives from /ui with dialogs from /ui-extensions. bun run test:pack rebuilds the package and checks this cross-entrypoint modal lifecycle and consumer form context before validating the packed consumer.

Controlled entity presentation

Import shared entity presentation from @collective-intelligence/ui-react/resources. Dashboard's private CRUD wrappers and external consumers use the same table, list, filter layout, pagination and dialog implementation. Data loading, authorization, URL state, selection, drafts and mutations belong to the caller.

ResourceTablePrimitive takes rows, columns, stable getRowKey, and renderCell. Optional row action, context-menu and detail renderers receive the same row. Action clicks do not activate the row; row activation supports Enter and Space. Expanded and selected state is controlled by caller callbacks. ResourceListPrimitive accepts stable item keys and an optional container slot. ResourceFiltersBar lays out caller-owned controls, while ResourcePaginationPrimitive supports previous/next and controlled numbered pages. Pending controls remain disabled. Pass navigationLabel to localize the navigation's accessible name (defaults to Resource pagination), alongside previousLabel, nextLabel, and ellipsisLabel for the controls.

ResourceDialogPrimitive uses the existing focus-managed dialog by default; pass open, onOpenChange, title, and optional description. Its explicit custom Dialog slot remains available, with focus management then owned by that replacement.

ResourceFormPrimitive renders display-ready ResourceField metadata, values, field errors and callbacks. Built-in controls cover text/email, numbers, booleans, enum options, date/datetime strings and explicit nullable clearing. Numbers and booleans retain their JSON value types. Custom controls receive the same value/change, disabled, read-only, required and error metadata; schema inference and registry lookup stay with the caller. Unsupported custom controls are shown explicitly. Form submission delegates validation and persistence to the caller; the presentation never constructs a client or QueryClient.

ResourceListPagePrimitive picks one body from caller-owned slots by status (pending, error or ready) and totalItems: loading for a first load, error, nothingYet for an empty list, noResults when hasActiveQuery is set, otherwise children. The optional toolbar shows with rows and with noResults. Pass paging (page, totalPages, onPageChange) and optional pagination labels for a pager that appears above one page. When the current page vanishes, the list asks onPageChange for the last page once. isRefetching marks a background refresh with aria-busy. Content fades in only when it replaces the loading slot.

ResourceAdvancedFilters adds a collapsible advanced-filter region to a ResourceFiltersBar. Pass the always-visible primary controls, the advanced content, the activeCount and the localized labels. Optional activeFilters render removable chips, onClear resets every filter, and the region opens by default when a filter is active or defaultOpen is set. The caller owns filter state and URL sync.

Run bun run build-storybook for the interactive Resources / Controlled entity / Journey example. bun run test:pack checks these exports from the packed JavaScript and declarations in an isolated external consumer.

Error alerts

Import ErrorAlert from @collective-intelligence/ui-react/ui-extensions. It composes the existing destructive Alert and Radix Collapsible primitives. Pass the visible message as children, an optional title, and an optional details object containing a trigger label and arbitrary React content. Omitting details removes both the disclosure trigger and its panel.

import { ErrorAlert } from "@collective-intelligence/ui-react/ui-extensions"

;<ErrorAlert
  title="Connection failed"
  details={{
    label: "Technical details",
    content: (
      <pre className="whitespace-pre-wrap break-words">{diagnostics}</pre>
    )
  }}
>
  The service could not be reached. Please try again.
</ErrorAlert>

The details start closed. Use defaultOpen for an initially expanded panel, or open with onOpenChange to control it. Labels, translations, diagnostic formatting and error recovery remain with the caller. Use className and classes to customize the root and individual presentation parts.

Failed write toast

Import ciWriteFailedToast and Toaster from @collective-intelligence/ui-react/ui. ciWriteFailedToast(messages?) returns a handler for the onWriteFailed prop of CollectiveIntelligenceProvider (@collective-intelligence/external-apps-client-sdk-react). The handler calls toast.error with one text:

  • For a CiError, the English text of its code.
  • For a CiTransportError, an English connection text. It does not say that the change was not saved: when the answer of a write is lost, CI can have saved it.

To use other texts, for example in another language, pass messages (CiWriteFailedMessages). Its keys are the CiError codes and transport. A key that you do not give keeps its English text.

import {
  Toaster,
  ciWriteFailedToast
} from "@collective-intelligence/ui-react/ui"

const onWriteFailed = ciWriteFailedToast({
  conflict: "Quelqu'un a modifié cet élément.",
  transport:
    "Pas de connexion. La modification n'est peut-être pas enregistrée."
})

;<CollectiveIntelligenceProvider client={client} onWriteFailed={onWriteFailed}>
  <App />
  <Toaster />
</CollectiveIntelligenceProvider>

The handler reads only the _tag and code of the error (CiWriteFailedEvent), so this package does not depend on the client SDK. The toast shows in the Toaster only when the app has one copy of this package: two copies have two toast stores. For this reason the client SDK for React has this package as a peer dependency.

Card options

Import CardOptionsBlock, CheckboxCardOption and RadioCardOption from @collective-intelligence/ui-react/ui-extensions. Each option is a card with a title, an optional description and its control; a click anywhere on the card changes the value, also inside a <form>.

import {
  CardOptionsBlock,
  CheckboxCardOption
} from "@collective-intelligence/ui-react/ui-extensions"

;<CardOptionsBlock>
  <CheckboxCardOption
    checked={selected}
    title="Studio: Use agent conversations"
    description="Capability to use Studio. It adds no permission that a run uses."
    wrapDescription
    onCheckedChange={setSelected}
  />
</CardOptionsBlock>

The description shows on one truncated line. Set wrapDescription to show it in full on more lines. CheckboxCardOption and RadioCardOption link the description to their control with aria-describedby. With CardOption and a custom control, pass a descriptionId and set the same id as the aria-describedby of your control.

Video player

Import VideoPlayer from its own subpath, @collective-intelligence/ui-react/ui-extensions/video-player. It renders one <video> and plays a Stable Media URL (…/media/{ownerKind}/{ownerId}…): adaptive HLS when the video's Renditions are ready, otherwise the stored file. Pass src, the native <video> attributes (controls, poster, autoPlay, aria-label, …), className and classes.root. Captions are <track> children.

import VideoPlayer from "@collective-intelligence/ui-react/ui-extensions/video-player"

;<VideoPlayer
  aria-label="Product walkthrough"
  controls
  requestHeaders={() => ({ Authorization: `Bearer ${token}` })}
  src={file.mediaUrl}
/>

Credentials stay with the consumer:

  • With requestHeaders, the player asks src with stream=hls, the callback's headers and credentials: "omit". A playlist answer starts hls.js, which adds the headers only to URLs on the origin of src under its /media/ path. Any other answer is the stored file: the player plays the final URL of the followed redirect.
  • Without requestHeaders, the player asks with credentials: "include" and redirect: "manual", and hls.js sends credentials only to the same API media URLs. A redirect (the stream is not ready) or any other answer lets the element load src itself with the session cookie.
  • Delivery URLs on the media host never receive a header, credentials or a query string. A browser without Media Source Extensions uses native HLS only with the cookie; with a header callback it plays the stored file.
  • When a fragment answers 403 (its Delivery URL expired with its Access Window), the player reloads the stream once at the current position.

The page origin must be allowed by the API CORS policy for a credentialed request; otherwise the player falls back to the element loading src.

Exception to "do not fetch data". The player probes the one URL its consumer passes, to choose between the stream and the stored file. That probe is media transport, not data access: it builds no URL of its own, reads no token and constructs no client.

hls.js (hls.js/light) is bundled in its own chunk and loaded by dynamic import only for a ready stream on a browser with Media Source Extensions; the other entrypoints and the player's own chunk do not contain it. Its Apache-2.0 notice ships in THIRD-PARTY-NOTICES.md. bun run test:pack checks the chunk split and the notice in the packed artifact.

Enum value migration

Repository-owned component options use snake_case. Update Card.visual from accent-gradient to accent_gradient; InputGroupAddon.align from inline-start, inline-end, block-start, or block-end to inline_start, inline_end, block_start, or block_end; and InputGroupButton.size from icon-sm or icon-xs to icon_sm or icon_xs. Matching data-align, data-size, and data-visual values use these new spellings too.

Native HTML input types retain their protocol spelling: for example, ResourceField.control accepts datetime-local and forwards it to the input.

版本与发布记录

@collective-intelligence/ui-react 共发布 31 个版本,首次发布于 2026/10/08;过去 12 个月发布了 31 个版本。

版本发布日期距今
0.2.2latest2026/11/091 天前
0.2.12026/11/091 天前
0.2.02026/11/055 天前
0.1.272026/11/036 天前
0.1.262026/10/319 天前
0.1.252026/10/3110 天前

关于 @collective-intelligence/ui-react 的常见问题

@collective-intelligence/ui-react 是什么?

Public React primitives, design-system components, icons, illustrations, and utilities for Collective Intelligence applications.

如何安装 @collective-intelligence/ui-react?

在项目目录运行 npm install @collective-intelligence/ui-react,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=18 <20)、react-dom(>=18 <20)、react-hook-form(^7.72.1)、@tanstack/react-query(>=5.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@collective-intelligence/ui-react 支持 TypeScript 吗?

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

@collective-intelligence/ui-react 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@collective-intelligence/ui-react 可以商用吗?

@collective-intelligence/ui-react 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@collective-intelligence/ui-react 的下载量有多少?

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

@collective-intelligence/ui-react 还在维护吗?

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