К основному содержанию
скилл CX Codex

reveal-3d — скилл для Claude Code: 3D-вьюер Cognite Reveal во Flows

Встраивает интерактивный 3D-вьюер Cognite Reveal в приложение Flows: CAD-модели, облака точек, панорамы 360° и сцены CDF.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add cognitedata/builder-skills --skill reveal-3d -a claude-code
Открыть на GitHub

Что делает reveal-3d

Скилл подключает npm-пакет @cognite/reveal-widget к приложению Flows на React и TypeScript. Внутри — пошаговый порядок работ: осмотреть проект, поставить пакет и peer-зависимости, добавить в Vite запись dedupe для three и @cognite/reveal, прописать CSP в manifest.json, собрать класс-контроллер поверх RevealWidgetController и смонтировать RevealWidget в контейнер с явной высотой.

Контроллером управляют императивно — из своих обработчиков событий, а не через useEffect на изменение пропсов. Ресурс грузят либо через браузер моделей (sdk.models3D.list() и классические modelId/revisionId), либо по ссылке CDM с externalId и space. Хэндл от addResource нужно освобождать методом .remove() при смене выбора и размонтировании.

Перед установкой проверьте два момента. Приложение должно быть обёрнуто в CogniteSdkProvider из @cognite/app-sdk, потому что именно он отдаёт CogniteClient через useCogniteSdk(). И флаг viewerOptions.useCoreDm выставляйте по фактическому расположению 3D-контента в проекте, а не наугад: если модели лежат в классическом 3D API, а флаг стоит в true, вьюер не найдёт данные. Версию @cognite/reveal скилл советует пинить на 4.36.0, а не на 4.35.3 из объявленного диапазона peer-зависимостей пакета.

Какие задачи решает

  • встроить 3D-вьюер Cognite Reveal в приложение Flows
  • показать CAD-модель или облако точек рядом с данными ассета
  • открыть коллекцию панорам 360° из CDF
  • подсветить инстанс Core Data Model на загруженной модели
  • перевести приложение со старого скопированного бандла на пакет @cognite/reveal-widget

Примеры запросов агенту

  • Добавь в приложение Flows 3D-вьюер Reveal для инстанса selectedEquipment
  • Подключи @cognite/reveal-widget и загрузи модель по modelId и revisionId
  • Настрой CSP в manifest.json под сцены и панорамы 360°

Как установить reveal-3d

1Через Skills CLI (Vercel)

npx skills add cognitedata/builder-skills --skill reveal-3d -a claude-code

2Вручную: положить файлы

~/.claude/skills/reveal-3d/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/reveal-3d/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора12

setup-python-tools Ставит клиентское выполнение Python-инструментов через Pyodide в приложение с уже готовым useAtlasChat. Нужен, когда агент отдаёт код инструмента, а считать он должен в браузере. CX Codex +1 1 900установок dm-limits-and-best-practices Справочный скилл про лимиты CDF Data Modeling: конкурентность и 429, пагинация, батчи, QueuedTaskRunner. Пригодится, когда код сыпет ошибками на нагрузке. CX Codex +1 1 900установок security Проходит по приложению Flows шаг за шагом: находит утечки секретов, опасный DOM, дыры в авторизации — и сразу правит их. CX Codex +1 1 900установок integrate-atlas-chat Скилл для встраивания чата Atlas прямо в интерфейс приложения Cognite. Нужен, когда сайдбар Fusion/EOS недоступен. CX Codex +1 1 900установок integrate-todo-list Добавляет в приложение инструмент TodoWrite и панель, где видно, как агент Atlas выполняет многошаговую работу. CX Codex +1 1 900установок dependencies-audit Скилл находит уязвимости, устаревшие и заброшенные пакеты, проблемы с лицензиями и чинит их, а не просто составляет отчёт. CX Codex +1 1 900установок test-coverage Скилл находит пробелы в покрытии тестами приложения на Flows и закрывает их: настраивает инструменты, пишет недостающие тесты, правит код ради тестируемости. CX Codex +1 1 900установок integrate-fusion-agent Скилл подключает боковую панель Atlas/EOS в приложение Flows/Fusion через @cognite/app-sdk вместо встроенного чата. CX Codex +1 1 700установок

Похожие

clerk-tanstack-patterns clerk Подсказывает агенту, как подключить Clerk к TanStack React Start: защита маршрутов, createServerFn, лоадеры и middleware. CX Codex +1 15 500установок power-apps-code-app-scaffold официальный github Создаёт каркас Power Apps Code App с React и TypeScript. Подходит для старта проекта с коннектором Power Platform. 8 700установок react-vite-dashboard официальный google-labs-code Скилл превращает макеты из Stitch в рабочий код дашборда на React и Vite. Он связывает дизайн-токены из DESIGN.md с кодом и подключает выборку данных через TanStack Query. CX Codex +1 5 500установок tanstack-router tanstack-skills Скилл по TanStack Router для React и Solid: файловый роутинг, поисковые параметры и загрузка данных с проверкой типов. CX Codex +1 4 900установок web-development TencentCloudBase Скилл для реализации, отладки и сборки веб-фронтенда, когда направление продукта уже определено. React, Vue, Vite, маршрутизация, проверка в браузере. CX Codex +1 1 800установок cloudinary-react cloudinary Подсказывает агенту точные импорты и паттерны Cloudinary React SDK, чтобы не гадать с путями и не ловить ошибки виджета загрузки. CX Codex +1 657установок

Рядом в теме «Фронтенд и UI»

Всё по теме «Фронтенд и UI» →

Вопросы о reveal-3d

Как установить reveal-3d в Claude?

Выполните npx skills add cognitedata/builder-skills --skill reveal-3d -a claude-code. Файл скилла окажется по пути ~/.claude/skills/reveal-3d/SKILL.md.

Что делает reveal-3d?

Проводит интеграцию пакета @cognite/reveal-widget в приложение Flows: установка зависимостей, настройка Vite и CSP, класс-контроллер и монтирование RevealWidget.

Что нужно, чтобы скилл сработал?

Приложение на React и TypeScript, обёрнутое в CogniteSdkProvider из @cognite/app-sdk, и 3D-контент в проекте CDF — модели, облака точек или панорамы.

Исходный текст

SKILL.md · Apache-2.0
---
name: reveal-3d
description: "Integrates the @cognite/reveal-widget npm package into Flows apps for an interactive Cognite Reveal 3D Scene/CAD/point cloud/360-image viewer. Use when adding 3D viewer, 3D visualization, Reveal, CAD model, Point cloud model, 360 image collection, Scenes, RevealWidget, RevealWidgetController, DM 3D mapping, asset 3D model, model browser, or Cognite 3D content to a Flows application."
metadata:
  argument-hint: "[DM instance variable name or description, e.g. 'asset' or 'selectedEquipment']"
---

# Reveal 3D Viewer

Add a Cognite Reveal 3D viewer to a Flows app using the published `@cognite/reveal-widget` npm package. Renders CAD models, point clouds, 360° image collections, and CDF scenes from CDF, with model browsing or direct model/revision IDs.

DM instance to visualize: **$ARGUMENTS**

## Use This When

The user wants to embed an interactive Cognite Reveal viewer for CDF 3D content in a Flows app.

Do **not** use this skill for static diagrams, graph visualizations, or unrelated custom Three.js scenes.

Do **not** use the deprecated app-local "copy the bundle" approach — that pattern (a `src/features/reveal-3d/` folder of copied provider/hook source) is replaced by installing `@cognite/reveal-widget` directly. If an app still has a copied bundle from a prior integration, migrate it to this package rather than extending it.

## Prerequisites

- The app uses React + TypeScript and is wrapped in `@cognite/app-sdk`'s `CogniteSdkProvider` (Flows auth), which supplies the `CogniteClient` (`sdk`) via `useCogniteSdk()` from `@cognite/app-sdk/react`. `@cognite/cli` is the CLI used to scaffold/deploy the app, not the runtime auth library — apps created with `npx @cognite/cli apps create` depend on `@cognite/app-sdk` for this, not `@cognite/cli` itself (the `useDune()`/`@cognite/dune/auth` hook only exists for legacy `--classic` scaffolds).
- The CDF project has 3D models, or the user has supplied direct model/revision IDs or a CDM (`externalId`/`space`) model reference.
- For DM-linked 3D, the instance/model must be identifiable via a CDM `externalId`/`space` pair or a classic `modelId`/`revisionId`; instance highlighting works once a model is loaded and the instance is contextualized (mapped) to it.
- Determine whether the project's 3D content lives in the **Core Data Model** or the classic 3D API before setting `viewerOptions.useCoreDm` — don't default it to `true`. There's no single flag for this; [csp-and-fixes.md](references/csp-and-fixes.md) gives the exact SDK calls to check directly.

## Integration Workflow

Follow these steps in order. Adapt paths to the target app's conventions instead of inventing new ones.

1. **Inspect the target app.** Read `package.json`, `vite.config.ts`, `src/main.tsx`, and the app's folder/alias conventions.
2. **Install the package and peers** with the app's package manager. See [Dependencies](#dependencies). Reuse existing pinned React and SDK versions where they satisfy the peer ranges.
3. **Configure Vite.** Read [vite-config.md](references/vite-config.md) and add the `three`/`@cognite/reveal` dedupe entry. No process/util/assert polyfills are needed — the package ships browser-ready.
4. **Configure `manifest.json`'s CSP allowances** for whatever the scene/model actually contains (scene ground-plane/skybox textures, 360° image collections). Read [csp-and-fixes.md](references/csp-and-fixes.md) — it also covers the app-side fix point clouds need (`manifest.json` can't grant it directly) and a StrictMode gotcha, so read it even if the app has no scenes/360 content yet.
5. **Add a controller class** that wraps `RevealWidgetController` and drives it imperatively (load resources, style/highlight instances, control the camera) from your own event handlers — not from `useEffect` reacting to prop changes. See [implementation.md](references/implementation.md).
6. **Mount `RevealWidget`** with `viewerOptions={{ sdk, useCoreDm }}` (set `useCoreDm` per the project, not hardcoded — see [csp-and-fixes.md](references/csp-and-fixes.md)), `setControllerRef`, and the required `appIdentifier` (a string identifying the host app) inside a container with an explicit height. `RevealWidget` manages its own internal Reveal context — do not wrap it in another provider from this package.
7. **Choose the resource pattern.** Use the model-browser pattern (`sdk.models3D.list()` + classic `modelId`/`revisionId`) as the default unless the user has already supplied a CDM `externalId`/`space` model reference. Full examples in [implementation.md](references/implementation.md).
8. **Clean up.** Call `.remove()` on any `Reveal3DResourceHandle` returned by `addResource` when it's no longer needed (selection change, unmount).
9. **Run typecheck and build** (`tsc --noEmit`, `pnpm build`, etc.) and fix any dependency/peer-version issues.

## Minimal Example

```tsx
import { useRef } from 'react';
import type { CogniteClient } from '@cognite/sdk';
import {
  RevealWidget,
  type Reveal3DResourceHandle,
  type RevealWidgetController,
  type ThreeDResourceIdentifier,
} from '@cognite/reveal-widget';

class ThreeDViewerController {
  private model: Reveal3DResourceHandle | undefined;

  constructor(private readonly widgetController: RevealWidgetController) {}

  async loadModel(resource: ThreeDResourceIdentifier): Promise<void> {
    this.model = await this.widgetController.addResource(resource);
    this.widgetController.cameraController.focusModel(this.model);
  }

  dispose(): void {
    this.model?.remove();
  }
}

export function ViewerPage({
  sdk,
  resource,
}: {
  sdk: CogniteClient;
  resource: ThreeDResourceIdentifier;
}) {
  const viewerRef = useRef<ThreeDViewerController>();

  function handleWidgetController(widgetController: RevealWidgetController | undefined) {
    viewerRef.current?.dispose();

    if (widgetController === undefined) {
      viewerRef.current = undefined;
      return;
    }

    const viewer = new ThreeDViewerController(widgetController);
    void viewer.loadModel(resource);
    viewerRef.current = viewer;
  }

  return (
    <div style={{ width: '100%', height: '70vh', position: 'relative' }}>
      <RevealWidget
        viewerOptions={{ sdk, useCoreDm }} // set per the project — see csp-and-fixes.md
        setControllerRef={handleWidgetController}
        appIdentifier="my-flows-app"
      />
    </div>
  );
}
```

## Dependencies

Suggested versions are starting points. If the target app already pins compatible versions, defer to the app.

| Package | Suggested version | Purpose |
|---------|-------------------|---------|
| `@cognite/reveal-widget` | `^0.3.0` | The `RevealWidget` component and its types |
| `react` / `react-dom` | `^18.3.1` (peer) | UI framework — peer dependency, must match the app |
| `@cognite/reveal` | `4.36.0` | Reveal viewer runtime — exact match required. Pin to `4.36.0`, not the `4.35.3` in `@cognite/reveal-widget`'s own declared peer range — see note below. |
| `@cognite/sdk` | `^10.14.0` (peer) | CDF API client — peer dependency |

Everything else (`three`, `@tanstack/react-query`, `@base-ui/react`, `@floating-ui/react`, `@tabler/icons-react`, `dayjs`, `lodash-es`, `ml-matrix`, `random-seed`, `@cognite/aura`, `@cognite/reveal-components`) is a transitive dependency of the package and installs automatically — do not add it manually unless the app needs to pin a version, **or unless app code imports from it directly**. The model-browser pattern in [implementation.md](references/implementation.md) does exactly that with `@tanstack/react-query` (`useInfiniteQuery`/`useQuery`) — add it as a direct dependency in that case, since importing from an undeclared transitive dependency breaks under strict package managers like pnpm.

Example install (pnpm; adapt to the app's package manager):

```bash
pnpm add @cognite/reveal-widget @cognite/[email protected] @cognite/sdk react react-dom
```

`@cognite/[email protected]`'s own peer range still says `@cognite/[email protected]`, but its dependency `@cognite/reveal-components` hardcodes `@cognite/[email protected]` internally. Pin the app to `4.36.0` and confirm the lockfile resolves a single `@cognite/reveal` version — the peer range is stale, and a real version split here (unlike a `resolve.dedupe` gap) breaks Reveal's shared viewer state silently.

Do **not** copy any source bundle into the app and do **not** install `process`, `util`, `assert`, `ajv`, or `vite-plugin-node-polyfills` for this package — none of that is needed.

## Critical Rules

- Drive the widget **imperatively** through `RevealWidgetController`, obtained via `setControllerRef`. Don't try to reconstruct Reveal's old declarative provider tree (`CacheProvider`/`RevealProvider`/`RevealCanvas`/`Reveal3DResources`) — that API belongs to the old copied-bundle approach and is not what this package exposes.
- `RevealWidget` wraps its own Reveal context internally — never nest it inside another provider from this package.
- Dispose the previous controller class instance (`.dispose()` calling `.remove()` on tracked handles) inside `setControllerRef` before constructing a new one, and again when `widgetController` becomes `undefined` (unmount).
- Resources passed to `addResource` must match the exact identifier shape for their `type`/`sourceType` combination (see [implementation.md](references/implementation.md)) — mixing classic and CDM fields is a type error.
- Instance highlighting only affects instances that are already contextualized (mapped) to a loaded model; load the model first, then call `styleByInstance`/`focusInstances`.
- `RevealWidget`'s container must have an explicit height — it fills its parent.
- Lazy-load canvas-heavy viewer content with `React.lazy` + `Suspense` when adding a route/page.
- `useCoreDm` must match the project, not default to `true` — wrong 401s and silent 360-collection failures otherwise. Don't wrap the app in `React.StrictMode` — it tears down `RevealWidget`'s viewer mid-load in dev and produces errors that don't occur in production. Point clouds need an app-side same-origin fix, since `manifest.json` can't grant the `data:` CSP allowance they'd otherwise need. All three: see [csp-and-fixes.md](references/csp-and-fixes.md).
- `appIdentifier` (a string naming the host app) is a **required** prop as of `@cognite/[email protected]` — mounting `RevealWidget` without it is a type error. By default the widget reports anonymous usage metrics (which features are used, e.g. adding a resource, moving the camera) to a dedicated `mixpanel-browser` instance. Pass the optional `tracking` prop to change this: `tracking={{ disabled: true }}` to opt out entirely, or `tracking={{ mixpanelToken }}` to report to a different Mixpanel project instead.

## Advanced Reference

For the full resource-identifier catalog (CAD, point cloud, 360 images, scenes), instance highlighting, and camera control, read [implementation.md](references/implementation.md).

For Vite/dedupe configuration, read [vite-config.md](references/vite-config.md).

For CSP/`manifest.json` allowances, the `useCoreDm`/StrictMode gotchas, the point-cloud app-side fix, and 360-collection troubleshooting, read [csp-and-fixes.md](references/csp-and-fixes.md).

## Verification Checklist

- [ ] `@cognite/reveal-widget` is installed alongside its peers (`react`, `react-dom`, `@cognite/reveal`, `@cognite/sdk`) at compatible versions.
- [ ] The app's `@cognite/reveal` is pinned to `4.36.0` (not the stale `4.35.3` in `@cognite/reveal-widget`'s peer range), with only one resolved `@cognite/reveal` version in the lockfile.
- [ ] No source bundle was copied into the app; all imports come from `@cognite/reveal-widget`, and no app code imports from `@cognite/reveal-components` directly.
- [ ] `vite.config.ts` includes `resolve.dedupe: ['three', '@cognite/reveal']` (plus the app's existing dedupe entries).
- [ ] No `process`/`util`/`assert` polyfills or `vite-plugin-node-polyfills` were added for this package.
- [ ] `RevealWidget` is mounted once, is not nested in another Reveal provider, its container has an explicit height, and it is given a required `appIdentifier` string prop.
- [ ] `viewerOptions.useCoreDm` matches whether the target project is actually Core-Data-Model-based.
- [ ] The app does not wrap itself in `React.StrictMode`.
- [ ] `manifest.json` grants `img-src` for `https://*.cognitedata.com` if the app loads scenes with ground planes/skybox, and `connect-src` for the actual signed-URL host observed from a CSP violation if it loads 360° image collections. If the app needs point cloud support, the same-origin `Blob`-patch fix has been applied and verified.
- [ ] A controller class wraps `RevealWidgetController`, obtained via `setControllerRef`, and drives `addResource`/`styleByInstance`/`focusInstances`/`cameraController` imperatively.
- [ ] The controller class is disposed (and tracked resource handles `.remove()`d) both when a new controller is set and on unmount (`widgetController === undefined`).
- [ ] Resource identifiers use the correct `type`/`sourceType` shape for the model being loaded.
- [ ] Typecheck and build pass.

© cognitedata · Apache-2.0 · cognitedata/builder-skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой