@carbon/utilities
Version:
Utilities and helpers to drive consistency across software products using the Carbon Design System
2 lines (1 loc) • 1.76 kB
JavaScript
function v(e,t){if(!e)return 0;const a=e.style.display;!e.offsetParent&&getComputedStyle(e).display==="none"&&(e.style.display="inline-block");const o=e.getBoundingClientRect()[t];return e.style.display=a,o}function w({container:e,items:t,offset:a,sizes:o,fixedSizes:f,offsetSize:c,maxVisibleItems:l,dimension:m,onChange:E,previousHiddenItems:u=[]}){const H=m==="width"?e.clientWidth:e.clientHeight;let s=[],i=[];const p=o.reduce((r,d)=>r+d,0),n=f.reduce((r,d)=>r+d,0);if(p+n<=H)s=l?t.slice(0,l):[...t],i=l?t.slice(l):[];else{const r=H-c;let d=0;for(let h=0;h<t.length;h++){const g=o[h];d+g+n<=r&&(!l||s.length<l)?(s.push(t[h]),d+=g):i.push(t[h])}}return u.length===i.length&&u.every((r,d)=>r===i[d])?u:(s.forEach(r=>r.removeAttribute("data-hidden")),i.forEach(r=>r.setAttribute("data-hidden","")),a&&a.toggleAttribute("data-hidden",i.length===0),E(s,i),i)}function L({container:e,maxVisibleItems:t,onChange:a,dimension:o="width"}){if(!(e instanceof HTMLElement))throw new Error("container must be an HTMLElement");if(typeof a!="function")throw new Error("onChange must be a function");if(t!==void 0&&(!Number.isInteger(t)||t<=0))throw new Error("maxVisibleItems must be a positive integer");const f=Array.from(e.children),c=f.find(n=>n.hasAttribute("data-offset")),l=f.filter(n=>n.hasAttribute("data-fixed")),m=f.filter(n=>n!==c&&!l.includes(n)),E=l.map(n=>v(n,o)),u=m.map(n=>v(n,o)),H=v(c,o);let s=[];function i(){s=w({container:e,items:m,offset:c,sizes:u,fixedSizes:E,offsetSize:H,maxVisibleItems:t,dimension:o,onChange:a,previousHiddenItems:s})}const p=new ResizeObserver(()=>requestAnimationFrame(i));return p.observe(e),requestAnimationFrame(i),{disconnect(){p.disconnect()}}}export{L as createOverflowHandler,v as getSize,w as updateOverflowHandler};