path.mjs 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. import { px } from '../../../value/types/numbers/units.mjs';
  2. const dashKeys = {
  3. offset: "stroke-dashoffset",
  4. array: "stroke-dasharray",
  5. };
  6. const camelKeys = {
  7. offset: "strokeDashoffset",
  8. array: "strokeDasharray",
  9. };
  10. /**
  11. * Build SVG path properties. Uses the path's measured length to convert
  12. * our custom pathLength, pathSpacing and pathOffset into stroke-dashoffset
  13. * and stroke-dasharray attributes.
  14. *
  15. * This function is mutative to reduce per-frame GC.
  16. */
  17. function buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true) {
  18. // Normalise path length by setting SVG attribute pathLength to 1
  19. attrs.pathLength = 1;
  20. // We use dash case when setting attributes directly to the DOM node and camel case
  21. // when defining props on a React component.
  22. const keys = useDashCase ? dashKeys : camelKeys;
  23. // Build the dash offset
  24. attrs[keys.offset] = px.transform(-offset);
  25. // Build the dash array
  26. const pathLength = px.transform(length);
  27. const pathSpacing = px.transform(spacing);
  28. attrs[keys.array] = `${pathLength} ${pathSpacing}`;
  29. }
  30. export { buildSVGPath };