@moondraft/import 0.0.0-stage → 0.1.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 (323) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +34 -0
  3. package/README.md +36 -2
  4. package/SOURCE.md +169 -0
  5. package/dist/adapter/convert.d.ts +122 -0
  6. package/dist/adapter/convert.js +2302 -0
  7. package/dist/adapter/figma.d.ts +9 -0
  8. package/dist/adapter/figma.js +30 -0
  9. package/dist/adapter/file-components.d.ts +14 -0
  10. package/dist/adapter/file-components.js +262 -0
  11. package/dist/adapter/file-resources.d.ts +29 -0
  12. package/dist/adapter/file-resources.js +562 -0
  13. package/dist/adapter/index.d.ts +6 -0
  14. package/dist/adapter/index.js +9 -0
  15. package/dist/adapter/link.d.ts +45 -0
  16. package/dist/adapter/link.js +688 -0
  17. package/dist/adapter/payload.d.ts +31 -0
  18. package/dist/adapter/payload.js +78 -0
  19. package/dist/adapter/shapes.d.ts +31 -0
  20. package/dist/adapter/shapes.js +75 -0
  21. package/dist/adapter/variables.d.ts +44 -0
  22. package/dist/adapter/variables.js +103 -0
  23. package/dist/figma-file.d.ts +38 -0
  24. package/dist/figma-file.js +97 -0
  25. package/dist/figma-worker.d.ts +11 -0
  26. package/dist/figma-worker.js +12 -0
  27. package/dist/figma.d.ts +26 -0
  28. package/dist/figma.js +96 -0
  29. package/dist/index.d.ts +28 -0
  30. package/dist/index.js +49 -0
  31. package/dist/report.d.ts +15 -0
  32. package/dist/report.js +69 -0
  33. package/dist/svg.d.ts +33 -0
  34. package/dist/svg.js +44 -0
  35. package/dist/syntax.d.ts +8 -0
  36. package/dist/syntax.js +19 -0
  37. package/dist/taco/figma-import/clipboard.d.ts +25 -0
  38. package/dist/taco/figma-import/clipboard.js +87 -0
  39. package/dist/taco/figma-import/clipboardSize.d.ts +31 -0
  40. package/dist/taco/figma-import/clipboardSize.js +107 -0
  41. package/dist/taco/figma-import/container/compression.d.ts +9 -0
  42. package/dist/taco/figma-import/container/compression.js +174 -0
  43. package/dist/taco/figma-import/container/error.d.ts +15 -0
  44. package/dist/taco/figma-import/container/error.js +19 -0
  45. package/dist/taco/figma-import/container/kiwiContainer.d.ts +38 -0
  46. package/dist/taco/figma-import/container/kiwiContainer.js +61 -0
  47. package/dist/taco/figma-import/container/limits.d.ts +22 -0
  48. package/dist/taco/figma-import/container/limits.js +22 -0
  49. package/dist/taco/figma-import/container/zip.d.ts +14 -0
  50. package/dist/taco/figma-import/container/zip.js +154 -0
  51. package/dist/taco/figma-import/figFile.d.ts +34 -0
  52. package/dist/taco/figma-import/figFile.js +91 -0
  53. package/dist/taco/figma-import/figFileDocument.d.ts +25 -0
  54. package/dist/taco/figma-import/figFileDocument.js +100 -0
  55. package/dist/taco/figma-import/import/blobs.d.ts +10 -0
  56. package/dist/taco/figma-import/import/blobs.js +23 -0
  57. package/dist/taco/figma-import/import/carry.d.ts +11 -0
  58. package/dist/taco/figma-import/import/carry.js +33 -0
  59. package/dist/taco/figma-import/import/componentProps.d.ts +84 -0
  60. package/dist/taco/figma-import/import/componentProps.js +313 -0
  61. package/dist/taco/figma-import/import/componentSets.d.ts +83 -0
  62. package/dist/taco/figma-import/import/componentSets.js +647 -0
  63. package/dist/taco/figma-import/import/converters/effects.d.ts +31 -0
  64. package/dist/taco/figma-import/import/converters/effects.js +127 -0
  65. package/dist/taco/figma-import/import/converters/ellipse.d.ts +7 -0
  66. package/dist/taco/figma-import/import/converters/ellipse.js +54 -0
  67. package/dist/taco/figma-import/import/converters/frame.d.ts +21 -0
  68. package/dist/taco/figma-import/import/converters/frame.js +55 -0
  69. package/dist/taco/figma-import/import/converters/gradient.d.ts +72 -0
  70. package/dist/taco/figma-import/import/converters/gradient.js +106 -0
  71. package/dist/taco/figma-import/import/converters/group.d.ts +21 -0
  72. package/dist/taco/figma-import/import/converters/group.js +39 -0
  73. package/dist/taco/figma-import/import/converters/image.d.ts +13 -0
  74. package/dist/taco/figma-import/import/converters/image.js +83 -0
  75. package/dist/taco/figma-import/import/converters/layout.d.ts +34 -0
  76. package/dist/taco/figma-import/import/converters/layout.js +168 -0
  77. package/dist/taco/figma-import/import/converters/line.d.ts +11 -0
  78. package/dist/taco/figma-import/import/converters/line.js +40 -0
  79. package/dist/taco/figma-import/import/converters/rectangle.d.ts +3 -0
  80. package/dist/taco/figma-import/import/converters/rectangle.js +11 -0
  81. package/dist/taco/figma-import/import/converters/section.d.ts +9 -0
  82. package/dist/taco/figma-import/import/converters/section.js +35 -0
  83. package/dist/taco/figma-import/import/converters/shared.d.ts +68 -0
  84. package/dist/taco/figma-import/import/converters/shared.js +362 -0
  85. package/dist/taco/figma-import/import/converters/text.d.ts +41 -0
  86. package/dist/taco/figma-import/import/converters/text.js +576 -0
  87. package/dist/taco/figma-import/import/converters/vector.d.ts +84 -0
  88. package/dist/taco/figma-import/import/converters/vector.js +468 -0
  89. package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +98 -0
  90. package/dist/taco/figma-import/import/converters/vectorNetwork.js +385 -0
  91. package/dist/taco/figma-import/import/fields.d.ts +15 -0
  92. package/dist/taco/figma-import/import/fields.js +29 -0
  93. package/dist/taco/figma-import/import/instances.d.ts +163 -0
  94. package/dist/taco/figma-import/import/instances.js +1323 -0
  95. package/dist/taco/figma-import/import/nestingCycles.d.ts +86 -0
  96. package/dist/taco/figma-import/import/nestingCycles.js +488 -0
  97. package/dist/taco/figma-import/import/slots.d.ts +56 -0
  98. package/dist/taco/figma-import/import/slots.js +96 -0
  99. package/dist/taco/figma-import/import/styles.d.ts +46 -0
  100. package/dist/taco/figma-import/import/styles.js +42 -0
  101. package/dist/taco/figma-import/import/tree.d.ts +66 -0
  102. package/dist/taco/figma-import/import/tree.js +194 -0
  103. package/dist/taco/figma-import/import/types.d.ts +232 -0
  104. package/dist/taco/figma-import/import/types.js +33 -0
  105. package/dist/taco/figma-import/import/variables.d.ts +136 -0
  106. package/dist/taco/figma-import/import/variables.js +762 -0
  107. package/dist/taco/figma-import/import/variantTrees.d.ts +20 -0
  108. package/dist/taco/figma-import/import/variantTrees.js +480 -0
  109. package/dist/taco/figma-import/import/walk.d.ts +159 -0
  110. package/dist/taco/figma-import/import/walk.js +1297 -0
  111. package/dist/taco/figma-import/index.d.ts +22 -0
  112. package/dist/taco/figma-import/index.js +13 -0
  113. package/dist/taco/figma-import/kiwi/byteReader.d.ts +37 -0
  114. package/dist/taco/figma-import/kiwi/byteReader.js +151 -0
  115. package/dist/taco/figma-import/kiwi/error.d.ts +14 -0
  116. package/dist/taco/figma-import/kiwi/error.js +29 -0
  117. package/dist/taco/figma-import/kiwi/limits.d.ts +18 -0
  118. package/dist/taco/figma-import/kiwi/limits.js +18 -0
  119. package/dist/taco/figma-import/kiwi/message.d.ts +10 -0
  120. package/dist/taco/figma-import/kiwi/message.js +145 -0
  121. package/dist/taco/figma-import/kiwi/schema.d.ts +42 -0
  122. package/dist/taco/figma-import/kiwi/schema.js +206 -0
  123. package/dist/taco/figma-import/kiwi/types.d.ts +46 -0
  124. package/dist/taco/figma-import/kiwi/types.js +18 -0
  125. package/dist/taco/model/agent-hidden-fields.d.ts +20 -0
  126. package/dist/taco/model/agent-hidden-fields.js +29 -0
  127. package/dist/taco/model/asset-users.d.ts +23 -0
  128. package/dist/taco/model/asset-users.js +128 -0
  129. package/dist/taco/model/auto-layout-lines.d.ts +32 -0
  130. package/dist/taco/model/auto-layout-lines.js +70 -0
  131. package/dist/taco/model/codec.d.ts +444 -0
  132. package/dist/taco/model/codec.js +5635 -0
  133. package/dist/taco/model/color.d.ts +11 -0
  134. package/dist/taco/model/color.js +61 -0
  135. package/dist/taco/model/comment-operations.d.ts +102 -0
  136. package/dist/taco/model/comment-operations.js +227 -0
  137. package/dist/taco/model/component-evaluation.d.ts +94 -0
  138. package/dist/taco/model/component-evaluation.js +548 -0
  139. package/dist/taco/model/component-expressions.d.ts +242 -0
  140. package/dist/taco/model/component-expressions.js +1082 -0
  141. package/dist/taco/model/component-properties.d.ts +111 -0
  142. package/dist/taco/model/component-properties.js +339 -0
  143. package/dist/taco/model/component-samples.d.ts +83 -0
  144. package/dist/taco/model/component-samples.js +290 -0
  145. package/dist/taco/model/component-validity.d.ts +85 -0
  146. package/dist/taco/model/component-validity.js +397 -0
  147. package/dist/taco/model/components.d.ts +155 -0
  148. package/dist/taco/model/components.js +505 -0
  149. package/dist/taco/model/connector-ends.d.ts +20 -0
  150. package/dist/taco/model/connector-ends.js +188 -0
  151. package/dist/taco/model/connector-geometry.d.ts +74 -0
  152. package/dist/taco/model/connector-geometry.js +293 -0
  153. package/dist/taco/model/corner-radii.d.ts +26 -0
  154. package/dist/taco/model/corner-radii.js +47 -0
  155. package/dist/taco/model/derivations.d.ts +81 -0
  156. package/dist/taco/model/derivations.js +151 -0
  157. package/dist/taco/model/export-settings.d.ts +53 -0
  158. package/dist/taco/model/export-settings.js +156 -0
  159. package/dist/taco/model/expressions/ast.d.ts +153 -0
  160. package/dist/taco/model/expressions/ast.js +6 -0
  161. package/dist/taco/model/expressions/cache.d.ts +23 -0
  162. package/dist/taco/model/expressions/cache.js +43 -0
  163. package/dist/taco/model/expressions/check.d.ts +72 -0
  164. package/dist/taco/model/expressions/check.js +517 -0
  165. package/dist/taco/model/expressions/completion.d.ts +61 -0
  166. package/dist/taco/model/expressions/completion.js +421 -0
  167. package/dist/taco/model/expressions/evaluate.d.ts +32 -0
  168. package/dist/taco/model/expressions/evaluate.js +519 -0
  169. package/dist/taco/model/expressions/forms.d.ts +84 -0
  170. package/dist/taco/model/expressions/forms.js +200 -0
  171. package/dist/taco/model/expressions/index.d.ts +14 -0
  172. package/dist/taco/model/expressions/index.js +17 -0
  173. package/dist/taco/model/expressions/lexer.d.ts +42 -0
  174. package/dist/taco/model/expressions/lexer.js +213 -0
  175. package/dist/taco/model/expressions/library.d.ts +33 -0
  176. package/dist/taco/model/expressions/library.js +117 -0
  177. package/dist/taco/model/expressions/names.d.ts +43 -0
  178. package/dist/taco/model/expressions/names.js +99 -0
  179. package/dist/taco/model/expressions/parser.d.ts +15 -0
  180. package/dist/taco/model/expressions/parser.js +438 -0
  181. package/dist/taco/model/expressions/rename.d.ts +34 -0
  182. package/dist/taco/model/expressions/rename.js +46 -0
  183. package/dist/taco/model/expressions/source.d.ts +15 -0
  184. package/dist/taco/model/expressions/source.js +161 -0
  185. package/dist/taco/model/expressions/types.d.ts +119 -0
  186. package/dist/taco/model/expressions/types.js +102 -0
  187. package/dist/taco/model/expressions/values.d.ts +97 -0
  188. package/dist/taco/model/expressions/values.js +160 -0
  189. package/dist/taco/model/geometry-limits.d.ts +16 -0
  190. package/dist/taco/model/geometry-limits.js +67 -0
  191. package/dist/taco/model/geometry.d.ts +47 -0
  192. package/dist/taco/model/geometry.js +193 -0
  193. package/dist/taco/model/group-bounds.d.ts +38 -0
  194. package/dist/taco/model/group-bounds.js +144 -0
  195. package/dist/taco/model/id-table.d.ts +37 -0
  196. package/dist/taco/model/id-table.js +80 -0
  197. package/dist/taco/model/index.d.ts +25 -0
  198. package/dist/taco/model/index.js +27 -0
  199. package/dist/taco/model/instance-resolver.d.ts +372 -0
  200. package/dist/taco/model/instance-resolver.js +1748 -0
  201. package/dist/taco/model/layer-syntax.d.ts +340 -0
  202. package/dist/taco/model/layer-syntax.js +3506 -0
  203. package/dist/taco/model/layout/constraints.d.ts +84 -0
  204. package/dist/taco/model/layout/constraints.js +445 -0
  205. package/dist/taco/model/layout/frame-layout.d.ts +46 -0
  206. package/dist/taco/model/layout/frame-layout.js +618 -0
  207. package/dist/taco/model/layout/node-sizing.d.ts +163 -0
  208. package/dist/taco/model/layout/node-sizing.js +486 -0
  209. package/dist/taco/model/legacy-connector-caps.d.ts +15 -0
  210. package/dist/taco/model/legacy-connector-caps.js +70 -0
  211. package/dist/taco/model/linear-call.d.ts +48 -0
  212. package/dist/taco/model/linear-call.js +58 -0
  213. package/dist/taco/model/new-nodes.d.ts +145 -0
  214. package/dist/taco/model/new-nodes.js +277 -0
  215. package/dist/taco/model/node-builder.d.ts +449 -0
  216. package/dist/taco/model/node-builder.js +2294 -0
  217. package/dist/taco/model/node-table-watch.d.ts +36 -0
  218. package/dist/taco/model/node-table-watch.js +63 -0
  219. package/dist/taco/model/node-transform.d.ts +39 -0
  220. package/dist/taco/model/node-transform.js +79 -0
  221. package/dist/taco/model/node-users-index.d.ts +10 -0
  222. package/dist/taco/model/node-users-index.js +82 -0
  223. package/dist/taco/model/operation-references.d.ts +80 -0
  224. package/dist/taco/model/operation-references.js +399 -0
  225. package/dist/taco/model/operations.d.ts +610 -0
  226. package/dist/taco/model/operations.js +2882 -0
  227. package/dist/taco/model/overlay-table.d.ts +71 -0
  228. package/dist/taco/model/overlay-table.js +171 -0
  229. package/dist/taco/model/override-remap.d.ts +69 -0
  230. package/dist/taco/model/override-remap.js +230 -0
  231. package/dist/taco/model/parent-table.d.ts +53 -0
  232. package/dist/taco/model/parent-table.js +193 -0
  233. package/dist/taco/model/problem-collector.d.ts +27 -0
  234. package/dist/taco/model/problem-collector.js +101 -0
  235. package/dist/taco/model/sha256.d.ts +10 -0
  236. package/dist/taco/model/sha256.js +74 -0
  237. package/dist/taco/model/shape-geometry.d.ts +96 -0
  238. package/dist/taco/model/shape-geometry.js +368 -0
  239. package/dist/taco/model/shared-node-table.d.ts +97 -0
  240. package/dist/taco/model/shared-node-table.js +546 -0
  241. package/dist/taco/model/slots.d.ts +113 -0
  242. package/dist/taco/model/slots.js +281 -0
  243. package/dist/taco/model/stroke-settings.d.ts +37 -0
  244. package/dist/taco/model/stroke-settings.js +90 -0
  245. package/dist/taco/model/svg-path-import.d.ts +89 -0
  246. package/dist/taco/model/svg-path-import.js +219 -0
  247. package/dist/taco/model/text-measurement.d.ts +142 -0
  248. package/dist/taco/model/text-measurement.js +846 -0
  249. package/dist/taco/model/text-reads.d.ts +66 -0
  250. package/dist/taco/model/text-reads.js +128 -0
  251. package/dist/taco/model/text-sizer.d.ts +358 -0
  252. package/dist/taco/model/text-sizer.js +996 -0
  253. package/dist/taco/model/theme-users.d.ts +59 -0
  254. package/dist/taco/model/theme-users.js +312 -0
  255. package/dist/taco/model/thumbnail.d.ts +15 -0
  256. package/dist/taco/model/thumbnail.js +34 -0
  257. package/dist/taco/model/types.d.ts +2347 -0
  258. package/dist/taco/model/types.js +366 -0
  259. package/dist/taco/model/unknown-property.d.ts +5 -0
  260. package/dist/taco/model/unknown-property.js +7 -0
  261. package/dist/taco/model/validated-documents.d.ts +22 -0
  262. package/dist/taco/model/validated-documents.js +22 -0
  263. package/dist/taco/model/variable-modes.d.ts +61 -0
  264. package/dist/taco/model/variable-modes.js +438 -0
  265. package/dist/taco/model/variable-references.d.ts +54 -0
  266. package/dist/taco/model/variable-references.js +183 -0
  267. package/dist/taco/model/variables.d.ts +24 -0
  268. package/dist/taco/model/variables.js +151 -0
  269. package/dist/taco/model/vector-network.d.ts +34 -0
  270. package/dist/taco/model/vector-network.js +411 -0
  271. package/dist/taco/svg-import/import-svg.d.ts +36 -0
  272. package/dist/taco/svg-import/import-svg.js +729 -0
  273. package/dist/taco/svg-import/index.d.ts +3 -0
  274. package/dist/taco/svg-import/index.js +3 -0
  275. package/dist/taco/svg-import/limits/limits.d.ts +79 -0
  276. package/dist/taco/svg-import/limits/limits.js +160 -0
  277. package/dist/taco/svg-import/paint/gradients.d.ts +64 -0
  278. package/dist/taco/svg-import/paint/gradients.js +429 -0
  279. package/dist/taco/svg-import/paint/paint.d.ts +32 -0
  280. package/dist/taco/svg-import/paint/paint.js +162 -0
  281. package/dist/taco/svg-import/paths/paths.d.ts +58 -0
  282. package/dist/taco/svg-import/paths/paths.js +205 -0
  283. package/dist/taco/svg-import/public-types.d.ts +279 -0
  284. package/dist/taco/svg-import/public-types.js +56 -0
  285. package/dist/taco/svg-import/report/report.d.ts +44 -0
  286. package/dist/taco/svg-import/report/report.js +79 -0
  287. package/dist/taco/svg-import/reuse/reuse.d.ts +99 -0
  288. package/dist/taco/svg-import/reuse/reuse.js +840 -0
  289. package/dist/taco/svg-import/shapes/shapes.d.ts +35 -0
  290. package/dist/taco/svg-import/shapes/shapes.js +386 -0
  291. package/dist/taco/svg-import/structure/effects.d.ts +26 -0
  292. package/dist/taco/svg-import/structure/effects.js +618 -0
  293. package/dist/taco/svg-import/structure/image.d.ts +24 -0
  294. package/dist/taco/svg-import/structure/image.js +495 -0
  295. package/dist/taco/svg-import/structure/walk.d.ts +85 -0
  296. package/dist/taco/svg-import/structure/walk.js +544 -0
  297. package/dist/taco/svg-import/style/color.d.ts +40 -0
  298. package/dist/taco/svg-import/style/color.js +275 -0
  299. package/dist/taco/svg-import/style/computed.d.ts +214 -0
  300. package/dist/taco/svg-import/style/computed.js +1534 -0
  301. package/dist/taco/svg-import/style/css.d.ts +127 -0
  302. package/dist/taco/svg-import/style/css.js +541 -0
  303. package/dist/taco/svg-import/style/media.d.ts +25 -0
  304. package/dist/taco/svg-import/style/media.js +307 -0
  305. package/dist/taco/svg-import/style/properties.d.ts +43 -0
  306. package/dist/taco/svg-import/style/properties.js +135 -0
  307. package/dist/taco/svg-import/style/selector-reach.d.ts +30 -0
  308. package/dist/taco/svg-import/style/selector-reach.js +169 -0
  309. package/dist/taco/svg-import/style/selector-validity.d.ts +14 -0
  310. package/dist/taco/svg-import/style/selector-validity.js +307 -0
  311. package/dist/taco/svg-import/text/text.d.ts +29 -0
  312. package/dist/taco/svg-import/text/text.js +545 -0
  313. package/dist/taco/svg-import/transform/matrix.d.ts +111 -0
  314. package/dist/taco/svg-import/transform/matrix.js +229 -0
  315. package/dist/taco/svg-import/tree/element-data.d.ts +52 -0
  316. package/dist/taco/svg-import/tree/element-data.js +155 -0
  317. package/dist/taco/svg-import/tree/elements.d.ts +36 -0
  318. package/dist/taco/svg-import/tree/elements.js +121 -0
  319. package/dist/taco/svg-import/units/length.d.ts +43 -0
  320. package/dist/taco/svg-import/units/length.js +125 -0
  321. package/dist/taco/svg-import/units/viewbox.d.ts +35 -0
  322. package/dist/taco/svg-import/units/viewbox.js +77 -0
  323. package/package.json +54 -4
@@ -0,0 +1,1534 @@
1
+ import { attr, elementClasses, elementId } from "../tree/elements.js";
2
+ import { parseSvgLength, parseSvgNumber } from "../units/length.js";
3
+ import { parseSvgColor } from "./color.js";
4
+ import { parseInlineStyle, } from "./css.js";
5
+ import { isUnsupportedValue, PRESENTATION_ATTRIBUTE_NAMES, PRESENTATION_PROPERTIES } from "./properties.js";
6
+ const BLACK = { r: 0, g: 0, b: 0, a: 1 };
7
+ /**
8
+ * Most invalid declarations kept whole per element; past the cap only the
9
+ * count grows, as with the CSS rejection list (see css.ts).
10
+ */
11
+ const MAX_KEPT_INVALID = 100;
12
+ /** The style of the root element, before its own declarations. */
13
+ export function initialComputedStyle() {
14
+ return {
15
+ fill: { kind: "color", color: BLACK },
16
+ fillOpacity: 1,
17
+ fillRule: "nonzero",
18
+ clipRule: "nonzero",
19
+ stroke: { kind: "none" },
20
+ strokeWidth: 1,
21
+ strokeOpacity: 1,
22
+ strokeLinecap: "butt",
23
+ strokeLinejoin: "miter",
24
+ strokeMiterlimit: 4,
25
+ strokeDasharray: null,
26
+ strokeDashoffset: 0,
27
+ color: BLACK,
28
+ opacity: 1,
29
+ display: "inline",
30
+ visibility: "visible",
31
+ clipPath: null,
32
+ mask: null,
33
+ filter: null,
34
+ blendMode: null,
35
+ nonScalingStroke: false,
36
+ maskType: "luminance",
37
+ overflowVisible: false,
38
+ fontFamily: ["sans-serif"],
39
+ fontSize: 16,
40
+ fontWeight: 400,
41
+ fontStyle: "normal",
42
+ obliqueAngle: null,
43
+ letterSpacing: null,
44
+ textDecoration: { underline: false, lineThrough: false },
45
+ textAnchor: "start",
46
+ stopColor: BLACK,
47
+ stopOpacity: 1,
48
+ markerStart: null,
49
+ markerMid: null,
50
+ markerEnd: null,
51
+ floodColor: BLACK,
52
+ floodOpacity: 1,
53
+ overline: false,
54
+ cssTransformWins: false,
55
+ preserveWhitespace: false,
56
+ invalid: [],
57
+ invalidOverflow: 0,
58
+ unsupported: [],
59
+ styleAttributeRejected: { rejected: [], overflow: 0 },
60
+ currentColorFields: new Map(),
61
+ };
62
+ }
63
+ /**
64
+ * The properties that pass from a parent's computed style to a child's.
65
+ * `textDecoration` here holds the lines propagated from ancestors plus the
66
+ * element's own, as CSS draws an ancestor's decoration on its descendants.
67
+ */
68
+ const INHERITED_KEYS = [
69
+ "fill", "fillOpacity", "fillRule", "clipRule", "stroke", "strokeWidth", "strokeOpacity",
70
+ "strokeLinecap", "strokeLinejoin", "strokeMiterlimit", "strokeDasharray",
71
+ "strokeDashoffset", "color", "visibility", "fontFamily", "fontSize",
72
+ "fontWeight", "fontStyle", "obliqueAngle", "letterSpacing", "textDecoration", "textAnchor",
73
+ "markerStart", "markerMid", "markerEnd",
74
+ "preserveWhitespace",
75
+ ];
76
+ /** The `display` keywords CSS accepts; every one but `none` draws the element. */
77
+ const DISPLAY_VALUES = new Set([
78
+ "none", "inline", "block", "contents", "list-item", "inline-block", "run-in",
79
+ "flow", "flow-root", "table", "inline-table", "table-row-group",
80
+ "table-header-group", "table-footer-group", "table-row", "table-cell",
81
+ "table-column-group", "table-column", "table-caption", "flex", "inline-flex",
82
+ "grid", "inline-grid", "ruby", "ruby-base", "ruby-text", "ruby-base-container",
83
+ "ruby-text-container", "inline list-item", "block flow", "inline flow",
84
+ "block flow-root", "inline flow-root", "block flex", "inline flex",
85
+ "block grid", "inline grid", "block table", "inline table",
86
+ ]);
87
+ /** The line keywords `text-decoration` may hold. */
88
+ const TEXT_DECORATION_LINES = new Set([
89
+ "none", "underline", "overline", "line-through", "blink",
90
+ ]);
91
+ /**
92
+ * The most entries one `stroke-dasharray` may list, and the longest value
93
+ * read at all. A longer value is ignored and reported, checked before the
94
+ * value is split, so one huge declaration cannot build a huge array.
95
+ */
96
+ const DASH_ENTRIES = 64;
97
+ const DASH_VALUE_CHARACTERS = 4096;
98
+ const BLEND_MODES = new Set([
99
+ "normal", "darken", "multiply", "color-burn", "lighten", "screen",
100
+ "color-dodge", "overlay", "soft-light", "hard-light", "difference",
101
+ "exclusion", "hue", "saturation", "color", "luminosity",
102
+ ]);
103
+ /** Each `overflow` keyword, and whether it draws content outside the viewport. */
104
+ const OVERFLOW_VISIBLE = {
105
+ visible: true, auto: true, hidden: false, scroll: false, clip: false,
106
+ };
107
+ function selectorRank(rule) {
108
+ switch (rule.selector.kind) {
109
+ case "type": return 1;
110
+ case "class": return 2;
111
+ case "id": return 3;
112
+ }
113
+ }
114
+ /**
115
+ * The `<style>` rules of one document, indexed by selector, so an element
116
+ * looks up only the rules for its own type, id and classes instead of
117
+ * testing every rule. Each lookup counts the rules it matches — one per
118
+ * rule, plus one per declaration and per character of its value, which is
119
+ * parsed again for every matching element — against the import's style work
120
+ * cap (`SvgImportLimits.styleWork`) before it builds anything, so a file
121
+ * pairing many rules, or a huge value, with many elements is refused instead
122
+ * of freezing the editor. Component checks count too: they compute styles
123
+ * like the walk does.
124
+ */
125
+ export class StyleRules {
126
+ #byKey = new Map();
127
+ /** Per key: its rules plus their declarations, the work one match costs. */
128
+ #workByKey = new Map();
129
+ #guard;
130
+ /**
131
+ * The root element's computed font size, which `rem` lengths are of
132
+ * (CSS Values 4, font-relative lengths). Set once the root's style is
133
+ * computed; on the root itself `rem` is of the initial 16px.
134
+ */
135
+ rootFontSize = 16;
136
+ constructor(rules, guard) {
137
+ this.#guard = guard;
138
+ for (const rule of rules) {
139
+ const key = `${rule.selector.kind}:${rule.selector.name}`;
140
+ let list = this.#byKey.get(key);
141
+ if (list === undefined) {
142
+ list = [];
143
+ this.#byKey.set(key, list);
144
+ }
145
+ list.push(rule);
146
+ // The work one match costs: the rule, plus each declaration by the
147
+ // length of its value, which is parsed again for every element the rule
148
+ // matches — so one huge value matched by many elements is refused.
149
+ let work = 1;
150
+ for (const declaration of rule.declarations)
151
+ work += 1 + declaration.value.length;
152
+ this.#workByKey.set(key, (this.#workByKey.get(key) ?? 0) + work);
153
+ }
154
+ }
155
+ /**
156
+ * Counts one build of an element against the import's cap
157
+ * (`SvgImportLimits.elementBuilds`): every build computes the element's
158
+ * style once, through these rules.
159
+ */
160
+ countElementBuild() {
161
+ this.#guard.countElementBuild();
162
+ }
163
+ /**
164
+ * Counts one font family tried for a run of text against the style work
165
+ * cap (`SvgImportLimits.styleWork`), so a long `font-family` list
166
+ * inherited by many text elements is refused instead of freezing the
167
+ * editor with font lookups.
168
+ */
169
+ countFontLookup() {
170
+ this.#guard.countStyleWork(1);
171
+ }
172
+ /**
173
+ * Counts the declarations of one inline `style` attribute against the
174
+ * style work cap (`SvgImportLimits.styleWork`) as they are parsed — one
175
+ * per declaration plus its value's length, as a matched rule's
176
+ * declarations count — so a huge attribute is refused while it is read,
177
+ * before its declaration list is built, copied and walked.
178
+ */
179
+ countInlineStyleWork(units) {
180
+ this.#guard.countStyleWork(units);
181
+ }
182
+ /** The rules that match the element, by specificity and then source order. */
183
+ matching(element) {
184
+ if (this.#byKey.size === 0)
185
+ return [];
186
+ const keys = [`type:${element.localName}`];
187
+ const id = elementId(element);
188
+ if (id !== null)
189
+ keys.push(`id:${id}`);
190
+ for (const name of new Set(elementClasses(element)))
191
+ keys.push(`class:${name}`);
192
+ let work = 0;
193
+ for (const key of keys)
194
+ work += this.#workByKey.get(key) ?? 0;
195
+ this.#guard.countStyleWork(work);
196
+ const matched = [];
197
+ for (const key of keys) {
198
+ for (const rule of this.#byKey.get(key) ?? [])
199
+ matched.push(rule);
200
+ }
201
+ return matched.sort((left, right) => selectorRank(left) - selectorRank(right) || left.order - right.order);
202
+ }
203
+ }
204
+ /**
205
+ * Computes one element's style: presentation attributes first, then matching
206
+ * `<style>` rules by specificity and source order, then the inline `style`;
207
+ * then, in the same order, the `!important` declarations of the rules and of
208
+ * the inline `style`, which beat every normal one.
209
+ * A declaration whose value does not parse is dropped, as CSS does, so a
210
+ * broken value never hides a working one. `currentColor` resolves against
211
+ * the element's own computed `color`.
212
+ */
213
+ export function computeElementStyle(element, parent, rules, viewport) {
214
+ rules.countElementBuild();
215
+ const base = parent === null ? initialComputedStyle() : parent;
216
+ const working = {};
217
+ for (const key of INHERITED_KEYS)
218
+ working[key] = base[key];
219
+ const initial = initialComputedStyle();
220
+ for (const key of ["opacity", "display", "clipPath", "mask", "filter", "blendMode", "nonScalingStroke", "maskType", "overflowVisible", "cssTransformWins"]) {
221
+ working[key] = initial[key];
222
+ }
223
+ working.stopColor = initial.stopColor;
224
+ working.stopOpacity = initial.stopOpacity;
225
+ working.floodColor = initial.floodColor;
226
+ working.floodOpacity = initial.floodOpacity;
227
+ // The lines an ancestor's text decoration propagates reach this element.
228
+ working.overline = base.overline;
229
+ const invalid = [];
230
+ let invalidOverflow = 0;
231
+ // Only the first few invalid declarations are kept whole; past the cap
232
+ // only the count grows, so an element whose style attribute is one invalid
233
+ // declaration after another cannot grow the list without end.
234
+ const pushInvalid = (record) => {
235
+ if (invalid.length < MAX_KEPT_INVALID)
236
+ invalid.push(record);
237
+ else
238
+ invalidOverflow += 1;
239
+ };
240
+ working.invalid = invalid;
241
+ const space = attr(element, "xml:space");
242
+ if (space === "preserve")
243
+ working.preserveWhitespace = true;
244
+ if (space === "default")
245
+ working.preserveWhitespace = false;
246
+ const declarations = [];
247
+ for (const name of PRESENTATION_ATTRIBUTE_NAMES) {
248
+ const value = attr(element, name);
249
+ if (value !== null)
250
+ declarations.push({ property: name, value });
251
+ }
252
+ const important = [];
253
+ const inline = parseInlineStyle(element.getAttribute("style") ?? "", (units) => rules.countInlineStyleWork(units));
254
+ working.styleAttributeRejected = { rejected: inline.rejected, overflow: inline.rejectedOverflow };
255
+ const matched = [
256
+ ...rules.matching(element).flatMap((rule) => rule.declarations),
257
+ ...inline.declarations,
258
+ ];
259
+ for (const declaration of matched)
260
+ (declaration.important === true ? important : declarations).push(declaration);
261
+ declarations.push(...important);
262
+ // Fields whose winning declaration so far is `currentColor`, or a `url()`
263
+ // paint (its id kept here) whose fallback is `currentColor`. A later
264
+ // declaration for the same field removes its entry, so only the last one
265
+ // counts; the rest resolve once the element's own `color` is known.
266
+ const pendingCurrentColor = new Map();
267
+ // An inherited `currentColor` paint is still the keyword here.
268
+ for (const key of ["fill", "stroke"]) {
269
+ const referenceId = base.currentColorFields.get(key);
270
+ if (referenceId !== undefined)
271
+ pendingCurrentColor.set(key, referenceId);
272
+ }
273
+ // Font-relative lengths in every property but font-size and font resolve
274
+ // against the element's final font size (CSS Values 4, font-relative
275
+ // lengths), so the font-size and font declarations are applied first on a
276
+ // copy to find it; the loop below applies and reports them in order.
277
+ const rootFontSize = parent === null ? initial.fontSize : rules.rootFontSize;
278
+ const fontSizeProbe = { ...working };
279
+ for (const declaration of declarations) {
280
+ if (declaration.brokenString === true || (declaration.property !== "font-size" && declaration.property !== "font"))
281
+ continue;
282
+ applyDeclaration(fontSizeProbe, declaration, base, viewport, new Map(), { fontSize: base.fontSize, rootFontSize });
283
+ }
284
+ const fontSize = fontSizeProbe.fontSize;
285
+ if (parent === null)
286
+ rules.rootFontSize = fontSize;
287
+ // The last declaration of each unsupported property wins, so a later
288
+ // default value hides an earlier one that would have been reported.
289
+ const unsupported = new Map();
290
+ for (const declaration of declarations) {
291
+ // A quoted string broken by a line break makes the declaration invalid,
292
+ // so it is ignored and, for a property the import reads, reported.
293
+ if (declaration.brokenString === true) {
294
+ const support = PRESENTATION_PROPERTIES[declaration.property]?.kind;
295
+ if (support === "applied" || support === "unsupported") {
296
+ pushInvalid({ property: declaration.property, value: quotedStart(declaration.value), reason: "a quoted string is broken by a line break" });
297
+ }
298
+ continue;
299
+ }
300
+ if (PRESENTATION_PROPERTIES[declaration.property]?.kind === "unsupported") {
301
+ unsupported.delete(declaration.property);
302
+ if (isUnsupportedValue(declaration.property, declaration.value)) {
303
+ unsupported.set(declaration.property, quotedStart(declaration.value));
304
+ }
305
+ continue;
306
+ }
307
+ const applied = applyDeclaration(working, declaration, base, viewport, pendingCurrentColor, { fontSize, rootFontSize });
308
+ if (applied !== true) {
309
+ const value = declaration.value.trim();
310
+ pushInvalid({
311
+ property: declaration.property,
312
+ value: quotedStart(value),
313
+ ...(typeof applied === "string" ? { reason: applied } : {}),
314
+ });
315
+ }
316
+ }
317
+ const color = working.color;
318
+ for (const [key, referenceId] of pendingCurrentColor) {
319
+ working[key] = key === "stopColor" || key === "floodColor"
320
+ ? color
321
+ : referenceId === null ? { kind: "color", color } : { kind: "ref", ...referenceId, fallback: color };
322
+ }
323
+ working.currentColorFields = pendingCurrentColor;
324
+ working.invalidOverflow = invalidOverflow;
325
+ working.unsupported = [...unsupported].map(([property, value]) => ({ property, value }));
326
+ return working;
327
+ }
328
+ /** A declaration's value as the report quotes it: a value over a cap can be huge, so only its start. */
329
+ function quotedStart(value) {
330
+ const trimmed = value.trim();
331
+ return trimmed.length > 80 ? `${trimmed.slice(0, 80).trimEnd()}…` : trimmed;
332
+ }
333
+ /** The CSS-wide keywords, which every property accepts. */
334
+ const CSS_WIDE_KEYWORDS = new Set(["inherit", "initial", "unset", "revert", "revert-layer"]);
335
+ /** Why a winning CSS transform the model cannot draw is left out. */
336
+ const CSS_TRANSFORM_UNSUPPORTED = "a CSS transform is not supported; it overrides the transform attribute, so neither is applied";
337
+ /** The transform functions CSS Transforms 1 and 2 define. */
338
+ const CSS_TRANSFORM_FUNCTIONS = new Set([
339
+ "matrix", "matrix3d", "translate", "translate3d", "translatex", "translatey", "translatez",
340
+ "scale", "scale3d", "scalex", "scaley", "scalez", "rotate", "rotate3d", "rotatex", "rotatey",
341
+ "rotatez", "skew", "skewx", "skewy", "perspective",
342
+ ]);
343
+ /** The argument lists each CSS transform function accepts. */
344
+ const CSS_TRANSFORM_ARGS = {
345
+ matrix: [["number", "number", "number", "number", "number", "number"]],
346
+ matrix3d: [Array.from({ length: 16 }, () => "number")],
347
+ translate: [["length-percentage"], ["length-percentage", "length-percentage"]],
348
+ translate3d: [["length-percentage", "length-percentage", "length"]],
349
+ translatex: [["length-percentage"]],
350
+ translatey: [["length-percentage"]],
351
+ translatez: [["length"]],
352
+ scale: [["number"], ["number", "number"]],
353
+ scale3d: [["number", "number", "number"]],
354
+ scalex: [["number"]],
355
+ scaley: [["number"]],
356
+ scalez: [["number"]],
357
+ rotate: [["angle"]],
358
+ rotate3d: [["number", "number", "number", "angle"]],
359
+ rotatex: [["angle"]],
360
+ rotatey: [["angle"]],
361
+ rotatez: [["angle"]],
362
+ skew: [["angle"], ["angle", "angle"]],
363
+ skewx: [["angle"]],
364
+ skewy: [["angle"]],
365
+ perspective: [["length"]],
366
+ };
367
+ /** The CSS angle units (CSS Values 4 §6); a unitless angle must be 0. */
368
+ const CSS_ANGLE_UNITS = new Set(["deg", "grad", "rad", "turn"]);
369
+ /** The functions whose value stands for an argument of any kind, unread here. */
370
+ const CSS_MATH_FUNCTIONS = new Set(["calc", "min", "max", "clamp", "var"]);
371
+ const CSS_DIMENSION_RE = /^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)([a-zA-Z%]*)$/;
372
+ /** The type of `a + b` or `a - b`: like kinds stay, a length and a percentage mix, `any` adopts. */
373
+ function calcSumType(a, b) {
374
+ if (a === "invalid" || b === "invalid")
375
+ return "invalid";
376
+ if (a === "any")
377
+ return b;
378
+ if (b === "any")
379
+ return a;
380
+ if (a === b)
381
+ return a;
382
+ const lengthish = (type) => type === "length" || type === "percentage" || type === "length-percentage";
383
+ return lengthish(a) && lengthish(b) ? "length-percentage" : "invalid";
384
+ }
385
+ /** The type of `a * b`: one side must be a number. */
386
+ function calcProductType(a, b) {
387
+ if (a === "invalid" || b === "invalid")
388
+ return "invalid";
389
+ if (a === "any")
390
+ return b;
391
+ if (b === "any")
392
+ return a;
393
+ if (a === "number")
394
+ return b;
395
+ if (b === "number")
396
+ return a;
397
+ return "invalid";
398
+ }
399
+ /** The type of `a / b`: the divisor must be a number. */
400
+ function calcQuotientType(a, b) {
401
+ if (a === "invalid" || b === "invalid")
402
+ return "invalid";
403
+ return b === "number" || b === "any" ? a : "invalid";
404
+ }
405
+ /** Whether a math expression of this type can be the argument of a transform function. */
406
+ function calcFits(type, kind) {
407
+ if (type === "invalid")
408
+ return false;
409
+ if (type === "any")
410
+ return true;
411
+ switch (kind) {
412
+ case "number": return type === "number";
413
+ case "length": return type === "length";
414
+ case "angle": return type === "angle";
415
+ case "length-percentage": return type === "length" || type === "percentage" || type === "length-percentage";
416
+ }
417
+ }
418
+ /** The deepest nesting a math expression may use; deeper input is invalid instead of overflowing the stack. */
419
+ const CALC_DEPTH_LIMIT = 100;
420
+ /**
421
+ * The type of one CSS math function call (`calc`, `min`, `max`, `clamp`,
422
+ * `var`), after CSS Values 4 §9: numbers, dimensions, percentages and the
423
+ * constants `e`, `pi`, `infinity` and `NaN` are leaves; `+` and `-` need
424
+ * white space on both sides; `*` and `/` take a number on one side;
425
+ * parentheses and math functions nest. A `var()` reference is `any`: whether
426
+ * it substitutes is not known here. "invalid" when the grammar fails.
427
+ */
428
+ function cssMathValueType(text) {
429
+ let i = 0;
430
+ let depth = 0;
431
+ const ws = () => {
432
+ let seen = false;
433
+ while (i < text.length && /\s/.test(text.charAt(i))) {
434
+ i++;
435
+ seen = true;
436
+ }
437
+ return seen;
438
+ };
439
+ const sum = () => {
440
+ let left = product();
441
+ for (;;) {
442
+ const spaced = ws();
443
+ const operator = text.charAt(i);
444
+ if (operator !== "+" && operator !== "-")
445
+ break;
446
+ // White space is required on both sides of + and - (CSS Values 4 §9.2).
447
+ if (!spaced)
448
+ return "invalid";
449
+ i++;
450
+ if (!ws())
451
+ return "invalid";
452
+ left = calcSumType(left, product());
453
+ }
454
+ return left;
455
+ };
456
+ const product = () => {
457
+ let left = leaf();
458
+ for (;;) {
459
+ // White space before the operator belongs to a following + or -, so it
460
+ // is put back when the next operator is not * or /.
461
+ const mark = i;
462
+ ws();
463
+ const operator = text.charAt(i);
464
+ if (operator !== "*" && operator !== "/") {
465
+ i = mark;
466
+ break;
467
+ }
468
+ i++;
469
+ const right = leaf();
470
+ left = operator === "*" ? calcProductType(left, right) : calcQuotientType(left, right);
471
+ }
472
+ return left;
473
+ };
474
+ const mathFunction = (name) => {
475
+ if (depth > CALC_DEPTH_LIMIT)
476
+ return "invalid";
477
+ depth++;
478
+ const result = mathFunctionBody(name);
479
+ depth--;
480
+ return result;
481
+ };
482
+ const mathFunctionBody = (name) => {
483
+ if (name === "var") {
484
+ // var() is not a math expression; scan to its closing parenthesis and
485
+ // check the custom property name (its fallback is not read).
486
+ const start = i;
487
+ let nesting = 1;
488
+ while (i < text.length && nesting > 0) {
489
+ if (text.charAt(i) === "(")
490
+ nesting++;
491
+ else if (text.charAt(i) === ")")
492
+ nesting--;
493
+ i++;
494
+ }
495
+ if (nesting !== 0)
496
+ return "invalid";
497
+ return /^\s*--[A-Za-z0-9_-]+(?:\s*,[\s\S]*?)?\s*$/.test(text.slice(start, i - 1)) ? "any" : "invalid";
498
+ }
499
+ if (name === "calc") {
500
+ const type = sum();
501
+ ws();
502
+ if (text.charAt(i) !== ")")
503
+ return "invalid";
504
+ i++;
505
+ return type;
506
+ }
507
+ // min and max take one or more sums, clamp exactly three (CSS Values 4).
508
+ let combined = null;
509
+ let parts = 0;
510
+ for (;;) {
511
+ const part = sum();
512
+ parts++;
513
+ combined = combined === null ? part : calcSumType(combined, part);
514
+ ws();
515
+ if (text.charAt(i) !== ",")
516
+ break;
517
+ i++;
518
+ }
519
+ if (text.charAt(i) !== ")")
520
+ return "invalid";
521
+ i++;
522
+ if (name === "clamp" && parts !== 3)
523
+ return "invalid";
524
+ return combined ?? "invalid";
525
+ };
526
+ const leaf = () => {
527
+ ws();
528
+ if (text.charAt(i) === "(") {
529
+ if (depth > CALC_DEPTH_LIMIT)
530
+ return "invalid";
531
+ depth++;
532
+ i++;
533
+ const inner = sum();
534
+ ws();
535
+ if (text.charAt(i) !== ")") {
536
+ depth--;
537
+ return "invalid";
538
+ }
539
+ i++;
540
+ depth--;
541
+ return inner;
542
+ }
543
+ const rest = text.slice(i);
544
+ const fn = /^([a-zA-Z-]+)\(/.exec(rest);
545
+ if (fn !== null) {
546
+ const name = (fn[1] ?? "").toLowerCase();
547
+ if (!CSS_MATH_FUNCTIONS.has(name))
548
+ return "invalid";
549
+ i += fn[0].length;
550
+ return mathFunction(name);
551
+ }
552
+ const number = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(rest);
553
+ if (number !== null) {
554
+ i += number[0].length;
555
+ const unit = /^[a-zA-Z%]+/.exec(text.slice(i));
556
+ if (unit === null)
557
+ return "number";
558
+ i += unit[0].length;
559
+ const name = unit[0].toLowerCase();
560
+ if (name === "%")
561
+ return "percentage";
562
+ if (CSS_LENGTH_UNITS.has(name))
563
+ return "length";
564
+ return CSS_ANGLE_UNITS.has(name) ? "angle" : "invalid";
565
+ }
566
+ const constant = /^(pi|e|infinity|nan)(?![a-zA-Z])/i.exec(rest);
567
+ if (constant !== null) {
568
+ i += constant[0].length;
569
+ return "number";
570
+ }
571
+ return "invalid";
572
+ };
573
+ const type = leaf();
574
+ ws();
575
+ return i === text.length ? type : "invalid";
576
+ }
577
+ /** Whether one CSS transform argument reads as its kind. */
578
+ function isCssTransformArg(token, kind) {
579
+ // A math function or var() counts when its expression is valid and its
580
+ // type fits the argument's kind; its value cannot be read here.
581
+ const math = /^([a-zA-Z-]+)\(([\s\S]*)\)$/.exec(token);
582
+ if (math !== null) {
583
+ if (!CSS_MATH_FUNCTIONS.has((math[1] ?? "").toLowerCase()))
584
+ return false;
585
+ return calcFits(cssMathValueType(token), kind);
586
+ }
587
+ const match = CSS_DIMENSION_RE.exec(token);
588
+ if (match === null)
589
+ return false;
590
+ const unit = (match[2] ?? "").toLowerCase();
591
+ if (unit === "") {
592
+ // A unitless number is a plain number, or a zero length or angle.
593
+ return kind === "number" || Number(match[1]) === 0;
594
+ }
595
+ if (unit === "%")
596
+ return kind === "length-percentage";
597
+ if (CSS_LENGTH_UNITS.has(unit))
598
+ return kind === "length" || kind === "length-percentage";
599
+ return CSS_ANGLE_UNITS.has(unit) && kind === "angle";
600
+ }
601
+ /**
602
+ * Splits a transform function's arguments into tokens: on top-level commas
603
+ * when it has them (CSS transform functions separate arguments with commas,
604
+ * so each part must be one token), otherwise the whole list must be a single
605
+ * token, which a math function with inner spaces still is. Null on an empty
606
+ * part or stray whitespace.
607
+ */
608
+ function cssTransformTokens(args) {
609
+ const parts = [];
610
+ let depth = 0;
611
+ let start = 0;
612
+ for (let i = 0; i < args.length; i++) {
613
+ const ch = args[i];
614
+ if (ch === "(")
615
+ depth++;
616
+ else if (ch === ")")
617
+ depth--;
618
+ else if (ch === "," && depth === 0) {
619
+ parts.push(args.slice(start, i));
620
+ start = i + 1;
621
+ }
622
+ }
623
+ parts.push(args.slice(start));
624
+ const tokens = [];
625
+ for (const part of parts) {
626
+ let inner = "";
627
+ let innerDepth = 0;
628
+ const found = [];
629
+ for (const ch of part.trim()) {
630
+ if (/\s/.test(ch) && innerDepth === 0) {
631
+ if (inner.length > 0) {
632
+ found.push(inner);
633
+ inner = "";
634
+ }
635
+ continue;
636
+ }
637
+ if (ch === "(")
638
+ innerDepth++;
639
+ else if (ch === ")")
640
+ innerDepth--;
641
+ inner += ch;
642
+ }
643
+ if (inner.length > 0)
644
+ found.push(inner);
645
+ if (found.length !== 1)
646
+ return null;
647
+ tokens.push(found[0] ?? "");
648
+ }
649
+ return tokens;
650
+ }
651
+ /**
652
+ * Whether a CSS transform value reads as a list of transform functions with
653
+ * valid argument lists, as CSS Transforms 1 §7 defines the property: a known
654
+ * function name, the argument count and kinds (numbers, lengths with units,
655
+ * percentages, angles with units, unitless zero, or a math function), comma
656
+ * separation, and balanced parentheses. `perspective(none)` also counts
657
+ * (CSS Transforms 2). Anything else is an invalid declaration, so a browser
658
+ * ignores it and the transform attribute still applies.
659
+ */
660
+ function isCssTransformList(value) {
661
+ let rest = value.trim();
662
+ while (rest.length > 0) {
663
+ const match = /^([a-zA-Z]+)\s*\(/.exec(rest);
664
+ if (match === null)
665
+ return false;
666
+ const name = (match[1] ?? "").toLowerCase();
667
+ const arities = CSS_TRANSFORM_ARGS[name];
668
+ if (arities === undefined || !CSS_TRANSFORM_FUNCTIONS.has(name))
669
+ return false;
670
+ // Scan to the closing parenthesis, balancing nested ones (calc, min, …).
671
+ let depth = 0;
672
+ let end = -1;
673
+ for (let i = match[0].length - 1; i < rest.length; i++) {
674
+ if (rest[i] === "(")
675
+ depth++;
676
+ else if (rest[i] === ")") {
677
+ depth--;
678
+ if (depth === 0) {
679
+ end = i;
680
+ break;
681
+ }
682
+ }
683
+ }
684
+ if (end < 0)
685
+ return false;
686
+ const args = rest.slice(match[0].length, end);
687
+ // perspective also takes `none` (CSS Transforms 2).
688
+ if (!(name === "perspective" && args.trim().toLowerCase() === "none")) {
689
+ const tokens = cssTransformTokens(args);
690
+ if (tokens === null)
691
+ return false;
692
+ const spec = arities.find((kinds) => kinds.length === tokens.length);
693
+ if (spec === undefined || !spec.every((kind, i) => isCssTransformArg(tokens[i] ?? "", kind)))
694
+ return false;
695
+ }
696
+ rest = rest.slice(end + 1).trim();
697
+ }
698
+ return true;
699
+ }
700
+ /**
701
+ * Applies a CSS-wide keyword to the fields a property sets. `inherit` takes
702
+ * the parent's value and `initial` the initial value. `unset` does either,
703
+ * by whether the property is inherited; so do `revert` and `revert-layer`,
704
+ * since the user agent style sheet sets none of these properties, except
705
+ * `overflow`, which it sets to `hidden` on the elements that read it.
706
+ */
707
+ function applyWideKeyword(working, property, keyword, parent, pendingCurrentColor) {
708
+ const single = STYLE_KEYS[property];
709
+ // fontStyle travels with its oblique angle, as the shorthand's keys do.
710
+ const keys = property === "marker"
711
+ ? MARKER_KEYS
712
+ : property === "font" ? FONT_KEYS
713
+ : single === undefined ? [] : single === "fontStyle" ? ["fontStyle", "obliqueAngle"] : [single];
714
+ const initial = initialComputedStyle();
715
+ for (const key of keys) {
716
+ const inherited = INHERITED_KEYS.includes(key);
717
+ // A keyword cannot remove the lines an ancestor's text decoration propagates.
718
+ if (keyword === "inherit" || (keyword !== "initial" && inherited) || key === "textDecoration") {
719
+ working[key] = parent[key];
720
+ const referenceId = parent.currentColorFields.get(key);
721
+ if (referenceId === undefined)
722
+ pendingCurrentColor.delete(key);
723
+ else
724
+ pendingCurrentColor.set(key, referenceId);
725
+ }
726
+ else {
727
+ // The initial style holds the user agent's `overflow: hidden`; CSS's initial value is `visible`.
728
+ working[key] = key === "overflowVisible"
729
+ ? keyword === "initial" || keyword === "unset"
730
+ : initial[key];
731
+ pendingCurrentColor.delete(key);
732
+ }
733
+ if (key === "textDecoration")
734
+ working.overline = parent.overline;
735
+ }
736
+ }
737
+ /**
738
+ * Applies one declaration to the working style. `fonts.fontSize` is the
739
+ * element's final font size, which font-relative lengths resolve against
740
+ * outside font-size and font; those resolve against the parent's. `rem`
741
+ * is of `fonts.rootFontSize`, the root's. Returns false when the
742
+ * value cannot be read, or the reason when it crosses a cap or is not
743
+ * supported, so the declaration is ignored; other unknown properties are not
744
+ * in the subset, pass by and return true.
745
+ */
746
+ function applyDeclaration(working, declaration, parent, viewport, pendingCurrentColor, fonts) {
747
+ const { property, value } = declaration;
748
+ const wideKeyword = value.trim().toLowerCase();
749
+ // A winning CSS transform overrides the transform attribute (CSS Transforms
750
+ // 1 §7), so the walk leaves the attribute out. `none`, and the wide
751
+ // keywords that compute to it, draw exactly what the browser draws; another
752
+ // transform function list the model cannot draw, and `inherit`, which draws
753
+ // the parent's transform, are reported. A value that is not a function
754
+ // list is invalid, so the declaration is ignored and the attribute stays.
755
+ if (property === "transform") {
756
+ if (CSS_WIDE_KEYWORDS.has(wideKeyword)) {
757
+ working.cssTransformWins = true;
758
+ return wideKeyword === "inherit" ? CSS_TRANSFORM_UNSUPPORTED : true;
759
+ }
760
+ if (wideKeyword === "none") {
761
+ working.cssTransformWins = true;
762
+ return true;
763
+ }
764
+ if (!isCssTransformList(value))
765
+ return false;
766
+ working.cssTransformWins = true;
767
+ return CSS_TRANSFORM_UNSUPPORTED;
768
+ }
769
+ if (CSS_WIDE_KEYWORDS.has(wideKeyword)) {
770
+ applyWideKeyword(working, property, wideKeyword, parent, pendingCurrentColor);
771
+ return true;
772
+ }
773
+ // CSS keywords are ASCII case-insensitive.
774
+ const keyword = value.trim().toLowerCase();
775
+ switch (property) {
776
+ case "fill":
777
+ case "stroke": {
778
+ const paint = parsePaintValue(value);
779
+ if (paint === null)
780
+ return false;
781
+ if (paint.kind === "currentColor") {
782
+ pendingCurrentColor.set(property, paint.referenceId);
783
+ }
784
+ else {
785
+ working[property] = paint;
786
+ pendingCurrentColor.delete(property);
787
+ }
788
+ return true;
789
+ }
790
+ case "fill-opacity":
791
+ case "stroke-opacity":
792
+ case "opacity":
793
+ case "stop-opacity":
794
+ case "flood-opacity": {
795
+ const number = unitInterval(value);
796
+ if (number === null)
797
+ return false;
798
+ working[STYLE_KEYS[property] ?? property] = number;
799
+ return true;
800
+ }
801
+ case "fill-rule":
802
+ if (keyword !== "nonzero" && keyword !== "evenodd")
803
+ return false;
804
+ working.fillRule = keyword;
805
+ return true;
806
+ case "clip-rule":
807
+ if (keyword !== "nonzero" && keyword !== "evenodd")
808
+ return false;
809
+ working.clipRule = keyword;
810
+ return true;
811
+ case "stroke-width": {
812
+ const width = lengthValue(value, fonts, viewport);
813
+ if (width === null || width < 0)
814
+ return false;
815
+ working.strokeWidth = width;
816
+ return true;
817
+ }
818
+ case "stroke-linecap":
819
+ if (keyword !== "butt" && keyword !== "round" && keyword !== "square")
820
+ return false;
821
+ working.strokeLinecap = keyword;
822
+ return true;
823
+ case "stroke-linejoin":
824
+ if (keyword !== "miter" && keyword !== "round" && keyword !== "bevel")
825
+ return false;
826
+ working.strokeLinejoin = keyword;
827
+ return true;
828
+ case "stroke-miterlimit": {
829
+ const limit = parseSvgNumber(value);
830
+ if (limit === null || limit < 1)
831
+ return false;
832
+ working.strokeMiterlimit = limit;
833
+ return true;
834
+ }
835
+ case "stroke-dasharray": {
836
+ if (keyword === "none") {
837
+ working.strokeDasharray = null;
838
+ return true;
839
+ }
840
+ // Checked before splitting, so a huge value is never turned into a
841
+ // huge array: past the cap the declaration is ignored and reported.
842
+ const tooMany = `it lists more than ${String(DASH_ENTRIES)} dashes`;
843
+ if (value.length > DASH_VALUE_CHARACTERS)
844
+ return tooMany;
845
+ // Split on comma-wsp, so two commas in a row leave an empty, invalid entry.
846
+ const entries = value.trim() === "" ? [] : value.trim().split(/\s*,\s*|\s+/);
847
+ if (entries.length > DASH_ENTRIES)
848
+ return tooMany;
849
+ if (entries.length === 0)
850
+ return false;
851
+ const dash = [];
852
+ for (const entry of entries) {
853
+ const length = lengthValue(entry, fonts, viewport);
854
+ if (length === null || length < 0)
855
+ return false;
856
+ dash.push(length);
857
+ }
858
+ working.strokeDasharray = dash;
859
+ return true;
860
+ }
861
+ case "stroke-dashoffset": {
862
+ const offset = lengthValue(value, fonts, viewport);
863
+ if (offset === null)
864
+ return false;
865
+ working.strokeDashoffset = offset;
866
+ return true;
867
+ }
868
+ case "color": {
869
+ // The color property has no none keyword, so color:none is invalid and ignored.
870
+ const parsed = parseSvgColor(value);
871
+ if (parsed === null || parsed.kind === "none")
872
+ return false;
873
+ // currentColor on color itself is the parent's color (CSS Color 4, currentcolor).
874
+ working.color = parsed.kind === "color" ? parsed.value : parent.color;
875
+ return true;
876
+ }
877
+ case "display":
878
+ // An unknown keyword is invalid and ignored, so an earlier
879
+ // display:none stays; every valid keyword but none draws.
880
+ if (!DISPLAY_VALUES.has(value.trim().toLowerCase()))
881
+ return false;
882
+ working.display = value.trim().toLowerCase() === "none" ? "none" : "inline";
883
+ return true;
884
+ case "visibility":
885
+ if (keyword !== "visible" && keyword !== "hidden" && keyword !== "collapse")
886
+ return false;
887
+ working.visibility = keyword;
888
+ return true;
889
+ case "clip-path":
890
+ return setReference(working, "clipPath", value);
891
+ case "mask":
892
+ return setReference(working, "mask", value);
893
+ case "filter":
894
+ return setReference(working, "filter", value);
895
+ case "marker-start":
896
+ return setReference(working, "markerStart", value);
897
+ case "marker-mid":
898
+ return setReference(working, "markerMid", value);
899
+ case "marker-end":
900
+ return setReference(working, "markerEnd", value);
901
+ case "marker": {
902
+ // The shorthand sets all three; it is a CSS property only, not a presentation attribute.
903
+ const probe = {};
904
+ if (!setReference(probe, "markerStart", value))
905
+ return false;
906
+ for (const key of MARKER_KEYS)
907
+ working[key] = probe.markerStart;
908
+ return true;
909
+ }
910
+ case "mix-blend-mode":
911
+ if (!BLEND_MODES.has(keyword))
912
+ return false;
913
+ working.blendMode = keyword === "normal" ? null : keyword;
914
+ return true;
915
+ case "mask-type": {
916
+ if (keyword !== "luminance" && keyword !== "alpha")
917
+ return false;
918
+ working.maskType = keyword;
919
+ return true;
920
+ }
921
+ case "overflow": {
922
+ // One keyword, or an x and a y keyword. SVG draws `auto` as
923
+ // `visible`; `hidden`, `scroll` and `clip` clip to the viewport.
924
+ const keywords = value.trim().toLowerCase().split(/\s+/);
925
+ const visible = keywords.map((keyword) => OVERFLOW_VISIBLE[keyword]);
926
+ if (keywords.length > 2 || visible.some((entry) => entry === undefined))
927
+ return false;
928
+ if (visible.length === 2 && visible[0] !== visible[1]) {
929
+ return "a different overflow on x and y is not supported";
930
+ }
931
+ working.overflowVisible = visible[0];
932
+ return true;
933
+ }
934
+ case "vector-effect": {
935
+ if (keyword === "none" || keyword === "non-scaling-stroke") {
936
+ working.nonScalingStroke = keyword === "non-scaling-stroke";
937
+ return true;
938
+ }
939
+ if (["non-scaling-size", "non-rotation", "fixed-position"].includes(keyword)) {
940
+ return `vector-effect ${keyword} is not supported; only non-scaling-stroke is applied`;
941
+ }
942
+ return false;
943
+ }
944
+ case "font-family": {
945
+ const families = fontFamilyList(value);
946
+ if (families === null)
947
+ return false;
948
+ working.fontFamily = families;
949
+ return true;
950
+ }
951
+ case "font": {
952
+ const font = fontShorthand(value, parent, fonts.rootFontSize);
953
+ if (font === null || typeof font === "string")
954
+ return font ?? false;
955
+ working.fontStyle = font.style;
956
+ working.obliqueAngle = font.angle;
957
+ working.fontWeight = font.weight;
958
+ working.fontSize = font.size;
959
+ working.fontFamily = font.families;
960
+ return true;
961
+ }
962
+ case "paint-order": {
963
+ // The model paints fill, then stroke, then markers; any other order
964
+ // is reported. Listed keywords come first, the rest follow in that order.
965
+ const keywords = value.trim().toLowerCase().split(/\s+/);
966
+ if (keywords.length === 1 && keywords[0] === "normal")
967
+ return true;
968
+ if (keywords.length > 3 || new Set(keywords).size !== keywords.length
969
+ || !keywords.every((keyword) => PAINT_LAYERS.includes(keyword)))
970
+ return false;
971
+ const order = [...keywords, ...PAINT_LAYERS.filter((layer) => !keywords.includes(layer))];
972
+ if (order.every((layer, index) => layer === PAINT_LAYERS[index]))
973
+ return true;
974
+ return `painting ${order.join(", ")} is not supported; it is painted ${PAINT_LAYERS.join(", ")}`;
975
+ }
976
+ case "font-size": {
977
+ const size = fontSizeValue(keyword, parent.fontSize, fonts.rootFontSize);
978
+ // Zero is a valid size (only negative ones are not); its text draws nothing.
979
+ if (size === null || size < 0)
980
+ return false;
981
+ working.fontSize = size;
982
+ return true;
983
+ }
984
+ case "font-weight": {
985
+ const weight = fontWeightValue(keyword, parent.fontWeight);
986
+ if (weight === null)
987
+ return false;
988
+ working.fontWeight = weight;
989
+ return true;
990
+ }
991
+ case "font-style": {
992
+ if (keyword === "italic" || keyword === "normal" || keyword === "oblique") {
993
+ working.fontStyle = keyword;
994
+ working.obliqueAngle = null;
995
+ return true;
996
+ }
997
+ const angle = obliqueDegrees(keyword);
998
+ if (angle === null)
999
+ return false;
1000
+ // A 0deg oblique is upright (CSS Fonts 4, font-style matching).
1001
+ working.fontStyle = angle === 0 ? "normal" : "oblique";
1002
+ working.obliqueAngle = angle === 0 ? null : angle;
1003
+ return true;
1004
+ }
1005
+ case "letter-spacing": {
1006
+ if (keyword === "normal") {
1007
+ working.letterSpacing = null;
1008
+ return true;
1009
+ }
1010
+ const spacing = parseSvgLength(value, fonts);
1011
+ if (spacing === null || spacing.kind !== "absolute")
1012
+ return false;
1013
+ working.letterSpacing = spacing.value;
1014
+ return true;
1015
+ }
1016
+ case "text-decoration": {
1017
+ const tokens = value.toLowerCase().trim().split(/\s+/);
1018
+ if (!tokens.every((token) => TEXT_DECORATION_LINES.has(token)))
1019
+ return false;
1020
+ // `none` stands alone and each line appears once (CSS Text Decoration 3).
1021
+ if (new Set(tokens).size !== tokens.length || (tokens.length > 1 && tokens.includes("none")))
1022
+ return false;
1023
+ // An ancestor's lines propagate to every descendant: the element's own
1024
+ // lines add to them and cannot remove them.
1025
+ working.textDecoration = {
1026
+ underline: parent.textDecoration.underline || tokens.includes("underline"),
1027
+ lineThrough: parent.textDecoration.lineThrough || tokens.includes("line-through"),
1028
+ };
1029
+ if (tokens.includes("overline"))
1030
+ working.overline = true;
1031
+ return true;
1032
+ }
1033
+ case "text-anchor":
1034
+ if (keyword !== "start" && keyword !== "middle" && keyword !== "end")
1035
+ return false;
1036
+ working.textAnchor = keyword;
1037
+ return true;
1038
+ case "stop-color":
1039
+ case "flood-color": {
1040
+ const field = property === "stop-color" ? "stopColor" : "floodColor";
1041
+ const parsed = parseSvgColor(value);
1042
+ if (parsed === null || parsed.kind === "none")
1043
+ return false;
1044
+ if (parsed.kind === "currentColor") {
1045
+ pendingCurrentColor.set(field, null);
1046
+ }
1047
+ else if (parsed.kind === "color") {
1048
+ working[field] = parsed.value;
1049
+ pendingCurrentColor.delete(field);
1050
+ }
1051
+ return true;
1052
+ }
1053
+ default:
1054
+ return true;
1055
+ }
1056
+ }
1057
+ /** The fields the `marker` shorthand sets. */
1058
+ const MARKER_KEYS = ["markerStart", "markerMid", "markerEnd"];
1059
+ /** The fields the `font` shorthand sets. */
1060
+ const FONT_KEYS = ["fontStyle", "obliqueAngle", "fontWeight", "fontSize", "fontFamily"];
1061
+ /** The layers `paint-order` orders, in their normal order. */
1062
+ const PAINT_LAYERS = ["fill", "stroke", "markers"];
1063
+ /** Maps a CSS property name to its `ComputedStyle` field where they differ. */
1064
+ const STYLE_KEYS = {
1065
+ "fill-opacity": "fillOpacity",
1066
+ "fill-rule": "fillRule",
1067
+ "clip-rule": "clipRule",
1068
+ "stroke-width": "strokeWidth",
1069
+ "stroke-opacity": "strokeOpacity",
1070
+ "stroke-linecap": "strokeLinecap",
1071
+ "stroke-linejoin": "strokeLinejoin",
1072
+ "stroke-miterlimit": "strokeMiterlimit",
1073
+ "stroke-dasharray": "strokeDasharray",
1074
+ "stroke-dashoffset": "strokeDashoffset",
1075
+ "clip-path": "clipPath",
1076
+ "mix-blend-mode": "blendMode",
1077
+ "vector-effect": "nonScalingStroke",
1078
+ "mask-type": "maskType",
1079
+ "overflow": "overflowVisible",
1080
+ "font-family": "fontFamily",
1081
+ "font-size": "fontSize",
1082
+ "font-weight": "fontWeight",
1083
+ "font-style": "fontStyle",
1084
+ "letter-spacing": "letterSpacing",
1085
+ "text-decoration": "textDecoration",
1086
+ "text-anchor": "textAnchor",
1087
+ "stop-color": "stopColor",
1088
+ "stop-opacity": "stopOpacity",
1089
+ "flood-color": "floodColor",
1090
+ "flood-opacity": "floodOpacity",
1091
+ "marker-start": "markerStart",
1092
+ "marker-mid": "markerMid",
1093
+ "marker-end": "markerEnd",
1094
+ "fill": "fill",
1095
+ "stroke": "stroke",
1096
+ "color": "color",
1097
+ "opacity": "opacity",
1098
+ "display": "display",
1099
+ "visibility": "visibility",
1100
+ "mask": "mask",
1101
+ "filter": "filter",
1102
+ };
1103
+ /**
1104
+ * Sets a `clip-path`, `mask` or `filter` from a declaration: a `url(#id)`
1105
+ * reference, or null for `none`. A value that is neither is invalid, so the
1106
+ * declaration is ignored, as CSS ignores it, an earlier winning value stays
1107
+ * and the function returns false.
1108
+ */
1109
+ function setReference(working, property, value) {
1110
+ const trimmed = value.trim();
1111
+ // The keyword is ASCII case-insensitive; a referenced id keeps its case.
1112
+ if (trimmed.toLowerCase() === "none") {
1113
+ working[property] = null;
1114
+ return true;
1115
+ }
1116
+ const match = /^url\(\s*(['"]?)#([^'")\s]+)\1\s*\)$/.exec(trimmed);
1117
+ if (match !== null) {
1118
+ working[property] = { id: match[2] ?? "", external: false };
1119
+ return true;
1120
+ }
1121
+ // Any other url(...) points into another file (`url(foo)` included, since
1122
+ // only a leading `#` names this file); it is never fetched, and the caller
1123
+ // reports it as external.
1124
+ const external = /^url\(\s*(['"]?)([^'")]+)\1\s*\)$/.exec(trimmed);
1125
+ if (external === null)
1126
+ return false;
1127
+ working[property] = { id: external[2] ?? "", external: true };
1128
+ return true;
1129
+ }
1130
+ /**
1131
+ * A paint value: `none`, a `url(#id)` reference with an optional fallback
1132
+ * color, or a color. `currentColor`, alone or as a reference's fallback,
1133
+ * comes back as such (with the reference's id) to resolve against the
1134
+ * element's own `color` once it is known.
1135
+ */
1136
+ function parsePaintValue(value) {
1137
+ const trimmed = value.trim();
1138
+ const local = /^url\(\s*(['"]?)#([^'")\s]+)\1\s*\)(.*)$/.exec(trimmed);
1139
+ // A URL to another file is still a reference; it is never fetched, so it
1140
+ // resolves as an invalid one and its fallback applies.
1141
+ const external = local === null ? /^url\(\s*(['"]?)([^'")\s]+)\1\s*\)(.*)$/.exec(trimmed) : null;
1142
+ const reference = local ?? external;
1143
+ if (reference !== null) {
1144
+ const target = { id: reference[2] ?? "", external: local === null };
1145
+ const rest = (reference[3] ?? "").trim();
1146
+ let fallback = null;
1147
+ if (rest.length > 0) {
1148
+ const color = parseSvgColor(rest);
1149
+ if (color !== null && color.kind === "currentColor")
1150
+ return { kind: "currentColor", referenceId: target };
1151
+ // A fallback that is not a paint makes the whole value invalid.
1152
+ if (color === null)
1153
+ return null;
1154
+ if (color.kind === "color")
1155
+ fallback = color.value;
1156
+ }
1157
+ return { kind: "ref", ...target, fallback };
1158
+ }
1159
+ const parsed = parseSvgColor(trimmed);
1160
+ if (parsed === null)
1161
+ return null;
1162
+ if (parsed.kind === "none")
1163
+ return { kind: "none" };
1164
+ if (parsed.kind === "currentColor")
1165
+ return { kind: "currentColor", referenceId: null };
1166
+ return { kind: "color", color: parsed.value };
1167
+ }
1168
+ /** A number clamped to the 0–1 interval, as the opacity properties use. */
1169
+ function unitInterval(value) {
1170
+ const trimmed = value.trim();
1171
+ if (trimmed === "")
1172
+ return null;
1173
+ const percent = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)%$/i.exec(trimmed);
1174
+ // A CSS number is decimal, so Number()'s hexadecimal, binary and octal forms are rejected.
1175
+ const number = percent !== null ? Number(percent[1]) / 100 : parseSvgNumber(trimmed);
1176
+ if (number === null || !Number.isFinite(number))
1177
+ return null;
1178
+ return Math.min(1, Math.max(0, number));
1179
+ }
1180
+ /** A length in px; percentages (of `stroke-width` and the dash properties) resolve against the viewport's normalized diagonal. */
1181
+ function lengthValue(value, fonts, viewport) {
1182
+ const parsed = parseSvgLength(value, fonts);
1183
+ if (parsed === null)
1184
+ return null;
1185
+ if (parsed.kind === "absolute")
1186
+ return parsed.value;
1187
+ if (viewport === null)
1188
+ return null;
1189
+ const diagonal = Math.hypot(viewport.width, viewport.height) / Math.SQRT2;
1190
+ return parsed.fraction * diagonal;
1191
+ }
1192
+ /**
1193
+ * The absolute size keywords, in px, as Chromium and Firefox compute them
1194
+ * with medium at 16px (CSS Fonts 4, font-size: the table is the browser's).
1195
+ */
1196
+ const FONT_SIZE_KEYWORDS = {
1197
+ "xx-small": 9,
1198
+ "x-small": 10,
1199
+ small: 13,
1200
+ medium: 16,
1201
+ large: 18,
1202
+ "x-large": 24,
1203
+ "xx-large": 32,
1204
+ "xxx-large": 48,
1205
+ };
1206
+ /**
1207
+ * `font-size`: a size keyword, `larger`/`smaller` (the parent's size by a
1208
+ * ratio of 1.2, as browsers use), a length or a percentage; percentages and
1209
+ * `em`/`ex` are of the parent's size, `rem` of the root's.
1210
+ */
1211
+ function fontSizeValue(value, parentSize, rootFontSize) {
1212
+ const trimmed = value.trim();
1213
+ const keyword = trimmed.toLowerCase();
1214
+ if (keyword === "larger")
1215
+ return parentSize * 1.2;
1216
+ if (keyword === "smaller")
1217
+ return parentSize / 1.2;
1218
+ if (Object.hasOwn(FONT_SIZE_KEYWORDS, keyword))
1219
+ return FONT_SIZE_KEYWORDS[keyword];
1220
+ const parsed = parseSvgLength(trimmed, { fontSize: parentSize, rootFontSize });
1221
+ if (parsed === null)
1222
+ return null;
1223
+ if (parsed.kind === "percent")
1224
+ return parentSize * parsed.fraction;
1225
+ return parsed.value;
1226
+ }
1227
+ /** The words an unquoted font family name cannot be: the CSS-wide keywords and `default` (CSS Fonts 4, §2.1.1). */
1228
+ const RESERVED_FAMILY_WORDS = new Set([...CSS_WIDE_KEYWORDS, "default"]);
1229
+ /**
1230
+ * A `font-family` list without quotes; null when it names no family or a
1231
+ * comma has no family on one side (`a,,b`, `, b`, `a,`), as CSS treats the
1232
+ * whole declaration as invalid then. Commas split the list only outside a
1233
+ * quoted name, and a backslash starts a CSS escape in or out of quotes
1234
+ * (`"ACME \"One\", Inc."` is one family, `"\49 nter"` is `Inter`).
1235
+ * Space between the words of an unquoted name collapses to one, as CSS
1236
+ * joins its identifiers with single spaces (`Times New Roman` is
1237
+ * `Times New Roman`); a quoted name keeps its spaces.
1238
+ */
1239
+ function fontFamilyList(value) {
1240
+ const families = [];
1241
+ let current = "";
1242
+ let quote = null;
1243
+ // The parts of the current family: quoted strings and unquoted identifiers.
1244
+ let strings = 0;
1245
+ let identifiers = 0;
1246
+ // The current unquoted word, one entry per code point, with escapes as null.
1247
+ let word = [];
1248
+ let invalid = false;
1249
+ const finishWord = () => {
1250
+ if (word.length === 0)
1251
+ return;
1252
+ if (!isCssIdentifier(word))
1253
+ invalid = true;
1254
+ identifiers += 1;
1255
+ word = [];
1256
+ };
1257
+ const finish = () => {
1258
+ finishWord();
1259
+ // A family is one string or one or more identifiers (CSS Fonts 4, §2.1.1).
1260
+ if (!(strings === 1 && identifiers === 0) && !(strings === 0 && identifiers > 0))
1261
+ invalid = true;
1262
+ // An unquoted family cannot be a CSS-wide keyword or "default", whatever
1263
+ // its letter case or escapes; one word of a longer name can be.
1264
+ else if (strings === 0 && identifiers === 1 && RESERVED_FAMILY_WORDS.has(current.trim().toLowerCase()))
1265
+ invalid = true;
1266
+ else
1267
+ families.push(strings === 1 ? current : current.trim());
1268
+ current = "";
1269
+ strings = 0;
1270
+ identifiers = 0;
1271
+ };
1272
+ for (let index = 0; index < value.length; index += 1) {
1273
+ const char = value[index];
1274
+ if (char === "\\") {
1275
+ const escape = cssEscape(value, index, quote !== null);
1276
+ // An escaped line break outside a string makes the declaration invalid.
1277
+ if (escape === null)
1278
+ return null;
1279
+ current += escape.text;
1280
+ if (quote === null)
1281
+ word.push(null);
1282
+ index = escape.end - 1;
1283
+ }
1284
+ else if (quote !== null) {
1285
+ if (char === quote) {
1286
+ quote = null;
1287
+ }
1288
+ else {
1289
+ current += char;
1290
+ }
1291
+ }
1292
+ else if (char === "'" || char === '"') {
1293
+ finishWord();
1294
+ // Only space can come before a family's first string; a string keeps its own spaces.
1295
+ if (strings === 0 && identifiers === 0)
1296
+ current = "";
1297
+ quote = char;
1298
+ strings += 1;
1299
+ }
1300
+ else if (char === ",") {
1301
+ finish();
1302
+ }
1303
+ else if (char === " " || char === "\t" || char === "\n" || char === "\r" || char === "\f") {
1304
+ finishWord();
1305
+ if (strings === 0 && !current.endsWith(" "))
1306
+ current += " ";
1307
+ }
1308
+ else {
1309
+ current += char;
1310
+ word.push(char);
1311
+ }
1312
+ }
1313
+ finish();
1314
+ return families.length === 0 || invalid ? null : families;
1315
+ }
1316
+ /**
1317
+ * Whether one unquoted word is a CSS identifier (CSS Syntax 3, would start
1318
+ * an identifier): a letter, `_`, a character outside ASCII or an escape
1319
+ * (null) first, or `-` followed by one of those or another `-`; then only
1320
+ * those, digits and `-`.
1321
+ */
1322
+ function isCssIdentifier(word) {
1323
+ const nameStart = (char) => char === null || (char !== undefined && (/[A-Za-z_]/.test(char) || char.charCodeAt(0) >= 0x80));
1324
+ const nameChar = (char) => nameStart(char) || /[0-9-]/.test(char);
1325
+ const first = word[0];
1326
+ const startsWell = first === "-" ? nameStart(word[1]) || word[1] === "-" : nameStart(first);
1327
+ return startsWell && word.every(nameChar);
1328
+ }
1329
+ /**
1330
+ * The text of the CSS escape whose backslash is at `start`, and the index
1331
+ * just after it (CSS Syntax 3, consume an escaped code point): one to six
1332
+ * hex digits and one optional following space (a CR LF pair counts as one)
1333
+ * name a code point, with zero, a surrogate or one past U+10FFFF read as
1334
+ * U+FFFD; any other character stands for itself. Inside a string an escaped
1335
+ * line break continues the string and adds nothing, and a backslash at the
1336
+ * end adds nothing; outside one, a backslash at the end reads as U+FFFD and
1337
+ * an escaped line break is not a valid escape, so the escape is null.
1338
+ */
1339
+ function cssEscape(value, start, inString) {
1340
+ let index = start + 1;
1341
+ if (index >= value.length)
1342
+ return { text: inString ? "" : "\uFFFD", end: index };
1343
+ const next = value[index];
1344
+ if (next === "\n" || next === "\r" || next === "\f") {
1345
+ if (!inString)
1346
+ return null;
1347
+ const end = next === "\r" && value[index + 1] === "\n" ? index + 2 : index + 1;
1348
+ return { text: "", end };
1349
+ }
1350
+ let hex = "";
1351
+ while (hex.length < 6 && index < value.length && /[0-9a-fA-F]/.test(value[index])) {
1352
+ hex += value[index];
1353
+ index += 1;
1354
+ }
1355
+ if (hex.length === 0)
1356
+ return { text: next, end: index + 1 };
1357
+ const space = value[index];
1358
+ if (space === "\r" && value[index + 1] === "\n")
1359
+ index += 2;
1360
+ else if (space === " " || space === "\t" || space === "\n" || space === "\r" || space === "\f")
1361
+ index += 1;
1362
+ const code = Number.parseInt(hex, 16);
1363
+ const valid = code !== 0 && code <= 0x10ffff && (code < 0xd800 || code > 0xdfff);
1364
+ return { text: valid ? String.fromCodePoint(code) : "\uFFFD", end: index };
1365
+ }
1366
+ const SYSTEM_FONTS = new Set(["caption", "icon", "menu", "message-box", "small-caption", "status-bar"]);
1367
+ const FONT_STRETCHES = new Set([
1368
+ "ultra-condensed", "extra-condensed", "condensed", "semi-condensed",
1369
+ "semi-expanded", "expanded", "extra-expanded", "ultra-expanded",
1370
+ ]);
1371
+ /**
1372
+ * The `font` shorthand: up to four style, variant, weight and stretch
1373
+ * keywords, the size with an optional `/` line height, then the family list.
1374
+ * Null when it cannot be read; the reason when it names something the
1375
+ * importer cannot draw (a system font, small caps, a stretch), so the whole
1376
+ * declaration is ignored. Unnamed style and weight reset to normal, as CSS
1377
+ * resets them; the line height does not change single-line SVG text.
1378
+ */
1379
+ function fontShorthand(value, parent, rootFontSize) {
1380
+ let rest = value.trim();
1381
+ if (SYSTEM_FONTS.has(rest.toLowerCase()))
1382
+ return "a system font is not supported";
1383
+ let style = "normal";
1384
+ let angle = null;
1385
+ let weight = 400;
1386
+ let unsupported = null;
1387
+ // Each of style, variant, weight and stretch may appear once (`normal`
1388
+ // fills any place); a repeat makes the whole declaration invalid.
1389
+ const seen = new Set();
1390
+ const first = (part) => {
1391
+ if (seen.has(part))
1392
+ return false;
1393
+ seen.add(part);
1394
+ return true;
1395
+ };
1396
+ for (let count = 0; count < 4; count += 1) {
1397
+ const match = /^(\S+)\s+/.exec(rest);
1398
+ if (match === null)
1399
+ break;
1400
+ const token = match[1].toLowerCase();
1401
+ if (token === "oblique") {
1402
+ if (!first("style"))
1403
+ return null;
1404
+ // oblique takes an optional angle, as in font-style; an angle out of
1405
+ // its range makes the whole declaration invalid, and a 0deg oblique
1406
+ // is upright (CSS Fonts 4, font-style).
1407
+ style = "oblique";
1408
+ rest = rest.slice(match[0].length);
1409
+ const angleMatch = /^([+-]?(?:\d*\.\d+|\d+)(?:e[+-]?\d+)?(?:deg|grad|rad|turn))\s+/i.exec(rest);
1410
+ if (angleMatch !== null) {
1411
+ const degrees = angleDegrees(angleMatch[1]);
1412
+ if (degrees === null || degrees < -90 || degrees > 90)
1413
+ return null;
1414
+ angle = degrees === 0 ? null : degrees;
1415
+ style = degrees === 0 ? "normal" : "oblique";
1416
+ rest = rest.slice(angleMatch[0].length);
1417
+ }
1418
+ continue;
1419
+ }
1420
+ if (token === "italic") {
1421
+ if (!first("style"))
1422
+ return null;
1423
+ style = "italic";
1424
+ }
1425
+ else if (token === "small-caps") {
1426
+ if (!first("variant"))
1427
+ return null;
1428
+ unsupported ??= "font-variant small-caps is not supported";
1429
+ }
1430
+ else if (FONT_STRETCHES.has(token)) {
1431
+ if (!first("stretch"))
1432
+ return null;
1433
+ unsupported ??= `font-stretch ${token} is not supported`;
1434
+ }
1435
+ else if (token !== "normal") {
1436
+ const parsed = /^\d/.test(token) || ["bold", "bolder", "lighter"].includes(token)
1437
+ ? fontWeightValue(token, parent.fontWeight)
1438
+ : null;
1439
+ if (parsed === null)
1440
+ break;
1441
+ if (!first("weight"))
1442
+ return null;
1443
+ weight = parsed;
1444
+ }
1445
+ rest = rest.slice(match[0].length);
1446
+ }
1447
+ const sized = /^([^\s/]+)\s*(?:\/\s*(\S+)\s*)?([\s\S]*)$/.exec(rest);
1448
+ if (sized === null)
1449
+ return null;
1450
+ if (sized[2] !== undefined && !lineHeightValid(sized[2]))
1451
+ return null;
1452
+ const size = fontSizeValue(sized[1], parent.fontSize, rootFontSize);
1453
+ const families = fontFamilyList(sized[3]);
1454
+ if (size === null || size < 0 || families === null)
1455
+ return null;
1456
+ return unsupported ?? { style, angle, weight, size, families };
1457
+ }
1458
+ /**
1459
+ * Whether a line height in the `font` shorthand is `normal`, a number, a
1460
+ * length or a percentage, none negative (CSS Inline 3, line-height). The
1461
+ * line height is never resolved, so any CSS length unit is valid here, not
1462
+ * only the units SVG lengths are drawn with (`1rem`, `10vh`).
1463
+ */
1464
+ function lineHeightValid(value) {
1465
+ if (value.toLowerCase() === "normal")
1466
+ return true;
1467
+ const match = /^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)([a-z%]*)$/i.exec(value);
1468
+ if (match === null || !CSS_LENGTH_UNITS.has(match[2].toLowerCase()))
1469
+ return false;
1470
+ const amount = Number(match[1]);
1471
+ return Number.isFinite(amount) && amount >= 0;
1472
+ }
1473
+ /**
1474
+ * The CSS length units (CSS Values 4, Lengths), with `%` and no unit for
1475
+ * the percentage and number forms of a line height. The transform argument
1476
+ * check reads the same set, after handling `%` and unitless zero itself.
1477
+ */
1478
+ const CSS_LENGTH_UNITS = new Set([
1479
+ "", "%", "px", "cm", "mm", "q", "in", "pt", "pc",
1480
+ "em", "rem", "ex", "rex", "cap", "rcap", "ch", "rch", "ic", "ric", "lh", "rlh",
1481
+ "vw", "vh", "vi", "vb", "vmin", "vmax",
1482
+ "svw", "svh", "svi", "svb", "svmin", "svmax",
1483
+ "lvw", "lvh", "lvi", "lvb", "lvmin", "lvmax",
1484
+ "dvw", "dvh", "dvi", "dvb", "dvmin", "dvmax",
1485
+ "cqw", "cqh", "cqi", "cqb", "cqmin", "cqmax",
1486
+ ]);
1487
+ /**
1488
+ * Whether a `font-style` keyword is `oblique` with an angle from -90deg to
1489
+ * 90deg (CSS Fonts 4, font-style); any other value after `oblique` makes
1490
+ * the declaration invalid.
1491
+ */
1492
+ function obliqueDegrees(keyword) {
1493
+ const match = /^oblique\s+(\S+)$/.exec(keyword);
1494
+ if (match === null)
1495
+ return null;
1496
+ const degrees = angleDegrees(match[1]);
1497
+ return degrees !== null && degrees >= -90 && degrees <= 90 ? degrees : null;
1498
+ }
1499
+ /** The degrees of one CSS angle, or null. Units are ASCII case-insensitive. */
1500
+ function angleDegrees(text) {
1501
+ const match = /^([+-]?(?:\d*\.\d+|\d+)(?:e[+-]?\d+)?)(deg|grad|rad|turn)$/i.exec(text);
1502
+ if (match === null)
1503
+ return null;
1504
+ const degrees = Number(match[1]) * ANGLE_DEGREES[(match[2] ?? "").toLowerCase()];
1505
+ return Number.isFinite(degrees) ? degrees : null;
1506
+ }
1507
+ /** Degrees in one of each CSS angle unit. */
1508
+ const ANGLE_DEGREES = { deg: 1, grad: 0.9, rad: 180 / Math.PI, turn: 360 };
1509
+ /** `font-weight`: a number, `normal`/`bold`, or `bolder`/`lighter` against the parent's weight. */
1510
+ function fontWeightValue(value, parentWeight) {
1511
+ const trimmed = value.trim();
1512
+ if (trimmed === "normal")
1513
+ return 400;
1514
+ if (trimmed === "bold")
1515
+ return 700;
1516
+ if (trimmed === "bolder") {
1517
+ if (parentWeight < 400)
1518
+ return 400;
1519
+ if (parentWeight < 600)
1520
+ return 700;
1521
+ return 900;
1522
+ }
1523
+ if (trimmed === "lighter") {
1524
+ if (parentWeight < 600)
1525
+ return 100;
1526
+ if (parentWeight < 800)
1527
+ return 400;
1528
+ return 700;
1529
+ }
1530
+ const number = parseSvgNumber(trimmed);
1531
+ if (number === null || number < 1 || number > 1000)
1532
+ return null;
1533
+ return number;
1534
+ }