curve.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import {
  2. curveBasis,
  3. curveBasisClosed,
  4. curveBasisOpen,
  5. curveBundle,
  6. curveBumpX,
  7. curveBumpY,
  8. curveCardinal,
  9. curveCardinalClosed,
  10. curveCardinalOpen,
  11. curveCatmullRom,
  12. curveCatmullRomClosed,
  13. curveCatmullRomOpen,
  14. curveLinear,
  15. curveLinearClosed,
  16. curveMonotoneX,
  17. curveMonotoneY,
  18. curveNatural,
  19. curveStep,
  20. curveStepAfter,
  21. curveStepBefore
  22. } from "d3";
  23. const curves = new Map([
  24. ["basis", curveBasis],
  25. ["basis-closed", curveBasisClosed],
  26. ["basis-open", curveBasisOpen],
  27. ["bundle", curveBundle],
  28. ["bump-x", curveBumpX],
  29. ["bump-y", curveBumpY],
  30. ["cardinal", curveCardinal],
  31. ["cardinal-closed", curveCardinalClosed],
  32. ["cardinal-open", curveCardinalOpen],
  33. ["catmull-rom", curveCatmullRom],
  34. ["catmull-rom-closed", curveCatmullRomClosed],
  35. ["catmull-rom-open", curveCatmullRomOpen],
  36. ["linear", curveLinear],
  37. ["linear-closed", curveLinearClosed],
  38. ["monotone-x", curveMonotoneX],
  39. ["monotone-y", curveMonotoneY],
  40. ["natural", curveNatural],
  41. ["step", curveStep],
  42. ["step-after", curveStepAfter],
  43. ["step-before", curveStepBefore]
  44. ]);
  45. export function maybeCurve(curve = curveLinear, tension) {
  46. if (typeof curve === "function") return curve; // custom curve
  47. const c = curves.get(`${curve}`.toLowerCase());
  48. if (!c) throw new Error(`unknown curve: ${curve}`);
  49. if (tension !== undefined) {
  50. if ("beta" in c) {
  51. return c.beta(tension);
  52. } else if ("tension" in c) {
  53. return c.tension(tension);
  54. } else if ("alpha" in c) {
  55. return c.alpha(tension);
  56. }
  57. }
  58. return c;
  59. }
  60. // For the “auto” curve, return a symbol instead of a curve implementation;
  61. // we’ll use d3.geoPath to render if there’s a projection.
  62. export function maybeCurveAuto(curve = curveAuto, tension) {
  63. return typeof curve !== "function" && `${curve}`.toLowerCase() === "auto" ? curveAuto : maybeCurve(curve, tension);
  64. }
  65. // This is a special built-in curve that will use d3.geoPath when there is a
  66. // projection, and the linear curve when there is not. You can explicitly
  67. // opt-out of d3.geoPath and instead use d3.line with the "linear" curve.
  68. export function curveAuto(context) {
  69. return curveLinear(context);
  70. }