distribute.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. function roundDec(val: number, dec: number) {
  2. return Math.round(val * (dec = 10 ** dec)) / dec;
  3. }
  4. export const SPACE_BETWEEN = 1;
  5. export const SPACE_AROUND = 2;
  6. export const SPACE_EVENLY = 3;
  7. const coord = (i: number, offs: number, iwid: number, gap: number) => roundDec(offs + i * (iwid + gap), 6);
  8. export type Each = (idx: number, offPct: number, dimPct: number) => void;
  9. /**
  10. * @internal
  11. */
  12. export function distribute(numItems: number, sizeFactor: number, justify: number, onlyIdx: number | null, each: Each) {
  13. let space = 1 - sizeFactor;
  14. /* eslint-disable no-multi-spaces */
  15. // prettier-ignore
  16. let gap = (
  17. justify === SPACE_BETWEEN ? space / (numItems - 1) :
  18. justify === SPACE_AROUND ? space / (numItems ) :
  19. justify === SPACE_EVENLY ? space / (numItems + 1) : 0
  20. );
  21. if (isNaN(gap) || gap === Infinity) {
  22. gap = 0;
  23. }
  24. // prettier-ignore
  25. let offs = (
  26. justify === SPACE_BETWEEN ? 0 :
  27. justify === SPACE_AROUND ? gap / 2 :
  28. justify === SPACE_EVENLY ? gap : 0
  29. );
  30. /* eslint-enable */
  31. let iwid = sizeFactor / numItems;
  32. let _iwid = roundDec(iwid, 6);
  33. if (onlyIdx == null) {
  34. for (let i = 0; i < numItems; i++) {
  35. each(i, coord(i, offs, iwid, gap), _iwid);
  36. }
  37. } else {
  38. each(onlyIdx, coord(onlyIdx, offs, iwid, gap), _iwid);
  39. }
  40. }