{"version":3,"file":"use-combobox-multi-value-overflow.mjs","names":[],"sources":["../../../src/combobox/use-combobox-multi-value-overflow.ts"],"sourcesContent":["/*!\n *\n *  Copyright (c) \"Neo4j\"\n *  Neo4j Sweden AB [http://neo4j.com]\n *\n *  This file is part of Neo4j.\n *\n *  Neo4j is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\nimport { useLayoutEffect, useRef, useState } from 'react';\n\n/**\n * The text of the overflow counter tag. Whole thousands round to a `K` suffix\n * - `1500` becomes `2K` - so the counter keeps a bounded width no matter how\n * large the selection grows.\n */\nexport const formatOverflowCount = (count: number): string =>\n  count < 1000 ? `${count}` : `${Math.round(count / 1000)}K`;\n\n/**\n * Every text the counter could show at its widest for a selection of `total`\n * options. K formatting makes the width non-monotonic - \"+999\" is wider than\n * \"+1K\" - so the reserve has to measure both the widest sub-thousand text and\n * the full count rather than the full count alone.\n */\nexport const getOverflowCounterMeasureTexts = (total: number): string[] =>\n  Array.from(\n    new Set([\n      formatOverflowCount(Math.min(total, 999)),\n      formatOverflowCount(total),\n    ]),\n  );\n\ntype ComboboxOverflowMeasurements = {\n  /** Widths of every selected tag, in selection order. */\n  tagWidths: number[];\n  /** Width of the widest counter tag the current selection could need. */\n  counterWidth: number;\n  /** Content width of the wrapping value container. */\n  containerWidth: number;\n  /** Column gap between tags. */\n  gap: number;\n  /** Maximum number of rows the tags may wrap into. */\n  maxRows: number;\n};\n\n/**\n * How many tags fit within `maxRows` rows of the value container, mirroring\n * the greedy line breaking of `flex-wrap`. When they all fit, the count is the\n * number of tags and no counter is needed; otherwise the result leaves room\n * for the counter tag on the last permitted row.\n */\nexport const computeVisibleTagCount = ({\n  tagWidths,\n  counterWidth,\n  containerWidth,\n  gap,\n  maxRows,\n}: ComboboxOverflowMeasurements): number => {\n  // An unmeasurable container - hidden, or not laid out yet - must not\n  // collapse the whole selection into a counter.\n  if (containerWidth <= 0) {\n    return tagWidths.length;\n  }\n\n  const rowLimit = Math.max(1, Math.floor(maxRows));\n  const boundedCounterWidth = Math.min(counterWidth, containerWidth);\n  // With more than one tag a counter may be needed, so the stylesheet caps\n  // every tag at the container width minus room for the counter, and the\n  // simulation must clamp with the same cap to match the rendered widths.\n  // Extremely narrow containers where the cap would leave no room for a tag\n  // fall back to capping at the container width alone.\n  const counterReservedCap = containerWidth - gap - boundedCounterWidth;\n  const tagCap =\n    tagWidths.length > 1 && counterReservedCap > 0\n      ? counterReservedCap\n      : containerWidth;\n  const widths = tagWidths.map((width) => Math.min(width, tagCap));\n  // Row and remaining row width after each prefix of tags, so every candidate\n  // cutoff can be checked without resimulating.\n  const placements: { row: number; rowWidth: number }[] = [];\n  let row = 1;\n  let rowWidth = 0;\n\n  widths.forEach((width, index) => {\n    if (index === 0) {\n      rowWidth = width;\n    } else if (rowWidth + gap + width <= containerWidth) {\n      rowWidth += gap + width;\n    } else {\n      row += 1;\n      rowWidth = width;\n    }\n\n    placements.push({ row, rowWidth });\n  });\n\n  if (row <= rowLimit) {\n    return widths.length;\n  }\n\n  for (let count = widths.length - 1; count >= 1; count -= 1) {\n    const placement = placements[count - 1];\n    const counterRow =\n      placement.rowWidth + gap + boundedCounterWidth <= containerWidth\n        ? placement.row\n        : placement.row + 1;\n\n    if (counterRow <= rowLimit) {\n      return count;\n    }\n  }\n\n  // Not even one tag leaves room for the counter, so the counter stands alone.\n  return 0;\n};\n\ntype UseComboboxMultiValueOverflowOptions = {\n  /** Undefined leaves the selection unbounded and skips all measuring. */\n  maxRows: number | undefined;\n  /** Number of selected options rendered as tags. */\n  tagCount: number;\n  /**\n   * Anything that changes tag widths without changing the container size, such\n   * as the selection itself or the control size, so those changes re-measure.\n   */\n  measureKey: string;\n};\n\n/**\n * Caps the rows of selected tags in a multi select control. All tags stay\n * rendered; the ones past `visibleCount` are taken out of the layout by the\n * stylesheet but stay measurable, so the computation is stable across passes.\n * Width comes from a `ResizeObserver` on the value container, and everything\n * else from `measureKey`.\n */\nexport const useComboboxMultiValueOverflow = ({\n  maxRows,\n  tagCount,\n  measureKey,\n}: UseComboboxMultiValueOverflowOptions) => {\n  const containerRef = useRef<HTMLDivElement | null>(null);\n  // null shows every tag, which is also the server-rendered state.\n  const [visibleCount, setVisibleCount] = useState<number | null>(null);\n  const isLimited = maxRows !== undefined && tagCount > 0;\n\n  const measure = () => {\n    const container = containerRef.current;\n\n    if (maxRows === undefined || container === null) {\n      setVisibleCount(null);\n      return;\n    }\n\n    const tags = Array.from(\n      container.querySelectorAll<HTMLElement>(\n        ':scope > .ndl-combobox-multi-value',\n      ),\n    );\n    // With K formatting the widest counter is not always the one for the full\n    // count - \"+999\" is wider than \"+1K\" - so every candidate is rendered as a\n    // measure tag and the widest one sets the reserve.\n    const counters = Array.from(\n      container.querySelectorAll<HTMLElement>(\n        ':scope > .ndl-combobox-multi-value-measure',\n      ),\n    );\n\n    if (tags.length === 0 || counters.length === 0) {\n      setVisibleCount(null);\n      return;\n    }\n\n    const counterWidth = Math.max(\n      ...counters.map((counter) => counter.getBoundingClientRect().width),\n    );\n    const gap =\n      Number.parseFloat(window.getComputedStyle(container).columnGap) || 0;\n\n    // The stylesheet caps every tag at the container width minus this reserve,\n    // so a tag too wide to sit next to the counter shrinks instead of\n    // collapsing. Set before the tag rects are read, so the forced layout\n    // below applies it and the widths reflect the cap. Rounded up plus one\n    // pixel of slack, so subpixel layout quantization can never make a capped\n    // tag plus the counter overflow the row.\n    container.style.setProperty(\n      '--ndl-combobox-counter-reserve',\n      `${Math.ceil(gap + counterWidth) + 1}px`,\n    );\n\n    // Fractional widths, so rounding never claims room the browser would wrap.\n    const nextVisibleCount = computeVisibleTagCount({\n      containerWidth: container.getBoundingClientRect().width,\n      counterWidth,\n      gap,\n      maxRows,\n      tagWidths: tags.map((tag) => tag.getBoundingClientRect().width),\n    });\n\n    setVisibleCount(nextVisibleCount >= tags.length ? null : nextVisibleCount);\n  };\n\n  const measureRef = useRef(measure);\n\n  useLayoutEffect(() => {\n    measureRef.current = measure;\n    measure();\n    // measure() reads the DOM, so it depends on everything the key encodes\n    // rather than on reactive values of its own.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [isLimited, maxRows, tagCount, measureKey]);\n\n  useLayoutEffect(() => {\n    const container = containerRef.current;\n\n    if (!isLimited || container === null) {\n      return;\n    }\n\n    // Hiding tags only changes the container height, and the recomputation is\n    // idempotent, so the observer settles after a single extra pass.\n    const observer = new ResizeObserver(() => {\n      measureRef.current();\n    });\n\n    observer.observe(container);\n    return () => {\n      observer.disconnect();\n    };\n  }, [isLimited]);\n\n  return { containerRef, visibleCount };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,uBAAuB,UAClC,QAAQ,MAAO,GAAG,UAAU,GAAG,KAAK,MAAM,QAAQ,GAAI,EAAE;;;;;;;AAQ1D,MAAa,kCAAkC,UAC7C,MAAM,qBACJ,IAAI,IAAI,CACN,oBAAoB,KAAK,IAAI,OAAO,GAAG,CAAC,GACxC,oBAAoB,KAAK,CAC3B,CAAC,CACH;;;;;;;AAqBF,MAAa,0BAA0B,EACrC,WACA,cACA,gBACA,KACA,cAC0C;CAG1C,IAAI,kBAAkB,GACpB,OAAO,UAAU;CAGnB,MAAM,WAAW,KAAK,IAAI,GAAG,KAAK,MAAM,OAAO,CAAC;CAChD,MAAM,sBAAsB,KAAK,IAAI,cAAc,cAAc;CAMjE,MAAM,qBAAqB,iBAAiB,MAAM;CAClD,MAAM,SACJ,UAAU,SAAS,KAAK,qBAAqB,IACzC,qBACA;CACN,MAAM,SAAS,UAAU,KAAK,UAAU,KAAK,IAAI,OAAO,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