offset.mjs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { resolveEdge, namedEdges } from './edge.mjs';
  2. const defaultOffset = [0, 0];
  3. function resolveOffset(offset, containerLength, targetLength, targetInset) {
  4. let offsetDefinition = Array.isArray(offset) ? offset : defaultOffset;
  5. let targetPoint = 0;
  6. let containerPoint = 0;
  7. if (typeof offset === "number") {
  8. /**
  9. * If we're provided offset: [0, 0.5, 1] then each number x should become
  10. * [x, x], so we default to the behaviour of mapping 0 => 0 of both target
  11. * and container etc.
  12. */
  13. offsetDefinition = [offset, offset];
  14. }
  15. else if (typeof offset === "string") {
  16. offset = offset.trim();
  17. if (offset.includes(" ")) {
  18. offsetDefinition = offset.split(" ");
  19. }
  20. else {
  21. /**
  22. * If we're provided a definition like "100px" then we want to apply
  23. * that only to the top of the target point, leaving the container at 0.
  24. * Whereas a named offset like "end" should be applied to both.
  25. */
  26. offsetDefinition = [offset, namedEdges[offset] ? offset : `0`];
  27. }
  28. }
  29. targetPoint = resolveEdge(offsetDefinition[0], targetLength, targetInset);
  30. containerPoint = resolveEdge(offsetDefinition[1], containerLength);
  31. return targetPoint - containerPoint;
  32. }
  33. export { resolveOffset };