@aceshooting/lyra-ui 29.2.2 → 30.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (440) hide show
  1. package/CHANGELOG.md +126 -106
  2. package/README.md +8 -7
  3. package/dist/ai/snapshot.js +1 -1
  4. package/dist/all.d.ts +1 -1
  5. package/dist/all.js +1 -1
  6. package/dist/autoloader.js +1 -1
  7. package/dist/cli/component-inventory.mjs +1 -1
  8. package/dist/cli/lyra-rename-ledger.mjs +1 -1
  9. package/dist/cli/migrate-wa.mjs +7 -3
  10. package/dist/cli/migration-analysis.mjs +1 -1
  11. package/dist/cli/migration-contract.json +1 -1
  12. package/dist/cli/migration-contract.mjs +1 -1
  13. package/dist/cli/migration-immutable-collections.mjs +6 -0
  14. package/dist/cli/migration-renames.mjs +1 -1
  15. package/dist/cli/migration-transforms.mjs +1 -1
  16. package/dist/components/agent-tools/activity-feed/activity-feed.class.d.ts +1 -1
  17. package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.d.ts +1 -2
  18. package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
  19. package/dist/components/agent-tools/agent-run/agent-run.class.d.ts +3 -4
  20. package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
  21. package/dist/components/agent-tools/agent-trace/agent-trace.class.d.ts +1 -1
  22. package/dist/components/agent-tools/agent-trace/agent-trace.class.js +2 -2
  23. package/dist/components/agent-tools/background-runs/background-runs.class.d.ts +1 -2
  24. package/dist/components/agent-tools/background-runs/background-runs.class.js +1 -1
  25. package/dist/components/agent-tools/change-review/change-review.class.d.ts +1 -2
  26. package/dist/components/agent-tools/change-review/change-review.class.js +1 -1
  27. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.d.ts +3 -2
  28. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
  29. package/dist/components/agent-tools/evaluation-run/evaluation-run.class.d.ts +7 -1
  30. package/dist/components/agent-tools/evaluation-run/evaluation-run.class.js +1 -1
  31. package/dist/components/agent-tools/prompt-studio/prompt-studio.class.d.ts +2 -2
  32. package/dist/components/agent-tools/prompt-studio/prompt-studio.class.js +3 -3
  33. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.d.ts +1 -1
  34. package/dist/components/agent-tools/subagent-panel/subagent-panel.class.d.ts +1 -2
  35. package/dist/components/agent-tools/subagent-panel/subagent-panel.class.js +2 -2
  36. package/dist/components/agent-tools/task-list/task-list.class.d.ts +1 -1
  37. package/dist/components/agent-tools/test-results/test-results.class.d.ts +1 -1
  38. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.d.ts +3 -4
  39. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +1 -5
  40. package/dist/components/agent-tools/tool-timeline/tool-timeline.class.d.ts +3 -3
  41. package/dist/components/agent-tools/trace-tree/trace-tree.class.d.ts +1 -0
  42. package/dist/components/agent-tools/trace-tree/trace-tree.class.js +1 -1
  43. package/dist/components/charts/chart/chart.class.js +3 -3
  44. package/dist/components/charts/chart-3d/chart-3d-data.d.ts +50 -0
  45. package/dist/components/charts/chart-3d/chart-3d-data.js +1 -0
  46. package/dist/components/charts/chart-3d/chart-3d-engine.js +1 -0
  47. package/dist/components/charts/chart-3d/chart-3d.class.d.ts +96 -0
  48. package/dist/components/charts/chart-3d/chart-3d.class.js +47 -0
  49. package/dist/components/charts/chart-3d/chart-3d.d.ts +1 -0
  50. package/dist/components/charts/chart-3d/chart-3d.js +1 -0
  51. package/dist/components/charts/chart-3d/chart-3d.styles.js +1 -0
  52. package/dist/components/charts/index.d.ts +1 -1
  53. package/dist/components/charts/index.js +1 -1
  54. package/dist/components/conversation/agent-workspace/agent-workspace.class.d.ts +3 -3
  55. package/dist/components/conversation/agent-workspace/agent-workspace.class.js +4 -5
  56. package/dist/components/conversation/code-block/code-block-base.class.js +1 -1
  57. package/dist/components/conversation/code-block/shiki-oniguruma.d.ts +3 -0
  58. package/dist/components/conversation/code-block/shiki-oniguruma.js +1 -0
  59. package/dist/components/conversation/code-block/shiki-types.d.ts +3 -5
  60. package/dist/components/conversation/code-block/shiki-types.js +1 -1
  61. package/dist/components/conversation/generation-metrics/generation-metrics.class.js +1 -1
  62. package/dist/components/conversation/markdown/markdown-progressive.js +1 -1
  63. package/dist/components/conversation/message-actions/message-actions.class.js +1 -1
  64. package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
  65. package/dist/components/conversation/model-select/model-select.class.js +1 -1
  66. package/dist/components/conversation/model-settings-panel/model-settings-panel.class.js +1 -1
  67. package/dist/components/conversation/prompt-input/prompt-input.class.js +3 -4
  68. package/dist/components/conversation/prompt-queue/prompt-queue.class.d.ts +1 -1
  69. package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
  70. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
  71. package/dist/components/conversation/thread-list/thread-list.class.d.ts +2 -2
  72. package/dist/components/conversation/thread-list/thread-list.class.js +1 -1
  73. package/dist/components/conversation/widget-renderer/registry.js +1 -1
  74. package/dist/components/conversation/widget-renderer/resolve.js +1 -1
  75. package/dist/components/data/calendar/calendar.class.d.ts +3 -1
  76. package/dist/components/data/data-grid/data-grid.class.js +2 -2
  77. package/dist/components/data/flow-canvas/flow-canvas.class.js +2 -2
  78. package/dist/components/data/flow-canvas/flow-source.js +1 -1
  79. package/dist/components/data/flow-node/flow-node.class.d.ts +2 -3
  80. package/dist/components/data/flow-node/flow-node.class.js +2 -4
  81. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  82. package/dist/components/data/sparkline/sparkline.class.d.ts +0 -1
  83. package/dist/components/data/sparkline/sparkline.class.js +1 -1
  84. package/dist/components/data/table/table.class.js +1 -1
  85. package/dist/components/forms/color-picker/color-core.js +1 -1
  86. package/dist/components/forms/date-picker/calendar-core.js +1 -1
  87. package/dist/components/forms/otp-input/otp-input.class.js +1 -1
  88. package/dist/components/forms/signature-pad/signature-pad.class.d.ts +4 -3
  89. package/dist/components/forms/signature-pad/signature-pad.class.js +1 -1
  90. package/dist/components/forms/swatch-picker/swatch-picker.class.d.ts +3 -2
  91. package/dist/components/forms/swatch-picker/swatch-picker.class.js +1 -1
  92. package/dist/components/layout/app-rail/app-rail-item.class.d.ts +0 -2
  93. package/dist/components/layout/app-rail/app-rail-item.class.js +1 -1
  94. package/dist/components/layout/app-rail/app-rail.class.d.ts +3 -3
  95. package/dist/components/layout/command-palette/command-palette.class.d.ts +1 -1
  96. package/dist/components/layout/details/accordion-item.class.d.ts +1 -2
  97. package/dist/components/layout/details/accordion-item.class.js +1 -1
  98. package/dist/components/layout/dock-panel/dock-panel.class.d.ts +4 -11
  99. package/dist/components/layout/dock-panel/dock-panel.class.js +1 -1
  100. package/dist/components/layout/drilldown-panel/drilldown-panel.class.js +1 -1
  101. package/dist/components/layout/menu/menu.class.js +1 -1
  102. package/dist/components/layout/menubar/menubar-item.class.d.ts +1 -1
  103. package/dist/components/layout/menubar/menubar.class.d.ts +1 -1
  104. package/dist/components/layout/multi-split/multi-split.class.d.ts +1 -1
  105. package/dist/components/layout/multi-split/multi-split.class.js +1 -1
  106. package/dist/components/layout/navigation-menu/navigation-menu.class.d.ts +2 -6
  107. package/dist/components/layout/navigation-menu/navigation-menu.class.js +1 -1
  108. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  109. package/dist/components/layout/virtual-list/virtual-list.class.d.ts +3 -2
  110. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  111. package/dist/components/layout/widget/widget.class.d.ts +5 -14
  112. package/dist/components/layout/widget/widget.class.js +2 -2
  113. package/dist/components/lr-chart-3d.js +1 -0
  114. package/dist/components/lr-model-viewer.js +1 -0
  115. package/dist/components/media/av-player/av-metadata.d.ts +1 -13
  116. package/dist/components/media/av-player/av-metadata.js +1 -1
  117. package/dist/components/media/av-player/av-player.class.js +1 -1
  118. package/dist/components/media/file-input/file-input.class.d.ts +10 -13
  119. package/dist/components/media/file-input/file-input.class.js +3 -3
  120. package/dist/components/media/file-input/file-input.styles.js +1 -1
  121. package/dist/components/media/image-viewer/image-viewer-panorama.d.ts +5 -0
  122. package/dist/components/media/image-viewer/image-viewer-panorama.js +8 -0
  123. package/dist/components/media/image-viewer/image-viewer-panorama.styles.js +1 -0
  124. package/dist/components/media/image-viewer/image-viewer.class.d.ts +29 -5
  125. package/dist/components/media/image-viewer/image-viewer.class.js +8 -5
  126. package/dist/components/media/image-viewer/image-viewer.styles.js +1 -1
  127. package/dist/components/media/map/map-anchor-controller.js +1 -0
  128. package/dist/components/media/map/map-anchor-options.d.ts +14 -0
  129. package/dist/components/media/map/map-anchor-options.js +1 -0
  130. package/dist/components/media/map/map-camera.d.ts +34 -0
  131. package/dist/components/media/map/map-camera.js +1 -0
  132. package/dist/components/media/map/map-construction-scheduler.d.ts +13 -0
  133. package/dist/components/media/map/map-construction-scheduler.js +1 -0
  134. package/dist/components/media/map/map-control-options.d.ts +39 -0
  135. package/dist/components/media/map/map-control-options.js +1 -0
  136. package/dist/components/media/map/map-controls-lifecycle.js +1 -0
  137. package/dist/components/media/map/map-cursor.js +1 -0
  138. package/dist/components/media/map/map-data-layer-model.d.ts +40 -0
  139. package/dist/components/media/map/map-data-layer-model.js +1 -0
  140. package/dist/components/media/map/map-drawing-controller.js +1 -0
  141. package/dist/components/media/map/map-drawing-gesture.js +1 -0
  142. package/dist/components/media/map/map-drawing-pan.js +1 -0
  143. package/dist/components/media/map/map-drawing-pointer.js +1 -0
  144. package/dist/components/media/map/map-drawing.d.ts +29 -0
  145. package/dist/components/media/map/map-drawing.js +1 -0
  146. package/dist/components/media/map/map-empty-style.d.ts +8 -0
  147. package/dist/components/media/map/map-empty-style.js +1 -0
  148. package/dist/components/media/map/map-engine-events.js +1 -0
  149. package/dist/components/media/map/map-export-attribution.js +1 -0
  150. package/dist/components/media/map/map-external-source-effects.js +1 -0
  151. package/dist/components/media/map/map-feature-loader-core.js +1 -0
  152. package/dist/components/media/map/map-feature-loader.js +1 -0
  153. package/dist/components/media/map/map-feature-state-router.d.ts +16 -0
  154. package/dist/components/media/map/map-feature-state-router.js +1 -0
  155. package/dist/components/media/map/map-feature-state-routes.js +1 -0
  156. package/dist/components/media/map/map-feature-state.d.ts +16 -0
  157. package/dist/components/media/map/map-feature-state.js +1 -0
  158. package/dist/components/media/map/map-hash-option.js +1 -0
  159. package/dist/components/media/map/map-hash-owner.js +1 -0
  160. package/dist/components/media/map/map-hash.js +1 -0
  161. package/dist/components/media/map/map-hit-test.d.ts +17 -0
  162. package/dist/components/media/map/map-hit-test.js +1 -0
  163. package/dist/components/media/map/map-image-admission.d.ts +7 -0
  164. package/dist/components/media/map/map-image-admission.js +1 -0
  165. package/dist/components/media/map/map-image-export-controller.js +1 -0
  166. package/dist/components/media/map/map-image-export-error.d.ts +3 -0
  167. package/dist/components/media/map/map-image-export-error.js +1 -0
  168. package/dist/components/media/map/map-image-export.d.ts +15 -0
  169. package/dist/components/media/map/map-image-export.js +5 -0
  170. package/dist/components/media/map/map-image-limits.d.ts +4 -0
  171. package/dist/components/media/map/map-image-limits.js +1 -0
  172. package/dist/components/media/map/map-image-metadata.js +3 -0
  173. package/dist/components/media/map/map-image-provider.d.ts +33 -0
  174. package/dist/components/media/map/map-image-provider.js +1 -0
  175. package/dist/components/media/map/map-images.d.ts +9 -0
  176. package/dist/components/media/map/map-images.js +1 -0
  177. package/dist/components/media/map/map-interaction-options.d.ts +26 -0
  178. package/dist/components/media/map/map-interaction-options.js +1 -0
  179. package/dist/components/media/map/map-layer-order.js +1 -0
  180. package/dist/components/media/map/map-loader.d.ts +35 -5
  181. package/dist/components/media/map/map-loader.js +1 -1
  182. package/dist/components/media/map/map-local-image-url.js +1 -0
  183. package/dist/components/media/map/map-local-image.js +1 -0
  184. package/dist/components/media/map/map-overlay-admission.d.ts +13 -0
  185. package/dist/components/media/map/map-overlay-admission.js +1 -0
  186. package/dist/components/media/map/map-owned-feature-input.js +1 -0
  187. package/dist/components/media/map/map-owned-features.js +1 -0
  188. package/dist/components/media/map/map-owned-resources.js +1 -0
  189. package/dist/components/media/map/map-paint-batch.js +1 -0
  190. package/dist/components/media/map/map-readers.js +1 -0
  191. package/dist/components/media/map/map-readiness.js +1 -0
  192. package/dist/components/media/map/map-resource-feature-loaders.js +1 -0
  193. package/dist/components/media/map/map-source-updates.js +1 -0
  194. package/dist/components/media/map/map-style-input.js +1 -0
  195. package/dist/components/media/map/map-style-lifecycle.js +1 -0
  196. package/dist/components/media/map/map-style-override-admission.d.ts +10 -0
  197. package/dist/components/media/map/map-style-override-admission.js +1 -0
  198. package/dist/components/media/map/map-style-overrides.js +1 -0
  199. package/dist/components/media/map/map-style-value.d.ts +3 -0
  200. package/dist/components/media/map/map-style-value.js +1 -0
  201. package/dist/components/media/map/map-vector-style.d.ts +10 -0
  202. package/dist/components/media/map/map-vector-style.js +1 -0
  203. package/dist/components/media/map/map.class.d.ts +558 -51
  204. package/dist/components/media/map/map.class.js +58 -11
  205. package/dist/components/media/map/map.styles.js +1 -1
  206. package/dist/components/media/qr-code/qr-code.class.d.ts +1 -3
  207. package/dist/components/media/qr-code/qr-code.class.js +1 -1
  208. package/dist/components/media/qr-code/qr-code.styles.js +1 -1
  209. package/dist/components/media/video/video.class.d.ts +25 -4
  210. package/dist/components/media/video/video.class.js +11 -3
  211. package/dist/components/media/video/video.styles.js +1 -1
  212. package/dist/components/media/video-playlist/video-playlist.class.d.ts +0 -1
  213. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  214. package/dist/components/overlays/chip/chip-group.class.d.ts +1 -1
  215. package/dist/components/overlays/chip/chip-group.class.js +1 -1
  216. package/dist/components/overlays/dialog/confirm.js +1 -1
  217. package/dist/components/overlays/overlay/popover.class.d.ts +1 -1
  218. package/dist/components/overlays/overlay/popover.class.js +2 -1
  219. package/dist/components/overlays/overlay/tooltip.class.js +1 -1
  220. package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.d.ts +4 -7
  221. package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +2 -2
  222. package/dist/components/retrieval/claim-evidence/claim-evidence.class.d.ts +2 -2
  223. package/dist/components/retrieval/community-card/community-card.class.d.ts +1 -4
  224. package/dist/components/retrieval/community-card/community-card.class.js +1 -1
  225. package/dist/components/retrieval/embedding-explorer/embedding-explorer-data.d.ts +12 -0
  226. package/dist/components/retrieval/embedding-explorer/embedding-explorer-data.js +1 -0
  227. package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -0
  228. package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.d.ts +26 -7
  229. package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.js +35 -4
  230. package/dist/components/retrieval/embedding-explorer/embedding-explorer.styles.js +1 -1
  231. package/dist/components/retrieval/entity-dossier/entity-dossier.class.d.ts +3 -9
  232. package/dist/components/retrieval/graph/graph-builtin-3d-engine.js +1 -0
  233. package/dist/components/retrieval/graph/graph-engine-adapter.js +1 -0
  234. package/dist/components/retrieval/graph/graph-engine-columns.js +1 -0
  235. package/dist/components/retrieval/graph/graph-model.js +1 -1
  236. package/dist/components/retrieval/graph/graph-spatial-controller.js +13 -8
  237. package/dist/components/retrieval/graph/graph-webgl-engine.js +1 -0
  238. package/dist/components/retrieval/graph/graph.class.d.ts +18 -5
  239. package/dist/components/retrieval/graph/graph.class.js +4 -4
  240. package/dist/components/retrieval/graph/graph.styles.js +1 -1
  241. package/dist/components/retrieval/grounding-summary/grounding-summary.class.d.ts +1 -1
  242. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +1 -1
  243. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +2 -2
  244. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.d.ts +6 -3
  245. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +3 -3
  246. package/dist/components/retrieval/memory-panel/memory-panel.class.d.ts +3 -10
  247. package/dist/components/retrieval/memory-panel/memory-panel.class.js +1 -1
  248. package/dist/components/retrieval/node-palette/node-palette.class.d.ts +1 -1
  249. package/dist/components/retrieval/path-strip/path-strip.class.d.ts +1 -4
  250. package/dist/components/retrieval/path-strip/path-strip.class.js +1 -1
  251. package/dist/components/retrieval/provenance-panel/provenance-panel.class.d.ts +2 -8
  252. package/dist/components/retrieval/rag-answer/rag-answer.class.d.ts +2 -2
  253. package/dist/components/retrieval/rag-answer/rag-answer.class.js +2 -3
  254. package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.d.ts +1 -11
  255. package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +1 -1
  256. package/dist/components/retrieval/retrieval-results/retrieval-results.class.d.ts +8 -12
  257. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +5 -6
  258. package/dist/components/retrieval/retrieval-search/retrieval-search.class.d.ts +1 -1
  259. package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.d.ts +4 -7
  260. package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +2 -3
  261. package/dist/components/retrieval/source-card/source-card.class.d.ts +6 -9
  262. package/dist/components/retrieval/source-card/source-card.class.js +1 -1
  263. package/dist/components/retrieval/source-picker/source-picker.class.d.ts +1 -4
  264. package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
  265. package/dist/components/utility/diff-view/diff-view.class.js +1 -1
  266. package/dist/components/utility/format/format-options.js +1 -1
  267. package/dist/components/utility/icon/icon.class.d.ts +0 -5
  268. package/dist/components/utility/icon/icon.class.js +2 -2
  269. package/dist/components/utility/icon/icon.styles.js +1 -1
  270. package/dist/components/utility/json-viewer/json-viewer.class.js +1 -1
  271. package/dist/components/utility/known-date/known-date.class.d.ts +0 -3
  272. package/dist/components/utility/known-date/known-date.class.js +1 -1
  273. package/dist/components/utility/mention-popover/mention-popover.class.d.ts +3 -2
  274. package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
  275. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  276. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
  277. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  278. package/dist/components/viewers/document-preview/document-preview.class.js +1 -1
  279. package/dist/components/viewers/document-viewer/document-viewer-kinds.d.ts +1 -1
  280. package/dist/components/viewers/document-viewer/document-viewer-kinds.js +1 -1
  281. package/dist/components/viewers/document-viewer/document-viewer.class.js +1 -1
  282. package/dist/components/viewers/document-viewer/registry.d.ts +1 -69
  283. package/dist/components/viewers/document-viewer/registry.js +1 -1
  284. package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
  285. package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
  286. package/dist/components/viewers/html-viewer/html-viewer.class.js +1 -1
  287. package/dist/components/viewers/include/include.class.js +1 -1
  288. package/dist/components/viewers/index.d.ts +1 -1
  289. package/dist/components/viewers/index.js +1 -1
  290. package/dist/components/viewers/model-viewer/model-viewer-document.js +1 -0
  291. package/dist/components/viewers/model-viewer/model-viewer-loader.js +1 -0
  292. package/dist/components/viewers/model-viewer/model-viewer-register.d.ts +1 -0
  293. package/dist/components/viewers/model-viewer/model-viewer-register.js +1 -0
  294. package/dist/components/viewers/model-viewer/model-viewer-source.d.ts +1 -0
  295. package/dist/components/viewers/model-viewer/model-viewer-source.js +1 -0
  296. package/dist/components/viewers/model-viewer/model-viewer.class.d.ts +61 -0
  297. package/dist/components/viewers/model-viewer/model-viewer.class.js +9 -0
  298. package/dist/components/viewers/model-viewer/model-viewer.d.ts +1 -0
  299. package/dist/components/viewers/model-viewer/model-viewer.js +1 -0
  300. package/dist/components/viewers/model-viewer/model-viewer.styles.js +1 -0
  301. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +2 -2
  302. package/dist/components/viewers/page-rail/page-rail.class.js +1 -1
  303. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
  304. package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +3 -3
  305. package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
  306. package/dist/components/viewers/table-viewer-shared.js +1 -1
  307. package/dist/components/viewers/xml-viewer/xml-viewer.class.js +1 -1
  308. package/dist/custom-elements-jsx.d.ts +1 -1
  309. package/dist/events.d.ts +137 -92
  310. package/dist/framework-types.d.ts +2 -2
  311. package/dist/hydration.d.ts +1 -1
  312. package/dist/internal/ansi.d.ts +3 -1
  313. package/dist/internal/ansi.js +1 -1
  314. package/dist/internal/autoloader-manifest.js +1 -1
  315. package/dist/internal/autoloader-tags.d.ts +1 -1
  316. package/dist/internal/autoloader-tags.js +1 -1
  317. package/dist/internal/av-metadata.d.ts +13 -0
  318. package/dist/internal/av-metadata.js +1 -0
  319. package/dist/internal/collection-snapshot.js +1 -1
  320. package/dist/internal/component-loaders.generated.js +1 -1
  321. package/dist/internal/data-descriptors.d.ts +30 -0
  322. package/dist/internal/default-strings/agent-tools.generated.js +1 -1
  323. package/dist/internal/default-strings/charts.generated.js +1 -1
  324. package/dist/internal/default-strings/conversation.generated.js +1 -1
  325. package/dist/internal/default-strings/media.generated.js +1 -1
  326. package/dist/internal/default-strings/shared.generated.js +1 -1
  327. package/dist/internal/default-strings/viewers.generated.js +1 -1
  328. package/dist/internal/document-renderer-registry.d.ts +75 -0
  329. package/dist/internal/document-renderer-registry.js +1 -0
  330. package/dist/internal/drop-session-controller.js +1 -1
  331. package/dist/internal/engine-3d-loader.d.ts +47 -0
  332. package/dist/internal/engine-3d-loader.js +1 -0
  333. package/dist/internal/engine-3d.d.ts +57 -0
  334. package/dist/internal/engine-3d.js +1 -0
  335. package/dist/internal/hierarchy-source-controller.js +1 -1
  336. package/dist/internal/localization-runtime.js +1 -1
  337. package/dist/internal/localization-types.d.ts +1 -1
  338. package/dist/internal/localization.js +1 -1
  339. package/dist/internal/lyra-element.d.ts +2 -2
  340. package/dist/internal/lyra-element.js +1 -1
  341. package/dist/internal/model-viewer-contract.d.ts +5 -0
  342. package/dist/internal/model-viewer-contract.js +1 -0
  343. package/dist/internal/package-metadata.js +1 -1
  344. package/dist/internal/positioner.js +1 -1
  345. package/dist/internal/rendered-state.js +1 -1
  346. package/dist/internal/root-registration-allowlist.js +1 -1
  347. package/dist/internal/scoped-definitions.generated.js +1 -1
  348. package/dist/internal/typed-columns.d.ts +39 -0
  349. package/dist/internal/typed-columns.js +1 -0
  350. package/dist/localization.js +1 -1
  351. package/dist/lyra.d.ts +1 -1
  352. package/dist/lyra.js +1 -1
  353. package/dist/ssr/all.d.ts +1 -1
  354. package/dist/ssr/all.js +1 -1
  355. package/dist/ssr.d.ts +4 -4
  356. package/dist/ssr.js +1 -1
  357. package/dist/svelte.d.ts +1 -1
  358. package/dist/testing/lyra-tag-event-map.d.ts +2 -2
  359. package/dist/testing/lyra-tag-event-map.js +1 -1
  360. package/dist/theme/theme-bootstrap.js +1 -1
  361. package/dist/theme/theme.js +1 -1
  362. package/dist/vue.d.ts +1 -1
  363. package/llms/components/lr-accordion-item.md +2 -2
  364. package/llms/components/lr-agent-eval-dashboard.md +3 -3
  365. package/llms/components/lr-agent-run.md +3 -3
  366. package/llms/components/lr-agent-trace.md +1 -1
  367. package/llms/components/lr-agent-workspace.md +1 -1
  368. package/llms/components/lr-app-rail-item.md +1 -1
  369. package/llms/components/lr-app-rail.md +5 -6
  370. package/llms/components/lr-background-runs.md +4 -4
  371. package/llms/components/lr-calendar.md +1 -1
  372. package/llms/components/lr-change-review.md +5 -5
  373. package/llms/components/lr-chart-3d.md +164 -0
  374. package/llms/components/lr-chunk-inspector.md +4 -5
  375. package/llms/components/lr-citation-badge.md +1 -1
  376. package/llms/components/lr-code-block-core.md +2 -4
  377. package/llms/components/lr-command-palette.md +3 -3
  378. package/llms/components/lr-community-card.md +2 -2
  379. package/llms/components/lr-date-picker.md +1 -1
  380. package/llms/components/lr-details.md +2 -2
  381. package/llms/components/lr-diff-view.md +2 -2
  382. package/llms/components/lr-dock-panel.md +5 -10
  383. package/llms/components/lr-document-viewer.md +21 -14
  384. package/llms/components/lr-embedding-explorer.md +24 -4
  385. package/llms/components/lr-entity-dossier.md +3 -4
  386. package/llms/components/lr-eval-dataset.md +3 -3
  387. package/llms/components/lr-eval-run.md +7 -1
  388. package/llms/components/lr-file-input.md +10 -11
  389. package/llms/components/lr-flow-node.md +2 -3
  390. package/llms/components/lr-geojson-viewer.md +1 -1
  391. package/llms/components/lr-graph.md +21 -2
  392. package/llms/components/lr-grounding-summary.md +1 -1
  393. package/llms/components/lr-icon.md +1 -3
  394. package/llms/components/lr-image-viewer.md +29 -2
  395. package/llms/components/lr-ingestion-queue.md +1 -1
  396. package/llms/components/lr-knowledge-base-admin.md +2 -2
  397. package/llms/components/lr-knowledge-graph-explorer.md +7 -1
  398. package/llms/components/lr-known-date.md +3 -10
  399. package/llms/components/lr-lite-chart.md +1 -1
  400. package/llms/components/lr-map.md +861 -49
  401. package/llms/components/lr-markdown-core.md +1 -2
  402. package/llms/components/lr-memory-panel.md +4 -8
  403. package/llms/components/lr-model-viewer.md +170 -0
  404. package/llms/components/lr-navigation-menu.md +3 -4
  405. package/llms/components/lr-node-palette.md +1 -1
  406. package/llms/components/lr-path-strip.md +2 -3
  407. package/llms/components/lr-provenance-panel.md +3 -5
  408. package/llms/components/lr-qr-code.md +3 -4
  409. package/llms/components/lr-rag-answer.md +1 -1
  410. package/llms/components/lr-rag-eval-dashboard.md +2 -5
  411. package/llms/components/lr-retrieval-results.md +6 -7
  412. package/llms/components/lr-retrieval-trace.md +3 -4
  413. package/llms/components/lr-signature-pad.md +4 -3
  414. package/llms/components/lr-source-card.md +1 -1
  415. package/llms/components/lr-source-list.md +5 -5
  416. package/llms/components/lr-source-picker.md +2 -3
  417. package/llms/components/lr-span-waterfall.md +4 -3
  418. package/llms/components/lr-sparkline.md +3 -3
  419. package/llms/components/lr-subagent-panel.md +3 -3
  420. package/llms/components/lr-tool-call-chip.md +6 -6
  421. package/llms/components/lr-tool-timeline.md +1 -1
  422. package/llms/components/lr-video-playlist.md +3 -3
  423. package/llms/components/lr-video.md +29 -2
  424. package/llms/components/lr-virtual-list.md +3 -2
  425. package/llms/components/lr-widget.md +6 -13
  426. package/llms/index.md +98 -95
  427. package/llms/migration.md +27 -38
  428. package/llms/peers.md +7 -6
  429. package/llms/shared/ai-and-peers.md +1 -1
  430. package/llms/shared/events-and-types.md +8 -0
  431. package/llms/shared/imports-and-registration.md +2 -2
  432. package/llms/shared/v29-to-v30-migration.md +256 -0
  433. package/llms/shared.md +11 -3
  434. package/llms.txt +4 -4
  435. package/locales.json +1 -2328
  436. package/package.json +41 -13
  437. package/registrations.json +1 -1
  438. package/skills/lyra-ui/SKILL.md +4 -3
  439. /package/dist/{components/viewers/document-viewer → internal}/deferred-teardown.js +0 -0
  440. /package/dist/{components/viewers/document-viewer/registry-ownership.js → internal/document-renderer-registry-ownership.js} +0 -0
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{normalizeImageZoom}from"../../../internal/image-zoom.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./image-viewer.styles.js";import{sanitizePercentRect}from"../../../internal/safe-css.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{normalizeImageFit}from"../../../internal/image-fit.js";import{IMAGE_VIEWER_HIGHLIGHT_LIMIT}from"./image-viewer-limits.js";import{LYRA_DEFAULT_imageViewerAnnotate,LYRA_DEFAULT_imageViewerAnnotationAdded,LYRA_DEFAULT_imageViewerAnnotationBoxPosition,LYRA_DEFAULT_imageViewerAnnotationCancelled,LYRA_DEFAULT_imageViewerAnnotationHint,LYRA_DEFAULT_imageViewerFailedToLoad,LYRA_DEFAULT_imageViewerFitActual,LYRA_DEFAULT_imageViewerFitContain,LYRA_DEFAULT_imageViewerFitLabel,LYRA_DEFAULT_imageViewerFitWidth,LYRA_DEFAULT_imageViewerHighlightsLabel,LYRA_DEFAULT_imageViewerLabel,LYRA_DEFAULT_imageViewerRotate,LYRA_DEFAULT_imageViewerUnlabeledHighlight}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewTypeImage}from"../../../internal/default-strings/shared.generated.js";const MIN_REGION_PERCENT=2,ARROW_STEP_PERCENT=2;import{IMAGE_VIEWER_HIGHLIGHT_LIMIT as IMAGE_VIEWER_HIGHLIGHT_LIMIT2}from"./image-viewer-limits.js";function normalizeImageRotation(value){const degrees=typeof value=="number"?finiteNumber(value,0):0;return(Math.round(degrees/90)%4+4)%4*90}function normalizeImageRegionRect(value){const rect=sanitizePercentRect(value);if(!(!rect||rect.x<0||rect.y<0||rect.width<=0||rect.height<=0||rect.x+rect.width>100||rect.y+rect.height>100))return rect}function normalizeHighlightTone(value){return value==="success"||value==="warning"||value==="danger"||value==="neutral"?value:"accent"}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}function screenPercentToImagePercent(px,py,rotation){switch(rotation){case 90:return{x:py,y:100-px};case 180:return{x:100-px,y:100-py};case 270:return{x:100-py,y:px};default:return{x:px,y:py}}}class LyraImageViewerBase extends LyraElement{}class LyraImageViewer extends DocumentAnchorTarget(LyraImageViewerBase){constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="base"][role="region"]')),this.src="",this.name="",this._fit="contain",this.zoom=1,this.minZoom=.5,this.maxZoom=4,this.zoomStep=.25,this._rotation=0,this.annotatable=!1,this.anchorKinds=["region"],this.loadState={kind:"idle"},this.draft=null,this.revealTarget=null,this.highlightFocusId=null,this.mediaLayoutSize=null,this.announcements=new AnnouncementSinkController(this,{eager:["assertive"]}),this.onImgLoad=event=>{const img=event.target;img===this.shadowRoot?.querySelector('[part="image"]')&&(this.loadState={kind:"loaded"},this.emit("lr-load",{naturalWidth:img.naturalWidth,naturalHeight:img.naturalHeight}))},this.onImgError=event=>{event.target===this.shadowRoot?.querySelector('[part="image"]')&&(this.cancelPointerDraft(),this.revealTarget=null,this.loadState={kind:"error"},this.announceLoadError(),this.emit("lr-render-error",{error:new Error("The image failed to load.")}))},this.onFrameZoomChange=event=>{this.zoom=event.detail.zoom},this.toggleAnnotatable=()=>{this.hasOperableContent&&(this.annotatable=!this.annotatable,this.emit("lr-annotatable-change",{annotatable:this.annotatable}))},this.onFitChange=event=>{this.fit=event.target.value},this.onWrapperKeyDown=event=>{if(event.target===event.currentTarget&&!(!this.annotatable||!this.hasOperableContent)){if(!this.draft){event.key==="Enter"&&(event.preventDefault(),this.draft={x:37.5,y:37.5,width:25,height:25},this.announceDraftPosition());return}switch(event.key){case"ArrowLeft":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x-ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowRight":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x+ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowUp":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y-ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"ArrowDown":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y+ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"Enter":event.preventDefault(),this.commitDraft();return;case"Escape":event.preventDefault(),this.draft=null,this.liveRegion?.announce(this.localize("imageViewerAnnotationCancelled"),{force:!0});return;default:return}this.announceDraftPosition()}},this.pointerDraftId=null,this.pointerOrigin=null,this.onWrapperPointerDown=event=>{if(!this.annotatable||!this.hasOperableContent||!this.wrapperEl||!event.isPrimary||event.button!==0||this.pointerDraftId!==null)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),origin=screenPercentToImagePercent(px,py,this.rotation);this.pointerOrigin=origin,this.pointerDraftId=event.pointerId;try{this.wrapperEl.setPointerCapture(event.pointerId)}catch{}this.draft={x:origin.x,y:origin.y,width:0,height:0},event.preventDefault()},this.onWrapperPointerMove=event=>{if(this.pointerDraftId!==event.pointerId||!this.pointerOrigin||!this.wrapperEl)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),point=screenPercentToImagePercent(px,py,this.rotation),x=Math.min(this.pointerOrigin.x,point.x),y=Math.min(this.pointerOrigin.y,point.y),width=Math.abs(point.x-this.pointerOrigin.x),height=Math.abs(point.y-this.pointerOrigin.y);this.draft={x,y,width,height}},this.onWrapperPointerUp=event=>{if(this.pointerDraftId!==event.pointerId)return;const draft=this.draft;this.cancelPointerDraft(event.pointerId),draft&&draft.width>=MIN_REGION_PERCENT&&draft.height>=MIN_REGION_PERCENT&&(this.draft=draft,this.commitDraft())}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewTypeImage:LYRA_DEFAULT_documentPreviewTypeImage,imageViewerAnnotate:LYRA_DEFAULT_imageViewerAnnotate,imageViewerAnnotationAdded:LYRA_DEFAULT_imageViewerAnnotationAdded,imageViewerAnnotationBoxPosition:LYRA_DEFAULT_imageViewerAnnotationBoxPosition,imageViewerAnnotationCancelled:LYRA_DEFAULT_imageViewerAnnotationCancelled,imageViewerAnnotationHint:LYRA_DEFAULT_imageViewerAnnotationHint,imageViewerFailedToLoad:LYRA_DEFAULT_imageViewerFailedToLoad,imageViewerFitActual:LYRA_DEFAULT_imageViewerFitActual,imageViewerFitContain:LYRA_DEFAULT_imageViewerFitContain,imageViewerFitLabel:LYRA_DEFAULT_imageViewerFitLabel,imageViewerFitWidth:LYRA_DEFAULT_imageViewerFitWidth,imageViewerHighlightsLabel:LYRA_DEFAULT_imageViewerHighlightsLabel,imageViewerLabel:LYRA_DEFAULT_imageViewerLabel,imageViewerRotate:LYRA_DEFAULT_imageViewerRotate,imageViewerUnlabeledHighlight:LYRA_DEFAULT_imageViewerUnlabeledHighlight}}static{this.styles=[LyraElement.styles,styles,srOnly]}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-annotation-create"])}get fit(){return this._fit}set fit(value){const old=this._fit;this._fit=normalizeImageFit(value),this.requestUpdate("fit",old)}get rotation(){return this._rotation}set rotation(value){const old=this._rotation;this._rotation=normalizeImageRotation(value),this.requestUpdate("rotation",old)}get hasOperableContent(){return this.loadState.kind==="loaded"}willUpdate(changed){if(super.willUpdate(changed),changed.has("src")){this.cancelPointerDraft(),this.revealTarget=null,this.mediaLayoutSize=null;const safeSrc=this.src?safeMediaSrc(this.src):null;this.loadState=safeSrc?{kind:"loading"}:this.src?{kind:"error"}:{kind:"idle"},this.hasUpdated&&this.src&&!safeSrc&&this.announceLoadError()}changed.has("annotatable")&&(!this.annotatable||!this.hasOperableContent)&&this.cancelPointerDraft()}updated(changed){super.updated(changed),changed.has("rotation")&&changed.get("rotation")!==void 0&&this.emit("lr-rotation-change",{rotation:this.rotation}),changed.has("fit")&&changed.get("fit")!==void 0&&this.emit("lr-fit-change",{fit:this.fit}),(changed.has("annotatable")||changed.has("loadState"))&&this.annotatable&&this.hasOperableContent&&(changed.has("loadState")||changed.get("annotatable")!==void 0)&&this.liveRegion?.announce(this.localize("imageViewerAnnotationHint"),{force:!0}),this.syncGeometryObserver()}zoomIn(){this.frameEl?.zoomIn()}zoomOut(){this.frameEl?.zoomOut()}resetZoom(){this.frameEl?.resetZoom()}rotate(){this.rotation=(this.rotation+90)%360}async applyAnchor(anchor){if(anchor.kind!=="region"||!this.hasOperableContent)return!1;const rect=normalizeImageRegionRect(anchor.rect);if(!rect)return!1;this.revealTarget=rect,await this.updateComplete;const target=this.shadowRoot?.querySelector("[data-reveal-target]"),viewport=this.frameEl?.shadowRoot?.querySelector('[part="viewport"]');if(!target||!viewport||target.getClientRects().length===0)return!1;target.scrollIntoView({block:"center",inline:"center"}),await new Promise(resolve=>{const view=this.ownerDocument.defaultView;view?view.requestAnimationFrame(()=>resolve()):resolve()});const targetRect=target.getBoundingClientRect(),viewportRect=viewport.getBoundingClientRect();return targetRect.right>viewportRect.left&&targetRect.left<viewportRect.right&&targetRect.bottom>viewportRect.top&&targetRect.top<viewportRect.bottom}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncGeometryObserver()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.disconnectGeometryObserver(),this.announcements.adopted(),this.scheduleAfterUpdate(()=>this.syncGeometryObserver())}disconnectGeometryObserver(){this.geometryObserver?.disconnect(),this.geometryObserver=void 0,this.observedWrapper=void 0,this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrame=void 0,this.geometryFrameOwner=void 0}updateMediaLayoutSize(width,height){!Number.isFinite(width)||!Number.isFinite(height)||width<=0||height<=0||this.mediaLayoutSize?.width===width&&this.mediaLayoutSize.height===height||(this.mediaLayoutSize={width,height})}scheduleMediaLayoutSize(width,height){if(!this.isConnected)return;const view=this.ownerDocument.defaultView;if(!view){this.updateMediaLayoutSize(width,height);return}this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrameOwner=view;const frame=view.requestAnimationFrame(()=>{!this.isConnected||this.ownerDocument.defaultView!==view||this.geometryFrameOwner!==view||this.geometryFrame!==frame||(this.geometryFrame=void 0,this.geometryFrameOwner=void 0,this.updateMediaLayoutSize(Math.round(width*100)/100,Math.round(height*100)/100))});this.geometryFrame=frame}syncGeometryObserver(){if(!this.isConnected)return;const wrapper=this.wrapperEl;if(wrapper===this.observedWrapper||(this.disconnectGeometryObserver(),!wrapper))return;this.observedWrapper=wrapper,this.scheduleMediaLayoutSize(wrapper.offsetWidth,wrapper.offsetHeight);const owner=this.ownerDocument.defaultView,ResizeObserverConstructor=owner?.ResizeObserver;if(!ResizeObserverConstructor)return;const observer=new ResizeObserverConstructor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==owner||this.geometryObserver!==observer)return;const entry=entries.find(candidate=>candidate.target===this.observedWrapper);entry&&this.scheduleMediaLayoutSize(entry.contentRect.width,entry.contentRect.height)});this.geometryObserver=observer,observer.observe(wrapper)}announceLoadError(){this.announcements.announceAssertive(this.localize("imageViewerFailedToLoad"))}onHighlightActivate(id){this.activeHighlightId=id,this.emit("lr-highlight-activate",{highlightId:id})}announceDraftPosition(){if(!this.draft)return;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1});this.liveRegion?.announce(this.localize("imageViewerAnnotationBoxPosition",void 0,{x:formatter.format(Math.round(this.draft.x)),y:formatter.format(Math.round(this.draft.y)),width:formatter.format(Math.round(this.draft.width)),height:formatter.format(Math.round(this.draft.height))}))}commitDraft(){if(!this.draft)return;const rect={x:this.draft.x,y:this.draft.y,width:this.draft.width,height:this.draft.height};this.draft=null,this.emit("lr-annotation-create",{anchor:{kind:"region",rect}}),this.liveRegion?.announce(this.localize("imageViewerAnnotationAdded"),{force:!0})}cancelPointerDraft(pointerId=this.pointerDraftId,releaseCapture=!0){if(pointerId!=null&&this.pointerDraftId!==pointerId)return;const wrapper=this.wrapperEl,capturedPointerId=this.pointerDraftId;if(this.pointerDraftId=null,this.pointerOrigin=null,this.draft=null,releaseCapture&&wrapper&&capturedPointerId!=null)try{wrapper.releasePointerCapture(capturedPointerId)}catch{}}canonicalRegionHighlights(){const source=this.highlights;if(this.regionHighlights?.[0]===source)return this.regionHighlights[1];const ids=new Set,result=[];for(const highlight of this.highlights){if(!highlight||typeof highlight.id!="string"||highlight.id.trim().length===0||ids.has(highlight.id)||highlight.anchor.kind!=="region")continue;const rect=normalizeImageRegionRect(highlight.anchor.rect);rect&&(ids.add(highlight.id),result.push({highlight,rect}))}return this.regionHighlights=[source,result],result}boundedRegionHighlights(){const all=this.canonicalRegionHighlights();if(all.length<=IMAGE_VIEWER_HIGHLIGHT_LIMIT)return{all,visible:all};const visible=all.slice(0,IMAGE_VIEWER_HIGHLIGHT_LIMIT),active=this.activeHighlightId?all.find(entry=>entry.highlight.id===this.activeHighlightId):void 0;return active&&!visible.includes(active)&&(visible[visible.length-1]=active),{all,visible}}onHighlightFocus(id){this.highlightFocusId=id}onHighlightKeyDown(event,id){const buttons=[...this.shadowRoot.querySelectorAll('[part="highlight"]')];if(buttons.length<2)return;const current=buttons.findIndex(button=>button.dataset.highlightId===id),rtl=this.effectiveDirection==="rtl";let next=current;if(event.key==="Home")next=0;else if(event.key==="End")next=buttons.length-1;else if(event.key==="ArrowDown"||event.key===(rtl?"ArrowLeft":"ArrowRight"))next=(current+1)%buttons.length;else if(event.key==="ArrowUp"||event.key===(rtl?"ArrowRight":"ArrowLeft"))next=(current-1+buttons.length)%buttons.length;else return;event.preventDefault();const target=buttons[next];this.highlightFocusId=target.dataset.highlightId??null,target.focus()}renderHighlights(){if(!this.hasOperableContent)return nothing;const{all:regionHighlights,visible}=this.boundedRegionHighlights();if(!regionHighlights.length)return nothing;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1}),preferredFocusId=visible.some(({highlight})=>highlight.id===this.highlightFocusId)?this.highlightFocusId:visible.some(({highlight})=>highlight.id===this.activeHighlightId)?this.activeHighlightId:visible[0]?.highlight.id??null,zoom=normalizeImageZoom(this.zoom,this.minZoom,this.maxZoom),layout=this.mediaLayoutSize;return html`<div
1
+ import{__decorate}from"tslib";import{panoramaStyles}from"./image-viewer-panorama.styles.js";import{ENGINE_3D_PREFERENCE}from"../../../internal/engine-3d.js";import{PanoramaController,PANORAMA_PROJECTION,PANORAMA_DEFAULT_CAMERA,normalizePanoramaCamera,snapshotPanoramaHotspots}from"./image-viewer-panorama.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{normalizeImageZoom}from"../../../internal/image-zoom.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./image-viewer.styles.js";import{sanitizePercentRect}from"../../../internal/safe-css.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{normalizeImageFit}from"../../../internal/image-fit.js";import{IMAGE_VIEWER_HIGHLIGHT_LIMIT}from"./image-viewer-limits.js";import{LYRA_DEFAULT_imageViewerAnnotate,LYRA_DEFAULT_imageViewerAnnotationAdded,LYRA_DEFAULT_imageViewerAnnotationBoxPosition,LYRA_DEFAULT_imageViewerAnnotationCancelled,LYRA_DEFAULT_imageViewerAnnotationHint,LYRA_DEFAULT_imageViewerFailedToLoad,LYRA_DEFAULT_imageViewerFitActual,LYRA_DEFAULT_imageViewerFitContain,LYRA_DEFAULT_imageViewerFitLabel,LYRA_DEFAULT_imageViewerFitWidth,LYRA_DEFAULT_imageViewerHighlightsLabel,LYRA_DEFAULT_imageViewerLabel,LYRA_DEFAULT_imageViewerRotate,LYRA_DEFAULT_imageViewerUnlabeledHighlight,LYRA_DEFAULT_panoramaHotspotsLabel,LYRA_DEFAULT_panoramaInstructions}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewTypeImage,LYRA_DEFAULT_engine3dContextLost,LYRA_DEFAULT_engine3dError,LYRA_DEFAULT_engine3dLoading,LYRA_DEFAULT_engine3dShowingBuiltin,LYRA_DEFAULT_engine3dShowingList,LYRA_DEFAULT_engine3dSoftwareRendering,LYRA_DEFAULT_engine3dUnavailable,LYRA_DEFAULT_engine3dUnsupported,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_model,LYRA_DEFAULT_navigation,LYRA_DEFAULT_next,LYRA_DEFAULT_open,LYRA_DEFAULT_paginationLabel,LYRA_DEFAULT_previous,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";const MIN_REGION_PERCENT=2,ARROW_STEP_PERCENT=2;import{IMAGE_VIEWER_HIGHLIGHT_LIMIT as IMAGE_VIEWER_HIGHLIGHT_LIMIT2}from"./image-viewer-limits.js";function normalizeImageRotation(value){const degrees=typeof value=="number"?finiteNumber(value,0):0;return(Math.round(degrees/90)%4+4)%4*90}function normalizeImageRegionRect(value){const rect=sanitizePercentRect(value);if(!(!rect||rect.x<0||rect.y<0||rect.width<=0||rect.height<=0||rect.x+rect.width>100||rect.y+rect.height>100))return rect}function normalizeHighlightTone(value){return value==="success"||value==="warning"||value==="danger"||value==="neutral"?value:"accent"}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}function screenPercentToImagePercent(px,py,rotation){switch(rotation){case 90:return{x:py,y:100-px};case 180:return{x:100-px,y:100-py};case 270:return{x:100-py,y:px};default:return{x:px,y:py}}}class LyraImageViewerBase extends LyraElement{}class LyraImageViewer extends DocumentAnchorTarget(LyraImageViewerBase){constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="base"][role="region"]')),this.panoramaRevision=0,this.panorama=new PanoramaController(this,{changed:()=>this.scheduleAfterUpdate(()=>super.requestUpdate("panoramaState",void 0,{hasChanged:()=>!0}),"panorama-state"),updated:async()=>(await Promise.resolve(),this.updateComplete),localize:key=>this.localize(key),direction:()=>this.effectiveDirection,fallback:detail=>this.emit("lr-engine-fallback",detail),pick:detail=>this.emit("lr-panorama-hotspot-select",detail),camera:camera=>{const old=this._panoramaCamera;this._panoramaCamera=camera,this.requestUpdate("panoramaCamera",old),this.emit("lr-panorama-camera-change",{camera})}}),this._projection="flat",this._engine="builtin",this._panoramaCamera=PANORAMA_DEFAULT_CAMERA,this._hotspots=Object.freeze([]),this.hotspotSource=this._hotspots,this.src="",this.name="",this._fit="contain",this.zoom=1,this.minZoom=.5,this.maxZoom=4,this.zoomStep=.25,this._rotation=0,this.annotatable=!1,this.anchorKinds=["region"],this.loadState={kind:"idle"},this.draft=null,this.revealTarget=null,this.highlightFocusId=null,this.mediaLayoutSize=null,this.announcements=new AnnouncementSinkController(this,{eager:["assertive"]}),this.declarativeAnchorUpdate=!1,this.onImgLoad=event=>{const img=event.target;img===this.shadowRoot?.querySelector('[part="image"]')&&(this.loadState={kind:"loaded"},this.emit("lr-load",{naturalWidth:img.naturalWidth,naturalHeight:img.naturalHeight}))},this.onImgError=event=>{event.target===this.shadowRoot?.querySelector('[part="image"]')&&(this.panorama.invalidate(),this.cancelPointerDraft(),this.revealTarget=null,this.loadState={kind:"error"},this.announceLoadError(),this.emit("lr-render-error",{error:new Error("The image failed to load.")}))},this.onFrameZoomChange=event=>{this.zoom=event.detail.zoom},this.toggleAnnotatable=()=>{this.hasOperableContent&&(this.annotatable=!this.annotatable,this.emit("lr-annotatable-change",{annotatable:this.annotatable}))},this.onFitChange=event=>{this.fit=event.target.value},this.onWrapperKeyDown=event=>{if(event.target===event.currentTarget&&!(!this.annotatable||!this.hasOperableContent)){if(!this.draft){event.key==="Enter"&&(event.preventDefault(),this.draft={x:37.5,y:37.5,width:25,height:25},this.announceDraftPosition());return}switch(event.key){case"ArrowLeft":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x-ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowRight":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x+ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowUp":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y-ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"ArrowDown":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y+ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"Enter":event.preventDefault(),this.commitDraft();return;case"Escape":event.preventDefault(),this.draft=null,this.liveRegion?.announce(this.localize("imageViewerAnnotationCancelled"),{force:!0});return;default:return}this.announceDraftPosition()}},this.pointerDraftId=null,this.pointerOrigin=null,this.onWrapperPointerDown=event=>{if(!this.annotatable||!this.hasOperableContent||!this.wrapperEl||!event.isPrimary||event.button!==0||this.pointerDraftId!==null)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),origin=screenPercentToImagePercent(px,py,this.rotation);this.pointerOrigin=origin,this.pointerDraftId=event.pointerId;try{this.wrapperEl.setPointerCapture(event.pointerId)}catch{}this.draft={x:origin.x,y:origin.y,width:0,height:0},event.preventDefault()},this.onWrapperPointerMove=event=>{if(this.pointerDraftId!==event.pointerId||!this.pointerOrigin||!this.wrapperEl)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),point=screenPercentToImagePercent(px,py,this.rotation),x=Math.min(this.pointerOrigin.x,point.x),y=Math.min(this.pointerOrigin.y,point.y),width=Math.abs(point.x-this.pointerOrigin.x),height=Math.abs(point.y-this.pointerOrigin.y);this.draft={x,y,width,height}},this.onWrapperPointerUp=event=>{if(this.pointerDraftId!==event.pointerId)return;const draft=this.draft;this.cancelPointerDraft(event.pointerId),draft&&draft.width>=MIN_REGION_PERCENT&&draft.height>=MIN_REGION_PERCENT&&(this.draft=draft,this.commitDraft())}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewTypeImage:LYRA_DEFAULT_documentPreviewTypeImage,engine3dContextLost:LYRA_DEFAULT_engine3dContextLost,engine3dError:LYRA_DEFAULT_engine3dError,engine3dLoading:LYRA_DEFAULT_engine3dLoading,engine3dShowingBuiltin:LYRA_DEFAULT_engine3dShowingBuiltin,engine3dShowingList:LYRA_DEFAULT_engine3dShowingList,engine3dSoftwareRendering:LYRA_DEFAULT_engine3dSoftwareRendering,engine3dUnavailable:LYRA_DEFAULT_engine3dUnavailable,engine3dUnsupported:LYRA_DEFAULT_engine3dUnsupported,imageViewerAnnotate:LYRA_DEFAULT_imageViewerAnnotate,imageViewerAnnotationAdded:LYRA_DEFAULT_imageViewerAnnotationAdded,imageViewerAnnotationBoxPosition:LYRA_DEFAULT_imageViewerAnnotationBoxPosition,imageViewerAnnotationCancelled:LYRA_DEFAULT_imageViewerAnnotationCancelled,imageViewerAnnotationHint:LYRA_DEFAULT_imageViewerAnnotationHint,imageViewerFailedToLoad:LYRA_DEFAULT_imageViewerFailedToLoad,imageViewerFitActual:LYRA_DEFAULT_imageViewerFitActual,imageViewerFitContain:LYRA_DEFAULT_imageViewerFitContain,imageViewerFitLabel:LYRA_DEFAULT_imageViewerFitLabel,imageViewerFitWidth:LYRA_DEFAULT_imageViewerFitWidth,imageViewerHighlightsLabel:LYRA_DEFAULT_imageViewerHighlightsLabel,imageViewerLabel:LYRA_DEFAULT_imageViewerLabel,imageViewerRotate:LYRA_DEFAULT_imageViewerRotate,imageViewerUnlabeledHighlight:LYRA_DEFAULT_imageViewerUnlabeledHighlight,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,model:LYRA_DEFAULT_model,navigation:LYRA_DEFAULT_navigation,next:LYRA_DEFAULT_next,open:LYRA_DEFAULT_open,paginationLabel:LYRA_DEFAULT_paginationLabel,panoramaHotspotsLabel:LYRA_DEFAULT_panoramaHotspotsLabel,panoramaInstructions:LYRA_DEFAULT_panoramaInstructions,previous:LYRA_DEFAULT_previous,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,panoramaStyles,styles,srOnly]}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-annotation-create"])}get projection(){return this._projection}set projection(value){const next=PANORAMA_PROJECTION.normalize(value),old=this._projection;next!==old&&(this._projection=next,this.panorama?.invalidate(),this.requestUpdate("projection",old))}get engine(){return this._engine}set engine(value){const next=ENGINE_3D_PREFERENCE.normalize(value),old=this._engine;next!==old&&(this._engine=next,this.panorama?.invalidate(),this.requestUpdate("engine",old))}get panoramaCamera(){return this._panoramaCamera}set panoramaCamera(value){const next=normalizePanoramaCamera(value),old=this._panoramaCamera;next.yaw===old.yaw&&next.pitch===old.pitch&&next.fieldOfView===old.fieldOfView||(this._panoramaCamera=next,this.requestUpdate("panoramaCamera",old))}get hotspots(){return this._hotspots}set hotspots(value){if(value===this.hotspotSource||value===this._hotspots)return;const old=this._hotspots;this.hotspotSource=value,this._hotspots=snapshotPanoramaHotspots(value,this.ownerDocument?.defaultView??null),this.panorama?.invalidate(),this.requestUpdate("hotspots",old)}get panoramaEnabled(){return this.projection==="equirectangular"&&this.engine==="webgl"}requestUpdate(name,oldValue,options){name==="src"&&this.panorama&&!Object.is(this.src,oldValue)&&(this.panoramaRevision++,this.panorama.invalidate()),super.requestUpdate(name,oldValue,options)}get fit(){return this._fit}set fit(value){const old=this._fit;this._fit=normalizeImageFit(value),this.requestUpdate("fit",old)}get rotation(){return this._rotation}set rotation(value){const old=this._rotation;this._rotation=normalizeImageRotation(value),this.requestUpdate("rotation",old)}get hasOperableContent(){return this.loadState.kind==="loaded"}willUpdate(changed){this.declarativeAnchorUpdate=!0;try{super.willUpdate(changed)}finally{this.declarativeAnchorUpdate=!1}if(changed.has("src")){this.cancelPointerDraft(),this.revealTarget=null,this.mediaLayoutSize=null;const safeSrc=this.src?safeMediaSrc(this.src):null;this.loadState=safeSrc?{kind:"loading"}:this.src?{kind:"error"}:{kind:"idle"},this.hasUpdated&&this.src&&!safeSrc&&this.announceLoadError()}changed.has("annotatable")&&(!this.annotatable||!this.hasOperableContent)&&this.cancelPointerDraft()}updated(changed){super.updated(changed),changed.has("rotation")&&changed.get("rotation")!==void 0&&this.emit("lr-rotation-change",{rotation:this.rotation}),changed.has("fit")&&changed.get("fit")!==void 0&&this.emit("lr-fit-change",{fit:this.fit}),(changed.has("annotatable")||changed.has("loadState"))&&this.annotatable&&this.hasOperableContent&&(changed.has("loadState")||changed.get("annotatable")!==void 0)&&this.liveRegion?.announce(this.localize("imageViewerAnnotationHint"),{force:!0}),this.syncGeometryObserver();const image=this.renderRoot.querySelector('[part="image"]');this.panorama.update(this.panoramaEnabled,this.hasOperableContent?image:null,this.panoramaRevision,this.hotspots,this.panoramaCamera,this.renderRoot.querySelector('[part="panorama-engine"]'))}zoomIn(){this.frameEl?.zoomIn()}zoomOut(){this.frameEl?.zoomOut()}resetZoom(){this.frameEl?.resetZoom()}rotate(){this.rotation=(this.rotation+90)%360}scrollToAnchor(target){const anchor=typeof target=="string"?this.highlights.find(highlight=>highlight.id===target)?.anchor:target;return!this.declarativeAnchorUpdate&&anchor?.kind==="region"&&(this.projection="flat"),super.scrollToAnchor(target)}async applyAnchor(anchor){if(anchor.kind!=="region"||!this.hasOperableContent)return!1;const rect=normalizeImageRegionRect(anchor.rect);if(!rect)return!1;this.revealTarget=rect,await this.updateComplete;const target=this.shadowRoot?.querySelector("[data-reveal-target]"),viewport=this.frameEl?.shadowRoot?.querySelector('[part="viewport"]');if(!target||!viewport||target.getClientRects().length===0)return!1;target.scrollIntoView({block:"center",inline:"center"}),await new Promise(resolve=>{const view=this.ownerDocument.defaultView;view?view.requestAnimationFrame(()=>resolve()):resolve()});const targetRect=target.getBoundingClientRect(),viewportRect=viewport.getBoundingClientRect();return targetRect.right>viewportRect.left&&targetRect.left<viewportRect.right&&targetRect.bottom>viewportRect.top&&targetRect.top<viewportRect.bottom}connectedCallback(){super.connectedCallback(),super.requestUpdate("panoramaReconnect",void 0,{hasChanged:()=>!0}),this.hasUpdated&&this.syncGeometryObserver()}adoptedCallback(){super.adoptedCallback(),this.panorama.adopted(),super.requestUpdate("panoramaAdopted",void 0,{hasChanged:()=>!0}),this.hostDescription.adopted(),this.disconnectGeometryObserver(),this.announcements.adopted(),this.scheduleAfterUpdate(()=>this.syncGeometryObserver())}disconnectGeometryObserver(){this.geometryObserver?.disconnect(),this.geometryObserver=void 0,this.observedWrapper=void 0,this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrame=void 0,this.geometryFrameOwner=void 0}updateMediaLayoutSize(width,height){!Number.isFinite(width)||!Number.isFinite(height)||width<=0||height<=0||this.mediaLayoutSize?.width===width&&this.mediaLayoutSize.height===height||(this.mediaLayoutSize={width,height})}scheduleMediaLayoutSize(width,height){if(!this.isConnected)return;const view=this.ownerDocument.defaultView;if(!view){this.updateMediaLayoutSize(width,height);return}this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrameOwner=view;const frame=view.requestAnimationFrame(()=>{!this.isConnected||this.ownerDocument.defaultView!==view||this.geometryFrameOwner!==view||this.geometryFrame!==frame||(this.geometryFrame=void 0,this.geometryFrameOwner=void 0,this.updateMediaLayoutSize(Math.round(width*100)/100,Math.round(height*100)/100))});this.geometryFrame=frame}syncGeometryObserver(){if(!this.isConnected)return;const wrapper=this.wrapperEl;if(wrapper===this.observedWrapper||(this.disconnectGeometryObserver(),!wrapper))return;this.observedWrapper=wrapper,this.scheduleMediaLayoutSize(wrapper.offsetWidth,wrapper.offsetHeight);const owner=this.ownerDocument.defaultView,ResizeObserverConstructor=owner?.ResizeObserver;if(!ResizeObserverConstructor)return;const observer=new ResizeObserverConstructor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==owner||this.geometryObserver!==observer)return;const entry=entries.find(candidate=>candidate.target===this.observedWrapper);entry&&this.scheduleMediaLayoutSize(entry.contentRect.width,entry.contentRect.height)});this.geometryObserver=observer,observer.observe(wrapper)}announceLoadError(){this.announcements.announceAssertive(this.localize("imageViewerFailedToLoad"))}onHighlightActivate(id){this.activeHighlightId=id,this.emit("lr-highlight-activate",{highlightId:id})}announceDraftPosition(){if(!this.draft)return;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1});this.liveRegion?.announce(this.localize("imageViewerAnnotationBoxPosition",void 0,{x:formatter.format(Math.round(this.draft.x)),y:formatter.format(Math.round(this.draft.y)),width:formatter.format(Math.round(this.draft.width)),height:formatter.format(Math.round(this.draft.height))}))}commitDraft(){if(!this.draft)return;const rect={x:this.draft.x,y:this.draft.y,width:this.draft.width,height:this.draft.height};this.draft=null,this.emit("lr-annotation-create",{anchor:{kind:"region",rect}}),this.liveRegion?.announce(this.localize("imageViewerAnnotationAdded"),{force:!0})}cancelPointerDraft(pointerId=this.pointerDraftId,releaseCapture=!0){if(pointerId!=null&&this.pointerDraftId!==pointerId)return;const wrapper=this.wrapperEl,capturedPointerId=this.pointerDraftId;if(this.pointerDraftId=null,this.pointerOrigin=null,this.draft=null,releaseCapture&&wrapper&&capturedPointerId!=null)try{wrapper.releasePointerCapture(capturedPointerId)}catch{}}canonicalRegionHighlights(){const source=this.highlights;if(this.regionHighlights?.[0]===source)return this.regionHighlights[1];const ids=new Set,result=[];for(const highlight of this.highlights){if(!highlight||typeof highlight.id!="string"||highlight.id.trim().length===0||ids.has(highlight.id)||highlight.anchor.kind!=="region")continue;const rect=normalizeImageRegionRect(highlight.anchor.rect);rect&&(ids.add(highlight.id),result.push({highlight,rect}))}return this.regionHighlights=[source,result],result}boundedRegionHighlights(){const all=this.canonicalRegionHighlights();if(all.length<=IMAGE_VIEWER_HIGHLIGHT_LIMIT)return{all,visible:all};const visible=all.slice(0,IMAGE_VIEWER_HIGHLIGHT_LIMIT),active=this.activeHighlightId?all.find(entry=>entry.highlight.id===this.activeHighlightId):void 0;return active&&!visible.includes(active)&&(visible[visible.length-1]=active),{all,visible}}onHighlightFocus(id){this.highlightFocusId=id}onHighlightKeyDown(event,id){const buttons=[...this.shadowRoot.querySelectorAll('[part="highlight"]')];if(buttons.length<2)return;const current=buttons.findIndex(button=>button.dataset.highlightId===id),rtl=this.effectiveDirection==="rtl";let next=current;if(event.key==="Home")next=0;else if(event.key==="End")next=buttons.length-1;else if(event.key==="ArrowDown"||event.key===(rtl?"ArrowLeft":"ArrowRight"))next=(current+1)%buttons.length;else if(event.key==="ArrowUp"||event.key===(rtl?"ArrowRight":"ArrowLeft"))next=(current-1+buttons.length)%buttons.length;else return;event.preventDefault();const target=buttons[next];this.highlightFocusId=target.dataset.highlightId??null,target.focus()}renderHighlights(){if(!this.hasOperableContent)return nothing;const{all:regionHighlights,visible}=this.boundedRegionHighlights();if(!regionHighlights.length)return nothing;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1}),preferredFocusId=visible.some(({highlight})=>highlight.id===this.highlightFocusId)?this.highlightFocusId:visible.some(({highlight})=>highlight.id===this.activeHighlightId)?this.activeHighlightId:visible[0]?.highlight.id??null,zoom=normalizeImageZoom(this.zoom,this.minZoom,this.maxZoom),layout=this.mediaLayoutSize;return html`<div
2
2
  part="highlight-layer"
3
3
  role="group"
4
4
  aria-label=${this.localize("imageViewerHighlightsLabel")}
@@ -27,8 +27,9 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
27
27
  data-reveal-target
28
28
  aria-hidden="true"
29
29
  style=${styleMap({left:`${rect.x}%`,top:`${rect.y}%`,width:`${rect.width}%`,height:`${rect.height}%`})}
30
- ></span>`:nothing}renderBody(){if(this.loadState.kind==="error")return html`<div part="error">${this.localize("imageViewerFailedToLoad")}</div>`;if(this.loadState.kind==="idle")return html`<p class="empty-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeImage")})}</p>`;const safeSrc=safeMediaSrc(this.src),swapped=this.rotation===90||this.rotation===270,layout=this.mediaLayoutSize,rotationFrameStyle=layout?styleMap({width:`${swapped?layout.height:layout.width}px`,height:`${swapped?layout.width:layout.height}px`}):nothing,effectiveAnnotatable=this.annotatable&&this.hasOperableContent;return html`<lr-pan-zoom
30
+ ></span>`:nothing}renderBody(){if(this.loadState.kind==="error")return html`<div part="error">${this.localize("imageViewerFailedToLoad")}</div>`;if(this.loadState.kind==="idle")return html`<p class="empty-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeImage")})}</p>`;const safeSrc=safeMediaSrc(this.src),swapped=this.rotation===90||this.rotation===270,layout=this.mediaLayoutSize,rotationFrameStyle=layout?styleMap({width:`${swapped?layout.height:layout.width}px`,height:`${swapped?layout.width:layout.height}px`}):nothing,effectiveAnnotatable=this.annotatable&&this.hasOperableContent&&!this.panorama.ready;return html`<lr-pan-zoom
31
31
  part="frame"
32
+ ?hidden=${this.panorama.ready}
32
33
  exportparts="viewport:frame-viewport,content:frame-content,controls:frame-controls"
33
34
  .zoom=${this.zoom}
34
35
  .minZoom=${this.minZoom}
@@ -65,7 +66,8 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
65
66
  </div>
66
67
  </div>
67
68
  </lr-pan-zoom>`}render(){const label=hostAriaLabel(this)??(this.name?.trim()?this.name:this.localize("imageViewerLabel")),operable=this.hasOperableContent;return html`<div part="base" role="region" aria-label=${label}>
68
- <div part="toolbar">
69
+ ${this.panorama.renderNotice()}
70
+ <div part="toolbar" ?hidden=${this.panorama.ready}>
69
71
  <span class="fit-control-wrapper">
70
72
  <select part="fit-control" aria-label=${this.localize("imageViewerFitLabel")} ?disabled=${!operable} @change=${this.onFitChange}>
71
73
  <option value="contain" ?selected=${this.fit==="contain"}>${this.localize("imageViewerFitContain")}</option>
@@ -77,7 +79,8 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
77
79
  <button part="rotate-button" type="button" ?disabled=${!operable} aria-label=${this.localize("imageViewerRotate")} @click=${()=>this.rotate()}>&#8635;</button>
78
80
  <button part="annotate-toggle" type="button" ?disabled=${!operable} aria-pressed=${this.annotatable&&operable?"true":"false"} aria-label=${this.localize("imageViewerAnnotate")} @click=${this.toggleAnnotatable}>&#9633;</button>
79
81
  </div>
80
- ${this.renderBody()}
82
+ <div class="panorama-stack" ?data-panorama=${this.panoramaEnabled}>${this.panorama.renderViewport(label,this.panoramaEnabled)}${this.renderBody()}</div>
83
+ ${this.panorama.renderHotspots(this.projection==="equirectangular")}
81
84
  <lr-live-region></lr-live-region>
82
85
  ${this.renderAnchorLiveRegion()}
83
- </div>`}disconnectedCallback(){this.cancelPointerDraft(),this.disconnectGeometryObserver(),super.disconnectedCallback()}}__decorate([property()],LyraImageViewer.prototype,"src",void 0),__decorate([property()],LyraImageViewer.prototype,"name",void 0),__decorate([property()],LyraImageViewer.prototype,"alt",void 0),__decorate([property({reflect:!0})],LyraImageViewer.prototype,"fit",null),__decorate([property({type:Number,reflect:!0})],LyraImageViewer.prototype,"zoom",void 0),__decorate([property({type:Number,attribute:"min-zoom"})],LyraImageViewer.prototype,"minZoom",void 0),__decorate([property({type:Number,attribute:"max-zoom"})],LyraImageViewer.prototype,"maxZoom",void 0),__decorate([property({type:Number,attribute:"zoom-step"})],LyraImageViewer.prototype,"zoomStep",void 0),__decorate([property({type:Number,reflect:!0})],LyraImageViewer.prototype,"rotation",null),__decorate([property({type:Boolean,reflect:!0})],LyraImageViewer.prototype,"annotatable",void 0),__decorate([state()],LyraImageViewer.prototype,"loadState",void 0),__decorate([state()],LyraImageViewer.prototype,"draft",void 0),__decorate([state()],LyraImageViewer.prototype,"revealTarget",void 0),__decorate([state()],LyraImageViewer.prototype,"highlightFocusId",void 0),__decorate([state()],LyraImageViewer.prototype,"mediaLayoutSize",void 0),__decorate([query("lr-pan-zoom")],LyraImageViewer.prototype,"frameEl",void 0),__decorate([query("lr-live-region")],LyraImageViewer.prototype,"liveRegion",void 0),__decorate([query('[part="image-wrapper"]')],LyraImageViewer.prototype,"wrapperEl",void 0);export{IMAGE_VIEWER_HIGHLIGHT_LIMIT2 as IMAGE_VIEWER_HIGHLIGHT_LIMIT,LyraImageViewer};
86
+ </div>`}disconnectedCallback(){this.panorama.disconnect(),this.cancelPointerDraft(),this.disconnectGeometryObserver(),super.disconnectedCallback()}}__decorate([property({converter:PANORAMA_PROJECTION,noAccessor:!0})],LyraImageViewer.prototype,"projection",null),__decorate([property({converter:ENGINE_3D_PREFERENCE,noAccessor:!0})],LyraImageViewer.prototype,"engine",null),__decorate([property({attribute:!1,noAccessor:!0})],LyraImageViewer.prototype,"panoramaCamera",null),__decorate([property({attribute:!1,noAccessor:!0})],LyraImageViewer.prototype,"hotspots",null),__decorate([property()],LyraImageViewer.prototype,"src",void 0),__decorate([property()],LyraImageViewer.prototype,"name",void 0),__decorate([property()],LyraImageViewer.prototype,"alt",void 0),__decorate([property({reflect:!0})],LyraImageViewer.prototype,"fit",null),__decorate([property({type:Number,reflect:!0})],LyraImageViewer.prototype,"zoom",void 0),__decorate([property({type:Number,attribute:"min-zoom"})],LyraImageViewer.prototype,"minZoom",void 0),__decorate([property({type:Number,attribute:"max-zoom"})],LyraImageViewer.prototype,"maxZoom",void 0),__decorate([property({type:Number,attribute:"zoom-step"})],LyraImageViewer.prototype,"zoomStep",void 0),__decorate([property({type:Number,reflect:!0})],LyraImageViewer.prototype,"rotation",null),__decorate([property({type:Boolean,reflect:!0})],LyraImageViewer.prototype,"annotatable",void 0),__decorate([state()],LyraImageViewer.prototype,"loadState",void 0),__decorate([state()],LyraImageViewer.prototype,"draft",void 0),__decorate([state()],LyraImageViewer.prototype,"revealTarget",void 0),__decorate([state()],LyraImageViewer.prototype,"highlightFocusId",void 0),__decorate([state()],LyraImageViewer.prototype,"mediaLayoutSize",void 0),__decorate([query("lr-pan-zoom")],LyraImageViewer.prototype,"frameEl",void 0),__decorate([query("lr-live-region")],LyraImageViewer.prototype,"liveRegion",void 0),__decorate([query('[part="image-wrapper"]')],LyraImageViewer.prototype,"wrapperEl",void 0);export{IMAGE_VIEWER_HIGHLIGHT_LIMIT2 as IMAGE_VIEWER_HIGHLIGHT_LIMIT,LyraImageViewer};
@@ -1 +1 @@
1
- import{iconHitTarget}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; min-inline-size: 0; } [part="base"] { display: flex; flex-direction: column; gap: var(--lr-space-s); min-inline-size: 0; max-inline-size: 100%; block-size: 100%; } [part="frame"] { flex: 1 1 auto; min-block-size: 0; } [part="frame"]::part(base) { block-size: 100%; grid-template-rows: minmax(0, 1fr) auto; } :host([fit="contain"]) [part="frame"]::part(viewport) { container-type: size; } :host([fit="width"]) [part="frame"]::part(viewport) { container-type: inline-size; contain-intrinsic-inline-size: var(--lr-size-20rem); } [part="toolbar"] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); } .fit-control-wrapper { position: relative; display: inline-flex; align-items: center; min-inline-size: 0; max-inline-size: 100%; } [part="fit-control"], [part="rotate-button"], [part="annotate-toggle"] { ${iconHitTarget} border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius); background: var(--lr-color-surface); color: var(--lr-color-text); font: inherit; cursor: pointer; } [part="fit-control"]:disabled, [part="rotate-button"]:disabled, [part="annotate-toggle"]:disabled { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part="fit-control"] { appearance: none; max-inline-size: 100%; padding-inline: var(--lr-space-s) var(--lr-space-l); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part="fit-control"] option { background: var(--lr-color-surface); color: var(--lr-color-text); } [part="fit-control"]:where(:not(:disabled)):hover, [part="rotate-button"]:where(:not(:disabled)):hover, [part="annotate-toggle"]:where(:not(:disabled)):hover { background: var(--lr-color-brand-quiet); } [part="fit-control"]:where(:not(:disabled)):active, [part="rotate-button"]:where(:not(:disabled)):active, [part="annotate-toggle"]:where(:not(:disabled)):active { background: color-mix( in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="fit-control"]:focus-visible, [part="rotate-button"]:focus-visible, [part="annotate-toggle"]:focus-visible { outline: var(--lr-focus-ring); outline-offset: var(--lr-focus-ring-offset); } .fit-control-chevron { position: absolute; inset-inline-end: var(--lr-space-xs); display: inline-flex; color: var(--lr-color-text-quiet); line-height: var(--lr-line-height-none); pointer-events: none; } .fit-control-chevron svg { transform: rotate(90deg); } [part="annotate-toggle"][aria-pressed="true"] { background: var( --lr-image-viewer-annotate-active-bg, var(--lr-color-brand-quiet) ); border-color: var( --lr-image-viewer-annotate-active-border, var(--lr-color-brand) ); } [part="annotate-toggle"][aria-pressed="true"]:where(:not(:disabled)):active { background: color-mix( in oklab, var(--lr-image-viewer-annotate-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="rotation-frame"] { position: relative; display: inline-block; max-inline-size: 100%; } :host([fit="actual"]) [part="rotation-frame"] { max-inline-size: none; } [part="rotation-frame"][data-measured] [part="image-wrapper"] { position: absolute; left: 50%; top: 50%; inline-size: max-content; max-inline-size: none; } [part="image-wrapper"] { position: relative; display: inline-block; max-inline-size: 100%; transition: transform var(--lr-transition-base); outline: none; } [part="image-wrapper"]:focus-visible { outline: var(--lr-focus-ring); outline-offset: calc(-1 * max(var(--lr-focus-ring-width) + 2 * var(--lr-border-width-thin), var(--lr-focus-ring-width) + var(--lr-focus-ring-offset))); } :host([fit="actual"]) [part="image-wrapper"] { max-inline-size: none; } :host([fit="contain"]) [part="frame"]::part(content), :host([fit="width"]) [part="frame"]::part(content) { inline-size: 100%; } [part="image"] { display: block; } :host([fit="width"]) [part="image"] { inline-size: 100cqi; block-size: auto; } :host([fit="width"]) :is([data-rotation="90"], [data-rotation="270"]) [part="image"] { inline-size: auto; block-size: 100cqi; } :host([fit="contain"]) [part="image"] { max-inline-size: 100cqi; max-block-size: 100cqb; block-size: auto; object-fit: contain; } :host([fit="contain"]) :is([data-rotation="90"], [data-rotation="270"]) [part="image"] { max-inline-size: 100cqb; max-block-size: 100cqi; } [part="highlight-layer"] { position: absolute; inset: 0; isolation: isolate; container-type: size; --_lr-image-viewer-hit-layer: -1; } [part="highlight"] { position: absolute; box-sizing: border-box; --_lr-image-viewer-highlight-bw: var(--lr-border-width-medium); border: solid var(--lr-image-viewer-highlight-border, var(--lr-color-brand)); border-width: min( var(--_lr-image-viewer-highlight-bw), var(--_lr-image-viewer-highlight-max-bh, calc(var(--_lr-image-viewer-highlight-h) * 0.5cqh)) ) min( var(--_lr-image-viewer-highlight-bw), var(--_lr-image-viewer-highlight-max-bw, calc(var(--_lr-image-viewer-highlight-w) * 0.5cqw)) ); --_lr-image-viewer-highlight-fill: var( --lr-image-viewer-highlight-bg, color-mix(in srgb, var(--lr-color-brand) 20%, transparent) ); background: var( --lr-image-viewer-highlight-fill, var(--_lr-image-viewer-highlight-fill) ); cursor: pointer; padding: 0; transition: var(--lr-transition-interactive); } [part="highlight"]::after { content: ""; position: absolute; z-index: var(--_lr-image-viewer-hit-layer); inset-inline: min(0px, calc((100% - var(--lr-icon-button-size)) / 2)); inset-block: min(0px, calc((100% - var(--lr-icon-button-size)) / 2)); } [part="highlight"]:where([data-tone="success"]) { border-style: double; border-color: var( --lr-image-viewer-highlight-success-border, var(--lr-color-success) ); --_lr-image-viewer-highlight-fill: var( --lr-image-viewer-highlight-success-bg, color-mix(in srgb, var(--lr-color-success) 20%, transparent) ); } [part="highlight"]:where([data-tone="warning"]) { border-style: dashed; border-color: var( --lr-image-viewer-highlight-warning-border, var(--lr-color-warning) ); --_lr-image-viewer-highlight-fill: var( --lr-image-viewer-highlight-warning-bg, color-mix(in srgb, var(--lr-color-warning) 20%, transparent) ); } [part="highlight"]:where([data-tone="danger"]) { border-style: dotted; border-color: var( --lr-image-viewer-highlight-danger-border, var(--lr-color-danger) ); --_lr-image-viewer-highlight-fill: var( --lr-image-viewer-highlight-danger-bg, color-mix(in srgb, var(--lr-color-danger) 20%, transparent) ); } [part="highlight"]:where([data-tone="neutral"]) { border-style: groove; border-color: var( --lr-image-viewer-highlight-neutral-border, var(--lr-color-border) ); --_lr-image-viewer-highlight-fill: var( --lr-image-viewer-highlight-neutral-bg, color-mix(in srgb, var(--lr-color-text) 12%, transparent) ); } [part="highlight"]:where([data-active]) { --_lr-image-viewer-highlight-bw: var( --lr-image-viewer-highlight-active-border-width, var(--lr-border-width-thick) ); outline: var( --lr-image-viewer-highlight-active-outline-width, var(--lr-focus-ring-width) ) solid var(--lr-image-viewer-highlight-active-color, var(--lr-color-brand)); outline-offset: var( --lr-image-viewer-highlight-active-outline-offset, var(--lr-focus-ring-offset) ); } [part="highlight"]:hover { background: color-mix( in oklab, var( --lr-image-viewer-highlight-fill, var(--_lr-image-viewer-highlight-fill) ), var(--lr-color-mix-partner) var(--lr-color-mix-hover) ); } [part="highlight"]:active { background: color-mix( in oklab, var( --lr-image-viewer-highlight-fill, var(--_lr-image-viewer-highlight-fill) ), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="highlight"]:focus-visible { outline: var(--lr-focus-ring); outline-offset: var(--lr-focus-ring-offset); } [part="highlight-label"] { position: absolute; inset-block-start: calc(var(--lr-size-1-5em) * -1); left: 0; font-size: var(--lr-font-size-xs); color: var(--lr-color-text); background: var(--lr-color-surface); padding-inline: var(--lr-space-2xs); max-inline-size: min(var(--lr-size-16rem), 100%); white-space: normal; overflow-wrap: anywhere; } [part="annotation-box"] { position: absolute; border: var(--lr-border-width-medium) dashed var(--lr-image-viewer-annotation-box-border, var(--lr-color-brand)); background: var( --lr-image-viewer-annotation-box-bg, color-mix(in srgb, var(--lr-color-brand) 15%, transparent) ); pointer-events: none; } .reveal-target { position: absolute; pointer-events: none; } @media (forced-colors: active) { [part="fit-control"]:hover:not(:disabled), [part="rotate-button"]:hover:not(:disabled), [part="annotate-toggle"]:hover:not(:disabled) { outline: var(--lr-border-width-thin) dashed Highlight; outline-offset: calc(-1 * var(--lr-border-width-thin)); } [part="fit-control"]:active:not(:disabled), [part="rotate-button"]:active:not(:disabled), [part="annotate-toggle"]:active:not(:disabled) { outline-style: double; outline-width: var(--lr-border-width-medium); } [part="annotate-toggle"][aria-pressed="true"] { border-color: Highlight; border-style: double; } [part="highlight"] { background: transparent; border-color: CanvasText; forced-color-adjust: none; } [part="highlight"]:where([data-active]) { outline-color: Highlight; } } .empty-note, [part="error"] { margin: 0; color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-md-sm); text-align: center; padding: var(--lr-space-l); } [part="error"] { color: var(--lr-color-danger); } `;export{styles};
1
+ import{iconHitTarget}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` [part='panorama-engine'] { inline-size: 100%; block-size: 100%; } .panorama-stack { display: contents; } .panorama-stack:where([data-panorama]) { display: grid; flex: 1 1 auto; min-block-size: var(--lr-size-20rem); min-inline-size: 0; } .panorama-stack:where([data-panorama]) > * { grid-area: 1 / 1; } [part='frame'][hidden], [part='toolbar'][hidden] { display: none; } :host { display: block; min-inline-size: 0; } [part="base"] { display: flex; flex-direction: column; gap: var(--lr-space-s); min-inline-size: 0; max-inline-size: 100%; block-size: 100%; } [part="frame"] { flex: 1 1 auto; min-block-size: 0; } [part="frame"]::part(base) { block-size: 100%; grid-template-rows: minmax(0, 1fr) auto; } :host([fit="contain"]) [part="frame"]::part(viewport) { container-type: size; } :host([fit="width"]) [part="frame"]::part(viewport) { container-type: inline-size; contain-intrinsic-inline-size: var(--lr-size-20rem); } [part="toolbar"] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); } .fit-control-wrapper { position: relative; display: inline-flex; align-items: center; min-inline-size: 0; max-inline-size: 100%; } [part="fit-control"], [part="rotate-button"], [part="annotate-toggle"] { ${iconHitTarget} border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius); background: var(--lr-color-surface); color: var(--lr-color-text); font: inherit; cursor: pointer; } [part="fit-control"]:disabled, [part="rotate-button"]:disabled, [part="annotate-toggle"]:disabled { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part="fit-control"] { appearance: none; max-inline-size: 100%; padding-inline: var(--lr-space-s) var(--lr-space-l); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part="fit-control"] option { background: var(--lr-color-surface); color: var(--lr-color-text); } [part="fit-control"]:where(:not(:disabled)):hover, [part="rotate-button"]:where(:not(:disabled)):hover, [part="annotate-toggle"]:where(:not(:disabled)):hover { background: var(--lr-color-brand-quiet); } [part="fit-control"]:where(:not(:disabled)):active, [part="rotate-button"]:where(:not(:disabled)):active, [part="annotate-toggle"]:where(:not(:disabled)):active { background: color-mix( in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="fit-control"]:focus-visible, [part="rotate-button"]:focus-visible, [part="annotate-toggle"]:focus-visible { outline: var(--lr-focus-ring); outline-offset: var(--lr-focus-ring-offset); } .fit-control-chevron { position: absolute; inset-inline-end: var(--lr-space-xs); display: inline-flex; color: var(--lr-color-text-quiet); line-height: var(--lr-line-height-none); pointer-events: none; } .fit-control-chevron svg { transform: rotate(90deg); } [part="annotate-toggle"][aria-pressed="true"] { background: var( --lr-image-viewer-annotate-active-bg, var(--lr-color-brand-quiet) ); border-color: var( --lr-image-viewer-annotate-active-border, var(--lr-color-brand) ); } [part="annotate-toggle"][aria-pressed="true"]:where(:not(:disabled)):active { background: color-mix( in oklab, var(--lr-image-viewer-annotate-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="rotation-frame"] { position: relative; display: inline-block; max-inline-size: 100%; } :host([fit="actual"]) [part="rotation-frame"] { max-inline-size: none; } [part="rotation-frame"][data-measured] [part="image-wrapper"] { position: absolute; left: 50%; top: 50%; inline-size: max-content; max-inline-size: none; } [part="image-wrapper"] { position: relative; display: inline-block; max-inline-size: 100%; transition: transform var(--lr-transition-base); outline: none; } [part="image-wrapper"]:focus-visible { outline: var(--lr-focus-ring); outline-offset: calc(-1 * max(var(--lr-focus-ring-width) + 2 * var(--lr-border-width-thin), var(--lr-focus-ring-width) + var(--lr-focus-ring-offset))); } :host([fit="actual"]) [part="image-wrapper"] { max-inline-size: none; } :host([fit="contain"]) [part="frame"]::part(content), :host([fit="width"]) [part="frame"]::part(content) { inline-size: 100%; } [part="image"] { display: block; } :host([fit="width"]) [part="image"] { inline-size: 100cqi; block-size: auto; } :host([fit="width"]) :is([data-rotation="90"], [data-rotation="270"]) [part="image"] { inline-size: auto; block-size: 100cqi; } :host([fit="contain"]) [part="image"] { max-inline-size: 100cqi; max-block-size: 100cqb; block-size: auto; object-fit: contain; } :host([fit="contain"]) :is([data-rotation="90"], [data-rotation="270"]) [part="image"] { max-inline-size: 100cqb; max-block-size: 100cqi; } [part="highlight-layer"] { position: absolute; inset: 0; isolation: isolate; container-type: size; --_lr-image-viewer-hit-layer: -1; } [part="highlight"] { position: absolute; box-sizing: border-box; --_lr-image-viewer-highlight-bw: var(--lr-border-width-medium); border: solid var(--lr-image-viewer-highlight-border, var(--lr-color-brand)); border-width: min( var(--_lr-image-viewer-highlight-bw), var(--_lr-image-viewer-highlight-max-bh, calc(var(--_lr-image-viewer-highlight-h) * 0.5cqh)) ) min( var(--_lr-image-viewer-highlight-bw), var(--_lr-image-viewer-highlight-max-bw, calc(var(--_lr-image-viewer-highlight-w) * 0.5cqw)) ); --_lr-image-viewer-highlight-fill: var( --lr-image-viewer-highlight-bg, color-mix(in srgb, var(--lr-color-brand) 20%, transparent) ); background: var( --lr-image-viewer-highlight-fill, var(--_lr-image-viewer-highlight-fill) ); cursor: pointer; padding: 0; transition: var(--lr-transition-interactive); } [part="highlight"]::after { content: ""; position: absolute; z-index: var(--_lr-image-viewer-hit-layer); inset-inline: min(0px, calc((100% - var(--lr-icon-button-size)) / 2)); inset-block: min(0px, calc((100% - var(--lr-icon-button-size)) / 2)); } [part="highlight"]:where([data-tone="success"]) { border-style: double; border-color: var( --lr-image-viewer-highlight-success-border, var(--lr-color-success) ); --_lr-image-viewer-highlight-fill: var( --lr-image-viewer-highlight-success-bg, color-mix(in srgb, var(--lr-color-success) 20%, transparent) ); } [part="highlight"]:where([data-tone="warning"]) { border-style: dashed; border-color: var( --lr-image-viewer-highlight-warning-border, var(--lr-color-warning) ); --_lr-image-viewer-highlight-fill: var( --lr-image-viewer-highlight-warning-bg, color-mix(in srgb, var(--lr-color-warning) 20%, transparent) ); } [part="highlight"]:where([data-tone="danger"]) { border-style: dotted; border-color: var( --lr-image-viewer-highlight-danger-border, var(--lr-color-danger) ); --_lr-image-viewer-highlight-fill: var( --lr-image-viewer-highlight-danger-bg, color-mix(in srgb, var(--lr-color-danger) 20%, transparent) ); } [part="highlight"]:where([data-tone="neutral"]) { border-style: groove; border-color: var( --lr-image-viewer-highlight-neutral-border, var(--lr-color-border) ); --_lr-image-viewer-highlight-fill: var( --lr-image-viewer-highlight-neutral-bg, color-mix(in srgb, var(--lr-color-text) 12%, transparent) ); } [part="highlight"]:where([data-active]) { --_lr-image-viewer-highlight-bw: var( --lr-image-viewer-highlight-active-border-width, var(--lr-border-width-thick) ); outline: var( --lr-image-viewer-highlight-active-outline-width, var(--lr-focus-ring-width) ) solid var(--lr-image-viewer-highlight-active-color, var(--lr-color-brand)); outline-offset: var( --lr-image-viewer-highlight-active-outline-offset, var(--lr-focus-ring-offset) ); } [part="highlight"]:hover { background: color-mix( in oklab, var( --lr-image-viewer-highlight-fill, var(--_lr-image-viewer-highlight-fill) ), var(--lr-color-mix-partner) var(--lr-color-mix-hover) ); } [part="highlight"]:active { background: color-mix( in oklab, var( --lr-image-viewer-highlight-fill, var(--_lr-image-viewer-highlight-fill) ), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="highlight"]:focus-visible { outline: var(--lr-focus-ring); outline-offset: var(--lr-focus-ring-offset); } [part="highlight-label"] { position: absolute; inset-block-start: calc(var(--lr-size-1-5em) * -1); left: 0; font-size: var(--lr-font-size-xs); color: var(--lr-color-text); background: var(--lr-color-surface); padding-inline: var(--lr-space-2xs); max-inline-size: min(var(--lr-size-16rem), 100%); white-space: normal; overflow-wrap: anywhere; } [part="annotation-box"] { position: absolute; border: var(--lr-border-width-medium) dashed var(--lr-image-viewer-annotation-box-border, var(--lr-color-brand)); background: var( --lr-image-viewer-annotation-box-bg, color-mix(in srgb, var(--lr-color-brand) 15%, transparent) ); pointer-events: none; } .reveal-target { position: absolute; pointer-events: none; } @media (forced-colors: active) { [part="fit-control"]:hover:not(:disabled), [part="rotate-button"]:hover:not(:disabled), [part="annotate-toggle"]:hover:not(:disabled) { outline: var(--lr-border-width-thin) dashed Highlight; outline-offset: calc(-1 * var(--lr-border-width-thin)); } [part="fit-control"]:active:not(:disabled), [part="rotate-button"]:active:not(:disabled), [part="annotate-toggle"]:active:not(:disabled) { outline-style: double; outline-width: var(--lr-border-width-medium); } [part="annotate-toggle"][aria-pressed="true"] { border-color: Highlight; border-style: double; } [part="highlight"] { background: transparent; border-color: CanvasText; forced-color-adjust: none; } [part="highlight"]:where([data-active]) { outline-color: Highlight; } } .empty-note, [part="error"] { margin: 0; color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-md-sm); text-align: center; padding: var(--lr-space-l); } [part="error"] { color: var(--lr-color-danger); } `;export{styles};
@@ -0,0 +1 @@
1
+ import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{getInheritedPropertyDescriptor}from"../../../internal/data-descriptors.js";import{applyComposedFocusRepair,captureComposedFocusRepair,focusFirstAvailable}from"../../../internal/focus-navigation.js";import{finiteRange}from"../../../internal/numbers.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{collectFocusableElements,composedContains,deepActiveElement}from"../../../internal/overlay-stack.js";import{virtualAnchorFromRect}from"../../../internal/positioner-geometry.js";import{admitMapAnchorOptions}from"./map-anchor-options.js";import{mapOwnValue,renderedSizeKey}from"./map-readers.js";class MapAnchorController{constructor(host){this.host=host,this.epoch=0,this.placed=!1,this.closingState=!1,this.observedBoundaries=[]}get closing(){return this.closingState}view(){return this.host.element.ownerDocument?.defaultView??null}stop(){this.epoch+=1,this.placed=!1,this.placedCoordinates=void 0;const cleanup=this.cleanup;this.cleanup=void 0,cleanup?.(),this.overlay?.suspend()}schedule(){if(this.stop(),this.frame!==void 0)return;const view=this.view();if(!view||typeof view.requestAnimationFrame!="function"){this.sync();return}this.frame=view.requestAnimationFrame(()=>{this.frame=void 0,this.sync()})}cancelFrame(){this.frame!==void 0&&(this.view()?.cancelAnimationFrame?.(this.frame),this.frame=void 0)}focus(){const wrapper=this.host.wrapper();if(!wrapper||!this.isOpen())return!1;const epoch=this.epoch,targets=collectFocusableElements(wrapper);return epoch!==this.epoch||!this.isOpen()||targets.length===0||(this.captureReturnTarget(wrapper),epoch!==this.epoch||!this.isOpen())?!1:focusFirstAvailable(targets)&&epoch===this.epoch&&this.isOpen()}isOpen(){const host=this.host,element=host.element,wrapper=host.wrapper();return element.isConnected&&!!host.map()&&host.styleLoaded()&&this.placed&&!element.isUpdatePending&&this.placedCoordinates===element.anchorLngLat&&!!wrapper&&!wrapper.hidden&&!host.interactionBlocked()&&this.hasContent()}captureReturnTarget(wrapper){const active=deepActiveElement(this.host.element.ownerDocument);if(!(!active||composedContains(wrapper,active)))try{const descriptor=getInheritedPropertyDescriptor(active,"focus");descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"&&(this.returnTarget=active,this.overlay?.updateRestoreFocusTo(this.returnTarget))}catch{}}close(reason){const host=this.host,element=host.element,wrapper=host.wrapper();if(!wrapper||!this.isOpen())return!1;const requestEpoch=this.epoch,map=host.map(),coordinates=element.anchorLngLat,repair=captureComposedFocusRepair(wrapper,this.returnTarget??null);if(requestEpoch!==this.epoch||map!==host.map()||coordinates!==element.anchorLngLat||!this.isOpen())return!1;this.closingState=!0;try{element.anchorLngLat=null}finally{this.closingState=!1}this.hide(!1,!0);const epoch=this.epoch;return host.emitClose(Object.freeze({reason})),repair&&epoch===this.epoch&&element.anchorLngLat===null&&applyComposedFocusRepair(repair),!0}hide(restore=!0,retire=!1){const host=this.host,element=host.element,wrapper=host.wrapper(),requestEpoch=this.epoch,map=host.map(),coordinates=element.anchorLngLat,repair=restore&&wrapper?captureComposedFocusRepair(wrapper,this.returnTarget??null):null;if(requestEpoch!==this.epoch||map!==host.map()||coordinates!==element.anchorLngLat)return;this.stop(),wrapper&&(wrapper.hidden=!0);const epoch=this.epoch;if(retire){const overlay=this.overlay;this.overlay=void 0,this.returnTarget=void 0,overlay?.deactivate({restoreFocus:!1})}else this.overlay?.suspend();repair&&epoch===this.epoch&&!this.placed&&applyComposedFocusRepair(repair)}dispose(){this.cancelFrame(),this.hide(!0,!0),this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[]}syncOverlay(wrapper){const host=this.host,element=host.element;if(!element.anchorClosable){const overlay=this.overlay;this.overlay=void 0,overlay?.deactivate({restoreFocus:!1});return}if(this.overlay)this.overlay.resume();else{const epoch=this.epoch;if(this.captureReturnTarget(wrapper),epoch!==this.epoch||!this.placed||!element.isConnected)return;const overlay=activateOverlay({host:element,panel:()=>host.wrapper()??null,onEscape:()=>{this.close("escape")},beforeInitialFocus:()=>!1,restoreFocusTo:()=>this.returnTarget??null,modal:!1,trapFocus:!1,lockScroll:!1});epoch===this.epoch&&this.placed&&element.isConnected&&element.anchorClosable&&!this.overlay?this.overlay=overlay:overlay.deactivate({restoreFocus:!1})}}hasContent(){return this.host.element.shadowRoot?.querySelector('slot[name="anchor"]')?.assignedNodes({flatten:!0}).some(node=>node.nodeType===1||node.nodeType===3&&!!node.textContent?.trim())??!1}observeBoundaries(boundaries){if(boundaries.length===this.observedBoundaries.length&&boundaries.every((value,index)=>value===this.observedBoundaries[index]))return;this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[...boundaries];const ResizeObserverClass=this.view()?.ResizeObserver;if(!ResizeObserverClass||boundaries.length===0)return;let sizes=boundaries.map(renderedSizeKey);this.boundaryObserver=new ResizeObserverClass(()=>{const next=boundaries.map(renderedSizeKey);next.every((value,index)=>value===sizes[index])||(sizes=next,this.host.element.isConnected&&this.schedule())});for(const boundary of boundaries)this.boundaryObserver.observe(boundary)}focusIn(event){const wrapper=this.host.wrapper(),previous=event.relatedTarget,view=this.view();if(!(!wrapper||!view||!(previous instanceof view.Element)||previous.ownerDocument!==this.host.element.ownerDocument||composedContains(wrapper,previous)))try{const descriptor=getInheritedPropertyDescriptor(previous,"focus");descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"&&(this.returnTarget=previous,this.overlay?.updateRestoreFocusTo(this.returnTarget))}catch{}}point(){const host=this.host,position=host.element.anchorLngLat,container=host.container();if(!container||!Array.isArray(position))return;const lng=mapOwnValue(position,"0"),lat=mapOwnValue(position,"1");if(typeof lng!="number"||!Number.isFinite(lng)||typeof lat!="number"||!Number.isFinite(lat)||Math.abs(lat)>90)return;const point=host.element.project([lng,lat]);if(!point)return;const[x,y]=point;return x>=0&&y>=0&&x<=container.clientWidth&&y<=container.clientHeight?point:void 0}sync(){const host=this.host,element=host.element;if(host.updateActive()){const[generation,connection]=host.generations(),map2=host.map();host.afterUpdate(()=>{const[style,current2]=host.generations();element.isConnected&&current2===connection&&style===generation&&host.map()===map2&&this.sync()},`map-anchor-${connection}-${generation}`);return}const wrapper=host.wrapper(),container=host.container(),fence=host.fence();if(!wrapper||!container||!fence||!element.isConnected||!host.map()||!host.styleLoaded()||host.interactionBlocked()||!this.hasContent()){this.hide();return}this.stop();const epoch=this.epoch,map=host.map(),coordinates=element.anchorLngLat,boundary=element.anchorBoundary,safeArea=element.anchorSafeArea,direction=host.direction(),current=()=>element.isConnected&&host.map()===map&&host.styleLoaded()&&epoch===this.epoch&&element.anchorLngLat===coordinates&&element.anchorBoundary===boundary&&element.anchorSafeArea===safeArea&&host.direction()===direction&&!host.interactionBlocked();try{const admitted=admitMapAnchorOptions({boundary,safeArea},element.ownerDocument,{current});if(!admitted.ok||!current()){epoch===this.epoch&&this.hide();return}this.observeBoundaries(admitted.boundaries);const point=this.point();if(!current())return;const width=finiteRange(container.clientWidth,0,0),height=finiteRange(container.clientHeight,0,0),edges=admitted.safeArea,start=Math.min(width,edges.inlineStart),end=Math.min(width,edges.inlineEnd),top=Math.min(height,edges.blockStart),bottom=Math.min(height,edges.blockEnd);if(!point||start+end>=width||top+bottom>=height){this.hide();return}fence.style.insetInlineStart=`${start}px`,fence.style.insetInlineEnd=`${end}px`,fence.style.insetBlockStart=`${top}px`,fence.style.insetBlockEnd=`${bottom}px`;const clip=fence.getBoundingClientRect();let left=clip.left,right=clip.right,upper=clip.top,lower=clip.bottom;for(const clipping of admitted.boundaries){const bounds=clipping.getBoundingClientRect();if(!current())return;left=Math.max(left,bounds.left),right=Math.min(right,bounds.right),upper=Math.max(upper,bounds.top),lower=Math.min(lower,bounds.bottom)}if(!(right-left>16&&lower-upper>16)){this.hide();return}wrapper.hidden=!1;const rect=container.getBoundingClientRect();if(!current())return;const placement=place(virtualAnchorFromRect({x:rect.left+point[0],y:rect.top+point[1],contextElement:container}),wrapper,{placement:"top",strategy:"absolute",offset:12,boundary:[fence,...admitted.boundaries],padding:8,onPlaced:()=>{!current()||!this.hasContent()||(this.placed||this.captureReturnTarget(wrapper),current()&&(this.placed=!0,this.placedCoordinates=coordinates,this.syncOverlay(wrapper)))}});if(!current()){placement();return}this.cleanup=placement,placement.ready.then(ready=>{!ready&&current()&&this.hide()})}catch{current()&&this.hide()}}}export{MapAnchorController};
@@ -0,0 +1,14 @@
1
+ /** Nonnegative finite CSS-pixel insets. Omitted logical edges default to zero. */
2
+ export interface LyraMapAnchorSafeArea{readonly blockStart?:number;readonly inlineEnd?:number;readonly blockEnd?:number;readonly inlineStart?:number;}export type LyraMapAnchorBoundary=Element|readonly Element[];
3
+ /** How an open anchor was closed: by `closeAnchor()`, its close button or Escape. */
4
+ export type LyraMapAnchorCloseReason='api'|'close-button'|'escape';export interface LyraMapAnchorCloseDetail{readonly reason:LyraMapAnchorCloseReason;}type MapAnchorSafeArea=Readonly<Required<LyraMapAnchorSafeArea>>;export interface MapAnchorOptionsContext{readonly current?:()=>boolean;}export type MapAnchorOptionsResult={readonly ok:true;readonly safeArea:MapAnchorSafeArea;
5
+ /** Detached mutable copy, suitable for the shared positioner's Element[] boundary input. */
6
+ readonly boundaries:Element[];}|{readonly ok:false;readonly code:'invalid-safe-area'|'invalid-boundary'|'stale';};
7
+ /**
8
+ * Snapshots own placement data without evaluating caller getters. Explicitly undefined edge
9
+ * values are invalid; an undefined safe-area object uses all-zero defaults. Valid large finite
10
+ * edges stay intact so the placement owner can collapse/clamp them against actual allocation.
11
+ * Boundaries must be real connected Elements in the supplied owner document; no DOM globals are
12
+ * read until a nonempty boundary needs validation, preserving SSR-safe module imports.
13
+ */
14
+ export declare function admitMapAnchorOptions(input:unknown,ownerDocument:Document,context?:MapAnchorOptionsContext):MapAnchorOptionsResult;export{};
@@ -0,0 +1 @@
1
+ import{getInheritedPropertyDescriptor,getOwnDataDescriptor,isObjectValue,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,readOwnArrayLength,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{finiteNumber}from"../../../internal/numbers.js";const EDGES=["blockStart","inlineEnd","blockEnd","inlineStart"];class StaleAnchorOptions extends Error{}function admitMapAnchorOptions(input,ownerDocument,context={}){let code="invalid-safe-area";const guard=()=>{let current=!1;try{current=context.current?.()??!0}catch{}if(!current)throw new StaleAnchorOptions},descriptor=(value,key)=>{guard();const result=getOwnDataDescriptor(value,key);return guard(),result},own=(value,key,optional=!1)=>{const result=descriptor(value,key);if(result===UNSAFE_OWN_DATA_DESCRIPTOR||result===MISSING_OWN_DATA_DESCRIPTOR&&!optional)throw new Error("Invalid anchor data.");return result===MISSING_OWN_DATA_DESCRIPTOR?void 0:result.value},keys=(value,allowed)=>{if(guard(),!isPlainDataRecord(value))throw new Error("Invalid anchor options.");guard();const result=Reflect.ownKeys(value);if(guard(),result.length>allowed.length||result.some(key=>typeof key!="string"||!allowed.includes(key)))throw new Error("Invalid anchor fields.");return result},inherited=(value,key)=>{guard();const result=getInheritedPropertyDescriptor(value,key);if(guard(),!result)throw new Error("Unavailable DOM capability.");return result},data=(value,key)=>{const result=inherited(value,key);if(!Object.hasOwn(result,"value"))throw new Error("Invalid DOM capability.");return result.value},getter=(value,key)=>{const result=inherited(value,key);if(typeof result.get!="function")throw new Error("Unavailable DOM capability.");return result.get},invoke=(read,receiver)=>{guard();const result=Reflect.apply(read,receiver,[]);return guard(),result};try{guard();const top=keys(input,["safeArea","boundary"]),rawSafeArea=top.includes("safeArea")?own(input,"safeArea"):void 0,safeKeys=rawSafeArea===void 0?[]:keys(rawSafeArea,EDGES),safeArea={};for(const edge of EDGES){const value=safeKeys.includes(edge)?own(rawSafeArea,edge):0;if(typeof value!="number"||!Number.isFinite(value)||value<0)throw new Error("Invalid anchor safe area.");safeArea[edge]=finiteNumber(value,0)}code="invalid-boundary";const rawBoundary=top.includes("boundary")?own(input,"boundary"):void 0;let values=[];guard();const isArray=Array.isArray(rawBoundary);if(guard(),isArray){guard();const count=readOwnArrayLength(rawBoundary);if(guard(),count===void 0||count>32)throw new Error("Invalid anchor boundary count.");const arrayKeys=Reflect.ownKeys(rawBoundary);if(guard(),arrayKeys.length!==count+1)throw new Error("Invalid anchor boundary array.");values=Array.from({length:count},(_entry,index)=>own(rawBoundary,String(index)))}else rawBoundary!==void 0&&(values=[rawBoundary]);const boundaries=[];if(values.length){if(typeof Document>"u"||typeof Element>"u"||typeof Node>"u")throw new Error("DOM boundaries unavailable.");const view=invoke(getter(Document.prototype,"defaultView"),ownerDocument),elementConstructor=view&&isObjectValue(view)?data(view,"Element"):Element,nodeConstructor=view&&isObjectValue(view)?data(view,"Node"):Node;if(!isObjectValue(elementConstructor)||!isObjectValue(nodeConstructor))throw new Error("DOM constructors unavailable.");const elementPrototype=data(elementConstructor,"prototype"),nodePrototype=data(nodeConstructor,"prototype");if(!isObjectValue(elementPrototype)||!isObjectValue(nodePrototype))throw new Error("DOM prototypes unavailable.");const localName=getter(elementPrototype,"localName"),documentOf=getter(nodePrototype,"ownerDocument"),connected=getter(nodePrototype,"isConnected");for(const value of values){if(!isObjectValue(value)||typeof invoke(localName,value)!="string"||invoke(documentOf,value)!==ownerDocument||invoke(connected,value)!==!0)throw new Error("Invalid anchor boundary.");boundaries.push(value)}}return guard(),Object.freeze({ok:!0,safeArea:Object.freeze(safeArea),boundaries})}catch(error){return Object.freeze({ok:!1,code:error instanceof StaleAnchorOptions?"stale":code})}}export{admitMapAnchorOptions};
@@ -0,0 +1,34 @@
1
+ /** `[[west, south], [east, north]]`, the order maplibre-gl takes. */
2
+ export type MapCameraBounds=readonly[readonly[number,number],readonly[number,number]];
3
+ /** A camera target accepted by `flyTo()`, `easeTo()` and `jumpTo()`. Every field is optional; an
4
+ * omitted or unusable field keeps the camera's current value. */
5
+ export interface LyraMapCameraOptions{
6
+ /** `[longitude, latitude]`; longitude is clamped into `[-180, 180]`, latitude into `[-90, 90]`. */
7
+ readonly center?:readonly[number,number];
8
+ /** Zoom level, clamped into the map's zoom limits (`minZoom`/`maxZoom`, `[0, 22]` by default). */
9
+ readonly zoom?:number;
10
+ /** Bearing in degrees, clockwise from north. */
11
+ readonly bearing?:number;
12
+ /** Pitch in degrees, clamped into `[0, 85]`. */
13
+ readonly pitch?:number;
14
+ /** Animation length in milliseconds for `flyTo()` and `easeTo()`; a negative or non-finite value
15
+ * uses the engine's own default. Ignored by `jumpTo()` and under `prefers-reduced-motion`. */
16
+ readonly duration?:number;}
17
+ /** A validated camera target, ready for the engine. */
18
+ export interface MapCameraTarget{readonly center?:[number,number];readonly zoom?:number;readonly bearing?:number;readonly pitch?:number;readonly duration?:number;}
19
+ /** Validates a camera command's options, or returns `undefined` when nothing in them is usable. */
20
+ export declare function normalizeCameraOptions(options:unknown,zoomLimits?:readonly[number,number]):MapCameraTarget|undefined;
21
+ /** Running extent of the positions seen so far. */
22
+ export interface CoordinateExtent{west:number;south:number;east:number;north:number;count:number;}export declare function emptyExtent():CoordinateExtent;
23
+ /** Adds one `[longitude, latitude]` to the extent. A non-finite coordinate is skipped; an
24
+ * out-of-range one is clamped, because the fit validates its box and rejects what a clamp keeps. */
25
+ export declare function extendExtent(extent:CoordinateExtent,longitude:unknown,latitude:unknown):void;
26
+ /**
27
+ * Extends `extent` with every position of an already-projected GeoJSON `Feature` or
28
+ * `FeatureCollection`. Iterative, so deeply nested input cannot exhaust the call stack, and bounded
29
+ * by `MAX_FIT_POSITIONS`. The box is a plain west/east span: data straddling the antimeridian frames
30
+ * the long way round.
31
+ */
32
+ export declare function extendExtentWithGeoJson(extent:CoordinateExtent,geojson:unknown):void;
33
+ /** The extent as a fit box, or `undefined` when no position was seen. */
34
+ export declare function extentToBounds(extent:CoordinateExtent):MapCameraBounds|undefined;
@@ -0,0 +1 @@
1
+ import{finiteRange}from"../../../internal/numbers.js";function isFiniteNumber(value){return typeof value=="number"&&Number.isFinite(value)}function normalizeCameraOptions(options,zoomLimits=[0,22]){if(typeof options!="object"||options===null)return;const source=options,target={},center=source.center;if(Array.isArray(center)&&center.length===2&&isFiniteNumber(center[0])&&isFiniteNumber(center[1])&&(target.center=[finiteRange(center[0],0,-180,180),finiteRange(center[1],0,-90,90)]),isFiniteNumber(source.zoom)&&(target.zoom=finiteRange(source.zoom,zoomLimits[0],zoomLimits[0],zoomLimits[1])),isFiniteNumber(source.bearing)&&(target.bearing=source.bearing),isFiniteNumber(source.pitch)&&(target.pitch=finiteRange(source.pitch,0,0,85)),!(target.center===void 0&&target.zoom===void 0&&target.bearing===void 0&&target.pitch===void 0))return isFiniteNumber(source.duration)&&source.duration>=0&&(target.duration=source.duration),Object.freeze(target)}function emptyExtent(){return{west:1/0,south:1/0,east:-1/0,north:-1/0,count:0}}function extendExtent(extent,longitude,latitude){if(!isFiniteNumber(longitude)||!isFiniteNumber(latitude))return;const lng=finiteRange(longitude,0,-180,180),lat=finiteRange(latitude,0,-90,90);lng<extent.west&&(extent.west=lng),lng>extent.east&&(extent.east=lng),lat<extent.south&&(extent.south=lat),lat>extent.north&&(extent.north=lat),extent.count+=1}const MAX_FIT_POSITIONS=5e6;function extendExtentWithGeoJson(extent,geojson){const stack=[geojson];let budget=MAX_FIT_POSITIONS;for(;stack.length>0&&budget>0;){const node=stack.pop();if(typeof node!="object"||node===null)continue;const record=node;switch(record.type){case"FeatureCollection":{const features=record.features;if(Array.isArray(features))for(let i=features.length-1;i>=0;i-=1)stack.push(features[i]);break}case"Feature":stack.push(record.geometry);break;case"GeometryCollection":{const geometries=record.geometries;if(Array.isArray(geometries))for(let i=geometries.length-1;i>=0;i-=1)stack.push(geometries[i]);break}case"Point":case"MultiPoint":case"LineString":case"MultiLineString":case"Polygon":case"MultiPolygon":budget-=extendExtentWithCoordinates(extent,record.coordinates,budget);break;default:break}}}function extendExtentWithCoordinates(extent,coordinates,budget){let read=0;const stack=[coordinates];for(;stack.length>0&&read<budget;){const node=stack.pop();if(!(!Array.isArray(node)||node.length===0))if(typeof node[0]=="number")extendExtent(extent,node[0],node[1]),read+=1;else for(let i=node.length-1;i>=0;i-=1)stack.push(node[i])}return read}function extentToBounds(extent){if(extent.count!==0)return Object.freeze([Object.freeze([extent.west,extent.south]),Object.freeze([extent.east,extent.north])])}export{emptyExtent,extendExtent,extendExtentWithGeoJson,extentToBounds,normalizeCameraOptions};
@@ -0,0 +1,13 @@
1
+ /** When `<lr-map>` constructs its engine: once visible, at browser idle time, at once, or on the
2
+ * first user input on the element (optionally also after `initializationDelay`). */
3
+ export type LyraMapInitialization='visible'|'idle'|'eager'|'interaction';type Cancel=()=>void;
4
+ /** Cancellable owner-realm scheduling capabilities. Null means no browser realm. */
5
+ export interface MapConstructionPort{connected():boolean;visible(admit:()=>void):Cancel;idle(admit:()=>void):Cancel;
6
+ /** Admits on the first input on the host, or after `delay` milliseconds when it is given. */
7
+ interaction?(admit:()=>void,delay:number|undefined):Cancel;}
8
+ /** One construction attempt per connection, after both admission and caller readiness. */
9
+ export declare class MapConstructionScheduler{private readonly port;private readonly construct;private active;private ready;private admitted;private consumed;private generation;private cancel?;private checkingConnection;constructor(port:MapConstructionPort|null,construct:()=>void);connect(mode?:LyraMapInitialization,delay?:number):void;disconnect():void;
10
+ /** Whether construction already happened for this connection. */
11
+ get constructed():boolean;reconfigure(mode:LyraMapInitialization,delay?:number):void;setReady(ready:boolean):void;private flush;}
12
+ /** Uses only the host's owner window; importing or creating this helper is SSR safe. */
13
+ export declare function createMapConstructionScheduler(host:Element,construct:()=>void):MapConstructionScheduler;export{};
@@ -0,0 +1 @@
1
+ const MAP_ACTIVATION_EVENTS=["pointerdown","touchstart","wheel","keydown","click"];class MapConstructionScheduler{constructor(port,construct){this.port=port,this.construct=construct,this.active=!1,this.ready=!1,this.admitted=!1,this.consumed=!1,this.generation=0,this.checkingConnection=!1}connect(mode="visible",delay){const generation=this.generation+1;this.disconnect(),generation===this.generation&&(this.active=!0,this.ready=!1,this.consumed=!1,this.reconfigure(mode,delay))}disconnect(){this.active=!1,this.generation+=1;const cancel=this.cancel;this.cancel=void 0,cancel?.()}get constructed(){return this.consumed}reconfigure(mode,delay){const generation=++this.generation,previous=this.cancel;if(this.cancel=void 0,previous?.(),generation!==this.generation||!this.active||(this.admitted=!1,!this.active||this.consumed||!this.port))return;const admit=()=>{if(!this.active||generation!==this.generation||this.consumed)return;this.admitted=!0;const cancel=this.cancel;this.cancel=void 0,cancel?.(),generation===this.generation&&this.flush()};if(mode==="eager")admit();else{const cancel=mode==="idle"?this.port.idle(admit):mode==="interaction"&&this.port.interaction?this.port.interaction(admit,delay):this.port.visible(admit);generation!==this.generation||this.admitted||!this.active?cancel():this.cancel=cancel}}setReady(ready){this.ready=ready,this.flush()}flush(followLatest=!0){if(!this.active||!this.ready||!this.admitted||this.consumed||!this.port||this.checkingConnection)return;const generation=this.generation;let connected;this.checkingConnection=!0;try{connected=this.port.connected()}finally{this.checkingConnection=!1}if(generation!==this.generation){followLatest&&this.flush(!1);return}!connected||!this.active||!this.ready||!this.admitted||this.consumed||(this.consumed=!0,this.construct())}}function createMapConstructionScheduler(host,construct){const view=host.ownerDocument.defaultView;return new MapConstructionScheduler(view?{connected:()=>host.isConnected,visible(admit){const Observer=view.IntersectionObserver;if(!Observer)return admit(),()=>{};const observer=new Observer(entries=>{entries.some(entry=>entry.target===host&&entry.isIntersecting)&&admit()});return observer.observe(host),()=>observer.disconnect()},interaction(admit,delay){const options={capture:!0,passive:!0};for(const type of MAP_ACTIVATION_EVENTS)host.addEventListener(type,admit,options);const handle=delay===void 0?void 0:view.setTimeout(admit,delay);return()=>{for(const type of MAP_ACTIVATION_EVENTS)host.removeEventListener(type,admit,options);handle!==void 0&&view.clearTimeout(handle)}},idle(admit){if(typeof view.requestIdleCallback=="function"&&typeof view.cancelIdleCallback=="function"){const handle2=view.requestIdleCallback(admit,{timeout:1e3});return()=>view.cancelIdleCallback(handle2)}const handle=view.setTimeout(admit,0);return()=>view.clearTimeout(handle)}}:null,construct)}export{MapConstructionScheduler,createMapConstructionScheduler};
@@ -0,0 +1,39 @@
1
+ export type MapOwnedControlKind='navigation'|'scale'|'geolocate'|'attribution';
2
+ /** Corner a declarative control is added to. The corners follow text direction under RTL. */
3
+ export type LyraMapControlPosition='top-left'|'top-right'|'bottom-left'|'bottom-right';
4
+ /** Unit system of the scale control. */
5
+ export type LyraMapScaleUnit='metric'|'imperial';
6
+ /** Options of the declarative navigation control (zoom buttons and compass). */
7
+ export interface LyraMapNavigationControlOptions{
8
+ /** Corner to add the control to. Defaults to `'top-right'`. */
9
+ readonly position?:LyraMapControlPosition;}
10
+ /** Options of the declarative scale control. */
11
+ export interface LyraMapScaleControlOptions{
12
+ /** Corner to add the control to. Defaults to `'bottom-left'`. */
13
+ readonly position?:LyraMapControlPosition;
14
+ /** Unit system. Defaults to `'metric'`. */
15
+ readonly unit?:LyraMapScaleUnit;}
16
+ /** Options of the declarative geolocation control. */
17
+ export interface LyraMapGeolocateControlOptions extends LyraMapNavigationControlOptions{readonly trackUserLocation?:boolean;readonly showUserLocation?:boolean;readonly showAccuracyCircle?:boolean;readonly zoomToUserAccuracy?:boolean;readonly positionOptions?:{readonly enableHighAccuracy?:boolean;readonly timeout?:number;readonly maximumAge?:number;};readonly fitBoundsOptions?:{readonly maxZoom?:number;};}
18
+ /** A text credit linked to an absolute HTTP(S) URL; admission takes an immutable own-data snapshot. */
19
+ export interface LyraMapAttributionLink{
20
+ /** Escaped display text, at most 4,096 characters. */
21
+ readonly label:string;
22
+ /** Absolute HTTP(S) URL, at most 2,048 characters, without credentials or control characters. */
23
+ readonly url:string;}
24
+ /** Options of the declarative attribution control. */
25
+ export interface LyraMapAttributionControlOptions extends LyraMapNavigationControlOptions{
26
+ /** Omission retains the peer's automatic compact layout. */
27
+ readonly compact?:boolean;
28
+ /** Text or guarded links; at most 32 items and 16 KiB of labels and URLs. Caller HTML is never interpreted. */
29
+ readonly customAttribution?:string|LyraMapAttributionLink|readonly(string|LyraMapAttributionLink)[];}export interface NormalizedMapControlOptions{readonly kind:MapOwnedControlKind;readonly position:LyraMapControlPosition;readonly unit:LyraMapScaleUnit|undefined;readonly options:Readonly<Record<string,unknown>>;readonly key:string;
30
+ /** Escaped labels only, for text export without URLs or link markup. */
31
+ readonly attributionText?:readonly string[];}export interface MapControlOptionsResult{readonly controls:ReadonlyMap<MapOwnedControlKind,NormalizedMapControlOptions>;readonly diagnostics:readonly{readonly kind:MapOwnedControlKind;readonly code:'invalid-options';}[];}
32
+ /**
33
+ * Detached constructor options only. No permission requests, geolocation calls, DOM work or
34
+ * activation occur here. Navigation/scale preserve their existing malformed-field defaults;
35
+ * malformed new controls are excluded with stable diagnostics. Unknown fields are not forwarded.
36
+ */
37
+ export declare function normalizeMapControlOptions(input:unknown):MapControlOptionsResult;export type LyraMapGeolocationErrorCode='permission-denied'|'position-unavailable'|'timeout'|'unknown';
38
+ /** Map an already extracted native numeric error code; do not inspect native messages or locations. */
39
+ export declare function mapGeolocationErrorCode(code:unknown):LyraMapGeolocationErrorCode;
@@ -0,0 +1 @@
1
+ import{resolveGuardedRel}from"../../../internal/link-rel.js";import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";const positions=new Set(["top-left","top-right","bottom-left","bottom-right"]);function runtimeRecord(input){try{return input!==null&&typeof input=="object"&&!Array.isArray(input)}catch{return!1}}function own(input,key){const descriptor=getOwnDataDescriptor(input,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Unsafe control option");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function optionalLegacy(input,key){try{return own(input,key)}catch{return}}function plain(input){if(!isPlainDataRecord(input))throw new TypeError("Expected plain control options");return input}function bool(input,key,fallback){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="boolean")throw new TypeError("Invalid boolean control option");return value}function number(input,key,fallback,maximum){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="number"||!Number.isFinite(value)||value<0||value>maximum)throw new RangeError("Invalid numeric control option");return value}function position(input,fallback){const value=own(input,"position");if(value===void 0)return fallback;if(!positions.has(value))throw new TypeError("Invalid control position");return value}const escapeText=value=>value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;");function attributionText(input){let total=0;const labels=[],text=value=>{if(typeof value!="string"||value.length>4096||(total+=value.length)>16384)throw new RangeError("Attribution text limit");return escapeText(value)},item=value=>{if(typeof value=="string"){const label2=text(value);return labels.push(label2),label2}const record=plain(value),label=text(own(record,"label")),raw=own(record,"url");if(typeof raw!="string"||raw.length>2048||/[\u0000-\u0020\u007f-\u009f]/.test(raw))throw new TypeError("Invalid attribution URL");const url=new URL(raw);if(url.protocol!=="http:"&&url.protocol!=="https:"||url.username||url.password||url.href.length>2048||(total+=url.href.length)>16384)throw new TypeError("Invalid attribution URL");const snapshot=Object.freeze({label,url:url.href});return labels.push(snapshot.label),`<a href="${escapeText(snapshot.url)}" target="_blank" rel="${resolveGuardedRel(void 0,"_blank")}">${snapshot.label}</a>`};let html;if(!Array.isArray(input))html=item(input);else{const length=own(input,"length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>32)throw new RangeError("Attribution count limit");const result=[];for(let index=0;index<length;index++)result.push(item(own(input,String(index))));html=Object.freeze(result)}return Object.freeze({html,text:Object.freeze(labels)})}function normalizeMapControlOptions(input){const controls=new Map,diagnostics=[],done=()=>Object.freeze({controls,diagnostics:Object.freeze(diagnostics.map(item=>Object.freeze(item)))});if(!runtimeRecord(input))return done();for(const kind of["navigation","scale","geolocate","attribution"])try{const value=kind==="navigation"||kind==="scale"?optionalLegacy(input,kind):own(input,kind);if(value===void 0||value===!1)continue;if(kind==="navigation"||kind==="scale"){if(value!==!0&&!runtimeRecord(value))continue;const entry2=value===!0?{}:value,fallback=kind==="navigation"?"top-right":"bottom-left",requested=optionalLegacy(entry2,"position"),corner2=positions.has(requested)?requested:fallback,unit=kind==="scale"?optionalLegacy(entry2,"unit")==="imperial"?"imperial":"metric":void 0;controls.set(kind,Object.freeze({kind,position:corner2,unit,options:Object.freeze(kind==="scale"?{unit}:{}),key:`${corner2}:${unit??""}`}));continue}const entry=value===!0?{}:plain(value),corner=position(entry,kind==="geolocate"?"top-right":"bottom-right");let options,attributionLabels;if(kind==="geolocate"){const rawPosition=own(entry,"positionOptions"),rawFit=own(entry,"fitBoundsOptions"),positionOptions=rawPosition===void 0?{}:plain(rawPosition),fit=rawFit===void 0?{}:plain(rawFit),showUserLocation=bool(entry,"showUserLocation",!0),showAccuracyCircle=bool(entry,"showAccuracyCircle",!0),zoomToUserAccuracy=own(entry,"zoomToUserAccuracy");if(zoomToUserAccuracy!==void 0&&typeof zoomToUserAccuracy!="boolean")throw new TypeError("Invalid zoom option");options=Object.freeze({trackUserLocation:bool(entry,"trackUserLocation",!1),showUserLocation,showAccuracyCircle:showUserLocation&&showAccuracyCircle,positionOptions:Object.freeze({enableHighAccuracy:bool(positionOptions,"enableHighAccuracy",!1),timeout:number(positionOptions,"timeout",6e3,864e5),maximumAge:number(positionOptions,"maximumAge",0,864e5)}),fitBoundsOptions:Object.freeze({maxZoom:number(fit,"maxZoom",15,24)}),...zoomToUserAccuracy===void 0?{}:{zoomToUserAccuracy}})}else{const compact=own(entry,"compact"),custom=own(entry,"customAttribution");if(compact!==void 0&&typeof compact!="boolean")throw new TypeError("Invalid attribution mode");const credits=custom===void 0?void 0:attributionText(custom);attributionLabels=credits?.text,options=Object.freeze({...compact===void 0?{}:{compact},...credits===void 0?{}:{customAttribution:credits.html}})}controls.set(kind,Object.freeze({kind,position:corner,unit:void 0,options,...attributionLabels?{attributionText:attributionLabels}:{},key:`${corner}:${JSON.stringify(options)}`}))}catch{diagnostics.push({kind,code:"invalid-options"})}return done()}function mapGeolocationErrorCode(code){return code===1?"permission-denied":code===2?"position-unavailable":code===3?"timeout":"unknown"}export{mapGeolocationErrorCode,normalizeMapControlOptions};
@@ -0,0 +1 @@
1
+ import{deepActiveElementIn}from"../../../internal/active-element.js";import{mapGeolocationErrorCode}from"./map-control-options.js";function geolocatedPosition(event){try{if(event===null||typeof event!="object")return{};const coords=event.coords;if(coords===null||typeof coords!="object")return{};const{longitude,latitude,accuracy}=coords;return typeof longitude!="number"||typeof latitude!="number"||typeof accuracy!="number"||!Number.isFinite(longitude)||!Number.isFinite(latitude)||!Number.isFinite(accuracy)||Math.abs(longitude)>180||Math.abs(latitude)>90||accuracy<0?{}:{lngLat:Object.freeze([longitude,latitude]),accuracy}}catch{return{}}}class MapControlsLifecycle{constructor(load){this.load=load,this.generation=0,this.entries=new Map}async sync(map,desired,context){const generation=++this.generation,retired=[];for(const[kind,entry]of this.entries){const next=desired.get(kind);entry.map===map&&entry.installed&&next&&(next.key===entry.options.key||entry.root&&map.controlContainer&&JSON.stringify(next.options)===JSON.stringify(entry.options.options))?(entry.context=context,entry.options=next):(this.entries.delete(kind),retired.push(entry))}for(const entry of retired)this.retire(entry);if(generation!==this.generation||!this.validContext(context)||generation!==this.generation)return;const pending=[];for(const[kind,options]of desired){if(generation!==this.generation)break;if(this.entries.has(kind))continue;const entry={map,options,context,installed:!1,attempted:!1,adding:!1,subscribing:!1,removed:!1,retired:!1,subscriptions:[]};this.entries.set(kind,entry),pending.push(entry)}const loaded=await Promise.all(pending.map(async entry=>{try{return await this.load(entry.options.kind)}catch{return}}));if(generation!==this.generation||!this.validContext(context))return;const constructors=new Map(pending.map((entry,index)=>[entry,loaded[index]])),priority=["navigation","scale","geolocate","attribution"];for(const corner of["top-left","top-right","bottom-left","bottom-right"]){const order=corner.startsWith("bottom")?[...priority].reverse():priority;for(const kind of order){if(generation!==this.generation||!this.validContext(context))return;const entry=this.entries.get(kind);entry?.options.position===corner&&constructors.has(entry)&&this.install(entry,constructors.get(entry))}}for(const corner of["top-left","top-right","bottom-left","bottom-right"]){if(generation!==this.generation||!this.validContext(context))return;const entries=priority.map(kind=>this.entries.get(kind)).filter(entry=>entry!==void 0&&entry.installed&&entry.options.position===corner);for(let index=entries.length-1;index>=0;index--){const entry=entries[index];if(generation!==this.generation||!this.current(entry))return;try{const parent=map.controlContainer?.(corner);if(generation!==this.generation||!this.current(entry))return;if(!parent||!entry.root)continue;const before=entries.slice(index+1).find(next=>next.root?.parentNode===parent)?.root??null,root=entry.root;if(root.parentNode===parent&&(before?root.nextSibling===before:root.nextSibling===null))continue;const active=root.getRootNode().activeElement,focus=active instanceof HTMLElement&&root.contains(active)?active:void 0;if(generation!==this.generation||!this.current(entry))return;const document=root.ownerDocument;let focusTransferred=!1;const trackFocus=()=>{focusTransferred=!0};focus&&document.addEventListener("focus",trackFocus,!0);try{parent.insertBefore(root,before)}finally{focus&&document.removeEventListener("focus",trackFocus,!0)}if(generation!==this.generation||!this.current(entry))return;const remaining=deepActiveElementIn(document),lostFocus=remaining===null||remaining===document.body||remaining===document.documentElement;if(focus?.isConnected&&root.contains(focus)&&focus.ownerDocument===document&&!focusTransferred&&lostFocus&&focus.focus({preventScroll:!0}),generation!==this.generation||!this.current(entry))return}catch{if(generation===this.generation&&this.current(entry))try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}}}dispose(){this.generation+=1;const retired=[...this.entries.values()];this.entries.clear();for(const entry of retired)this.retire(entry)}validContext(context){try{return context.isCurrent()}catch{return!1}}current(entry){const owned=()=>!entry.retired&&this.entries.get(entry.options.kind)===entry;return owned()&&this.validContext(entry.context)&&owned()}install(entry,Constructor){try{if(!this.current(entry)){this.release(entry);return}if(typeof Constructor!="function")throw new Error("Map control is unavailable.");const control=new Constructor(entry.options.options);if(control===null||typeof control!="object"&&typeof control!="function")throw new Error("Map control is unavailable.");if(entry.control=control,!this.current(entry)){this.release(entry);return}if(entry.options.kind==="geolocate"){if(typeof entry.control.on!="function"||typeof entry.control.off!="function")throw new Error("Map control events are unavailable.");if(this.subscribe(entry,"error",event=>{if(!this.current(entry))return;let code;try{event!==null&&typeof event=="object"&&(code=event.code)}catch{}this.current(entry)&&entry.context.onEvent({kind:"geolocate-error",code:mapGeolocationErrorCode(code)})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"outofmaxbounds",()=>{this.current(entry)&&entry.context.onEvent({kind:"geolocate-out-of-bounds",code:"out-of-bounds"})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"geolocate",event=>{if(!this.current(entry))return;const position=geolocatedPosition(event);this.current(entry)&&entry.context.onEvent(Object.freeze({kind:"geolocate-success",...position}))}),!this.current(entry)){this.release(entry);return}}const onAdd=entry.control.onAdd;if(!this.current(entry)){this.release(entry);return}const descriptor=Object.getOwnPropertyDescriptor(entry.control,"onAdd");if(!this.current(entry)){this.release(entry);return}try{if(onAdd&&(entry.control.onAdd=function(...args){const root=onAdd.apply(this,args);return entry.root=root,root}),!this.current(entry)){this.release(entry);return}entry.attempted=!0,entry.adding=!0,entry.map.addControl(entry.control,entry.options.position)}finally{try{onAdd&&(descriptor?Object.defineProperty(entry.control,"onAdd",descriptor):delete entry.control.onAdd)}finally{entry.adding=!1,entry.retired&&this.retire(entry)}}if(!this.current(entry)){this.release(entry);return}entry.installed=!0}catch{const report=this.current(entry),generation=this.generation;if(this.release(entry),report&&generation===this.generation&&this.validContext(entry.context)&&generation===this.generation)try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}subscribe(entry,type,callback){entry.subscriptions.push({type,callback}),entry.subscribing=!0;try{entry.control.on(type,callback)}finally{entry.subscribing=!1,entry.retired&&this.retire(entry)}}release(entry){this.entries.get(entry.options.kind)===entry&&this.entries.delete(entry.options.kind),this.retire(entry)}retire(entry){if(entry.retired=!0,entry.subscribing)return;const subscriptions=entry.subscriptions.splice(0);for(const{type,callback}of subscriptions)try{entry.control?.off?.(type,callback)}catch{}if(!(!entry.attempted||entry.adding||entry.removed||!entry.control)){entry.removed=!0;try{entry.map.removeControl(entry.control)}catch{}}}}export{MapControlsLifecycle};
@@ -0,0 +1 @@
1
+ class MapCursorOwner{constructor(){this.baseline="",this.baselinePriority=""}set(canvas,mode){if(this.canvas!==canvas&&(this.clear(),this.canvas=canvas),!canvas)return;const current=canvas.style.getPropertyValue("cursor");if((this.written===void 0||current!==this.written||canvas.style.getPropertyPriority("cursor")!=="")&&(this.baseline=current,this.baselinePriority=canvas.style.getPropertyPriority("cursor")),!mode){this.clear();return}this.written=mode==="hover"?"pointer":"crosshair",canvas.style.setProperty("cursor",this.written)}clear(){const canvas=this.canvas,written=this.written;this.canvas=void 0,this.written=void 0,canvas&&written!==void 0&&canvas.style.getPropertyValue("cursor")===written&&canvas.style.getPropertyPriority("cursor")===""&&(this.baseline?canvas.style.setProperty("cursor",this.baseline,this.baselinePriority):canvas.style.removeProperty("cursor"))}}export{MapCursorOwner};
@@ -0,0 +1,40 @@
1
+ import{type CanonicalMapVectorStyle,type LyraMapVectorPaint,type LyraMapVectorLayout,type LyraMapVectorStyleExpression}from'./map-vector-style.js';import{type OwnDataDescriptorResult}from'../../../internal/data-descriptors.js';import{type LyraMapInteractionOptions,type CanonicalMapInteraction}from'./map-interaction-options.js';import type{LyraMapOverlayLayer,LyraMapOverlaySource}from'./map-overlay-admission.js';
2
+ /** Four native corners, ordered top-left, top-right, bottom-right, bottom-left. */
3
+ export type LyraMapSourceCoordinates=readonly[readonly[number,number],readonly[number,number],readonly[number,number],readonly[number,number]];export type LyraMapLabelValue=null|boolean|number|string|readonly LyraMapLabelValue[]|{readonly[key:string]:LyraMapLabelValue;};
4
+ /** Physical native text anchor, independent of the surrounding UI direction. */
5
+ export type LyraMapLabelAnchor='center'|'left'|'right'|'top'|'bottom'|'top-left'|'top-right'|'bottom-left'|'bottom-right';
6
+ /** Text labels require a style with a glyph provider. Set exactly one of field or expression. */
7
+ export interface LyraMapLabelOptions{readonly field?:string;readonly expression?:readonly LyraMapLabelValue[];readonly placement?:'point'|'line';
8
+ /** Physical native anchor. Omission preserves the native center default. */
9
+ readonly anchor?:LyraMapLabelAnchor;
10
+ /** Native text-size ems; positive x is right and y down in label coordinates. Not mirrored in RTL.
11
+ * Each finite coordinate is within [-16,16]. Omission preserves native [0,0]. */
12
+ readonly offset?:readonly[number,number];readonly size?:number;readonly color?:string;readonly haloColor?:string;readonly haloWidth?:number;readonly minZoom?:number;readonly font?:readonly string[];readonly allowOverlap?:boolean;readonly ignorePlacement?:boolean;}export interface LyraMapTileSource{readonly url?:string;readonly tiles?:readonly string[];readonly minZoom?:number;readonly maxZoom?:number;readonly attribution?:string;readonly scheme?:'xyz'|'tms';}export interface LyraMapExternalDataLayerOptions extends LyraMapInteractionOptions{readonly sourceId:string;
13
+ /** Native layer insertion target; a missing target appends. */
14
+ readonly before?:string;readonly minZoom?:number;readonly maxZoom?:number;readonly opacity?:number;
15
+ /** Whole-layer category toggled by hiddenCategories and an authored legend row. */
16
+ readonly category?:string;}export interface LyraMapVectorDataLayer extends LyraMapExternalDataLayerOptions{readonly kind:'vector';readonly source:LyraMapTileSource;readonly sourceLayer:string;readonly render:'line'|'circle'|'fill'|'symbol';readonly color?:string;readonly strokeColor?:string;readonly width?:number;readonly radius?:number;readonly categoryField?:string;
17
+ /** Render-specific bounded paint; explicit values override the flat defaults. Row opacity remains separate. */
18
+ readonly paint?:LyraMapVectorPaint;
19
+ /** Render-specific bounded layout. Icon-only symbols do not require glyphs. */
20
+ readonly layout?:LyraMapVectorLayout;
21
+ /** Bounded boolean expression applied to the primary layer and its optional label. */
22
+ readonly filter?:LyraMapVectorStyleExpression;readonly label?:LyraMapLabelOptions;}export interface LyraMapRasterDataLayer extends LyraMapExternalDataLayerOptions{readonly kind:'raster';readonly source:LyraMapTileSource&{readonly tileSize?:number;};}
23
+ /** Interactive hits use the four-corner footprint, independently of pixel alpha. Hits expose sourceId, without a feature ID or sourceLayer. */
24
+ export interface LyraMapImageDataLayer extends LyraMapExternalDataLayerOptions{readonly kind:'image';
25
+ /** HTTP(S), strict base64 PNG/JPEG/WebP data URL, or same-origin blob URL. Local images are validated and bounded before use. */
26
+ readonly url:string;readonly coordinates:LyraMapSourceCoordinates;}
27
+ /** Interactive hits use the four-corner footprint; coordinate updates move it with the canvas. No per-pixel or feature-state identity is implied. */
28
+ export interface LyraMapCanvasDataLayer extends LyraMapExternalDataLayerOptions{readonly kind:'canvas';readonly canvas:HTMLCanvasElement;readonly coordinates:LyraMapSourceCoordinates;readonly animate?:boolean;
29
+ /** Nonnegative safe integer; change after drawing into the same canvas. Defaults to zero. */
30
+ readonly redrawRevision?:number;}export type LyraMapExternalDataLayer=LyraMapVectorDataLayer|LyraMapRasterDataLayer|LyraMapImageDataLayer|LyraMapCanvasDataLayer;export interface CanonicalMapLabel{readonly expression:readonly LyraMapLabelValue[];readonly placement:'point'|'line';readonly anchor?:LyraMapLabelAnchor;readonly offset?:readonly[number,number];readonly size:number;readonly color?:string;readonly haloColor?:string;readonly haloWidth:number;readonly minZoom:number;readonly font?:readonly string[];readonly allowOverlap:boolean;readonly ignorePlacement:boolean;}export interface CanonicalMapExternalLayer extends CanonicalMapInteraction{readonly style?:CanonicalMapVectorStyle;readonly sourceId:string;readonly kind:LyraMapExternalDataLayer['kind'];readonly source:Readonly<Record<string,unknown>>;readonly redrawRevision?:number;readonly sourceLayer?:string;readonly render:'line'|'circle'|'fill'|'symbol'|'raster';readonly before?:string;readonly minZoom:number;readonly maxZoom:number;readonly opacity:number;readonly category?:string;readonly categoryField?:string;readonly color?:string;readonly strokeColor?:string;readonly width:number;readonly radius:number;readonly label?:CanonicalMapLabel;}export interface CanonicalMapRowPlacement{readonly before?:string;readonly minZoom:number;readonly maxZoom:number;readonly requested:boolean;}
31
+ /** Own-data projection shared by legacy GeoJSON rows and explicit source families. */
32
+ export declare function projectMapRowPlacement(value:unknown):CanonicalMapRowPlacement|undefined;
33
+ /** Bounded native expression data, with no accessors, executable values, cycles or handles. */
34
+ export declare function projectMapLabelOptions(value:unknown):CanonicalMapLabel|undefined;export type MapDataLayerModel<T> ={readonly ok:true;readonly geojson:readonly T[];readonly external:readonly CanonicalMapExternalLayer[];}|{readonly ok:false;};
35
+ /** Mixed first-100 admission; legacy row validation remains with its existing projector. */
36
+ export declare function projectMapDataLayerModel<T extends{readonly sourceId:string;}>(value:unknown,options:{readonly baseUrl:string;readonly ownerOrigin?:string;readonly projectGeoJson:(row:unknown,kind:OwnDataDescriptorResult)=>T|undefined;}):MapDataLayerModel<T>;export declare function buildMapLabelLayer(id:string,source:string,label:CanonicalMapLabel,color:(value:string|undefined)=>string):LyraMapOverlayLayer['layer'];
37
+ /** Native source/layer descriptors for the separate generated external-resource owner. */
38
+ export declare function buildMapExternalLayers(rows:readonly CanonicalMapExternalLayer[],context:{readonly nativeId:(row:CanonicalMapExternalLayer)=>string;readonly color:(value:string|undefined)=>string;
39
+ /** Strict resolution for authored typed color leaves; invalid colors must throw. */
40
+ readonly styleColor?:(value:string)=>string;readonly hidden:ReadonlySet<string>;readonly glyphs:boolean;readonly mutedOpacity?:number;}):{readonly sources:readonly LyraMapOverlaySource[];readonly layers:readonly LyraMapOverlayLayer[];readonly hits:ReadonlyMap<string,{readonly sourceId:string;readonly sourceLayer?:string;}>;};
@@ -0,0 +1 @@
1
+ import{projectMapVectorStyle,resolveMapVectorStyle}from"./map-vector-style.js";import{projectMapLocalImageUrl}from"./map-local-image-url.js";import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,readOwnArrayLength,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{projectMapInteractionOptions}from"./map-interaction-options.js";import{safeFetchUrl}from"../../../internal/safe-url.js";const EXTERNAL_KINDS=new Set(["vector","raster","image","canvas"]),COMMON_KEYS=["interactive","priority","kind","sourceId","before","minZoom","maxZoom","opacity","category"],TILE_TOKENS=new Set(["z","x","y","ratio","quadkey","bbox-epsg-3857","prefix"]);function invalid(){throw new Error("Invalid map data layer.")}function own(value,key){const descriptor=getOwnDataDescriptor(value,key);return descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?invalid():descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function record(value,keys,knownKind){if(!isPlainDataRecord(value))return invalid();const fields=Reflect.ownKeys(value);if(fields.length>keys.length||fields.some(key=>typeof key!="string"||!keys.includes(key)))return invalid();for(const key of fields)(key!=="kind"||knownKind===void 0)&&own(value,key);return value}function text(value,limit,trim=!0){return typeof value!="string"||value.length>limit||trim&&!value.trim()?invalid():trim?value.trim():value}function id(value){const result=text(value,128);return["__proto__","constructor","prototype"].includes(result)?invalid():result}function optionalText(value,limit=256){return value===void 0?void 0:text(value,limit)}function numeric(value,fallback,min,max){return value===void 0?fallback:typeof value!="number"||!Number.isFinite(value)?invalid():Math.min(max,Math.max(min,value))}function boolean(value,fallback){return value===void 0?fallback:typeof value=="boolean"?value:invalid()}function dense(value,limit){if(!Array.isArray(value))return invalid();const prototype=Object.getPrototypeOf(value),constructor=prototype&&Object.getOwnPropertyDescriptor(prototype,"constructor");if(!constructor||!Object.hasOwn(constructor,"value")||typeof constructor.value!="function"||Function.prototype.toString.call(constructor.value)!==Function.prototype.toString.call(Array)||Object.getOwnPropertyDescriptor(constructor.value,"prototype")?.value!==prototype)return invalid();const length=readOwnArrayLength(value);if(length===void 0||length>limit||Reflect.ownKeys(value).length!==length+1)return invalid();const output=[];for(let index=0;index<length;index++){const descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)return invalid();output.push(descriptor.value)}return output}function coordinates(value){const corners=dense(value,4);return corners.length!==4?invalid():Object.freeze(corners.map(corner=>{const pair=dense(corner,2);return pair.length!==2||typeof pair[0]!="number"||!Number.isFinite(pair[0])||Math.abs(pair[0])>180||typeof pair[1]!="number"||!Number.isFinite(pair[1])||Math.abs(pair[1])>90?invalid():Object.freeze([pair[0],pair[1]])}))}function canvas(value){try{const read=typeof HTMLCanvasElement>"u"?void 0:Object.getOwnPropertyDescriptor(HTMLCanvasElement.prototype,"width")?.get;if(read&&typeof Reflect.apply(read,value,[])=="number")return value}catch{}return invalid()}function url(value,base,tiled=!1){const input=text(value,4096),marker="lyratileplaceholder";if(input.toLowerCase().includes(marker)||base.toLowerCase().includes(marker))return invalid();const tokens=[],substituted=input.replace(/\{([^{}]+)\}/gu,(_match,token)=>!tiled||!TILE_TOKENS.has(token)?invalid():(tokens.push(token),`${marker}${tokens.length-1}token`));if(/[{}]/u.test(substituted)||safeFetchUrl(substituted)===null)return invalid();const parsed=new URL(substituted,base);if(!["http:","https:"].includes(parsed.protocol)||parsed.username||parsed.password)return invalid();let result=parsed.href;for(const[index,token]of tokens.entries()){const placeholder=`${marker}${index}token`;if(result.split(placeholder).length!==2)return invalid();result=result.replace(placeholder,`{${token}}`)}return result.length<=4096?result:invalid()}function zoomRange(value){const authoredMin=own(value,"minZoom"),authoredMax=own(value,"maxZoom");if(typeof authoredMin=="number"&&typeof authoredMax=="number"&&authoredMin>authoredMax)return invalid();const min=numeric(authoredMin,0,0,24),max=numeric(authoredMax,24,0,24);return min<=max?[min,max]:invalid()}function projectMapRowPlacement(value){try{if(value===null||typeof value!="object")return;const[minZoom,maxZoom]=zoomRange(value),before=own(value,"before"),requested=["before","minZoom","maxZoom"].some(key=>getOwnDataDescriptor(value,key)!==MISSING_OWN_DATA_DESCRIPTOR);return Object.freeze({minZoom,maxZoom,requested,...before===void 0?{}:{before:id(before)}})}catch{return}}function tileSource(value,kind,base){const source=record(value,["url","tiles","minZoom","maxZoom","attribution","scheme",...kind==="raster"?["tileSize"]:[]]),sourceUrl=own(source,"url"),tiles=own(source,"tiles");if(sourceUrl===void 0==(tiles===void 0))return invalid();const[minzoom,maxzoom]=zoomRange(source),scheme=own(source,"scheme");if(scheme!==void 0&&scheme!=="xyz"&&scheme!=="tms")return invalid();const attribution=own(source,"attribution"),native={type:kind,...own(source,"minZoom")!==void 0?{minzoom}:{},...own(source,"maxZoom")!==void 0?{maxzoom}:{},...scheme!==void 0?{scheme}:{}};if(sourceUrl!==void 0)native.url=url(sourceUrl,base);else{const entries=dense(tiles,16);if(!entries.length)return invalid();native.tiles=Object.freeze(entries.map(entry=>url(entry,base,!0)))}return attribution!==void 0&&(native.attribution=text(attribution,4096,!1).replace(/[&<>"']/gu,character=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[character])),kind==="raster"&&own(source,"tileSize")!==void 0&&(native.tileSize=numeric(own(source,"tileSize"),512,1,4096)),Object.freeze(native)}function projectMapLabelOptions(value){try{const input=record(value,["field","expression","placement","anchor","offset","size","color","haloColor","haloWidth","minZoom","font","allowOverlap","ignorePlacement"]),field=own(input,"field"),expression=own(input,"expression");if(field===void 0==(expression===void 0))return;let count=0,bytes=0;const path=new WeakSet,encoder=new TextEncoder,clone=(entry,depth)=>{if(++count>4096||depth>12)return invalid();if(entry===null||typeof entry=="boolean")return entry;if(typeof entry=="number")return Number.isFinite(entry)?entry:invalid();if(typeof entry=="string")return entry.length>65536-bytes?invalid():(bytes+=encoder.encode(entry).length,bytes<=65536?entry:invalid());if(typeof entry!="object"||path.has(entry))return invalid();path.add(entry);try{if(Array.isArray(entry))return Object.freeze(dense(entry,4096).map(child=>clone(child,depth+1)));if(!isPlainDataRecord(entry))return invalid();const keys=Reflect.ownKeys(entry);if(keys.length>4096)return invalid();const result=Object.create(null);for(const key of keys){if(typeof key!="string"||["__proto__","prototype","constructor"].includes(key))return invalid();clone(key,depth+1),result[key]=clone(own(entry,key),depth+1)}return Object.freeze(result)}finally{path.delete(entry)}},projected=field!==void 0?Object.freeze(["get",text(field,128)]):clone(expression,0);if(!Array.isArray(projected)||!projected.length||typeof projected[0]!="string")return;const authoredPlacement=own(input,"placement"),placement=authoredPlacement===void 0?"point":authoredPlacement;if(placement!=="point"&&placement!=="line")return;const anchor=own(input,"anchor");if(Object.hasOwn(input,"anchor")&&(typeof anchor!="string"||!["center","left","right","top","bottom","top-left","top-right","bottom-left","bottom-right"].includes(anchor)))return;const offsetInput=own(input,"offset"),offset=Object.hasOwn(input,"offset")?dense(offsetInput,2):void 0;if(offset&&(offset.length!==2||offset.some(value2=>typeof value2!="number"||!Number.isFinite(value2)||Math.abs(value2)>16)))return;const size=numeric(own(input,"size"),12,1,128),fonts=own(input,"font"),font=fonts===void 0?void 0:Object.freeze(dense(fonts,8).map(entry=>text(entry,128)));return font?.length===0?void 0:Object.freeze({expression:projected,placement,size,...anchor===void 0?{}:{anchor},...offset===void 0?{}:{offset:Object.freeze([offset[0],offset[1]])},color:optionalText(own(input,"color")),haloColor:optionalText(own(input,"haloColor")),haloWidth:numeric(own(input,"haloWidth"),0,0,size/4),minZoom:numeric(own(input,"minZoom"),0,0,24),font,allowOverlap:boolean(own(input,"allowOverlap"),!1),ignorePlacement:boolean(own(input,"ignorePlacement"),!1)})}catch{return}}function external(value,base,ownerOrigin,kind){if(!isPlainDataRecord(value)||typeof kind!="string"||!EXTERNAL_KINDS.has(kind))return invalid();const extra=kind==="vector"?["source","sourceLayer","render","color","strokeColor","width","radius","categoryField","label","paint","layout","filter"]:kind==="raster"?["source"]:kind==="image"?["url","coordinates"]:["canvas","coordinates","animate","redrawRevision"],input=record(value,[...COMMON_KEYS,...extra],kind),[minZoom,maxZoom]=zoomRange(input),source=kind==="vector"||kind==="raster"?tileSource(own(input,"source"),kind,base):Object.freeze({type:kind,coordinates:coordinates(own(input,"coordinates")),...kind==="image"?{url:projectMapLocalImageUrl(own(input,"url"),ownerOrigin)?.url??url(own(input,"url"),base)}:{canvas:canvas(own(input,"canvas")),animate:boolean(own(input,"animate"),!0)}}),authoredRevision=kind==="canvas"?own(input,"redrawRevision"):void 0,revision=kind==="canvas"?authoredRevision===void 0?0:authoredRevision:void 0;if(revision!==void 0&&(typeof revision!="number"||!Number.isSafeInteger(revision)||revision<0))return invalid();const render=kind==="vector"?own(input,"render"):"raster";if(render!=="line"&&render!=="circle"&&render!=="fill"&&render!=="symbol"&&render!=="raster"||kind==="vector"&&render==="raster")return invalid();const labelInput=own(input,"label"),label=labelInput===void 0?void 0:projectMapLabelOptions(labelInput);if(labelInput!==void 0&&!label)return invalid();const style=kind==="vector"&&render!=="raster"?projectMapVectorStyle({render,hasLabel:label!==void 0,...Object.hasOwn(input,"paint")?{paint:own(input,"paint")}:{},...Object.hasOwn(input,"layout")?{layout:own(input,"layout")}:{},...Object.hasOwn(input,"filter")?{filter:own(input,"filter")}:{}}):void 0;return kind==="vector"&&!style||label&&Math.max(minZoom,label.minZoom)>maxZoom?invalid():Object.freeze({...projectMapInteractionOptions(input),sourceId:id(own(input,"sourceId")),kind,source,...revision===void 0?{}:{redrawRevision:revision},sourceLayer:kind==="vector"?text(own(input,"sourceLayer"),128):void 0,render,before:own(input,"before")===void 0?void 0:id(own(input,"before")),minZoom,maxZoom,opacity:numeric(own(input,"opacity"),1,0,1),category:optionalText(own(input,"category"),128),categoryField:optionalText(own(input,"categoryField"),128),color:optionalText(own(input,"color")),strokeColor:optionalText(own(input,"strokeColor")),width:numeric(own(input,"width"),2,0,100),radius:numeric(own(input,"radius"),4,0,200),label,...style?{style}:{}})}function projectMapDataLayerModel(value,options){let requestedExternal=!1,invalidPlacement=!1;try{const geojson=[],sources=[],seen=new Set;if(!Array.isArray(value))return Object.freeze({ok:!0,geojson:Object.freeze(geojson),external:Object.freeze(sources)});const length=readOwnArrayLength(value);if(length===void 0)return{ok:!0,geojson:Object.freeze([]),external:Object.freeze([])};for(let index=0;index<Math.min(length,100);index++){const entry=getOwnDataDescriptor(value,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const row=entry.value,descriptor=row!==null&&typeof row=="object"?getOwnDataDescriptor(row,"kind"):MISSING_OWN_DATA_DESCRIPTOR,kind=descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:descriptor.value;if(typeof kind=="string"&&EXTERNAL_KINDS.has(kind)){requestedExternal=!0;const layer=external(row,options.baseUrl,options.ownerOrigin??"null",kind);if(seen.has(layer.sourceId))continue;if(sources.length>=32)return{ok:!1};seen.add(layer.sourceId),sources.push(layer)}else{if(row!==null&&typeof row=="object"&&["before","minZoom","maxZoom"].some(key=>getOwnDataDescriptor(row,key)!==MISSING_OWN_DATA_DESCRIPTOR)&&!projectMapRowPlacement(row))return invalidPlacement=!0,{ok:!1};const layer=options.projectGeoJson(row,descriptor);if(!layer||seen.has(layer.sourceId))continue;seen.add(layer.sourceId),geojson.push(layer)}}return Object.freeze({ok:!0,geojson:Object.freeze(geojson),external:Object.freeze(sources)})}catch{return requestedExternal||invalidPlacement?{ok:!1}:{ok:!0,geojson:Object.freeze([]),external:Object.freeze([])}}}function buildMapLabelLayer(id2,source,label,color){return{id:id2,type:"symbol",source,minzoom:label.minZoom,layout:{"text-field":label.expression,"text-size":label.size,"symbol-placement":label.placement,"text-allow-overlap":label.allowOverlap,"text-ignore-placement":label.ignorePlacement,...label.font?{"text-font":label.font}:{},...label.anchor===void 0?{}:{"text-anchor":label.anchor},...label.offset===void 0?{}:{"text-offset":label.offset}},paint:{"text-color":color(label.color),"text-halo-color":color(label.haloColor),"text-halo-width":label.haloWidth}}}function buildMapExternalLayers(rows,context){const sources=[],layers=[],hits=new Map,muted=numeric(context.mutedOpacity,.15,0,1);for(const row of rows){if(row.label&&!context.glyphs)throw new Error("Map labels require a glyph provider.");const sourceId=context.nativeId(row);sources.push({id:sourceId,source:row.source});const opacity=row.category&&context.hidden.has(row.category)?row.opacity*muted:row.opacity,alpha=!(row.category&&context.hidden.has(row.category))&&row.categoryField&&context.hidden.size?["case",["in",["to-string",["get",row.categoryField]],["literal",[...context.hidden]]],opacity*muted,opacity]:opacity,sourceLayer=row.sourceLayer?{"source-layer":row.sourceLayer}:{},style=row.style?resolveMapVectorStyle(row.style,context.styleColor??(()=>{throw new Error("Strict map color resolution is unavailable.")})):void 0,push=layer=>{const filter=style?.filter,filtered=filter===void 0?layer:{...layer,filter:layer.filter===void 0?filter:["all",layer.filter,filter]};layers.push({layer:{...filtered,...sourceLayer,minzoom:Math.max(row.minZoom,typeof layer.minzoom=="number"?layer.minzoom:0),maxzoom:row.maxZoom},...row.before?{before:row.before}:{}}),row.sourceLayer&&hits.set(layer.id,{sourceId:row.sourceId,sourceLayer:row.sourceLayer})},color=context.color(row.color),stroke=context.color(row.strokeColor??row.color);if(row.render!=="symbol"){const paint=row.render==="line"?{"line-color":color,"line-width":row.width,"line-opacity":alpha}:row.render==="circle"?{"circle-color":color,"circle-radius":row.radius,"circle-stroke-color":stroke,"circle-stroke-width":row.width,"circle-opacity":alpha,"circle-stroke-opacity":alpha}:row.render==="fill"?{"fill-color":color,"fill-outline-color":stroke,"fill-opacity":alpha}:{"raster-opacity":opacity};if(push({id:`${sourceId}-render`,type:row.render,source:sourceId,paint:style?{...paint,...style.paint}:paint,...style&&Object.keys(style.layout).length?{layout:style.layout}:{}}),(row.kind==="image"||row.kind==="canvas")&&row.interactive){const corners=row.source.coordinates,ring=Object.freeze([...corners.map(point=>Object.freeze([...point])),Object.freeze([...corners[0]])]),geometry=Object.freeze({type:"Polygon",coordinates:Object.freeze([ring])}),feature=Object.freeze({type:"Feature",properties:Object.freeze({}),geometry}),hitSource=`${sourceId}-hit-source`,hitLayer=`${sourceId}-hit`;sources.push({id:hitSource,source:Object.freeze({type:"geojson",data:feature})}),push({id:hitLayer,type:"fill",source:hitSource,paint:{"fill-opacity":0,"fill-antialias":!1}}),hits.set(hitLayer,Object.freeze({sourceId:row.sourceId}))}}if(row.render==="symbol"){const icon=style?.layout["icon-image"]!==void 0,layer=row.label?buildMapLabelLayer(`${sourceId}-render`,sourceId,row.label,context.color):{id:`${sourceId}-render`,type:"symbol",source:sourceId};push({...layer,layout:{...layer.layout,...icon?{"icon-size":1,"icon-allow-overlap":!1,"icon-ignore-placement":!1}:{},...style?.layout},paint:{...layer.paint,...style?.paint,...row.label?{"text-opacity":alpha}:{},...icon?{"icon-opacity":alpha}:{}}})}else if(row.label){const layer=buildMapLabelLayer(`${sourceId}-label`,sourceId,row.label,context.color);push({...layer,paint:{...layer.paint,"text-opacity":alpha}})}if(layers.length>128)throw new Error("Map data layer limit exceeded.")}return{sources:Object.freeze(sources),layers:Object.freeze(layers),hits}}export{buildMapExternalLayers,buildMapLabelLayer,projectMapDataLayerModel,projectMapLabelOptions,projectMapRowPlacement};
@@ -0,0 +1 @@
1
+ import{activateOverlay}from"../../../internal/overlay-manager.js";import{acquireMapDrawingGesture}from"./map-drawing-gesture.js";import{acquireMapDrawingPan}from"./map-drawing-pan.js";import{MapDrawingPointer}from"./map-drawing-pointer.js";import{MapDrawing,measureDrawing}from"./map-drawing.js";import{mapCoordinates,mapOwnValue}from"./map-readers.js";import{snapshotMapOwnedFeatureInput}from"./map-owned-feature-input.js";import{MapOwnedFeatures}from"./map-owned-features.js";const CLOSE_DISTANCE=12;class MapDrawingController{constructor(host){this.host=host,this.started=!1,this.editingState=!1,this.handlesState=[],this.labelsState=[],this.selectedState=0,this.dispatchingState=!1,this.editAdmission=!1,this.editCancelled=!1,this.resourceEpoch=0,this.idCounter=0,this.resourcesPending=!1,this.resourceWork=Promise.resolve()}get active(){return this.session!==void 0}get snapshot(){return this.snapshotState}get editing(){return this.editingState}get handles(){return this.handlesState}get labels(){return this.labelsState}get selected(){return this.selectedState}get dispatching(){return this.dispatchingState}get pending(){return this.resourcesPending}get work(){return this.resourceWork}get sourceId(){return this.source}ownsLayer(id){return this.features?.ownsLayer(id)===!0}consumeClick(){return this.pointer?.consumeClick()===!0}begin(event,index){this.pointer?.begin(event,index)}select(index){index!==this.selectedState&&(this.selectedState=index,this.host.changed())}setSnapshot(value){value!==this.snapshotState&&(this.snapshotState=value,this.host.changed())}setEditing(value){value!==this.editingState&&(this.editingState=value,this.host.changed())}setHandles(value){value!==this.handlesState&&(this.handlesState=value,this.host.changed())}edit(snapshot){if(this.editAdmission)return!1;this.editCancelled=!1,this.editAdmission=!0;try{return this.admitEdit(snapshot)}finally{this.editAdmission=!1}}admitEdit(snapshot){const host=this.host,element=host.element,authoredStyle=element.mapStyle,authoredMode=element.drawMode,previous=this.session,map=host.map(),[style,connection]=host.generations(),epoch=host.epoch();if(!map||!host.styleLoaded()||!host.usable()||element.pickMode||!host.actionAllowed()||previous&&this.completing!==previous||this.dispatchingState&&(!previous||this.completing!==previous))return!1;const engine=()=>{const[s,c]=host.generations();return host.map()===map&&s===style&&c===connection},current=()=>engine()&&host.epoch()===epoch&&!this.editCancelled&&this.session===previous&&element.mapStyle===authoredStyle&&element.drawMode===authoredMode&&!element.pickMode&&host.actionAllowed();let candidate;try{const phase=mapOwnValue(snapshot,"phase");if(!current()||phase!=="completed")return!1;const mode=mapOwnValue(snapshot,"mode");if(!current()||mode!=="line"&&mode!=="polygon")return!1;const vertices=mapOwnValue(snapshot,"vertices");if(!current()||!Array.isArray(vertices))return!1;const length=mapOwnValue(vertices,"length");if(!current()||typeof length!="number"||!Number.isSafeInteger(length)||length<2||length>512)return!1;candidate=new MapDrawing(mode);for(let index=0;index<length;index++){const point=mapOwnValue(vertices,String(index));if(!current())return!1;const result=candidate.add(point);if(!current()||!result.accepted)return!1}if(!candidate.complete().accepted||!current())return!1}catch{return!1}previous&&this.clear();const admittedEpoch=host.epoch(),owns=()=>engine()&&host.epoch()===admittedEpoch&&!this.editCancelled&&element.mapStyle===authoredStyle&&(!this.session||this.session===candidate)&&!element.pickMode&&element.drawMode==="none";if(!owns()||!host.actionAllowed())return!1;const sameEngine=()=>host.map()===map&&host.generations()[1]===connection,lease=acquireMapDrawingGesture(map,{current:()=>sameEngine()&&host.epoch()===admittedEpoch&&(!this.session||this.session===candidate)});return!lease.accepted||!owns()||!host.actionAllowed()?(lease.release(),!1):(this.release=lease.release,this.session=candidate,this.setEditing(!0),this.started=!0,this.select(0),this.setSnapshot(candidate.snapshot()),host.clearError(),this.sync(),this.renderResources(),this.session===candidate)}undo(){const session=this.session;if(!session||this.dispatchingState||!this.host.interactionAllowed())return!1;const result=session.undo();return result.accepted?(this.setSnapshot(result.state),this.host.clearError(),this.emitChange(session),this.session===session&&this.snapshotState===result.state&&this.renderResources(),!0):!1}complete(){const session=this.session;if(!session||this.dispatchingState||!this.host.actionAllowed())return!1;const result=this.editingState?{accepted:!0,state:session.snapshot(),error:void 0}:session.complete();if(!result.accepted)return this.host.showError(result.error),!1;this.setSnapshot(result.state),this.dispatchingState=!0,this.completing=session;try{this.host.emit("lr-map-draw-complete",result.state)}finally{this.dispatchingState=!1,this.completing=void 0}return this.session===session&&this.clear(),!0}cancel(reason,keepMode,armedMode){const session=this.session;if(!session&&armedMode!=="line"&&armedMode!=="polygon")return this.editAdmission&&(this.editCancelled=!0),!1;const state=session?session.snapshot().phase!=="cancelled"?session.cancel().state:void 0:armedMode==="line"||armedMode==="polygon"?new MapDrawing(armedMode).cancel().state:void 0;return this.clear(keepMode),state&&this.host.emitCancel(Object.freeze({...state,reason})),!0}clear(keepMode=!1){const host=this.host,pointer=this.pointer,release=this.release,overlay=this.overlay,mode=host.element.drawMode;this.pointer=void 0,this.release=void 0,this.overlay=void 0,this.session=void 0,this.started=!1,this.setEditing(!1),this.setHandles([]),this.setSnapshot(void 0),host.clearError(),!keepMode&&host.element.drawMode===mode&&host.resetMode(),pointer?.consumeClick()&&host.suppressClick(),pointer?.dispose(),release?.(),overlay?.deactivate(),this.keyCleanup?.(),this.keyCleanup=void 0,this.clearPreview(!1),this.setLabels([]),!this.session&&(host.advanceEpoch(),this.renderResources(),host.syncCursor())}sync(){const host=this.host,element=host.element;if(host.updateActive()){host.afterUpdate(()=>this.sync(),"map-sync-drawing");return}if(element.pickMode){this.cancel("pick-mode",!1,element.drawMode);return}if(host.interactionBlocked()){this.cancel("disabled",!1,element.drawMode);return}if(element.drawMode!=="line"&&element.drawMode!=="polygon"&&!this.editingState)return;const map=host.map();if(!(!element.isConnected||!map||!host.styleLoaded()||!host.usable())){if(!this.session){const mode=element.drawMode;if(mode!=="line"&&mode!=="polygon")return;const[,connection]=host.generations(),epoch=host.epoch(),current=()=>host.map()===map&&host.epoch()===epoch&&host.generations()[1]===connection;this.dispatchingState=!0;let lease;try{lease=acquireMapDrawingGesture(map,{current})}finally{this.dispatchingState=!1}if(!lease.accepted||!current()||!element.isConnected||element.drawMode!==mode||element.pickMode||host.interactionBlocked()){lease.release(),!lease.accepted&&current()&&host.showError();return}this.release=lease.release,host.clearError(),this.session=new MapDrawing(mode),this.setSnapshot(this.session.snapshot())}this.installPointer(),this.installKeys(),this.scheduleHandles(),this.resourceStyle!==host.generations()[0]&&this.renderResources(),this.overlay||(this.overlay=activateOverlay({host:element,panel:()=>element.shadowRoot?.querySelector('[part="drawing-controls"]')??null,onEscape:()=>{this.cancel("escape",!1,element.drawMode)},beforeInitialFocus:()=>!1,modal:!1,trapFocus:!1,lockScroll:!1})),host.syncCursor()}}installPointer(){const host=this.host,map=host.map(),session=this.session,epoch=host.epoch(),[style,connection]=host.generations();if(!map||!session||this.pointer)return;const engine=()=>{const[s,c]=host.generations();return host.map()===map&&host.epoch()===epoch&&s===style&&c===connection},owns=()=>engine()&&this.session===session;try{const canvas=map.getCanvas();if(!owns()||!host.interactionAllowed())return;this.pointer=new MapDrawingPointer({canvas,current:()=>owns()&&host.actionAllowed(),vertices:()=>session.snapshot().vertices,project:point=>host.element.project(point),unproject:point=>host.element.unproject(point),replace:(index,point)=>this.replaceVertex(session,index,point),acquirePan:()=>acquireMapDrawingPan(map,{current:()=>host.map()===map&&host.epoch()===epoch&&host.generations()[1]===connection}),cancel:()=>{owns()&&this.cancel("pointercancel",!1,host.element.drawMode)},tap:(index,distance)=>{owns()&&this.tap(session,index,distance)},end:index=>{owns()&&this.emitVertexEnd(session,index)}})}catch{owns()&&host.showError()}}replaceVertex(session,index,point){if(this.session!==session||this.dispatchingState||!this.host.actionAllowed())return!1;const result=session.replace(index,point);return this.session!==session?!1:result.accepted?(this.setSnapshot(result.state),this.host.clearError(),this.select(index),this.emitChange(session),this.session===session&&this.snapshotState===result.state&&this.renderResources(),!0):(this.host.showError(result.error),!1)}styleChanging(){const pointer=this.pointer;this.pointer=void 0,pointer?.consumeClick()&&this.host.suppressClick(),pointer?.dispose(),this.resourceStyle=void 0,this.clearPreview(!1)}tap(session,index,distance){const state=session.snapshot();this.session!==session||this.editingState||state.mode!=="polygon"||state.phase!=="drawing"||index!==0||state.vertices.length<3||!(distance<=CLOSE_DISTANCE)||this.complete()}emitVertexEnd(session,index){if(this.session!==session)return;const state=session.snapshot();if(!(!Number.isSafeInteger(index)||index<0||index>=state.vertices.length)){this.dispatchingState=!0;try{this.host.emitVertexEnd(Object.freeze({...state,index}))}finally{this.dispatchingState=!1}}}installKeys(){const host=this.host,map=host.map(),session=this.session;if(!map||!session||this.keyCleanup)return;let canvas;try{canvas=map.getCanvas()}catch{return}const key=event=>{this.session!==session||host.map()!==map||event.defaultPrevented||event.isComposing||event.altKey||event.ctrlKey||event.metaKey||event.shiftKey||event.target!==canvas||(event.key==="Enter"&&!event.repeat?(event.preventDefault(),this.complete()):event.key==="Backspace"&&!this.editingState&&(event.preventDefault(),this.undo()))};canvas.addEventListener("keydown",key);const shortcuts=canvas.getAttribute("aria-keyshortcuts");canvas.setAttribute("aria-keyshortcuts",this.editingState?"Enter":"Enter Backspace"),this.keyCleanup=()=>{canvas.removeEventListener("keydown",key),shortcuts===null?canvas.removeAttribute("aria-keyshortcuts"):canvas.setAttribute("aria-keyshortcuts",shortcuts)}}preview(point){const state=this.snapshotState,next=this.session&&!this.editingState&&state?.phase==="drawing"&&state.vertices.length>0?point:void 0;if(next===void 0&&this.previewPoint===void 0||(this.previewPoint=next,this.previewFrame!==void 0))return;const view=this.host.element.ownerDocument.defaultView,render=()=>{this.previewFrame=void 0,this.session&&this.renderResources()};if(!view||typeof view.requestAnimationFrame!="function"){render();return}this.previewFrame=view.requestAnimationFrame(render)}clearPreview(render=!0){this.previewFrame!==void 0&&this.host.element.ownerDocument.defaultView?.cancelAnimationFrame(this.previewFrame),this.previewFrame=void 0;const had=this.previewPoint!==void 0;this.previewPoint=void 0,had&&render&&this.session&&this.renderResources()}setLabels(value){const previous=this.labelsState;value.length===previous.length&&value.every((label,index)=>{const old=previous[index];return old.kind===label.kind&&old.value===label.value&&old.x===label.x&&old.y===label.y})||(this.labelsState=value,this.host.changed())}repaint(){this.session&&this.renderResources()}scheduleHandles(){this.host.afterUpdate(()=>this.syncHandles(),"map-drawing-handles")}syncHandles(){const host=this.host,map=host.map(),session=this.session,state=this.snapshotState,epoch=host.epoch(),current=()=>host.map()===map&&this.session===session&&this.snapshotState===state&&host.epoch()===epoch&&host.interactionAllowed(),next=[],labels=[];if(map&&session&&state&&current())try{const canvas=map.getCanvas();if(!current())return;const base=host.element.shadowRoot?.querySelector('[part="base"]');if(base){const viewport=canvas.getBoundingClientRect();if(!current())return;const rect=base.getBoundingClientRect();if(!current())return;const width=canvas.clientWidth,height=canvas.clientHeight,baseWidth=base.clientWidth,baseHeight=base.clientHeight;if([viewport.left,viewport.top,viewport.width,viewport.height,rect.left,rect.top,rect.width,rect.height,width,height,baseWidth,baseHeight].every(Number.isFinite)&&Math.min(width,height,baseWidth,baseHeight,viewport.width,viewport.height,rect.width,rect.height)>0){for(let index=0;index<state.vertices.length;index++){const point=host.element.project(state.vertices[index]);if(!current())return;if(!point||point[0]<0||point[1]<0||point[0]>width||point[1]>height)continue;const x=(viewport.left-rect.left+point[0]*viewport.width/width)*baseWidth/rect.width,y=(viewport.top-rect.top+point[1]*viewport.height/height)*baseHeight/rect.height;Number.isFinite(x)&&Number.isFinite(y)&&next.push({index,x,y})}if(host.element.drawingMeasurements&&state.vertices.length>1){const place=(kind,value,...points)=>{let sx=0,sy=0;for(const point of points){const projected=host.element.project(point);if(!projected)return;sx+=projected[0]/points.length,sy+=projected[1]/points.length}if(!(sx>=0&&sy>=0&&sx<=width&&sy<=height)||!Number.isFinite(value))return;const x=(viewport.left-rect.left+sx*viewport.width/width)*baseWidth/rect.width,y=(viewport.top-rect.top+sy*viewport.height/height)*baseHeight/rect.height;Number.isFinite(x)&&Number.isFinite(y)&&labels.push({kind,value,x,y})},vertices=state.vertices,measured=measureDrawing(state.mode,vertices);if(measured.segments.forEach((value,index)=>{place("segment",value,vertices[index],vertices[index+1])}),measured.closing!==void 0&&place("closing",measured.closing,vertices[vertices.length-1],vertices[0]),measured.area!==void 0&&measured.centroid&&place("area",measured.area,measured.centroid),state.mode==="line"&&place("length",measured.length,vertices[vertices.length-1]),!current())return}}}}catch{if(!current())return}next.length&&!next.some(handle=>handle.index===this.selectedState)&&this.select(next[0].index),(next.length!==this.handlesState.length||next.some((handle,index)=>{const previous=this.handlesState[index];return!previous||previous.index!==handle.index||previous.x!==handle.x||previous.y!==handle.y}))&&this.setHandles(next),this.setLabels(labels)}vertexKey(event,index){const host=this.host,session=this.session,state=this.snapshotState,map=host.map(),epoch=host.epoch();if(!session||!state||!map||this.dispatchingState||!host.interactionAllowed())return;const current=()=>this.session===session&&this.snapshotState===state&&host.map()===map&&host.epoch()===epoch&&host.interactionAllowed();if(!["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","PageUp","PageDown","Home","End"].includes(event.key))return;if(event.preventDefault(),event.stopPropagation(),event.key==="Home"||event.key==="End"||event.key==="PageUp"||event.key==="PageDown"){const handles=this.handlesState,position=handles.findIndex(handle2=>handle2.index===index),selected=event.key==="Home"?0:event.key==="End"?handles.length-1:Math.max(0,Math.min(handles.length-1,position+(event.key==="PageUp"?-1:1))),handle=handles[selected];handle&&current()&&(this.select(handle.index),host.element.shadowRoot?.querySelectorAll('[part="drawing-vertex"]')[selected]?.focus());return}const vertex=state.vertices[index];if(!vertex)return;const point=host.element.project(vertex);if(!point||!current())return;const step=event.shiftKey?32:8,rtl=host.direction()==="rtl"?-1:1,dx=event.key==="ArrowLeft"?-step*rtl:event.key==="ArrowRight"?step*rtl:0,dy=event.key==="ArrowUp"?-step:event.key==="ArrowDown"?step:0,coordinate=host.element.unproject([point[0]+dx,point[1]+dy]);coordinate&&current()&&this.replaceVertex(session,index,coordinate)&&this.emitVertexEnd(session,index)}emitChange(session){if(this.session===session){this.dispatchingState=!0;try{this.host.emit("lr-map-draw-change",session.snapshot())}finally{this.dispatchingState=!1}}}add(point){const session=this.session;if(!session||this.dispatchingState||!this.host.interactionAllowed())return!1;const first=!this.started,result=session.add(point);if(!result.accepted)return this.host.showError(result.error),!1;if(this.setSnapshot(result.state),this.host.clearError(),first){this.started=!0,this.dispatchingState=!0;try{this.host.emit("lr-map-draw-start",result.state)}finally{this.dispatchingState=!1}}return this.emitChange(session),this.session===session&&this.snapshotState===result.state&&this.renderResources(),!0}addCenter(){const host=this.host,map=host.map(),session=this.session,epoch=host.epoch();if(!(!map||!session||this.dispatchingState||!host.interactionAllowed()))try{const point=mapCoordinates(map.getCenter());host.map()===map&&this.session===session&&host.epoch()===epoch&&point&&this.add(point)}catch{this.session===session&&host.showError()}}cancelResources(forgetSource=!1){this.features?.cancel(),this.abort?.abort(),this.finishWork?.(),this.abort=void 0,this.finishWork=void 0,this.resourcesPending=!1,forgetSource&&(this.source=void 0)}disposeResources(){this.features?.dispose(),this.source=void 0}renderResources(){const host=this.host,map=host.map();if(this.cancelResources(),!map||!host.styleLoaded()||!host.element.isConnected)return;const state=this.snapshotState,[style]=host.generations(),epoch=++this.resourceEpoch;this.resourceStyle=style;const controller=new AbortController;this.abort=controller;const current=()=>host.map()===map&&host.generations()[0]===style&&epoch===this.resourceEpoch&&host.element.isConnected&&!controller.signal.aborted,vertices=state&&(state.phase==="drawing"||this.editingState&&state.phase==="completed")?state.vertices:[];if(this.scheduleHandles(),!vertices.length&&!this.source)return;this.resourcesPending=!0,host.invalidate();let finish;this.resourceWork=new Promise(resolve=>{finish=resolve}),this.finishWork=finish;const run=async()=>{try{let id=this.source;if(vertices.length&&!id){const reserved=snapshotMapOwnedFeatureInput({overlays:host.element.overlays,images:[],styleOverrides:[]}).overlays,used=new Set([...reserved.sources.map(row=>row.id),...reserved.layers.map(row=>row.layer.id)]);for(let attempt=0;attempt<512&&current();attempt++){const candidate=`lr-drawing-${this.idCounter++}`;if(![candidate,`${candidate}-points`,`${candidate}-line`,`${candidate}-fill`,`${candidate}-preview`].some(value=>used.has(value)||map.getSource(value)||map.getLayer(value))){current()&&(id=candidate);break}}if(!id)throw new Error("Drawing resources are unavailable.");this.source=id}if(!current())return;const features=vertices.map(point=>({type:"Feature",properties:{},geometry:{type:"Point",coordinates:[...point]}}));vertices.length>1&&features.push({type:"Feature",properties:{},geometry:{type:"LineString",coordinates:vertices.map(point=>[...point])}}),state?.mode==="polygon"&&vertices.length>2&&features.push({type:"Feature",properties:{},geometry:{type:"Polygon",coordinates:[[...vertices.map(point=>[...point]),[...vertices[0]]]]}});const preview=this.previewPoint,drawingPhase=state?.phase==="drawing"&&!this.editingState;if(preview&&drawingPhase&&vertices.length){const last=vertices[vertices.length-1],band=state?.mode==="polygon"&&vertices.length>1?[[...last],[...preview],[...vertices[0]]]:[[...last],[...preview]];features.push({type:"Feature",properties:{preview:!0},geometry:{type:"LineString",coordinates:band}})}const color=host.accentColor(),layers=vertices.length?[{layer:{id:`${id}-fill`,type:"fill",source:id,filter:["==","$type","Polygon"],paint:{"fill-color":color,"fill-opacity":.2}}},{layer:{id:`${id}-line`,type:"line",source:id,filter:["all",["==","$type","LineString"],["!has","preview"]],paint:{"line-color":color,"line-width":2}}},{layer:{id:`${id}-preview`,type:"line",source:id,filter:["all",["==","$type","LineString"],["has","preview"]],paint:{"line-color":color,"line-width":2,"line-dasharray":[2,2]}}},{layer:{id:`${id}-points`,type:"circle",source:id,filter:["==","$type","Point"],paint:{"circle-color":color,"circle-radius":5}}}]:[];await(this.features??=new MapOwnedFeatures).reconcile(map,style,{overlays:{sources:vertices.length?[{id,source:{type:"geojson",data:{type:"FeatureCollection",features}}}]:[],layers},images:[],styleOverrides:[]},{owner:host.element,signal:controller.signal,isCurrent:current,isGeneratedLayer:()=>!1,resolve:(value,property)=>host.resolve(value,property)}),current()&&!vertices.length&&(this.source=void 0)}catch{current()&&(host.showError(),host.fail())}finally{finish(),current()&&(this.resourcesPending=!1,this.abort=void 0,this.finishWork=void 0,host.check())}};queueMicrotask(()=>{current()?run():finish()})}}export{MapDrawingController,measureDrawing};
@@ -0,0 +1 @@
1
+ import{getInheritedPropertyDescriptor,isObjectValue}from"../../../internal/data-descriptors.js";const owners=new WeakMap;class GestureFailure extends Error{constructor(code){super("Map drawing gesture is unavailable."),this.code=code}}const rejected=code=>Object.freeze({accepted:!1,code,release:()=>!1});function acquireMapDrawingGesture(peer,context){if(!isObjectValue(peer))return rejected("unavailable");if(owners.has(peer))return rejected("reentrant");const owner={released:!1,releasing:!1};owners.set(peer,owner);let handler,enabled,enable,ownedDisable=!1,releaseResult;const current=()=>{const owns=()=>!owner.released&&owners.get(peer)===owner;try{return owns()&&context.current()===!0&&owns()}catch{return!1}},guard=()=>{if(!current())throw new GestureFailure("stale")},data=(value,key)=>{guard();const descriptor=getInheritedPropertyDescriptor(value,key);if(guard(),!descriptor||!Object.hasOwn(descriptor,"value"))throw new GestureFailure("unavailable");return descriptor.value},method=(value,key)=>{const candidate=data(value,key);if(typeof candidate!="function")throw new GestureFailure("unavailable");return candidate},readEnabled=()=>{guard();const value=Reflect.apply(enabled,handler,[]);if(guard(),typeof value!="boolean")throw new GestureFailure("peer-error");return value},retire=()=>{owner.released=!0,owners.get(peer)===owner&&owners.delete(peer)},release=()=>{if(releaseResult!==void 0)return releaseResult;if(owner.releasing)return!1;owner.releasing=!0;try{return guard(),ownedDisable?data(peer,"doubleClickZoom")!==handler?releaseResult=!1:readEnabled()?releaseResult=!0:(guard(),Reflect.apply(enable,handler,[]),guard(),releaseResult=readEnabled()):releaseResult=!0}catch{return releaseResult=!1}finally{retire(),owner.releasing=!1}};try{const capability=data(peer,"doubleClickZoom");if(!isObjectValue(capability))throw new GestureFailure("unavailable");handler=capability,enabled=method(handler,"isEnabled");const disable=method(handler,"disable");if(enable=method(handler,"enable"),readEnabled()&&(ownedDisable=!0,guard(),Reflect.apply(disable,handler,[]),guard(),readEnabled()))throw ownedDisable=!1,new GestureFailure("peer-error");if(guard(),data(peer,"doubleClickZoom")!==handler)throw new GestureFailure("stale");return Object.freeze({accepted:!0,release})}catch(error){const code=current()?error instanceof GestureFailure?error.code:"peer-error":"stale";return release(),Object.freeze({accepted:!1,code,release})}}export{acquireMapDrawingGesture};
@@ -0,0 +1 @@
1
+ import{getInheritedPropertyDescriptor,isObjectValue}from"../../../internal/data-descriptors.js";const owners=new WeakMap;class PanFailure extends Error{constructor(code){super("Map drawing pan is unavailable."),this.code=code}}const rejected=code=>Object.freeze({accepted:!1,code,release:()=>!1});function acquireMapDrawingPan(peer,context){if(!isObjectValue(peer))return rejected("unavailable");if(owners.has(peer))return rejected("reentrant");const owner={released:!1,releasing:!1};owners.set(peer,owner);let handler,enabled,enable,ownedDisable=!1,releaseResult;const current=()=>{const owns=()=>!owner.released&&owners.get(peer)===owner;try{return owns()&&context.current()===!0&&owns()}catch{return!1}},guard=()=>{if(!current())throw new PanFailure("stale")},data=(value,key)=>{guard();const descriptor=getInheritedPropertyDescriptor(value,key);if(guard(),!descriptor||!Object.hasOwn(descriptor,"value"))throw new PanFailure("unavailable");return descriptor.value},method=(value,key)=>{const candidate=data(value,key);if(typeof candidate!="function")throw new PanFailure("unavailable");return candidate},guardHandler=()=>{if(data(peer,"dragPan")!==handler)throw new PanFailure("stale")},readEnabled=()=>{guardHandler();const value=Reflect.apply(enabled,handler,[]);if(guardHandler(),typeof value!="boolean")throw new PanFailure("peer-error");return value},retire=()=>{owner.released=!0,owners.get(peer)===owner&&owners.delete(peer)},release=()=>{if(releaseResult!==void 0)return releaseResult;if(owner.releasing)return!1;owner.releasing=!0;try{return guard(),ownedDisable?data(peer,"dragPan")!==handler?releaseResult=!1:readEnabled()?releaseResult=!0:(guardHandler(),Reflect.apply(enable,handler,[]),guardHandler(),releaseResult=readEnabled()):releaseResult=!0}catch{return releaseResult=!1}finally{retire(),owner.releasing=!1}};try{const capability=data(peer,"dragPan");if(!isObjectValue(capability))throw new PanFailure("unavailable");handler=capability,enabled=method(handler,"isEnabled");const disable=method(handler,"disable");if(enable=method(handler,"enable"),readEnabled()&&(ownedDisable=!0,guardHandler(),Reflect.apply(disable,handler,[]),guardHandler(),readEnabled()))throw ownedDisable=!1,new PanFailure("peer-error");if(guard(),data(peer,"dragPan")!==handler)throw new PanFailure("stale");return Object.freeze({accepted:!0,release})}catch(error){const code=current()?error instanceof PanFailure?error.code:"peer-error":"stale";return release(),Object.freeze({accepted:!1,code,release})}}export{acquireMapDrawingPan};