@react-x11/components 0.7.1 → 0.9.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 (354) hide show
  1. package/README.md +295 -51
  2. package/dist/charts/node.d.ts +1 -1
  3. package/dist/charts/node.d.ts.map +1 -1
  4. package/dist/charts/node.js +6 -2
  5. package/dist/charts/node.js.map +1 -1
  6. package/dist/color-picker/ColorPicker.d.ts.map +1 -1
  7. package/dist/color-picker/ColorPicker.js +43 -33
  8. package/dist/color-picker/ColorPicker.js.map +1 -1
  9. package/dist/embed/client.d.ts +48 -3
  10. package/dist/embed/client.d.ts.map +1 -1
  11. package/dist/embed/client.js +79 -5
  12. package/dist/embed/client.js.map +1 -1
  13. package/dist/embed/index.d.ts +1 -1
  14. package/dist/embed/index.d.ts.map +1 -1
  15. package/dist/embed/index.js +1 -1
  16. package/dist/embed/index.js.map +1 -1
  17. package/dist/html/node.d.ts +3 -1
  18. package/dist/html/node.d.ts.map +1 -1
  19. package/dist/html/node.js +7 -5
  20. package/dist/html/node.js.map +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +1 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/{markdown → internal/markdown}/ast.d.ts +12 -0
  26. package/dist/internal/markdown/ast.d.ts.map +1 -0
  27. package/dist/internal/markdown/ast.js +22 -0
  28. package/dist/internal/markdown/ast.js.map +1 -0
  29. package/dist/internal/markdown/parse.d.ts.map +1 -0
  30. package/dist/{markdown → internal/markdown}/parse.js +112 -22
  31. package/dist/internal/markdown/parse.js.map +1 -0
  32. package/dist/internal/markdown/stringify.d.ts +4 -0
  33. package/dist/internal/markdown/stringify.d.ts.map +1 -0
  34. package/dist/internal/markdown/stringify.js +684 -0
  35. package/dist/internal/markdown/stringify.js.map +1 -0
  36. package/dist/internal/markdown/tags.d.ts.map +1 -0
  37. package/dist/internal/markdown/tags.js.map +1 -0
  38. package/dist/internal/scroll.d.ts +3 -2
  39. package/dist/internal/scroll.d.ts.map +1 -1
  40. package/dist/internal/scroll.js +33 -15
  41. package/dist/internal/scroll.js.map +1 -1
  42. package/dist/internal/units.d.ts +2 -0
  43. package/dist/internal/units.d.ts.map +1 -0
  44. package/dist/internal/units.js +35 -0
  45. package/dist/internal/units.js.map +1 -0
  46. package/dist/internal/window.d.ts.map +1 -1
  47. package/dist/internal/window.js +4 -2
  48. package/dist/internal/window.js.map +1 -1
  49. package/dist/maps/anchors.d.ts +98 -0
  50. package/dist/maps/anchors.d.ts.map +1 -0
  51. package/dist/maps/anchors.js +531 -0
  52. package/dist/maps/anchors.js.map +1 -0
  53. package/dist/maps/controller.d.ts +283 -0
  54. package/dist/maps/controller.d.ts.map +1 -0
  55. package/dist/maps/controller.js +743 -0
  56. package/dist/maps/controller.js.map +1 -0
  57. package/dist/maps/gl/buckets.d.ts +95 -0
  58. package/dist/maps/gl/buckets.d.ts.map +1 -0
  59. package/dist/maps/gl/buckets.js +362 -0
  60. package/dist/maps/gl/buckets.js.map +1 -0
  61. package/dist/maps/gl/build-worker.d.ts +13 -0
  62. package/dist/maps/gl/build-worker.d.ts.map +1 -0
  63. package/dist/maps/gl/build-worker.js +44 -0
  64. package/dist/maps/gl/build-worker.js.map +1 -0
  65. package/dist/maps/gl/color.d.ts +8 -0
  66. package/dist/maps/gl/color.d.ts.map +1 -0
  67. package/dist/maps/gl/color.js +57 -0
  68. package/dist/maps/gl/color.js.map +1 -0
  69. package/dist/maps/gl/cover.d.ts +51 -0
  70. package/dist/maps/gl/cover.d.ts.map +1 -0
  71. package/dist/maps/gl/cover.js +124 -0
  72. package/dist/maps/gl/cover.js.map +1 -0
  73. package/dist/maps/gl/index.d.ts +3 -0
  74. package/dist/maps/gl/index.d.ts.map +1 -0
  75. package/dist/maps/gl/index.js +20 -0
  76. package/dist/maps/gl/index.js.map +1 -0
  77. package/dist/maps/gl/markers.d.ts +28 -0
  78. package/dist/maps/gl/markers.d.ts.map +1 -0
  79. package/dist/maps/gl/markers.js +60 -0
  80. package/dist/maps/gl/markers.js.map +1 -0
  81. package/dist/maps/gl/overlays.d.ts +68 -0
  82. package/dist/maps/gl/overlays.d.ts.map +1 -0
  83. package/dist/maps/gl/overlays.js +300 -0
  84. package/dist/maps/gl/overlays.js.map +1 -0
  85. package/dist/maps/gl/pane.d.ts +12 -0
  86. package/dist/maps/gl/pane.d.ts.map +1 -0
  87. package/dist/maps/gl/pane.js +37 -0
  88. package/dist/maps/gl/pane.js.map +1 -0
  89. package/dist/maps/gl/placement.d.ts +111 -0
  90. package/dist/maps/gl/placement.d.ts.map +1 -0
  91. package/dist/maps/gl/placement.js +567 -0
  92. package/dist/maps/gl/placement.js.map +1 -0
  93. package/dist/maps/gl/renderer.d.ts +352 -0
  94. package/dist/maps/gl/renderer.d.ts.map +1 -0
  95. package/dist/maps/gl/renderer.js +1127 -0
  96. package/dist/maps/gl/renderer.js.map +1 -0
  97. package/dist/maps/gl/shaders.d.ts +120 -0
  98. package/dist/maps/gl/shaders.d.ts.map +1 -0
  99. package/dist/maps/gl/shaders.js +451 -0
  100. package/dist/maps/gl/shaders.js.map +1 -0
  101. package/dist/maps/gl/store.d.ts +115 -0
  102. package/dist/maps/gl/store.d.ts.map +1 -0
  103. package/dist/maps/gl/store.js +469 -0
  104. package/dist/maps/gl/store.js.map +1 -0
  105. package/dist/maps/gl/text.d.ts +154 -0
  106. package/dist/maps/gl/text.d.ts.map +1 -0
  107. package/dist/maps/gl/text.js +382 -0
  108. package/dist/maps/gl/text.js.map +1 -0
  109. package/dist/maps/gl/view.d.ts +54 -0
  110. package/dist/maps/gl/view.d.ts.map +1 -0
  111. package/dist/maps/gl/view.js +974 -0
  112. package/dist/maps/gl/view.js.map +1 -0
  113. package/dist/maps/index.d.ts +1 -1
  114. package/dist/maps/index.d.ts.map +1 -1
  115. package/dist/maps/index.js +216 -52
  116. package/dist/maps/index.js.map +1 -1
  117. package/dist/maps/labels.d.ts +37 -16
  118. package/dist/maps/labels.d.ts.map +1 -1
  119. package/dist/maps/labels.js +188 -119
  120. package/dist/maps/labels.js.map +1 -1
  121. package/dist/maps/node.d.ts +162 -56
  122. package/dist/maps/node.d.ts.map +1 -1
  123. package/dist/maps/node.js +607 -515
  124. package/dist/maps/node.js.map +1 -1
  125. package/dist/maps/overlay.d.ts +72 -9
  126. package/dist/maps/overlay.d.ts.map +1 -1
  127. package/dist/maps/overlay.js +108 -28
  128. package/dist/maps/overlay.js.map +1 -1
  129. package/dist/maps/paint.d.ts +3 -0
  130. package/dist/maps/paint.d.ts.map +1 -1
  131. package/dist/maps/paint.js.map +1 -1
  132. package/dist/maps/proj.d.ts +14 -0
  133. package/dist/maps/proj.d.ts.map +1 -1
  134. package/dist/maps/proj.js +28 -0
  135. package/dist/maps/proj.js.map +1 -1
  136. package/dist/maps/renderer.d.ts +69 -0
  137. package/dist/maps/renderer.d.ts.map +1 -0
  138. package/dist/maps/renderer.js +66 -0
  139. package/dist/maps/renderer.js.map +1 -0
  140. package/dist/maps/sources.d.ts +25 -3
  141. package/dist/maps/sources.d.ts.map +1 -1
  142. package/dist/maps/sources.js +17 -0
  143. package/dist/maps/sources.js.map +1 -1
  144. package/dist/maps/theme.d.ts +19 -0
  145. package/dist/maps/theme.d.ts.map +1 -0
  146. package/dist/maps/theme.js +44 -0
  147. package/dist/maps/theme.js.map +1 -0
  148. package/dist/maps/tiles.d.ts +117 -17
  149. package/dist/maps/tiles.d.ts.map +1 -1
  150. package/dist/maps/tiles.js +163 -30
  151. package/dist/maps/tiles.js.map +1 -1
  152. package/dist/maps/types.d.ts +188 -20
  153. package/dist/maps/types.d.ts.map +1 -1
  154. package/dist/markdown/expressions.d.ts +1 -1
  155. package/dist/markdown/expressions.d.ts.map +1 -1
  156. package/dist/markdown/expressions.js.map +1 -1
  157. package/dist/markdown/index.d.ts +7 -6
  158. package/dist/markdown/index.d.ts.map +1 -1
  159. package/dist/markdown/index.js +9 -7
  160. package/dist/markdown/index.js.map +1 -1
  161. package/dist/markdown/spans.d.ts +1 -1
  162. package/dist/markdown/spans.d.ts.map +1 -1
  163. package/dist/media-player/index.d.ts +11 -3
  164. package/dist/media-player/index.d.ts.map +1 -1
  165. package/dist/media-player/index.js +13 -2
  166. package/dist/media-player/index.js.map +1 -1
  167. package/dist/rich-text-editor/clipboard.d.ts +23 -0
  168. package/dist/rich-text-editor/clipboard.d.ts.map +1 -0
  169. package/dist/rich-text-editor/clipboard.js +307 -0
  170. package/dist/rich-text-editor/clipboard.js.map +1 -0
  171. package/dist/rich-text-editor/collab.d.ts +32 -0
  172. package/dist/rich-text-editor/collab.d.ts.map +1 -0
  173. package/dist/rich-text-editor/collab.js +55 -0
  174. package/dist/rich-text-editor/collab.js.map +1 -0
  175. package/dist/rich-text-editor/commands.d.ts +50 -0
  176. package/dist/rich-text-editor/commands.d.ts.map +1 -0
  177. package/dist/rich-text-editor/commands.js +376 -0
  178. package/dist/rich-text-editor/commands.js.map +1 -0
  179. package/dist/rich-text-editor/drag.d.ts +68 -0
  180. package/dist/rich-text-editor/drag.d.ts.map +1 -0
  181. package/dist/rich-text-editor/drag.js +148 -0
  182. package/dist/rich-text-editor/drag.js.map +1 -0
  183. package/dist/rich-text-editor/html.d.ts +145 -0
  184. package/dist/rich-text-editor/html.d.ts.map +1 -0
  185. package/dist/rich-text-editor/html.js +516 -0
  186. package/dist/rich-text-editor/html.js.map +1 -0
  187. package/dist/rich-text-editor/index.d.ts +263 -0
  188. package/dist/rich-text-editor/index.d.ts.map +1 -0
  189. package/dist/rich-text-editor/index.js +822 -0
  190. package/dist/rich-text-editor/index.js.map +1 -0
  191. package/dist/rich-text-editor/inline.d.ts +94 -0
  192. package/dist/rich-text-editor/inline.d.ts.map +1 -0
  193. package/dist/rich-text-editor/inline.js +252 -0
  194. package/dist/rich-text-editor/inline.js.map +1 -0
  195. package/dist/rich-text-editor/keymap.d.ts +71 -0
  196. package/dist/rich-text-editor/keymap.d.ts.map +1 -0
  197. package/dist/rich-text-editor/keymap.js +393 -0
  198. package/dist/rich-text-editor/keymap.js.map +1 -0
  199. package/dist/rich-text-editor/keys.d.ts +29 -0
  200. package/dist/rich-text-editor/keys.d.ts.map +1 -0
  201. package/dist/rich-text-editor/keys.js +93 -0
  202. package/dist/rich-text-editor/keys.js.map +1 -0
  203. package/dist/rich-text-editor/look.d.ts +71 -0
  204. package/dist/rich-text-editor/look.d.ts.map +1 -0
  205. package/dist/rich-text-editor/look.js +342 -0
  206. package/dist/rich-text-editor/look.js.map +1 -0
  207. package/dist/rich-text-editor/markdown.d.ts +18 -0
  208. package/dist/rich-text-editor/markdown.d.ts.map +1 -0
  209. package/dist/rich-text-editor/markdown.js +496 -0
  210. package/dist/rich-text-editor/markdown.js.map +1 -0
  211. package/dist/rich-text-editor/nodes.d.ts +135 -0
  212. package/dist/rich-text-editor/nodes.d.ts.map +1 -0
  213. package/dist/rich-text-editor/nodes.js +397 -0
  214. package/dist/rich-text-editor/nodes.js.map +1 -0
  215. package/dist/rich-text-editor/render.d.ts +68 -0
  216. package/dist/rich-text-editor/render.d.ts.map +1 -0
  217. package/dist/rich-text-editor/render.js +500 -0
  218. package/dist/rich-text-editor/render.js.map +1 -0
  219. package/dist/rich-text-editor/schema.d.ts +16 -0
  220. package/dist/rich-text-editor/schema.d.ts.map +1 -0
  221. package/dist/rich-text-editor/schema.js +386 -0
  222. package/dist/rich-text-editor/schema.js.map +1 -0
  223. package/dist/rich-text-editor/store.d.ts +11 -0
  224. package/dist/rich-text-editor/store.d.ts.map +1 -0
  225. package/dist/rich-text-editor/store.js +43 -0
  226. package/dist/rich-text-editor/store.js.map +1 -0
  227. package/dist/rich-text-editor/suggest.d.ts +127 -0
  228. package/dist/rich-text-editor/suggest.d.ts.map +1 -0
  229. package/dist/rich-text-editor/suggest.js +0 -0
  230. package/dist/rich-text-editor/suggest.js.map +1 -0
  231. package/dist/rich-text-editor/tables.d.ts +41 -0
  232. package/dist/rich-text-editor/tables.d.ts.map +1 -0
  233. package/dist/rich-text-editor/tables.js +204 -0
  234. package/dist/rich-text-editor/tables.js.map +1 -0
  235. package/dist/rich-text-editor/toolbar.d.ts +58 -0
  236. package/dist/rich-text-editor/toolbar.d.ts.map +1 -0
  237. package/dist/rich-text-editor/toolbar.js +548 -0
  238. package/dist/rich-text-editor/toolbar.js.map +1 -0
  239. package/dist/rich-text-editor/view.d.ts +368 -0
  240. package/dist/rich-text-editor/view.d.ts.map +1 -0
  241. package/dist/rich-text-editor/view.js +1968 -0
  242. package/dist/rich-text-editor/view.js.map +1 -0
  243. package/dist/rich-text-editor/virtual.d.ts +54 -0
  244. package/dist/rich-text-editor/virtual.d.ts.map +1 -0
  245. package/dist/rich-text-editor/virtual.js +262 -0
  246. package/dist/rich-text-editor/virtual.js.map +1 -0
  247. package/dist/richtext/node.d.ts +25 -2
  248. package/dist/richtext/node.d.ts.map +1 -1
  249. package/dist/richtext/node.js +46 -24
  250. package/dist/richtext/node.js.map +1 -1
  251. package/dist/table/index.d.ts.map +1 -1
  252. package/dist/table/index.js +14 -5
  253. package/dist/table/index.js.map +1 -1
  254. package/dist/terminal/backends.d.ts +4 -1
  255. package/dist/terminal/backends.d.ts.map +1 -1
  256. package/dist/terminal/backends.js.map +1 -1
  257. package/dist/terminal/index.d.ts +18 -7
  258. package/dist/terminal/index.d.ts.map +1 -1
  259. package/dist/terminal/index.js +28 -11
  260. package/dist/terminal/index.js.map +1 -1
  261. package/dist/terminal/vt/node.d.ts +56 -3
  262. package/dist/terminal/vt/node.d.ts.map +1 -1
  263. package/dist/terminal/vt/node.js +106 -26
  264. package/dist/terminal/vt/node.js.map +1 -1
  265. package/dist/terminal/vt/renderer.d.ts +4 -0
  266. package/dist/terminal/vt/renderer.d.ts.map +1 -1
  267. package/dist/terminal/vt/renderer.js +14 -5
  268. package/dist/terminal/vt/renderer.js.map +1 -1
  269. package/dist/tree/index.d.ts.map +1 -1
  270. package/dist/tree/index.js +6 -4
  271. package/dist/tree/index.js.map +1 -1
  272. package/package.json +23 -4
  273. package/src/charts/node.ts +6 -2
  274. package/src/color-picker/ColorPicker.ts +107 -81
  275. package/src/embed/client.ts +102 -8
  276. package/src/embed/index.ts +2 -0
  277. package/src/html/node.ts +7 -5
  278. package/src/index.ts +2 -0
  279. package/src/{markdown → internal/markdown}/ast.ts +24 -7
  280. package/src/{markdown → internal/markdown}/parse.ts +134 -24
  281. package/src/internal/markdown/stringify.ts +772 -0
  282. package/src/internal/scroll.ts +39 -18
  283. package/src/internal/units.ts +34 -0
  284. package/src/internal/window.ts +4 -2
  285. package/src/maps/anchors.ts +607 -0
  286. package/src/maps/controller.ts +999 -0
  287. package/src/maps/gl/buckets.ts +457 -0
  288. package/src/maps/gl/build-worker.ts +55 -0
  289. package/src/maps/gl/color.ts +62 -0
  290. package/src/maps/gl/cover.ts +170 -0
  291. package/src/maps/gl/index.ts +23 -0
  292. package/src/maps/gl/markers.ts +83 -0
  293. package/src/maps/gl/overlays.ts +379 -0
  294. package/src/maps/gl/pane.ts +42 -0
  295. package/src/maps/gl/placement.ts +816 -0
  296. package/src/maps/gl/renderer.ts +1576 -0
  297. package/src/maps/gl/shaders.ts +486 -0
  298. package/src/maps/gl/store.ts +566 -0
  299. package/src/maps/gl/text.ts +495 -0
  300. package/src/maps/gl/view.ts +1224 -0
  301. package/src/maps/index.ts +270 -81
  302. package/src/maps/labels.ts +214 -121
  303. package/src/maps/node.ts +763 -629
  304. package/src/maps/overlay.ts +148 -43
  305. package/src/maps/paint.ts +3 -0
  306. package/src/maps/proj.ts +31 -0
  307. package/src/maps/renderer.ts +155 -0
  308. package/src/maps/sources.ts +38 -3
  309. package/src/maps/theme.ts +51 -0
  310. package/src/maps/tiles.ts +191 -33
  311. package/src/maps/types.ts +188 -20
  312. package/src/markdown/expressions.ts +5 -1
  313. package/src/markdown/index.ts +14 -11
  314. package/src/markdown/spans.ts +1 -1
  315. package/src/media-player/index.ts +18 -4
  316. package/src/rich-text-editor/clipboard.ts +439 -0
  317. package/src/rich-text-editor/collab.ts +91 -0
  318. package/src/rich-text-editor/commands.ts +448 -0
  319. package/src/rich-text-editor/dom-globals.d.ts +23 -0
  320. package/src/rich-text-editor/drag.ts +211 -0
  321. package/src/rich-text-editor/html.ts +619 -0
  322. package/src/rich-text-editor/index.ts +1331 -0
  323. package/src/rich-text-editor/inline.ts +345 -0
  324. package/src/rich-text-editor/keymap.ts +510 -0
  325. package/src/rich-text-editor/keys.ts +119 -0
  326. package/src/rich-text-editor/look.ts +427 -0
  327. package/src/rich-text-editor/markdown.ts +653 -0
  328. package/src/rich-text-editor/nodes.ts +497 -0
  329. package/src/rich-text-editor/render.ts +800 -0
  330. package/src/rich-text-editor/schema.ts +431 -0
  331. package/src/rich-text-editor/store.ts +39 -0
  332. package/src/rich-text-editor/suggest.ts +597 -0
  333. package/src/rich-text-editor/tables.ts +272 -0
  334. package/src/rich-text-editor/toolbar.ts +724 -0
  335. package/src/rich-text-editor/view.ts +2287 -0
  336. package/src/rich-text-editor/virtual.ts +347 -0
  337. package/src/richtext/node.ts +59 -30
  338. package/src/table/index.ts +14 -5
  339. package/src/terminal/backends.ts +4 -1
  340. package/src/terminal/index.ts +43 -15
  341. package/src/terminal/vt/node.ts +128 -29
  342. package/src/terminal/vt/renderer.ts +27 -5
  343. package/src/tree/index.ts +6 -4
  344. package/dist/markdown/ast.d.ts.map +0 -1
  345. package/dist/markdown/ast.js +0 -17
  346. package/dist/markdown/ast.js.map +0 -1
  347. package/dist/markdown/parse.d.ts.map +0 -1
  348. package/dist/markdown/parse.js.map +0 -1
  349. package/dist/markdown/tags.d.ts.map +0 -1
  350. package/dist/markdown/tags.js.map +0 -1
  351. /package/dist/{markdown → internal/markdown}/parse.d.ts +0 -0
  352. /package/dist/{markdown → internal/markdown}/tags.d.ts +0 -0
  353. /package/dist/{markdown → internal/markdown}/tags.js +0 -0
  354. /package/src/{markdown → internal/markdown}/tags.ts +0 -0
@@ -0,0 +1,1224 @@
1
+ // The GL renderer as `<Map>` mounts it: a pane (`./pane.ts`) with a
2
+ // `<glarea>` in it, and every frame drawn into the surface from vector tiles
3
+ // — the style, and over it the labels.
4
+ //
5
+ // **The camera is not this renderer's.** It is the map's controller's
6
+ // (`../controller.ts`), which the retained renderer answers to as well, so a
7
+ // fallback in the middle of a pan keeps the camera and the handle. What this
8
+ // file adds is what a camera move costs here: a frame. A pan step is two
9
+ // numbers on the controller and `requestFrame()`, with no render and no
10
+ // commit in the loop — which matters more here than for the retained
11
+ // renderer, because every frame here is a full redraw and the budget for one
12
+ // is the whole frame, not a strip.
13
+ //
14
+ // **Input reaches the map through the pane's handlers**, which a press, a
15
+ // drag and a wheel over the surface bubble up to on both backends — the
16
+ // pointer over a `<glarea>` is the tree's (react-x11#545) — and which end at
17
+ // the controller methods the retained renderer's element calls.
18
+ //
19
+ // **A failure is `<Map>`'s to handle.** A surface that will not come up, a
20
+ // connection with no direct GL, a context or a shader that will not build, a
21
+ // throw from a frame: each is reported once through `onFailure`, and `<Map>`
22
+ // moves an `'auto'` map to the retained renderer or tells a `'gl'` one
23
+ // through `onError`. Nothing here falls back on its own.
24
+ import React, { useEffect, useMemo } from 'react';
25
+ import type { ReactElement, ReactNode } from 'react';
26
+ import { useTheme } from 'react-x11';
27
+ import type { Style } from 'react-x11/style';
28
+
29
+ import { scaleOf } from '../../internal/units.js';
30
+ import type { MapController, MapPointerInput, MapView } from '../controller.js';
31
+ import {
32
+ ATTRIBUTION_OPACITY,
33
+ ATTRIBUTION_SIZE,
34
+ attributionLayout,
35
+ } from '../overlay.js';
36
+ import type { MapOverlay, OverlayPalette } from '../overlay.js';
37
+ import { prepareStyle } from '../paint.js';
38
+ import type { PreparedStyle } from '../paint.js';
39
+ import {
40
+ DEFAULT_TILE_SIZE,
41
+ project,
42
+ transformFor,
43
+ worldSize,
44
+ } from '../proj.js';
45
+ import type { MapCamera, ScreenRect } from '../proj.js';
46
+ import { attributionOf, pyramidOf } from '../sources.js';
47
+ import type { MapSource } from '../sources.js';
48
+ import type { MapStyle } from '../style.js';
49
+ import { defaultStyleFor, isDarkTheme, overlayPalette } from '../theme.js';
50
+ import type { MapFrameStats, MapProps } from '../types.js';
51
+ import { parseColor, premultiplied } from './color.js';
52
+ import type { Rgba } from './color.js';
53
+ import { renderCover } from './cover.js';
54
+ import type { CoverResult } from './cover.js';
55
+ import { MarkerBatcher } from './markers.js';
56
+ import {
57
+ buildOverlayBucket,
58
+ overlayRegion,
59
+ regionHolds,
60
+ regionPlacement,
61
+ } from './overlays.js';
62
+ import type { OverlayBucket } from './overlays.js';
63
+ import { GL_PANE } from './pane.js';
64
+ import { LABEL_INSTANCE, LabelPlacer } from './placement.js';
65
+ import type { LabelBatch, PlacementFrame } from './placement.js';
66
+ import { GlMapRenderer } from './renderer.js';
67
+ import type {
68
+ AttributionDraw,
69
+ FadeFrame,
70
+ OverlayDraw,
71
+ RenderFrame,
72
+ RenderTile,
73
+ } from './renderer.js';
74
+ import { GlTileStore } from './store.js';
75
+ import { LabelAtlas, SurfaceTextEngine } from './text.js';
76
+
77
+ const h = React.createElement;
78
+
79
+ /**
80
+ * Adaptive quality's rungs, cheapest last. Each leaves out more than the
81
+ * one before it, in the order that costs the picture least:
82
+ *
83
+ * 1. **The fill edge pass** — the half-pixel line that antialiases every
84
+ * polygon. A fifth of a dense frame, measured, and a staircase edge is
85
+ * invisible on a map in motion.
86
+ * 2. **The style's newest detail layers** — those whose `minZoom` is within
87
+ * `detail` levels of the zoom: buildings and service roads first, then
88
+ * sites, minor roads. The style already says which layers are details,
89
+ * by bringing them in last.
90
+ * 3. **A coarser tile level** — the parent level's tiles, drawn at this
91
+ * zoom: generalized geometry and fewer features, which is what a low-zoom
92
+ * frame (all land and water polygons) is made cheaper by.
93
+ */
94
+ export const QUALITY_LADDER: readonly {
95
+ edges: boolean;
96
+ detail: number;
97
+ coarser: number;
98
+ }[] = [
99
+ { edges: true, detail: 0, coarser: 0 },
100
+ { edges: false, detail: 0, coarser: 0 },
101
+ { edges: false, detail: 1, coarser: 0 },
102
+ { edges: false, detail: 2, coarser: 0 },
103
+ { edges: false, detail: 2, coarser: 1 },
104
+ { edges: false, detail: 3, coarser: 2 },
105
+ ];
106
+
107
+ type Rung = (typeof QUALITY_LADDER)[number];
108
+
109
+ /**
110
+ * The rung a moving frame is drawn at: the lowest predicted to fit the
111
+ * budget, and a rung up only once that one is predicted well inside it —
112
+ * so a frame that sits at the budget does not flicker between two rungs.
113
+ */
114
+ export function chooseQuality(
115
+ current: number,
116
+ predict: (rung: number) => number,
117
+ budgetMs: number,
118
+ ): number {
119
+ const top = QUALITY_LADDER.length - 1;
120
+ let rung = Math.max(0, Math.min(current, top));
121
+ while (rung < top && predict(rung) > budgetMs) rung++;
122
+ while (rung > 0 && predict(rung - 1) <= budgetMs * 0.75) rung--;
123
+ return rung;
124
+ }
125
+
126
+ /**
127
+ * Milliseconds per segment instance, learned from frames it measured. It
128
+ * starts at what this renderer measured on an M1 Pro (3.7 M instances in
129
+ * 8.5 ms) and moves toward each measured frame, so a slower GPU is priced
130
+ * right within a few frames of the first gesture.
131
+ */
132
+ class CostModel {
133
+ msPerInstance = 2.4e-6;
134
+ overheadMs = 0.4;
135
+
136
+ predict(instances: number): number {
137
+ return this.overheadMs + instances * this.msPerInstance;
138
+ }
139
+
140
+ learn(instances: number, ms: number): void {
141
+ // A near-empty frame is all overhead and says nothing about the slope.
142
+ if (instances < 50_000) return;
143
+ const slope = Math.max(0, ms - this.overheadMs) / instances;
144
+ this.msPerInstance += 0.25 * (slope - this.msPerInstance);
145
+ }
146
+ }
147
+
148
+ interface AreaNode {
149
+ requestFrame?(): void;
150
+ }
151
+
152
+ interface PaneNode {
153
+ focus?(): void;
154
+ contentBox?(): { x: number; y: number; width: number; height: number };
155
+ notifyA11ySceneChanged?(): void;
156
+ resolvedTextStyle?(): { family?: string };
157
+ }
158
+
159
+ interface DrawInfo {
160
+ width: number;
161
+ height: number;
162
+ node: object;
163
+ }
164
+
165
+ interface SyntheticPointer {
166
+ x: number;
167
+ y: number;
168
+ button?: number;
169
+ detail?: number;
170
+ shiftKey?: boolean;
171
+ ctrlKey?: boolean;
172
+ altKey?: boolean;
173
+ metaKey?: boolean;
174
+ deltaY?: number;
175
+ /** Whether the device measured the scroll rather than clicking it — a
176
+ * touchpad's valuators against a wheel's notches. */
177
+ smooth?: boolean;
178
+ keysym?: number;
179
+ capturePointer?(): void;
180
+ preventDefault?(): void;
181
+ }
182
+
183
+ /** How far outside the pane tiles are kept warm, in logical pixels — the
184
+ * retained renderer's ring, so an ordinary flick has its tiles. */
185
+ const COVER_PADDING = 256;
186
+ /** How long a fade waits for the new level's tiles before starting anyway. */
187
+ const FADE_WAIT_MS = 400;
188
+ const DEFAULT_BUDGET_MS = 12;
189
+ /** Milliseconds a frame may spend building tiles' buckets on this thread;
190
+ * a frame always builds at least one waiting tile. */
191
+ const BUILD_BUDGET_MS = 6;
192
+ /** Milliseconds a frame may spend measuring strings it has not set before
193
+ * — the one label cost that can be large (the first strings on X11 load
194
+ * fonts and rasterize glyphs in JS). Placement's remainder waits a frame. */
195
+ const TEXT_BUDGET_MOVING_MS = 1;
196
+ const TEXT_BUDGET_SETTLED_MS = 4;
197
+ /**
198
+ * How often a moving view is placed again, in milliseconds — every other
199
+ * frame or so. The labels shown follow the map every frame regardless; what
200
+ * waits a frame is a name coming into view, and what that buys is the frame
201
+ * that would have placed *and* measured *and* uploaded at once, which is
202
+ * what the late frames of a labelled pan were made of.
203
+ */
204
+ const PLACE_INTERVAL_MS = 25;
205
+ /** How long the zoom must hold still before labels not already shown are
206
+ * placed (see `PlacementFrame.admit`). Under the controller's settle
207
+ * window, so the frame that marks the camera settled is one that admits
208
+ * them. */
209
+ const ZOOM_QUIET_MS = 120;
210
+ /** Sources taken off the map whose tiles are kept for a switch back. */
211
+ const INACTIVE_STORES = 2;
212
+ const NO_RASTER: MapFrameStats['draw'] = {
213
+ features: 0,
214
+ vertices: 0,
215
+ decimated: 0,
216
+ culled: 0,
217
+ batches: 0,
218
+ };
219
+ /** A theme colour that does not parse falls back to these. */
220
+ const BLACK: Rgba = [0, 0, 0, 1];
221
+ const WHITE: Rgba = [1, 1, 1, 1];
222
+
223
+ const INDIRECT =
224
+ '@react-x11/components maps: this <glarea> draws through indirect GLX, ' +
225
+ 'which has no shaders — the GL renderer needs the direct backend, which ' +
226
+ "on X11 is createRoot({ glPolicy: 'auto' }) and a DRI3 or Apple-DRI server";
227
+
228
+ const globals = globalThis as unknown as {
229
+ performance?: { now(): number };
230
+ setTimeout(fn: () => void, ms: number): unknown;
231
+ clearTimeout(handle: unknown): void;
232
+ process?: { env?: Record<string, string | undefined> };
233
+ console?: { warn(message: string): void };
234
+ };
235
+ const now = (): number => globals.performance?.now() ?? Date.now();
236
+
237
+ const EMPTY_PANE: ScreenRect = { x: 0, y: 0, width: 0, height: 0 };
238
+ const EMPTY_COVER: CoverResult = {
239
+ tiles: [],
240
+ missing: [],
241
+ level: 0,
242
+ own: 0,
243
+ ancestors: 0,
244
+ descendants: 0,
245
+ inView: [],
246
+ };
247
+
248
+ /** Which levels a frame shows: one, or two while the second fades in. */
249
+ interface LevelPlan {
250
+ base: CoverResult;
251
+ next: CoverResult | null;
252
+ alpha: number;
253
+ }
254
+
255
+ /** One source on the map, as a frame found it. */
256
+ interface SourceCover {
257
+ source: MapSource;
258
+ store: GlTileStore;
259
+ pyramid: { minZoom: number; maxZoom: number; tileSize: number };
260
+ target: CoverResult;
261
+ }
262
+
263
+ /** What `<Map>` hands the GL renderer. */
264
+ export interface GlMapPaneProps {
265
+ /** The map's controller: its camera, its gestures and its handle. */
266
+ controller: MapController;
267
+ /** Everything `<Map>` was given. */
268
+ map: MapProps;
269
+ /** GL failed — the surface, the context, a shader, a frame. Called once;
270
+ * what happens next is `<Map>`'s decision. */
271
+ onFailure: (error: Error) => void;
272
+ style?: Style;
273
+ role?: string;
274
+ 'aria-label'?: string;
275
+ 'data-testname'?: string;
276
+ /** Drawn above the surface, as core draws a `<glarea>`'s children — given
277
+ * only where `useSupports('glOverlay')` says this connection does. */
278
+ children?: ReactNode;
279
+ }
280
+
281
+ class GlMapDriver implements MapView {
282
+ props: GlMapPaneProps;
283
+ theme: unknown = null;
284
+ private readonly _controller: MapController;
285
+ private _pane: PaneNode | null = null;
286
+ private _area: AreaNode | null = null;
287
+ private _renderer: GlMapRenderer | null = null;
288
+ private _gl: unknown = null;
289
+ private _failed = false;
290
+ /** A store per source object — the retained cache's rule: a source is its
291
+ * own cache, whatever its id. */
292
+ private readonly _stores = new Map<MapSource, GlTileStore>();
293
+ /** Sources taken off the map, oldest first, whose tiles are kept. */
294
+ private _inactive: MapSource[] = [];
295
+ private _style: MapStyle | null = null;
296
+ private _prepared: PreparedStyle | null = null;
297
+ private _committed: MapProps | null = null;
298
+ private _lastEnd: number | null = null;
299
+ private _drawnZoom: number | null = null;
300
+ /** When the zoom last changed — which holds new labels back. */
301
+ private _zoomedAt = -Infinity;
302
+ private _rung = 0;
303
+ private readonly _cost = new CostModel();
304
+ private _shown: number | null = null;
305
+ private _fade: {
306
+ to: number;
307
+ start: number | null;
308
+ waitSince: number;
309
+ } | null = null;
310
+ private readonly _placer = new LabelPlacer();
311
+ private readonly _markers = new MarkerBatcher();
312
+ /** The overlays' bucket, and what it was built from. */
313
+ private _overlay: {
314
+ bucket: OverlayBucket;
315
+ overlays: readonly MapOverlay[];
316
+ accent: string;
317
+ } | null = null;
318
+ private _atlas: LabelAtlas | null = null;
319
+ private _atlasKey = '';
320
+ /** No labels — the app has no fonts, or placing them failed — and no
321
+ * asking again every frame. */
322
+ private _noText = false;
323
+ /** The attribution's one instance. */
324
+ private readonly _attributionText = new Float32Array(LABEL_INSTANCE);
325
+ /** An attribution a frame could not draw yet — its string not measured,
326
+ * or its raster not in the texture — and the size it is set at. */
327
+ private _attributionWanted: { text: string; size: number } | null = null;
328
+ /** When labels were last placed. */
329
+ private _placedAt = -Infinity;
330
+ private _pumpTimer: unknown = null;
331
+ private _stats: MapFrameStats | null = null;
332
+ private _announced = false;
333
+ private _paneStyle: {
334
+ base: Style | undefined;
335
+ background: string;
336
+ value: Style;
337
+ } | null = null;
338
+
339
+ constructor(controller: MapController, props: GlMapPaneProps) {
340
+ this._controller = controller;
341
+ this.props = props;
342
+ }
343
+
344
+ // --- the controller's view ----------------------------------------------------
345
+
346
+ /** The pane in the window's logical pixels: its box's, which is current
347
+ * before the first frame and on a surface that never draws at all. */
348
+ pane(): ScreenRect {
349
+ const box = this._pane?.contentBox?.();
350
+ if (!box) return EMPTY_PANE;
351
+ const s = scaleOf(this._pane);
352
+ return {
353
+ x: box.x / s,
354
+ y: box.y / s,
355
+ width: box.width / s,
356
+ height: box.height / s,
357
+ };
358
+ }
359
+
360
+ scale(): number {
361
+ return scaleOf(this._pane);
362
+ }
363
+
364
+ /** Any camera move is one frame — there is no blit to prefer. */
365
+ moved(): void {
366
+ this.request();
367
+ }
368
+
369
+ /** Still: the next frame draws everything adaptive quality left out. */
370
+ settled(): void {
371
+ this.request();
372
+ }
373
+
374
+ /** `refresh()`: the style read again, and every tile's buckets and label
375
+ * anchors built again from its bytes. */
376
+ refresh(): void {
377
+ this._style = null;
378
+ this._prepared = null;
379
+ for (const store of this._stores.values()) store.rebuild();
380
+ this._placer.reset();
381
+ this.request();
382
+ }
383
+
384
+ stats(): MapFrameStats | null {
385
+ return this._stats;
386
+ }
387
+
388
+ focus(): void {
389
+ this._pane?.focus?.();
390
+ }
391
+
392
+ readonly request = (): void => {
393
+ this._area?.requestFrame?.();
394
+ };
395
+
396
+ attach(): void {
397
+ this._controller.attach(this);
398
+ }
399
+
400
+ readonly paneRef = (node: PaneNode | null): void => {
401
+ this._pane = node;
402
+ if (node) this._controller.attach(this);
403
+ };
404
+
405
+ readonly areaRef = (node: AreaNode | null): void => {
406
+ this._area = node;
407
+ };
408
+
409
+ /** A commit landed: what it changed that a frame shows asks for one. */
410
+ committed(): void {
411
+ const map = this.props.map;
412
+ const before = this._committed;
413
+ this._committed = map;
414
+ if (!before) return;
415
+ if (map.markers !== before.markers) {
416
+ this._pane?.notifyA11ySceneChanged?.();
417
+ }
418
+ if (
419
+ map.camera !== before.camera ||
420
+ map.markers !== before.markers ||
421
+ map.overlays !== before.overlays ||
422
+ map.sources !== before.sources ||
423
+ map.mapStyle !== before.mapStyle ||
424
+ map.attribution !== before.attribution ||
425
+ map.antialias !== before.antialias ||
426
+ map.fillRule !== before.fillRule ||
427
+ map.levelFade !== before.levelFade ||
428
+ map.adaptive !== before.adaptive
429
+ ) {
430
+ this.request();
431
+ }
432
+ }
433
+
434
+ /** The style's background: what the pane shows under the surface, and
435
+ * what the surface is cleared to. */
436
+ background(): string {
437
+ const style =
438
+ this.props.map.mapStyle ?? defaultStyleFor(isDarkTheme(this.theme));
439
+ return style.background ?? '#ffffff';
440
+ }
441
+
442
+ /** The pane's style, the same object for as long as nothing in it changes
443
+ * — a new one every render would be a damage claim every render. */
444
+ paneStyle(base: Style | undefined, background: string): Style {
445
+ const cached = this._paneStyle;
446
+ if (cached && cached.base === base && cached.background === background) {
447
+ return cached.value;
448
+ }
449
+ const value = [base, { backgroundColor: background }] as unknown as Style;
450
+ this._paneStyle = { base, background, value };
451
+ return value;
452
+ }
453
+
454
+ // --- input --------------------------------------------------------------------
455
+
456
+ private _local(ev: { x: number; y: number }): { x: number; y: number } {
457
+ const pane = this.pane();
458
+ return { x: ev.x - pane.x, y: ev.y - pane.y };
459
+ }
460
+
461
+ private _input(ev: SyntheticPointer): MapPointerInput {
462
+ const p = this._local(ev);
463
+ return {
464
+ x: p.x,
465
+ y: p.y,
466
+ button: ev.button,
467
+ detail: ev.detail,
468
+ shiftKey: ev.shiftKey,
469
+ ctrlKey: ev.ctrlKey,
470
+ altKey: ev.altKey,
471
+ metaKey: ev.metaKey,
472
+ };
473
+ }
474
+
475
+ /** The pane's handlers — the whole of the map's input, on both backends. */
476
+ readonly handlers = {
477
+ onMouseDown: (ev: SyntheticPointer): void => {
478
+ if (this._controller.pointerDown(this._input(ev)) === 'pan') {
479
+ this._pane?.focus?.();
480
+ }
481
+ ev.capturePointer?.();
482
+ },
483
+ onMouseMove: (ev: SyntheticPointer): void => {
484
+ const input = this._input(ev);
485
+ if (this._controller.dragging) this._controller.pointerDrag(input);
486
+ else this._controller.pointerMove(input);
487
+ },
488
+ onMouseUp: (ev: SyntheticPointer): void => {
489
+ this._controller.pointerUp(this._input(ev));
490
+ },
491
+ onMouseLeave: (): void => this._controller.pointerLeave(),
492
+ onWheel: (ev: SyntheticPointer): void => {
493
+ if (
494
+ this._controller.wheel(
495
+ this._local(ev),
496
+ ev.deltaY ?? 0,
497
+ ev.smooth === true,
498
+ )
499
+ ) {
500
+ ev.preventDefault?.();
501
+ }
502
+ },
503
+ onKeyDown: (ev: SyntheticPointer): void => {
504
+ if (this._controller.keyDown(ev.keysym ?? 0, ev.shiftKey ?? false)) {
505
+ ev.preventDefault?.();
506
+ }
507
+ },
508
+ };
509
+
510
+ // --- failure ------------------------------------------------------------------
511
+
512
+ readonly surfaceError = (error: Error): void => {
513
+ this._fail(error);
514
+ };
515
+
516
+ private _fail(error: unknown): void {
517
+ if (this._failed) return;
518
+ this._failed = true;
519
+ try {
520
+ this._renderer?.dispose();
521
+ } catch {
522
+ // A context that failed may not delete what it made either.
523
+ }
524
+ this._renderer = null;
525
+ this.props.onFailure(
526
+ error instanceof Error ? error : new Error(String(error)),
527
+ );
528
+ }
529
+
530
+ // --- the frame ------------------------------------------------------------------
531
+
532
+ readonly draw = (gl: unknown, info: DrawInfo): void => {
533
+ if (this._failed) return;
534
+ try {
535
+ if ((gl as { backend?: string }).backend !== 'direct') {
536
+ throw new Error(INDIRECT);
537
+ }
538
+ const controller = this._controller;
539
+ // A fit asked for before layout had a size lands in the first frame
540
+ // that has one, and this frame draws it.
541
+ controller.beginFrame();
542
+ controller.painting = true;
543
+ try {
544
+ this._frame(gl, info);
545
+ } finally {
546
+ controller.painting = false;
547
+ }
548
+ } catch (error) {
549
+ // Core hands an `onDraw` throw to `<glarea onError>` and nothing else;
550
+ // caught here, it is the map's failure, reported the one way.
551
+ this._fail(error);
552
+ }
553
+ };
554
+
555
+ private _styleNow(): { style: MapStyle; prepared: PreparedStyle } {
556
+ const style =
557
+ this.props.map.mapStyle ?? defaultStyleFor(isDarkTheme(this.theme));
558
+ if (style !== this._style || !this._prepared) {
559
+ this._style = style;
560
+ this._prepared = prepareStyle(style);
561
+ for (const store of this._stores.values()) {
562
+ store.setStyle(this._prepared);
563
+ }
564
+ }
565
+ return { style, prepared: this._prepared };
566
+ }
567
+
568
+ /** A store for every source on the map, in order; the stores of sources
569
+ * taken off it stop loading and keep their tiles, a couple of them. */
570
+ private _sourcesNow(
571
+ prepared: PreparedStyle,
572
+ ): { source: MapSource; store: GlTileStore }[] {
573
+ const map = this.props.map;
574
+ const sources = map.sources ?? [];
575
+ const out: { source: MapSource; store: GlTileStore }[] = [];
576
+ sources.forEach((source, index) => {
577
+ let store = this._stores.get(source);
578
+ if (!store) {
579
+ store = new GlTileStore({
580
+ source,
581
+ sourceId: source.id ?? `source-${index}`,
582
+ prepared,
583
+ onChange: this.request,
584
+ onError: (error, tile) => this.props.map.onTileError?.(error, tile),
585
+ workers: map.buildWorkers ?? 0,
586
+ });
587
+ this._stores.set(source, store);
588
+ }
589
+ out.push({ source, store });
590
+ });
591
+ this._inactive = this._inactive.filter((s) => !sources.includes(s));
592
+ for (const [source, store] of this._stores) {
593
+ if (sources.includes(source) || this._inactive.includes(source)) {
594
+ continue;
595
+ }
596
+ store.abortLoads();
597
+ this._inactive.push(source);
598
+ }
599
+ while (this._inactive.length > INACTIVE_STORES) {
600
+ const old = this._inactive.shift()!;
601
+ this._stores.get(old)?.dispose((data) => this._renderer?.release(data));
602
+ this._stores.delete(old);
603
+ }
604
+ return out;
605
+ }
606
+
607
+ private _budget(): number | null {
608
+ const adaptive = this.props.map.adaptive;
609
+ if (!adaptive) return null;
610
+ return typeof adaptive === 'object'
611
+ ? (adaptive.budgetMs ?? DEFAULT_BUDGET_MS)
612
+ : DEFAULT_BUDGET_MS;
613
+ }
614
+
615
+ /**
616
+ * The level fade: which level the frame is drawn from, and the one fading
617
+ * in over it.
618
+ *
619
+ * A new level is waited for — briefly, until every tile of it in view has
620
+ * answered — so the fade shows it arriving rather than a stand-in for it;
621
+ * then it fades in over the level it replaces, with an ease at both ends.
622
+ * A level more than one step away is not faded (the view it would fade
623
+ * from is sixteen times the tiles), and a change of target halfway
624
+ * through a fade takes the half-shown level as the one it fades from.
625
+ */
626
+ private _planLevels(
627
+ target: CoverResult,
628
+ cover: (level: number) => CoverResult,
629
+ at: number,
630
+ ): LevelPlan {
631
+ const fadeMs = this.props.map.levelFade ?? 0;
632
+ const to = target.level;
633
+ const plain = { base: target, next: null, alpha: 0 };
634
+ if (fadeMs <= 0 || this._shown === null || Math.abs(to - this._shown) > 1) {
635
+ this._shown = to;
636
+ this._fade = null;
637
+ return plain;
638
+ }
639
+ if (to === this._shown) {
640
+ this._fade = null;
641
+ return plain;
642
+ }
643
+ let fade = this._fade;
644
+ if (!fade || fade.to !== to) {
645
+ if (fade && fade.start !== null && (at - fade.start) / fadeMs >= 0.5) {
646
+ this._shown = fade.to;
647
+ }
648
+ if (this._shown === to) {
649
+ this._fade = null;
650
+ return plain;
651
+ }
652
+ fade = this._fade = { to, start: null, waitSince: at };
653
+ }
654
+ const base = cover(this._shown);
655
+ if (fade.start === null) {
656
+ if (target.missing.length > 0 && at - fade.waitSince < FADE_WAIT_MS) {
657
+ return { base, next: null, alpha: 0 };
658
+ }
659
+ fade.start = at;
660
+ }
661
+ const p = (at - fade.start) / fadeMs;
662
+ if (p >= 1) {
663
+ this._shown = to;
664
+ this._fade = null;
665
+ return plain;
666
+ }
667
+ return { base, next: target, alpha: p * p * (3 - 2 * p) };
668
+ }
669
+
670
+ private _frame(gl: unknown, info: DrawInfo): void {
671
+ const map = this.props.map;
672
+ const controller = this._controller;
673
+ const scale = scaleOf(info.node);
674
+ if (gl !== this._gl) {
675
+ // A new context — the surface was recreated — owns none of the old
676
+ // one's buffers, so everything is uploaded again from the buckets the
677
+ // stores still hold.
678
+ this._renderer = null;
679
+ this._gl = gl;
680
+ }
681
+ this._renderer ??= new GlMapRenderer(gl, {
682
+ antialias: map.antialias,
683
+ fillRule: map.fillRule,
684
+ });
685
+ const renderer = this._renderer;
686
+ renderer.antialias = map.antialias ?? true;
687
+ renderer.fillRule = map.fillRule ?? 'nonzero';
688
+ const { style, prepared } = this._styleNow();
689
+ const camera = controller.camera();
690
+ if (this._drawnZoom !== null && this._drawnZoom !== camera.zoom) {
691
+ this._zoomedAt = now();
692
+ }
693
+ this._drawnZoom = camera.zoom;
694
+ const pane = { width: info.width / scale, height: info.height / scale };
695
+ const at = now();
696
+ const moving = controller.moving;
697
+ const budget = this._budget();
698
+
699
+ // Every source's tiles: built as far as the budget goes, then asked
700
+ // for — the view, and the ring around it that keeps a pan's tiles warm.
701
+ const sources = this._sourcesNow(prepared);
702
+ const buildStart = now();
703
+ const deadline = buildStart + BUILD_BUDGET_MS;
704
+ let more = false;
705
+ for (const { store } of sources) {
706
+ store.tick();
707
+ if (store.pump(deadline)) more = true;
708
+ }
709
+ const buildMs = now() - buildStart;
710
+ const covers: SourceCover[] = sources.map(({ source, store }) => {
711
+ const pyramid = pyramidOf(source);
712
+ const target = renderCover(camera, pane, scale, pyramid, store, {
713
+ padding: COVER_PADDING,
714
+ });
715
+ store.want(target.missing);
716
+ return { source, store, pyramid, target };
717
+ });
718
+
719
+ // The level fade and adaptive quality are the first source's — the
720
+ // basemap's; a pyramid over it is drawn at its own level throughout.
721
+ const primary = covers[0] ?? null;
722
+ const coverAt = (level: number): CoverResult =>
723
+ primary
724
+ ? renderCover(camera, pane, scale, primary.pyramid, primary.store, {
725
+ level,
726
+ })
727
+ : EMPTY_COVER;
728
+ const plan: LevelPlan = primary
729
+ ? this._planLevels(primary.target, coverAt, at)
730
+ : { base: EMPTY_COVER, next: null, alpha: 0 };
731
+ if (primary && plan.base !== primary.target) {
732
+ primary.store.want(plan.base.missing);
733
+ }
734
+
735
+ const frameOf = (tiles: RenderTile[][], rung: Rung): RenderFrame => ({
736
+ width: info.width,
737
+ height: info.height,
738
+ zoom: camera.zoom,
739
+ scale,
740
+ style: prepared,
741
+ background: style.background,
742
+ sources: tiles,
743
+ detail: rung.detail,
744
+ edges: rung.edges ? undefined : false,
745
+ });
746
+ // The frame at a rung: the plan's levels with that rung's detail left
747
+ // out — and, when no fade is running, a coarser level for the base.
748
+ const build = (
749
+ r: number,
750
+ ): { frame: RenderFrame; fade: FadeFrame | null } => {
751
+ const q = QUALITY_LADDER[r];
752
+ const base: RenderTile[][] = [];
753
+ const arriving: RenderTile[][] = [];
754
+ covers.forEach((c, i) => {
755
+ let own = i === 0 ? plan.base : c.target;
756
+ if (i === 0 && q.coarser > 0 && !plan.next) {
757
+ const coarser = Math.max(c.pyramid.minZoom, own.level - q.coarser);
758
+ if (coarser < own.level) own = coverAt(coarser);
759
+ }
760
+ base.push(own.tiles);
761
+ arriving.push(i === 0 && plan.next ? plan.next.tiles : c.target.tiles);
762
+ });
763
+ return {
764
+ frame: frameOf(base, q),
765
+ fade: plan.next
766
+ ? { frame: frameOf(arriving, q), alpha: plan.alpha }
767
+ : null,
768
+ };
769
+ };
770
+ let rung = 0;
771
+ let predictedMs = 0;
772
+ if (budget !== null && moving && primary) {
773
+ // The coarser level is what the ladder's last rungs draw, so ask for
774
+ // it too — after the view's own tiles, which come first.
775
+ primary.store.want(
776
+ coverAt(Math.max(primary.pyramid.minZoom, primary.target.level - 1))
777
+ .missing,
778
+ );
779
+ const predict = (r: number): number => {
780
+ const built = build(r);
781
+ const work =
782
+ renderer.estimate(built.frame) +
783
+ (built.fade ? renderer.estimate(built.fade.frame) : 0);
784
+ return this._cost.predict(work);
785
+ };
786
+ rung = chooseQuality(this._rung, predict, budget);
787
+ predictedMs = predict(rung);
788
+ }
789
+ this._rung = rung;
790
+ const { frame, fade } = build(rung);
791
+
792
+ // The text: the labels, and the attribution, set in the same atlas.
793
+ let labels: LabelBatch | null = null;
794
+ let attribution: AttributionDraw | null = null;
795
+ let labelMs = 0;
796
+ if (!this._noText) {
797
+ const started = now();
798
+ try {
799
+ const atlas = this._atlasFor(info.node, style, scale);
800
+ if (atlas) {
801
+ atlas.beginFrame(
802
+ now() + (moving ? TEXT_BUDGET_MOVING_MS : TEXT_BUDGET_SETTLED_MS),
803
+ );
804
+ // The attribution before the names: it is one string, measured
805
+ // once, and a frame whose budget went on names would leave it
806
+ // for a later one — for as long as names keep arriving.
807
+ attribution = this._attributionFor(atlas, frame);
808
+ labels = this._labelsFor(atlas, frame, fade, at, moving);
809
+ this._pumpSoon();
810
+ }
811
+ } catch (error) {
812
+ // Labels are the map's to lose, not the frame's: a failure placing
813
+ // them turns them off, once and said, and the map draws on.
814
+ this._noText = true;
815
+ this._atlas?.dispose();
816
+ this._atlas = null;
817
+ if (globals.process?.env?.NODE_ENV !== 'production') {
818
+ globals.console?.warn(
819
+ `@react-x11/components: <Map> stopped drawing labels: ${String(error)}`,
820
+ );
821
+ }
822
+ }
823
+ labelMs = now() - started;
824
+ }
825
+
826
+ // The overlays and the markers, laid out on the same world as the
827
+ // tiles under them.
828
+ const palette = overlayPalette(this.theme);
829
+ const overlays = this._overlaysFor(
830
+ renderer,
831
+ camera,
832
+ pane,
833
+ scale,
834
+ palette,
835
+ info,
836
+ );
837
+ const markers = map.markers?.length
838
+ ? this._markers.batch(
839
+ map.markers,
840
+ transformFor(camera, pane, DEFAULT_TILE_SIZE),
841
+ pane,
842
+ scale,
843
+ palette,
844
+ )
845
+ : null;
846
+
847
+ // Adaptive quality prices moving frames with a rate it learns from
848
+ // frames it times — and it times only settled ones. Timing a frame means
849
+ // `glFinish`, which holds this thread until the GPU is done and, on the
850
+ // Cocoa backend, until the surface is: a moving frame cannot afford
851
+ // that, and what it reads is not the frame's cost either. Timed on every
852
+ // moving frame, the cheapest rungs read 16–52 ms of what is a few
853
+ // milliseconds of drawing, and the model learned from that put nearly
854
+ // every frame on the coarsest rung. A settled frame is drawn once and
855
+ // animates nothing, so it can afford two finishes: one to drain what
856
+ // came before it, and one to time it alone. It still errs slow — a lone
857
+ // frame after a pause meets a GPU that has clocked down — which errs on
858
+ // the side of frame rate.
859
+ const calibrate = budget !== null && !moving;
860
+ const finish = (): void => (gl as { finish?(): void }).finish?.();
861
+ if (calibrate) finish();
862
+ const drawStart = now();
863
+ const stats = renderer.render(frame, {
864
+ fade,
865
+ labels,
866
+ overlays,
867
+ markers,
868
+ attribution,
869
+ });
870
+ let measuredMs = 0;
871
+ if (calibrate) {
872
+ finish();
873
+ measuredMs = now() - drawStart;
874
+ // An upload is not drawing, and would teach the model it was.
875
+ if (stats.uploads === 0) this._cost.learn(stats.instances, measuredMs);
876
+ }
877
+ map.onAfterDraw?.(gl, { width: info.width, height: info.height });
878
+ for (const { store } of sources) {
879
+ store.evict((data) => renderer.release(data));
880
+ }
881
+
882
+ const end = now();
883
+ const interval = this._lastEnd === null ? 0 : end - this._lastEnd;
884
+ this._lastEnd = end;
885
+ let tiles = 0;
886
+ let ready = 0;
887
+ let fromAncestor = 0;
888
+ let fromDescendant = 0;
889
+ let errors = 0;
890
+ let building = 0;
891
+ let loading = 0;
892
+ for (const c of covers) {
893
+ tiles += c.target.inView.length;
894
+ ready += c.target.own;
895
+ fromAncestor += c.target.ancestors;
896
+ fromDescendant += c.target.descendants;
897
+ errors += c.store.failedAmong(c.target.inView);
898
+ building += c.store.building;
899
+ loading += c.store.loading;
900
+ }
901
+ const level = primary?.target.level ?? 0;
902
+ this._stats = {
903
+ renderer: 'gl',
904
+ // Nothing rasterized, no surfaces held, and every frame whole.
905
+ rasterMs: 0,
906
+ surfaceBytes: 0,
907
+ damage: null,
908
+ draw: NO_RASTER,
909
+ drawMs: stats.cpuMs + labelMs,
910
+ tiles,
911
+ ready,
912
+ fromAncestor,
913
+ fromDescendant,
914
+ pending: building,
915
+ restyling: false,
916
+ labels: stats.labels,
917
+ errors,
918
+ gl: {
919
+ interval,
920
+ cpuMs: stats.cpuMs,
921
+ buildMs,
922
+ building,
923
+ loading,
924
+ gpuBytes: renderer.gpuBytes,
925
+ instances: stats.instances,
926
+ drawCalls: stats.drawCalls,
927
+ uploads: stats.uploads,
928
+ uploadBytes: stats.uploadBytes,
929
+ offscreen: stats.offscreen,
930
+ level,
931
+ shownLevel: this._shown ?? level,
932
+ fade: stats.fade,
933
+ quality: rung,
934
+ predictedMs,
935
+ measuredMs,
936
+ moving,
937
+ labelCandidates: labels ? this._placer.stats.candidates : 0,
938
+ labelsPlaced: labels ? this._placer.stats.placed : 0,
939
+ labelMs,
940
+ textPending: this._atlas?.pending ?? false,
941
+ },
942
+ };
943
+ // A label still fading, strings this frame had no budget to measure, or
944
+ // rasters still to go into the texture want the next frame; a raster
945
+ // in flight asks for one itself when it lands.
946
+ const labelling =
947
+ labels !== null &&
948
+ (this._placer.animating ||
949
+ this._atlas?.starved === true ||
950
+ this._atlas?.uploading === true);
951
+ // An attribution this frame could not draw may have gone into the
952
+ // texture during it — the upload happens as the labels draw, after the
953
+ // frame chose what to draw — and then it is the next frame's.
954
+ const wanted = this._attributionWanted;
955
+ const attributing =
956
+ wanted !== null && this._atlas?.entry(wanted.text, wanted.size) != null;
957
+ if (more || this._fade || labelling || attributing) this.request();
958
+ if (!this._announced) {
959
+ this._announced = true;
960
+ this._pane?.notifyA11ySceneChanged?.();
961
+ }
962
+ map.onFrame?.(this._stats);
963
+ }
964
+
965
+ /**
966
+ * The overlays' bucket, placed for this frame: the one there is while the
967
+ * overlays are the same array, the theme's accent the same colour and
968
+ * the view inside the bucket's region, and a new one around the view
969
+ * otherwise.
970
+ */
971
+ private _overlaysFor(
972
+ renderer: GlMapRenderer,
973
+ camera: MapCamera,
974
+ pane: { width: number; height: number },
975
+ scale: number,
976
+ palette: OverlayPalette,
977
+ info: DrawInfo,
978
+ ): OverlayDraw | null {
979
+ const overlays = this.props.map.overlays;
980
+ let current = this._overlay;
981
+ if (!overlays || overlays.length === 0) {
982
+ if (current) renderer.release(current.bucket.data);
983
+ this._overlay = null;
984
+ return null;
985
+ }
986
+ if (
987
+ !current ||
988
+ current.overlays !== overlays ||
989
+ current.accent !== palette.accent ||
990
+ !regionHolds(current.bucket.region, camera, pane, scale)
991
+ ) {
992
+ if (current) renderer.release(current.bucket.data);
993
+ current = this._overlay = {
994
+ bucket: buildOverlayBucket(
995
+ overlays,
996
+ overlayRegion(camera, pane, scale),
997
+ palette,
998
+ ),
999
+ overlays,
1000
+ accent: palette.accent,
1001
+ };
1002
+ }
1003
+ const { bucket } = current;
1004
+ return {
1005
+ data: bucket.data,
1006
+ passes: bucket.passes,
1007
+ ...regionPlacement(bucket.region, camera, info.width, info.height, scale),
1008
+ };
1009
+ }
1010
+
1011
+ /**
1012
+ * The atlas every string on the map is set in — the labels, and the
1013
+ * attribution. Made on the first frame, from the app the surface belongs
1014
+ * to, and again when the face or the scale changes; null, and not asked
1015
+ * for again, when the app has no fonts.
1016
+ */
1017
+ private _atlasFor(
1018
+ node: object,
1019
+ style: MapStyle,
1020
+ scale: number,
1021
+ ): LabelAtlas | null {
1022
+ const family =
1023
+ style.fontFamily ??
1024
+ this._pane?.resolvedTextStyle?.().family ??
1025
+ 'sans-serif';
1026
+ const key = `${family}|${scale}`;
1027
+ if (this._atlas && this._atlasKey === key) return this._atlas;
1028
+ this._atlas?.dispose();
1029
+ this._atlas = null;
1030
+ const engine = SurfaceTextEngine.forApp(
1031
+ (node as { app?: unknown }).app,
1032
+ family,
1033
+ );
1034
+ if (!engine) {
1035
+ this._noText = true;
1036
+ return null;
1037
+ }
1038
+ // Margin for a halo of two logical pixels, and the texel either side
1039
+ // that keeps its samples inside it (see `quadInset`).
1040
+ this._atlas = new LabelAtlas(engine, { pad: 2 * Math.ceil(2 * scale) + 2 });
1041
+ this._atlas.onChange = this.request;
1042
+ this._atlasKey = key;
1043
+ this._placer.reset();
1044
+ return this._atlas;
1045
+ }
1046
+
1047
+ /**
1048
+ * The frame's labels: placed over the tiles of the level being shown —
1049
+ * the arriving one, once a fade is past halfway — and batched for the
1050
+ * renderer.
1051
+ */
1052
+ private _labelsFor(
1053
+ atlas: LabelAtlas,
1054
+ frame: RenderFrame,
1055
+ fade: FadeFrame | null,
1056
+ at: number,
1057
+ moving: boolean,
1058
+ ): LabelBatch {
1059
+ const from = fade && fade.alpha >= 0.5 ? fade.frame : frame;
1060
+ const centre = project(this._controller.camera().center);
1061
+ const placement: PlacementFrame = {
1062
+ width: frame.width,
1063
+ height: frame.height,
1064
+ scale: frame.scale,
1065
+ zoom: frame.zoom,
1066
+ style: frame.style,
1067
+ tiles: from.sources.flat(),
1068
+ centerX: centre.x,
1069
+ centerY: centre.y,
1070
+ // The projection's world, which the cover lays every source out on.
1071
+ world: worldSize(frame.zoom, DEFAULT_TILE_SIZE) * frame.scale,
1072
+ now: at,
1073
+ admit: at - this._zoomedAt >= ZOOM_QUIET_MS,
1074
+ moving,
1075
+ };
1076
+ if (!moving || at - this._placedAt >= PLACE_INTERVAL_MS) {
1077
+ this._placer.place(placement, atlas);
1078
+ this._placedAt = at;
1079
+ }
1080
+ return this._placer.batch(placement, atlas);
1081
+ }
1082
+
1083
+ /**
1084
+ * The attribution, as the retained renderer draws it: the same box on the
1085
+ * same pixels (`attributionLayout`), the text in the labels' face, from
1086
+ * the labels' atlas. Null while there is none to draw — `attribution=""`,
1087
+ * or no source that names one — and until its raster is in the texture,
1088
+ * so the box and its text arrive together.
1089
+ */
1090
+ private _attributionFor(
1091
+ atlas: LabelAtlas,
1092
+ frame: RenderFrame,
1093
+ ): AttributionDraw | null {
1094
+ this._attributionWanted = null;
1095
+ const map = this.props.map;
1096
+ const text = attributionOf(map.attribution, map.sources ?? []);
1097
+ if (!text) return null;
1098
+ const s = frame.scale;
1099
+ const size = ATTRIBUTION_SIZE * s;
1100
+ const box = atlas.measure(text, size);
1101
+ const entry = box ? atlas.entry(text, size) : null;
1102
+ if (!box || !entry) {
1103
+ this._attributionWanted = { text, size };
1104
+ return null;
1105
+ }
1106
+ const at = attributionLayout(
1107
+ { width: box.width / s, height: box.height / s },
1108
+ { x: 0, y: 0, width: frame.width / s, height: frame.height / s },
1109
+ s,
1110
+ );
1111
+ const palette = overlayPalette(this.theme);
1112
+ // The string sits `pad` inside its raster, and a level label's quad is
1113
+ // centred on its anchor and set on whole pixels: this anchor puts the
1114
+ // string's corner on the layout's.
1115
+ const d = this._attributionText;
1116
+ d[0] = at.x - atlas.pad + entry.width / 2;
1117
+ d[1] = at.y - atlas.pad + entry.height / 2;
1118
+ d[2] = 1;
1119
+ d[3] = 0;
1120
+ d[4] = entry.x;
1121
+ d[5] = entry.y;
1122
+ d[6] = entry.width;
1123
+ d[7] = entry.height;
1124
+ d.set(premultiplied(parseColor(palette.text) ?? BLACK), 8);
1125
+ d.fill(0, 12, 17); // no halo: the box is what it reads against
1126
+ d[17] = 1;
1127
+ return {
1128
+ box: at.box,
1129
+ boxColor: premultiplied(
1130
+ parseColor(palette.background) ?? WHITE,
1131
+ ATTRIBUTION_OPACITY,
1132
+ ),
1133
+ text: { atlas, instances: d, count: 1 },
1134
+ };
1135
+ }
1136
+
1137
+ /**
1138
+ * Rasterize what placement asked for — after this frame rather than in
1139
+ * it. Setting a batch of strings is milliseconds of this thread, and the
1140
+ * gap between two frames is where that costs no frame anything.
1141
+ */
1142
+ private _pumpSoon(): void {
1143
+ if (this._pumpTimer !== null || !this._atlas?.pending) return;
1144
+ this._pumpTimer = globals.setTimeout(() => {
1145
+ this._pumpTimer = null;
1146
+ this._atlas?.pump();
1147
+ }, 0);
1148
+ }
1149
+
1150
+ /**
1151
+ * Let go of everything GL: the stores, the atlas, the renderer — all of
1152
+ * it made again, lazily, by the next frame if there is one. React's
1153
+ * strict-mode double effect is the case where there is.
1154
+ */
1155
+ dispose(): void {
1156
+ this._controller.detach(this);
1157
+ if (this._pumpTimer !== null) globals.clearTimeout(this._pumpTimer);
1158
+ this._pumpTimer = null;
1159
+ this._atlas?.dispose();
1160
+ this._atlas = null;
1161
+ this._atlasKey = '';
1162
+ for (const store of this._stores.values()) {
1163
+ store.dispose((data) => this._renderer?.release(data));
1164
+ }
1165
+ this._stores.clear();
1166
+ this._inactive = [];
1167
+ // Its buffers go with the renderer's.
1168
+ this._overlay = null;
1169
+ try {
1170
+ this._renderer?.dispose();
1171
+ } catch {
1172
+ // The surface may be gone already, and its context with it.
1173
+ }
1174
+ this._renderer = null;
1175
+ this._gl = null;
1176
+ }
1177
+ }
1178
+
1179
+ /**
1180
+ * The GL half of `<Map>`: a pane with a `<glarea>` in it, drawn every frame
1181
+ * from vector tiles. Mounted by `<Map>` when it chooses GL; not exported
1182
+ * from the package on its own.
1183
+ */
1184
+ export function GlMapPane(props: GlMapPaneProps): ReactElement {
1185
+ const theme = useTheme();
1186
+ const driver = useMemo(
1187
+ () => new GlMapDriver(props.controller, props),
1188
+ [props.controller],
1189
+ );
1190
+ driver.props = props;
1191
+ driver.theme = theme;
1192
+ useEffect(() => {
1193
+ driver.attach();
1194
+ return () => driver.dispose();
1195
+ }, [driver]);
1196
+ useEffect(() => driver.committed());
1197
+ const background = driver.background();
1198
+ return h(
1199
+ GL_PANE,
1200
+ {
1201
+ ref: driver.paneRef,
1202
+ mapController: props.controller,
1203
+ style: driver.paneStyle(props.style, background),
1204
+ role: props.role,
1205
+ 'aria-label': props['aria-label'],
1206
+ 'data-testname': props['data-testname'],
1207
+ ...driver.handlers,
1208
+ },
1209
+ h(
1210
+ 'glarea',
1211
+ {
1212
+ ref: driver.areaRef,
1213
+ style: FILL,
1214
+ clearColor: background,
1215
+ frameLoop: 'demand',
1216
+ onDraw: driver.draw,
1217
+ onError: driver.surfaceError,
1218
+ },
1219
+ props.children,
1220
+ ),
1221
+ );
1222
+ }
1223
+
1224
+ const FILL = { flexGrow: 1 };