@pairdraw/dom-css 0.20.0 → 0.21.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.
@@ -10,7 +10,7 @@ import { compact, uniq } from "es-toolkit/array";
10
10
  import valueParser from "postcss-value-parser";
11
11
  import { themeNamespaces } from "twirlwind";
12
12
  import { foldFormula, tokenNumberInUnit, variableValueReferences } from "@pairdraw/scene-graph/variables";
13
- import { colorToCSS, colorToHex } from "@pairdraw/scene-graph/color";
13
+ import { colorToDocumentCSS } from "@pairdraw/scene-graph/color";
14
14
  import { blurSigma } from "@pairdraw/scene-graph/geometry";
15
15
  import { gradientPoint } from "@pairdraw/scene-graph/gradient";
16
16
  import { hasTextList, listNumberFormat, paragraphSpacingAt, paragraphStyleAt, pixelLength, textLengthPixels, textListItems, textParagraphRanges } from "@pairdraw/scene-graph/text";
@@ -21,7 +21,7 @@ import { instanceSlotFrames, slotPropertyId } from "@pairdraw/scene-graph/slots"
21
21
  //#region src/tokens/names.ts
22
22
  /** Every variable, collection by collection, in each collection's own order. */
23
23
  function collectionVariables(source) {
24
- return compact([...source.variableCollections.values()].flatMap((collection) => collection.variableIds.map((id) => source.variables.get(id))));
24
+ return compact([...source.variableCollections.values()].filter((collection) => !collection.deleted).flatMap((collection) => collection.variableIds.map((id) => source.variables.get(id))));
25
25
  }
26
26
  const SCOPE_NAMESPACES = {
27
27
  CORNER_RADIUS: "radius",
@@ -145,27 +145,27 @@ function cssNameVariableName(name) {
145
145
  }
146
146
  //#endregion
147
147
  //#region src/export/css.ts
148
- /** Opaque colors as hex, which Tailwind matches to its palette; translucent ones as `rgba()`. */
149
- function cssColor(color) {
150
- return color.a >= 1 ? colorToHex(color) : colorToCSS(color);
148
+ /** A color as CSS in the document's profile, so a Display P3 color keeps its gamut. */
149
+ function cssColor(color, profile = "srgb") {
150
+ return colorToDocumentCSS(color, profile);
151
151
  }
152
- function fillToCSS(fill) {
152
+ function fillToCSS(fill, profile = "srgb") {
153
153
  if (fill?.type !== "SOLID" || !fill.visible) return void 0;
154
154
  return cssColor({
155
155
  ...fill.color,
156
156
  a: fill.opacity
157
- });
157
+ }, profile);
158
158
  }
159
159
  /** A number CSS reads the same back: six decimals, no trailing zeros or negative zero. */
160
160
  function cssNumber(value) {
161
161
  const rounded = Number(value.toFixed(6));
162
162
  return String(rounded === 0 ? 0 : rounded);
163
163
  }
164
- function stopToCSS(stop, opacity) {
164
+ function stopToCSS(stop, opacity, profile) {
165
165
  return `${cssColor({
166
166
  ...stop.color,
167
167
  a: stop.color.a * opacity
168
- })} ${cssNumber(stop.position * 100)}%`;
168
+ }, profile)} ${cssNumber(stop.position * 100)}%`;
169
169
  }
170
170
  /** The unit-square point as a CSS position pair, percentages of the box's width and height. */
171
171
  function positionToCSS(point) {
@@ -176,11 +176,11 @@ function positionToCSS(point) {
176
176
  * maps the box's unit square onto gradient space; its inverse gives the line's ends, the
177
177
  * ellipse's centre and radii, or the sweep's start ray. Diamond gradients have no CSS spelling.
178
178
  */
179
- function gradientFillToCSS(fill, width, height) {
179
+ function gradientFillToCSS(fill, width, height, profile = "srgb") {
180
180
  const transform = fill.gradientTransform;
181
181
  const stops = fill.gradientStops;
182
182
  if (!fill.visible || !transform || !stops || stops.length === 0 || width <= 0 || height <= 0) return;
183
- const painted = stops.map((stop) => stopToCSS(stop, fill.opacity)).join(", ");
183
+ const painted = stops.map((stop) => stopToCSS(stop, fill.opacity, profile)).join(", ");
184
184
  if (fill.type === "GRADIENT_LINEAR") {
185
185
  const start = gradientPoint(transform, {
186
186
  x: 0,
@@ -220,10 +220,10 @@ function gradientFillToCSS(fill, width, height) {
220
220
  * out; the bottom one becomes `background-color`, and a solid above another paint has no CSS
221
221
  * spelling here. Image paints export through the element's own source, not this list.
222
222
  */
223
- function gradientFillsToCSS(fills, width, height) {
223
+ function gradientFillsToCSS(fills, width, height, profile = "srgb") {
224
224
  const layers = [];
225
225
  for (let index = fills.length - 1; index >= 0; index--) {
226
- const css = gradientFillToCSS(fills[index], width, height);
226
+ const css = gradientFillToCSS(fills[index], width, height, profile);
227
227
  if (css) layers.push(css);
228
228
  }
229
229
  return layers.length > 0 ? layers.join(", ") : void 0;
@@ -256,12 +256,12 @@ function borderWidths(node) {
256
256
  left: node.borderLeftWeight
257
257
  };
258
258
  }
259
- function strokeColorToCSS(stroke) {
259
+ function strokeColorToCSS(stroke, profile = "srgb") {
260
260
  if (!stroke?.visible) return void 0;
261
261
  return cssColor({
262
262
  ...stroke.color,
263
263
  a: stroke.opacity
264
- });
264
+ }, profile);
265
265
  }
266
266
  function px$2(value) {
267
267
  return `${Number(value.toFixed(3))}px`;
@@ -270,14 +270,14 @@ function px$2(value) {
270
270
  * A shadow as `box-shadow` writes it, or as `text-shadow` does without its spread. CSS blurs a
271
271
  * shadow by half its blur length, so the length is twice the sigma the canvas blurs it by.
272
272
  */
273
- function shadowToCSS(effect, spread = true) {
273
+ function shadowToCSS(effect, spread = true, profile = "srgb") {
274
274
  const parts = [
275
275
  `${effect.type === "INNER_SHADOW" ? "inset " : ""}${px$2(effect.offset.x)}`,
276
276
  px$2(effect.offset.y),
277
277
  px$2(2 * blurSigma(effect.radius))
278
278
  ];
279
279
  if (spread) parts.push(px$2(effect.spread));
280
- parts.push(cssColor(effect.color));
280
+ parts.push(cssColor(effect.color, profile));
281
281
  return parts.join(" ");
282
282
  }
283
283
  const isShadow = (effect) => effect.type === "DROP_SHADOW" || effect.type === "INNER_SHADOW";
@@ -298,11 +298,11 @@ function addBlurs(style, visible) {
298
298
  * Every visible shadow, in order, plus layer and background blur, blurred as the canvas draws
299
299
  * them: CSS's `blur()` takes the Gaussian sigma itself.
300
300
  */
301
- function effectsToCSS(effects) {
301
+ function effectsToCSS(effects, profile = "srgb") {
302
302
  const style = {};
303
303
  const visible = effects.filter((effect) => effect.visible);
304
304
  const shadows = visible.filter(isShadow);
305
- if (shadows.length > 0) style["box-shadow"] = shadows.map((effect) => shadowToCSS(effect)).join(", ");
305
+ if (shadows.length > 0) style["box-shadow"] = shadows.map((effect) => shadowToCSS(effect, true, profile)).join(", ");
306
306
  addBlurs(style, visible);
307
307
  return style;
308
308
  }
@@ -310,11 +310,11 @@ function effectsToCSS(effects) {
310
310
  * Text's effects: each visible drop shadow as `text-shadow`, which has no spread and shadows the
311
311
  * glyphs, and its layer and background blurs. An inner shadow has no form CSS gives text.
312
312
  */
313
- function textEffectsToCSS(effects) {
313
+ function textEffectsToCSS(effects, profile = "srgb") {
314
314
  const style = {};
315
315
  const visible = effects.filter((effect) => effect.visible);
316
316
  const shadows = visible.filter(isDropShadow);
317
- if (shadows.length > 0) style["text-shadow"] = shadows.map((effect) => shadowToCSS(effect, false)).join(", ");
317
+ if (shadows.length > 0) style["text-shadow"] = shadows.map((effect) => shadowToCSS(effect, false, profile)).join(", ");
318
318
  addBlurs(style, visible);
319
319
  return style;
320
320
  }
@@ -610,7 +610,7 @@ function quoteString(value) {
610
610
  return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("\n", "\\a ")}"`;
611
611
  }
612
612
  /** One mode's value as CSS, or why it has none. */
613
- function modeValue(variable, value, modeId, names, variables) {
613
+ function modeValue(variable, value, modeId, names, variables, profile) {
614
614
  const expression = variable.expressions?.[modeId];
615
615
  if (expression) return expression.css;
616
616
  if (value === void 0) return { issue: "has no value in this mode" };
@@ -623,7 +623,7 @@ function modeValue(variable, value, modeId, names, variables) {
623
623
  const target = names.get(value.aliasId);
624
624
  return target ? `var(--${target})` : { issue: "aliases a variable that does not exist" };
625
625
  }
626
- if (variable.type === "COLOR" && typeof value === "object") return cssColor(value);
626
+ if (variable.type === "COLOR" && typeof value === "object") return cssColor(value, profile);
627
627
  if (variable.type === "FLOAT" && typeof value === "number") return tokenNumberToCSS(value, variableUnit(variable));
628
628
  if (variable.type === "STRING" && typeof value === "string") return variableNamespace(variable) === "font" ? value : quoteString(value);
629
629
  if (variable.type === "BOOLEAN") return { issue: "is a boolean, which CSS has no value for" };
@@ -691,7 +691,7 @@ function buildTokenStylesheet(source, { format, include = () => true }, validate
691
691
  const defaultModeOf = (variable) => source.variableCollections.get(variable.collectionId)?.defaultModeId ?? "";
692
692
  function declare(variable, modeId, value) {
693
693
  const name = names.get(variable.id) ?? variable.id;
694
- const css = modeValue(variable, value, modeId, names, source.variables);
694
+ const css = modeValue(variable, value, modeId, names, source.variables, source.documentColorSpace);
695
695
  if (typeof css !== "string") {
696
696
  issues.push({
697
697
  message: `${variable.name} ${css.issue}`,
@@ -1219,21 +1219,21 @@ function styledRanges(node) {
1219
1219
  return ranges;
1220
1220
  }
1221
1221
  /** Underline or strikethrough as CSS writes it: Figma's offset is CSS's, from the baseline. */
1222
- function decorationCSS(style) {
1222
+ function decorationCSS(style, profile) {
1223
1223
  if (style.textDecoration === "NONE") return {};
1224
1224
  const underline = style.textDecoration === "UNDERLINE";
1225
1225
  const css = { "text-decoration-line": underline ? "underline" : "line-through" };
1226
1226
  if (style.textDecorationStyle !== "SOLID") css["text-decoration-style"] = style.textDecorationStyle.toLowerCase();
1227
- const color = fillToCSS(style.textDecorationFills.find((fill) => fill.visible));
1227
+ const color = fillToCSS(style.textDecorationFills.find((fill) => fill.visible), profile);
1228
1228
  if (color) css["text-decoration-color"] = color;
1229
1229
  if (style.textDecorationThickness !== null) css["text-decoration-thickness"] = px$1(style.textDecorationThickness);
1230
1230
  if (underline && style.textUnderlineOffset !== null) css["text-underline-offset"] = px$1(style.textUnderlineOffset);
1231
1231
  if (underline && !style.textDecorationSkipInk) css["text-decoration-skip-ink"] = "none";
1232
1232
  return css;
1233
1233
  }
1234
- function characterCSS(style, decorated) {
1234
+ function characterCSS(style, decorated, profile) {
1235
1235
  return {
1236
- color: fillToCSS(style.fills.at(0)) ?? "",
1236
+ color: fillToCSS(style.fills.at(0), profile) ?? "",
1237
1237
  "font-family": style.fontFamily,
1238
1238
  "font-size": px$1(style.fontSize),
1239
1239
  "font-weight": String(style.fontWeight),
@@ -1241,7 +1241,7 @@ function characterCSS(style, decorated) {
1241
1241
  "letter-spacing": letterSpacingToCSS(style.letterSpacing),
1242
1242
  "line-height": style.lineHeight === null ? "normal" : lineHeightToCSS(style.lineHeight),
1243
1243
  "text-transform": textCaseToCSS(style.textCase) ?? "none",
1244
- ...decorated ? decorationCSS(style) : {}
1244
+ ...decorated ? decorationCSS(style, profile) : {}
1245
1245
  };
1246
1246
  }
1247
1247
  /**
@@ -1249,8 +1249,8 @@ function characterCSS(style, decorated) {
1249
1249
  * where the span changes the font size: CSS inherits spacing already resolved at the text's size,
1250
1250
  * while the canvas spaces each run by its own size.
1251
1251
  */
1252
- function spanCSS(style, decorated, base) {
1253
- const own = characterCSS(style, decorated);
1252
+ function spanCSS(style, decorated, base, profile) {
1253
+ const own = characterCSS(style, decorated, profile);
1254
1254
  const css = differing(own, base);
1255
1255
  const { unit, value } = style.letterSpacing;
1256
1256
  if (unit === "PERCENT" && value !== 0 && "font-size" in css) css["letter-spacing"] = own["letter-spacing"];
@@ -1264,8 +1264,8 @@ function differing(css, base) {
1264
1264
  * Whether the text decorates every character alike. CSS draws an element's decoration through
1265
1265
  * its descendants, which cannot take it off, so mixed decorations go on the spans instead.
1266
1266
  */
1267
- function uniformDecoration(node, ranges) {
1268
- const decorations = ranges.filter((range) => node.text.slice(range.start, range.end).replaceAll("\n", "") !== "").map((range) => decorationCSS(range.style));
1267
+ function uniformDecoration(node, ranges, profile) {
1268
+ const decorations = ranges.filter((range) => node.text.slice(range.start, range.end).replaceAll("\n", "") !== "").map((range) => decorationCSS(range.style, profile));
1269
1269
  return decorations.every((decoration) => isEqual(decoration, decorations[0]));
1270
1270
  }
1271
1271
  function textNode(text) {
@@ -1302,13 +1302,13 @@ function linkElement(href, css, text) {
1302
1302
  * linked characters are a link instead.
1303
1303
  */
1304
1304
  function inlineContent(projection, start, end) {
1305
- const { node, ranges, base, decorated } = projection;
1305
+ const { node, ranges, base, decorated, profile } = projection;
1306
1306
  const pieces = [];
1307
1307
  for (const range of ranges) {
1308
1308
  const from = Math.max(start, range.start);
1309
1309
  const to = Math.min(end, range.end);
1310
1310
  if (to <= from) continue;
1311
- const css = spanCSS(range.style, !decorated, base);
1311
+ const css = spanCSS(range.style, !decorated, base, profile);
1312
1312
  const text = node.text.slice(from, to);
1313
1313
  const previous = pieces.at(-1);
1314
1314
  if (previous && previous.href === range.href && isEqual(previous.css, css)) previous.text += text;
@@ -1437,16 +1437,17 @@ function groupEm(projection, paragraphs, item) {
1437
1437
  * its content. Runs of characters styled apart become spans; text with lists, paragraph
1438
1438
  * spacing, or a first-line indent becomes blocks, which a `<div>` holds.
1439
1439
  */
1440
- function textElementContent(node, layerStyle) {
1440
+ function textElementContent(node, layerStyle, profile = "srgb") {
1441
1441
  const ranges = styledRanges(node);
1442
- const decorated = uniformDecoration(node, ranges);
1442
+ const decorated = uniformDecoration(node, ranges, profile);
1443
1443
  const style = Object.fromEntries(Object.entries(layerStyle).filter(([property]) => !DECORATION_PROPERTIES.has(property)));
1444
- if (decorated) Object.assign(style, decorationCSS(characterStyle(node)));
1444
+ if (decorated) Object.assign(style, decorationCSS(characterStyle(node), profile));
1445
1445
  const projection = {
1446
1446
  node,
1447
1447
  ranges,
1448
- base: characterCSS(characterStyle(node), decorated),
1449
- decorated
1448
+ base: characterCSS(characterStyle(node), decorated, profile),
1449
+ decorated,
1450
+ profile
1450
1451
  };
1451
1452
  if (!needsBlocks(node)) return {
1452
1453
  tagName: "span",
@@ -1559,9 +1560,9 @@ function addCornerRadii(style, node, css) {
1559
1560
  }
1560
1561
  if (node.cornerRadius > 0) style["border-radius"] = css("cornerRadius", px(node.cornerRadius));
1561
1562
  }
1562
- function addStroke(style, node, css) {
1563
+ function addStroke(style, node, css, profile) {
1563
1564
  const stroke = node.strokes.find((item) => item.visible);
1564
- const literalColor = strokeColorToCSS(stroke);
1565
+ const literalColor = strokeColorToCSS(stroke, profile);
1565
1566
  if (!literalColor || !stroke) return;
1566
1567
  const color = css("strokes/0/color", literalColor);
1567
1568
  const borderStyle = node.dashPattern.length > 0 ? "dashed" : "solid";
@@ -1584,14 +1585,14 @@ function addStroke(style, node, css) {
1584
1585
  * dash or take per-side weights, and outer and inner rings paint in separate CSS layers, so a
1585
1586
  * stroke order that alternates them is approximated.
1586
1587
  */
1587
- function extraStrokeShadows(strokes, first) {
1588
+ function extraStrokeShadows(strokes, first, profile) {
1588
1589
  const outer = [];
1589
1590
  const inner = [];
1590
1591
  let outside = 0;
1591
1592
  let inside = first.weight;
1592
1593
  for (const stroke of strokes) {
1593
1594
  if (!stroke.visible) continue;
1594
- const color = strokeColorToCSS(stroke);
1595
+ const color = strokeColorToCSS(stroke, profile);
1595
1596
  if (!color) continue;
1596
1597
  if (stroke.align !== "OUTSIDE") {
1597
1598
  inside += stroke.align === "CENTER" ? stroke.weight / 2 : stroke.weight;
@@ -1737,21 +1738,21 @@ const CSS_BLEND_MODES = {
1737
1738
  COLOR: "color",
1738
1739
  LUMINOSITY: "luminosity"
1739
1740
  };
1740
- function styleFromSceneNode(node, parent, css) {
1741
+ function styleFromSceneNode(node, parent, css, profile) {
1741
1742
  const style = {};
1742
1743
  addSize(style, node, parent, css);
1743
1744
  addPositioning(style, node, parent);
1744
1745
  addSizeConstraints(style, node, css);
1745
- const fill = fillToCSS(node.fills.at(0));
1746
+ const fill = fillToCSS(node.fills.at(0), profile);
1746
1747
  if (fill) style["background-color"] = css("fills/0/color", fill);
1747
- const gradients = gradientFillsToCSS(node.fills, node.width, node.height);
1748
+ const gradients = gradientFillsToCSS(node.fills, node.width, node.height, profile);
1748
1749
  if (gradients) style["background-image"] = gradients;
1749
1750
  addImageStyle(style, node);
1750
- addStroke(style, node, css);
1751
- Object.assign(style, effectsToCSS(node.effects));
1751
+ addStroke(style, node, css, profile);
1752
+ Object.assign(style, effectsToCSS(node.effects, profile));
1752
1753
  const visibleStrokes = node.strokes.filter((stroke) => stroke.visible);
1753
1754
  if (visibleStrokes.length > 1) {
1754
- const rings = extraStrokeShadows(visibleStrokes.slice(1), visibleStrokes[0]);
1755
+ const rings = extraStrokeShadows(visibleStrokes.slice(1), visibleStrokes[0], profile);
1755
1756
  if (rings.length > 0) style["box-shadow"] = [rings.join(", "), style["box-shadow"]].filter((shadow) => Boolean(shadow)).join(", ");
1756
1757
  }
1757
1758
  if (node.opacity < 1) style.opacity = css("opacity", String(node.opacity));
@@ -1780,14 +1781,14 @@ function styleFromSceneNode(node, parent, css) {
1780
1781
  addBoxSizing(style);
1781
1782
  return style;
1782
1783
  }
1783
- function styleFromTextNode(node, parent, css) {
1784
+ function styleFromTextNode(node, parent, css, profile) {
1784
1785
  const style = {};
1785
1786
  addSize(style, node, parent, css);
1786
1787
  addPositioning(style, node, parent);
1787
1788
  addLayoutChild(style, node, parent);
1788
1789
  if (resolveNodeTextDirection(node) === "RTL") style.direction = "rtl";
1789
- const color = fillToCSS(node.fills.at(0));
1790
- style.color = color ? css("fills/0/color", color) : cssColor(BLACK);
1790
+ const color = fillToCSS(node.fills.at(0), profile);
1791
+ style.color = color ? css("fills/0/color", color) : cssColor(BLACK, profile);
1791
1792
  style["font-family"] = node.fontFamily;
1792
1793
  style["font-size"] = css("fontSize", px(node.fontSize));
1793
1794
  style["font-weight"] = String(node.fontWeight);
@@ -1802,7 +1803,7 @@ function styleFromTextNode(node, parent, css) {
1802
1803
  }
1803
1804
  if (node.textAlignHorizontal !== "LEFT") style["text-align"] = node.textAlignHorizontal.toLowerCase();
1804
1805
  if (node.opacity < 1) style.opacity = css("opacity", String(node.opacity));
1805
- Object.assign(style, textEffectsToCSS(node.effects));
1806
+ Object.assign(style, textEffectsToCSS(node.effects, profile));
1806
1807
  if (node.textDecoration !== "NONE") style["text-decoration-line"] = node.textDecoration === "UNDERLINE" ? "underline" : "line-through";
1807
1808
  const textTransform = textCaseToCSS(node.textCase);
1808
1809
  if (textTransform) style["text-transform"] = textTransform;
@@ -1919,7 +1920,7 @@ function sceneNodeToDesignNode(context, node, inherited, root) {
1919
1920
  };
1920
1921
  const css = (field, literal) => tokens?.reference(node, field, modes) ?? literal;
1921
1922
  if (node.type === "TEXT") {
1922
- const content = textElementContent(node, styleFromTextNode(node, parent, css));
1923
+ const content = textElementContent(node, styleFromTextNode(node, parent, css, graph.documentColorSpace), graph.documentColorSpace);
1923
1924
  return {
1924
1925
  type: "element",
1925
1926
  tagName: content.tagName,
@@ -1931,7 +1932,7 @@ function sceneNodeToDesignNode(context, node, inherited, root) {
1931
1932
  };
1932
1933
  }
1933
1934
  if (VECTOR_SHAPES.has(node.type) || readIcon(node)) {
1934
- const vector = vectorDesignNode(context, node, attrs, styleFromSceneNode(node, parent, css));
1935
+ const vector = vectorDesignNode(context, node, attrs, styleFromSceneNode(node, parent, css, graph.documentColorSpace));
1935
1936
  if (vector) return vector;
1936
1937
  }
1937
1938
  const children = projectChildren(context, node, modes, false);
@@ -1943,7 +1944,7 @@ function sceneNodeToDesignNode(context, node, inherited, root) {
1943
1944
  sourceSceneNode: node,
1944
1945
  children
1945
1946
  };
1946
- const style = styleFromSceneNode(node, parent, css);
1947
+ const style = styleFromSceneNode(node, parent, css, graph.documentColorSpace);
1947
1948
  const shader = layerShader(graph, node);
1948
1949
  if (shader) addShaderLayerStyle(style);
1949
1950
  return {