## **PanoTagPlugin**

## 功能说明

**全景热点标签插件** 提供在全景模式下标注房源不同位置热点标签信息。

详细功能点如下：

- 热点标签共分为“音频标签(Audio)”、“文本标签(Text)”、“图文标签(ImageText)”、“VR 跳转标签(Link)”、“营销标签(Marketing)”、“图片视频贴片(MediaPlane)”、“自定义标签(Custom)”等。
- `contentType` 决定标签内容及对应数据结构。
- `stickType` 决定标签如何附着到场景，支持 `2DPoint`、`3DPoint`、`Plane`、`Model`、`3DBox`、`Polygon` 和 `Mask`。
- 用户可以自由组合上述标签分类属性，根据自己的业务类型，创造更加适合的全景热点标签。

## 安装引用

**请按需选择 `yarn` 或 `npm` 安装方式：**

```bash npm2yarn
npm install @realsee/dnalogel
```

**通过 es 引用：**

```tsx
import { PanoTagPlugin } from '@realsee/dnalogel'
```

## 开发指南

### 初始化

在初始化 `Five` 实例时，将 `PanoTagPlugin` 配置在初始化插件参数即可。

```ts
import { Five } from '@realsee/five'
import { PanoTagPlugin } from '@realsee/dnalogel'

const five = new Five({
  plugins: [
    [
      PanoTagPlugin,
      'panoTagPlugin', // 自定义插件名称
      {
        // 参数配置
      },
    ],
  ],
})
```

### React 初始化

在创建 `FiveProvider` 时，将 `PanoTagPlugin` 配置在初始化插件参数即可。

```ts
import { PanoTagPlugin } from '@realsee/dnalogel'
import { createFiveProvider, FiveCanvas } from '@realsee/five/react'

const FiveProvider = createFiveProvider({
  plugins: [
    [
      PanoTagPlugin,
      'panoTagPlugin', // 自定义插件名称
      {
        // 参数配置
      },
    ],
  ],
})
```

### Vue 初始化

在使用 `FiveProvider` 时，将 `PanoTagPlugin` 配置在初始化插件参数即可。

```vue
<template>
  <FiveProvider :fiveInitArgs="fiveInitArgs"> </FiveProvider>
</template>
<script setup>
import PanoTagPlugin from '@realsee/dnalogel/libs/PanoTagPlugin'
import { FiveProvider, FiveCanvas } from '@realsee/five/vue'
const fiveInitArgs = {
  plugins: [
    [
      PanoTagPlugin,
      'panoTagPlugin', // 自定义插件名称
      {
        // 参数配置
      },
    ],
  ],
}
</script>
```

### 载入数据

```ts twoslash
// ---cut---
// 调用 `load` 方法载入全景标签数据
plugin.load(data)
//            ^?
```

### 核心方法

#### 载入插件数据
全量加载数据（会覆盖之前的数据）
```ts twoslash
// ---cut---
plugin.load(data)
```
增量添加数据
```ts twoslash
let tag: any
// ---cut---
plugin.addTag(tag)
```
清除标签数据
```ts twoslash
// ---cut---
plugin.clearTags()
```

#### 修改标签配置
```ts twoslash
let globalConfig:any
let contentTypeConfig:any
let contentTypeKey:any
let config: any
// ---cut---
plugin.changeConfig({ globalConfig, contentTypeConfig })
plugin.changeGlobalConfig(globalConfig)
plugin.changeContentTypeConfig(contentTypeKey, config)
```

#### 启用/禁用/展示/隐藏/销毁
```ts twoslash
// ---cut---
// 开启插件
plugin.enable()
// 禁用插件
plugin.disable()
// 显示插件
plugin.show()
// 隐藏插件
plugin.hide()
// 销毁插件
plugin.dispose()
```

#### 修改标签数据
修改 `tag.data`
```ts twoslash
let data: any
// ---cut---
plugin.changeDataById(1, data)
// or
const tag = plugin.getTagById(1)
tag?.changeData(data)
```

- `destroyTagById: (id: TagId | TagId[]) => void` 销毁 tag

- `pauseCurrentMedia: () => void` 暂停当前标签内进行的所有多媒体

## 热点标签配置

热点标签可以通过丰富的配置来实现各种不同的标签展示效果：

### 添加 config

1. load 时添加
```ts twoslash
import type { TagConfig } from '@realsee/dnalogel'

// ---cut---
const globalConfig: TagConfig = {}
const TextTagConfig: TagConfig = {}

pluginInstance.load({
  tagList: [],
  globalConfig: globalConfig,
  contentTypeConfig: {
    'Text': TextTagConfig
  }
})
```

2. 实时切换
```ts twoslash

// ---cut---
import type { TagConfig } from '@realsee/dnalogel'

const globalConfig: TagConfig = {}
const contentTypeConfig = {
  'Text': {}
}

pluginInstance.changeConfig({
  globalConfig,
  contentTypeConfig
})
```

### Config 种类
#### 1. 全局 Config
```ts twoslash
import type { TagConfig } from '@realsee/dnalogel'

// ---cut---
const globalConfig: TagConfig = {}

pluginInstance.load({
  tagList: [],
  globalConfig: globalConfig
})
```

#### 2. 按标签类型的config，只对指定类型的标签生效
> 这种设置方式全局配置也会同时生效，配置冲突时以局部配置为准
```ts twoslash
import type { TagConfig } from '@realsee/dnalogel'

// ---cut---
const TextTagConfig: TagConfig = {}

pluginInstance.load({
  tagList: [],
  contentTypeConfig: {
    'Text': TextTagConfig
  }
})
```
#### 2. 标签单独配置，只对单个标签生效
> 这种设置方式全局配置和标签类型维度的配置也会同时生效，配置冲突时以标签单独配置为准
```ts twoslash
import type { TagConfig } from '@realsee/dnalogel'
let tagData: any

// ---cut---
const TagConfig1: TagConfig = {}

pluginInstance.load({
  tagList: [
    {
      ...tagData, // 标签数据
      config: TagConfig1 // 只针对本标签有效
    }
  ],
})
```

### Config interface
```ts twoslash
import type { TagConfig } from '@realsee/dnalogel'

// ---cut---
const config: Simplify<TagConfig> = {
  visibleConfig: {
    keep: null,
//   ^?
    visibleFiveMode: ['Panorama'],
//   ^?
    visibleDistance: { min: 0, max: 10 },
//   ^?
    visiblePanoIndex: undefined,
//   ^?
    // 仅在 Mapview/Floorplan 下跟随当前楼层可见性
    followModelVisibility: false,
    // 从模型态点击入口进入全景时，是否允许看向标签点（仅全景标签）
    entryFromModel: false,
    // 碰撞检测配置：控制遮挡判断
    intersectRaycaster: {
      enabled: true,
      distanceAccuracy: 0.04,
      checkPoints: 'corner',
      needPassed: 1,
    },
    // 3D 标签在全景下，根据相机与法线夹角的可见范围
    angleRange: undefined,
  },
  unfoldedConfig: {
    keep: null,
//   ^?
    autoFoldWhenHide: false,
//   ^?
    autoUnfold: {
      enable: true,
//     ^?
      strategy: 'MinimumDistance',
//     ^?
      maxNumber: 1,
//     ^?
      distance: { min: 0, max: 10 }
//     ^?
    },
    // 进入可见范围则展开，离开则收起
    unfoldDistance: undefined,
    // 其他策略：'ScreenPostion' | 'FoldWhenMove' | 'ScreenCenter'
    // ScreenPostion: 根据投影 x 位置范围展开
    // FoldWhenMove: 屏幕移动自动收起
    // ScreenCenter: 屏幕中心优先展开
  },
  // 初始状态
  initialState: {
    visible: undefined,
    unfolded: undefined,
  },
  // 初始化合并到 tag.data 的默认数据（支持 important 覆盖）
  initialData: {
    important: false,
  },
  // 3D 标签容器配置
  tag3DConfig: {
    // ratio 等缩放参数在全局默认里也可配置
  }
}
```

### 修改Config
参照 [修改标签配置](https://open.realsee.cn/docs/dnalogel/PanoTagPlugin#修改标签配置)

### 常用配置项说明

#### visibleConfig（可见性）

- `keep`: 在指定模式下强制可见/不可见。可选 `'visible' | 'hidden' | null`。设置后同组内其他项不再生效。
- `visibleFiveMode`: 指定在哪些 Five 模式下可见。支持`Five.Mode | Five.Mode[] | 'PanoramaLike'|'ModelLike'|'all' | ((tag: TagInstance) => TagVisibleMode)`返回。
- `followModelVisibility`: Mapview/Floorplan 下是否仅在当前楼层可见。
- `entryFromModel`: 模型态点击入口，进入全景后自动看向标签（仅全景标签）。
- `visibleDistance`: 按与摄像机距离控制可见范围，`MinMax` 或 `'unLimited'`。
- `visiblePanoIndex`: 控制在哪些全景点位可见：`'all' | 'current' | number[]`。
- `intersectRaycaster`: 标签遮挡检测（开启将按模型遮挡判断可见）。
  - `enabled`: 是否开启
  - `distanceAccuracy`: 距离误差
  - `checkPoints`: `'center' | 'corner' | Vector3[]`
  - `needPassed`: 通过多少检测点算可见
- `angleRange`: 全景下（3D 标签）按相机与法线夹角范围可见。

#### unfoldedConfig（展开/收起）

- `keep`: `'unfolded' | 'folded' | null`（优先级最高）。
- `autoFoldWhenHide`: 隐藏时自动收起（部分标签天然不可收起）。
- `unfoldDistance`: 进入范围展开，出范围收起。
- `autoUnfold` 策略：
  - `'MinimumDistance'`: 最近标签自动展开，支持 `maxNumber`、`distance`。
  - `'ScreenPostion'`: 根据标签投影到屏幕的 X 坐标范围展开（`autoUnfoldProjectX`，取值区间为 [-1, 1]，越接近 0 越靠近屏幕中心）。
  - `'FoldWhenMove'`: 屏幕移动时收起。
  - `'ScreenCenter'`: 屏幕中心优先展开（支持 `distance`、`maxNumber`）。

#### 初始行为与数据

- `initialState`: 初始的 `visible/unfolded`。
- `initialData`: 合并到 `tag.data` 的默认数据，支持 `important` 强覆盖。

#### 渲染与交互

- `tag3DConfig`: 3D 容器参数（全局默认里也常配置 ratio 等）。
- `modelConfig.autoLookAtEnabled`: 模型标签进入全景后是否自动朝向相机。
- `renderType`: `'Mesh' | 'Dom'`（营销贴片等在特定条件可用 Mesh）。
- `simulate3D`: 是否模拟近大远小。
- `clickable`: 标签是否可点。

#### popoverConfig（浮窗，开启后 `unfoldedConfig` 失效）

- `enabled`: 是否启用浮窗（默认 `false`）。
- `trigger`: `'hover' | 'click'`（默认 `'hover'`）。
- `triggerDelay`: 悬停触发延迟（单位 ms，插件默认 500，可覆盖）。
- `placement`: 浮窗位置（`top/bottom/left/right/.../auto`）。
- `autoPlacementBaseSpace`: 自动定位时的参考分区 `{ top, right, bottom }`。
- `transitionDuration`: 动画时长（ms）。
- `theme`: `'dark' | 'light'`。
- `toolbar`: `{ showMore?: boolean; showShare?: boolean }`。
- `zIndex`: 浮层 zIndex（默认 `2000000`）。
- `imageURLTransform`: `(url, { width, height }) => string` 图片地址加工。
- `viewMoreText`: “查看更多” 文案。
- `beforeOpen(tag)`: 返回 `false` 可拦截 hover 打开。

示例：通过 `load` 全局开启浮窗并使用 hover 触发

```ts
pluginInstance.load({
  tagList: [],
  globalConfig: {
    popoverConfig: {
      enabled: true,
      trigger: 'hover',
      triggerDelay: 500,
      placement: 'auto',
    },
  },
})
```

示例：给单个标签开启浮窗，并自定义主题/工具栏

```ts
pluginInstance.load({
  tagList: [
    {
      // ... 其他 tag 字段
      config: {
        popoverConfig: {
          enabled: true,
          theme: 'light',
          toolbar: { showMore: true, showShare: true },
        },
      },
    },
  ],
})
```

示例：运行时更新全局配置

```ts
pluginInstance.changeGlobalConfig({
  popoverConfig: {
    enabled: true,
    trigger: 'click',
  },
})
```

## 添加自定义热点标签

热点标签中有一个标签类型叫做“自定义热点标签”，使用这个标签类型，开发者可以根据自己的业务需要，自定义添加任意符合规范的标签样式。

可以参考下面的例子：

```ts
// 添加自定义热点
const addCustomerTag = () => {
  // 自定义Element
  const ele = document.createElement('div')
  ele.innerText = '这是一个自定义的热点标签'
  ele.style.color = 'red'
  ele.style.width = '200px'
  ele.style.border = '1px solid #000'

  const tagData: Tag = {
    id: '03338b76-b64a-4e90-37fb-44e3c0ffeb88',
    stickType: '2DPoint',
    position: [-1.7882169929208833, 1.022040232156752, -2.339700937271118],
    data: {
      text: '自定义热点标签',
    },
    element: ele,
    // ContentType设置为Custom
    contentType: 'Custom',
  }
  pluginInstance.addTag(tagData)
}
```

## 自定义标签渲染器

### 1. 指定自定义标签类型的渲染方式

**使用场景：**

我通过某种方式生产了一批 contentType 为 `super_tag` 的标签数据，我现在想用 `PanoTagPlugin` 来渲染这批数据，显示结果为：`<div>I'm super tag, my name is {data.name}</div>`

**代码示例：**

```tsx
import { createRoot } from 'react-dom/client'
import type { TagInstance } from '@realsee/dnalogel'

const plugin = five.plugins.panoTagPlugin

/** 自定义标签组件 */
function SuperTag(props: { tag: TagInstance<'Custom'> }) {
  return <div>I'm a super tag, my name is {props.tag.data.name}</div>
}

plugin.registerRenderer('super_tag', (container: HTMLElement, tagInstance: TagInstance<'Custom'>) => {
  // 使用 <SuperTag> 来渲染 contentType 为 "super_tag" 的标签
  const root = createRoot(container)
  root.render(<SuperTag tag={tagInstance} />)
  // 需返回销毁函数
  return () => root.unmount()
})

// 自定义标签数据
plugin.load({
  tagList: [
    {
      contentType: 'super_tag',
      position: [0, 1, 2],
      data: {
        name: 'super tag 1',
      },
    },
  ],
})
```

> Tips: `plugin.registerRenderer` 调用一次即可，无需多次调用。若不确定是否已经调用过，可以使用 `if (plugin.rendererMap.has('My_Custom_Tag_Type')) {}` 判断渲染器是否已被注册。

### 2. 替换已有标签的渲染方式

**使用场景：**

我觉得`PanoTagPlugin`里的文本标签(`contentType: 'Text'`)太丑了，我想在数据不变的情况下自己换一套样式

**代码示例：**

```tsx
import { createRoot } from 'react-dom/client'
import type { TagInstance } from '@realsee/dnalogel'

const plugin = five.plugins.panoTagPlugin

/** 自定义文本标签组件 */
function BeautifulTextTag(props: { tag: TagInstance<'Text'> }) {
  return <div>I'm a beautiful text tag, my title is {props.tag.data.title}</div>
}

plugin.registerRenderer('Text', (container: HTMLElement, tagInstance: TagInstance<'Text'>) => {
  // 使用 <BeautifulTextTag> 来渲染 contentType 为 "Text" 的标签，替换掉默认的渲染方式
  const root = createRoot(container)
  root.render(<BeautifulTextTag tag={tagInstance} />)
  // 需返回销毁函数
  return () => root.unmount()
})

// 原有标签数据
plugin.load({
  tagList: [
    {
      contentType: 'Text',
      position: [0, 1, 2],
      data: {
        title: 'text tag',
      },
    },
  ],
})
```

### 3. 使用内置的渲染器来渲染自定义标签

**使用场景：**

我有一套 contentType 为 `My_Text` 的标签数据, 我觉得`PanoTagPlugin`里的文本标签样式正好符合我的需求，我想用插件内置的文本标签来渲染我这套数据，并且我无法改动原始数据类型。

**代码示例：**

```ts
const plugin = five.plugins.panoTagPlugin

/** 使用内置的 `Text` 标签的样式来渲染 `My_Text`标签 */
plugin.bindRenderer('My_Text', `Text`)

// 原有标签数据
plugin.load({
  tagList: [
    {
      contentType: 'My_Text',
      position: [0, 1, 2],
      data: {
        title: 'text tag',
      },
    },
  ],
})
```

### 4. 标签data更改时，组件数据同步更新

**使用场景：**
我有一个输入框，我输入的内容要实时渲染到我的自定义文本标签上

**代码示例：**
```tsx
import { useEffect, useState } from 'react'
import type { TagInstance } from '@realsee/dnalogel'

// 示例2中的自定义标签组件 BeautifulTextTag
function BeautifulTextTag(props: { tag: TagInstance<'Text'> }) {
  const [data, setData] = useState(props.tag.data)

  useEffect(() => {
    // 监听 dataChanged，实时更新 state
    props.tag.hooks.on('dataChanged', setData)

    return () => props.tag.hooks.off('dataChanged', setData)
  }, [props.tag])


  return <div>inputting text is: {data.title}</div>
}

// input 输入框
function Input() {
  const [text, setTextState] = useState('')

  const setText = (inputValue: string) => {
    setTextState(inputValue)
    plugin.changeDataById('id', { title: inputValue })
  }

  return <input value={text} onChange={(e) => setText(e.target.value)} />
}
```


## 监听标签事件

支持的事件

- `click` 单个标签点击事件
- `playStateChange` 标签内多媒体播放状态变化事件
- `exposure` 标签曝光事件
- `show` 标签插件显示事件
- `hide` 标签插件隐藏事件
- `enable` 标签插件启用事件
- `disable` 标签插件禁用事件
- `hover` 标签悬停触发事件（开启 popover 且 trigger='hover' 或 'click' 时触发）
- `showPopover` 标签浮窗显示事件
- `hidePopover` 标签浮窗隐藏事件

参考一下代码进行事件监听：

```ts
import type { TagClickParams, TagId, TagInstance } from '@realsee/dnalogel'

// 监听标签点击事件
pluginInstance.hooks.on("click", (params: TagClickParams) => {
  console.log("click", params);
});

// 监听标签内多媒体播放状态变化事件
pluginInstance.hooks.on("playStateChange", (params: { event: Event; state: 'playing' | 'paused'; tag: TagInstance; mediaInstance: HTMLMediaElement }) => {
  console.log("playStateChange", params);
});

// 监听标签曝光事件
pluginInstance.hooks.on("exposure", (params: { id: TagId; type: 'start' | 'end' }) => {
  console.log("exposure", params);
});

// 监听标签插件显示事件
pluginInstance.hooks.on("show", (options: { userAction: boolean }) => {
  console.log("show", options);
});

// 监听标签插件隐藏事件
pluginInstance.hooks.on("hide", (options: { userAction: boolean }) => {
  console.log("hide", options);
});

// 监听标签插件启用事件
pluginInstance.hooks.on("enable", (options: { userAction: boolean }) => {
  console.log("enable", options);
});

// 监听标签插件禁用事件
pluginInstance.hooks.on("disable", (options: { userAction: boolean }) => {
  console.log("disable", options);
});
```

### 支持 hover 触发

开启浮窗并使用 hover/点击触发展示：

```ts
// 全局开启浮窗，并配置触发方式/延迟
pluginInstance.changeGlobalConfig({
  popoverConfig: {
    enabled: true,
    trigger: 'hover',        // 或 'click'
    triggerDelay: 500,       // 仅在 trigger='hover' 时生效
  },
})

// 也可在 load 时配置，或在标签级 config.popoverConfig 中覆盖
```

监听 hover 与浮窗事件：

```ts
// 监听标签 hover（悬停或点击触发展示前的统一事件）
pluginInstance.hooks.on('hover', ({ event, tag }) => {
  console.log('hover', { event, id: tag.id, contentType: tag.contentType })
})

// 监听浮窗显示/隐藏
tagInstance.hooks.on('showPopover', () => console.log('popover show'))
tagInstance.hooks.on('hidePopover', () => console.log('popover hide'))
```

运行时临时禁用/启用 hover：

```ts
// 全局关闭/开启 hover（不影响配置，只做临时屏蔽）
pluginInstance.setGlobalHoverEnabled(false)
pluginInstance.setGlobalHoverEnabled(true)

// 按标签 ID 禁用/启用 hover（仅临时控制）
pluginInstance.setTagHoverEnabled('tag-id', false)
pluginInstance.setTagHoverEnabled('tag-id', true)
```

移除事件监听

```ts
// 移除事件监听
pluginInstance.hooks.off('click', clickHandler)
pluginInstance.hooks.off('playStateChange', playStateChangeHandler)
pluginInstance.hooks.off('exposure', exposureHandler)
pluginInstance.hooks.off('show', showHandler)
pluginInstance.hooks.off('hide', hideHandler)
pluginInstance.hooks.off('enable', enableHandler)
pluginInstance.hooks.off('disable', disableHandler)
```

## 数据结构

插件中最重要的结构是 `Tag`。添加热点标签、修改标签信息等操作都需要使用它。在 `@realsee/dnalogel@3.81.0` 中，它的两个泛型参数分别表示内容类型与附着类型：

```typescript
import type { Tag } from '@realsee/dnalogel'

const tag: Tag<'Text', '2DPoint'> = {
  id: 'living-room',
  contentType: 'Text',
  stickType: '2DPoint',
  position: [0, 1.4, -2],
  data: {
    title: '客厅',
  },
}
```

当前公开结构包含以下字段：

| 字段 | 约定 |
| --- | --- |
| `contentType` | 必填内容类型，例如 `Text`、`ImageText`、`Audio`、`Link`、`Marketing`、`MediaPlane`、`Model` 或 `Custom`，并决定对应的 `data` 结构。 |
| `stickType` | 可选附着类型，支持 `2DPoint`、`3DPoint`、`Plane`、`Model`、`3DBox`、`Polygon` 和 `Mask`，默认值为 `2DPoint`。 |
| `position` | 必填坐标，结构取决于 `stickType`；平面使用四个坐标，点和模型标签使用一个坐标。 |
| `data` | 由 `contentType` 决定的必填内容数据。 |
| `config` | 可选 `TagConfig<C>`，用于控制可见性、展开、交互和浮窗行为。 |
| `id`、`enabled`、`normal`、`element`、`className`、`fiveState`、`style`、`hoverEnabled` | 可选的标识、状态、渲染和交互字段；`3DPoint` 标签必须提供 `normal`。 |

旧的 `pointType` 和 `dimensionType` 只作为兼容字段保留，新接入应使用 `stickType` 和双参数 `Tag<C, S>` 契约。

## demo 源码参考

[示例源码](https://github.com/realsee-developer/dnalogel/tree/main/src/PanoTagPlugin)

网页版本：https://open.realsee.cn/docs/dnalogel/PanoTagPlugin
文档索引：https://open.realsee.cn/docs.md
