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/cjs/index.js CHANGED
@@ -62365,6 +62365,16 @@ const FixedBottomSection = styled.div `
62365
62365
  border-bottom-left-radius: ${getTheme("com/menu/corner-radius")};
62366
62366
  border-bottom-right-radius: ${getTheme("com/menu/corner-radius")};
62367
62367
  `;
62368
+ const DivFooterSC = styled.div `
62369
+ display: flex;
62370
+ align-items: center;
62371
+ justify-content: center;
62372
+ gap: ${getTheme("com/menu/item/horizontal-gap")};
62373
+ padding: ${getTheme("com/menu/top-padding")} 0;
62374
+ min-height: ${getTheme("com/menu/item/size-md/min-height")};
62375
+ ${getTheme("Paragraph/Sm")}
62376
+ color: ${getTheme("com/menu/item/action/label/color-text/default")};
62377
+ `;
62368
62378
  styled.span `
62369
62379
  ${getTheme("Subheading/XS")}
62370
62380
  color: ${getTheme("com/menu/group-label/color-text")};
@@ -69271,11 +69281,13 @@ const normalizeText = (value) => {
69271
69281
  .trim();
69272
69282
  };
69273
69283
 
69274
- 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, }) => {
69284
+ 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, }) => {
69285
+ // Chiều cao hàng = min-height item + gap xs (4px): md 36+4, lg 44+4.
69286
+ const intrinsicItemHeight = virtualItemHeight ?? (size === "lg" ? 48 : 40);
69275
69287
  const [localSearch, setLocalSearch] = React.useState(searchValue);
69276
69288
  const [debouncedSearchValue, setDebouncedSearchValue] = React.useState(searchValue);
69277
69289
  const searchInputRef = React.useRef(null);
69278
- const debouncedSetSearch = React.useMemo(() => debounce$2((value) => setDebouncedSearchValue(value), 300), []);
69290
+ const debouncedSetSearch = React.useMemo(() => debounce$2((value) => setDebouncedSearchValue(value), searchDebounce), [searchDebounce]);
69279
69291
  React.useEffect(() => {
69280
69292
  debouncedSetSearch(localSearch);
69281
69293
  }, [localSearch, debouncedSetSearch]);
@@ -69286,10 +69298,14 @@ const FISMenuSelect = ({ placeholder, groups, size = "md", multi = false, select
69286
69298
  };
69287
69299
  }, [debouncedSetSearch]);
69288
69300
  React.useEffect(() => {
69289
- if (onSearchChange && debouncedSearchValue !== searchValue) {
69290
- onSearchChange(debouncedSearchValue);
69291
- }
69301
+ if (!onSearchChange || debouncedSearchValue === searchValue)
69302
+ return;
69303
+ onSearchChange(debouncedSearchValue);
69292
69304
  }, [debouncedSearchValue, onSearchChange, searchValue]);
69305
+ // Quan sát text search (phục vụ creatable ở client mode) — không tắt lọc client.
69306
+ React.useEffect(() => {
69307
+ onSearchInput?.(debouncedSearchValue);
69308
+ }, [debouncedSearchValue, onSearchInput]);
69293
69309
  const search = localSearch;
69294
69310
  const filteredGroups = React.useMemo(() => {
69295
69311
  if (onSearchChange) {
@@ -69341,7 +69357,7 @@ const FISMenuSelect = ({ placeholder, groups, size = "md", multi = false, select
69341
69357
  : null;
69342
69358
  const totalItems = groups.reduce((acc, group) => acc + group.items.length, 0);
69343
69359
  const hasSearch = search.trim() !== "";
69344
- const showInput = totalItems >= 7 || hasSearch;
69360
+ const showInput = showSearch ?? (totalItems >= 7 || hasSearch);
69345
69361
  const hasFilteredResult = groupsToRender.length > 0;
69346
69362
  const shouldShowNoResult = hasSearch && !hasFilteredResult;
69347
69363
  const handleSearchChange = (e) => {
@@ -69375,7 +69391,63 @@ const FISMenuSelect = ({ placeholder, groups, size = "md", multi = false, select
69375
69391
  searchInputRef.current.focus();
69376
69392
  }
69377
69393
  }, [focusSearchInput]);
69378
- return (jsxRuntime.jsxs(DivContainerSC$a, { "$maxHeight": maxHeight, className: className, children: [showInput && !combobox && (jsxRuntime.jsx(DivSearchSC, { children: jsxRuntime.jsx(FISInputText, { iconPrefix: jsxRuntime.jsx(SearchIcon, {}), placeholder: placeholder, value: search, onChange: handleSearchChange, ref: searchInputRef }) })), loading && (jsxRuntime.jsxs(DivLoaderSC, { children: [jsxRuntime.jsx(FISProgressCircular, { size: size, variant: "indeterminate" }), jsxRuntime.jsx(PTitleSC$3, { children: loadingText })] })), !loading && noData && (jsxRuntime.jsxs(DivLoaderSC, { children: [jsxRuntime.jsx(DivIconDataSC, { children: jsxRuntime.jsx(NoDataIcon, {}) }), jsxRuntime.jsx(PTitleSC$3, { children: noDataText })] })), !loading && !noData && (shouldShowNoResult || noResult) && (jsxRuntime.jsxs(DivLoaderSC, { children: [jsxRuntime.jsx(DivIconDataSC, { children: jsxRuntime.jsx(NoResultIcon, {}) }), jsxRuntime.jsx(PTitleSC$3, { children: noResultText })] })), !shouldShowNoResult && !noData && !loading && (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx(MenuContent, { "$removeSelectedGroup": !!removeSelectedGroup, onScroll: onPopupScroll, children: groupsToRender.map((group, index) => (jsxRuntime.jsxs(DivWrapperSC$6, { children: [index !== 0 && jsxRuntime.jsx(FISMenuSection, { withDivider: true }), group?.groupLabel && (jsxRuntime.jsx(FISMenuSection, { label: group?.groupLabel })), group.items.map((item, idx) => (jsxRuntime.jsx(FISTooltip, { title: item.label, variant: "primary", children: renderOption ? (jsxRuntime.jsx("div", { onClick: () => handleItemClick(item), children: renderOption(item) })) : (jsxRuntime.jsx(FISMenuItem, { title: item.label, description: item.description, size: size, onClickMenu: () => handleItemClick(item), selected: selectedValues.includes(item.value), type: "select" })) }, idx)))] }, index))) }), removeSelectedGroup && (jsxRuntime.jsx(FixedBottomSection, { children: jsxRuntime.jsx(DivWrapperSC$6, { children: removeSelectedGroup.items.map((item, idx) => (jsxRuntime.jsx(FISTooltip, { title: item.label, variant: "primary", children: jsxRuntime.jsx(FISMenuItem, { title: item.label, description: item.description, size: size, onClickMenu: () => onChangeSelected?.([]), type: "select", iconPrefix: jsxRuntime.jsx(RemoveIcon, {}), negative: true }) }, idx))) }) }))] }))] }));
69394
+ /* ---- Windowing thật (virtualized) — chỉ render item trong viewport ---- */
69395
+ const VIRTUAL_OVERSCAN = 6;
69396
+ const scrollElRef = React.useRef(null);
69397
+ const [virtualScrollTop, setVirtualScrollTop] = React.useState(0);
69398
+ const [virtualViewportH, setVirtualViewportH] = React.useState(0);
69399
+ const measureViewport = React.useCallback(() => {
69400
+ if (scrollElRef.current)
69401
+ setVirtualViewportH(scrollElRef.current.clientHeight);
69402
+ }, []);
69403
+ // callback ref: đo lại mỗi khi MenuContent mount (đóng/mở, đổi no-data...).
69404
+ const setScrollEl = React.useCallback((el) => {
69405
+ scrollElRef.current = el;
69406
+ if (el)
69407
+ setVirtualViewportH(el.clientHeight);
69408
+ }, []);
69409
+ const handleMenuScroll = React.useCallback((e) => {
69410
+ if (virtualized) {
69411
+ setVirtualScrollTop(e.currentTarget.scrollTop);
69412
+ }
69413
+ onPopupScroll?.(e); // vẫn phát loadmore
69414
+ }, [virtualized, onPopupScroll]);
69415
+ React.useEffect(() => {
69416
+ if (!virtualized)
69417
+ return;
69418
+ window.addEventListener("resize", measureViewport);
69419
+ return () => window.removeEventListener("resize", measureViewport);
69420
+ }, [virtualized, measureViewport]);
69421
+ const flatRows = React.useMemo(() => {
69422
+ if (!virtualized)
69423
+ return [];
69424
+ const rows = [];
69425
+ groupsToRender.forEach((group, gi) => {
69426
+ if (group.groupLabel) {
69427
+ rows.push({ type: "label", label: group.groupLabel, key: `l-${gi}` });
69428
+ }
69429
+ group.items.forEach((item, ii) => {
69430
+ rows.push({ type: "item", item, key: `i-${gi}-${item.value}-${ii}` });
69431
+ });
69432
+ });
69433
+ return rows;
69434
+ }, [virtualized, groupsToRender]);
69435
+ const rowHeight = intrinsicItemHeight;
69436
+ const totalVirtualHeight = flatRows.length * rowHeight;
69437
+ const startIndex = Math.max(0, Math.floor(virtualScrollTop / rowHeight) - VIRTUAL_OVERSCAN);
69438
+ const endIndex = Math.min(flatRows.length, Math.ceil((virtualScrollTop + virtualViewportH) / rowHeight) +
69439
+ VIRTUAL_OVERSCAN);
69440
+ const visibleRows = flatRows.slice(startIndex, endIndex);
69441
+ const renderItemNode = (item) => (jsxRuntime.jsx(FISTooltip, { title: item.label, variant: "primary", children: renderOption ? (jsxRuntime.jsx("div", { onClick: () => handleItemClick(item), children: renderOption(item) })) : (jsxRuntime.jsx(FISMenuItem, { title: item.label, description: item.description, size: size, onClickMenu: () => handleItemClick(item), selected: selectedValues.includes(item.value), type: "select" })) }));
69442
+ return (jsxRuntime.jsxs(DivContainerSC$a, { "$maxHeight": maxHeight, className: className, children: [showInput && !combobox && (jsxRuntime.jsx(DivSearchSC, { children: jsxRuntime.jsx(FISInputText, { iconPrefix: jsxRuntime.jsx(SearchIcon, {}), placeholder: placeholder, value: search, onChange: handleSearchChange, ref: searchInputRef }) })), loading && (jsxRuntime.jsxs(DivLoaderSC, { children: [jsxRuntime.jsx(FISProgressCircular, { size: size, variant: "indeterminate" }), jsxRuntime.jsx(PTitleSC$3, { children: loadingText })] })), !loading && noData && (jsxRuntime.jsxs(DivLoaderSC, { children: [jsxRuntime.jsx(DivIconDataSC, { children: jsxRuntime.jsx(NoDataIcon, {}) }), jsxRuntime.jsx(PTitleSC$3, { children: noDataText })] })), !loading && !noData && (shouldShowNoResult || noResult) && (jsxRuntime.jsxs(DivLoaderSC, { children: [jsxRuntime.jsx(DivIconDataSC, { children: jsxRuntime.jsx(NoResultIcon, {}) }), jsxRuntime.jsx(PTitleSC$3, { children: noResultText })] })), !shouldShowNoResult && !noData && !loading && (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [virtualized ? (jsxRuntime.jsxs(MenuContent, { ref: setScrollEl, "$removeSelectedGroup": !!removeSelectedGroup, onScroll: handleMenuScroll, children: [jsxRuntime.jsx("div", { style: { height: totalVirtualHeight, position: "relative" }, children: visibleRows.map((row, i) => {
69443
+ const index = startIndex + i;
69444
+ return (jsxRuntime.jsx("div", { style: {
69445
+ position: "absolute",
69446
+ top: index * rowHeight,
69447
+ left: 0,
69448
+ right: 0,
69449
+ }, children: row.type === "label" ? (jsxRuntime.jsx(FISMenuSection, { label: row.label })) : (renderItemNode(row.item)) }, row.key));
69450
+ }) }), footer && jsxRuntime.jsx(DivFooterSC, { children: footer })] })) : (jsxRuntime.jsxs(MenuContent, { "$removeSelectedGroup": !!removeSelectedGroup, onScroll: onPopupScroll, children: [groupsToRender.map((group, index) => (jsxRuntime.jsxs(DivWrapperSC$6, { children: [index !== 0 && jsxRuntime.jsx(FISMenuSection, { withDivider: true }), group?.groupLabel && (jsxRuntime.jsx(FISMenuSection, { label: group?.groupLabel })), group.items.map((item, idx) => (jsxRuntime.jsx(FISTooltip, { title: item.label, variant: "primary", children: renderOption ? (jsxRuntime.jsx("div", { onClick: () => handleItemClick(item), children: renderOption(item) })) : (jsxRuntime.jsx(FISMenuItem, { title: item.label, description: item.description, size: size, onClickMenu: () => handleItemClick(item), selected: selectedValues.includes(item.value), type: "select" })) }, idx)))] }, index))), footer && jsxRuntime.jsx(DivFooterSC, { children: footer })] })), removeSelectedGroup && (jsxRuntime.jsx(FixedBottomSection, { children: jsxRuntime.jsx(DivWrapperSC$6, { children: removeSelectedGroup.items.map((item, idx) => (jsxRuntime.jsx(FISTooltip, { title: item.label, variant: "primary", children: jsxRuntime.jsx(FISMenuItem, { title: item.label, description: item.description, size: size, onClickMenu: () => onChangeSelected?.([]), type: "select", iconPrefix: jsxRuntime.jsx(RemoveIcon, {}), negative: true }) }, idx))) }) }))] }))] }));
69379
69451
  };
69380
69452
  FISMenuSelect.displayName = "FISMenuSelect";
69381
69453
 
@@ -75581,7 +75653,7 @@ function isMenuSize(value) {
75581
75653
  return value === "sm" || value === "md";
75582
75654
  }
75583
75655
 
75584
- const FISSelect = React.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) => {
75656
+ const FISSelect = React.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) => {
75585
75657
  const [isOpen, setIsOpen] = React.useState(false);
75586
75658
  const [referenceElement, setReferenceElement] = React.useState(null);
75587
75659
  const [popperElement, setPopperElement] = React.useState(null);
@@ -75725,6 +75797,14 @@ const FISSelect = React.forwardRef(({ className, style, size = "md", options, va
75725
75797
  maxHeight,
75726
75798
  onPopupScroll,
75727
75799
  renderOption,
75800
+ noData,
75801
+ noResult,
75802
+ footer,
75803
+ searchDebounce,
75804
+ showSearch,
75805
+ onSearchInput,
75806
+ virtualized,
75807
+ virtualItemHeight,
75728
75808
  ...restProps,
75729
75809
  }), [
75730
75810
  options,
@@ -75740,6 +75820,14 @@ const FISSelect = React.forwardRef(({ className, style, size = "md", options, va
75740
75820
  maxHeight,
75741
75821
  onPopupScroll,
75742
75822
  renderOption,
75823
+ noData,
75824
+ noResult,
75825
+ footer,
75826
+ searchDebounce,
75827
+ showSearch,
75828
+ onSearchInput,
75829
+ virtualized,
75830
+ virtualItemHeight,
75743
75831
  restProps,
75744
75832
  ]);
75745
75833
  React.useEffect(() => {
@@ -75783,6 +75871,455 @@ const FISSelect = React.forwardRef(({ className, style, size = "md", options, va
75783
75871
  });
75784
75872
  FISSelect.displayName = "FISSelect";
75785
75873
 
75874
+ const SPINNER_DELAY = 150;
75875
+ const SCROLL_THRESHOLD = 32;
75876
+ /** Chống double-fetch do onOpen fire cả khi đóng (chỉ dùng khi reuseOnReopen=false). */
75877
+ const OPEN_DEDUPE_MS = 400;
75878
+ /**
75879
+ * Ngưỡng auto-fill mặc định: số item tối thiểu để dropdown chắc chắn có thanh cuộn.
75880
+ * Đây là ước lượng CỐ ĐỊNH (không đo DOM). Hợp với dropdown thấp (~maxHeight 320-420,
75881
+ * item size md). Nếu maxHeight lớn / item cao, truyền `autoFillMinItems` lớn hơn.
75882
+ * Xem công thức chọn số trong JSDoc của prop `autoFillMinItems` (types.ts).
75883
+ */
75884
+ const DEFAULT_AUTO_FILL_MIN_ITEMS = 12;
75885
+ /** Key nhận diện một truy vấn: mode + search (server) + params. */
75886
+ function buildKey(mode, search, params) {
75887
+ return JSON.stringify({ mode, search, params: params ?? null });
75888
+ }
75889
+ function dedupeByValue(list) {
75890
+ const seen = new Set();
75891
+ const out = [];
75892
+ for (const item of list) {
75893
+ if (!seen.has(item.value)) {
75894
+ seen.add(item.value);
75895
+ out.push(item);
75896
+ }
75897
+ }
75898
+ return out;
75899
+ }
75900
+ function useApiSelect(opts) {
75901
+ const [items, setItems] = React.useState([]);
75902
+ const [hasMore, setHasMore] = React.useState(false);
75903
+ const [inFlightInitial, setInFlightInitial] = React.useState(false);
75904
+ const [inFlightMore, setInFlightMore] = React.useState(false);
75905
+ const [showInitialSpinner, setShowInitialSpinner] = React.useState(false);
75906
+ const [errorInitial, setErrorInitial] = React.useState(null);
75907
+ const [errorMore, setErrorMore] = React.useState(null);
75908
+ const [serverSearch, setServerSearch] = React.useState("");
75909
+ const [uiSearch, setUiSearch] = React.useState("");
75910
+ const [resolvedSelected, setResolvedSelected] = React.useState(() => {
75911
+ const map = new Map();
75912
+ (opts.defaultSelectedOptions ?? []).forEach((o) => map.set(o.value, o));
75913
+ return map;
75914
+ });
75915
+ const [active, setActive] = React.useState(!opts.fetchOnOpen);
75916
+ /** Đã settle (fetch xong, dù rỗng) cho query hiện tại -> quyết định noData/noResult. */
75917
+ const [settled, setSettled] = React.useState(false);
75918
+ // Giữ props/flags mới nhất cho các callback ổn định.
75919
+ const configRef = React.useRef(opts);
75920
+ configRef.current = opts;
75921
+ const paramsKey = JSON.stringify(opts.params ?? null);
75922
+ const key = React.useMemo(() => buildKey(opts.mode, opts.searchMode === "server" ? serverSearch : "", opts.params), [opts.mode, opts.searchMode, serverSearch, paramsKey]);
75923
+ const abortRef = React.useRef(null);
75924
+ const fetchSeqRef = React.useRef(0);
75925
+ const nextPageParamRef = React.useRef(undefined);
75926
+ const itemsRef = React.useRef(items);
75927
+ itemsRef.current = items;
75928
+ const activeRef = React.useRef(active);
75929
+ activeRef.current = active;
75930
+ const serverSearchRef = React.useRef(serverSearch);
75931
+ serverSearchRef.current = serverSearch;
75932
+ /** Key của truy vấn mà `items` hiện đang phản ánh (null = chưa tải). */
75933
+ const loadedKeyRef = React.useRef(null);
75934
+ /** Mốc thời gian lần ép tải khi mở gần nhất (chống close-fire khi reuseOnReopen=false). */
75935
+ const lastForceOpenRef = React.useRef(0);
75936
+ const requestedIdsRef = React.useRef(new Set());
75937
+ // Flags đọc-mới-nhất cho scroll handler (cập nhật ngay trong render).
75938
+ const flagsRef = React.useRef({
75939
+ hasMore,
75940
+ inFlightMore,
75941
+ inFlightInitial,
75942
+ errorMore,
75943
+ mode: opts.mode,
75944
+ });
75945
+ flagsRef.current = {
75946
+ hasMore,
75947
+ inFlightMore,
75948
+ inFlightInitial,
75949
+ errorMore,
75950
+ mode: opts.mode,
75951
+ };
75952
+ // Spinner trễ để tránh nháy khi API phản hồi nhanh.
75953
+ React.useEffect(() => {
75954
+ if (!inFlightInitial) {
75955
+ setShowInitialSpinner(false);
75956
+ return;
75957
+ }
75958
+ const t = setTimeout(() => setShowInitialSpinner(true), SPINNER_DELAY);
75959
+ return () => clearTimeout(t);
75960
+ }, [inFlightInitial]);
75961
+ const runFetch = React.useCallback(async (params) => {
75962
+ const cfg = configRef.current;
75963
+ if (!cfg.fetchEnabled)
75964
+ return;
75965
+ const { reset } = params;
75966
+ abortRef.current?.abort();
75967
+ const controller = new AbortController();
75968
+ abortRef.current = controller;
75969
+ const seq = ++fetchSeqRef.current;
75970
+ const search = cfg.searchMode === "server" ? serverSearchRef.current : "";
75971
+ const currentKey = buildKey(cfg.mode, search, cfg.params);
75972
+ const pageParam = reset ? undefined : nextPageParamRef.current;
75973
+ if (reset) {
75974
+ setInFlightInitial(true);
75975
+ setErrorInitial(null);
75976
+ setErrorMore(null); // reset từ trang 1 -> lỗi loadmore cũ không còn ngữ cảnh
75977
+ setItems([]);
75978
+ setHasMore(false);
75979
+ setSettled(false);
75980
+ nextPageParamRef.current = undefined;
75981
+ // Invalidate ngay: items vừa bị xoá nên loadedKey cũ không còn đúng
75982
+ // (tránh A->B->A nhanh bị skip fetch khi B chưa xong).
75983
+ loadedKeyRef.current = null;
75984
+ }
75985
+ else {
75986
+ setInFlightMore(true);
75987
+ setErrorMore(null);
75988
+ }
75989
+ try {
75990
+ const raw = await cfg.fetcher({
75991
+ search,
75992
+ params: cfg.params,
75993
+ pageParam,
75994
+ signal: controller.signal,
75995
+ });
75996
+ if (seq !== fetchSeqRef.current || controller.signal.aborted)
75997
+ return;
75998
+ const normalized = Array.isArray(raw)
75999
+ ? {
76000
+ options: raw,
76001
+ hasMore: false,
76002
+ nextPageParam: undefined,
76003
+ }
76004
+ : raw;
76005
+ const merged = reset
76006
+ ? dedupeByValue(normalized.options)
76007
+ : dedupeByValue([...itemsRef.current, ...normalized.options]);
76008
+ setItems(merged);
76009
+ setHasMore(cfg.mode === "loadmore" ? normalized.hasMore : false);
76010
+ nextPageParamRef.current = normalized.nextPageParam;
76011
+ setSettled(true);
76012
+ loadedKeyRef.current = currentKey; // đánh dấu đã tải cho query này
76013
+ cfg.onLoaded?.(merged, reset ? "initial" : "more");
76014
+ // Auto-fill: trang đầu quá ngắn (không tràn dropdown) -> không có scroll để
76015
+ // loadmore. Nếu vẫn còn trang và list chưa đủ dài thì tự tải tiếp trang kế.
76016
+ // Guard `normalized.options.length > 0` tránh loop vô hạn khi API trả rỗng
76017
+ // nhưng vẫn báo hasMore.
76018
+ if (cfg.mode === "loadmore" &&
76019
+ cfg.autoFill &&
76020
+ activeRef.current &&
76021
+ normalized.hasMore &&
76022
+ normalized.options.length > 0 &&
76023
+ merged.length < cfg.autoFillMinItems) {
76024
+ void runFetch({ reset: false });
76025
+ }
76026
+ }
76027
+ catch (err) {
76028
+ if (err?.name === "AbortError" ||
76029
+ seq !== fetchSeqRef.current) {
76030
+ return;
76031
+ }
76032
+ if (reset) {
76033
+ setErrorInitial(err);
76034
+ setSettled(true);
76035
+ loadedKeyRef.current = null; // lỗi -> cho phép thử lại
76036
+ }
76037
+ else {
76038
+ setErrorMore(err);
76039
+ }
76040
+ cfg.onFetchError?.(err, reset ? "initial" : "more");
76041
+ }
76042
+ finally {
76043
+ if (seq === fetchSeqRef.current) {
76044
+ if (reset)
76045
+ setInFlightInitial(false);
76046
+ else
76047
+ setInFlightMore(false);
76048
+ }
76049
+ }
76050
+ }, []);
76051
+ // Tải khi: mở lần đầu (active bật) hoặc đổi search/params (key đổi).
76052
+ // Mở lại cùng một query (key không đổi) -> effect không chạy -> không refetch.
76053
+ React.useEffect(() => {
76054
+ if (!active || !opts.fetchEnabled)
76055
+ return;
76056
+ if (loadedKeyRef.current === key)
76057
+ return; // đã có data cho query này
76058
+ void runFetch({ reset: true });
76059
+ // eslint-disable-next-line react-hooks/exhaustive-deps
76060
+ }, [active, key, opts.fetchEnabled]);
76061
+ // Huỷ request khi unmount.
76062
+ React.useEffect(() => {
76063
+ return () => abortRef.current?.abort();
76064
+ }, []);
76065
+ // Resolve label cho value đã chọn nhưng chưa có trong list.
76066
+ React.useEffect(() => {
76067
+ const cfg = configRef.current;
76068
+ if (!cfg.fetchByIds || opts.selectedValues.length === 0)
76069
+ return;
76070
+ const present = new Set(itemsRef.current.map((i) => i.value));
76071
+ const missing = opts.selectedValues.filter((v) => !present.has(v) &&
76072
+ !resolvedSelected.has(v) &&
76073
+ !requestedIdsRef.current.has(v));
76074
+ if (missing.length === 0)
76075
+ return;
76076
+ missing.forEach((v) => requestedIdsRef.current.add(v));
76077
+ let cancelled = false;
76078
+ void cfg
76079
+ .fetchByIds(missing)
76080
+ .then((fetched) => {
76081
+ if (cancelled)
76082
+ return;
76083
+ setResolvedSelected((prev) => {
76084
+ const next = new Map(prev);
76085
+ fetched.forEach((o) => next.set(o.value, o));
76086
+ return next;
76087
+ });
76088
+ })
76089
+ .catch(() => {
76090
+ // Bỏ qua lỗi resolve label; value vẫn hiển thị dạng thô.
76091
+ });
76092
+ return () => {
76093
+ cancelled = true;
76094
+ };
76095
+ // eslint-disable-next-line react-hooks/exhaustive-deps
76096
+ }, [opts.selectedValues, items, resolvedSelected]);
76097
+ // Seed lại khi defaultSelectedOptions đổi.
76098
+ React.useEffect(() => {
76099
+ if (!opts.defaultSelectedOptions?.length)
76100
+ return;
76101
+ setResolvedSelected((prev) => {
76102
+ const next = new Map(prev);
76103
+ opts.defaultSelectedOptions.forEach((o) => next.set(o.value, o));
76104
+ return next;
76105
+ });
76106
+ }, [opts.defaultSelectedOptions]);
76107
+ const handleOpen = React.useCallback(() => {
76108
+ if (!activeRef.current) {
76109
+ setActive(true); // effect sẽ tải lần đầu
76110
+ return;
76111
+ }
76112
+ // Đã active (mở lại / đóng). Xoá lỗi loadmore cũ để mở lại là danh sách sạch,
76113
+ // cuộn có thể thử tải thêm lại. (reuseOnReopen=true không reset nên phải clear
76114
+ // ở đây; reuseOnReopen=false thì reset của runFetch bên dưới cũng clear.)
76115
+ setErrorMore(null);
76116
+ // reuseOnReopen=true -> dùng lại data; false -> tải lại.
76117
+ if (!configRef.current.reuseOnReopen) {
76118
+ const now = Date.now();
76119
+ if (now - lastForceOpenRef.current < OPEN_DEDUPE_MS)
76120
+ return;
76121
+ lastForceOpenRef.current = now;
76122
+ void runFetch({ reset: true });
76123
+ }
76124
+ }, [runFetch]);
76125
+ const handlePopupScroll = React.useCallback((e) => {
76126
+ const f = flagsRef.current;
76127
+ if (f.mode !== "loadmore")
76128
+ return;
76129
+ if (!f.hasMore || f.inFlightMore || f.inFlightInitial || f.errorMore) {
76130
+ return;
76131
+ }
76132
+ const el = e.currentTarget;
76133
+ if (el.scrollTop + el.clientHeight >=
76134
+ el.scrollHeight - SCROLL_THRESHOLD) {
76135
+ void runFetch({ reset: false });
76136
+ }
76137
+ }, [runFetch]);
76138
+ const handleServerSearch = React.useCallback((value) => {
76139
+ setServerSearch(value);
76140
+ }, []);
76141
+ const handleUiSearch = React.useCallback((value) => {
76142
+ setUiSearch(value);
76143
+ }, []);
76144
+ const refresh = React.useCallback(() => {
76145
+ // Clear như reload() để nhất quán: cho phép thử lại fetchByIds với id từng
76146
+ // request nhưng resolve label thất bại (id đã resolve vẫn được guard bởi
76147
+ // resolvedSelected nên không gọi lại thừa).
76148
+ requestedIdsRef.current.clear();
76149
+ loadedKeyRef.current = null; // buộc tải lại query hiện tại
76150
+ void runFetch({ reset: true });
76151
+ }, [runFetch]);
76152
+ const reload = React.useCallback(() => {
76153
+ requestedIdsRef.current.clear();
76154
+ loadedKeyRef.current = null;
76155
+ if (serverSearchRef.current === "") {
76156
+ void runFetch({ reset: true }); // key không đổi -> tự tải lại
76157
+ }
76158
+ else {
76159
+ setServerSearch(""); // key đổi -> effect sẽ tải lại
76160
+ }
76161
+ }, [runFetch]);
76162
+ const getOptions = React.useCallback(() => itemsRef.current, []);
76163
+ // Ghép options cuối cùng: [selected chưa có trong list] có thể ghim đầu/cuối.
76164
+ const groups = React.useMemo(() => {
76165
+ const result = [];
76166
+ const present = new Set(items.map((i) => i.value));
76167
+ const extraSelected = opts.selectedValues
76168
+ .filter((v) => !present.has(v) && resolvedSelected.has(v))
76169
+ .map((v) => resolvedSelected.get(v));
76170
+ const extraGroup = extraSelected.length ? { items: extraSelected } : null;
76171
+ if (extraGroup && opts.pinSelectedOnTop)
76172
+ result.push(extraGroup);
76173
+ if (items.length)
76174
+ result.push({ items });
76175
+ if (extraGroup && !opts.pinSelectedOnTop)
76176
+ result.push(extraGroup);
76177
+ return result;
76178
+ }, [items, resolvedSelected, opts.selectedValues, opts.pinSelectedOnTop]);
76179
+ const searchActive = (opts.searchMode === "server" ? serverSearch : uiSearch).trim() !== "";
76180
+ const noData = settled &&
76181
+ !inFlightInitial &&
76182
+ !errorInitial &&
76183
+ items.length === 0 &&
76184
+ !searchActive;
76185
+ // Client mode: để MenuSelect tự quyết noResult khi lọc rỗng.
76186
+ const noResult = opts.searchMode === "server" &&
76187
+ settled &&
76188
+ !inFlightInitial &&
76189
+ !errorInitial &&
76190
+ items.length === 0 &&
76191
+ searchActive;
76192
+ return {
76193
+ groups,
76194
+ loading: showInitialSpinner,
76195
+ inFlightInitial,
76196
+ inFlightMore,
76197
+ errorInitial,
76198
+ errorMore,
76199
+ hasMore,
76200
+ noData,
76201
+ noResult,
76202
+ serverSearch,
76203
+ handleOpen,
76204
+ handlePopupScroll,
76205
+ handleServerSearch,
76206
+ handleUiSearch,
76207
+ refresh,
76208
+ reload,
76209
+ getOptions,
76210
+ retryInitial: () => void runFetch({ reset: true }),
76211
+ retryMore: () => void runFetch({ reset: false }),
76212
+ };
76213
+ }
76214
+
76215
+ const DivFooterRowSC = styled.div `
76216
+ display: flex;
76217
+ align-items: center;
76218
+ justify-content: center;
76219
+ gap: ${getTheme("sem/dimension/gap/xs")};
76220
+ `;
76221
+ const ButtonRetrySC = styled.button `
76222
+ border: none;
76223
+ background: none;
76224
+ padding: 0;
76225
+ cursor: pointer;
76226
+ ${getTheme("Paragraph/Sm")}
76227
+ color: ${getTheme("com/menu/item/action/label/color-text/default")};
76228
+ text-decoration: underline;
76229
+
76230
+ &:hover {
76231
+ opacity: 0.8;
76232
+ }
76233
+ `;
76234
+
76235
+ // FISSelect là generic forwardRef; wrapper cần ép kiểu lỏng để tránh chọi generic.
76236
+ const AnySelect = FISSelect;
76237
+ function ApiSelectInner(props, ref) {
76238
+ 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;
76239
+ // Dep theo NỘI DUNG value (parent có thể tạo mảng mới mỗi render). Chỉ stringify
76240
+ // khi là mảng (multi); single-select dùng thẳng primitive cho rẻ.
76241
+ const valueKey = Array.isArray(value) ? JSON.stringify(value) : value;
76242
+ const selectedValues = React.useMemo(() => {
76243
+ if (multi)
76244
+ return Array.isArray(value) ? value : [];
76245
+ return value !== undefined && value !== null && value !== ""
76246
+ ? [value]
76247
+ : [];
76248
+ // eslint-disable-next-line react-hooks/exhaustive-deps
76249
+ }, [multi, valueKey]);
76250
+ const api = useApiSelect({
76251
+ mode,
76252
+ // fetcher là union FetchAll | FetchPage; hook gọi theo dạng page rồi tự chuẩn
76253
+ // hoá (mảng -> FetchPageResult). Ép về 1 chữ ký chung để tránh chọi union.
76254
+ fetcher: fetcher,
76255
+ searchMode,
76256
+ params,
76257
+ fetchEnabled,
76258
+ fetchOnOpen,
76259
+ reuseOnReopen,
76260
+ autoFill,
76261
+ autoFillMinItems,
76262
+ pinSelectedOnTop,
76263
+ defaultSelectedOptions,
76264
+ fetchByIds,
76265
+ onLoaded,
76266
+ onFetchError,
76267
+ selectedValues,
76268
+ });
76269
+ const selectRef = React.useRef(null);
76270
+ React.useImperativeHandle(ref, () => ({
76271
+ focus: () => selectRef.current?.focus(),
76272
+ openDropdown: () => selectRef.current?.openDropdown(),
76273
+ refresh: api.refresh,
76274
+ reload: api.reload,
76275
+ getOptions: api.getOptions,
76276
+ }), [api.refresh, api.reload, api.getOptions]);
76277
+ // onChange đã là (v: T | T[]) => void nên chuyển thẳng, không cần ép kiểu nhánh.
76278
+ const handleChange = (val) => onChange(val);
76279
+ const footer = React.useMemo(() => {
76280
+ if (api.errorInitial) {
76281
+ return (jsxRuntime.jsxs(DivFooterRowSC, { role: "alert", children: [jsxRuntime.jsx("span", { children: errorText }), jsxRuntime.jsx(ButtonRetrySC, { type: "button", onClick: api.retryInitial, "aria-label": retryText, children: retryText })] }));
76282
+ }
76283
+ if (api.inFlightMore) {
76284
+ return (jsxRuntime.jsxs(DivFooterRowSC, { "aria-live": "polite", "aria-busy": "true", children: [jsxRuntime.jsx(FISProgressCircular, { variant: "indeterminate", size: "xs" }), jsxRuntime.jsx("span", { children: loadingMoreText })] }));
76285
+ }
76286
+ if (api.errorMore) {
76287
+ return (jsxRuntime.jsxs(DivFooterRowSC, { role: "alert", children: [jsxRuntime.jsx("span", { children: errorText }), jsxRuntime.jsx(ButtonRetrySC, { type: "button", onClick: api.retryMore, "aria-label": retryText, children: retryText })] }));
76288
+ }
76289
+ return null;
76290
+ }, [
76291
+ api.errorInitial,
76292
+ api.inFlightMore,
76293
+ api.errorMore,
76294
+ api.retryInitial,
76295
+ api.retryMore,
76296
+ errorText,
76297
+ retryText,
76298
+ loadingMoreText,
76299
+ ]);
76300
+ const mergedProps = {
76301
+ ...rest,
76302
+ maxHeight,
76303
+ multi,
76304
+ value,
76305
+ onChange: handleChange,
76306
+ options: api.groups,
76307
+ loading: api.loading,
76308
+ noData: api.noData,
76309
+ noResult: api.noResult,
76310
+ footer,
76311
+ onOpen: api.handleOpen,
76312
+ onPopupScroll: api.handlePopupScroll,
76313
+ onSearchChange: searchMode === "server" ? api.handleServerSearch : undefined,
76314
+ onSearchInput: api.handleUiSearch,
76315
+ showSearch: searchMode === "server" ? true : undefined,
76316
+ searchDebounce,
76317
+ };
76318
+ return jsxRuntime.jsx(AnySelect, { ref: selectRef, ...mergedProps });
76319
+ }
76320
+ const FISApiSelect = React.forwardRef(ApiSelectInner);
76321
+ FISApiSelect.displayName = "FISApiSelect";
76322
+
75786
76323
  const useNotification = () => {
75787
76324
  const context = React.useContext(NotificationContext);
75788
76325
  if (!context) {
@@ -76104,6 +76641,7 @@ const FISText = React.forwardRef(({ tag, variant, children, color, ...rest }, re
76104
76641
  FISText.displayName = "FISText";
76105
76642
 
76106
76643
  exports.FISAlertBanner = FISAlertBanner;
76644
+ exports.FISApiSelect = FISApiSelect;
76107
76645
  exports.FISAvatar = FISAvatar;
76108
76646
  exports.FISBadge = FISBadge;
76109
76647
  exports.FISBreadcrumb = FISBreadcrumb;