fis-component 0.1.21 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -62345,6 +62345,16 @@ const FixedBottomSection = styled.div `
62345
62345
  border-bottom-left-radius: ${getTheme("com/menu/corner-radius")};
62346
62346
  border-bottom-right-radius: ${getTheme("com/menu/corner-radius")};
62347
62347
  `;
62348
+ const DivFooterSC = styled.div `
62349
+ display: flex;
62350
+ align-items: center;
62351
+ justify-content: center;
62352
+ gap: ${getTheme("com/menu/item/horizontal-gap")};
62353
+ padding: ${getTheme("com/menu/top-padding")} 0;
62354
+ min-height: ${getTheme("com/menu/item/size-md/min-height")};
62355
+ ${getTheme("Paragraph/Sm")}
62356
+ color: ${getTheme("com/menu/item/action/label/color-text/default")};
62357
+ `;
62348
62358
  styled.span `
62349
62359
  ${getTheme("Subheading/XS")}
62350
62360
  color: ${getTheme("com/menu/group-label/color-text")};
@@ -69251,11 +69261,13 @@ const normalizeText = (value) => {
69251
69261
  .trim();
69252
69262
  };
69253
69263
 
69254
- const FISMenuSelect = ({ placeholder, groups, size = "md", multi = false, selectedValues = [], onChangeSelected, searchValue = "", onSearchChange, loading = false, noData = false, noResult = false, combobox, className, onClickMenu, loadingText = "Data loading...", noDataText = "No data", noResultText = "No result", removeSelectedText = "Remove selected", selectedGroupLabel = "Selected", maxHeight, focusSearchInput = true, onPopupScroll, normalizeTextSearch = false, renderOption, }) => {
69264
+ const FISMenuSelect = ({ placeholder, groups, size = "md", multi = false, selectedValues = [], onChangeSelected, searchValue = "", onSearchChange, loading = false, noData = false, noResult = false, combobox, className, onClickMenu, loadingText = "Data loading...", noDataText = "No data", noResultText = "No result", removeSelectedText = "Remove selected", selectedGroupLabel = "Selected", maxHeight, focusSearchInput = true, onPopupScroll, normalizeTextSearch = false, renderOption, searchDebounce = 300, footer, showSearch, onSearchInput, virtualized = false, virtualItemHeight, }) => {
69265
+ // Chiều cao hàng = min-height item + gap xs (4px): md 36+4, lg 44+4.
69266
+ const intrinsicItemHeight = virtualItemHeight ?? (size === "lg" ? 48 : 40);
69255
69267
  const [localSearch, setLocalSearch] = useState(searchValue);
69256
69268
  const [debouncedSearchValue, setDebouncedSearchValue] = useState(searchValue);
69257
69269
  const searchInputRef = useRef(null);
69258
- const debouncedSetSearch = useMemo$1(() => debounce$1((value) => setDebouncedSearchValue(value), 300), []);
69270
+ const debouncedSetSearch = useMemo$1(() => debounce$1((value) => setDebouncedSearchValue(value), searchDebounce), [searchDebounce]);
69259
69271
  useEffect(() => {
69260
69272
  debouncedSetSearch(localSearch);
69261
69273
  }, [localSearch, debouncedSetSearch]);
@@ -69266,10 +69278,14 @@ const FISMenuSelect = ({ placeholder, groups, size = "md", multi = false, select
69266
69278
  };
69267
69279
  }, [debouncedSetSearch]);
69268
69280
  useEffect(() => {
69269
- if (onSearchChange && debouncedSearchValue !== searchValue) {
69270
- onSearchChange(debouncedSearchValue);
69271
- }
69281
+ if (!onSearchChange || debouncedSearchValue === searchValue)
69282
+ return;
69283
+ onSearchChange(debouncedSearchValue);
69272
69284
  }, [debouncedSearchValue, onSearchChange, searchValue]);
69285
+ // Quan sát text search (phục vụ creatable ở client mode) — không tắt lọc client.
69286
+ useEffect(() => {
69287
+ onSearchInput?.(debouncedSearchValue);
69288
+ }, [debouncedSearchValue, onSearchInput]);
69273
69289
  const search = localSearch;
69274
69290
  const filteredGroups = useMemo$1(() => {
69275
69291
  if (onSearchChange) {
@@ -69321,7 +69337,7 @@ const FISMenuSelect = ({ placeholder, groups, size = "md", multi = false, select
69321
69337
  : null;
69322
69338
  const totalItems = groups.reduce((acc, group) => acc + group.items.length, 0);
69323
69339
  const hasSearch = search.trim() !== "";
69324
- const showInput = totalItems >= 7 || hasSearch;
69340
+ const showInput = showSearch ?? (totalItems >= 7 || hasSearch);
69325
69341
  const hasFilteredResult = groupsToRender.length > 0;
69326
69342
  const shouldShowNoResult = hasSearch && !hasFilteredResult;
69327
69343
  const handleSearchChange = (e) => {
@@ -69355,7 +69371,63 @@ const FISMenuSelect = ({ placeholder, groups, size = "md", multi = false, select
69355
69371
  searchInputRef.current.focus();
69356
69372
  }
69357
69373
  }, [focusSearchInput]);
69358
- return (jsxs(DivContainerSC$a, { "$maxHeight": maxHeight, className: className, children: [showInput && !combobox && (jsx(DivSearchSC, { children: jsx(FISInputText, { iconPrefix: jsx(SearchIcon, {}), placeholder: placeholder, value: search, onChange: handleSearchChange, ref: searchInputRef }) })), loading && (jsxs(DivLoaderSC, { children: [jsx(FISProgressCircular, { size: size, variant: "indeterminate" }), jsx(PTitleSC$3, { children: loadingText })] })), !loading && noData && (jsxs(DivLoaderSC, { children: [jsx(DivIconDataSC, { children: jsx(NoDataIcon, {}) }), jsx(PTitleSC$3, { children: noDataText })] })), !loading && !noData && (shouldShowNoResult || noResult) && (jsxs(DivLoaderSC, { children: [jsx(DivIconDataSC, { children: jsx(NoResultIcon, {}) }), jsx(PTitleSC$3, { children: noResultText })] })), !shouldShowNoResult && !noData && !loading && (jsxs(Fragment, { children: [jsx(MenuContent, { "$removeSelectedGroup": !!removeSelectedGroup, onScroll: onPopupScroll, children: groupsToRender.map((group, index) => (jsxs(DivWrapperSC$6, { children: [index !== 0 && jsx(FISMenuSection, { withDivider: true }), group?.groupLabel && (jsx(FISMenuSection, { label: group?.groupLabel })), group.items.map((item, idx) => (jsx(FISTooltip, { title: item.label, variant: "primary", children: renderOption ? (jsx("div", { onClick: () => handleItemClick(item), children: renderOption(item) })) : (jsx(FISMenuItem, { title: item.label, description: item.description, size: size, onClickMenu: () => handleItemClick(item), selected: selectedValues.includes(item.value), type: "select" })) }, idx)))] }, index))) }), removeSelectedGroup && (jsx(FixedBottomSection, { children: jsx(DivWrapperSC$6, { children: removeSelectedGroup.items.map((item, idx) => (jsx(FISTooltip, { title: item.label, variant: "primary", children: jsx(FISMenuItem, { title: item.label, description: item.description, size: size, onClickMenu: () => onChangeSelected?.([]), type: "select", iconPrefix: jsx(RemoveIcon, {}), negative: true }) }, idx))) }) }))] }))] }));
69374
+ /* ---- Windowing thật (virtualized) — chỉ render item trong viewport ---- */
69375
+ const VIRTUAL_OVERSCAN = 6;
69376
+ const scrollElRef = useRef(null);
69377
+ const [virtualScrollTop, setVirtualScrollTop] = useState(0);
69378
+ const [virtualViewportH, setVirtualViewportH] = useState(0);
69379
+ const measureViewport = useCallback(() => {
69380
+ if (scrollElRef.current)
69381
+ setVirtualViewportH(scrollElRef.current.clientHeight);
69382
+ }, []);
69383
+ // callback ref: đo lại mỗi khi MenuContent mount (đóng/mở, đổi no-data...).
69384
+ const setScrollEl = useCallback((el) => {
69385
+ scrollElRef.current = el;
69386
+ if (el)
69387
+ setVirtualViewportH(el.clientHeight);
69388
+ }, []);
69389
+ const handleMenuScroll = useCallback((e) => {
69390
+ if (virtualized) {
69391
+ setVirtualScrollTop(e.currentTarget.scrollTop);
69392
+ }
69393
+ onPopupScroll?.(e); // vẫn phát loadmore
69394
+ }, [virtualized, onPopupScroll]);
69395
+ useEffect(() => {
69396
+ if (!virtualized)
69397
+ return;
69398
+ window.addEventListener("resize", measureViewport);
69399
+ return () => window.removeEventListener("resize", measureViewport);
69400
+ }, [virtualized, measureViewport]);
69401
+ const flatRows = useMemo$1(() => {
69402
+ if (!virtualized)
69403
+ return [];
69404
+ const rows = [];
69405
+ groupsToRender.forEach((group, gi) => {
69406
+ if (group.groupLabel) {
69407
+ rows.push({ type: "label", label: group.groupLabel, key: `l-${gi}` });
69408
+ }
69409
+ group.items.forEach((item, ii) => {
69410
+ rows.push({ type: "item", item, key: `i-${gi}-${item.value}-${ii}` });
69411
+ });
69412
+ });
69413
+ return rows;
69414
+ }, [virtualized, groupsToRender]);
69415
+ const rowHeight = intrinsicItemHeight;
69416
+ const totalVirtualHeight = flatRows.length * rowHeight;
69417
+ const startIndex = Math.max(0, Math.floor(virtualScrollTop / rowHeight) - VIRTUAL_OVERSCAN);
69418
+ const endIndex = Math.min(flatRows.length, Math.ceil((virtualScrollTop + virtualViewportH) / rowHeight) +
69419
+ VIRTUAL_OVERSCAN);
69420
+ const visibleRows = flatRows.slice(startIndex, endIndex);
69421
+ const renderItemNode = (item) => (jsx(FISTooltip, { title: item.label, variant: "primary", children: renderOption ? (jsx("div", { onClick: () => handleItemClick(item), children: renderOption(item) })) : (jsx(FISMenuItem, { title: item.label, description: item.description, size: size, onClickMenu: () => handleItemClick(item), selected: selectedValues.includes(item.value), type: "select" })) }));
69422
+ return (jsxs(DivContainerSC$a, { "$maxHeight": maxHeight, className: className, children: [showInput && !combobox && (jsx(DivSearchSC, { children: jsx(FISInputText, { iconPrefix: jsx(SearchIcon, {}), placeholder: placeholder, value: search, onChange: handleSearchChange, ref: searchInputRef }) })), loading && (jsxs(DivLoaderSC, { children: [jsx(FISProgressCircular, { size: size, variant: "indeterminate" }), jsx(PTitleSC$3, { children: loadingText })] })), !loading && noData && (jsxs(DivLoaderSC, { children: [jsx(DivIconDataSC, { children: jsx(NoDataIcon, {}) }), jsx(PTitleSC$3, { children: noDataText })] })), !loading && !noData && (shouldShowNoResult || noResult) && (jsxs(DivLoaderSC, { children: [jsx(DivIconDataSC, { children: jsx(NoResultIcon, {}) }), jsx(PTitleSC$3, { children: noResultText })] })), !shouldShowNoResult && !noData && !loading && (jsxs(Fragment, { children: [virtualized ? (jsxs(MenuContent, { ref: setScrollEl, "$removeSelectedGroup": !!removeSelectedGroup, onScroll: handleMenuScroll, children: [jsx("div", { style: { height: totalVirtualHeight, position: "relative" }, children: visibleRows.map((row, i) => {
69423
+ const index = startIndex + i;
69424
+ return (jsx("div", { style: {
69425
+ position: "absolute",
69426
+ top: index * rowHeight,
69427
+ left: 0,
69428
+ right: 0,
69429
+ }, children: row.type === "label" ? (jsx(FISMenuSection, { label: row.label })) : (renderItemNode(row.item)) }, row.key));
69430
+ }) }), footer && jsx(DivFooterSC, { children: footer })] })) : (jsxs(MenuContent, { "$removeSelectedGroup": !!removeSelectedGroup, onScroll: onPopupScroll, children: [groupsToRender.map((group, index) => (jsxs(DivWrapperSC$6, { children: [index !== 0 && jsx(FISMenuSection, { withDivider: true }), group?.groupLabel && (jsx(FISMenuSection, { label: group?.groupLabel })), group.items.map((item, idx) => (jsx(FISTooltip, { title: item.label, variant: "primary", children: renderOption ? (jsx("div", { onClick: () => handleItemClick(item), children: renderOption(item) })) : (jsx(FISMenuItem, { title: item.label, description: item.description, size: size, onClickMenu: () => handleItemClick(item), selected: selectedValues.includes(item.value), type: "select" })) }, idx)))] }, index))), footer && jsx(DivFooterSC, { children: footer })] })), removeSelectedGroup && (jsx(FixedBottomSection, { children: jsx(DivWrapperSC$6, { children: removeSelectedGroup.items.map((item, idx) => (jsx(FISTooltip, { title: item.label, variant: "primary", children: jsx(FISMenuItem, { title: item.label, description: item.description, size: size, onClickMenu: () => onChangeSelected?.([]), type: "select", iconPrefix: jsx(RemoveIcon, {}), negative: true }) }, idx))) }) }))] }))] }));
69359
69431
  };
69360
69432
  FISMenuSelect.displayName = "FISMenuSelect";
69361
69433
 
@@ -75561,7 +75633,7 @@ function isMenuSize(value) {
75561
75633
  return value === "sm" || value === "md";
75562
75634
  }
75563
75635
 
75564
- const FISSelect = forwardRef(({ className, style, size = "md", options, value, disabled = false, textLabel = "", iconLabel, required, negative, message, positive, multi, placeholder, placeholderSearch, loading, onChange, renderOption, onClickIconLabel, displayValue, multiDisplayText, searchValue, onSearchChange, portal = true, maxHeight, onPopupScroll, onOpen, hideChip, tooltipTitle, tooltipVariant = "primary", ...restProps }, ref) => {
75636
+ const FISSelect = forwardRef(({ className, style, size = "md", options, value, disabled = false, textLabel = "", iconLabel, required, negative, message, positive, multi, placeholder, placeholderSearch, loading, onChange, renderOption, onClickIconLabel, displayValue, multiDisplayText, searchValue, onSearchChange, portal = true, maxHeight, onPopupScroll, onOpen, hideChip, tooltipTitle, tooltipVariant = "primary", noData, noResult, footer, searchDebounce, showSearch, onSearchInput, virtualized, virtualItemHeight, ...restProps }, ref) => {
75565
75637
  const [isOpen, setIsOpen] = useState(false);
75566
75638
  const [referenceElement, setReferenceElement] = useState(null);
75567
75639
  const [popperElement, setPopperElement] = useState(null);
@@ -75705,6 +75777,14 @@ const FISSelect = forwardRef(({ className, style, size = "md", options, value, d
75705
75777
  maxHeight,
75706
75778
  onPopupScroll,
75707
75779
  renderOption,
75780
+ noData,
75781
+ noResult,
75782
+ footer,
75783
+ searchDebounce,
75784
+ showSearch,
75785
+ onSearchInput,
75786
+ virtualized,
75787
+ virtualItemHeight,
75708
75788
  ...restProps,
75709
75789
  }), [
75710
75790
  options,
@@ -75720,6 +75800,14 @@ const FISSelect = forwardRef(({ className, style, size = "md", options, value, d
75720
75800
  maxHeight,
75721
75801
  onPopupScroll,
75722
75802
  renderOption,
75803
+ noData,
75804
+ noResult,
75805
+ footer,
75806
+ searchDebounce,
75807
+ showSearch,
75808
+ onSearchInput,
75809
+ virtualized,
75810
+ virtualItemHeight,
75723
75811
  restProps,
75724
75812
  ]);
75725
75813
  useEffect(() => {
@@ -75763,6 +75851,455 @@ const FISSelect = forwardRef(({ className, style, size = "md", options, value, d
75763
75851
  });
75764
75852
  FISSelect.displayName = "FISSelect";
75765
75853
 
75854
+ const SPINNER_DELAY = 150;
75855
+ const SCROLL_THRESHOLD = 32;
75856
+ /** Chống double-fetch do onOpen fire cả khi đóng (chỉ dùng khi reuseOnReopen=false). */
75857
+ const OPEN_DEDUPE_MS = 400;
75858
+ /**
75859
+ * Ngưỡng auto-fill mặc định: số item tối thiểu để dropdown chắc chắn có thanh cuộn.
75860
+ * Đây là ước lượng CỐ ĐỊNH (không đo DOM). Hợp với dropdown thấp (~maxHeight 320-420,
75861
+ * item size md). Nếu maxHeight lớn / item cao, truyền `autoFillMinItems` lớn hơn.
75862
+ * Xem công thức chọn số trong JSDoc của prop `autoFillMinItems` (types.ts).
75863
+ */
75864
+ const DEFAULT_AUTO_FILL_MIN_ITEMS = 12;
75865
+ /** Key nhận diện một truy vấn: mode + search (server) + params. */
75866
+ function buildKey(mode, search, params) {
75867
+ return JSON.stringify({ mode, search, params: params ?? null });
75868
+ }
75869
+ function dedupeByValue(list) {
75870
+ const seen = new Set();
75871
+ const out = [];
75872
+ for (const item of list) {
75873
+ if (!seen.has(item.value)) {
75874
+ seen.add(item.value);
75875
+ out.push(item);
75876
+ }
75877
+ }
75878
+ return out;
75879
+ }
75880
+ function useApiSelect(opts) {
75881
+ const [items, setItems] = useState([]);
75882
+ const [hasMore, setHasMore] = useState(false);
75883
+ const [inFlightInitial, setInFlightInitial] = useState(false);
75884
+ const [inFlightMore, setInFlightMore] = useState(false);
75885
+ const [showInitialSpinner, setShowInitialSpinner] = useState(false);
75886
+ const [errorInitial, setErrorInitial] = useState(null);
75887
+ const [errorMore, setErrorMore] = useState(null);
75888
+ const [serverSearch, setServerSearch] = useState("");
75889
+ const [uiSearch, setUiSearch] = useState("");
75890
+ const [resolvedSelected, setResolvedSelected] = useState(() => {
75891
+ const map = new Map();
75892
+ (opts.defaultSelectedOptions ?? []).forEach((o) => map.set(o.value, o));
75893
+ return map;
75894
+ });
75895
+ const [active, setActive] = useState(!opts.fetchOnOpen);
75896
+ /** Đã settle (fetch xong, dù rỗng) cho query hiện tại -> quyết định noData/noResult. */
75897
+ const [settled, setSettled] = useState(false);
75898
+ // Giữ props/flags mới nhất cho các callback ổn định.
75899
+ const configRef = useRef(opts);
75900
+ configRef.current = opts;
75901
+ const paramsKey = JSON.stringify(opts.params ?? null);
75902
+ const key = useMemo$1(() => buildKey(opts.mode, opts.searchMode === "server" ? serverSearch : "", opts.params), [opts.mode, opts.searchMode, serverSearch, paramsKey]);
75903
+ const abortRef = useRef(null);
75904
+ const fetchSeqRef = useRef(0);
75905
+ const nextPageParamRef = useRef(undefined);
75906
+ const itemsRef = useRef(items);
75907
+ itemsRef.current = items;
75908
+ const activeRef = useRef(active);
75909
+ activeRef.current = active;
75910
+ const serverSearchRef = useRef(serverSearch);
75911
+ serverSearchRef.current = serverSearch;
75912
+ /** Key của truy vấn mà `items` hiện đang phản ánh (null = chưa tải). */
75913
+ const loadedKeyRef = useRef(null);
75914
+ /** Mốc thời gian lần ép tải khi mở gần nhất (chống close-fire khi reuseOnReopen=false). */
75915
+ const lastForceOpenRef = useRef(0);
75916
+ const requestedIdsRef = useRef(new Set());
75917
+ // Flags đọc-mới-nhất cho scroll handler (cập nhật ngay trong render).
75918
+ const flagsRef = useRef({
75919
+ hasMore,
75920
+ inFlightMore,
75921
+ inFlightInitial,
75922
+ errorMore,
75923
+ mode: opts.mode,
75924
+ });
75925
+ flagsRef.current = {
75926
+ hasMore,
75927
+ inFlightMore,
75928
+ inFlightInitial,
75929
+ errorMore,
75930
+ mode: opts.mode,
75931
+ };
75932
+ // Spinner trễ để tránh nháy khi API phản hồi nhanh.
75933
+ useEffect(() => {
75934
+ if (!inFlightInitial) {
75935
+ setShowInitialSpinner(false);
75936
+ return;
75937
+ }
75938
+ const t = setTimeout(() => setShowInitialSpinner(true), SPINNER_DELAY);
75939
+ return () => clearTimeout(t);
75940
+ }, [inFlightInitial]);
75941
+ const runFetch = useCallback(async (params) => {
75942
+ const cfg = configRef.current;
75943
+ if (!cfg.fetchEnabled)
75944
+ return;
75945
+ const { reset } = params;
75946
+ abortRef.current?.abort();
75947
+ const controller = new AbortController();
75948
+ abortRef.current = controller;
75949
+ const seq = ++fetchSeqRef.current;
75950
+ const search = cfg.searchMode === "server" ? serverSearchRef.current : "";
75951
+ const currentKey = buildKey(cfg.mode, search, cfg.params);
75952
+ const pageParam = reset ? undefined : nextPageParamRef.current;
75953
+ if (reset) {
75954
+ setInFlightInitial(true);
75955
+ setErrorInitial(null);
75956
+ setErrorMore(null); // reset từ trang 1 -> lỗi loadmore cũ không còn ngữ cảnh
75957
+ setItems([]);
75958
+ setHasMore(false);
75959
+ setSettled(false);
75960
+ nextPageParamRef.current = undefined;
75961
+ // Invalidate ngay: items vừa bị xoá nên loadedKey cũ không còn đúng
75962
+ // (tránh A->B->A nhanh bị skip fetch khi B chưa xong).
75963
+ loadedKeyRef.current = null;
75964
+ }
75965
+ else {
75966
+ setInFlightMore(true);
75967
+ setErrorMore(null);
75968
+ }
75969
+ try {
75970
+ const raw = await cfg.fetcher({
75971
+ search,
75972
+ params: cfg.params,
75973
+ pageParam,
75974
+ signal: controller.signal,
75975
+ });
75976
+ if (seq !== fetchSeqRef.current || controller.signal.aborted)
75977
+ return;
75978
+ const normalized = Array.isArray(raw)
75979
+ ? {
75980
+ options: raw,
75981
+ hasMore: false,
75982
+ nextPageParam: undefined,
75983
+ }
75984
+ : raw;
75985
+ const merged = reset
75986
+ ? dedupeByValue(normalized.options)
75987
+ : dedupeByValue([...itemsRef.current, ...normalized.options]);
75988
+ setItems(merged);
75989
+ setHasMore(cfg.mode === "loadmore" ? normalized.hasMore : false);
75990
+ nextPageParamRef.current = normalized.nextPageParam;
75991
+ setSettled(true);
75992
+ loadedKeyRef.current = currentKey; // đánh dấu đã tải cho query này
75993
+ cfg.onLoaded?.(merged, reset ? "initial" : "more");
75994
+ // Auto-fill: trang đầu quá ngắn (không tràn dropdown) -> không có scroll để
75995
+ // loadmore. Nếu vẫn còn trang và list chưa đủ dài thì tự tải tiếp trang kế.
75996
+ // Guard `normalized.options.length > 0` tránh loop vô hạn khi API trả rỗng
75997
+ // nhưng vẫn báo hasMore.
75998
+ if (cfg.mode === "loadmore" &&
75999
+ cfg.autoFill &&
76000
+ activeRef.current &&
76001
+ normalized.hasMore &&
76002
+ normalized.options.length > 0 &&
76003
+ merged.length < cfg.autoFillMinItems) {
76004
+ void runFetch({ reset: false });
76005
+ }
76006
+ }
76007
+ catch (err) {
76008
+ if (err?.name === "AbortError" ||
76009
+ seq !== fetchSeqRef.current) {
76010
+ return;
76011
+ }
76012
+ if (reset) {
76013
+ setErrorInitial(err);
76014
+ setSettled(true);
76015
+ loadedKeyRef.current = null; // lỗi -> cho phép thử lại
76016
+ }
76017
+ else {
76018
+ setErrorMore(err);
76019
+ }
76020
+ cfg.onFetchError?.(err, reset ? "initial" : "more");
76021
+ }
76022
+ finally {
76023
+ if (seq === fetchSeqRef.current) {
76024
+ if (reset)
76025
+ setInFlightInitial(false);
76026
+ else
76027
+ setInFlightMore(false);
76028
+ }
76029
+ }
76030
+ }, []);
76031
+ // Tải khi: mở lần đầu (active bật) hoặc đổi search/params (key đổi).
76032
+ // Mở lại cùng một query (key không đổi) -> effect không chạy -> không refetch.
76033
+ useEffect(() => {
76034
+ if (!active || !opts.fetchEnabled)
76035
+ return;
76036
+ if (loadedKeyRef.current === key)
76037
+ return; // đã có data cho query này
76038
+ void runFetch({ reset: true });
76039
+ // eslint-disable-next-line react-hooks/exhaustive-deps
76040
+ }, [active, key, opts.fetchEnabled]);
76041
+ // Huỷ request khi unmount.
76042
+ useEffect(() => {
76043
+ return () => abortRef.current?.abort();
76044
+ }, []);
76045
+ // Resolve label cho value đã chọn nhưng chưa có trong list.
76046
+ useEffect(() => {
76047
+ const cfg = configRef.current;
76048
+ if (!cfg.fetchByIds || opts.selectedValues.length === 0)
76049
+ return;
76050
+ const present = new Set(itemsRef.current.map((i) => i.value));
76051
+ const missing = opts.selectedValues.filter((v) => !present.has(v) &&
76052
+ !resolvedSelected.has(v) &&
76053
+ !requestedIdsRef.current.has(v));
76054
+ if (missing.length === 0)
76055
+ return;
76056
+ missing.forEach((v) => requestedIdsRef.current.add(v));
76057
+ let cancelled = false;
76058
+ void cfg
76059
+ .fetchByIds(missing)
76060
+ .then((fetched) => {
76061
+ if (cancelled)
76062
+ return;
76063
+ setResolvedSelected((prev) => {
76064
+ const next = new Map(prev);
76065
+ fetched.forEach((o) => next.set(o.value, o));
76066
+ return next;
76067
+ });
76068
+ })
76069
+ .catch(() => {
76070
+ // Bỏ qua lỗi resolve label; value vẫn hiển thị dạng thô.
76071
+ });
76072
+ return () => {
76073
+ cancelled = true;
76074
+ };
76075
+ // eslint-disable-next-line react-hooks/exhaustive-deps
76076
+ }, [opts.selectedValues, items, resolvedSelected]);
76077
+ // Seed lại khi defaultSelectedOptions đổi.
76078
+ useEffect(() => {
76079
+ if (!opts.defaultSelectedOptions?.length)
76080
+ return;
76081
+ setResolvedSelected((prev) => {
76082
+ const next = new Map(prev);
76083
+ opts.defaultSelectedOptions.forEach((o) => next.set(o.value, o));
76084
+ return next;
76085
+ });
76086
+ }, [opts.defaultSelectedOptions]);
76087
+ const handleOpen = useCallback(() => {
76088
+ if (!activeRef.current) {
76089
+ setActive(true); // effect sẽ tải lần đầu
76090
+ return;
76091
+ }
76092
+ // Đã active (mở lại / đóng). Xoá lỗi loadmore cũ để mở lại là danh sách sạch,
76093
+ // cuộn có thể thử tải thêm lại. (reuseOnReopen=true không reset nên phải clear
76094
+ // ở đây; reuseOnReopen=false thì reset của runFetch bên dưới cũng clear.)
76095
+ setErrorMore(null);
76096
+ // reuseOnReopen=true -> dùng lại data; false -> tải lại.
76097
+ if (!configRef.current.reuseOnReopen) {
76098
+ const now = Date.now();
76099
+ if (now - lastForceOpenRef.current < OPEN_DEDUPE_MS)
76100
+ return;
76101
+ lastForceOpenRef.current = now;
76102
+ void runFetch({ reset: true });
76103
+ }
76104
+ }, [runFetch]);
76105
+ const handlePopupScroll = useCallback((e) => {
76106
+ const f = flagsRef.current;
76107
+ if (f.mode !== "loadmore")
76108
+ return;
76109
+ if (!f.hasMore || f.inFlightMore || f.inFlightInitial || f.errorMore) {
76110
+ return;
76111
+ }
76112
+ const el = e.currentTarget;
76113
+ if (el.scrollTop + el.clientHeight >=
76114
+ el.scrollHeight - SCROLL_THRESHOLD) {
76115
+ void runFetch({ reset: false });
76116
+ }
76117
+ }, [runFetch]);
76118
+ const handleServerSearch = useCallback((value) => {
76119
+ setServerSearch(value);
76120
+ }, []);
76121
+ const handleUiSearch = useCallback((value) => {
76122
+ setUiSearch(value);
76123
+ }, []);
76124
+ const refresh = useCallback(() => {
76125
+ // Clear như reload() để nhất quán: cho phép thử lại fetchByIds với id từng
76126
+ // request nhưng resolve label thất bại (id đã resolve vẫn được guard bởi
76127
+ // resolvedSelected nên không gọi lại thừa).
76128
+ requestedIdsRef.current.clear();
76129
+ loadedKeyRef.current = null; // buộc tải lại query hiện tại
76130
+ void runFetch({ reset: true });
76131
+ }, [runFetch]);
76132
+ const reload = useCallback(() => {
76133
+ requestedIdsRef.current.clear();
76134
+ loadedKeyRef.current = null;
76135
+ if (serverSearchRef.current === "") {
76136
+ void runFetch({ reset: true }); // key không đổi -> tự tải lại
76137
+ }
76138
+ else {
76139
+ setServerSearch(""); // key đổi -> effect sẽ tải lại
76140
+ }
76141
+ }, [runFetch]);
76142
+ const getOptions = useCallback(() => itemsRef.current, []);
76143
+ // Ghép options cuối cùng: [selected chưa có trong list] có thể ghim đầu/cuối.
76144
+ const groups = useMemo$1(() => {
76145
+ const result = [];
76146
+ const present = new Set(items.map((i) => i.value));
76147
+ const extraSelected = opts.selectedValues
76148
+ .filter((v) => !present.has(v) && resolvedSelected.has(v))
76149
+ .map((v) => resolvedSelected.get(v));
76150
+ const extraGroup = extraSelected.length ? { items: extraSelected } : null;
76151
+ if (extraGroup && opts.pinSelectedOnTop)
76152
+ result.push(extraGroup);
76153
+ if (items.length)
76154
+ result.push({ items });
76155
+ if (extraGroup && !opts.pinSelectedOnTop)
76156
+ result.push(extraGroup);
76157
+ return result;
76158
+ }, [items, resolvedSelected, opts.selectedValues, opts.pinSelectedOnTop]);
76159
+ const searchActive = (opts.searchMode === "server" ? serverSearch : uiSearch).trim() !== "";
76160
+ const noData = settled &&
76161
+ !inFlightInitial &&
76162
+ !errorInitial &&
76163
+ items.length === 0 &&
76164
+ !searchActive;
76165
+ // Client mode: để MenuSelect tự quyết noResult khi lọc rỗng.
76166
+ const noResult = opts.searchMode === "server" &&
76167
+ settled &&
76168
+ !inFlightInitial &&
76169
+ !errorInitial &&
76170
+ items.length === 0 &&
76171
+ searchActive;
76172
+ return {
76173
+ groups,
76174
+ loading: showInitialSpinner,
76175
+ inFlightInitial,
76176
+ inFlightMore,
76177
+ errorInitial,
76178
+ errorMore,
76179
+ hasMore,
76180
+ noData,
76181
+ noResult,
76182
+ serverSearch,
76183
+ handleOpen,
76184
+ handlePopupScroll,
76185
+ handleServerSearch,
76186
+ handleUiSearch,
76187
+ refresh,
76188
+ reload,
76189
+ getOptions,
76190
+ retryInitial: () => void runFetch({ reset: true }),
76191
+ retryMore: () => void runFetch({ reset: false }),
76192
+ };
76193
+ }
76194
+
76195
+ const DivFooterRowSC = styled.div `
76196
+ display: flex;
76197
+ align-items: center;
76198
+ justify-content: center;
76199
+ gap: ${getTheme("sem/dimension/gap/xs")};
76200
+ `;
76201
+ const ButtonRetrySC = styled.button `
76202
+ border: none;
76203
+ background: none;
76204
+ padding: 0;
76205
+ cursor: pointer;
76206
+ ${getTheme("Paragraph/Sm")}
76207
+ color: ${getTheme("com/menu/item/action/label/color-text/default")};
76208
+ text-decoration: underline;
76209
+
76210
+ &:hover {
76211
+ opacity: 0.8;
76212
+ }
76213
+ `;
76214
+
76215
+ // FISSelect là generic forwardRef; wrapper cần ép kiểu lỏng để tránh chọi generic.
76216
+ const AnySelect = FISSelect;
76217
+ function ApiSelectInner(props, ref) {
76218
+ const { mode = "loadmore", fetcher, searchMode = mode === "all" ? "client" : "server", searchDebounce = 300, params, fetchEnabled = true, fetchOnOpen = true, reuseOnReopen = true, autoFill = true, autoFillMinItems = DEFAULT_AUTO_FILL_MIN_ITEMS, pinSelectedOnTop = false, defaultSelectedOptions, fetchByIds, onLoaded, onFetchError, loadingMoreText = "Đang tải thêm...", errorText = "Tải dữ liệu lỗi", retryText = "Thử lại", maxHeight = 400, value, onChange, multi, ...rest } = props;
76219
+ // Dep theo NỘI DUNG value (parent có thể tạo mảng mới mỗi render). Chỉ stringify
76220
+ // khi là mảng (multi); single-select dùng thẳng primitive cho rẻ.
76221
+ const valueKey = Array.isArray(value) ? JSON.stringify(value) : value;
76222
+ const selectedValues = useMemo$1(() => {
76223
+ if (multi)
76224
+ return Array.isArray(value) ? value : [];
76225
+ return value !== undefined && value !== null && value !== ""
76226
+ ? [value]
76227
+ : [];
76228
+ // eslint-disable-next-line react-hooks/exhaustive-deps
76229
+ }, [multi, valueKey]);
76230
+ const api = useApiSelect({
76231
+ mode,
76232
+ // fetcher là union FetchAll | FetchPage; hook gọi theo dạng page rồi tự chuẩn
76233
+ // hoá (mảng -> FetchPageResult). Ép về 1 chữ ký chung để tránh chọi union.
76234
+ fetcher: fetcher,
76235
+ searchMode,
76236
+ params,
76237
+ fetchEnabled,
76238
+ fetchOnOpen,
76239
+ reuseOnReopen,
76240
+ autoFill,
76241
+ autoFillMinItems,
76242
+ pinSelectedOnTop,
76243
+ defaultSelectedOptions,
76244
+ fetchByIds,
76245
+ onLoaded,
76246
+ onFetchError,
76247
+ selectedValues,
76248
+ });
76249
+ const selectRef = useRef(null);
76250
+ useImperativeHandle(ref, () => ({
76251
+ focus: () => selectRef.current?.focus(),
76252
+ openDropdown: () => selectRef.current?.openDropdown(),
76253
+ refresh: api.refresh,
76254
+ reload: api.reload,
76255
+ getOptions: api.getOptions,
76256
+ }), [api.refresh, api.reload, api.getOptions]);
76257
+ // onChange đã là (v: T | T[]) => void nên chuyển thẳng, không cần ép kiểu nhánh.
76258
+ const handleChange = (val) => onChange(val);
76259
+ const footer = useMemo$1(() => {
76260
+ if (api.errorInitial) {
76261
+ return (jsxs(DivFooterRowSC, { role: "alert", children: [jsx("span", { children: errorText }), jsx(ButtonRetrySC, { type: "button", onClick: api.retryInitial, "aria-label": retryText, children: retryText })] }));
76262
+ }
76263
+ if (api.inFlightMore) {
76264
+ return (jsxs(DivFooterRowSC, { "aria-live": "polite", "aria-busy": "true", children: [jsx(FISProgressCircular, { variant: "indeterminate", size: "xs" }), jsx("span", { children: loadingMoreText })] }));
76265
+ }
76266
+ if (api.errorMore) {
76267
+ return (jsxs(DivFooterRowSC, { role: "alert", children: [jsx("span", { children: errorText }), jsx(ButtonRetrySC, { type: "button", onClick: api.retryMore, "aria-label": retryText, children: retryText })] }));
76268
+ }
76269
+ return null;
76270
+ }, [
76271
+ api.errorInitial,
76272
+ api.inFlightMore,
76273
+ api.errorMore,
76274
+ api.retryInitial,
76275
+ api.retryMore,
76276
+ errorText,
76277
+ retryText,
76278
+ loadingMoreText,
76279
+ ]);
76280
+ const mergedProps = {
76281
+ ...rest,
76282
+ maxHeight,
76283
+ multi,
76284
+ value,
76285
+ onChange: handleChange,
76286
+ options: api.groups,
76287
+ loading: api.loading,
76288
+ noData: api.noData,
76289
+ noResult: api.noResult,
76290
+ footer,
76291
+ onOpen: api.handleOpen,
76292
+ onPopupScroll: api.handlePopupScroll,
76293
+ onSearchChange: searchMode === "server" ? api.handleServerSearch : undefined,
76294
+ onSearchInput: api.handleUiSearch,
76295
+ showSearch: searchMode === "server" ? true : undefined,
76296
+ searchDebounce,
76297
+ };
76298
+ return jsx(AnySelect, { ref: selectRef, ...mergedProps });
76299
+ }
76300
+ const FISApiSelect = forwardRef(ApiSelectInner);
76301
+ FISApiSelect.displayName = "FISApiSelect";
76302
+
75766
76303
  const useNotification = () => {
75767
76304
  const context = React__default.useContext(NotificationContext);
75768
76305
  if (!context) {
@@ -76083,5 +76620,5 @@ const TextSC = styled.p `
76083
76620
  const FISText = forwardRef(({ tag, variant, children, color, ...rest }, ref) => (jsx(TextSC, { as: tag, "$variant": variant, "$color": color ? getTheme(color) : "", ref: ref, ...rest, children: children })));
76084
76621
  FISText.displayName = "FISText";
76085
76622
 
76086
- export { FISAlertBanner, FISAvatar, FISBadge, FISBreadcrumb, FISButton, FISButtonGroup, FISCheckbox, FISCheckboxGroup, FISChipButton, FISCollapse, FISCombobox, FISDateRange, FISDivider, FISIconButton, FISInputArea, FISInputDate, FISInputField, FISInputLabel, FISInputStepper, FISInputText, FISInputTime, FISLinkButton, FISMenuItem, FISMenuSection, FISMenuSelect, FISMenuSelectDropdown, FISPagination, FISProgressCircular, FISProgressLinear, FISRadio, RadioGroup as FISRadioGroup, FISSegmented, FISSelect, FISSelectItem, FISSorter, FISSplitButton, FISSwitch, FISTab, FISTable, FISTableCell, FISTableHeaderCell, FISText, FISThemeProvider, FISToast, FISTooltip, SegmentedPanelItem, TabPanelItem, useNotification, useToast };
76623
+ export { FISAlertBanner, FISApiSelect, FISAvatar, FISBadge, FISBreadcrumb, FISButton, FISButtonGroup, FISCheckbox, FISCheckboxGroup, FISChipButton, FISCollapse, FISCombobox, FISDateRange, FISDivider, FISIconButton, FISInputArea, FISInputDate, FISInputField, FISInputLabel, FISInputStepper, FISInputText, FISInputTime, FISLinkButton, FISMenuItem, FISMenuSection, FISMenuSelect, FISMenuSelectDropdown, FISPagination, FISProgressCircular, FISProgressLinear, FISRadio, RadioGroup as FISRadioGroup, FISSegmented, FISSelect, FISSelectItem, FISSorter, FISSplitButton, FISSwitch, FISTab, FISTable, FISTableCell, FISTableHeaderCell, FISText, FISThemeProvider, FISToast, FISTooltip, SegmentedPanelItem, TabPanelItem, useNotification, useToast };
76087
76624
  //# sourceMappingURL=index.js.map