# @cognite/reveal-widget

A React component for embedding an interactive [Cognite Reveal](https://cognitedata.github.io/reveal)
3D viewer in your application: `RevealWidget`. It loads and renders CAD models, point clouds,
360° image collections, and CDF scenes, and lets you highlight and focus specific instances
(assets) within them.

This package exposes `RevealWidget` and the types needed to drive it via
`RevealWidgetController`. More capabilities from the broader Reveal Components toolkit
will be exposed here incrementally over time.

## Usage tracking (Mixpanel)

`RevealWidget` can report anonymous usage events to a Cognite-owned Mixpanel project. This
tells us which features of the widget are actually used (loading a resource, styling
instances, moving the camera, etc.) so we can prioritize development. No event payload
includes page URLs, referrers, resource IDs, or any other identifying data.

`RevealWidget` requires an `appIdentifier` prop so aggregate usage can be attributed
correctly. The optional `tracking` prop lets you change where events go:

```tsx
// Reports to the default Cognite Mixpanel project (the default when `tracking` is omitted).
<RevealWidget viewerOptions={...} appIdentifier="my-app" />

// Opt out entirely — no events are sent anywhere.
<RevealWidget viewerOptions={...} appIdentifier="my-app" tracking={{ disabled: true }} />

// Report to your own Mixpanel project instead of Cognite's.
<RevealWidget
  viewerOptions={...}
  appIdentifier="my-app"
  tracking={{ mixpanelToken: 'your-own-project-token' }}
/>

// Route events through your own tracking/analytics pipeline instead of Mixpanel.
<RevealWidget
  viewerOptions={...}
  appIdentifier="my-app"
  tracking={{ usageMetricsTracker: { track: (event, properties) => myOwnTracker(event, properties) } }}
/>
```

See `RevealWidgetTrackingProps` for the full set of options.

## Install

```bash
npm install @cognite/reveal-widget @cognite/reveal @cognite/sdk react react-dom
```

`react`, `react-dom`, `@cognite/reveal`, and `@cognite/sdk` are peer dependencies — install
versions matching what your app already uses. Everything else the widget needs installs
automatically as a regular dependency.

If your bundler doesn't already dedupe singletons across your dependency tree, add:

```ts
// vite.config.ts
resolve: {
  dedupe: ['three', '@cognite/reveal'];
}
```

## Usage

`RevealWidget` hands you a `RevealWidgetController` via `setControllerRef`. Rather than
reacting to prop changes through `useEffect`, wrap it in your own class and drive it
imperatively — e.g. from event handlers elsewhere in your app (a click on an asset in a list,
a button press, etc.):

```tsx
import { useRef } from 'react';
import type { CogniteClient } from '@cognite/sdk';
import {
  Default3DStyles,
  RevealWidget,
  type Reveal3DResourceHandle,
  type RevealWidgetController,
  type ThreeDResourceIdentifier,
  type InstanceId,
} 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);
  }

  async highlightAsset(instanceId: InstanceId): Promise<void> {
    if (this.model === undefined) return;
    await this.widgetController.styleByInstance(
      [{ instanceIds: [instanceId], style: Default3DStyles.Highlighted }],
      [this.model]
    );
    await this.widgetController.focusInstances([instanceId]);
  }

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

export function ThreeDViewer({
  sdk,
  resource,
  onReady,
}: {
  sdk: CogniteClient;
  resource: ThreeDResourceIdentifier;
  onReady: (viewer: ThreeDViewerController | undefined) => void;
}) {
  const viewerRef = useRef<ThreeDViewerController>();

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

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

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

  return (
    <div style={{ width: '100%', height: '70vh', position: 'relative' }}>
      <RevealWidget
        viewerOptions={{ sdk, useCoreDm: true }}
        setControllerRef={handleWidgetController}
      />
    </div>
  );
}

// Elsewhere, e.g. from a click handler in whatever renders a list of assets:
// viewer.highlightAsset({ externalId: 'CogniteAsset-1022', space: 'my-space' });
```

`RevealWidget` wraps its own Reveal context internally — don't wrap it in another provider from
this package.

### Loading resources

`controller.addResource(...)` accepts CAD models, point clouds, 360° image collections, or
scenes, identified by `type` and `sourceType`:

```ts
{ type: 'cad',        sourceType: 'classic', modelId: number, revisionId: number }
{ type: 'cad',        sourceType: 'cdm',     externalId: string, space: string }
{ type: 'pointcloud', sourceType: 'classic', modelId: number, revisionId: number }
{ type: 'pointcloud', sourceType: 'cdm',     externalId: string, space: string }
{ type: 'image360',   sourceType: 'dm' | 'cdm', externalId: string, space: string }
{ type: 'image360',   sourceType: 'events',  siteId: string }
{ type: 'scene',                              externalId: string, space: string }
```

CAD/point cloud/image360 resources resolve to a `Reveal3DResourceHandle` usable with
`styleByInstance`/`getModels()`/`cameraController.focusModel()`; a `'scene'` resource resolves to
a handle that only supports `.remove()`.

### Loading a scene by location

`controller.addResourceByLocation(location, selectedScene?)` loads the scene configured for a
location, matched by external ID or name and including its sub-locations. It resolves to a result
with a `status`:

- `'loaded'`: exactly one scene was found and added; `scene` is its handle
- `'selection-required'`: several scenes were found and nothing was loaded; `candidates` lists
  each `{ scene, locationName }`. Call again with the chosen `scene` as `selectedScene`
- `'not-found'`: no such location, or it has no scene

### Searching mapped assets

`controller.assets.searchMappedAssets({ query?, limit? })` searches the data modeling assets
mapped to the visible CAD models, point clouds and data model 360 image collections, including
those of a loaded scene. Classic assets are never searched, so use it with `useCoreDm: true` in
data-modeling-only projects. `limit` defaults to 100 (maximum 1000). There is no pagination; when
`hasMore` is true, narrow the search with `query`.

```ts
const { assets, hasMore } = await controller.assets.searchMappedAssets({
  query: 'pump',
});
await controller.focusInstances([assets[0].instanceId]);
```

### HTML overlays

`controller.htmlOverlays.add(element, position)` attaches an HTML element to a position in the 3D scene, e.g. to show a notification.
The element follows the position as the camera moves and is hidden while the position is out of view.
`position` is `{ x, y, z }` in CDF coordinates, the same ones the coordinates of CDF 3D models and their assets are given in.
It returns a handle whose `remove()` removes the overlay.
Removing an overlay right after adding it is safe.
Adding the same element again moves it to the new position.

The widget sets `position: absolute` on the element, which overlays require.
Other styling is up to you, e.g. `transform: translate(-50%, -50%)` to center the element on the position, and `pointer-events: none` if it should not interfere with camera navigation.

```ts
const element = document.createElement('div');
element.textContent = 'Pump 01 needs attention';
element.style.transform = 'translate(-50%, -50%)';

const overlay = controller.htmlOverlays.add(element, { x: 10, y: 20, z: 5 });

// Hide or show all overlays without removing them
controller.htmlOverlays.setVisible(false);

// Remove one overlay, or all of them
overlay.remove();
controller.htmlOverlays.clear();
```

Overlays are removed when the widget unmounts or its controller is replaced.

### Highlighting instances

Instances (assets) are identified either by classic numeric asset ID or by a data modeling
`{ externalId, space }` reference:

```ts
instanceIds: [1560727417020285];
instanceIds: [{ externalId: 'CogniteAsset-1022', space: 'my-space' }];
```

### Camera control

```ts
controller.cameraController.focusModel(handle); // fit one model
controller.cameraController.focusCameraAll(); // fit all models
await controller.focusInstances([someInstanceId]); // zoom to a specific instance
```

If the instance is mapped to an annotation in a 360 image, `focusInstances` enters that image
instead of moving to a bounding box.

## Cleaning up

Resources added via `addResource` should be removed when no longer needed:

```ts
const handle = await controller.addResource(resource);
// ...later:
handle.remove();
```
