@cloudwick/astral-ui-cli 2.1.0 → 2.3.0
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/README.md +16 -4
- package/dist/index.js +672 -773
- package/dist/index.js.map +1 -1
- package/dist/templates/constants/keyboardKey.ts +1 -0
- package/dist/templates/hooks/index.ts +17 -2
- package/dist/templates/hooks/useAsyncOptions.ts +346 -0
- package/dist/templates/hooks/useAsyncOptionsReducer.ts +182 -0
- package/dist/templates/hooks/useAvailableProjection.ts +77 -0
- package/dist/templates/hooks/useFilterQuery.ts +145 -0
- package/dist/templates/hooks/useIgnoredPropWarning.ts +17 -0
- package/dist/templates/hooks/useInfiniteScroll.ts +20 -9
- package/dist/templates/hooks/useOnValueChange.ts +17 -0
- package/dist/templates/hooks/usePrefetchBaseline.ts +38 -0
- package/dist/templates/schema/components-config.schema.json +3 -0
- package/dist/templates/utils/devWarn.ts +9 -0
- package/dist/templates/utils/index.ts +4 -0
- package/dist/templates/utils/mergeUnique.ts +24 -0
- package/dist/templates/utils/resolveLoadErrors.ts +40 -0
- package/dist/templates/utils/resolveReloadControls.ts +31 -0
- package/package.json +1 -1
- package/dist/templates/utils/matchesQuery.test.tsx +0 -32
package/dist/index.js
CHANGED
|
@@ -150,6 +150,67 @@ var init_project_info = __esm({
|
|
|
150
150
|
}
|
|
151
151
|
});
|
|
152
152
|
|
|
153
|
+
// src/utils/components-config.ts
|
|
154
|
+
var components_config_exports = {};
|
|
155
|
+
__export(components_config_exports, {
|
|
156
|
+
generateComponentsConfig: () => generateComponentsConfig,
|
|
157
|
+
getDefaultConfig: () => getDefaultConfig
|
|
158
|
+
});
|
|
159
|
+
function normalizePath(path12) {
|
|
160
|
+
return path12.replace(/^\/+|\/+$/g, "");
|
|
161
|
+
}
|
|
162
|
+
function getDefaultConfig(projectInfo) {
|
|
163
|
+
const componentPath = projectInfo.isNextJs ? "components/ui" : "src/components/ui";
|
|
164
|
+
const utilsPath = projectInfo.isNextJs ? "lib/utils" : projectInfo.isVite ? "src/utils" : "src/utils";
|
|
165
|
+
const cleanUtilsPath = utilsPath.replace(/\.(ts|js)$/, "");
|
|
166
|
+
const constantsPath = projectInfo.isNextJs ? "lib/constants" : "src/constants";
|
|
167
|
+
const hooksPath = projectInfo.isNextJs ? "lib/hooks" : "src/hooks";
|
|
168
|
+
let tailwindConfig = "tailwind.config.js";
|
|
169
|
+
if (projectInfo.typescript) {
|
|
170
|
+
tailwindConfig = "tailwind.config.ts";
|
|
171
|
+
}
|
|
172
|
+
const cssPath = projectInfo.isNextJs ? "app/globals.css" : "src/assets/css/index.css";
|
|
173
|
+
return {
|
|
174
|
+
tailwindConfig,
|
|
175
|
+
cssPath,
|
|
176
|
+
componentsPath: componentPath,
|
|
177
|
+
utilsPath: cleanUtilsPath,
|
|
178
|
+
constantsPath,
|
|
179
|
+
hooksPath
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
function generateComponentsConfig({
|
|
183
|
+
projectInfo,
|
|
184
|
+
userInputs
|
|
185
|
+
}) {
|
|
186
|
+
const defaults = getDefaultConfig(projectInfo);
|
|
187
|
+
const tailwindConfig = normalizePath(userInputs?.tailwindConfig ?? defaults.tailwindConfig);
|
|
188
|
+
const cssPath = normalizePath(userInputs?.cssPath ?? defaults.cssPath);
|
|
189
|
+
const componentsPath = normalizePath(userInputs?.componentsPath ?? defaults.componentsPath);
|
|
190
|
+
const utilsPath = normalizePath(userInputs?.utilsPath ?? defaults.utilsPath);
|
|
191
|
+
const constantsPath = normalizePath(userInputs?.constantsPath ?? defaults.constantsPath);
|
|
192
|
+
const hooksPath = normalizePath(userInputs?.hooksPath ?? defaults.hooksPath);
|
|
193
|
+
return {
|
|
194
|
+
$schema: "./schema/components-config.schema.json",
|
|
195
|
+
tailwind: {
|
|
196
|
+
config: tailwindConfig,
|
|
197
|
+
css: cssPath
|
|
198
|
+
},
|
|
199
|
+
aliases: {
|
|
200
|
+
components: componentsPath,
|
|
201
|
+
utils: utilsPath,
|
|
202
|
+
constants: constantsPath,
|
|
203
|
+
hooks: hooksPath
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
var init_components_config = __esm({
|
|
208
|
+
"src/utils/components-config.ts"() {
|
|
209
|
+
"use strict";
|
|
210
|
+
init_cjs_shims();
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
|
|
153
214
|
// src/index.ts
|
|
154
215
|
init_cjs_shims();
|
|
155
216
|
var import_commander4 = require("commander");
|
|
@@ -536,11 +597,13 @@ async function copyTemplateFiles({
|
|
|
536
597
|
console.info(import_chalk2.default.gray(` Directory: ${cwd}`));
|
|
537
598
|
const { getProjectInfo: getProjectInfo2 } = await Promise.resolve().then(() => (init_project_info(), project_info_exports));
|
|
538
599
|
const projectInfo = await getProjectInfo2(cwd);
|
|
539
|
-
|
|
600
|
+
const { getDefaultConfig: getDefaultConfig2 } = await Promise.resolve().then(() => (init_components_config(), components_config_exports));
|
|
601
|
+
const defaults = getDefaultConfig2(projectInfo);
|
|
602
|
+
let utilsPath = defaults.utilsPath;
|
|
540
603
|
let cssPath = "src/assets/css/index.css";
|
|
541
604
|
let componentsPath = "src/components/ui";
|
|
542
|
-
let constantsPath =
|
|
543
|
-
let hooksPath =
|
|
605
|
+
let constantsPath = defaults.constantsPath;
|
|
606
|
+
let hooksPath = defaults.hooksPath;
|
|
544
607
|
let tailwindConfigFilename;
|
|
545
608
|
try {
|
|
546
609
|
const configPath = import_path4.default.join(cwd, "components.json");
|
|
@@ -720,58 +783,15 @@ async function copyTemplateFiles({
|
|
|
720
783
|
}
|
|
721
784
|
}
|
|
722
785
|
|
|
723
|
-
// src/
|
|
724
|
-
|
|
725
|
-
function normalizePath(path12) {
|
|
726
|
-
return path12.replace(/^\/+|\/+$/g, "");
|
|
727
|
-
}
|
|
728
|
-
function getDefaultConfig(projectInfo) {
|
|
729
|
-
const componentPath = projectInfo.isNextJs ? "components/ui" : "src/components/ui";
|
|
730
|
-
const utilsPath = projectInfo.isNextJs ? "lib/utils" : projectInfo.isVite ? "src/utils" : "src/utils";
|
|
731
|
-
const cleanUtilsPath = utilsPath.replace(/\.(ts|js)$/, "");
|
|
732
|
-
const constantsPath = projectInfo.isNextJs ? "lib/constants" : "src/constants";
|
|
733
|
-
let tailwindConfig = "tailwind.config.js";
|
|
734
|
-
if (projectInfo.typescript) {
|
|
735
|
-
tailwindConfig = "tailwind.config.ts";
|
|
736
|
-
}
|
|
737
|
-
const cssPath = projectInfo.isNextJs ? "app/globals.css" : "src/assets/css/index.css";
|
|
738
|
-
return {
|
|
739
|
-
tailwindConfig,
|
|
740
|
-
cssPath,
|
|
741
|
-
componentsPath: componentPath,
|
|
742
|
-
utilsPath: cleanUtilsPath,
|
|
743
|
-
constantsPath
|
|
744
|
-
};
|
|
745
|
-
}
|
|
746
|
-
function generateComponentsConfig({
|
|
747
|
-
projectInfo,
|
|
748
|
-
userInputs
|
|
749
|
-
}) {
|
|
750
|
-
const defaults = getDefaultConfig(projectInfo);
|
|
751
|
-
const tailwindConfig = normalizePath(userInputs?.tailwindConfig ?? defaults.tailwindConfig);
|
|
752
|
-
const cssPath = normalizePath(userInputs?.cssPath ?? defaults.cssPath);
|
|
753
|
-
const componentsPath = normalizePath(userInputs?.componentsPath ?? defaults.componentsPath);
|
|
754
|
-
const utilsPath = normalizePath(userInputs?.utilsPath ?? defaults.utilsPath);
|
|
755
|
-
const constantsPath = normalizePath(userInputs?.constantsPath ?? defaults.constantsPath);
|
|
756
|
-
return {
|
|
757
|
-
$schema: "./schema/components-config.schema.json",
|
|
758
|
-
tailwind: {
|
|
759
|
-
config: tailwindConfig,
|
|
760
|
-
css: cssPath
|
|
761
|
-
},
|
|
762
|
-
aliases: {
|
|
763
|
-
components: componentsPath,
|
|
764
|
-
utils: utilsPath,
|
|
765
|
-
constants: constantsPath
|
|
766
|
-
}
|
|
767
|
-
};
|
|
768
|
-
}
|
|
786
|
+
// src/commands/init.ts
|
|
787
|
+
init_components_config();
|
|
769
788
|
|
|
770
789
|
// src/utils/display-alias-instructions.ts
|
|
771
790
|
init_cjs_shims();
|
|
772
791
|
var import_chalk3 = __toESM(require("chalk"));
|
|
773
792
|
var import_fs_extra5 = __toESM(require("fs-extra"));
|
|
774
793
|
var import_path5 = __toESM(require("path"));
|
|
794
|
+
init_components_config();
|
|
775
795
|
init_project_info();
|
|
776
796
|
async function displayAliasInstructions({
|
|
777
797
|
cwd,
|
|
@@ -808,10 +828,16 @@ async function displayAliasInstructions({
|
|
|
808
828
|
const utilsPath = import_path5.default.relative(".", config.aliases.utils);
|
|
809
829
|
const constantsPath = import_path5.default.relative(".", config.aliases.constants);
|
|
810
830
|
const projectInfo = await getProjectInfo(cwd);
|
|
831
|
+
const hooksPath = import_path5.default.relative(
|
|
832
|
+
".",
|
|
833
|
+
config.aliases.hooks ?? getDefaultConfig(projectInfo).hooksPath
|
|
834
|
+
);
|
|
811
835
|
const extension = projectInfo.typescript ? ".ts" : ".js";
|
|
812
836
|
console.info(import_chalk3.default.cyan("Detected paths:\n"));
|
|
813
837
|
console.info(import_chalk3.default.gray(` \u2022 Components: ${componentsPath}`));
|
|
814
838
|
console.info(import_chalk3.default.gray(` \u2022 Utils: ${utilsPath}`));
|
|
839
|
+
console.info(import_chalk3.default.gray(` \u2022 Constants: ${constantsPath}`));
|
|
840
|
+
console.info(import_chalk3.default.gray(` \u2022 Hooks: ${hooksPath}`));
|
|
815
841
|
console.info(import_chalk3.default.gray(" \u2022 The utils alias points to the utils directory\n"));
|
|
816
842
|
if (hasTsConfig || hasJsConfig || projectType === "next.js") {
|
|
817
843
|
const configFile = hasTsConfig ? "tsconfig.json" : "jsconfig.json";
|
|
@@ -826,7 +852,8 @@ async function displayAliasInstructions({
|
|
|
826
852
|
"@components/*": ["${componentsPath}/*"],
|
|
827
853
|
"@utils": ["${utilsPath}"],
|
|
828
854
|
"@constants": ["${constantsPath}"],
|
|
829
|
-
"@constants/*": ["${constantsPath}/*"]
|
|
855
|
+
"@constants/*": ["${constantsPath}/*"],
|
|
856
|
+
"@hooks": ["${hooksPath}"]
|
|
830
857
|
}
|
|
831
858
|
}
|
|
832
859
|
}
|
|
@@ -862,7 +889,8 @@ async function displayAliasInstructions({
|
|
|
862
889
|
"@components/*": ["${componentsPath}/*"],
|
|
863
890
|
"@utils": ["${utilsPath}"],
|
|
864
891
|
"@constants": ["${constantsPath}"],
|
|
865
|
-
"@constants/*": ["${constantsPath}/*"]
|
|
892
|
+
"@constants/*": ["${constantsPath}/*"],
|
|
893
|
+
"@hooks": ["${hooksPath}"]
|
|
866
894
|
}
|
|
867
895
|
}
|
|
868
896
|
}
|
|
@@ -880,7 +908,8 @@ resolve: {
|
|
|
880
908
|
alias: {
|
|
881
909
|
'@components': path.resolve(__dirname, '${componentsPath}'),
|
|
882
910
|
'@utils': path.resolve(__dirname, '${utilsPath}'),
|
|
883
|
-
'@constants': path.resolve(__dirname, '${constantsPath}')
|
|
911
|
+
'@constants': path.resolve(__dirname, '${constantsPath}'),
|
|
912
|
+
'@hooks': path.resolve(__dirname, '${hooksPath}')
|
|
884
913
|
}
|
|
885
914
|
}
|
|
886
915
|
|
|
@@ -915,7 +944,8 @@ resolve: {
|
|
|
915
944
|
alias: {
|
|
916
945
|
'@components': path.resolve(__dirname, '${componentsPath}'),
|
|
917
946
|
'@utils': path.resolve(__dirname, '${utilsPath}'),
|
|
918
|
-
'@constants': path.resolve(__dirname, '${constantsPath}')
|
|
947
|
+
'@constants': path.resolve(__dirname, '${constantsPath}'),
|
|
948
|
+
'@hooks': path.resolve(__dirname, '${hooksPath}')
|
|
919
949
|
}
|
|
920
950
|
}
|
|
921
951
|
`));
|
|
@@ -954,7 +984,8 @@ Option 1: Use CRACO (Create React App Configuration Override)
|
|
|
954
984
|
alias: {
|
|
955
985
|
'@components': path.resolve(__dirname, '${componentsPath}'),
|
|
956
986
|
'@utils': path.resolve(__dirname, '${utilsPath}'),
|
|
957
|
-
'@constants': path.resolve(__dirname, '${constantsPath}')
|
|
987
|
+
'@constants': path.resolve(__dirname, '${constantsPath}'),
|
|
988
|
+
'@hooks': path.resolve(__dirname, '${hooksPath}')
|
|
958
989
|
}
|
|
959
990
|
}
|
|
960
991
|
};
|
|
@@ -985,13 +1016,21 @@ Option 1: Use CRACO (Create React App Configuration Override)
|
|
|
985
1016
|
console.info(import_chalk3.default.white(`
|
|
986
1017
|
import { Button } from '@components/button';
|
|
987
1018
|
import { cn } from '@utils';
|
|
1019
|
+
import { keyboardKeys } from '@constants';
|
|
1020
|
+
import { useWindowSize } from '@hooks';
|
|
988
1021
|
`));
|
|
1022
|
+
console.info(
|
|
1023
|
+
import_chalk3.default.gray(
|
|
1024
|
+
"\n Note: Components such as Select, TransferList and MultiSelectTransfer import\n shared hooks from '@hooks', so this alias is required for them to resolve.\n"
|
|
1025
|
+
)
|
|
1026
|
+
);
|
|
989
1027
|
}
|
|
990
1028
|
|
|
991
1029
|
// src/utils/prompt-config.ts
|
|
992
1030
|
init_cjs_shims();
|
|
993
1031
|
var import_prompts = __toESM(require("prompts"));
|
|
994
1032
|
var import_chalk4 = __toESM(require("chalk"));
|
|
1033
|
+
init_components_config();
|
|
995
1034
|
async function promptForConfig({
|
|
996
1035
|
projectInfo,
|
|
997
1036
|
skipPrompts = false
|
|
@@ -1041,6 +1080,13 @@ async function promptForConfig({
|
|
|
1041
1080
|
message: "Constants directory:",
|
|
1042
1081
|
initial: defaults.constantsPath,
|
|
1043
1082
|
validate: (value) => value.trim().length > 0 || "Path cannot be empty"
|
|
1083
|
+
},
|
|
1084
|
+
{
|
|
1085
|
+
type: "text",
|
|
1086
|
+
name: "hooksPath",
|
|
1087
|
+
message: "Hooks directory:",
|
|
1088
|
+
initial: defaults.hooksPath,
|
|
1089
|
+
validate: (value) => value.trim().length > 0 || "Path cannot be empty"
|
|
1044
1090
|
}
|
|
1045
1091
|
], {
|
|
1046
1092
|
onCancel: () => {
|
|
@@ -1055,7 +1101,7 @@ async function promptForConfig({
|
|
|
1055
1101
|
`));
|
|
1056
1102
|
return void 0;
|
|
1057
1103
|
}
|
|
1058
|
-
if (!responses || !responses.tailwindConfig || !responses.cssPath || !responses.componentsPath || !responses.utilsPath || !responses.constantsPath) {
|
|
1104
|
+
if (!responses || !responses.tailwindConfig || !responses.cssPath || !responses.componentsPath || !responses.utilsPath || !responses.constantsPath || !responses.hooksPath) {
|
|
1059
1105
|
console.info(import_chalk4.default.yellow("\n\u26A0\uFE0F Configuration incomplete. Using defaults.\n"));
|
|
1060
1106
|
return void 0;
|
|
1061
1107
|
}
|
|
@@ -1064,14 +1110,15 @@ async function promptForConfig({
|
|
|
1064
1110
|
cssPath: responses.cssPath,
|
|
1065
1111
|
componentsPath: responses.componentsPath,
|
|
1066
1112
|
utilsPath: responses.utilsPath,
|
|
1067
|
-
constantsPath: responses.constantsPath
|
|
1113
|
+
constantsPath: responses.constantsPath,
|
|
1114
|
+
hooksPath: responses.hooksPath
|
|
1068
1115
|
};
|
|
1069
1116
|
}
|
|
1070
1117
|
|
|
1071
1118
|
// package.json
|
|
1072
1119
|
var package_default = {
|
|
1073
1120
|
name: "@cloudwick/astral-ui-cli",
|
|
1074
|
-
version: "2.
|
|
1121
|
+
version: "2.3.0",
|
|
1075
1122
|
description: "CLI for installing Astral UI components in any codebase",
|
|
1076
1123
|
main: "dist/index.js",
|
|
1077
1124
|
bin: {
|
|
@@ -1531,16 +1578,20 @@ var REGISTRY = {
|
|
|
1531
1578
|
"name": "button",
|
|
1532
1579
|
"description": "The Button component is a versatile interactive element used to trigger actions, submit forms, or navigate between pages. It provides multiple visual styles, sizes, colors, and states including loading and disabled states. **When to use:** - Primary and secondary actions in forms and dialogs - Call-to-action elements on pages - Navigation triggers - Form submissions - Destructive actions (with error color) **Component Architecture:** - Built with React forwardRef for ref forwarding - Styled with Tailwind CSS and class-variance-authority (cva) - Integrates with Tooltip component for hover tooltips - Supports icon integration via ADPIcon or custom React nodes",
|
|
1533
1580
|
"dependencies": [
|
|
1534
|
-
"tailwind-variants",
|
|
1535
1581
|
"react",
|
|
1582
|
+
"tailwind-variants",
|
|
1536
1583
|
"@floating-ui/react",
|
|
1537
1584
|
"tailwind-merge"
|
|
1538
1585
|
],
|
|
1539
1586
|
"internalDependencies": [
|
|
1540
|
-
"
|
|
1541
|
-
"
|
|
1587
|
+
"adpIcon",
|
|
1588
|
+
"tooltip"
|
|
1542
1589
|
],
|
|
1543
1590
|
"files": [
|
|
1591
|
+
{
|
|
1592
|
+
"name": "reloadButton.tsx",
|
|
1593
|
+
"content": 'import * as React from "react";\n\nimport { Button } from "./button";\nimport { ADPIcon, iconList } from "../adpIcon";\n\nexport interface IReloadButtonProps {\n /** Absent means the surface has no reload affordance, and nothing renders. */\n onReload?: () => void;\n /** Spins the icon and blocks a second click while the refetch is in flight. */\n isReloading?: boolean;\n /** OR-ed with `isReloading` \u2014 a disabled surface has nothing to reload. */\n disabled?: boolean;\n /** Doubles as the accessible name; the button is icon-only. */\n tooltip?: string;\n className?: string;\n}\n\n/**\n * The icon-only refetch affordance for any surface backed by an async option source. One component\n * so the icon, the in-flight disable and the tooltip/aria-label pairing cannot drift between them.\n */\nexport function ReloadButton({\n onReload,\n isReloading,\n disabled,\n tooltip,\n className = "p-1"\n}: IReloadButtonProps ): React.ReactElement | null {\n if ( typeof onReload !== "function" ) {\n return null;\n }\n return (\n <Button\n variant="shade"\n color="secondary"\n className={className}\n size="sm"\n onClick={onReload}\n disabled={disabled === true || isReloading === true}\n tooltip={tooltip}\n aria-label={tooltip}\n >\n <ADPIcon icon={iconList.reload} size="xs" spin={isReloading} />\n </Button>\n );\n}\n\nReloadButton.displayName = "ReloadButton";\n'
|
|
1594
|
+
},
|
|
1544
1595
|
{
|
|
1545
1596
|
"name": "index.ts",
|
|
1546
1597
|
"content": 'export {\n Button,\n ESizes,\n colors,\n variants,\n ButtonSizeToSpinnerMap,\n type IButtonProps,\n type TColor,\n type TVariant,\n type TSize\n} from "./button";\nexport { buttonVariants } from "./buttonVariants";'
|
|
@@ -1723,7 +1774,6 @@ export const checkboxVariants = tv({
|
|
|
1723
1774
|
"dependencies": [
|
|
1724
1775
|
"tailwind-variants",
|
|
1725
1776
|
"react",
|
|
1726
|
-
"react-dom",
|
|
1727
1777
|
"tailwind-merge"
|
|
1728
1778
|
],
|
|
1729
1779
|
"internalDependencies": [
|
|
@@ -2360,25 +2410,35 @@ DropdownItem.displayName = "DropdownItem";
|
|
|
2360
2410
|
},
|
|
2361
2411
|
"multiselecttransfer": {
|
|
2362
2412
|
"name": "multiSelectTransfer",
|
|
2363
|
-
"description": 'The MultiSelectTransfer is a multi-select form control that pairs a compact, pill-based trigger with two ways to pick options: a lightweight **dropdown** for quick selection and a full-screen **transfer-list modal** for managing large or ordered selections across an **Available** and a **Selected** panel. Committed selections render as removable pills in the trigger, collapsing to a "+N More" badge past a configurable limit. It supports both controlled and uncontrolled usage, client- and server-side filtering, infinite scroll, and optional reordering. **When to use:** - Selecting multiple items (permissions, columns, tags, members) from a pool that can be browsed quickly or curated in depth - Form fields where the current selection should stay visible as pills - Workflows that need a "confirm before commit" step (Cancel/Done in the modal) - Large, possibly paginated option sets that benefit from windowing and infinite scroll - Ordered selections where the position of chosen items matters (`reorderable`) **Component Architecture:** - Styled with `tailwind-variants` (`tv()`) slots \u2014 see `multiSelectTransferVariants.ts` - Composes the standalone `TransferList` inside a `Modal` for the full-management view - Dropdown and transfer-list panels window (virtualize) large option sets - Infinite scroll via the shared `useInfiniteScroll` (`IntersectionObserver`) hook - Debounced server-side filtering via the shared `
|
|
2413
|
+
"description": 'The MultiSelectTransfer is a multi-select form control that pairs a compact, pill-based trigger with two ways to pick options: a lightweight **dropdown** for quick selection and a full-screen **transfer-list modal** for managing large or ordered selections across an **Available** and a **Selected** panel. Committed selections render as removable pills in the trigger, collapsing to a "+N More" badge past a configurable limit. It supports both controlled and uncontrolled usage, client- and server-side filtering, infinite scroll, and optional reordering. **When to use:** - Selecting multiple items (permissions, columns, tags, members) from a pool that can be browsed quickly or curated in depth - Form fields where the current selection should stay visible as pills - Workflows that need a "confirm before commit" step (Cancel/Done in the modal) - Large, possibly paginated option sets that benefit from windowing and infinite scroll - Ordered selections where the position of chosen items matters (`reorderable`) **Component Architecture:** - Styled with `tailwind-variants` (`tv()`) slots \u2014 see `multiSelectTransferVariants.ts` - Composes the standalone `TransferList` inside a `Modal` for the full-management view - Dropdown and transfer-list panels window (virtualize) large option sets - Infinite scroll via the shared `useInfiniteScroll` (`IntersectionObserver`) hook - Debounced server-side filtering via the shared `useFilterQuery` hook (also used by `Select`) - Both surfaces\' search inputs can be turned off with `searchable={false}`; the dropdown\'s option list then takes focus and owns the keyboard, as each TransferList panel\'s list already does - Client-side filtering via the shared `matchesQuery` util when no filter handler is given - Reuses `ADPIcon`, `Tooltip` (for clipped pill labels), and `TransferList` - Dark-mode aware and RTL-safe (logical spacing properties throughout)',
|
|
2364
2414
|
"dependencies": [
|
|
2365
2415
|
"react",
|
|
2366
2416
|
"tailwind-variants",
|
|
2417
|
+
"react-merge-refs",
|
|
2367
2418
|
"tailwind-merge"
|
|
2368
2419
|
],
|
|
2369
2420
|
"internalDependencies": [
|
|
2370
2421
|
"transferList",
|
|
2371
2422
|
"adpIcon",
|
|
2372
2423
|
"tooltip",
|
|
2424
|
+
"checkbox",
|
|
2373
2425
|
"modal",
|
|
2374
2426
|
"button",
|
|
2375
|
-
"
|
|
2376
|
-
"
|
|
2427
|
+
"loader",
|
|
2428
|
+
"card"
|
|
2377
2429
|
],
|
|
2378
2430
|
"files": [
|
|
2431
|
+
{
|
|
2432
|
+
"name": "useMultiSelectTransferOptionSource.ts",
|
|
2433
|
+
"content": 'import { useCallback, useState, type ReactNode } from "react";\n\nimport { useAsyncOptions, useIgnoredPropWarning, type TPrefetch } from "@hooks";\nimport { resolveLoadErrors, resolveReloadControls } from "@utils";\nimport type { TMultiSelectTransferLoadOptions, TMultiSelectTransferOption } from "./types";\n\nconst EMPTY_OPTIONS: readonly TMultiSelectTransferOption[] = [];\n\ninterface IUseMultiSelectTransferOptionSourceArgs {\n options?: TMultiSelectTransferOption[];\n loadOptions?: TMultiSelectTransferLoadOptions;\n initialOptions?: readonly TMultiSelectTransferOption[];\n prefetch?: TPrefetch;\n refetchOnClear?: boolean;\n optionsKey?: string | number;\n loadErrorMessage?: ReactNode;\n loadMoreErrorMessage?: ReactNode;\n showReloadButton?: boolean;\n onLoadError?: ( error: unknown ) => void;\n /** Legacy (consumer-driven) paging and loading. Ignored in async mode. */\n hasMore?: boolean;\n onLoadMore?: () => void;\n isLoading?: boolean;\n onReload?: () => void;\n isReloading?: boolean;\n onFilterChange?: ( query: string ) => void;\n}\n\ninterface IMultiSelectTransferOptionSource {\n options: readonly TMultiSelectTransferOption[];\n /** The mode decision, made once here \u2014 the component must never re-test `loadOptions` itself. */\n isAsync: boolean;\n isServerFiltered: boolean;\n /** Any load in flight \u2014 feeds aria-busy on the option list. */\n isLoading: boolean;\n /** Loader INSTEAD of rows: a search/reload fetch, not a page append. */\n isSearchFetch: boolean;\n /** Loader BELOW the rows, and the infinite-scroll observer\'s in-flight gate. */\n isLoadingMore: boolean;\n hasMore: boolean;\n total: number | undefined;\n onLoadMore?: () => void;\n onRetryLoadMore?: () => void;\n isReloading?: boolean;\n onReload?: () => void;\n onFilterQueryChange: ( query: string ) => void;\n ensureDefaults: () => void;\n /** Set when the whole list failed. Mutually exclusive with `loadMoreError`. */\n loadError?: ReactNode;\n /** Set when a page append failed. The rows the user was reading stay on screen. */\n loadMoreError?: ReactNode;\n /** Ends legacy load-more mode: typing or clearing means the next fetch replaces rows, not appends. */\n clearLoadMoreMode: () => void;\n}\n\n/**\n * MultiSelectTransfer\'s option-source policy: async vs legacy `options` / `isLoading` / `hasMore` /\n * `onLoadMore`, the replace-vs-append loader question, and the paging trio. In async mode the hook\n * knows the request *kind* directly; the legacy path still needs a ref latch, since `isLoading` is a\n * bare boolean there and the kind has to be inferred from its edges.\n */\nexport function useMultiSelectTransferOptionSource({\n options,\n loadOptions,\n initialOptions,\n prefetch,\n refetchOnClear = false,\n optionsKey,\n loadErrorMessage,\n loadMoreErrorMessage,\n showReloadButton = false,\n onLoadError,\n hasMore = false,\n onLoadMore,\n isLoading = false,\n onReload,\n isReloading,\n onFilterChange\n}: IUseMultiSelectTransferOptionSourceArgs ): IMultiSelectTransferOptionSource {\n const isAsync = typeof loadOptions === "function";\n\n const asyncOptions = useAsyncOptions<TMultiSelectTransferOption>({\n loadOptions,\n initialOptions,\n prefetchDefaults: prefetch !== "never",\n refetchOnClear,\n optionsKey,\n onLoadError,\n getOptionKey: ( option ) => option.value\n });\n\n // \u2500\u2500 Legacy replace-vs-append detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // State, not a pair of refs: `isLoadingMore` decides whether the loader replaces the rows or appends\n // below them, so it IS render output, and a ref read during render neither schedules a re-render nor\n // rolls back with a discarded one. `wasLoading` rides along so the true\u2192false edge is detected\n // against committed state. Cleared only once `isLoading` finishes, so it survives the consumer\'s\n // setPage-before-fetch gap.\n const [ legacyLoad, setLegacyLoad ] = useState({ isLoadingMore: false, wasLoading: isLoading });\n if ( legacyLoad.wasLoading !== isLoading ) {\n setLegacyLoad({\n // A finished load ends load-more mode; a starting one leaves it as `onLoadMore` set it.\n isLoadingMore: isLoading ? legacyLoad.isLoadingMore : false,\n wasLoading: isLoading\n });\n }\n\n useIgnoredPropWarning(\n isAsync && options !== undefined,\n "MultiSelectTransfer: `options` is ignored when `loadOptions` is set \u2014 use `initialOptions` to seed the list."\n );\n // The mirror of the above: seed rows only mean anything to the async source, so without a loader they\n // vanish silently \u2014 the same mistake, and just as quiet.\n useIgnoredPropWarning(\n !isAsync && initialOptions !== undefined,\n "MultiSelectTransfer: `initialOptions` is ignored without `loadOptions` \u2014 pass those rows as `options` instead."\n );\n // Same class of mistake: `prefetch` only ever schedules the baseline fetch, so with the rows already\n // in `options` there is nothing for it to trigger and it silently does nothing.\n useIgnoredPropWarning(\n !isAsync && prefetch !== undefined,\n "MultiSelectTransfer: `prefetch` is ignored without `loadOptions` \u2014 `options` are already on screen, so there is nothing to fetch."\n );\n\n const onFilterQueryChange = ( query: string ): void => {\n onFilterChange?.( query );\n asyncOptions.onFilterChange( query );\n };\n\n const handleLegacyLoadMore = (): void => {\n // Batched with whatever `onLoadMore` sets, so one render sees both this and the consumer\'s\n // `isLoading` \u2014 an append loader never renders as a replacing one.\n setLegacyLoad(( previous ) => ({ ...previous, isLoadingMore: true }));\n onLoadMore?.();\n };\n\n // Stable, and it propagates through the component\'s resetFilter \u2192 commitSelection \u2192 the\n // outside-click listener, which would otherwise re-subscribe every render. The bail-out keeps a\n // close that was never in load-more mode from scheduling a render.\n const clearLoadMoreMode = useCallback(() => {\n setLegacyLoad(( previous ) => ( previous.isLoadingMore ? { ...previous, isLoadingMore: false } : previous ));\n }, []);\n\n return {\n options: isAsync ? asyncOptions.options : options ?? EMPTY_OPTIONS,\n isAsync,\n isServerFiltered: isAsync || typeof onFilterChange === "function",\n isLoading: isLoading === true || ( isAsync && asyncOptions.isBusy ),\n isSearchFetch: isAsync\n ? asyncOptions.isReplacing\n : isLoading === true && !legacyLoad.isLoadingMore,\n isLoadingMore: isAsync ? asyncOptions.isLoadingMore : legacyLoad.isLoadingMore,\n hasMore: isAsync ? asyncOptions.hasMore : hasMore,\n total: isAsync ? asyncOptions.total : undefined,\n onLoadMore: isAsync ? asyncOptions.loadMore : handleLegacyLoadMore,\n onRetryLoadMore: isAsync ? asyncOptions.retryMore : undefined,\n ...resolveReloadControls({ isAsync, source: asyncOptions, onReload, isReloading, showReloadButton }),\n onFilterQueryChange,\n ensureDefaults: asyncOptions.ensureDefaults,\n ...resolveLoadErrors({\n errorKind: asyncOptions.errorKind,\n loadErrorMessage,\n loadMoreErrorMessage\n }),\n clearLoadMoreMode\n };\n}\n'
|
|
2434
|
+
},
|
|
2435
|
+
{
|
|
2436
|
+
"name": "useMultiSelectTransferDraft.ts",
|
|
2437
|
+
"content": 'import { useCallback, useState } from "react";\n\nimport { useAvailableProjection } from "@hooks";\nimport type { TMultiSelectTransferOption } from "./types";\n\ninterface IMultiSelectTransferDraft {\n /** Derived: the loaded pool plus the opening snapshot, minus whatever is in the draft selection. */\n draftAvailable: TMultiSelectTransferOption[];\n /** Owned: the ordered draft selection. Order matters when `reorderable`. */\n draftSelected: TMultiSelectTransferOption[];\n /** Wire to `TransferList`\'s onChange; only its second argument is needed. */\n onDraftChange: (\n nextAvailable: TMultiSelectTransferOption[],\n nextSelected: TMultiSelectTransferOption[]\n ) => void;\n /** Seed the draft from the committed selection. Call when opening the modal. */\n seedDraft: ( committed: TMultiSelectTransferOption[]) => void;\n}\n\n/**\n * The transfer-list modal\'s draft, as a **projection** of the loaded option pool rather than a second\n * array kept in sync with it. A paged-in option appears in Available automatically; an option the\n * user moved right is never re-offered; and an `optionsKey` change re-seeds by construction. An\n * option that left Selected but is not in the pool is covered by the opening snapshot, since the\n * only way into the draft is the pool or the committed value.\n *\n * `searchQuery` is the panel\'s active server query (empty when the search is client-side, where\n * TransferList filters for us); it keeps the snapshot from surfacing an option the server\'s answer\n * for that query would not have returned.\n */\nexport function useMultiSelectTransferDraft(\n pool: readonly TMultiSelectTransferOption[],\n isOpen: boolean,\n searchQuery = ""\n): IMultiSelectTransferDraft {\n const [ draftSelected, setDraftSelected ] = useState<TMultiSelectTransferOption[]>([]);\n // Options that belong in Available but the loaded pool may not contain \u2014 committed values that were\n // never fetched. Snapshotted at open (state, not a live prop read) so a parent re-render mid-draft\n // cannot disturb the panels.\n const [ openingSnapshot, setOpeningSnapshot ] = useState<TMultiSelectTransferOption[]>([]);\n\n // Gated on `isOpen`: the modal renders nothing while closed, so re-projecting the whole pool on\n // every landed page and every dropdown search would be work no one can see.\n const draftAvailable = useAvailableProjection( isOpen, pool, openingSnapshot, draftSelected, searchQuery );\n\n const seedDraft = useCallback(( committed: TMultiSelectTransferOption[]) => {\n setDraftSelected( committed );\n setOpeningSnapshot( committed );\n }, []);\n\n const onDraftChange = useCallback(\n ( _nextAvailable: TMultiSelectTransferOption[], nextSelected: TMultiSelectTransferOption[]) => {\n setDraftSelected( nextSelected );\n },\n []\n );\n\n return { draftAvailable, draftSelected, onDraftChange, seedDraft };\n}\n'
|
|
2438
|
+
},
|
|
2379
2439
|
{
|
|
2380
2440
|
"name": "types.ts",
|
|
2381
|
-
"content": 'import type { ReactNode } from "react";\n\nimport type { ITransferListItem } from "../transferList/types";\n\nexport enum EMultiSelectTransferSizes {\n MD = "md",\n LG = "lg"\n}\n\nexport type TMultiSelectTransferSize = `${EMultiSelectTransferSizes}`;\n\n// Options feed straight into the composed TransferList, so an option IS a transfer-list item.\n// Aliased to ITransferListItem (not redeclared) so the shared shape lives in one place.\nexport type TMultiSelectTransferOption = ITransferListItem;\n\nexport interface IMultiSelectTransferProps {\n id?: string;\n className?: string;\n label?: ReactNode;\n placeholder?: string;\n helperText?: ReactNode;\n error?: boolean;\n disabled?: boolean;\n size?: TMultiSelectTransferSize;\n\n options
|
|
2441
|
+
"content": 'import type { ReactNode } from "react";\n\nimport type { TLoadOptions, TPrefetch } from "@hooks";\nimport type { ITransferListItem } from "../transferList/types";\n\nexport enum EMultiSelectTransferSizes {\n MD = "md",\n LG = "lg"\n}\n\nexport type TMultiSelectTransferSize = `${EMultiSelectTransferSizes}`;\n\n// Options feed straight into the composed TransferList, so an option IS a transfer-list item.\n// Aliased to ITransferListItem (not redeclared) so the shared shape lives in one place.\nexport type TMultiSelectTransferOption = ITransferListItem;\n\n/**\n * Async option source. Paged: `cursor`, `hasMore` and `total` on the resolved page are all honoured.\n */\nexport type TMultiSelectTransferLoadOptions = TLoadOptions<TMultiSelectTransferOption>;\n\nexport interface IMultiSelectTransferProps {\n /** Unique id for the trigger. A generated id is used when omitted. */\n id?: string;\n /** Custom className for the wrapper. */\n className?: string;\n /** Label displayed above the trigger. */\n label?: ReactNode;\n /** Text shown in the trigger while nothing is selected. @default "Select..." */\n placeholder?: string;\n /** Helper text displayed below the trigger. */\n helperText?: ReactNode;\n /** Display error styling. @default false */\n error?: boolean;\n /** Disable all interaction. @default false */\n disabled?: boolean;\n /** Trigger size variant. @default "md" */\n size?: TMultiSelectTransferSize;\n\n /**\n * Options to choose from; treated as the result for the current query in server mode. Ignored (with\n * a dev warning) when `loadOptions` is set \u2014 pass `initialOptions` to seed the list instead.\n */\n options?: TMultiSelectTransferOption[];\n /** Selected options. Passing this makes the component controlled. */\n value?: TMultiSelectTransferOption[];\n /** Fired with the next selection when the dropdown or modal commits. */\n onChange?: ( selected: TMultiSelectTransferOption[]) => void;\n\n /** Seeds/re-syncs dropdown search; semi-controlled \u2014 pair with onFilterChange. */\n filterValue?: string;\n /**\n * Debounced search-query callback; also called with "" when the component clears search (dropdown\n * commit/cancel, or opening the transfer list modal).\n *\n * Without `loadOptions`: switches off local filtering \u2014 `options` is treated as already filtered\n * for the query \u2014 and the fetch, loading state, paging, and response ordering are the consumer\'s\n * responsibility.\n *\n * With `loadOptions`: notification-only, for analytics or `filterValue` syncing.\n */\n onFilterChange?: ( query: string ) => void;\n /**\n * Renders the dropdown\'s search input and the transfer list modal\'s two panel search inputs. With\n * `false` the dropdown\'s option list becomes the focused widget on open and owns the keyboard\n * (`role="listbox"` plus `aria-activedescendant`), so Escape, Tab, the arrows, Home/End and Enter\n * behave as they do with the input present, and Space activates the active row. Only the ability to\n * narrow the list is gone, which suits short, fixed option sets. The reload button is unaffected.\n * @default true\n */\n searchable?: boolean;\n /** Placeholder for the dropdown filter input and the transfer list modal\'s panel search inputs. @default "Search..." */\n searchPlaceholder?: string;\n /** Debounce for the search query, in both sync and `loadOptions` mode. Set to 0 to disable. @default 300 */\n filterDebounceMs?: number;\n\n // Consumer-owned paging, the escape-hatch counterpart to `onFilterChange` above. Both are ignored\n // when `loadOptions` is set, which derives them from the cursor the loader returns.\n /** Whether more options can be loaded; arms the dropdown\'s infinite-scroll sentinel. Ignored when `loadOptions` is set. @default false */\n hasMore?: boolean;\n /** Fired when the infinite-scroll sentinel at the bottom of the option list scrolls into view. Ignored when `loadOptions` is set. */\n onLoadMore?: () => void;\n /** Loader replaces rows on search fetch, appends on load-more. OR-ed with the loader\'s own state, so it still applies in async mode. @default false */\n isLoading?: boolean;\n\n /** Max pills shown in the trigger before showing "+N More". @default 3 */\n maxVisiblePills?: number;\n\n /** Title rendered in the transfer list modal header. */\n transferListTitle?: ReactNode;\n /** Subtitle rendered under the modal title. */\n transferListSubtitle?: ReactNode;\n /** Fully custom modal header node; overrides title/subtitle when provided. */\n transferListHeader?: ReactNode;\n /** Called when the transfer list CTA is clicked (before the modal opens). */\n onOpenTransferList?: () => void;\n\n /** Enable reordering (drag + arrows) of selected items in the transfer list. */\n reorderable?: boolean;\n /** The reload button is shown when this is provided. Fired when the reload button is clicked. */\n onReload?: () => void;\n /** Spins the transfer list reload icon. */\n isReloading?: boolean;\n /** Tooltip for the transfer list reload button. */\n reloadTooltip?: string;\n /** Custom content rendered under the transfer list available panel search. */\n availablePanelHeaderSlot?: ReactNode;\n /** Custom content rendered under the transfer list selected panel search. */\n selectedPanelHeaderSlot?: ReactNode;\n /** Label for the modal cancel button. @default "Cancel" */\n cancelLabel?: ReactNode;\n /** Label for the modal commit button. @default "Done" */\n doneLabel?: ReactNode;\n\n /**\n * Server-side option source. When provided, the component owns the option list, paging, the request\n * lifecycle and the loading state; `options` / `hasMore` / `onLoadMore` / `isLoading` are ignored and\n * `onFilterChange` becomes notification-only. Responsible for mapping the payload to\n * `TMultiSelectTransferOption` \u2014 envelopes and domain filtering are the consumer\'s business. Options\n * are stored exactly as returned, so extra fields survive. A fresh inline arrow is fine: the loader\n * is read through a ref.\n */\n loadOptions?: TMultiSelectTransferLoadOptions;\n /**\n * Seed rows for a list you already have \u2014 an SSR payload, a route loader, a warm cache. They paint on the\n * first frame of both surfaces instead of a loader, and stay put while the baseline fetch revalidates over\n * them (the dropdown\'s spinner appends below the rows, as it does for any load in flight). They do not\n * suppress that fetch: pair with `prefetch="never"` if the seed is the whole list until the user types.\n * Seed rows carry no cursor, so nothing pages until a real page lands.\n * A *search* replaces them, since seed rows are not results for a query; clearing it brings them back until\n * a fetched baseline does. Async mode only \u2014 ignored (dev warning) without `loadOptions`, where the rows\n * belong in `options`.\n */\n initialOptions?: readonly TMultiSelectTransferOption[];\n /**\n * When to fetch the unfiltered first page.\n * - `"open"` \u2014 when the dropdown or the transfer-list modal first opens, whichever comes first.\n * - `"mount"` \u2014 at render, so the first open shows rows instead of a loader. The trigger renders its\n * committed chips either way, so this buys latency rather than fixing an empty-looking control.\n * - `"never"` \u2014 no baseline at all; fetch only once the user types. For heavy lists.\n *\n * Async mode only \u2014 ignored (dev warning) without `loadOptions`, where `options` are already on screen\n * and there is nothing to fetch.\n * @default "open"\n */\n prefetch?: TPrefetch;\n /** Clearing the search revalidates the cached baseline instead of just restoring it. @default false */\n refetchOnClear?: boolean;\n /**\n * Identity of the option set, for dependent pickers. When it changes, cached pages are dropped and the\n * list is repopulated. Compose several parents into one scalar. Does NOT clear the selection.\n */\n optionsKey?: string | number;\n /** Shown in place of the rows when `loadOptions` rejects. @default "Couldn\'t load options." */\n loadErrorMessage?: ReactNode;\n /** Shown under the loaded rows when a page append rejects; a failed page never blanks the list. @default "Couldn\'t load more." */\n loadMoreErrorMessage?: ReactNode;\n /** Label for the retry button beside `loadMoreErrorMessage`. @default "Retry" */\n retryLabel?: string;\n /** Shows the reload button in async mode, wired to re-run the current query from page one. @default false */\n showReloadButton?: boolean;\n /** Notified when a load rejects (the component renders the message and swallows it). */\n onLoadError?: ( error: unknown ) => void;\n}\n'
|
|
2382
2442
|
},
|
|
2383
2443
|
{
|
|
2384
2444
|
"name": "multiSelectTransferVariants.ts",
|
|
@@ -2396,6 +2456,16 @@ export const multiSelectTransferVariants = tv({
|
|
|
2396
2456
|
filterInput: "w-full outline-none bg-transparent text-secondary-500 dark:text-secondary-200" +
|
|
2397
2457
|
" placeholder:text-secondary-200 dark:placeholder:text-secondary-400 rounded border border-secondary-100 dark:border-secondary-500 p-2",
|
|
2398
2458
|
optionsList: "max-h-60 overflow-y-auto",
|
|
2459
|
+
// The listbox is the focused widget whenever the search input is hidden, so it carries its own
|
|
2460
|
+
// focus ring \u2014 the treatment TransferList's panel listbox already has.
|
|
2461
|
+
optionsListbox: "outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary-400",
|
|
2462
|
+
// "No options" when empty and not mid search-fetch.
|
|
2463
|
+
noOptionsMessage: "px-4 py-2.5 text-center text-secondary-400 dark:text-secondary-300",
|
|
2464
|
+
// Loader row (replaces on search fetch, appends on load-more \u2014 see dropdown).
|
|
2465
|
+
loaderRow: "flex justify-center py-3",
|
|
2466
|
+
// "Error instead of rows", and the recoverable "that page failed" row below the loaded rows.
|
|
2467
|
+
errorMessage: "px-4 py-3 text-center text-sm text-error-700 dark:text-error-400",
|
|
2468
|
+
loadMoreErrorRow: "flex items-center justify-center gap-2 py-3 text-sm text-error-700 dark:text-error-400",
|
|
2399
2469
|
optionItem: "group relative flex items-center gap-2 px-4 py-2.5 cursor-pointer outline-none" +
|
|
2400
2470
|
" hover:bg-frostBlue focus-visible:bg-frostBlue dark:hover:bg-secondary-800 dark:focus-visible:bg-secondary-800",
|
|
2401
2471
|
// self-stretch pins the wrapper's height to the row's cross-size (driven by the checkbox)
|
|
@@ -2454,7 +2524,8 @@ export const multiSelectTransferVariants = tv({
|
|
|
2454
2524
|
pill: "text-base",
|
|
2455
2525
|
pillMore: "text-base",
|
|
2456
2526
|
placeholder: "text-base",
|
|
2457
|
-
optionLabel: "text-base"
|
|
2527
|
+
optionLabel: "text-base",
|
|
2528
|
+
noOptionsMessage: "text-base"
|
|
2458
2529
|
},
|
|
2459
2530
|
lg: {
|
|
2460
2531
|
trigger: "py-[0.2rem] px-4",
|
|
@@ -2462,7 +2533,8 @@ export const multiSelectTransferVariants = tv({
|
|
|
2462
2533
|
pill: "text-md",
|
|
2463
2534
|
pillMore: "text-md",
|
|
2464
2535
|
placeholder: "text-md",
|
|
2465
|
-
optionLabel: "text-md"
|
|
2536
|
+
optionLabel: "text-md",
|
|
2537
|
+
noOptionsMessage: "text-md"
|
|
2466
2538
|
}
|
|
2467
2539
|
},
|
|
2468
2540
|
disabled: {
|
|
@@ -2474,21 +2546,34 @@ export const multiSelectTransferVariants = tv({
|
|
|
2474
2546
|
checked: {
|
|
2475
2547
|
true: { optionItem: "bg-frostBlue dark:bg-secondary-700" },
|
|
2476
2548
|
false: {}
|
|
2549
|
+
},
|
|
2550
|
+
// With the search input hidden only the reload button is left in the header row, at its end.
|
|
2551
|
+
searchable: {
|
|
2552
|
+
false: { dropdownHeader: "justify-end" }
|
|
2477
2553
|
}
|
|
2478
2554
|
},
|
|
2479
2555
|
defaultVariants: {
|
|
2480
2556
|
error: false,
|
|
2481
2557
|
size: "md",
|
|
2558
|
+
searchable: true,
|
|
2482
2559
|
disabled: false,
|
|
2483
2560
|
checked: false
|
|
2484
2561
|
}
|
|
2485
2562
|
});
|
|
2486
2563
|
`
|
|
2487
2564
|
},
|
|
2565
|
+
{
|
|
2566
|
+
"name": "multiSelectTransferTrigger.tsx",
|
|
2567
|
+
"content": 'import * as React from "react";\n\nimport { ADPIcon, iconList } from "../adpIcon";\nimport { MultiSelectTransferPill } from "./multiSelectTransferPill";\nimport { multiSelectTransferVariants } from "./multiSelectTransferVariants";\nimport type { TMultiSelectTransferOption, TMultiSelectTransferSize } from "./types";\n\ninterface IMultiSelectTransferTriggerProps {\n id: string;\n error?: boolean;\n size: TMultiSelectTransferSize;\n disabled: boolean;\n isOpen: boolean;\n /** The committed selection \u2014 the trigger shows pills for this, never for the in-progress draft. */\n value: TMultiSelectTransferOption[];\n placeholder: string;\n maxVisiblePills: number;\n onClick: () => void;\n onKeyDown: ( e: React.KeyboardEvent<HTMLDivElement> ) => void;\n onRemovePill: ( option: TMultiSelectTransferOption, e: React.MouseEvent ) => void;\n onOpenTransferList: ( e: React.MouseEvent ) => void;\n}\n\n/**\n * The read-only control for MultiSelectTransfer: committed pills (capped by `maxVisiblePills` with a\n * "+N More" overflow), the transfer-list CTA and the open/close chevron. It owns no state.\n *\n * The trigger comes back through `forwardRef`, not a `triggerRef` prop: a ref taken as an ordinary\n * prop cannot be merged with a caller\'s own, and is invisible to anything composing over `ref`.\n */\nexport const MultiSelectTransferTrigger = React.forwardRef<\n HTMLDivElement,\n IMultiSelectTransferTriggerProps\n>( function MultiSelectTransferTrigger({\n id,\n error,\n size,\n disabled,\n isOpen,\n value,\n placeholder,\n maxVisiblePills,\n onClick,\n onKeyDown,\n onRemovePill,\n onOpenTransferList\n}, triggerRef ) {\n const {\n trigger,\n pillsArea,\n pill: pillClass,\n pillLabel,\n pillDismiss,\n pillMore,\n ctaArea,\n ctaButton,\n placeholder: placeholderClass\n } = multiSelectTransferVariants({ error, size, disabled });\n\n const visiblePills = value.slice( 0, maxVisiblePills );\n const overflowCount = value.length - visiblePills.length;\n\n return (\n <div\n id={id}\n ref={triggerRef}\n role="button"\n aria-expanded={isOpen}\n aria-haspopup="listbox"\n tabIndex={disabled ? -1 : 0}\n className={trigger()}\n onClick={onClick}\n onKeyDown={onKeyDown}\n >\n <div className={pillsArea()}>\n {value.length === 0 ? (\n <span className={placeholderClass()}>{placeholder}</span>\n ) : (\n <>\n {visiblePills.map(( opt ) => (\n <MultiSelectTransferPill\n key={opt.value}\n option={opt}\n pillClass={pillClass()}\n pillLabelClass={pillLabel()}\n pillDismissClass={pillDismiss()}\n onRemove={onRemovePill}\n />\n ))}\n {overflowCount > 0 && <span className={pillMore()}>+{overflowCount} More</span>}\n </>\n )}\n </div>\n <div className={ctaArea()}>\n <button\n type="button"\n aria-label="Open transfer list"\n title="Open transfer list"\n className={ctaButton()}\n onClick={onOpenTransferList}\n disabled={disabled}\n >\n <ADPIcon icon={iconList.expand} size="xs" />\n </button>\n <ADPIcon icon={isOpen ? iconList.upArrow : iconList.downArrow} className={ctaButton()} size="xs" />\n </div>\n </div>\n );\n});\n\nMultiSelectTransferTrigger.displayName = "MultiSelectTransferTrigger";\n'
|
|
2568
|
+
},
|
|
2488
2569
|
{
|
|
2489
2570
|
"name": "multiSelectTransferPill.tsx",
|
|
2490
2571
|
"content": 'import * as React from "react";\n\nimport { useIsTruncated } from "@hooks";\nimport { ADPIcon, iconList } from "../adpIcon";\nimport { Tooltip } from "../tooltip";\nimport { type TMultiSelectTransferOption } from "./types";\n\ninterface IMultiSelectTransferPillProps {\n option: TMultiSelectTransferOption;\n /** tv() class for the pill container (doubles as the truncation observer root). */\n pillClass: string;\n /** tv() class for the (truncating) label. */\n pillLabelClass: string;\n /** tv() class for the dismiss button. */\n pillDismissClass: string;\n onRemove: ( option: TMultiSelectTransferOption, e: React.MouseEvent ) => void;\n}\n\n/**\n * A single selected pill in the trigger. Its own component (not inlined in the map) so it can run\n * {@link useIsTruncated} per pill: the full label is surfaced in a Tooltip only when the label is\n * actually clipped, instead of on every pill hover.\n *\n * The Tooltip always wraps the label (gated via its `canOpen` prop) rather than being swapped in\n * and out - that keeps the measured label element mounted so the truncation observer never loses\n * its target. `triggerElementClassName` makes the Tooltip\'s trigger span a shrinkable flex box so\n * the nested label still truncates against the pill\'s max-width. Non-string (ReactNode) labels\n * have no text to show, so they render plainly.\n */\nexport function MultiSelectTransferPill({\n option,\n pillClass,\n pillLabelClass,\n pillDismissClass,\n onRemove\n}: IMultiSelectTransferPillProps ): React.ReactElement {\n const { ref: labelRef, containerRef: pillRef, isTruncated } = useIsTruncated<HTMLSpanElement, HTMLSpanElement>();\n const isStringLabel = typeof option.label === "string";\n\n return (\n <span ref={pillRef} className={pillClass}>\n {isStringLabel ? (\n <Tooltip\n placement="top"\n canOpen={isTruncated}\n title={option.label as string}\n triggerElementClassName="flex min-w-0 max-w-full"\n trigger={\n <span ref={labelRef} className={pillLabelClass}>\n {option.label}\n </span>\n }\n />\n ) : (\n <span className={pillLabelClass}>{option.label}</span>\n )}\n <button\n type="button"\n aria-label={`Remove ${option.value}`}\n className={pillDismissClass}\n onClick={( e ) => onRemove( option, e )}\n >\n <ADPIcon icon={iconList.cross} size="xs" />\n </button>\n </span>\n );\n}\n\nMultiSelectTransferPill.displayName = "MultiSelectTransferPill";\n'
|
|
2491
2572
|
},
|
|
2573
|
+
{
|
|
2574
|
+
"name": "multiSelectTransferOptionRow.tsx",
|
|
2575
|
+
"content": 'import * as React from "react";\n\nimport { Checkbox } from "../checkbox";\nimport { useIsTruncated } from "@hooks";\n\ninterface IOptionRowProps {\n id: string;\n label: React.ReactNode;\n checked: boolean;\n active: boolean;\n disabled?: boolean;\n onToggle: () => void;\n onActivate: () => void;\n optionItemClass: string | undefined;\n optionLabelWrapClass: string;\n optionLabelClass: string;\n}\n\n/**\n * A single dropdown row (both "Select All" and regular options): checkbox + label. Measures\n * its own label via `useIsTruncated` so the hover/focus expand affordance (see\n * multiSelectTransferVariants\' optionLabel) only ever shows up on rows whose text is actually\n * clipped.\n *\n * Rows are not individually tabbable: focus sits on the single tab stop above them \u2014 the filter input\n * (a combobox) where the search is shown, otherwise the listbox itself \u2014 and keyboard navigation is\n * driven from there by `aria-activedescendant` / arrow keys. `active` marks the row the arrow keys\n * have landed on so it can be highlighted and scrolled into view; the pointer path still toggles on\n * click / activates on hover.\n */\nexport function OptionRow({\n id,\n label,\n checked,\n active,\n disabled,\n onToggle,\n onActivate,\n optionItemClass,\n optionLabelWrapClass,\n optionLabelClass\n}: IOptionRowProps ): React.ReactElement {\n const { ref: labelRef, containerRef: labelWrapRef, isTruncated: isLabelTruncated } = useIsTruncated<HTMLSpanElement>();\n\n return (\n <div\n id={id}\n role="option"\n aria-selected={checked}\n aria-disabled={disabled}\n data-active={active || undefined}\n data-truncated={isLabelTruncated || undefined}\n className={optionItemClass}\n onClick={() => {\n if ( !disabled ) {\n onToggle();\n }\n }}\n onMouseMove={() => {\n if ( !disabled && !active ) {\n onActivate();\n }\n }}\n >\n {/* The row div owns the toggle; the checkbox is presentational (readOnly). */}\n <Checkbox checked={checked} disabled={disabled} readOnly tabIndex={-1} />\n <span ref={labelWrapRef} className={optionLabelWrapClass}>\n <span ref={labelRef} className={optionLabelClass}>{label}</span>\n </span>\n </div>\n );\n}\n'
|
|
2576
|
+
},
|
|
2492
2577
|
{
|
|
2493
2578
|
"name": "multiSelectTransferModal.tsx",
|
|
2494
2579
|
"content": `import * as React from "react";
|
|
@@ -2515,13 +2600,27 @@ interface IMultiSelectTransferModalProps {
|
|
|
2515
2600
|
reloadTooltip?: string;
|
|
2516
2601
|
onReload?: () => void;
|
|
2517
2602
|
isReloading?: boolean;
|
|
2603
|
+
/** Renders both panels' search inputs; forwarded straight to TransferList. */
|
|
2604
|
+
searchable?: boolean;
|
|
2518
2605
|
searchPlaceholder?: string;
|
|
2519
2606
|
availablePanelHeaderSlot?: React.ReactNode;
|
|
2520
2607
|
selectedPanelHeaderSlot?: React.ReactNode;
|
|
2521
2608
|
|
|
2522
|
-
|
|
2523
|
-
|
|
2524
|
-
|
|
2609
|
+
hasMoreAvailable?: boolean;
|
|
2610
|
+
onLoadMoreAvailable?: () => void;
|
|
2611
|
+
/** Loader (or error) REPLACES the available rows rather than appending below them. */
|
|
2612
|
+
isLoadingAvailable?: boolean;
|
|
2613
|
+
/** Loader appends below the available rows (a page fetch). */
|
|
2614
|
+
isLoadingMoreAvailable: boolean;
|
|
2615
|
+
availableLoadError?: React.ReactNode;
|
|
2616
|
+
availableLoadMoreError?: React.ReactNode;
|
|
2617
|
+
onRetryLoadMoreAvailable?: () => void;
|
|
2618
|
+
retryLabel?: string;
|
|
2619
|
+
/** Server-side total for the available panel. */
|
|
2620
|
+
availableTotalCount?: number;
|
|
2621
|
+
/** Set (async mode only) to drive the available panel's search server-side. */
|
|
2622
|
+
availableSearchTerm?: string;
|
|
2623
|
+
onAvailableSearchChange?: ( query: string ) => void;
|
|
2525
2624
|
|
|
2526
2625
|
cancelLabel: React.ReactNode;
|
|
2527
2626
|
doneLabel: React.ReactNode;
|
|
@@ -2545,12 +2644,21 @@ export function MultiSelectTransferModal({
|
|
|
2545
2644
|
reloadTooltip,
|
|
2546
2645
|
onReload,
|
|
2547
2646
|
isReloading,
|
|
2647
|
+
searchable,
|
|
2548
2648
|
searchPlaceholder,
|
|
2549
2649
|
availablePanelHeaderSlot,
|
|
2550
2650
|
selectedPanelHeaderSlot,
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2651
|
+
hasMoreAvailable,
|
|
2652
|
+
onLoadMoreAvailable,
|
|
2653
|
+
isLoadingAvailable,
|
|
2654
|
+
isLoadingMoreAvailable,
|
|
2655
|
+
availableLoadError,
|
|
2656
|
+
availableLoadMoreError,
|
|
2657
|
+
onRetryLoadMoreAvailable,
|
|
2658
|
+
retryLabel,
|
|
2659
|
+
availableTotalCount,
|
|
2660
|
+
availableSearchTerm,
|
|
2661
|
+
onAvailableSearchChange,
|
|
2554
2662
|
cancelLabel,
|
|
2555
2663
|
doneLabel
|
|
2556
2664
|
}: IMultiSelectTransferModalProps ): React.ReactElement {
|
|
@@ -2590,12 +2698,21 @@ export function MultiSelectTransferModal({
|
|
|
2590
2698
|
reloadTooltip={reloadTooltip}
|
|
2591
2699
|
onReload={onReload}
|
|
2592
2700
|
isReloading={isReloading}
|
|
2701
|
+
searchable={searchable}
|
|
2593
2702
|
searchPlaceholder={searchPlaceholder}
|
|
2594
2703
|
availablePanelHeaderSlot={availablePanelHeaderSlot}
|
|
2595
2704
|
selectedPanelHeaderSlot={selectedPanelHeaderSlot}
|
|
2596
|
-
hasMoreAvailable={
|
|
2597
|
-
onLoadMoreAvailable={
|
|
2598
|
-
isLoadingMoreAvailable={
|
|
2705
|
+
hasMoreAvailable={hasMoreAvailable}
|
|
2706
|
+
onLoadMoreAvailable={onLoadMoreAvailable}
|
|
2707
|
+
isLoadingMoreAvailable={isLoadingMoreAvailable}
|
|
2708
|
+
isLoadingAvailable={isLoadingAvailable}
|
|
2709
|
+
availableLoadError={availableLoadError}
|
|
2710
|
+
availableLoadMoreError={availableLoadMoreError}
|
|
2711
|
+
onRetryLoadMoreAvailable={onRetryLoadMoreAvailable}
|
|
2712
|
+
retryLabel={retryLabel}
|
|
2713
|
+
availableTotalCount={availableTotalCount}
|
|
2714
|
+
availableSearchTerm={availableSearchTerm}
|
|
2715
|
+
onAvailableSearchChange={onAvailableSearchChange}
|
|
2599
2716
|
/>
|
|
2600
2717
|
</div>
|
|
2601
2718
|
<div className="flex justify-end gap-3 px-6 py-4 bg-white border-t z-10 border-secondary-100 dark:bg-secondary-800 dark:border-secondary-500">
|
|
@@ -2612,438 +2729,25 @@ export function MultiSelectTransferModal({
|
|
|
2612
2729
|
MultiSelectTransferModal.displayName = "MultiSelectTransferModal";
|
|
2613
2730
|
`
|
|
2614
2731
|
},
|
|
2732
|
+
{
|
|
2733
|
+
"name": "multiSelectTransferDropdownHeader.tsx",
|
|
2734
|
+
"content": 'import * as React from "react";\n\nimport { ReloadButton } from "../button/reloadButton";\n\ninterface IMultiSelectTransferDropdownHeaderProps {\n /** tv() class for the strip itself, resolved by the dropdown that owns the variant config. */\n headerClass: string;\n /** tv() class for the search input. */\n filterInputClass: string;\n\n /** Renders the search input. With `false` the header holds only the reload affordance. */\n searchable: boolean;\n filterQuery: string;\n onFilterInput: ( e: React.ChangeEvent<HTMLInputElement> ) => void;\n onFilterKeyDown: ( e: React.KeyboardEvent<HTMLElement> ) => void;\n onFilterKeyUp: ( e: React.KeyboardEvent<HTMLElement> ) => void;\n onFilterBlur: ( e: React.FocusEvent<HTMLInputElement> ) => void;\n searchPlaceholder: string;\n\n /** The listbox this combobox drives, and the row its activedescendant points at. */\n listboxId: string;\n activeDescendant?: string;\n\n reloadTooltip?: string;\n onReload?: () => void;\n isReloading?: boolean;\n}\n\n/**\n * The chrome above the dropdown\'s option list: the search input \u2014 a combobox driving the listbox\n * below it through `aria-activedescendant` \u2014 and the optional reload button. With neither on screen\n * it renders nothing, so the rows start at the top of the dropdown rather than under an empty bar.\n */\nexport function MultiSelectTransferDropdownHeader({\n headerClass,\n filterInputClass,\n searchable,\n filterQuery,\n onFilterInput,\n onFilterKeyDown,\n onFilterKeyUp,\n onFilterBlur,\n searchPlaceholder,\n listboxId,\n activeDescendant,\n reloadTooltip,\n onReload,\n isReloading\n}: IMultiSelectTransferDropdownHeaderProps ): React.ReactElement | null {\n if ( !searchable && typeof onReload !== "function" ) {\n return null;\n }\n\n return (\n <div className={headerClass}>\n {searchable && (\n <input\n type="text"\n value={filterQuery}\n onChange={onFilterInput}\n onKeyDown={onFilterKeyDown}\n onKeyUp={onFilterKeyUp}\n onBlur={onFilterBlur}\n placeholder={searchPlaceholder}\n className={filterInputClass}\n role="combobox"\n aria-expanded="true"\n aria-controls={listboxId}\n aria-activedescendant={activeDescendant}\n aria-autocomplete="list"\n aria-label="Search options"\n autoFocus\n />\n )}\n <ReloadButton onReload={onReload} isReloading={isReloading} tooltip={reloadTooltip} />\n </div>\n );\n}\n\nMultiSelectTransferDropdownHeader.displayName = "MultiSelectTransferDropdownHeader";\n'
|
|
2735
|
+
},
|
|
2615
2736
|
{
|
|
2616
2737
|
"name": "multiSelectTransferDropdown.tsx",
|
|
2617
|
-
"content": 'import * as React from "react";\nimport { useId, useMemo, useRef } from "react";\nimport { cn } from "tailwind-variants";\n\nimport { useIsTruncated, useListboxKeyboardNav } from "@hooks";\nimport { Checkbox } from "../checkbox";\nimport { Loader } from "../loader";\nimport { ADPIcon, iconList } from "../adpIcon";\nimport { Button } from "../button";\nimport type { TTransferListValue } from "../transferList/types";\nimport { multiSelectTransferVariants } from "./multiSelectTransferVariants";\nimport type { TMultiSelectTransferOption, TMultiSelectTransferSize } from "./types";\n\n// Past this many rows the options list is windowed (virtualized) instead of fully rendered, so a\n// very large option set doesn\'t mount thousands of rows (each with its own ResizeObserver).\nconst VIRTUALIZE_THRESHOLD = 100;\n// Approximate row height (px) used before rows are measured; measureElement corrects it.\nconst ESTIMATED_OPTION_HEIGHT = 40;\n\ninterface IOptionRowProps {\n id: string;\n label: React.ReactNode;\n checked: boolean;\n active: boolean;\n disabled?: boolean;\n onToggle: () => void;\n onActivate: () => void;\n optionItemClass: string | undefined;\n optionLabelWrapClass: string;\n optionLabelClass: string;\n}\n\n/**\n * A single dropdown row (both "Select All" and regular options): checkbox + label. Measures\n * its own label via `useIsTruncated` so the hover/focus expand affordance (see\n * multiSelectTransferVariants\' optionLabel) only ever shows up on rows whose text is actually\n * clipped.\n *\n * Rows are not individually tabbable: focus stays on the filter input (a combobox) and keyboard\n * navigation is driven by `aria-activedescendant` / arrow keys from there (mirroring the Select\n * component). `active` marks the row the arrow keys have landed on so it can be highlighted and\n * scrolled into view; the pointer path still toggles on click / activates on hover.\n */\nfunction OptionRow({\n id,\n label,\n checked,\n active,\n disabled,\n onToggle,\n onActivate,\n optionItemClass,\n optionLabelWrapClass,\n optionLabelClass\n}: IOptionRowProps ): React.ReactElement {\n const { ref: labelRef, containerRef: labelWrapRef, isTruncated: isLabelTruncated } = useIsTruncated<HTMLSpanElement>();\n\n return (\n <div\n id={id}\n role="option"\n aria-selected={checked}\n aria-disabled={disabled}\n data-active={active || undefined}\n data-truncated={isLabelTruncated || undefined}\n className={optionItemClass}\n onClick={() => {\n if ( !disabled ) {\n onToggle();\n }\n }}\n onMouseMove={() => {\n if ( !disabled && !active ) {\n onActivate();\n }\n }}\n >\n {/* The row div owns the toggle; the checkbox is presentational (readOnly). */}\n <Checkbox checked={checked} disabled={disabled} readOnly tabIndex={-1} />\n <span ref={labelWrapRef} className={optionLabelWrapClass}>\n <span ref={labelRef} className={optionLabelClass}>{label}</span>\n </span>\n </div>\n );\n}\n\n/** A navigable row in the dropdown: the optional "Select All" pseudo-row or a real option. */\ntype TDropdownRow =\n | { kind: "select-all" }\n | { kind: "option"; option: TMultiSelectTransferOption };\n\ninterface IMultiSelectTransferDropdownProps {\n error?: boolean;\n size: TMultiSelectTransferSize;\n disabled?: boolean;\n\n filterQuery: string;\n onFilterInput: ( e: React.ChangeEvent<HTMLInputElement> ) => void;\n onFilterKeyDown: ( e: React.KeyboardEvent<HTMLInputElement> ) => void;\n searchPlaceholder: string;\n\n options: TMultiSelectTransferOption[];\n selectedValues: Set<TTransferListValue>;\n onOptionToggle: ( option: TMultiSelectTransferOption ) => void;\n\n hasSelectAll: boolean;\n areAllSelected: boolean;\n onSelectAll: () => void;\n\n isLoading?: boolean;\n sentinelRef: React.RefObject<HTMLDivElement>;\n\n reloadTooltip?: string;\n onReload?: () => void;\n isReloading?: boolean;\n}\n\n/**\n * The open-state dropdown for MultiSelectTransfer: a search input, an optional "Select All"\n * row, the (draft-checked) option list, and the infinite-scroll sentinel.\n */\nexport function MultiSelectTransferDropdown({\n error,\n size,\n disabled,\n filterQuery,\n onFilterInput,\n onFilterKeyDown,\n searchPlaceholder,\n options,\n selectedValues,\n onOptionToggle,\n hasSelectAll,\n areAllSelected,\n onSelectAll,\n isLoading,\n sentinelRef,\n reloadTooltip,\n onReload,\n isReloading\n}: IMultiSelectTransferDropdownProps ): React.ReactElement {\n const {\n dropdownContainer,\n dropdownHeader,\n filterInput,\n optionsList,\n optionItem,\n optionLabelWrap,\n optionLabel\n } = multiSelectTransferVariants({ error, size, disabled });\n\n const listboxId = useId();\n const listRef = useRef<HTMLDivElement>( null );\n\n // Flat list of navigable rows in render order: the "Select All" pseudo-row (if shown) followed\n // by the options. Drives arrow-key navigation and aria-activedescendant.\n const rows = useMemo<TDropdownRow[]>(\n () => [\n ...( hasSelectAll ? [{ kind: "select-all" as const }] : []),\n ...options.map(( option ) => ({ kind: "option" as const, option }))\n ],\n [ hasSelectAll, options ]\n );\n\n const isRowDisabled = ( row: TDropdownRow ): boolean =>\n row.kind === "option" && Boolean( row.option.isDisabled );\n\n const rowId = ( index: number ): string => `${listboxId}-row-${index}`;\n\n // A stable key for the current option set, so the active row resets to the first selectable\n // row only when the list actually changes (e.g. after filtering) - not on every re-render,\n // which would fight the user\'s arrow-key position. Memoized so it recomputes only with `rows`.\n const rowsKey = useMemo(\n () => rows.map(( r ) => ( r.kind === "option" ? r.option.value : "select-all" )).join( "\\n" ),\n [rows]\n );\n\n // Windowing kicks in only past the threshold; below it every row renders as before. The\n // virtualizer scroll element is the options list itself (max-h-60 overflow-y-auto).\n const {\n activeIndex,\n setActiveIndex,\n moveActive,\n firstEnabledIndex,\n virtualizer: rowVirtualizer,\n shouldVirtualize\n } = useListboxKeyboardNav({\n itemCount: rows.length,\n isItemDisabled: ( index ) => isRowDisabled( rows[index]),\n resetKey: rowsKey,\n scrollElementRef: listRef,\n optionId: rowId,\n estimateSize: ESTIMATED_OPTION_HEIGHT,\n virtualizeThreshold: VIRTUALIZE_THRESHOLD\n });\n\n const activateRow = ( index: number ) => {\n const row = rows[index];\n if ( !row ) {\n return;\n }\n if ( row.kind === "select-all" ) {\n onSelectAll();\n } else if ( !row.option.isDisabled ) {\n onOptionToggle( row.option );\n }\n };\n\n // Filter-input keydown: own the option-navigation keys (matching the Select component\'s\n // Arrow/Enter forwarding) and delegate Escape/Tab (cancel/commit) to the parent handler.\n // Everything else (typing) falls through to the input\'s onChange.\n const handleKeyDown = ( e: React.KeyboardEvent<HTMLInputElement> ) => {\n switch ( e.key ) {\n case "ArrowDown":\n e.preventDefault();\n moveActive( 1 );\n break;\n case "ArrowUp":\n e.preventDefault();\n moveActive( -1 );\n break;\n case "Home":\n e.preventDefault();\n setActiveIndex( firstEnabledIndex( 0, 1 ));\n break;\n case "End":\n e.preventDefault();\n setActiveIndex( firstEnabledIndex( rows.length - 1, -1 ));\n break;\n case "Enter":\n e.preventDefault();\n activateRow( activeIndex );\n break;\n default:\n onFilterKeyDown( e );\n }\n };\n\n const activeDescendant = activeIndex >= 0 && rows.length > 0 ? rowId( activeIndex ) : undefined;\n\n const rowKey = ( row: TDropdownRow ): string | number => ( row.kind === "option" ? row.option.value : "select-all" );\n\n // Shared row renderer so the windowed and full-render paths produce identical rows.\n const renderRow = ( row: TDropdownRow, index: number ): React.ReactElement => {\n const isActive = index === activeIndex;\n const activeClass = isActive && "bg-frostBlue dark:bg-secondary-800";\n if ( row.kind === "select-all" ) {\n return (\n <OptionRow\n key="select-all"\n id={rowId( index )}\n label="Select All"\n checked={areAllSelected}\n active={isActive}\n onToggle={onSelectAll}\n onActivate={() => setActiveIndex( index )}\n optionItemClass={cn( optionItem({ checked: areAllSelected }), activeClass )}\n optionLabelWrapClass={optionLabelWrap()}\n optionLabelClass={optionLabel()}\n />\n );\n }\n const opt = row.option;\n const isChecked = selectedValues.has( opt.value );\n return (\n <OptionRow\n key={opt.value}\n id={rowId( index )}\n label={opt.label}\n checked={isChecked}\n active={isActive}\n disabled={opt.isDisabled}\n onToggle={() => onOptionToggle( opt )}\n onActivate={() => setActiveIndex( index )}\n optionItemClass={cn(\n optionItem({ checked: isChecked }),\n !opt.isDisabled && activeClass,\n opt.isDisabled && "opacity-50 cursor-not-allowed"\n )}\n optionLabelWrapClass={optionLabelWrap()}\n optionLabelClass={optionLabel()}\n />\n );\n };\n\n return (\n <div className={dropdownContainer()}>\n <div className={dropdownHeader()}>\n <input\n type="text"\n value={filterQuery}\n onChange={onFilterInput}\n onKeyDown={handleKeyDown}\n placeholder={searchPlaceholder}\n className={filterInput()}\n role="combobox"\n aria-expanded="true"\n aria-controls={listboxId}\n aria-activedescendant={activeDescendant}\n aria-autocomplete="list"\n aria-label="Search options"\n autoFocus\n />\n\n {typeof onReload === "function" && (\n <Button\n variant="shade"\n color="secondary"\n className="p-1"\n size="sm"\n onClick={onReload}\n disabled={isReloading}\n tooltip={reloadTooltip}\n aria-label={reloadTooltip}\n >\n <ADPIcon icon={iconList.reload} size="xs" spin={isReloading} />\n </Button>\n )}\n </div>\n\n <div ref={listRef} id={listboxId} className={optionsList()} role="listbox" aria-multiselectable="true">\n {shouldVirtualize ? (\n <div className="relative w-full" style={{ height: rowVirtualizer.getTotalSize() }}>\n {rowVirtualizer.getVirtualItems().map(( virtualRow ) => (\n <div\n key={rowKey( rows[virtualRow.index])}\n data-index={virtualRow.index}\n ref={rowVirtualizer.measureElement}\n className="absolute inset-x-0 top-0"\n style={{ transform: `translateY(${virtualRow.start}px)` }}\n >\n {renderRow( rows[virtualRow.index], virtualRow.index )}\n </div>\n ))}\n {/* Sentinel pinned to the bottom of the full scroll height. */}\n <div ref={sentinelRef} className="absolute bottom-0 h-px w-px" aria-hidden="true" />\n </div>\n ) : (\n <>\n {rows.map(( row, index ) => renderRow( row, index ))}\n {/* Infinite scroll sentinel */}\n <div ref={sentinelRef} className="h-px" aria-hidden="true" />\n </>\n )}\n\n {isLoading && (\n <div className="flex justify-center py-3" role="status" aria-label="Loading">\n <Loader size="sm" />\n </div>\n )}\n </div>\n </div>\n );\n}\n\nMultiSelectTransferDropdown.displayName = "MultiSelectTransferDropdown";\n'
|
|
2738
|
+
"content": 'import * as React from "react";\nimport { useEffect, useId, useMemo, useRef } from "react";\nimport { cn } from "tailwind-variants";\n\nimport { Loader } from "../loader";\nimport { Button } from "../button";\n\nimport { useListboxKeyboardNav, type TSentinelRef } from "@hooks";\nimport { keyboardKeys } from "@constants";\nimport type { TTransferListValue } from "../transferList/types";\nimport { MultiSelectTransferDropdownHeader } from "./multiSelectTransferDropdownHeader";\nimport { OptionRow } from "./multiSelectTransferOptionRow";\nimport { multiSelectTransferVariants } from "./multiSelectTransferVariants";\nimport type { TMultiSelectTransferOption, TMultiSelectTransferSize } from "./types";\n\n// Past this many rows the options list is windowed (virtualized) instead of fully rendered, so a\n// very large option set doesn\'t mount thousands of rows (each with its own ResizeObserver).\nconst VIRTUALIZE_THRESHOLD = 100;\n// Approximate row height (px) used before rows are measured; measureElement corrects it.\nconst ESTIMATED_OPTION_HEIGHT = 40;\n// Keys blocked during search fetch (see handleKeyDown).\nconst navigationKeys = new Set([\n keyboardKeys.arrowDown,\n keyboardKeys.arrowUp,\n keyboardKeys.home,\n keyboardKeys.end,\n keyboardKeys.enter\n]);\n\n/** A navigable row in the dropdown: the optional "Select All" pseudo-row or a real option. */\ntype TDropdownRow =\n | { kind: "select-all" }\n | { kind: "option"; option: TMultiSelectTransferOption };\n\ninterface IMultiSelectTransferDropdownProps {\n error?: boolean;\n size: TMultiSelectTransferSize;\n disabled?: boolean;\n\n /** Renders the in-dropdown search input. With `false` the option list itself owns focus. */\n searchable: boolean;\n filterQuery: string;\n onFilterInput: ( e: React.ChangeEvent<HTMLInputElement> ) => void;\n onFilterKeyDown: ( e: React.KeyboardEvent<HTMLElement> ) => void;\n onFilterKeyUp: ( e: React.KeyboardEvent<HTMLElement> ) => void;\n onFilterBlur: ( e: React.FocusEvent<HTMLInputElement> ) => void;\n searchPlaceholder: string;\n\n /** Readonly so the option source\'s pool can be passed through without a defensive copy. */\n options: readonly TMultiSelectTransferOption[];\n selectedValues: Set<TTransferListValue>;\n onOptionToggle: ( option: TMultiSelectTransferOption ) => void;\n\n hasSelectAll: boolean;\n areAllSelected: boolean;\n onSelectAll: () => void;\n\n /** Any load in flight; renders the loader row below the list. */\n isLoading?: boolean;\n /**\n * Loader (or error) takes the rows\' place rather than appending below them. Required, and supplied\n * by the option source rather than re-derived here, so the hook is the single source of this\n * predicate \u2014 two components deriving it differently is how they drifted.\n */\n isSearchFetch: boolean;\n sentinelRef: TSentinelRef;\n\n /** Replaces the rows when set: the whole list failed to load. */\n loadError?: React.ReactNode;\n /** Shown below the loaded rows when a page append failed. */\n loadMoreError?: React.ReactNode;\n /** Fired by the retry button beside `loadMoreError`. */\n onRetryLoadMore?: () => void;\n retryLabel?: string;\n\n reloadTooltip?: string;\n onReload?: () => void;\n isReloading?: boolean;\n}\n\n/**\n * The open-state dropdown for MultiSelectTransfer: an optional search input, an optional "Select All"\n * row, the (draft-checked) option list, and the infinite-scroll sentinel.\n */\nexport function MultiSelectTransferDropdown({\n error,\n size,\n disabled,\n searchable,\n filterQuery,\n onFilterInput,\n onFilterKeyDown,\n onFilterKeyUp,\n onFilterBlur,\n searchPlaceholder,\n options,\n selectedValues,\n onOptionToggle,\n hasSelectAll,\n areAllSelected,\n onSelectAll,\n isLoading,\n isSearchFetch,\n sentinelRef,\n loadError,\n loadMoreError,\n onRetryLoadMore,\n retryLabel = "Retry",\n reloadTooltip,\n onReload,\n isReloading\n}: IMultiSelectTransferDropdownProps ): React.ReactElement {\n const {\n dropdownContainer,\n optionsList,\n optionsListbox,\n noOptionsMessage,\n loaderRow,\n errorMessage,\n loadMoreErrorRow,\n optionItem,\n optionLabelWrap,\n optionLabel,\n dropdownHeader,\n filterInput\n } = multiSelectTransferVariants({ error, size, disabled, searchable });\n\n const listboxId = useId();\n const listRef = useRef<HTMLDivElement>( null );\n const listboxRef = useRef<HTMLDivElement>( null );\n\n // The error occupies the loader\'s slot, so it inherits the same nav-key and activedescendant gate.\n const areRowsReplaced = isSearchFetch === true || loadError !== undefined;\n\n // Flat list of navigable rows in render order: the "Select All" pseudo-row (if shown) followed\n // by the options. Drives arrow-key navigation and aria-activedescendant.\n const rows = useMemo<TDropdownRow[]>(\n () => [\n ...( hasSelectAll ? [{ kind: "select-all" as const }] : []),\n ...options.map(( option ) => ({ kind: "option" as const, option }))\n ],\n [ hasSelectAll, options ]\n );\n\n const isRowDisabled = ( row: TDropdownRow ): boolean =>\n row.kind === "option" && Boolean( row.option.isDisabled );\n\n const rowId = ( index: number ): string => `${listboxId}-row-${index}`;\n\n // A stable key for the current option set, so the active row resets to the first selectable\n // row only when the list actually changes (e.g. after filtering) - not on every re-render,\n // which would fight the user\'s arrow-key position. Memoized so it recomputes only with `rows`.\n const rowsKey = useMemo(\n () => rows.map(( r ) => ( r.kind === "option" ? r.option.value : "select-all" )).join( "\\n" ),\n [rows]\n );\n\n // Windowing kicks in only past the threshold; below it every row renders directly (no\n // virtualization). The virtualizer scroll element is the options list itself (max-h-60 overflow-y-auto).\n const {\n activeIndex,\n setActiveIndex,\n moveActive,\n firstEnabledIndex,\n virtualizer: rowVirtualizer,\n shouldVirtualize\n } = useListboxKeyboardNav({\n itemCount: rows.length,\n isItemDisabled: ( index ) => isRowDisabled( rows[index]),\n resetKey: rowsKey,\n scrollElementRef: listRef,\n optionId: rowId,\n estimateSize: ESTIMATED_OPTION_HEIGHT,\n virtualizeThreshold: VIRTUALIZE_THRESHOLD\n });\n\n const activateRow = ( index: number ) => {\n const row = rows[index];\n if ( !row ) {\n return;\n }\n if ( row.kind === "select-all" ) {\n onSelectAll();\n } else if ( !row.option.isDisabled ) {\n onOptionToggle( row.option );\n }\n };\n\n // Nav keys handled here; Escape/Tab/delete-hold delegated to parent.\n const handleKeyDown = ( e: React.KeyboardEvent<HTMLElement> ) => {\n // Space activates the active row only while the list owns focus. With the search input present it\n // is a literal character in the query and has to reach the input untouched.\n const isActivateKey = e.key === keyboardKeys.enter || ( !searchable && e.key === keyboardKeys.space );\n // Ignore nav keys during search fetch \u2014 stale rows still in memory.\n if ( areRowsReplaced && ( navigationKeys.has( e.key ) || isActivateKey )) {\n e.preventDefault();\n return;\n }\n if ( isActivateKey ) {\n e.preventDefault();\n activateRow( activeIndex );\n return;\n }\n switch ( e.key ) {\n case keyboardKeys.arrowDown:\n e.preventDefault();\n moveActive( 1 );\n break;\n case keyboardKeys.arrowUp:\n e.preventDefault();\n moveActive( -1 );\n break;\n case keyboardKeys.home:\n e.preventDefault();\n setActiveIndex( firstEnabledIndex( 0, 1 ));\n break;\n case keyboardKeys.end:\n e.preventDefault();\n setActiveIndex( firstEnabledIndex( rows.length - 1, -1 ));\n break;\n default:\n onFilterKeyDown( e );\n }\n };\n\n // Dropped while the rows are unmounted, so it never points at an id that has left the DOM.\n const activeDescendant =\n !areRowsReplaced && activeIndex >= 0 && rows.length > 0 ? rowId( activeIndex ) : undefined;\n\n // With no search input to autofocus, the list is what the dropdown opens onto: a keyboard user has\n // to land on something that answers the arrow keys, and the trigger behind the open dropdown answers\n // only Escape. The dropdown mounts on open, so this runs once per open.\n useEffect(() => {\n if ( !searchable ) {\n listboxRef.current?.focus();\n }\n }, [searchable]);\n\n // Everything the search input carries as the focused widget \u2014 the tab stop, the activedescendant\n // cursor and the nav-key handler \u2014 sits on the listbox instead when the input is hidden. The\n // combobox role does not move with them: without a text box there is no combobox, which leaves the\n // focused-listbox shape each TransferList panel already uses. The tab stop stays even with no rows,\n // so Escape is never stranded on an empty or loading list.\n const listboxFocusProps: React.HTMLAttributes<HTMLDivElement> = searchable\n ? {}\n : {\n tabIndex: 0,\n "aria-label": "Options",\n "aria-activedescendant": activeDescendant,\n onKeyDown: handleKeyDown\n };\n\n const rowKey = ( row: TDropdownRow ): string | number => ( row.kind === "option" ? row.option.value : "select-all" );\n\n // Shared row renderer so the windowed and full-render paths produce identical rows.\n const renderRow = ( row: TDropdownRow, index: number ): React.ReactElement => {\n const isActive = index === activeIndex;\n const activeClass = isActive && "bg-frostBlue dark:bg-secondary-800";\n if ( row.kind === "select-all" ) {\n return (\n <OptionRow\n key="select-all"\n id={rowId( index )}\n label="Select All"\n checked={areAllSelected}\n active={isActive}\n onToggle={onSelectAll}\n onActivate={() => setActiveIndex( index )}\n optionItemClass={cn( optionItem({ checked: areAllSelected }), activeClass )}\n optionLabelWrapClass={optionLabelWrap()}\n optionLabelClass={optionLabel()}\n />\n );\n }\n const opt = row.option;\n const isChecked = selectedValues.has( opt.value );\n return (\n <OptionRow\n key={opt.value}\n id={rowId( index )}\n label={opt.label}\n checked={isChecked}\n active={isActive}\n disabled={opt.isDisabled}\n onToggle={() => onOptionToggle( opt )}\n onActivate={() => setActiveIndex( index )}\n optionItemClass={cn(\n optionItem({ checked: isChecked }),\n !opt.isDisabled && activeClass,\n opt.isDisabled && "opacity-50 cursor-not-allowed"\n )}\n optionLabelWrapClass={optionLabelWrap()}\n optionLabelClass={optionLabel()}\n />\n );\n };\n\n // Lazy fn avoids virtualizer/measure work on loader-only renders.\n const renderOptionRows = (): React.ReactNode => ( shouldVirtualize ? (\n <div className="relative w-full" style={{ height: rowVirtualizer.getTotalSize() }}>\n {rowVirtualizer.getVirtualItems().map(( virtualRow ) => (\n <div\n key={rowKey( rows[virtualRow.index])}\n data-index={virtualRow.index}\n ref={rowVirtualizer.measureElement}\n className="absolute inset-x-0 top-0"\n style={{ transform: `translateY(${virtualRow.start}px)` }}\n >\n {renderRow( rows[virtualRow.index], virtualRow.index )}\n </div>\n ))}\n {/* Sentinel pinned to the bottom of the full scroll height. */}\n <div ref={sentinelRef} className="absolute bottom-0 h-px w-px" aria-hidden="true" />\n </div>\n ) : (\n <>\n {rows.map(( row, index ) => renderRow( row, index ))}\n {/* Infinite scroll sentinel */}\n <div ref={sentinelRef} className="h-px" aria-hidden="true" />\n </>\n ));\n\n return (\n <div className={dropdownContainer()}>\n <MultiSelectTransferDropdownHeader\n headerClass={dropdownHeader()}\n filterInputClass={filterInput()}\n searchable={searchable}\n filterQuery={filterQuery}\n onFilterInput={onFilterInput}\n onFilterKeyDown={handleKeyDown}\n onFilterKeyUp={onFilterKeyUp}\n onFilterBlur={onFilterBlur}\n searchPlaceholder={searchPlaceholder}\n listboxId={listboxId}\n activeDescendant={activeDescendant}\n reloadTooltip={reloadTooltip}\n onReload={onReload}\n isReloading={isReloading}\n />\n\n {/* Outer scroll: loader/error/empty sit outside listbox (not valid listbox children). */}\n <div ref={listRef} className={optionsList()}>\n <div\n ref={listboxRef}\n id={listboxId}\n role="listbox"\n aria-multiselectable="true"\n aria-busy={isLoading}\n className={optionsListbox()}\n {...listboxFocusProps}\n >\n {!areRowsReplaced && options.length > 0 && renderOptionRows()}\n </div>\n {/* role="alert" is assertive: the user\'s action did not do what they asked. */}\n {loadError !== undefined && (\n <div className={errorMessage()} role="alert">{loadError}</div>\n )}\n {!areRowsReplaced && options.length === 0 && (\n <div className={noOptionsMessage()}>No options</div>\n )}\n {/* A failed page append keeps the rows and offers Retry. Only this button retries, so a\n sentinel that never left the viewport cannot hammer a failing endpoint. */}\n {loadMoreError !== undefined && (\n <div className={loadMoreErrorRow()} role="alert">\n <span>{loadMoreError}</span>\n {typeof onRetryLoadMore === "function" && (\n <Button size="xs" variant="outline" color="secondary" onClick={onRetryLoadMore}>\n {retryLabel}\n </Button>\n )}\n </div>\n )}\n {isLoading && (\n <div className={loaderRow()} role="status" aria-label="Loading">\n <Loader size="sm" />\n </div>\n )}\n </div>\n </div>\n );\n}\n\nMultiSelectTransferDropdown.displayName = "MultiSelectTransferDropdown";\n'
|
|
2618
2739
|
},
|
|
2619
2740
|
{
|
|
2620
2741
|
"name": "multiSelectTransfer.tsx",
|
|
2621
|
-
"content": `import * as React from "react";
|
|
2622
|
-
import { useState, useRef, useEffect, useId, useCallback, useMemo } from "react";
|
|
2623
|
-
|
|
2624
|
-
import { useDebouncedCallback, useInfiniteScroll } from "@hooks";
|
|
2625
|
-
import { ADPIcon, iconList } from "../adpIcon";
|
|
2626
|
-
import { matchesQuery } from "@utils";
|
|
2627
|
-
import { MultiSelectTransferDropdown } from "./multiSelectTransferDropdown";
|
|
2628
|
-
import { MultiSelectTransferPill } from "./multiSelectTransferPill";
|
|
2629
|
-
import { MultiSelectTransferModal } from "./multiSelectTransferModal";
|
|
2630
|
-
import { multiSelectTransferVariants } from "./multiSelectTransferVariants";
|
|
2631
|
-
import {
|
|
2632
|
-
EMultiSelectTransferSizes,
|
|
2633
|
-
type TMultiSelectTransferOption,
|
|
2634
|
-
type IMultiSelectTransferProps
|
|
2635
|
-
} from "./types";
|
|
2636
|
-
|
|
2637
|
-
export function MultiSelectTransfer({
|
|
2638
|
-
id,
|
|
2639
|
-
className,
|
|
2640
|
-
label,
|
|
2641
|
-
placeholder = "Select options...",
|
|
2642
|
-
helperText,
|
|
2643
|
-
error = false,
|
|
2644
|
-
disabled = false,
|
|
2645
|
-
size = EMultiSelectTransferSizes.MD,
|
|
2646
|
-
options,
|
|
2647
|
-
value,
|
|
2648
|
-
onChange,
|
|
2649
|
-
filterValue,
|
|
2650
|
-
onFilterChange,
|
|
2651
|
-
searchPlaceholder = "Search...",
|
|
2652
|
-
filterDebounceMs = 300,
|
|
2653
|
-
hasMore = false,
|
|
2654
|
-
onLoadMore,
|
|
2655
|
-
isLoading = false,
|
|
2656
|
-
maxVisiblePills = 3,
|
|
2657
|
-
transferListTitle,
|
|
2658
|
-
transferListSubtitle,
|
|
2659
|
-
transferListHeader,
|
|
2660
|
-
onOpenTransferList,
|
|
2661
|
-
reorderable = false,
|
|
2662
|
-
reloadTooltip = "Reload",
|
|
2663
|
-
onReload,
|
|
2664
|
-
isReloading = false,
|
|
2665
|
-
availablePanelHeaderSlot,
|
|
2666
|
-
selectedPanelHeaderSlot,
|
|
2667
|
-
cancelLabel = "Cancel",
|
|
2668
|
-
doneLabel = "Done"
|
|
2669
|
-
}: IMultiSelectTransferProps ): React.ReactElement {
|
|
2670
|
-
const [ isOpen, setIsOpen ] = useState( false );
|
|
2671
|
-
const [ pendingSelected, setPendingSelected ] = useState<TMultiSelectTransferOption[]>([]);
|
|
2672
|
-
const [ filterQuery, setFilterQuery ] = useState( filterValue ?? "" );
|
|
2673
|
-
const [ isModalOpen, setIsModalOpen ] = useState( false );
|
|
2674
|
-
// Draft state for the transfer-list modal, committed on Done / discarded on Cancel.
|
|
2675
|
-
const [ transferAvailable, setTransferAvailable ] = useState<TMultiSelectTransferOption[]>([]);
|
|
2676
|
-
const [ transferSelected, setTransferSelected ] = useState<TMultiSelectTransferOption[]>([]);
|
|
2677
|
-
|
|
2678
|
-
// Committed selection shown as pills in the trigger. When the consumer passes \`value\` the
|
|
2679
|
-
// component is controlled and this tracks it; otherwise (uncontrolled) we own it internally
|
|
2680
|
-
// and update it on commit so chips still render without a parent wiring up onChange.
|
|
2681
|
-
const isControlled = value !== undefined;
|
|
2682
|
-
const [ internalValue, setInternalValue ] = useState<TMultiSelectTransferOption[]>( value ?? []);
|
|
2683
|
-
const currentValue = isControlled ? value : internalValue;
|
|
2684
|
-
|
|
2685
|
-
const containerRef = useRef<HTMLDivElement>( null );
|
|
2686
|
-
const triggerRef = useRef<HTMLDivElement>( null );
|
|
2687
|
-
const generatedId = useId();
|
|
2688
|
-
const triggerId = id ?? generatedId;
|
|
2689
|
-
|
|
2690
|
-
// Debounced bridge to the consumer's onFilterChange (server-side filtering). filterDebounceMs=0
|
|
2691
|
-
// fires synchronously; the pending timer is cancelled on unmount and on an external reset.
|
|
2692
|
-
const { call: debouncedFilterChange, cancel: cancelFilterChange } = useDebouncedCallback(
|
|
2693
|
-
( query: string ) => onFilterChange?.( query ),
|
|
2694
|
-
filterDebounceMs
|
|
2695
|
-
);
|
|
2696
|
-
|
|
2697
|
-
// Sync controlled filterValue from parent. Cancel any in-flight debounced callback so a
|
|
2698
|
-
// stale query can't fire onFilterChange after the parent has intentionally reset the value.
|
|
2699
|
-
useEffect(() => {
|
|
2700
|
-
if ( filterValue !== undefined ) {
|
|
2701
|
-
cancelFilterChange();
|
|
2702
|
-
setFilterQuery( filterValue );
|
|
2703
|
-
}
|
|
2704
|
-
}, [ filterValue, cancelFilterChange ]);
|
|
2705
|
-
|
|
2706
|
-
// Keep the pending (draft) selection in sync when the parent changes \`value\` while the
|
|
2707
|
-
// dropdown is open. Keyed on the values' contents (not the array reference) so an unrelated
|
|
2708
|
-
// parent re-render passing a new array can't wipe the user's in-progress draft; it fires
|
|
2709
|
-
// only on a real external change or when the dropdown (re)opens.
|
|
2710
|
-
const valueRef = useRef( currentValue );
|
|
2711
|
-
valueRef.current = currentValue;
|
|
2712
|
-
const valueKey = useMemo(() => currentValue.map(( o ) => o.value ).join( "\\n" ), [currentValue]);
|
|
2713
|
-
useEffect(() => {
|
|
2714
|
-
if ( isOpen ) {
|
|
2715
|
-
setPendingSelected( valueRef.current );
|
|
2716
|
-
}
|
|
2717
|
-
}, [ valueKey, isOpen ]);
|
|
2718
|
-
|
|
2719
|
-
// Keep the latest draft in a ref so the outside-click listener can commit it without
|
|
2720
|
-
// re-subscribing on every toggle.
|
|
2721
|
-
const pendingSelectedRef = useRef( pendingSelected );
|
|
2722
|
-
pendingSelectedRef.current = pendingSelected;
|
|
2723
|
-
|
|
2724
|
-
// Commit the pending (draft) selection and close the dropdown. Used by outside-click and
|
|
2725
|
-
// by toggling the trigger closed.
|
|
2726
|
-
const commitSelection = useCallback(() => {
|
|
2727
|
-
if ( !isControlled ) {
|
|
2728
|
-
setInternalValue( pendingSelectedRef.current );
|
|
2729
|
-
}
|
|
2730
|
-
onChange?.( pendingSelectedRef.current );
|
|
2731
|
-
setIsOpen( false );
|
|
2732
|
-
setPendingSelected([]);
|
|
2733
|
-
setFilterQuery( "" );
|
|
2734
|
-
}, [ onChange, isControlled ]);
|
|
2735
|
-
|
|
2736
|
-
// Infinite-scroll sentinel for the dropdown options list (gated on the open state).
|
|
2737
|
-
const sentinelRef = useInfiniteScroll({ hasMore, isLoading, onLoadMore, enabled: isOpen });
|
|
2738
|
-
|
|
2739
|
-
// Close dropdown on outside click and commit the pending selection. Disabled while the
|
|
2740
|
-
// transfer-list modal is open: the modal renders in a body portal (outside containerRef),
|
|
2741
|
-
// so a click inside it would otherwise be treated as an outside click and close the dropdown.
|
|
2742
|
-
useEffect(() => {
|
|
2743
|
-
const handleOutsideClick = ( e: MouseEvent ) => {
|
|
2744
|
-
if ( containerRef.current && !containerRef.current.contains( e.target as Node )) {
|
|
2745
|
-
commitSelection();
|
|
2746
|
-
}
|
|
2747
|
-
};
|
|
2748
|
-
if ( isOpen && !isModalOpen ) {
|
|
2749
|
-
document.addEventListener( "mousedown", handleOutsideClick );
|
|
2750
|
-
}
|
|
2751
|
-
return () => document.removeEventListener( "mousedown", handleOutsideClick );
|
|
2752
|
-
}, [ isOpen, isModalOpen, commitSelection ]);
|
|
2753
|
-
|
|
2754
|
-
// While the transfer-list modal is open, fold newly loaded options (from paginated onLoadMore)
|
|
2755
|
-
// into the available draft. Only options absent from BOTH draft panels are appended, so items
|
|
2756
|
-
// the user has already moved to Selected are never duplicated or yanked back. On a plain move
|
|
2757
|
-
// there are no additions, so this is a no-op.
|
|
2758
|
-
useEffect(() => {
|
|
2759
|
-
if ( !isModalOpen ) {
|
|
2760
|
-
return;
|
|
2761
|
-
}
|
|
2762
|
-
setTransferAvailable(( prev ) => {
|
|
2763
|
-
const known = new Set([ ...prev, ...transferSelected ].map(( o ) => o.value ));
|
|
2764
|
-
const additions = options.filter(( o ) => !known.has( o.value ));
|
|
2765
|
-
return additions.length ? [ ...prev, ...additions ] : prev;
|
|
2766
|
-
});
|
|
2767
|
-
}, [ options, isModalOpen, transferSelected ]);
|
|
2768
|
-
|
|
2769
|
-
const handleFilterInput = useCallback(
|
|
2770
|
-
( e: React.ChangeEvent<HTMLInputElement> ) => {
|
|
2771
|
-
const query = e.target.value;
|
|
2772
|
-
setFilterQuery( query );
|
|
2773
|
-
debouncedFilterChange( query );
|
|
2774
|
-
},
|
|
2775
|
-
[debouncedFilterChange]
|
|
2776
|
-
);
|
|
2777
|
-
|
|
2778
|
-
const handleTriggerClick = () => {
|
|
2779
|
-
if ( disabled ) {
|
|
2780
|
-
return;
|
|
2781
|
-
}
|
|
2782
|
-
if ( isOpen ) {
|
|
2783
|
-
commitSelection();
|
|
2784
|
-
} else {
|
|
2785
|
-
setPendingSelected( currentValue );
|
|
2786
|
-
setIsOpen( true );
|
|
2787
|
-
}
|
|
2788
|
-
};
|
|
2789
|
-
|
|
2790
|
-
// Discard the in-progress draft, close the dropdown, and return focus to the trigger so a
|
|
2791
|
-
// keyboard user is never stranded on <body>.
|
|
2792
|
-
const cancelDropdown = () => {
|
|
2793
|
-
setIsOpen( false );
|
|
2794
|
-
setPendingSelected([]);
|
|
2795
|
-
setFilterQuery( "" );
|
|
2796
|
-
triggerRef.current?.focus();
|
|
2797
|
-
};
|
|
2798
|
-
|
|
2799
|
-
const handleTriggerKeyDown = ( e: React.KeyboardEvent<HTMLDivElement> ) => {
|
|
2800
|
-
// Ignore keys bubbling up from the nested CTA button (Open transfer list); it handles its
|
|
2801
|
-
// own activation. Only act when the trigger itself is the focused target.
|
|
2802
|
-
if ( e.target !== e.currentTarget ) {
|
|
2803
|
-
return;
|
|
2804
|
-
}
|
|
2805
|
-
if ( e.key === "Enter" || e.key === " " ) {
|
|
2806
|
-
e.preventDefault();
|
|
2807
|
-
handleTriggerClick();
|
|
2808
|
-
}
|
|
2809
|
-
if ( e.key === "Escape" ) {
|
|
2810
|
-
cancelDropdown();
|
|
2811
|
-
}
|
|
2812
|
-
};
|
|
2813
|
-
|
|
2814
|
-
const handleDropdownKeyDown = ( e: React.KeyboardEvent<HTMLInputElement> ) => {
|
|
2815
|
-
if ( e.key === "Escape" ) {
|
|
2816
|
-
e.preventDefault();
|
|
2817
|
-
cancelDropdown();
|
|
2818
|
-
return;
|
|
2819
|
-
}
|
|
2820
|
-
// Tab is the keyboard analog of clicking away: commit the draft and let focus move on
|
|
2821
|
-
// naturally (no preventDefault). Escape above still cancels/discards.
|
|
2822
|
-
if ( e.key === "Tab" ) {
|
|
2823
|
-
commitSelection();
|
|
2824
|
-
}
|
|
2825
|
-
};
|
|
2826
|
-
|
|
2827
|
-
// When no onFilterChange is provided, filter options client-side. Memoized so a stable
|
|
2828
|
-
// array identity flows into the (virtualized) dropdown's row memo.
|
|
2829
|
-
const displayedOptions = useMemo(
|
|
2830
|
-
() => ( onFilterChange ? options : options.filter(( opt ) => matchesQuery( opt, filterQuery ))),
|
|
2831
|
-
[ onFilterChange, options, filterQuery ]
|
|
2832
|
-
);
|
|
2833
|
-
|
|
2834
|
-
// Set of the draft-selected values for O(1) membership checks in the options list and Select All.
|
|
2835
|
-
const pendingValues = useMemo(
|
|
2836
|
-
() => new Set( pendingSelected.map(( p ) => p.value )),
|
|
2837
|
-
[pendingSelected]
|
|
2838
|
-
);
|
|
2839
|
-
|
|
2840
|
-
const selectableOptions = useMemo(
|
|
2841
|
-
() => displayedOptions.filter(( o ) => !o.isDisabled ),
|
|
2842
|
-
[displayedOptions]
|
|
2843
|
-
);
|
|
2844
|
-
const areAllSelected = useMemo(
|
|
2845
|
-
() => selectableOptions.length > 0 && selectableOptions.every(( o ) => pendingValues.has( o.value )),
|
|
2846
|
-
[ selectableOptions, pendingValues ]
|
|
2847
|
-
);
|
|
2848
|
-
|
|
2849
|
-
const handleOptionToggle = ( option: TMultiSelectTransferOption ) => {
|
|
2850
|
-
setPendingSelected(( prev ) => {
|
|
2851
|
-
const exists = prev.some(( o ) => o.value === option.value );
|
|
2852
|
-
return exists ? prev.filter(( o ) => o.value !== option.value ) : [ ...prev, option ];
|
|
2853
|
-
});
|
|
2854
|
-
};
|
|
2855
|
-
|
|
2856
|
-
const handleSelectAll = () => {
|
|
2857
|
-
setPendingSelected(( prev ) => {
|
|
2858
|
-
const prevValues = new Set( prev.map(( p ) => p.value ));
|
|
2859
|
-
if ( areAllSelected ) {
|
|
2860
|
-
const selectableValues = new Set( selectableOptions.map(( o ) => o.value ));
|
|
2861
|
-
return prev.filter(( p ) => !selectableValues.has( p.value ));
|
|
2862
|
-
}
|
|
2863
|
-
return [ ...prev, ...selectableOptions.filter(( o ) => !prevValues.has( o.value )) ];
|
|
2864
|
-
});
|
|
2865
|
-
};
|
|
2866
|
-
|
|
2867
|
-
const handleRemovePill = ( option: TMultiSelectTransferOption, e: React.MouseEvent ) => {
|
|
2868
|
-
e.stopPropagation();
|
|
2869
|
-
if ( disabled ) {
|
|
2870
|
-
return;
|
|
2871
|
-
}
|
|
2872
|
-
const next = currentValue.filter(( o ) => o.value !== option.value );
|
|
2873
|
-
if ( !isControlled ) {
|
|
2874
|
-
setInternalValue( next );
|
|
2875
|
-
}
|
|
2876
|
-
onChange?.( next );
|
|
2877
|
-
};
|
|
2878
|
-
|
|
2879
|
-
const handleOpenTransferList = ( e: React.MouseEvent ) => {
|
|
2880
|
-
e.stopPropagation();
|
|
2881
|
-
// Collapse the dropdown; the modal is the active surface. Discard the in-progress draft
|
|
2882
|
-
// and filter query so a stale dropdown state doesn't linger behind the modal.
|
|
2883
|
-
setIsOpen( false );
|
|
2884
|
-
setPendingSelected([]);
|
|
2885
|
-
setFilterQuery( "" );
|
|
2886
|
-
// Seed the modal draft: selected = committed value, available = the rest.
|
|
2887
|
-
const selectedValues = new Set( currentValue.map(( o ) => o.value ));
|
|
2888
|
-
setTransferSelected( currentValue );
|
|
2889
|
-
setTransferAvailable( options.filter(( o ) => !selectedValues.has( o.value )));
|
|
2890
|
-
setIsModalOpen( true );
|
|
2891
|
-
onOpenTransferList?.();
|
|
2892
|
-
};
|
|
2893
|
-
|
|
2894
|
-
const handleTransferDone = () => {
|
|
2895
|
-
if ( !isControlled ) {
|
|
2896
|
-
setInternalValue( transferSelected );
|
|
2897
|
-
}
|
|
2898
|
-
onChange?.( transferSelected );
|
|
2899
|
-
setIsModalOpen( false );
|
|
2900
|
-
};
|
|
2901
|
-
|
|
2902
|
-
const handleTransferCancel = () => setIsModalOpen( false );
|
|
2903
|
-
|
|
2904
|
-
const visiblePills = currentValue.slice( 0, maxVisiblePills );
|
|
2905
|
-
const overflowCount = currentValue.length - visiblePills.length;
|
|
2906
|
-
|
|
2907
|
-
const {
|
|
2908
|
-
base,
|
|
2909
|
-
label: labelClass,
|
|
2910
|
-
helperText: helperTextClass,
|
|
2911
|
-
trigger,
|
|
2912
|
-
pillsArea,
|
|
2913
|
-
pill: pillClass,
|
|
2914
|
-
pillLabel,
|
|
2915
|
-
pillDismiss,
|
|
2916
|
-
pillMore,
|
|
2917
|
-
ctaArea,
|
|
2918
|
-
ctaButton,
|
|
2919
|
-
placeholder: placeholderClass
|
|
2920
|
-
} = multiSelectTransferVariants({ error, size, disabled });
|
|
2921
|
-
|
|
2922
|
-
return (
|
|
2923
|
-
<div ref={containerRef} className={base({ class: className })}>
|
|
2924
|
-
{label !== undefined && (
|
|
2925
|
-
<label htmlFor={triggerId} className={labelClass()}>
|
|
2926
|
-
{label}
|
|
2927
|
-
</label>
|
|
2928
|
-
)}
|
|
2929
|
-
|
|
2930
|
-
<div className="relative">
|
|
2931
|
-
{/* Trigger: read-only control showing pills + CTA */}
|
|
2932
|
-
<div
|
|
2933
|
-
id={triggerId}
|
|
2934
|
-
ref={triggerRef}
|
|
2935
|
-
role="button"
|
|
2936
|
-
aria-expanded={isOpen}
|
|
2937
|
-
aria-haspopup="listbox"
|
|
2938
|
-
tabIndex={disabled ? -1 : 0}
|
|
2939
|
-
className={trigger()}
|
|
2940
|
-
onClick={handleTriggerClick}
|
|
2941
|
-
onKeyDown={handleTriggerKeyDown}
|
|
2942
|
-
>
|
|
2943
|
-
<div className={pillsArea()}>
|
|
2944
|
-
{currentValue.length === 0 ? (
|
|
2945
|
-
<span className={placeholderClass()}>{placeholder}</span>
|
|
2946
|
-
) : (
|
|
2947
|
-
<>
|
|
2948
|
-
{visiblePills.map(( opt ) => (
|
|
2949
|
-
<MultiSelectTransferPill
|
|
2950
|
-
key={opt.value}
|
|
2951
|
-
option={opt}
|
|
2952
|
-
pillClass={pillClass()}
|
|
2953
|
-
pillLabelClass={pillLabel()}
|
|
2954
|
-
pillDismissClass={pillDismiss()}
|
|
2955
|
-
onRemove={handleRemovePill}
|
|
2956
|
-
/>
|
|
2957
|
-
))}
|
|
2958
|
-
{overflowCount > 0 && (
|
|
2959
|
-
<span className={pillMore()}>+{overflowCount} More</span>
|
|
2960
|
-
)}
|
|
2961
|
-
</>
|
|
2962
|
-
)}
|
|
2963
|
-
</div>
|
|
2964
|
-
<div className={ctaArea()}>
|
|
2965
|
-
<button
|
|
2966
|
-
type="button"
|
|
2967
|
-
aria-label="Open transfer list"
|
|
2968
|
-
className={ctaButton()}
|
|
2969
|
-
onClick={handleOpenTransferList}
|
|
2970
|
-
disabled={disabled}
|
|
2971
|
-
>
|
|
2972
|
-
<ADPIcon icon={iconList.expand} size="xs" />
|
|
2973
|
-
</button>
|
|
2974
|
-
<ADPIcon
|
|
2975
|
-
icon={isOpen ? iconList.upArrow : iconList.downArrow}
|
|
2976
|
-
className={ctaButton()}
|
|
2977
|
-
size="xs" />
|
|
2978
|
-
</div>
|
|
2979
|
-
</div>
|
|
2980
|
-
|
|
2981
|
-
{isOpen && (
|
|
2982
|
-
<MultiSelectTransferDropdown
|
|
2983
|
-
error={error}
|
|
2984
|
-
size={size}
|
|
2985
|
-
disabled={disabled}
|
|
2986
|
-
filterQuery={filterQuery}
|
|
2987
|
-
onFilterInput={handleFilterInput}
|
|
2988
|
-
onFilterKeyDown={handleDropdownKeyDown}
|
|
2989
|
-
searchPlaceholder={searchPlaceholder}
|
|
2990
|
-
options={displayedOptions}
|
|
2991
|
-
selectedValues={pendingValues}
|
|
2992
|
-
onOptionToggle={handleOptionToggle}
|
|
2993
|
-
hasSelectAll={selectableOptions.length > 0}
|
|
2994
|
-
areAllSelected={areAllSelected}
|
|
2995
|
-
onSelectAll={handleSelectAll}
|
|
2996
|
-
isLoading={isLoading}
|
|
2997
|
-
sentinelRef={sentinelRef}
|
|
2998
|
-
reloadTooltip={reloadTooltip}
|
|
2999
|
-
onReload={onReload}
|
|
3000
|
-
isReloading={isReloading}
|
|
3001
|
-
/>
|
|
3002
|
-
)}
|
|
3003
|
-
</div>
|
|
3004
|
-
|
|
3005
|
-
{helperText && <div className={helperTextClass()}>{helperText}</div>}
|
|
3006
|
-
|
|
3007
|
-
<MultiSelectTransferModal
|
|
3008
|
-
showModal={isModalOpen}
|
|
3009
|
-
availableItems={transferAvailable}
|
|
3010
|
-
selectedItems={transferSelected}
|
|
3011
|
-
onChange={( nextAvailable, nextSelected ) => {
|
|
3012
|
-
setTransferAvailable( nextAvailable );
|
|
3013
|
-
setTransferSelected( nextSelected );
|
|
3014
|
-
}}
|
|
3015
|
-
onCancel={handleTransferCancel}
|
|
3016
|
-
onDone={handleTransferDone}
|
|
3017
|
-
header={transferListHeader}
|
|
3018
|
-
title={transferListTitle}
|
|
3019
|
-
subtitle={transferListSubtitle}
|
|
3020
|
-
reorderable={reorderable}
|
|
3021
|
-
reloadTooltip={reloadTooltip}
|
|
3022
|
-
onReload={onReload}
|
|
3023
|
-
isReloading={isReloading}
|
|
3024
|
-
searchPlaceholder={searchPlaceholder}
|
|
3025
|
-
availablePanelHeaderSlot={availablePanelHeaderSlot}
|
|
3026
|
-
selectedPanelHeaderSlot={selectedPanelHeaderSlot}
|
|
3027
|
-
hasMore={hasMore}
|
|
3028
|
-
onLoadMore={onLoadMore}
|
|
3029
|
-
isLoading={isLoading}
|
|
3030
|
-
cancelLabel={cancelLabel}
|
|
3031
|
-
doneLabel={doneLabel}
|
|
3032
|
-
/>
|
|
3033
|
-
</div>
|
|
3034
|
-
);
|
|
3035
|
-
}
|
|
3036
|
-
|
|
3037
|
-
MultiSelectTransfer.displayName = "MultiSelectTransfer";
|
|
3038
|
-
`
|
|
2742
|
+
"content": 'import * as React from "react";\nimport { useState, useRef, useEffect, useId, useCallback, useMemo } from "react";\nimport mergeRefs from "react-merge-refs";\n\nimport { keyboardKeys } from "@constants";\nimport { useFilterQuery, useIgnoredPropWarning, useInfiniteScroll, useOnValueChange, usePrefetchBaseline } from "@hooks";\nimport { matchesQuery } from "@utils";\nimport { MultiSelectTransferDropdown } from "./multiSelectTransferDropdown";\nimport { MultiSelectTransferTrigger } from "./multiSelectTransferTrigger";\nimport { MultiSelectTransferModal } from "./multiSelectTransferModal";\nimport { useMultiSelectTransferOptionSource } from "./useMultiSelectTransferOptionSource";\nimport { useMultiSelectTransferDraft } from "./useMultiSelectTransferDraft";\nimport { multiSelectTransferVariants } from "./multiSelectTransferVariants";\nimport {\n EMultiSelectTransferSizes,\n type TMultiSelectTransferOption,\n type IMultiSelectTransferProps\n} from "./types";\n\n/**\n * A pill trigger over a dropdown option list, with a two-panel transfer-list modal as its second\n * surface. The forwarded ref lands on the wrapper `<div>`.\n */\nexport const MultiSelectTransfer = React.forwardRef<\n HTMLDivElement,\n IMultiSelectTransferProps\n>( function MultiSelectTransfer({\n id,\n className,\n label,\n placeholder = "Select options...",\n helperText,\n error = false,\n disabled = false,\n size = EMultiSelectTransferSizes.MD,\n options,\n value,\n onChange,\n filterValue,\n onFilterChange,\n searchable = true,\n searchPlaceholder = "Search...",\n filterDebounceMs = 300,\n hasMore = false,\n onLoadMore,\n isLoading = false,\n maxVisiblePills = 3,\n transferListTitle,\n transferListSubtitle,\n transferListHeader,\n onOpenTransferList,\n reorderable = false,\n reloadTooltip = "Reload",\n onReload,\n isReloading,\n availablePanelHeaderSlot,\n selectedPanelHeaderSlot,\n cancelLabel = "Cancel",\n doneLabel = "Done",\n loadOptions,\n initialOptions,\n // Left undefined here, not defaulted: sync mode warns on a `prefetch` the consumer actually passed,\n // which an eager default would erase. Resolved at the one place that reads it as a trigger.\n prefetch,\n refetchOnClear = false,\n optionsKey,\n loadErrorMessage,\n loadMoreErrorMessage,\n retryLabel = "Retry",\n showReloadButton = false,\n onLoadError\n}, forwardedRef ) {\n const [ isOpen, setIsOpen ] = useState( false );\n const [ pendingSelected, setPendingSelected ] = useState<TMultiSelectTransferOption[]>([]);\n const [ isModalOpen, setIsModalOpen ] = useState( false );\n\n // Committed selection shown as pills in the trigger. When the consumer passes `value` the\n // component is controlled and this tracks it; otherwise (uncontrolled) we own it internally\n // and update it on commit so chips still render without a parent wiring up onChange.\n const isControlled = value !== undefined;\n const [ internalValue, setInternalValue ] = useState<TMultiSelectTransferOption[]>( value ?? []);\n const currentValue = isControlled ? value : internalValue;\n\n const containerRef = useRef<HTMLDivElement>( null );\n // The wrapper is both the consumer\'s ref target and ours (the outside-click check tests against it).\n // Memoised so React does not re-attach it every render.\n const rootRef = useMemo(() => mergeRefs([ forwardedRef, containerRef ]), [forwardedRef]);\n const triggerRef = useRef<HTMLDivElement>( null );\n const generatedId = useId();\n const triggerId = id ?? generatedId;\n\n // Owns the async/legacy mode decision, the option pool, the paging trio, and the replace-vs-append\n // loader question. Declared before useFilterQuery because it supplies that hook\'s handler.\n const optionSource = useMultiSelectTransferOptionSource({\n options,\n loadOptions,\n initialOptions,\n prefetch,\n refetchOnClear,\n optionsKey,\n loadErrorMessage,\n loadMoreErrorMessage,\n showReloadButton,\n onLoadError,\n hasMore,\n onLoadMore,\n isLoading,\n onReload,\n isReloading,\n onFilterChange\n });\n const { clearLoadMoreMode, ensureDefaults } = optionSource;\n\n // Filter query (useFilterQuery); resetFilter notifies server-side consumers on clear.\n const {\n filterQuery,\n handleFilterInput: onQueryInput,\n setFilterQuery: setQuery,\n handleFilterKeyDown,\n handleFilterKeyUp,\n handleFilterBlur,\n resetFilter: resetQuery\n } = useFilterQuery({ filterValue, onFilterChange: optionSource.onFilterQueryChange, filterDebounceMs });\n\n // With no search input on either surface nothing can produce a query: the debounce never runs and the\n // clear path has nothing to clear, so the handler is dead code at the call site.\n useIgnoredPropWarning(\n !searchable && onFilterChange !== undefined,\n "MultiSelectTransfer: `onFilterChange` is ignored when `searchable={false}` \u2014 there is no search input to produce a query."\n );\n\n const resetFilter = useCallback(() => {\n clearLoadMoreMode();\n resetQuery();\n }, [ clearLoadMoreMode, resetQuery ]);\n\n // Keep the pending (draft) selection in sync when the parent changes `value` while the\n // dropdown is open. Keyed on the values\' contents (not the array reference) so an unrelated\n // parent re-render passing a new array can\'t wipe the user\'s in-progress draft; it fires\n // only on a real external change or when the dropdown (re)opens.\n const valueRef = useRef( currentValue );\n valueRef.current = currentValue;\n const valueKey = useMemo(() => currentValue.map(( o ) => o.value ).join( "\\n" ), [currentValue]);\n useEffect(() => {\n if ( isOpen ) {\n setPendingSelected( valueRef.current );\n }\n }, [ valueKey, isOpen ]);\n\n // Keep the latest draft in a ref so the outside-click listener can commit it without\n // re-subscribing on every toggle.\n const pendingSelectedRef = useRef( pendingSelected );\n pendingSelectedRef.current = pendingSelected;\n\n // Commit the pending (draft) selection and close the dropdown. Used by outside-click and\n // by toggling the trigger closed.\n const commitSelection = useCallback(() => {\n if ( !isControlled ) {\n setInternalValue( pendingSelectedRef.current );\n }\n onChange?.( pendingSelectedRef.current );\n setIsOpen( false );\n setPendingSelected([]);\n resetFilter();\n }, [ onChange, isControlled, resetFilter ]);\n\n // Infinite-scroll sentinel for the dropdown options list (gated on the open state). The in-flight\n // gate is `isLoadingMore`, not the blanket `isLoading`: a search fetch tearing the observer down and\n // re-arming it is a spurious extra page request.\n const sentinelRef = useInfiniteScroll({\n hasMore: optionSource.hasMore,\n isLoading: optionSource.isLoadingMore,\n onLoadMore: optionSource.onLoadMore,\n enabled: isOpen\n });\n\n // Prefetch the baseline on the first OPEN of either surface by default \u2014 the trigger\'s CTA can open\n // the modal without the dropdown ever being opened, and that path needs a populated pool just as\n // much. `prefetch="mount"` instead fills the pool at render, so the first open of either surface\n // shows rows rather than a loader.\n usePrefetchBaseline({ prefetch: prefetch ?? "open", isOpen: isOpen || isModalOpen, optionsKey, ensureDefaults });\n\n // Route an optionsKey CHANGE into the clear path, which drops the search view and lets\n // ensureDefaults lazily repopulate. Skipped on mount so a seeded `filterValue` isn\'t reset on paint.\n useOnValueChange( optionsKey, resetFilter );\n\n // Close dropdown on outside click and commit the pending selection. Disabled while the\n // transfer-list modal is open: the modal renders in a body portal (outside containerRef),\n // so a click inside it would otherwise be treated as an outside click and close the dropdown.\n useEffect(() => {\n const handleOutsideClick = ( e: MouseEvent ) => {\n if ( containerRef.current && !containerRef.current.contains( e.target as Node )) {\n commitSelection();\n }\n };\n if ( isOpen && !isModalOpen ) {\n document.addEventListener( "mousedown", handleOutsideClick );\n }\n return () => document.removeEventListener( "mousedown", handleOutsideClick );\n }, [ isOpen, isModalOpen, commitSelection ]);\n\n // The modal draft is a projection of the loaded pool, so a newly-paged option shows up in Available\n // with no synchronising effect and an item the user already moved is never yanked back. The query is\n // passed only in async mode: there the pool is a server answer the draft\'s snapshot must be matched\n // against, whereas in legacy mode the panel owns its own local search and filters the draft itself.\n const { draftAvailable, draftSelected, onDraftChange, seedDraft } = useMultiSelectTransferDraft(\n optionSource.options,\n isModalOpen,\n optionSource.isAsync ? filterQuery : ""\n );\n\n // Typing ends load-more mode \u2014 the keystroke\'s fetch is a search, so the loader must replace rows.\n const handleFilterInput = useCallback(\n ( e: React.ChangeEvent<HTMLInputElement> ) => {\n clearLoadMoreMode();\n onQueryInput( e );\n },\n [ onQueryInput, clearLoadMoreMode ]\n );\n\n // TransferList reports its panel search as a plain string rather than a change event.\n const handleAvailableSearchChange = useCallback(\n ( query: string ) => {\n clearLoadMoreMode();\n setQuery( query );\n },\n [ setQuery, clearLoadMoreMode ]\n );\n\n const handleTriggerClick = () => {\n if ( disabled ) {\n return;\n }\n if ( isOpen ) {\n commitSelection();\n } else {\n setPendingSelected( currentValue );\n setIsOpen( true );\n }\n };\n\n // Discard the in-progress draft, close the dropdown, and return focus to the trigger so a\n // keyboard user is never stranded on <body>.\n const cancelDropdown = () => {\n setIsOpen( false );\n setPendingSelected([]);\n resetFilter();\n triggerRef.current?.focus();\n };\n\n const handleTriggerKeyDown = ( e: React.KeyboardEvent<HTMLDivElement> ) => {\n // Ignore keys bubbling up from the nested CTA button (Open transfer list); it handles its\n // own activation. Only act when the trigger itself is the focused target.\n if ( e.target !== e.currentTarget ) {\n return;\n }\n if ( e.key === keyboardKeys.enter || e.key === keyboardKeys.space ) {\n e.preventDefault();\n handleTriggerClick();\n }\n if ( e.key === keyboardKeys.escape ) {\n cancelDropdown();\n }\n };\n\n const handleDropdownKeyDown = ( e: React.KeyboardEvent<HTMLElement> ) => {\n handleFilterKeyDown( e );\n if ( e.key === keyboardKeys.escape ) {\n e.preventDefault();\n cancelDropdown();\n return;\n }\n // Tab is the keyboard analog of clicking away: commit the draft and let focus move on\n // naturally (no preventDefault). Escape above still cancels/discards.\n if ( e.key === keyboardKeys.tab ) {\n commitSelection();\n }\n };\n\n // When no server-side filter is in play, filter options client-side. Memoized so a stable\n // array identity flows into the (virtualized) dropdown\'s row memo.\n const displayedOptions = useMemo(\n () => ( optionSource.isServerFiltered\n ? optionSource.options\n : optionSource.options.filter(( opt ) => matchesQuery( opt, filterQuery ))),\n [ optionSource.isServerFiltered, optionSource.options, filterQuery ]\n );\n\n // Set of the draft-selected values for O(1) membership checks in the options list and Select All.\n const pendingValues = useMemo(\n () => new Set( pendingSelected.map(( p ) => p.value )),\n [pendingSelected]\n );\n\n const selectableOptions = useMemo(\n () => displayedOptions.filter(( o ) => !o.isDisabled ),\n [displayedOptions]\n );\n const areAllSelected = useMemo(\n () => selectableOptions.length > 0 && selectableOptions.every(( o ) => pendingValues.has( o.value )),\n [ selectableOptions, pendingValues ]\n );\n\n const handleOptionToggle = ( option: TMultiSelectTransferOption ) => {\n setPendingSelected(( prev ) => {\n const exists = prev.some(( o ) => o.value === option.value );\n return exists ? prev.filter(( o ) => o.value !== option.value ) : [ ...prev, option ];\n });\n };\n\n const handleSelectAll = () => {\n setPendingSelected(( prev ) => {\n const prevValues = new Set( prev.map(( p ) => p.value ));\n if ( areAllSelected ) {\n const selectableValues = new Set( selectableOptions.map(( o ) => o.value ));\n return prev.filter(( p ) => !selectableValues.has( p.value ));\n }\n return [ ...prev, ...selectableOptions.filter(( o ) => !prevValues.has( o.value )) ];\n });\n };\n\n const handleRemovePill = ( option: TMultiSelectTransferOption, e: React.MouseEvent ) => {\n e.stopPropagation();\n if ( disabled ) {\n return;\n }\n const next = currentValue.filter(( o ) => o.value !== option.value );\n if ( !isControlled ) {\n setInternalValue( next );\n }\n onChange?.( next );\n };\n\n const handleOpenTransferList = ( e: React.MouseEvent ) => {\n e.stopPropagation();\n // Every other route out of the dropdown commits its draft, and the CTA is no exception: options\n // ticked in the menu carry into the modal instead of being dropped. Available is derived from\n // the pool minus the seed, so only the selection is seeded.\n if ( isOpen ) {\n // Seed from the draft rather than waiting for the committed value to come back round through\n // `value`; commitSelection then closes the dropdown and clears the draft/filter.\n seedDraft( pendingSelectedRef.current );\n commitSelection();\n } else {\n resetFilter();\n seedDraft( currentValue );\n }\n setIsModalOpen( true );\n onOpenTransferList?.();\n };\n\n // Both close paths reset the filter, like every other close in this component: the modal\'s Available\n // panel shares one useFilterQuery instance with the dropdown, so a query left behind here would be\n // the dropdown\'s query the next time it opens.\n const handleTransferDone = () => {\n if ( !isControlled ) {\n setInternalValue( draftSelected );\n }\n onChange?.( draftSelected );\n setIsModalOpen( false );\n resetFilter();\n };\n\n const handleTransferCancel = () => {\n setIsModalOpen( false );\n resetFilter();\n };\n\n const { base, label: labelClass, helperText: helperTextClass } =\n multiSelectTransferVariants({ error, size, disabled });\n\n return (\n <div ref={rootRef} className={base({ class: className })}>\n {label !== undefined && (\n <label htmlFor={triggerId} className={labelClass()}>\n {label}\n </label>\n )}\n\n <div className="relative">\n <MultiSelectTransferTrigger\n id={triggerId}\n ref={triggerRef}\n error={error}\n size={size}\n disabled={disabled}\n isOpen={isOpen}\n value={currentValue}\n placeholder={placeholder}\n maxVisiblePills={maxVisiblePills}\n onClick={handleTriggerClick}\n onKeyDown={handleTriggerKeyDown}\n onRemovePill={handleRemovePill}\n onOpenTransferList={handleOpenTransferList}\n />\n\n {isOpen && (\n <MultiSelectTransferDropdown\n error={error}\n size={size}\n disabled={disabled}\n searchable={searchable}\n filterQuery={filterQuery}\n onFilterInput={handleFilterInput}\n onFilterKeyDown={handleDropdownKeyDown}\n onFilterKeyUp={handleFilterKeyUp}\n onFilterBlur={handleFilterBlur}\n searchPlaceholder={searchPlaceholder}\n options={displayedOptions}\n selectedValues={pendingValues}\n onOptionToggle={handleOptionToggle}\n hasSelectAll={selectableOptions.length >= 2}\n areAllSelected={areAllSelected}\n onSelectAll={handleSelectAll}\n isLoading={optionSource.isLoading}\n isSearchFetch={optionSource.isSearchFetch}\n sentinelRef={sentinelRef}\n loadError={optionSource.loadError}\n loadMoreError={optionSource.loadMoreError}\n onRetryLoadMore={optionSource.onRetryLoadMore}\n retryLabel={retryLabel}\n reloadTooltip={reloadTooltip}\n onReload={optionSource.onReload}\n isReloading={optionSource.isReloading}\n />\n )}\n </div>\n\n {helperText && <div className={helperTextClass()}>{helperText}</div>}\n\n <MultiSelectTransferModal\n showModal={isModalOpen}\n availableItems={draftAvailable}\n selectedItems={draftSelected}\n onChange={onDraftChange}\n onCancel={handleTransferCancel}\n onDone={handleTransferDone}\n header={transferListHeader}\n title={transferListTitle}\n subtitle={transferListSubtitle}\n reorderable={reorderable}\n reloadTooltip={reloadTooltip}\n onReload={optionSource.onReload}\n isReloading={optionSource.isReloading}\n searchable={searchable}\n searchPlaceholder={searchPlaceholder}\n availablePanelHeaderSlot={availablePanelHeaderSlot}\n selectedPanelHeaderSlot={selectedPanelHeaderSlot}\n hasMoreAvailable={optionSource.hasMore}\n onLoadMoreAvailable={optionSource.onLoadMore}\n // Replace-loader semantics apply only in async mode. In legacy mode, `isLoading` drives an\n // APPEND loader (via `isLoadingMore`) with the rows kept, so this stays undefined.\n isLoadingAvailable={optionSource.isAsync ? optionSource.isSearchFetch : undefined}\n isLoadingMoreAvailable={optionSource.isLoadingMore}\n availableLoadError={optionSource.loadError}\n availableLoadMoreError={optionSource.loadMoreError}\n onRetryLoadMoreAvailable={optionSource.onRetryLoadMore}\n retryLabel={retryLabel}\n availableTotalCount={optionSource.total}\n {...( optionSource.isAsync && searchable\n // Over a paged pool a client-side panel search would only search the pages that happen to be\n // loaded. One query, one useFilterQuery instance: the dropdown is always closed while the\n // modal is open, so the two can never contend. The SELECTED panel\'s search stays local \u2014 it\n // is a plain array and there is no server to ask. With the searches hidden there is no query\n // to thread at all.\n ? { availableSearchTerm: filterQuery, onAvailableSearchChange: handleAvailableSearchChange }\n : {})}\n cancelLabel={cancelLabel}\n doneLabel={doneLabel}\n />\n </div>\n );\n});\n\nMultiSelectTransfer.displayName = "MultiSelectTransfer";\n'
|
|
3039
2743
|
},
|
|
3040
2744
|
{
|
|
3041
2745
|
"name": "index.ts",
|
|
3042
|
-
"content": 'export { MultiSelectTransfer } from "./multiSelectTransfer";\nexport { multiSelectTransferVariants } from "./multiSelectTransferVariants";\nexport type {\n IMultiSelectTransferProps,\n TMultiSelectTransferOption,\n TMultiSelectTransferSize\n} from "./types";\n'
|
|
2746
|
+
"content": 'export { MultiSelectTransfer } from "./multiSelectTransfer";\nexport { multiSelectTransferVariants } from "./multiSelectTransferVariants";\nexport type {\n IMultiSelectTransferProps,\n TMultiSelectTransferOption,\n TMultiSelectTransferSize,\n TMultiSelectTransferLoadOptions\n} from "./types";\n'
|
|
3043
2747
|
},
|
|
3044
2748
|
{
|
|
3045
2749
|
"name": "README.md",
|
|
3046
|
-
"content": '# MultiSelectTransfer Component\n\n## Component Overview\n\nThe MultiSelectTransfer is a multi-select form control that pairs a compact, pill-based\ntrigger with two ways to pick options: a lightweight **dropdown** for quick selection and\na full-screen **transfer-list modal** for managing large or ordered selections across an\n**Available** and a **Selected** panel. Committed selections render as removable pills in\nthe trigger, collapsing to a "+N More" badge past a configurable limit. It supports both\ncontrolled and uncontrolled usage, client- and server-side filtering, infinite scroll, and\noptional reordering.\n\n**When to use:**\n- Selecting multiple items (permissions, columns, tags, members) from a pool that can be\n browsed quickly or curated in depth\n- Form fields where the current selection should stay visible as pills\n- Workflows that need a "confirm before commit" step (Cancel/Done in the modal)\n- Large, possibly paginated option sets that benefit from windowing and infinite scroll\n- Ordered selections where the position of chosen items matters (`reorderable`)\n\n**Component Architecture:**\n- Styled with `tailwind-variants` (`tv()`) slots \u2014 see `multiSelectTransferVariants.ts`\n- Composes the standalone `TransferList` inside a `Modal` for the full-management view\n- Dropdown and transfer-list panels window (virtualize) large option sets\n- Infinite scroll via the shared `useInfiniteScroll` (`IntersectionObserver`) hook\n- Debounced server-side filtering via the shared `useDebouncedCallback` hook\n- Client-side filtering via the shared `matchesQuery` util when no filter handler is given\n- Reuses `ADPIcon`, `Tooltip` (for clipped pill labels), and `TransferList`\n- Dark-mode aware and RTL-safe (logical spacing properties throughout)\n\n## Basic Usage\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nexport function Example() {\n const options: TMultiSelectTransferOption[] = [\n { value: "chocolate", label: "Chocolate" },\n { value: "vanilla", label: "Vanilla" },\n { value: "strawberry", label: "Strawberry" }\n ];\n\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n\n return (\n <MultiSelectTransfer\n label="Favorite Flavors"\n placeholder="Select flavors..."\n options={options}\n value={selected}\n onChange={setSelected}\n />\n );\n}\n```\n\n> **Note:** Update the import path based on your project structure. If you used the Astral UI CLI, the typical import path would be `@components/ui/multiSelectTransfer` or `@components/multiSelectTransfer`.\n\n## Component Props\n\n`MultiSelectTransfer` is a function component and does **not** forward a ref.\n\n| Prop | Type | Default | Required | Description |\n|---|---|---|---|---|\n| `options` | `TMultiSelectTransferOption[]` | \u2014 | Yes | Options shown in the dropdown and seeded into the transfer-list Available panel. |\n| `value` | `TMultiSelectTransferOption[]` | `undefined` | No | Controlled selection. Omit to run uncontrolled (the component owns selection internally). |\n| `onChange` | `(selected: TMultiSelectTransferOption[]) => void` | \u2014 | No | Fired when a selection is committed (dropdown close, modal Done, or pill removal). |\n| `id` | `string` | auto (`useId`) | No | Id for the trigger, wired to the `label` via `htmlFor`. |\n| `className` | `string` | \u2014 | No | Extra classes on the root container. |\n| `label` | `ReactNode` | `undefined` | No | Label rendered above the trigger. |\n| `placeholder` | `string` | `"Select options..."` | No | Text shown in the trigger when nothing is selected. |\n| `helperText` | `ReactNode` | `undefined` | No | Helper text rendered below the trigger. |\n| `error` | `boolean` | `false` | No | Apply error styling to the trigger and helper text. |\n| `disabled` | `boolean` | `false` | No | Disable all interaction. |\n| `size` | `\'md\' \\| \'lg\'` | `\'md\'` | No | Control size variant. |\n| `maxVisiblePills` | `number` | `3` | No | Max pills shown in the trigger before collapsing to "+N More". |\n| `filterValue` | `string` | `undefined` | No | Controlled query for the dropdown search input. |\n| `onFilterChange` | `(query: string) => void` | \u2014 | No | Server-side filter handler. When provided, client-side filtering is skipped. |\n| `searchPlaceholder` | `string` | `"Search..."` | No | Placeholder for the dropdown filter input and the transfer-list modal\'s panel search inputs. |\n| `filterDebounceMs` | `number` | `300` | No | Debounce delay (ms) for `onFilterChange`. Set to `0` to fire synchronously. |\n| `hasMore` | `boolean` | `false` | No | Whether more options can be loaded (drives infinite scroll). |\n| `onLoadMore` | `() => void` | \u2014 | No | Called when the infinite-scroll sentinel becomes visible. |\n| `isLoading` | `boolean` | `false` | No | Show a loading indicator at the bottom of the list. |\n| `transferListTitle` | `ReactNode` | `undefined` | No | Title in the transfer-list modal header. |\n| `transferListSubtitle` | `ReactNode` | `undefined` | No | Subtitle under the modal title. |\n| `transferListHeader` | `ReactNode` | `undefined` | No | Fully custom modal header; overrides `transferListTitle`/`transferListSubtitle`. |\n| `onOpenTransferList` | `() => void` | \u2014 | No | Called when the transfer-list CTA is clicked, before the modal opens. |\n| `reorderable` | `boolean` | `false` | No | Enable drag + arrow reordering of the Selected panel in the modal. |\n| `onReload` | `() => void` | \u2014 | No | Shows a reload button (dropdown and modal) and is fired on click. |\n| `isReloading` | `boolean` | `false` | No | Spins the reload icon. |\n| `reloadTooltip` | `string` | `"Reload"` | No | Tooltip for the reload button. |\n| `availablePanelHeaderSlot` | `ReactNode` | `undefined` | No | Custom content under the modal Available panel search. |\n| `selectedPanelHeaderSlot` | `ReactNode` | `undefined` | No | Custom content under the modal Selected panel search. |\n| `cancelLabel` | `ReactNode` | `"Cancel"` | No | Label for the modal cancel button. |\n| `doneLabel` | `ReactNode` | `"Done"` | No | Label for the modal commit button. |\n\n### `TMultiSelectTransferOption`\n\n| Field | Type | Required | Description |\n|---|---|---|---|\n| `value` | `string \\| number` | Yes | Stable unique identifier for the option. |\n| `label` | `ReactNode` | Yes | Display content for the option, pill, and transfer-list row. |\n| `searchValue` | `string` | No | Plain text used for client-side search matching. Set this when `label` is custom JSX so the option stays findable by its visible text. Takes precedence over `label`/`value`. |\n| `isDisabled` | `boolean` | No | Prevents the option from being selected or moved; excluded from "Select all". |\n\n## Sizes\n\nTwo sizes are available via the `size` prop:\n\n- **`md`** (default) \u2014 standard density, `text-base` labels; use in typical forms.\n- **`lg`** \u2014 roomier padding and `text-md` labels; use in prominent or touch-oriented UIs.\n\n```tsx\n<MultiSelectTransfer label="Medium" options={options} size="md" />\n<MultiSelectTransfer label="Large" options={options} size="lg" />\n```\n\n## Usage Patterns\n\n### Controlled vs. Uncontrolled\n\n- **Controlled** \u2014 pass `value` and `onChange`. The parent owns the selection; pills reflect\n `value` exactly. Required if you need to read or reset the selection externally.\n- **Uncontrolled** \u2014 omit `value` (optionally still pass `onChange` to observe changes). The\n component tracks the committed selection internally, so pills still render without any\n parent wiring.\n\n### Two ways to select\n\n1. **Dropdown** \u2014 clicking the trigger opens a searchable list with per-option checkboxes and\n a "Select all". Selection is a **draft**: it commits when the dropdown closes (outside\n click, toggling the trigger, or `Tab`) and discards on `Escape`.\n2. **Transfer-list modal** \u2014 clicking the expand CTA opens a two-panel modal seeded from the\n current selection. Moves are a **draft** committed on **Done** and discarded on **Cancel**.\n\n### Filtering\n\n- **Client-side (default)** \u2014 options are filtered locally against the query. No handler needed.\n- **Server-side** \u2014 pass `onFilterChange`; the component stops filtering locally and hands you\n the (debounced) query so you can fetch and update `options` yourself.\n\n## Practical Examples\n\n### 1. Controlled selection with a live count\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nconst options: TMultiSelectTransferOption[] = [\n { value: "chocolate", label: "Chocolate" },\n { value: "vanilla", label: "Vanilla" },\n { value: "strawberry", label: "Strawberry" },\n { value: "mint", label: "Mint" }\n];\n\nfunction FlavorPicker() {\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n\n return (\n <MultiSelectTransfer\n label="Flavors"\n placeholder="Select flavors..."\n options={options}\n value={selected}\n onChange={setSelected}\n helperText={`${selected.length} selected`}\n />\n );\n}\n```\n\n### 2. Validation and error state in a form\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n Button,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nfunction PermissionsField({ options }: { options: TMultiSelectTransferOption[] }) {\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n const [touched, setTouched] = useState(false);\n const hasError = touched && selected.length === 0;\n\n const handleSubmit = () => {\n setTouched(true);\n if (selected.length === 0) return;\n // submit selected...\n };\n\n return (\n <form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }}>\n <MultiSelectTransfer\n label="Permissions"\n placeholder="Assign permissions..."\n options={options}\n value={selected}\n onChange={setSelected}\n error={hasError}\n helperText={hasError ? "Select at least one permission." : undefined}\n />\n <Button type="submit">Save</Button>\n </form>\n );\n}\n```\n\n### 3. Server-side filtering with debounce\n\n```tsx\nimport { useEffect, useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nfunction RemoteUserPicker() {\n const [query, setQuery] = useState("");\n const [options, setOptions] = useState<TMultiSelectTransferOption[]>([]);\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n\n useEffect(() => {\n let active = true;\n setIsLoading(true);\n fetchUsers(query)\n .then((users) => {\n if (active) setOptions(users.map((u) => ({ value: u.id, label: u.name })));\n })\n .finally(() => active && setIsLoading(false));\n return () => { active = false; };\n }, [query]);\n\n return (\n <MultiSelectTransfer\n label="Assignees"\n placeholder="Select users..."\n options={options}\n value={selected}\n onChange={setSelected}\n onFilterChange={setQuery}\n filterDebounceMs={300}\n isLoading={isLoading}\n />\n );\n}\n```\n\n### 4. Paginated options with infinite scroll and reload\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nconst PAGE_SIZE = 20;\n\nfunction PaginatedPicker() {\n const [loaded, setLoaded] = useState<TMultiSelectTransferOption[]>([]);\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [isReloading, setIsReloading] = useState(false);\n const [hasMore, setHasMore] = useState(true);\n\n const loadMore = async () => {\n if (isLoading) return;\n setIsLoading(true);\n const page = await fetchPage(loaded.length, PAGE_SIZE);\n setLoaded((prev) => [...prev, ...page.items]);\n setHasMore(page.hasMore);\n setIsLoading(false);\n };\n\n const reload = async () => {\n setIsReloading(true);\n const page = await fetchPage(0, PAGE_SIZE);\n setLoaded(page.items);\n setHasMore(page.hasMore);\n setIsReloading(false);\n };\n\n return (\n <MultiSelectTransfer\n label="Items"\n placeholder="Select items..."\n options={loaded}\n value={selected}\n onChange={setSelected}\n hasMore={hasMore}\n onLoadMore={loadMore}\n isLoading={isLoading}\n onReload={reload}\n isReloading={isReloading}\n />\n );\n}\n```\n\n### 5. Ordered selection via the transfer-list modal\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nfunction ColumnManager({ columns }: { columns: TMultiSelectTransferOption[] }) {\n const [visible, setVisible] = useState<TMultiSelectTransferOption[]>([]);\n\n return (\n <MultiSelectTransfer\n label="Visible columns"\n placeholder="No columns selected..."\n options={columns}\n value={visible}\n onChange={setVisible}\n reorderable\n maxVisiblePills={2}\n transferListTitle="Manage columns"\n transferListSubtitle="Choose which columns appear and in what order."\n doneLabel="Apply"\n />\n );\n}\n```\n\n## Styling and Customization\n\n- Use `className` to add classes to the root container.\n- The `size` and `error` props cover the common visual states.\n- For deeper theming, import the exported variants and compose them directly:\n\n```tsx\nimport { multiSelectTransferVariants } from "@components/multiSelectTransfer";\n\nconst { trigger, pill } = multiSelectTransferVariants({ size: "lg", error: false });\n```\n\nDark mode follows the library convention (a `.dark` class on a root ancestor); all slots\nship dark-mode styles. Spacing uses logical properties (`ps-`, `pe-`, `ms-`, `me-`) so the\ncontrol mirrors correctly in RTL layouts.\n\n## Technical Details\n\n- **State management:** The trigger shows a **committed** selection while the dropdown and\n modal each maintain their own **draft**. Drafts commit on close/Done and discard on\n Escape/Cancel, giving a clear "confirm before apply" model. In uncontrolled mode the\n committed value is held internally; in controlled mode it tracks `value`.\n- **Draft preservation:** The dropdown draft is keyed on the option values\' contents, not the\n array reference, so an unrelated parent re-render that passes a new `value` array cannot wipe\n an in-progress draft \u2014 it re-syncs only on a genuine external change or on (re)open.\n- **Filtering:** Without `onFilterChange`, options are filtered client-side via `matchesQuery`\n and memoized for stable identity. `matchesQuery` matches an option\'s `searchValue` first, then a\n string `label`, then its `value` \u2014 set `searchValue` on options whose `label` is custom JSX so\n they stay findable by their visible text. With `onFilterChange`, filtering is delegated to the parent\n and the query is debounced (`filterDebounceMs`); a pending debounce is cancelled on unmount and\n on an external `filterValue` reset so a stale query never fires late.\n- **Virtualization:** Both the dropdown options list and the modal panels window large option\n sets (past ~100 items) so multi-thousand-item lists open and filter without mounting every row.\n- **Infinite scroll:** An `IntersectionObserver` sentinel (via `useInfiniteScroll`) calls\n `onLoadMore` when scrolled into view, gated on the open state. While the modal is open, newly\n loaded options are folded into the Available draft without duplicating or reclaiming items the\n user has already moved to Selected.\n- **Modal portal:** The transfer-list modal renders in a body portal. The dropdown\'s\n outside-click listener is suspended while the modal is open so a click inside the portal is not\n misread as an outside click.\n- **Pill overflow:** The trigger shows up to `maxVisiblePills` pills, then a "+N More" badge.\n Long pill labels truncate to a max width and surface the full text via a `Tooltip` only when\n actually clipped.\n\n## Accessibility\n\n**Implemented:**\n- The trigger is a keyboard-operable control: `role="button"`, `aria-haspopup="listbox"`, and\n `aria-expanded` reflecting the open state.\n- The trigger is focusable (`tabIndex={0}`) when enabled and removed from the tab order\n (`tabIndex={-1}`) when `disabled`.\n- Keyboard support on the trigger: `Enter`/`Space` toggle the dropdown; `Escape` closes and\n discards the draft.\n- Keyboard support in the dropdown: `Escape` cancels/discards and returns focus to the trigger\n so a keyboard user is never stranded on `<body>`; `Tab` commits the draft and lets focus move\n on naturally.\n- The `label` is associated with the trigger via `htmlFor`/`id` (auto-generated when `id` is\n omitted).\n- The transfer-list CTA and reload buttons carry descriptive `aria-label`/tooltip text.\n- Disabled options are excluded from selection and from "Select all".\n\n**Best Practices:**\n- Always provide a `label` (or an external `aria-label`) so the control is announced.\n- Use `error` together with `helperText` to communicate validation state visibly rather than by\n color alone.\n- Keep option `label`s meaningful as text \u2014 pills, tooltips, and screen readers all render them.\n- Provide stable, unique `value`s; reusing a value across options breaks selection tracking and\n keys.\n- When filtering server-side, keep `isLoading` accurate so assistive tech and users get correct\n loading feedback.\n'
|
|
2750
|
+
"content": '# MultiSelectTransfer Component\n\n## Component Overview\n\nThe MultiSelectTransfer is a multi-select form control that pairs a compact, pill-based\ntrigger with two ways to pick options: a lightweight **dropdown** for quick selection and\na full-screen **transfer-list modal** for managing large or ordered selections across an\n**Available** and a **Selected** panel. Committed selections render as removable pills in\nthe trigger, collapsing to a "+N More" badge past a configurable limit. It supports both\ncontrolled and uncontrolled usage, client- and server-side filtering, infinite scroll, and\noptional reordering.\n\n**When to use:**\n- Selecting multiple items (permissions, columns, tags, members) from a pool that can be\n browsed quickly or curated in depth\n- Form fields where the current selection should stay visible as pills\n- Workflows that need a "confirm before commit" step (Cancel/Done in the modal)\n- Large, possibly paginated option sets that benefit from windowing and infinite scroll\n- Ordered selections where the position of chosen items matters (`reorderable`)\n\n**Component Architecture:**\n- Styled with `tailwind-variants` (`tv()`) slots \u2014 see `multiSelectTransferVariants.ts`\n- Composes the standalone `TransferList` inside a `Modal` for the full-management view\n- Dropdown and transfer-list panels window (virtualize) large option sets\n- Infinite scroll via the shared `useInfiniteScroll` (`IntersectionObserver`) hook\n- Debounced server-side filtering via the shared `useFilterQuery` hook (also used by `Select`)\n- Both surfaces\' search inputs can be turned off with `searchable={false}`; the dropdown\'s option list\n then takes focus and owns the keyboard, as each TransferList panel\'s list already does\n- Client-side filtering via the shared `matchesQuery` util when no filter handler is given\n- Reuses `ADPIcon`, `Tooltip` (for clipped pill labels), and `TransferList`\n- Dark-mode aware and RTL-safe (logical spacing properties throughout)\n\n## Basic Usage\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nexport function Example() {\n const options: TMultiSelectTransferOption[] = [\n { value: "chocolate", label: "Chocolate" },\n { value: "vanilla", label: "Vanilla" },\n { value: "strawberry", label: "Strawberry" }\n ];\n\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n\n return (\n <MultiSelectTransfer\n label="Favorite Flavors"\n placeholder="Select flavors..."\n options={options}\n value={selected}\n onChange={setSelected}\n />\n );\n}\n```\n\n> **Note:** Update the import path based on your project structure. If you used the Astral UI CLI, the typical import path would be `@components/ui/multiSelectTransfer` or `@components/multiSelectTransfer`.\n\n## Component Props\n\n`MultiSelectTransfer` is a function component and does **not** forward a ref.\n\n| Prop | Type | Default | Required | Description |\n|---|---|---|---|---|\n| `options` | `TMultiSelectTransferOption[]` | \u2014 | No | Options shown in the dropdown and projected into the transfer-list Available panel. Ignored (dev warning) when `loadOptions` is set. |\n| `value` | `TMultiSelectTransferOption[]` | `undefined` | No | Controlled selection. Omit to run uncontrolled (the component owns selection internally). |\n| `onChange` | `(selected: TMultiSelectTransferOption[]) => void` | \u2014 | No | Fired when a selection is committed (dropdown close, modal Done, or pill removal). |\n| `id` | `string` | auto (`useId`) | No | Id for the trigger, wired to the `label` via `htmlFor`. |\n| `className` | `string` | \u2014 | No | Extra classes on the root container. |\n| `ref` | `Ref<HTMLDivElement>` | \u2014 | No | Forwarded to the root container \u2014 for programmatic focus/scroll and form libraries that bind by ref. |\n| `label` | `ReactNode` | `undefined` | No | Label rendered above the trigger. |\n| `placeholder` | `string` | `"Select options..."` | No | Text shown in the trigger when nothing is selected. |\n| `helperText` | `ReactNode` | `undefined` | No | Helper text rendered below the trigger. |\n| `error` | `boolean` | `false` | No | Apply error styling to the trigger and helper text. |\n| `disabled` | `boolean` | `false` | No | Disable all interaction. |\n| `size` | `\'md\' \\| \'lg\'` | `\'md\'` | No | Control size variant. |\n| `maxVisiblePills` | `number` | `3` | No | Max pills shown in the trigger before collapsing to "+N More". |\n| `filterValue` | `string` | `undefined` | No | Seeds the dropdown search input and re-syncs it whenever this value changes (not fully controlled \u2014 see Technical Details). |\n| `onFilterChange` | `(query: string) => void` | \u2014 | No | Server-side filter handler. When provided, client-side filtering is skipped. |\n| `searchable` | `boolean` | `true` | No | Renders the dropdown\'s search input and the modal\'s two panel searches. With `false` the dropdown\'s option list takes focus on open and owns the keyboard (`role="listbox"` plus `aria-activedescendant`, no combobox); the reload button, "Select all", paging and Escape/Tab are unaffected, and `onFilterChange` is ignored (dev warning). |\n| `searchPlaceholder` | `string` | `"Search..."` | No | Placeholder for the dropdown filter input and the transfer-list modal\'s panel search inputs. Ignored when `searchable={false}`. |\n| `filterDebounceMs` | `number` | `300` | No | Debounce delay (ms) for `onFilterChange`. Set to `0` to fire synchronously. |\n| `hasMore` | `boolean` | `false` | No | Whether more options can be loaded (drives infinite scroll). |\n| `onLoadMore` | `() => void` | \u2014 | No | Called when the infinite-scroll sentinel becomes visible. |\n| `isLoading` | `boolean` | `false` | No | A load is in flight. Replaces the option rows for a search fetch; appends a loader below them for a load-more. |\n| `transferListTitle` | `ReactNode` | `undefined` | No | Title in the transfer-list modal header. |\n| `transferListSubtitle` | `ReactNode` | `undefined` | No | Subtitle under the modal title. |\n| `transferListHeader` | `ReactNode` | `undefined` | No | Fully custom modal header; overrides `transferListTitle`/`transferListSubtitle`. |\n| `onOpenTransferList` | `() => void` | \u2014 | No | Called when the transfer-list CTA is clicked, before the modal opens. |\n| `reorderable` | `boolean` | `false` | No | Enable drag + arrow reordering of the Selected panel in the modal. |\n| `onReload` | `() => void` | \u2014 | No | Shows a reload button (dropdown and modal) and is fired on click. |\n| `isReloading` | `boolean` | `false` | No | Spins the reload icon. |\n| `reloadTooltip` | `string` | `"Reload"` | No | Tooltip for the reload button. |\n| `availablePanelHeaderSlot` | `ReactNode` | `undefined` | No | Custom content under the modal Available panel search. |\n| `selectedPanelHeaderSlot` | `ReactNode` | `undefined` | No | Custom content under the modal Selected panel search. |\n| `cancelLabel` | `ReactNode` | `"Cancel"` | No | Label for the modal cancel button. |\n| `doneLabel` | `ReactNode` | `"Done"` | No | Label for the modal commit button. |\n| `loadOptions` | `(query, meta) => Promise<TMultiSelectTransferOption[] \\| IOptionPage<...>>` | \u2014 | No | Async, paged option source. Switches the component into [async mode](#async-mode-loadoptions). |\n| `initialOptions` | `readonly TMultiSelectTransferOption[]` | `undefined` | No | Seed rows for a list you already have (SSR payload, route loader, warm cache). Painted on the first frame and kept on screen while the baseline fetch revalidates over them \u2014 see [Seeding with `initialOptions`](#seeding-with-initialoptions). Async mode only. |\n| `prefetch` | `"mount" \\| "open" \\| "never"` | `"open"` | No | When to fetch the unfiltered first page. `"open"` when the dropdown \u2014 or the transfer-list modal, whichever comes first \u2014 opens; `"mount"` at render, so the first open shows rows instead of a loader; `"never"` only once the user types. Async mode only. |\n| `refetchOnClear` | `boolean` | `false` | No | Clearing the search revalidates the cached baseline instead of only restoring it. |\n| `optionsKey` | `string \\| number` | `undefined` | No | Identity of the option set. A change drops cached pages and repopulates. Does **not** clear the selection. |\n| `loadErrorMessage` | `ReactNode` | `"Couldn\'t load options."` | No | Shown in place of the rows when a load rejects. |\n| `loadMoreErrorMessage` | `ReactNode` | `"Couldn\'t load more."` | No | Shown under the loaded rows when a page append rejects. |\n| `retryLabel` | `string` | `"Retry"` | No | Label for the retry button beside `loadMoreErrorMessage`. |\n| `showReloadButton` | `boolean` | `false` | No | Shows the reload button in async mode, wired to re-run the current query from page one. |\n| `onLoadError` | `(error: unknown) => void` | \u2014 | No | Notified when a load rejects (the component renders the message and swallows it). |\n\n### `TMultiSelectTransferOption`\n\n| Field | Type | Required | Description |\n|---|---|---|---|\n| `value` | `string \\| number` | Yes | Stable unique identifier for the option. |\n| `label` | `ReactNode` | Yes | Display content for the option, pill, and transfer-list row. |\n| `searchValue` | `string` | No | Plain text used for client-side search matching. Set this when `label` is custom JSX so the option stays findable by its visible text. Takes precedence over `label`/`value`. |\n| `isDisabled` | `boolean` | No | Prevents the option from being selected or moved; excluded from "Select all". |\n\n## Sizes\n\nTwo sizes are available via the `size` prop:\n\n- **`md`** (default) \u2014 standard density, `text-base` labels; use in typical forms.\n- **`lg`** \u2014 roomier padding and `text-md` labels; use in prominent or touch-oriented UIs.\n\n```tsx\n<MultiSelectTransfer label="Medium" options={options} size="md" />\n<MultiSelectTransfer label="Large" options={options} size="lg" />\n```\n\n## Usage Patterns\n\n### Controlled vs. Uncontrolled\n\n- **Controlled** \u2014 pass `value` and `onChange`. The parent owns the selection; pills reflect\n `value` exactly. Required if you need to read or reset the selection externally.\n- **Uncontrolled** \u2014 omit `value` (optionally still pass `onChange` to observe changes). The\n component tracks the committed selection internally, so pills still render without any\n parent wiring.\n\n### Two ways to select\n\n1. **Dropdown** \u2014 clicking the trigger opens a searchable list (`searchable={false}` drops the search\n box and nothing else) with per-option checkboxes and a "Select all". Selection is a **draft**: it\n commits when the dropdown closes (outside click, toggling the trigger, the transfer-list CTA, or\n `Tab`) and discards on `Escape`.\n2. **Transfer-list modal** \u2014 clicking the expand CTA opens a two-panel modal seeded from the\n current selection. Opening it from an open dropdown commits that dropdown\'s draft first, so\n options ticked in the menu arrive on the Selected side rather than being dropped. Moves are a\n **draft** committed on **Done** and discarded on **Cancel**.\n\n### Filtering\n\n- **Client-side (default)** \u2014 options are filtered locally against the query. No handler needed.\n- **Server-side** \u2014 pass `onFilterChange`; the component stops filtering locally and hands you\n the (debounced) query so you can fetch and update `options` yourself. While Backspace/Delete is\n held the debounce waits for keyup (or blur), so a long-press cannot fire a search mid-hold.\n- **Async (`loadOptions`)** \u2014 the component owns the option list, paging, the request lifecycle and\n the loading state. See [Async mode](#async-mode-loadoptions).\n- **No search at all** \u2014 `searchable={false}` hides the dropdown\'s search input *and* the modal\'s two\n panel searches, so nothing on either surface can produce a query. Everything else stays: the reload\n button, "Select all", infinite scroll and the full keyboard model. `onFilterChange` never fires and\n is dev-warned if passed, and in async mode `loadOptions` is only ever called with an empty query \u2014\n paging still works, searching does not.\n- When the (client- or server-filtered) list has no matches, the dropdown shows a **"No options"**\n notice \u2014 the same copy as `Select`. While a search fetch is in flight (`isLoading`), the loader\n replaces that notice so an empty-and-loading menu never flashes "No options" mid-request.\n- Wherever the component clears the query itself \u2014 committing or cancelling the dropdown, or opening\n the transfer list modal \u2014 `onFilterChange("")` fires too (only if the query was non-empty), so your\n `options` never stay filtered by a query the user can no longer see. On modal open that also means\n the modal\'s Available panel gets the full list back.\n\n## Async mode (`loadOptions`)\n\nServer-side filtering above leaves three things at every call site: the results state, a\nmonotonic-ticket guard against out-of-order responses (debouncing limits how often a request *starts*,\nnot how many are in flight), and \u2014 for a paged source \u2014 page accumulation plus the\n"is this loader replacing rows or appending them?" distinction. `loadOptions` moves all of it inside:\n\n```tsx\n<MultiSelectTransfer\n label="Rows"\n loadOptions={async (query, { cursor, signal }) => {\n const res = await fetchRows({ query, cursor, signal });\n return {\n options: res.rows.map((r) => ({ value: r.id, label: r.name })),\n cursor: res.nextToken, // absent/null \u21D2 no further pages\n total: res.totalCount // renders as "(loaded of total)" in the modal panel header\n };\n }}\n/>\n```\n\n`meta` carries `{ signal, cursor, page, reason }`; `reason` is `"defaults" | "search" | "more" | "reload"`.\nReturn a bare array for an unpaged source. Honouring `meta.signal` is optional \u2014 ordering is guaranteed\nby an internal per-slot ticket either way. A fresh inline arrow is fine: the loader is read through a ref.\n\nBehaviour worth knowing:\n\n- **Paging acts on the *active* bucket.** The empty-query baseline and the current search each carry\n their own cursor and page count, so paging a search and paging the baseline never interfere \u2014 and\n clearing the search back to the baseline resumes *its* paging from *its* cursor.\n- **Clearing the search restores the cached baseline with no request.** Pass `refetchOnClear` to also\n revalidate; stale rows stay on screen while it runs.\n- **A failed page keeps the rows** and offers **Retry** below them, and the infinite-scroll sentinel\n disarms until you press it \u2014 a sentinel still sitting in the viewport must not hammer a failing\n endpoint. Retry re-requests the *same* page; the cursor never advanced. A whole-list failure (the\n first page, a search, a reload) shows `loadErrorMessage` in place of the rows instead.\n- **Pages are appended with dedupe on `value`.** Server paging over an unstable sort returns\n duplicates, and both surfaces key their rows by `value`.\n- **The modal\'s Available search is server-side in async mode**, sharing the dropdown\'s single\n debounced query \u2014 over a paged pool, filtering only the pages that happen to be loaded would be a\n lie. Closing the modal (**Done** or **Cancel**) clears that query, so it never leaks into the\n dropdown. The **Selected** panel\'s search is always local: that side is a plain array with no server\n to ask, and there is nothing to page.\n- **The modal\'s Available panel is a projection** of the loaded pool minus the draft selection. A page\n that lands while the modal is open simply appears; an item the user already moved right is never\n yanked back. A committed option the pool never returned is supplied from a snapshot taken at open \u2014\n matched locally against the active query, so it cannot surface as a result for a search it does not\n match.\n\n This replaced an append-only fold effect, and it changes two things on the **non-async path too**\n (see [Migration notes](#migration-notes)).\n- **"Select All"** covers the loaded rows the active search leaves visible \u2014 never every server-side\n match. Toggling it off removes only those visible rows from the draft, so a selection made under an\n earlier query survives. The row is shown only when at least two selectable options are on screen.\n- **`optionsKey` does not clear the committed selection** \u2014 same reasoning as `Select`: that is a\n domain rule, and clearing a controlled `value` from inside means firing an `onChange` nobody asked for.\n- Options are stored exactly as returned, so extra fields you hang on an option survive and reach\n `onChange` as the same object.\n\n### Seeding with `initialOptions`\n\n`initialOptions` is for the case where **you already have the rows** \u2014 an SSR payload, a route loader, a\nwarm query cache. They are painted on the first frame of both surfaces instead of a loader, and stay on\nscreen while the baseline fetch revalidates over them \u2014 the dropdown\'s spinner appends *below* the rows,\nas it does for any load in flight, so the revalidation is visible without hiding anything. This is the\none thing `prefetch` cannot do: `prefetch="mount"` still costs a round trip before anything appears.\n\n```tsx\n<MultiSelectTransfer\n label="Rows"\n initialOptions={ssrRows} // painted immediately, in the dropdown and the modal\n loadOptions={fetchRows} // still runs, and replaces them when page one lands\n/>\n```\n\nIt does **not** suppress the baseline fetch. If the seed *is* the whole list until the user types \u2014 a\nheavy source you do not want to hit on open \u2014 pair it with `prefetch="never"`:\n\n```tsx\n<MultiSelectTransfer initialOptions={recentlyUsed} prefetch="never" loadOptions={searchEverything} />\n```\n\nWithout `initialOptions`, that combination opens to an empty list on both surfaces.\n\nSeed rows carry no cursor, so the infinite-scroll sentinel stays disarmed until a real page lands \u2014 a\nseed is not page one. A *search* replaces them, because they are not results for a query; clearing it\nbrings them back until a fetched baseline does. And seed rows only mean something to the async source \u2014\npassing `initialOptions` without `loadOptions` is ignored with a dev warning, because those rows belong\nin `options`.\n\n`prefetch` is async-only for the same reason: it schedules the baseline fetch and nothing else, so\nwithout `loadOptions` there is no fetch to schedule. Passing it there is ignored with a dev warning.\n\n## Migration notes\n\nAdding `loadOptions` is opt-in and every new prop is optional, so no call site has to change. Two\n**runtime** behaviours of the transfer-list modal did change for existing (non-async) consumers,\nbecause the modal\'s Available panel is now derived from `options` rather than folded into owned state:\n\n| Situation | Before | Now |\n|---|---|---|\n| An item is moved back from Selected to Available | It was **appended to the end** of Available | It returns to its position in `options` |\n| The parent **shrinks** `options` while the modal is open | Previously-shown rows **lingered** in Available | They disappear, matching the new `options` |\n\nNeither loses a selection or changes what `onChange` reports \u2014 the committed value is unaffected in\nboth cases. The first is a visible row-ordering difference; the second makes the panel honest about\nwhat the parent is actually offering. If you depended on either, own the pool yourself and drive the\n`TransferList` directly instead of through `MultiSelectTransfer`.\n\nEverything else on the legacy path is unchanged, including the `hasMore` / `onLoadMore` / `isLoading`\ntrio and the append-vs-replace loader behaviour in both the dropdown and the modal.\n\n## Practical Examples\n\n### 1. Controlled selection with a live count\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nconst options: TMultiSelectTransferOption[] = [\n { value: "chocolate", label: "Chocolate" },\n { value: "vanilla", label: "Vanilla" },\n { value: "strawberry", label: "Strawberry" },\n { value: "mint", label: "Mint" }\n];\n\nfunction FlavorPicker() {\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n\n return (\n <MultiSelectTransfer\n label="Flavors"\n placeholder="Select flavors..."\n options={options}\n value={selected}\n onChange={setSelected}\n helperText={`${selected.length} selected`}\n />\n );\n}\n```\n\n### 2. Validation and error state in a form\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n Button,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nfunction PermissionsField({ options }: { options: TMultiSelectTransferOption[] }) {\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n const [touched, setTouched] = useState(false);\n const hasError = touched && selected.length === 0;\n\n const handleSubmit = () => {\n setTouched(true);\n if (selected.length === 0) return;\n // submit selected...\n };\n\n return (\n <form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }}>\n <MultiSelectTransfer\n label="Permissions"\n placeholder="Assign permissions..."\n options={options}\n value={selected}\n onChange={setSelected}\n error={hasError}\n helperText={hasError ? "Select at least one permission." : undefined}\n />\n <Button type="submit">Save</Button>\n </form>\n );\n}\n```\n\n### 3. Server-side filtering with debounce\n\n```tsx\nimport { useEffect, useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nfunction RemoteUserPicker() {\n const [query, setQuery] = useState("");\n const [options, setOptions] = useState<TMultiSelectTransferOption[]>([]);\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n\n useEffect(() => {\n let active = true;\n setIsLoading(true);\n fetchUsers(query)\n .then((users) => {\n if (active) setOptions(users.map((u) => ({ value: u.id, label: u.name })));\n })\n .finally(() => active && setIsLoading(false));\n return () => { active = false; };\n }, [query]);\n\n return (\n <MultiSelectTransfer\n label="Assignees"\n placeholder="Select users..."\n options={options}\n value={selected}\n onChange={setSelected}\n onFilterChange={setQuery}\n filterDebounceMs={300}\n isLoading={isLoading}\n />\n );\n}\n```\n\n### 4. Paginated options with infinite scroll and reload\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nconst PAGE_SIZE = 20;\n\nfunction PaginatedPicker() {\n const [loaded, setLoaded] = useState<TMultiSelectTransferOption[]>([]);\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [isReloading, setIsReloading] = useState(false);\n const [hasMore, setHasMore] = useState(true);\n\n const loadMore = async () => {\n if (isLoading) return;\n setIsLoading(true);\n const page = await fetchPage(loaded.length, PAGE_SIZE);\n setLoaded((prev) => [...prev, ...page.items]);\n setHasMore(page.hasMore);\n setIsLoading(false);\n };\n\n const reload = async () => {\n setIsReloading(true);\n const page = await fetchPage(0, PAGE_SIZE);\n setLoaded(page.items);\n setHasMore(page.hasMore);\n setIsReloading(false);\n };\n\n return (\n <MultiSelectTransfer\n label="Items"\n placeholder="Select items..."\n options={loaded}\n value={selected}\n onChange={setSelected}\n hasMore={hasMore}\n onLoadMore={loadMore}\n isLoading={isLoading}\n onReload={reload}\n isReloading={isReloading}\n />\n );\n}\n```\n\n### 5. Ordered selection via the transfer-list modal\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nfunction ColumnManager({ columns }: { columns: TMultiSelectTransferOption[] }) {\n const [visible, setVisible] = useState<TMultiSelectTransferOption[]>([]);\n\n return (\n <MultiSelectTransfer\n label="Visible columns"\n placeholder="No columns selected..."\n options={columns}\n value={visible}\n onChange={setVisible}\n reorderable\n maxVisiblePills={2}\n transferListTitle="Manage columns"\n transferListSubtitle="Choose which columns appear and in what order."\n doneLabel="Apply"\n />\n );\n}\n```\n\n## Styling and Customization\n\n- Use `className` to add classes to the root container.\n- The `size` and `error` props cover the common visual states.\n- For deeper theming, import the exported variants and compose them directly:\n\n```tsx\nimport { multiSelectTransferVariants } from "@components/multiSelectTransfer";\n\nconst { trigger, pill } = multiSelectTransferVariants({ size: "lg", error: false });\n```\n\nDark mode follows the library convention (a `.dark` class on a root ancestor); all slots\nship dark-mode styles. Spacing uses logical properties (`ps-`, `pe-`, `ms-`, `me-`) so the\ncontrol mirrors correctly in RTL layouts.\n\n## Technical Details\n\n- **State management:** The trigger shows a **committed** selection while the dropdown and\n modal each maintain their own **draft**. Drafts commit on close/Done and discard on\n Escape/Cancel, giving a clear "confirm before apply" model. In uncontrolled mode the\n committed value is held internally; in controlled mode it tracks `value`.\n- **Focus model:** With the search input shown it is the dropdown\'s combobox \u2014 focused on open and\n carrying `aria-controls` and `aria-activedescendant` over the listbox beneath it. With\n `searchable={false}` there is no combobox to relocate: the listbox itself becomes the single tab\n stop, is focused on open, carries `aria-activedescendant`, and owns the same key handler \u2014 the shape\n each `TransferList` panel\'s listbox already uses. Escape still cancels back to the trigger, Tab still\n commits, and `Space` activates the active row (with the input present it is a literal character in\n the query). There is no type-ahead in either mode.\n- **Draft preservation:** The dropdown draft is keyed on the option values\' contents, not the\n array reference, so an unrelated parent re-render that passes a new `value` array cannot wipe\n an in-progress draft \u2014 it re-syncs only on a genuine external change or on (re)open.\n- **Filtering:** Without `onFilterChange`, options are filtered client-side via `matchesQuery`\n and memoized for stable identity. `matchesQuery` matches an option\'s `searchValue` first, then a\n string `label`, then its `value` \u2014 set `searchValue` on options whose `label` is custom JSX so\n they stay findable by their visible text. With `onFilterChange`, filtering is delegated to the parent\n and the query is debounced (`filterDebounceMs`); a pending debounce is cancelled on unmount, on an\n external `filterValue` reset, and whenever the component clears the query itself \u2014 where\n `onFilterChange("")` fires immediately instead, so a stale query can never overtake the reset.\n While Backspace/Delete is held the debounce is deferred until keyup (or blur), so a long-press\n cannot fire mid-hold. `filterValue` is a seed plus an external sync rather than a fully controlled\n value: the input owns its own text, a *new* `filterValue` overwrites it, and re-passing the same\n one does not pull it back \u2014 feed `onFilterChange` into the state you pass as `filterValue` to keep\n them in step. All of that lives in the shared `useFilterQuery` hook, which `Select` also uses, so\n the identically-named props on both components behave identically by construction.\n- **Virtualization:** Both the dropdown options list and the modal panels window large option\n sets (past ~100 items) so multi-thousand-item lists open and filter without mounting every row.\n- **Infinite scroll:** An `IntersectionObserver` sentinel (via `useInfiniteScroll`) calls\n `onLoadMore` when scrolled into view, gated on the open state. While the modal is open, newly\n loaded options are folded into the Available draft without duplicating or reclaiming items the\n user has already moved to Selected.\n- **Loading UI:** `isLoading` covers two situations with opposite needs, and the component tells them\n apart by whether the sentinel above asked for the load. A **search fetch** replaces the option rows\n with the loader \u2014 they belong to the previous query, so leaving them clickable would let the user\n pick an option the incoming results no longer contain (`Select` does the same). An empty-and-loading\n menu therefore shows the loader alone rather than "No options". Arrow/Enter are ignored while those\n rows are gone, so the keyboard cannot reach one either, and the listbox is marked `aria-busy`. A\n **load-more** is adding to those rows, so the loader is appended below them and the scroll position\n survives \u2014 a load-more stays a load-more until it finishes, even if the consumer flips `isLoading`\n a render or two after `onLoadMore`.\n- **Modal portal:** The transfer-list modal renders in a body portal. The dropdown\'s\n outside-click listener is suspended while the modal is open so a click inside the portal is not\n misread as an outside click.\n- **Pill overflow:** The trigger shows up to `maxVisiblePills` pills, then a "+N More" badge.\n Long pill labels truncate to a max width and surface the full text via a `Tooltip` only when\n actually clipped.\n\n## Accessibility\n\n**Implemented:**\n- The trigger is a keyboard-operable control: `role="button"`, `aria-haspopup="listbox"`, and\n `aria-expanded` reflecting the open state.\n- The trigger is focusable (`tabIndex={0}`) when enabled and removed from the tab order\n (`tabIndex={-1}`) when `disabled`.\n- Keyboard support on the trigger: `Enter`/`Space` toggle the dropdown; `Escape` closes and\n discards the draft.\n- Keyboard support in the dropdown: `Escape` cancels/discards and returns focus to the trigger\n so a keyboard user is never stranded on `<body>`; `Tab` commits the draft and lets focus move\n on naturally.\n- The `label` is associated with the trigger via `htmlFor`/`id` (auto-generated when `id` is\n omitted).\n- The transfer-list CTA and reload buttons carry descriptive `aria-label`/tooltip text.\n- The dropdown\'s search input is a `combobox` (`aria-controls` / `aria-activedescendant` /\n `aria-autocomplete="list"`) over the option `listbox`. With `searchable={false}` no combobox is\n rendered: the `listbox` takes `tabIndex={0}` and `aria-activedescendant` itself and is focused on\n open, so Arrow/Home/End/Enter/Space/Escape/Tab are unchanged. It stays focusable while the rows are\n replaced by a loader or an error, so Escape is never stranded.\n- Disabled options are excluded from selection and from "Select all".\n\n**Best Practices:**\n- Always provide a `label` (or an external `aria-label`) so the control is announced.\n- Use `error` together with `helperText` to communicate validation state visibly rather than by\n color alone.\n- Keep option `label`s meaningful as text \u2014 pills, tooltips, and screen readers all render them.\n- Provide stable, unique `value`s; reusing a value across options breaks selection tracking and\n keys.\n- When filtering server-side, keep `isLoading` accurate so assistive tech and users get correct\n loading feedback.\n'
|
|
3047
2751
|
}
|
|
3048
2752
|
],
|
|
3049
2753
|
"directories": []
|
|
@@ -3599,254 +3303,98 @@ export const scrollbarVariants = tv({
|
|
|
3599
3303
|
},
|
|
3600
3304
|
"select": {
|
|
3601
3305
|
"name": "select",
|
|
3602
|
-
"description":
|
|
3306
|
+
"description": 'The Select component provides a dropdown selection interface for choosing one option from a list. It includes search functionality (hidden with `searchable={false}`), custom rendering, and keyboard navigation. **When to use:** - Form fields requiring single selection from options - Filtering interfaces - Settings and preferences selection - Any scenario requiring choice from predefined list **Component Architecture:** - Built on `react-select`, which handles positioning (`menuPlacement="auto"`) and keyboard navigation - Styled with Tailwind CSS and `tailwind-variants` (`tv()`) - Search input lives inside the dropdown unless `searchable={false}` hides it; filtering is client-side by default, or delegated to the parent via `onFilterChange` (see [Filtering](#filtering)) - Accessible with proper ARIA attributes',
|
|
3603
3307
|
"dependencies": [
|
|
3604
3308
|
"react-select",
|
|
3605
3309
|
"react",
|
|
3606
3310
|
"tailwind-variants",
|
|
3311
|
+
"react-merge-refs",
|
|
3607
3312
|
"tailwind-merge"
|
|
3608
3313
|
],
|
|
3609
3314
|
"internalDependencies": [
|
|
3610
3315
|
"adpIcon",
|
|
3611
|
-
"checkbox",
|
|
3612
3316
|
"button",
|
|
3613
|
-
"
|
|
3317
|
+
"loader",
|
|
3318
|
+
"checkbox",
|
|
3319
|
+
"tooltip",
|
|
3320
|
+
"card"
|
|
3614
3321
|
],
|
|
3615
3322
|
"files": [
|
|
3616
3323
|
{
|
|
3617
3324
|
"name": "utils.ts",
|
|
3618
|
-
"content": `import { type StylesConfig, type GroupBase } from "react-select";
|
|
3619
|
-
|
|
3620
|
-
|
|
3621
|
-
|
|
3622
|
-
|
|
3623
|
-
export const getSelectableOptions = (
|
|
3624
|
-
options: readonly ( IOption | GroupBase<IOption> )[]
|
|
3625
|
-
): IOption[] =>
|
|
3626
|
-
options.filter(( o ): o is IOption => "value" in o && o.value !== "select-all" && !o.isDisabled );
|
|
3627
|
-
|
|
3628
|
-
// True when every selectable option is already in the draft. An empty selectable set is never
|
|
3629
|
-
// "all selected". Shared by the Select-All toggle (select.tsx) and the Select-All row's checked
|
|
3630
|
-
// state (SelectOption) so both agree on the same definition.
|
|
3631
|
-
export const areAllSelectableSelected = (
|
|
3632
|
-
options: readonly ( IOption | GroupBase<IOption> )[],
|
|
3633
|
-
draft: IOption[]
|
|
3634
|
-
): boolean => {
|
|
3635
|
-
const selectable = getSelectableOptions( options );
|
|
3636
|
-
if ( selectable.length === 0 ) {
|
|
3637
|
-
return false;
|
|
3638
|
-
}
|
|
3639
|
-
const draftValues = new Set( draft.map(( o ) => o.value ));
|
|
3640
|
-
return selectable.every(( o ) => draftValues.has( o.value ));
|
|
3641
|
-
};
|
|
3325
|
+
"content": 'import { type StylesConfig, type GroupBase } from "react-select";\nimport { type TSelectSize, type IOption } from "./types";\n\n// Synthetic Select-All row value, injected in select.tsx. Never query-matched \u2014 it is an affordance\n// over the result set, not a member of it.\nexport const SELECT_ALL_VALUE = "select-all";\n\nconst isSelectable = ( option: IOption ): boolean =>\n option.value !== SELECT_ALL_VALUE && !option.isDisabled;\n\n// The "Create ..." row react-select\'s Creatable appends to the option list, which it marks with\n// `__isNew__`. It is an action rather than a member of the pool: picking it produces an option that\n// does not exist yet, so it carries none of a real row\'s selection affordances.\nexport const isCreateOption = ( option: IOption ): boolean =>\n ( option as IOption & { __isNew__?: boolean }).__isNew__ === true;\n\n// The option a create produces, as an ordinary option. react-select stamps `__isNew__` on what it hands\n// to `onChange` as well as on the Create row, and within this component that mark means one thing: this\n// row is the Create affordance, so it has no checkbox and no part in filtering. An option that merely\n// came from a create is not that, so the mark comes off before it reaches either the list or the\n// consumer \u2014 who is invited to put it straight back into `options`, where it would otherwise land as a\n// second Create row.\nexport const toPoolOption = ( option: IOption ): IOption => {\n const pooled = { ...option } as IOption & { __isNew__?: boolean };\n delete pooled.__isNew__;\n return pooled;\n};\n\n// An entry is a group only when its `options` field is actually a list. Options are stored exactly as\n// returned by the consumer, so one may legitimately carry an unrelated `options` data field; keying the\n// branch on the key alone would send it down the group path and throw on `.filter`.\nconst isGroup = ( entry: IOption | GroupBase<IOption> ): entry is GroupBase<IOption> =>\n "options" in entry && Array.isArray(( entry as GroupBase<IOption> ).options );\n\n// The real, enabled options, with groups flattened so the Select-All affordance reaches their\n// children \u2014 a group has no `value` of its own, so a list of nothing but groups would otherwise\n// resolve to nothing selectable. Sync mode may mix loose options and groups freely; both shapes go\n// through one pass and the result stays in render order. Narrowing the result by the active query\n// gives what "all" refers to: the enabled options currently on screen.\nexport const getSelectableOptions = (\n options: readonly ( IOption | GroupBase<IOption> )[]\n): IOption[] => {\n const selectable: IOption[] = [];\n options.forEach(( entry ) => {\n if ( isGroup( entry )) {\n selectable.push( ...entry.options.filter( isSelectable ));\n } else if ( isSelectable( entry )) {\n selectable.push( entry );\n }\n });\n return selectable;\n};\n\n// Every value the pool already accounts for, groups flattened and disabled rows included: what a\n// created option is checked against before it is added, so a value the consumer supplies keeps its own\n// row rather than gaining a second one. Disabled rows count \u2014 an option the consumer has deliberately\n// put out of reach is still spoken for.\nexport const getPooledValues = (\n options: readonly ( IOption | GroupBase<IOption> )[]\n): Set<IOption["value"]> => {\n const values = new Set<IOption["value"]>();\n options.forEach(( entry ) => {\n if ( isGroup( entry )) {\n entry.options.forEach(( option ) => values.add( option.value ));\n } else {\n values.add( entry.value );\n }\n });\n return values;\n};\n\n// True when every selectable option is already in the draft. An empty selectable set is never\n// "all selected". Shared by the Select-All toggle and the row\'s checked state (both resolved in\n// select.tsx) so the two agree on one definition. Takes an already-narrowed option list rather than\n// the raw one, and the draft as a value Set, which is what keeps the check off a linear scan.\nexport const areAllSelectableSelected = (\n selectable: readonly IOption[],\n draftValues: ReadonlySet<IOption["value"]>\n): boolean => selectable.length > 0 && selectable.every(( o ) => draftValues.has( o.value ));\n\nexport const reactSelectCustomStyles = <\n IsMulti extends boolean,\n Group extends GroupBase<IOption>\n>(\n error: boolean,\n size: TSelectSize,\n multiSelect: boolean\n): StylesConfig<IOption, IsMulti, Group> => {\n return {\n container: ( base ) => ({\n ...base,\n display: "flex",\n flexDirection: "column",\n gap: "0.5rem"\n }),\n control: ( base, state ) => ({\n ...base,\n display: "flex",\n alignItems: "center",\n gap: "0.5rem",\n borderRadius: "0.5rem",\n padding: size === "md" ? "0.2rem 0.75rem" : "0.2rem 1rem",\n "&:hover": {\n borderColor: "inherit"\n },\n boxShadow: state.isFocused\n ? error\n ? "0px 0px 2px 2px #F1AE9D"\n : "0px 0px 2px 2px #99CBFA"\n : base.boxShadow,\n borderColor: error\n ? "rgb(var(--error-700))"\n : state.isFocused\n ? "rgb(var(--primary-500))"\n : "rgb(var(--gray-200))",\n backgroundColor: state.isDisabled\n ? "rgb(var(--gray-50))"\n : base.backgroundColor,\n "&:disabled": {\n color: "rgb(var(--secondary-200))"\n },\n // Dark mode styles\n ".dark &": {\n backgroundColor: state.isDisabled\n ? "rgb(var(--secondary-800))"\n : "rgb(var(--iridium))",\n boxShadow: state.isFocused\n ? error\n ? "0px 0px 2px 2px #F38176"\n : "0px 0px 2px 2px #99CBFA"\n : base.boxShadow,\n borderColor: error\n ? "rgb(var(--error-400))"\n : "rgb(var(--secondary-500))",\n "&:disabled": {\n color: "rgb(var(--secondary-300))"\n },\n color: "rgb(var(--secondary-400))"\n }\n }),\n menu: ( base ) => ({\n ...base,\n boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1)",\n borderRadius: "0.5rem",\n overflow: "hidden",\n border: "1px solid rgb(var(--secondary-50))",\n // Dark mode styles\n ".dark &": {\n backgroundColor: "rgb(var(--iridium))",\n borderColor: "rgb(var(--secondary-500))"\n }\n }),\n menuList: ( base ) => ({\n ...base,\n padding: 0\n }),\n // Loose options and groups may be mixed in one list, and react-select renders a loose option as a\n // SIBLING of the group before it with nothing marking where the group ended \u2014 so it reads as one of\n // that group\'s members. The rule closes each group off. Scoped to groups that are followed by\n // something, so a trailing group never draws a line against the menu\'s own edge.\n group: ( base ) => ({\n ...base,\n "&:not(:last-child)": {\n borderBottom: "1px solid rgb(var(--gray-200))",\n marginBottom: "0.5rem",\n ".dark &": { borderBottomColor: "rgb(var(--secondary-500))" }\n }\n }),\n // react-select\'s default heading is a hardcoded grey that ignores dark mode, and its 12px inset\n // leaves the label out of line with the option rows it heads.\n groupHeading: ( base ) => ({\n ...base,\n padding: "0 1rem",\n fontWeight: 600,\n color: "rgb(var(--secondary-400))",\n ".dark &": { color: "rgb(var(--secondary-300))" }\n }),\n menuPortal: ( base ) => ({\n ...base,\n zIndex: 2020\n }),\n option: ( base, state ) => ({\n ...base,\n ...( multiSelect ? { display: "flex", alignItems: "center" } : {}),\n color: "rgb(var(--secondary-500))",\n fontWeight: "normal",\n padding: "0.625rem 1rem",\n transition: "200ms ease-in-out",\n position: "relative",\n backgroundColor: "transparent",\n "&:after":\n state.isSelected && !multiSelect\n ? {\n content: "\\"\\"",\n position: "absolute",\n height: "8px",\n width: "16px",\n transform: "rotate(-45deg)",\n border: "2px solid rgb(var(--secondary-500))",\n right: "0.4rem",\n top: "35%",\n borderTop: 0,\n borderRight: 0\n }\n : {},\n // Dark mode styles\n ".dark &": {\n color: "rgb(var(--secondary-200))",\n "&:after":\n state.isSelected && !multiSelect\n ? {\n content: "\\"\\"",\n position: "absolute",\n height: "8px",\n width: "16px",\n transform: "rotate(-45deg)",\n border: "2px solid rgb(var(--gray-800))",\n right: "0.4rem",\n top: "35%",\n borderTop: 0,\n borderRight: 0\n }\n : {}\n }\n }),\n indicatorsContainer: ( base ) => ({ ...base, display: "flex", alignItems: "center", gap: "8px" }),\n valueContainer: ( base ) => ({ ...base, padding: 0, ...multiSelect ? { gap: "0.25rem" } : {} }),\n clearIndicator: ( base ) => ({ ...base, padding: 0 }),\n multiValue: ( base, state ) => ({\n ...base,\n margin: "0 0.5rem 0 0",\n borderRadius: "0.25rem",\n // Cap each chip and let its label truncate (react-select\'s multiValueLabel already sets\n // overflow:hidden + text-overflow:ellipsis) so one long value can\'t stretch the control.\n maxWidth: size === "md" ? "12rem" : "14rem",\n minWidth: 0,\n backgroundColor: state.isDisabled\n ? "rgb(var(--gray-100))"\n : "rgb(var(--gray-50))",\n color: state.isDisabled\n ? "rgb(var(--secondary-300))"\n : "rgb(var(--secondary-500))",\n ".dark &": {\n backgroundColor: "rgb(var(--secondary-600))",\n color: state.isDisabled\n ? "rgb(var(--secondary-400))"\n : "rgb(var(--secondary-200))"\n }\n }),\n multiValueLabel: ( base, state ) => ({\n ...base,\n padding: "0.25rem",\n fontSize: size === "md" ? "0.875rem" : "1rem",\n color: state.isDisabled\n ? "rgb(var(--secondary-300))"\n : "rgb(var(--secondary-500))",\n ".dark &": {\n color: state.isDisabled\n ? "rgb(var(--secondary-400))"\n : "rgb(var(--secondary-200))"\n }\n }),\n multiValueRemove: ( base, state ) => ({\n ...base,\n padding: "0.25rem",\n paddingLeft: "0!important",\n display: state.data.isFixed ? "none" : "flex",\n alignItems: "center",\n justifyContent: "center",\n marginStart: "-0.5rem",\n "&:hover": {\n backgroundColor: "transparent",\n color: "inherit"\n }\n }),\n input: ( base ) => ({\n ...base,\n margin: 0,\n padding: 0,\n fontSize: size === "md" ? "0.875rem" : "1rem",\n color: "rgb(var(--secondary-500))",\n ".dark &": { color: "rgb(var(--secondary-200))" }\n }),\n singleValue: ( base, state ) => ({\n ...base,\n margin: 0,\n fontSize: size === "md" ? "0.875rem" : "1rem",\n color: state.isDisabled\n ? "rgb(var(--secondary-300))"\n : "rgb(var(--secondary-500))",\n ".dark &": {\n color: state.isDisabled\n ? "rgb(var(--secondary-400))"\n : "rgb(var(--secondary-200))"\n }\n }),\n placeholder: ( base ) => ({\n ...base,\n fontSize: size === "md" ? "0.875rem" : "1rem",\n color: "rgb(var(--secondary-200))",\n ".dark &": { color: "rgb(var(--secondary-400))" }\n })\n };\n};'
|
|
3326
|
+
},
|
|
3327
|
+
{
|
|
3328
|
+
"name": "useSelectOutsideClose.ts",
|
|
3329
|
+
"content": `import { useEffect, type MutableRefObject } from "react";
|
|
3642
3330
|
|
|
3643
|
-
|
|
3644
|
-
|
|
3645
|
-
|
|
3646
|
-
|
|
3647
|
-
|
|
3648
|
-
|
|
3649
|
-
|
|
3650
|
-
|
|
3651
|
-
|
|
3652
|
-
|
|
3653
|
-
|
|
3654
|
-
|
|
3655
|
-
|
|
3656
|
-
|
|
3657
|
-
|
|
3658
|
-
|
|
3659
|
-
|
|
3660
|
-
|
|
3661
|
-
|
|
3662
|
-
|
|
3663
|
-
|
|
3664
|
-
|
|
3665
|
-
|
|
3666
|
-
|
|
3667
|
-
|
|
3668
|
-
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
|
|
3672
|
-
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
: state.isFocused
|
|
3676
|
-
? "rgb(var(--primary-500))"
|
|
3677
|
-
: "rgb(var(--gray-200))",
|
|
3678
|
-
backgroundColor: state.isDisabled
|
|
3679
|
-
? "rgb(var(--gray-50))"
|
|
3680
|
-
: base.backgroundColor,
|
|
3681
|
-
"&:disabled": {
|
|
3682
|
-
color: "rgb(var(--secondary-200))"
|
|
3683
|
-
},
|
|
3684
|
-
// Dark mode styles
|
|
3685
|
-
".dark &": {
|
|
3686
|
-
backgroundColor: state.isDisabled
|
|
3687
|
-
? "rgb(var(--secondary-800))"
|
|
3688
|
-
: "rgb(var(--iridium))",
|
|
3689
|
-
boxShadow: state.isFocused
|
|
3690
|
-
? error
|
|
3691
|
-
? "0px 0px 2px 2px #F38176"
|
|
3692
|
-
: "0px 0px 2px 2px #99CBFA"
|
|
3693
|
-
: base.boxShadow,
|
|
3694
|
-
borderColor: error
|
|
3695
|
-
? "rgb(var(--error-400))"
|
|
3696
|
-
: "rgb(var(--secondary-500))",
|
|
3697
|
-
"&:disabled": {
|
|
3698
|
-
color: "rgb(var(--secondary-300))"
|
|
3699
|
-
},
|
|
3700
|
-
color: "rgb(var(--secondary-400))"
|
|
3701
|
-
}
|
|
3702
|
-
}),
|
|
3703
|
-
menu: ( base ) => ({
|
|
3704
|
-
...base,
|
|
3705
|
-
boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1)",
|
|
3706
|
-
borderRadius: "0.5rem",
|
|
3707
|
-
overflow: "hidden",
|
|
3708
|
-
border: "1px solid rgb(var(--secondary-50))",
|
|
3709
|
-
// Dark mode styles
|
|
3710
|
-
".dark &": {
|
|
3711
|
-
backgroundColor: "rgb(var(--iridium))",
|
|
3712
|
-
borderColor: "rgb(var(--secondary-500))"
|
|
3713
|
-
}
|
|
3714
|
-
}),
|
|
3715
|
-
menuList: ( base ) => ({
|
|
3716
|
-
...base,
|
|
3717
|
-
padding: 0
|
|
3718
|
-
}),
|
|
3719
|
-
menuPortal: ( base ) => ({
|
|
3720
|
-
...base,
|
|
3721
|
-
zIndex: 2020
|
|
3722
|
-
}),
|
|
3723
|
-
option: ( base, state ) => ({
|
|
3724
|
-
...base,
|
|
3725
|
-
...( multiSelect ? { display: "flex", alignItems: "center" } : {}),
|
|
3726
|
-
color: "rgb(var(--secondary-500))",
|
|
3727
|
-
fontWeight: "normal",
|
|
3728
|
-
padding: "0.625rem 1rem",
|
|
3729
|
-
transition: "200ms ease-in-out",
|
|
3730
|
-
position: "relative",
|
|
3731
|
-
backgroundColor: "transparent",
|
|
3732
|
-
"&:after":
|
|
3733
|
-
state.isSelected && !multiSelect
|
|
3734
|
-
? {
|
|
3735
|
-
content: "\\"\\"",
|
|
3736
|
-
position: "absolute",
|
|
3737
|
-
height: "8px",
|
|
3738
|
-
width: "16px",
|
|
3739
|
-
transform: "rotate(-45deg)",
|
|
3740
|
-
border: "2px solid rgb(var(--secondary-500))",
|
|
3741
|
-
right: "0.4rem",
|
|
3742
|
-
top: "35%",
|
|
3743
|
-
borderTop: 0,
|
|
3744
|
-
borderRight: 0
|
|
3745
|
-
}
|
|
3746
|
-
: {},
|
|
3747
|
-
// Dark mode styles
|
|
3748
|
-
".dark &": {
|
|
3749
|
-
color: "rgb(var(--secondary-200))",
|
|
3750
|
-
"&:after":
|
|
3751
|
-
state.isSelected && !multiSelect
|
|
3752
|
-
? {
|
|
3753
|
-
content: "\\"\\"",
|
|
3754
|
-
position: "absolute",
|
|
3755
|
-
height: "8px",
|
|
3756
|
-
width: "16px",
|
|
3757
|
-
transform: "rotate(-45deg)",
|
|
3758
|
-
border: "2px solid rgb(var(--gray-800))",
|
|
3759
|
-
right: "0.4rem",
|
|
3760
|
-
top: "35%",
|
|
3761
|
-
borderTop: 0,
|
|
3762
|
-
borderRight: 0
|
|
3763
|
-
}
|
|
3764
|
-
: {}
|
|
3765
|
-
}
|
|
3766
|
-
}),
|
|
3767
|
-
indicatorsContainer: ( base ) => ({ ...base, display: "flex", alignItems: "center", gap: "8px" }),
|
|
3768
|
-
valueContainer: ( base ) => ({ ...base, padding: 0, ...multiSelect ? { gap: "0.25rem" } : {} }),
|
|
3769
|
-
clearIndicator: ( base ) => ({ ...base, padding: 0 }),
|
|
3770
|
-
multiValue: ( base, state ) => ({
|
|
3771
|
-
...base,
|
|
3772
|
-
margin: "0 0.5rem 0 0",
|
|
3773
|
-
borderRadius: "0.25rem",
|
|
3774
|
-
// Cap each chip and let its label truncate (react-select's multiValueLabel already sets
|
|
3775
|
-
// overflow:hidden + text-overflow:ellipsis) so one long value can't stretch the control.
|
|
3776
|
-
maxWidth: size === "md" ? "12rem" : "14rem",
|
|
3777
|
-
minWidth: 0,
|
|
3778
|
-
backgroundColor: state.isDisabled
|
|
3779
|
-
? "rgb(var(--gray-100))"
|
|
3780
|
-
: "rgb(var(--gray-50))",
|
|
3781
|
-
color: state.isDisabled
|
|
3782
|
-
? "rgb(var(--secondary-300))"
|
|
3783
|
-
: "rgb(var(--secondary-500))",
|
|
3784
|
-
".dark &": {
|
|
3785
|
-
backgroundColor: "rgb(var(--secondary-600))",
|
|
3786
|
-
color: state.isDisabled
|
|
3787
|
-
? "rgb(var(--secondary-400))"
|
|
3788
|
-
: "rgb(var(--secondary-200))"
|
|
3789
|
-
}
|
|
3790
|
-
}),
|
|
3791
|
-
multiValueLabel: ( base, state ) => ({
|
|
3792
|
-
...base,
|
|
3793
|
-
padding: "0.25rem",
|
|
3794
|
-
fontSize: size === "md" ? "0.875rem" : "1rem",
|
|
3795
|
-
color: state.isDisabled
|
|
3796
|
-
? "rgb(var(--secondary-300))"
|
|
3797
|
-
: "rgb(var(--secondary-500))",
|
|
3798
|
-
".dark &": {
|
|
3799
|
-
color: state.isDisabled
|
|
3800
|
-
? "rgb(var(--secondary-400))"
|
|
3801
|
-
: "rgb(var(--secondary-200))"
|
|
3331
|
+
interface IUseSelectOutsideCloseArgs {
|
|
3332
|
+
/** Only while the menu is open is a listener attached. */
|
|
3333
|
+
menuOpen: boolean;
|
|
3334
|
+
/** The menu's (possibly portaled) DOM node, so clicks inside it are not "outside". */
|
|
3335
|
+
menuNodeRef: MutableRefObject<HTMLDivElement | null>;
|
|
3336
|
+
/** Commits the multi-select draft, then closes. */
|
|
3337
|
+
commitAndClose: () => void;
|
|
3338
|
+
}
|
|
3339
|
+
|
|
3340
|
+
/**
|
|
3341
|
+
* Closes the dropdown on interaction outside the component. react-select's own outside-click
|
|
3342
|
+
* handling relies on its input being focused (it is not \u2014 focus lives in the dropdown search input),
|
|
3343
|
+
* so Select handles it here instead.
|
|
3344
|
+
*/
|
|
3345
|
+
export function useSelectOutsideClose({
|
|
3346
|
+
menuOpen,
|
|
3347
|
+
menuNodeRef,
|
|
3348
|
+
commitAndClose
|
|
3349
|
+
}: IUseSelectOutsideCloseArgs ): void {
|
|
3350
|
+
useEffect(() => {
|
|
3351
|
+
if ( !menuOpen ) {
|
|
3352
|
+
return undefined;
|
|
3353
|
+
}
|
|
3354
|
+
const handlePointerDown = ( e: MouseEvent ) => {
|
|
3355
|
+
// Outsideness is read off the event's dispatch path, which names every element the mousedown
|
|
3356
|
+
// travelled through even once the DOM has moved on. react-select swaps the control input of
|
|
3357
|
+
// the Select being opened, so the clicked node is frequently detached by the time this
|
|
3358
|
+
// listener runs and its ancestors are no longer reachable from it.
|
|
3359
|
+
const path = e.composedPath();
|
|
3360
|
+
const target = ( path[0] ?? e.target ) as HTMLElement | null;
|
|
3361
|
+
if ( !target ) {
|
|
3362
|
+
return;
|
|
3802
3363
|
}
|
|
3803
|
-
|
|
3804
|
-
|
|
3805
|
-
|
|
3806
|
-
|
|
3807
|
-
paddingLeft: "0!important",
|
|
3808
|
-
display: state.data.isFixed ? "none" : "flex",
|
|
3809
|
-
alignItems: "center",
|
|
3810
|
-
justifyContent: "center",
|
|
3811
|
-
marginStart: "-0.5rem",
|
|
3812
|
-
"&:hover": {
|
|
3813
|
-
backgroundColor: "transparent",
|
|
3814
|
-
color: "inherit"
|
|
3364
|
+
// Clicks inside the (possibly portaled) menu keep it open.
|
|
3365
|
+
const menuNode = menuNodeRef.current;
|
|
3366
|
+
if ( menuNode && path.includes( menuNode )) {
|
|
3367
|
+
return;
|
|
3815
3368
|
}
|
|
3816
|
-
|
|
3817
|
-
|
|
3818
|
-
|
|
3819
|
-
|
|
3820
|
-
padding: 0,
|
|
3821
|
-
fontSize: size === "md" ? "0.875rem" : "1rem",
|
|
3822
|
-
color: "rgb(var(--secondary-500))",
|
|
3823
|
-
".dark &": { color: "rgb(var(--secondary-200))" }
|
|
3824
|
-
}),
|
|
3825
|
-
singleValue: ( base, state ) => ({
|
|
3826
|
-
...base,
|
|
3827
|
-
margin: 0,
|
|
3828
|
-
fontSize: size === "md" ? "0.875rem" : "1rem",
|
|
3829
|
-
color: state.isDisabled
|
|
3830
|
-
? "rgb(var(--secondary-300))"
|
|
3831
|
-
: "rgb(var(--secondary-500))",
|
|
3832
|
-
".dark &": {
|
|
3833
|
-
color: state.isDisabled
|
|
3834
|
-
? "rgb(var(--secondary-400))"
|
|
3835
|
-
: "rgb(var(--secondary-200))"
|
|
3369
|
+
// The per-chip remove "\xD7" and the clear-all control have their own react-select handlers;
|
|
3370
|
+
// don't hijack those into a menu close.
|
|
3371
|
+
if ( target.closest?.( ".select__multi-value__remove, .select__clear-indicator" )) {
|
|
3372
|
+
return;
|
|
3836
3373
|
}
|
|
3837
|
-
|
|
3838
|
-
|
|
3839
|
-
|
|
3840
|
-
|
|
3841
|
-
|
|
3842
|
-
|
|
3843
|
-
|
|
3844
|
-
|
|
3845
|
-
}
|
|
3374
|
+
// Everything else \u2014 the control body/chevron (toggle-closed), another Select's control, or a
|
|
3375
|
+
// truly outside click \u2014 commits the draft and closes.
|
|
3376
|
+
commitAndClose();
|
|
3377
|
+
};
|
|
3378
|
+
// Defer attaching the listener so the click that opened the menu cannot immediately
|
|
3379
|
+
// close it.
|
|
3380
|
+
const raf = requestAnimationFrame(() => {
|
|
3381
|
+
document.addEventListener( "mousedown", handlePointerDown );
|
|
3382
|
+
});
|
|
3383
|
+
return () => {
|
|
3384
|
+
cancelAnimationFrame( raf );
|
|
3385
|
+
document.removeEventListener( "mousedown", handlePointerDown );
|
|
3386
|
+
};
|
|
3387
|
+
}, [ menuOpen, commitAndClose, menuNodeRef ]);
|
|
3388
|
+
}
|
|
3389
|
+
`
|
|
3390
|
+
},
|
|
3391
|
+
{
|
|
3392
|
+
"name": "useSelectOptionSource.ts",
|
|
3393
|
+
"content": 'import { type ReactNode } from "react";\nimport type { GroupBase } from "react-select";\n\nimport { useAsyncOptions, useIgnoredPropWarning, type TPrefetch } from "@hooks";\nimport { resolveLoadErrors, resolveReloadControls } from "@utils";\nimport type { IOption, TSelectLoadOptions, TSelectOptions } from "./types";\n\n// Module-level so the identity is stable across renders when `options` is absent \u2014 a fresh `[]`\n// per render would invalidate handleSelectAllDraft\'s useCallback and the whole option context.\nconst EMPTY_OPTIONS: readonly never[] = [];\n\ninterface IUseSelectOptionSourceArgs<Group extends GroupBase<IOption>> {\n options?: TSelectOptions<Group>;\n loadOptions?: TSelectLoadOptions;\n initialOptions?: readonly IOption[];\n prefetch?: TPrefetch;\n refetchOnClear?: boolean;\n optionsKey?: string | number;\n loadErrorMessage?: ReactNode;\n showReloadButton?: boolean;\n onLoadError?: ( error: unknown ) => void;\n /** Consumer-owned loading flag; OR-ed with the async loader rather than replaced by it. */\n isLoading?: boolean;\n onReload?: () => void;\n isReloading?: boolean;\n onFilterChange?: ( query: string ) => void;\n}\n\ninterface ISelectOptionSource<Group extends GroupBase<IOption>> {\n options: TSelectOptions<Group>;\n isServerFiltered: boolean;\n /** Loader instead of rows (SelectMenu\'s `isLoading`). */\n isLoading: boolean;\n isReloading?: boolean;\n onReload?: () => void;\n /** Hand to `useFilterQuery`; notifies the consumer AND drives the async source. */\n onFilterQueryChange: ( query: string ) => void;\n ensureDefaults: () => void;\n loadError?: ReactNode;\n}\n\n/**\n * All of `Select`\'s option-source policy: async vs sync mode detection, value precedence between the\n * consumer\'s own flags and the loader\'s derived ones, default messages, and the dev warnings for the\n * two footguns a type-level XOR cannot express against react-select\'s generics.\n */\nexport function useSelectOptionSource<Group extends GroupBase<IOption>>({\n options,\n loadOptions,\n initialOptions,\n prefetch,\n refetchOnClear = false,\n optionsKey,\n loadErrorMessage,\n showReloadButton = false,\n onLoadError,\n isLoading,\n onReload,\n isReloading,\n onFilterChange\n}: IUseSelectOptionSourceArgs<Group> ): ISelectOptionSource<Group> {\n const isAsync = typeof loadOptions === "function";\n\n const asyncOptions = useAsyncOptions<IOption>({\n loadOptions,\n initialOptions,\n prefetchDefaults: prefetch !== "never",\n refetchOnClear,\n optionsKey,\n onLoadError,\n getOptionKey: ( option ) => option.value\n });\n\n // The two footguns a type-level XOR cannot express against react-select\'s generics.\n useIgnoredPropWarning(\n isAsync && options !== undefined,\n "Select: `options` is ignored when `loadOptions` is set \u2014 use `initialOptions` to seed the list."\n );\n useIgnoredPropWarning(\n asyncOptions.hasMore,\n "Select: `loadOptions` reported `hasMore` \u2014 Select does not page. Use MultiSelectTransfer."\n );\n // The mirror of the first: seed rows only mean anything to the async source, so without a loader they\n // vanish silently \u2014 the same mistake as passing `options` in async mode, and just as quiet.\n useIgnoredPropWarning(\n !isAsync && initialOptions !== undefined,\n "Select: `initialOptions` is ignored without `loadOptions` \u2014 pass those rows as `options` instead."\n );\n // Same class of mistake: `prefetch` only ever schedules the baseline fetch, so with the rows already\n // in `options` there is nothing for it to trigger and it silently does nothing.\n useIgnoredPropWarning(\n !isAsync && prefetch !== undefined,\n "Select: `prefetch` is ignored without `loadOptions` \u2014 `options` are already on screen, so there is nothing to fetch."\n );\n\n // Notifies the consumer AND drives the async source, so onFilterChange keeps working for analytics\n // and filterValue syncing in async mode. Not memoised: useFilterQuery reads its handler through a ref.\n const onFilterQueryChange = ( query: string ): void => {\n onFilterChange?.( query );\n asyncOptions.onFilterChange( query );\n };\n\n return {\n options: isAsync ? asyncOptions.options : options ?? EMPTY_OPTIONS,\n isServerFiltered: isAsync || typeof onFilterChange === "function",\n // OR-ed, not switched: a consumer raising isLoading in async mode for their own reason wants a loader.\n isLoading: isLoading === true || ( isAsync && asyncOptions.isReplacing ),\n ...resolveReloadControls({ isAsync, source: asyncOptions, onReload, isReloading, showReloadButton }),\n onFilterQueryChange,\n ensureDefaults: asyncOptions.ensureDefaults,\n // Select never pages, so `loadMoreError` is unreachable here and deliberately dropped.\n loadError: resolveLoadErrors({\n errorKind: asyncOptions.errorKind,\n loadErrorMessage\n }).loadError\n };\n}\n'
|
|
3846
3394
|
},
|
|
3847
3395
|
{
|
|
3848
3396
|
"name": "types.ts",
|
|
3849
|
-
"content": 'import type { ReactNode, ReactElement, MutableRefObject, RefObject } from "react";\nimport type { Props as ReactSelectProps, GroupBase } from "react-select";\n\nimport { type TIconType } from "../adpIcon";\n\n/**\n * Available sizes for the Select component\n */\nexport enum ESelectSizes {\n MD = "md",\n LG = "lg"\n}\n\n/**\n * Size type derived from available sizes\n */\nexport type TSelectSize = `${ESelectSizes}`;\n\n/**\n * Option type for Select component\n */\nexport interface IOption {\n label: ReactNode;\n value: any;\n /** Plain-text used for searching when `label` is a ReactNode. Takes precedence over label/value. */\n searchValue?: string;\n isFixed?: boolean;\n isDisabled?: boolean;\n}\n\n/**\n * Props for the Select component\n */\nexport interface ISelectProps<\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n> extends Omit<\n ReactSelectProps<IOption, IsMulti, Group>,\n // `inputValue`, `onInputChange` and `isSearchable` are intentionally omitted: this component\n // owns an internal search box (see `searchPlaceholder`) and controls react-select\'s inputValue\n // itself, so these react-select props would silently no-op if forwarded.\n "options" | "value" | "className" | "inputValue" | "onInputChange" | "isSearchable"\n > {\n /** Unique id for the select input */\n id?: string;\n /** Custom className for wrapper */\n className?: string;\n /** Label displayed above select */\n label?: ReactNode;\n /** Select size variant */\n size?: TSelectSize;\n /** Options or groups to render */\n options?: ReactSelectProps<IOption, IsMulti, Group>["options"];\n /** Current value of the select */\n value?: ReactSelectProps<IOption, IsMulti, Group>["value"];\n /** Helper text displayed below */\n helperText?: ReactNode;\n /** Display error styling */\n error?: boolean;\n /** Disable the select */\n disabled?: boolean;\n /** Enable creatable select */\n creatable?: boolean;\n /** Field touched state */\n touched?: boolean;\n /** Max number of visible values in multi */\n maxVisibleValues?: number;\n /** Label for truncated values */\n maxVisibleValuesMsg?: string;\n /** Custom footer in menu */\n menuFooter?: ReactNode;\n /** Prefix icon for the control */\n prefixIcon?: TIconType | ReactNode;\n /** Suffix icon for the control */\n suffixIcon?: TIconType | ReactNode;\n /** Placeholder text for the search input inside the dropdown */\n searchPlaceholder?: string;\n /** Tooltip for the select reload button. */\n reloadTooltip?: string;\n /** The reload button is shown when this is provided. Fired when the reload button is clicked. */\n onReload?: () => void;\n /** Spins the select reload button. */\n isReloading?: boolean;\n}\n\n/**\n * Per-render option config for the SelectOption component. react-select keys custom components by\n * reference and remounts them whenever that reference changes; the `customComponents` object in\n * select.tsx is rebuilt every render. Feeding these live values through context (rather than a\n * closure inside a freshly-created Option) lets SelectOption keep a stable module-level identity,\n * so react-select re-renders it in place instead of remounting - which is what keeps the\n * `useIsTruncated` measurement (and the hover-expand affordance) from flickering.\n */\nexport interface ISelectOptionContext {\n /** In-progress multi-select draft. Drives checkboxes / Select All while the committed value drives the control. */\n draftValues?: IOption[];\n /** Toggle a single option in the multi-select draft. */\n onToggleDraftOption?: ( option: IOption ) => void;\n /** Toggle Select All / Deselect All on the multi-select draft (shared with the keyboard path). */\n onSelectAll?: () => void;\n /** tv() class for the label wrapper. */\n optionLabelWrapClass: string;\n /** tv() class for the (truncating) label. */\n optionLabelClass: string;\n /** tv() class for the hover/focus full-text overlay. */\n optionOverlayClass: string;\n /**\n * Latest input modality, shared across every option. The full-text overlay follows the pointer\n * (local `isHovered`) while the user is using the mouse, and react-select\'s `isFocused` while\n * they\'re navigating by keyboard. Without this, react-select\'s `isFocused` - which lingers on the\n * last-focused option after the pointer leaves, and is also set by mouse hover - keeps an\n * overlay visible after the mouse has moved away (and shows two at once mid-transition).\n */\n interactionModeRef: MutableRefObject<"pointer" | "keyboard">;\n}\n\n/**\n * Live, per-instance config for the stable SelectMenu component. Mirrors {@link ISelectOptionContext}:\n * routing these through context lets SelectMenu keep a module-level identity - so react-select never\n * remounts it and the search input keeps its focus, caret, and scroll position across keystrokes -\n * while still re-rendering with current values whenever they change. (A component closing over these\n * directly would freeze them at first render, since its identity must never change.)\n */\nexport interface ISelectMenuContext {\n /** Current search text (controls react-select\'s inputValue). */\n filterQuery: string;\n /** Called with the search input\'s new value. */\n onFilterChange: ( value: string ) => void;\n /** Placeholder for the search input. */\n searchPlaceholder: string;\n /** Optional custom footer rendered below the option list. */\n menuFooter?: ReactNode;\n /** Close the menu, discarding the multi-select draft. */\n closeMenu: () => void;\n /** Commit the multi-select draft, then close. */\n commitAndClose: () => void;\n /** tv() class for the search container. */\n searchContainerClass: string;\n /** tv() class for the search input. */\n searchInputClass: string;\n /** Ref to the search input; focused when the menu opens. */\n searchInputRef: RefObject<HTMLInputElement>;\n /** Captures the menu\'s (possibly portaled) DOM node for the outside-click check. */\n menuNodeRef: MutableRefObject<HTMLDivElement | null>;\n /** Ref to the component wrapper, used to reach react-select\'s hidden control input. */\n containerRef: RefObject<HTMLDivElement>;\n /** Shown when provided; fired on reload-button click. */\n onReload?: () => void;\n /** Spins/disables the reload button. */\n isReloading?: boolean;\n /** Reload-button tooltip / aria-label. */\n reloadTooltip?: string;\n /** Shared input-modality flag (see {@link ISelectOptionContext}); flipped to "keyboard" here. */\n interactionModeRef: MutableRefObject<"pointer" | "keyboard">;\n}\n\nexport interface IOptionLabelOverlayProps {\n anchorRef: RefObject<HTMLElement>;\n className: string;\n children: ReactNode;\n}\n\nexport interface ITruncatedMultiValueProps {\n /** The plain-text label, used as the Tooltip title. */\n label: string;\n /** react-select\'s rendered chip (MultiValueContainer + label + remove). */\n chip: ReactElement;\n}\n\nexport interface ISelectComponentsConfig {\n prefixIcon?: TIconType | ReactNode;\n suffixIcon?: TIconType | ReactNode;\n maxVisibleValues: number;\n maxVisibleValuesMsg?: string;\n disabled: boolean;\n}\n'
|
|
3397
|
+
"content": 'import type {\n ChangeEvent,\n FocusEvent,\n KeyboardEvent,\n ReactNode,\n ReactElement,\n MutableRefObject,\n RefObject\n} from "react";\nimport type { Props as ReactSelectProps, GroupBase } from "react-select";\n\nimport type { TLoadOptions, TPrefetch } from "@hooks";\nimport { type TIconType } from "../adpIcon";\n\n/**\n * Available sizes for the Select component\n */\nexport enum ESelectSizes {\n MD = "md",\n LG = "lg"\n}\n\n/**\n * Size type derived from available sizes\n */\nexport type TSelectSize = `${ESelectSizes}`;\n\n/**\n * Option type for Select component\n */\nexport interface IOption {\n label: ReactNode;\n value: any;\n /** Plain-text used for searching when `label` is a ReactNode. Takes precedence over label/value. */\n searchValue?: string;\n isFixed?: boolean;\n isDisabled?: boolean;\n}\n\n/**\n * Async option source. Page one only: a resolved page that reports `hasMore` is dev-warned, and no\n * further page is ever requested.\n */\nexport type TSelectLoadOptions = TLoadOptions<IOption>;\n\n/** Latest input modality. Drives which signal shows an option\'s full-text overlay. */\nexport type TSelectInteractionMode = "pointer" | "keyboard";\n\n/** Options as react-select accepts them \u2014 sync mode may carry groups; async mode never does. */\nexport type TSelectOptions<Group extends GroupBase<IOption> = GroupBase<IOption>> =\n readonly ( IOption | Group )[];\n\n/**\n * Props for the Select component\n */\nexport interface ISelectProps<\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n> extends Omit<\n ReactSelectProps<IOption, IsMulti, Group>,\n // `inputValue`, `onInputChange` and `isSearchable` are intentionally omitted: this component\n // owns an internal search box (see `searchPlaceholder`) and controls react-select\'s inputValue\n // itself, so these react-select props would silently no-op if forwarded.\n // `isLoading` and `filterOption` are omitted and re-declared below (not forwarded to react-select).\n // `tabSelectsValue` is omitted because Tab commits the multi-select draft and leaves: selecting the\n // focused option on the way out would toggle a value the user never chose.\n "options" | "value" | "className" | "inputValue" | "onInputChange" | "isSearchable" | "isLoading"\n | "filterOption" | "tabSelectsValue"\n > {\n /** Unique id for the select input */\n id?: string;\n /** Custom className for wrapper */\n className?: string;\n /** Label displayed above select */\n label?: ReactNode;\n /** Select size variant */\n size?: TSelectSize;\n /** Options or groups to render. Ignored (dev warning) when `loadOptions` is set \u2014 seed with `initialOptions` instead. */\n options?: ReactSelectProps<IOption, IsMulti, Group>["options"];\n /** Current value of the select */\n value?: ReactSelectProps<IOption, IsMulti, Group>["value"];\n /** Helper text displayed below */\n helperText?: ReactNode;\n /** Display error styling */\n error?: boolean;\n /** Disable the select */\n disabled?: boolean;\n /** Enable creatable select */\n creatable?: boolean;\n /** Field touched state */\n touched?: boolean;\n /** Max number of visible values in multi */\n maxVisibleValues?: number;\n /** Label for truncated values */\n maxVisibleValuesMsg?: string;\n /** Custom footer in menu */\n menuFooter?: ReactNode;\n /** Prefix icon for the control */\n prefixIcon?: TIconType | ReactNode;\n /** Suffix icon for the control */\n suffixIcon?: TIconType | ReactNode;\n /**\n * Renders the search input inside the dropdown. With `false` the menu opens straight onto the option\n * list and the control keeps the whole keyboard model: arrows and PageUp/PageDown move the focused\n * option, Home/End jump to its ends, Enter or Space selects, Escape closes and discards the\n * multi-select draft, Tab commits it. Space and Home/End work only in this mode \u2014 with a search input\n * on screen they belong to the text field. The reload button is independent of this and still renders\n * when `onReload` / `showReloadButton` is set.\n * @default true\n */\n searchable?: boolean;\n /** Placeholder text for the search input inside the dropdown. Ignored when `searchable={false}`. */\n searchPlaceholder?: string;\n /** Tooltip for the select reload button. */\n reloadTooltip?: string;\n /** The reload button is shown when this is provided. Fired when the reload button is clicked. */\n onReload?: () => void;\n /** Spins the select reload button. */\n isReloading?: boolean;\n /** Seeds/re-syncs dropdown search; semi-controlled \u2014 pair with onFilterChange. Applies in both modes. */\n filterValue?: string;\n /**\n * Debounced search-query callback; also called with "" when the component clears search.\n *\n * Without `loadOptions`: switches off local filtering \u2014 `options` is treated as already filtered\n * for the query \u2014 and the fetch, loading state, and response ordering are the consumer\'s\n * responsibility.\n *\n * With `loadOptions`: notification-only, for analytics or `filterValue` syncing.\n */\n onFilterChange?: ( query: string ) => void;\n /** Debounce for the search query, in both sync and `loadOptions` mode. Set to 0 to disable. @default 300 */\n filterDebounceMs?: number;\n /** Replaces option list with loader. OR-ed with the loader\'s own state, so it still applies in async mode. @default false */\n isLoading?: boolean;\n /**\n * Custom client-side match, replacing the shared `matchesQuery` default.\n *\n * @deprecated Use `onFilterChange` instead, which does the same job without a second filtering axis:\n * it hands you the query and treats `options` as already filtered, so your predicate lives in your own\n * `useMemo` rather than in a react-select callback. Pair with `filterDebounceMs={0}` to keep filtering\n * synchronous. Ignored entirely when filtering is already delegated (`onFilterChange`/`loadOptions`),\n * and scheduled for removal in the next major.\n *\n * ```tsx\n * const visible = useMemo(() => all.filter(( o ) => myMatch( o, query )), [ all, query ]);\n * <Select options={visible} onFilterChange={setQuery} filterDebounceMs={0} />\n * ```\n */\n filterOption?: ReactSelectProps<IOption, IsMulti, Group>["filterOption"];\n\n /**\n * Server-side option source. When provided, `Select` owns the option list, the request lifecycle and\n * the loading state; `options` is ignored (dev warning) and `onFilterChange` becomes\n * notification-only. Responsible for mapping the payload to `IOption` \u2014 envelopes and domain\n * filtering are the consumer\'s business. Options are stored exactly as returned, so extra fields\n * survive. A fresh inline arrow is fine: the loader is read through a ref.\n *\n * Page one only: `cursor` / `hasMore` / `total` in the result are ignored.\n */\n loadOptions?: TSelectLoadOptions;\n /**\n * Seed rows for a list you already have \u2014 an SSR payload, a route loader, a warm cache. They paint on the\n * first frame, so there is no loader to sit through, and they stay put while the baseline fetch revalidates\n * over them. They do not suppress that fetch: pair with `prefetch="never"` if the seed is the whole list\n * until the user types. A *search* replaces them, since seed rows are not results for a query; clearing it\n * brings them back until a fetched baseline lands. Async mode only \u2014 ignored (dev warning) without\n * `loadOptions`, where the rows belong in `options`.\n */\n initialOptions?: readonly IOption[];\n /**\n * When to fetch the unfiltered baseline.\n * - `"open"` \u2014 on first menu open. Right for forms with several server-filtered Selects, where paying\n * for menus the user may never open is the worse trade.\n * - `"mount"` \u2014 at render, before any interaction. Use when the list is near-certain to be needed and\n * a visible-but-empty Select would read as broken.\n * - `"never"` \u2014 no baseline at all; fetch only once the user types. For heavy lists.\n *\n * Async mode only \u2014 ignored (dev warning) without `loadOptions`, where `options` are already on screen\n * and there is nothing to fetch.\n * @default "open"\n */\n prefetch?: TPrefetch;\n /** Clearing the search revalidates the cached baseline instead of just restoring it. Costs one request per menu close. @default false */\n refetchOnClear?: boolean;\n /**\n * Identity of the option set, for dependent selects. When it changes, cached results are dropped and\n * the list is repopulated \u2014 immediately if the menu is open, otherwise on next open. Compose several\n * parents into one scalar: ``optionsKey={`${domainId}|${accessType}`}``. Does NOT clear the selection.\n */\n optionsKey?: string | number;\n /** Shown in the menu when `loadOptions` rejects. @default "Couldn\'t load options." */\n loadErrorMessage?: ReactNode;\n /** Shows the menu\'s reload button in async mode, wired to re-run the current query. @default false */\n showReloadButton?: boolean;\n /** Notified when a load rejects (the component renders `loadErrorMessage` and swallows it). */\n onLoadError?: ( error: unknown ) => void;\n}\n\n/**\n * Per-render option config for the SelectOption component. react-select keys custom components by\n * reference and remounts them whenever that reference changes; the `customComponents` object in\n * select.tsx is rebuilt every render. Feeding these live values through context (rather than a\n * closure inside a freshly-created Option) lets SelectOption keep a stable module-level identity,\n * so react-select re-renders it in place instead of remounting - which is what keeps the\n * `useIsTruncated` measurement (and the hover-expand affordance) from flickering.\n */\nexport interface ISelectOptionContext {\n /**\n * In-progress multi-select draft, as a value Set. Drives checkboxes / Select All while the\n * committed value drives the control. A Set rather than the array: every option row tests its own\n * membership, so an array would make one menu render O(options x draft).\n */\n draftValues?: ReadonlySet<IOption["value"]>;\n /**\n * Checked state of the Select All row: every option the query currently leaves VISIBLE is in the\n * draft. Resolved on the Select, which is the only place that knows the visible set \u2014 react-select\n * hands each option its unfiltered `options` array, so deriving it here would report unchecked\n * even with every visible row ticked.\n */\n areAllSelected?: boolean;\n /** Toggle a single option in the multi-select draft. */\n onToggleDraftOption?: ( option: IOption ) => void;\n /** Toggle Select All / Deselect All on the multi-select draft (shared with the keyboard path). */\n onSelectAll?: () => void;\n /** tv() class for the label wrapper. */\n optionLabelWrapClass: string;\n /** tv() class for the (truncating) label. */\n optionLabelClass: string;\n /** tv() class for the hover/focus full-text overlay. */\n optionOverlayClass: string;\n /**\n * Latest input modality, shared across every option. The full-text overlay follows the pointer\n * (local `isHovered`) while the user is using the mouse, and react-select\'s `isFocused` while\n * they\'re navigating by keyboard. Without this, react-select\'s `isFocused` - which lingers on the\n * last-focused option after the pointer leaves, and is also set by mouse hover - keeps an\n * overlay visible after the mouse has moved away (and shows two at once mid-transition).\n *\n * State on the Select, not a shared ref: this decides what an option renders, and writing a ref\n * schedules no re-render. Setting the mode it already holds is a no-op React bails out of, so\n * hovering along a list costs a render only at a genuine modality switch.\n */\n interactionMode: TSelectInteractionMode;\n /** Records the modality the user just used. See {@link ISelectOptionContext.interactionMode}. */\n onInteractionMode: ( mode: TSelectInteractionMode ) => void;\n}\n\n/**\n * Per-instance menu config via context (keeps SelectMenu\'s stable identity).\n */\nexport interface ISelectMenuContext {\n /** Current search text (controls react-select\'s inputValue). */\n filterQuery: string;\n /** Updates the query and (debounced) notifies `onFilterChange`. */\n onFilterInput: ( e: ChangeEvent<HTMLInputElement> ) => void;\n /** Marks Backspace/Delete held; defer debounce until keyup. */\n onFilterKeyDown: ( e: KeyboardEvent<HTMLInputElement> ) => void;\n /** On Backspace/Delete release, starts the deferred debounce. */\n onFilterKeyUp: ( e: KeyboardEvent<HTMLInputElement> ) => void;\n /** On blur during hold, flush deferred debounce. */\n onFilterBlur: ( e: FocusEvent<HTMLInputElement> ) => void;\n /** Renders the in-dropdown search input; the reload button is independent of it. */\n searchable: boolean;\n /** Placeholder for the search input. */\n searchPlaceholder: string;\n /** Optional custom footer rendered below the option list. */\n menuFooter?: ReactNode;\n /** Close the menu, discarding the multi-select draft. */\n closeMenu: () => void;\n /** Commit the multi-select draft, then close. */\n commitAndClose: () => void;\n /** tv() class for the search container. */\n searchContainerClass: string;\n /** tv() class for the search input. */\n searchInputClass: string;\n /** tv() class for the loader shown in place of the option list. */\n loaderClass: string;\n /** Replaces the option list with the loader. */\n isLoading?: boolean;\n /** Replaces the option list when set (async load failure). */\n loadError?: ReactNode;\n /** tv() class for the error container. */\n errorClass: string;\n /** Ref to the search input; focused when the menu opens. */\n searchInputRef: RefObject<HTMLInputElement>;\n /** Captures the menu\'s (possibly portaled) DOM node for the outside-click check. */\n menuNodeRef: MutableRefObject<HTMLDivElement | null>;\n /** Ref to the component wrapper, used to reach react-select\'s hidden control input. */\n containerRef: RefObject<HTMLDivElement>;\n /** Shown when provided; fired on reload-button click. */\n onReload?: () => void;\n /** Spins/disables the reload button. */\n isReloading?: boolean;\n /** Reload-button tooltip / aria-label. */\n reloadTooltip?: string;\n /** Records the input modality (see {@link ISelectOptionContext.interactionMode}); set to "keyboard" here. */\n onInteractionMode: ( mode: TSelectInteractionMode ) => void;\n}\n\nexport interface IOptionLabelOverlayProps {\n anchorRef: RefObject<HTMLElement>;\n className: string;\n children: ReactNode;\n}\n\nexport interface ITruncatedMultiValueProps {\n /** The plain-text label, used as the Tooltip title. */\n label: string;\n /** react-select\'s rendered chip (MultiValueContainer + label + remove). */\n chip: ReactElement;\n}\n\nexport interface ISelectComponentsConfig {\n prefixIcon?: TIconType | ReactNode;\n suffixIcon?: TIconType | ReactNode;\n maxVisibleValues: number;\n maxVisibleValuesMsg?: string;\n disabled: boolean;\n}\n'
|
|
3850
3398
|
},
|
|
3851
3399
|
{
|
|
3852
3400
|
"name": "selectVariants.ts",
|
|
@@ -3860,6 +3408,10 @@ export const selectVariants = tv({
|
|
|
3860
3408
|
menuSearchContainer: "flex items-center justify-between gap-4 px-4 py-3 border-b dark:border-b-0 border-secondary-100",
|
|
3861
3409
|
menuSearchInput: "w-full outline-none bg-transparent text-sm text-secondary-500 placeholder:text-secondary-200" +
|
|
3862
3410
|
" dark:text-secondary-200 dark:placeholder:text-secondary-400 rounded border border-secondary-100 dark:border-secondary-500 p-2",
|
|
3411
|
+
menuLoader: "flex justify-center py-3",
|
|
3412
|
+
// The async load-failure notice. It occupies the loader's slot, so no variant is needed \u2014 this is
|
|
3413
|
+
// the only state that uses it.
|
|
3414
|
+
menuError: "px-4 py-3 text-sm text-error-700 dark:text-error-400",
|
|
3863
3415
|
// The label stays in flow and simply truncates; the full text is shown on hover/focus by a
|
|
3864
3416
|
// separate position:fixed overlay (see OptionLabelOverlay in selectComponents) rather than by
|
|
3865
3417
|
// expanding this element. That keeps the option row height stable (no layout shift) and lets
|
|
@@ -3876,29 +3428,280 @@ export const selectVariants = tv({
|
|
|
3876
3428
|
error: {
|
|
3877
3429
|
true: { helperText: "text-error-700 dark:text-error-400" },
|
|
3878
3430
|
false: { helperText: "text-secondary-400 dark:text-secondary-200" }
|
|
3431
|
+
},
|
|
3432
|
+
// With the search input gone the strip holds only the reload button, which belongs at its end.
|
|
3433
|
+
searchable: {
|
|
3434
|
+
false: { menuSearchContainer: "justify-end" }
|
|
3879
3435
|
}
|
|
3880
3436
|
},
|
|
3881
3437
|
defaultVariants: {
|
|
3882
|
-
error: false
|
|
3438
|
+
error: false,
|
|
3439
|
+
searchable: true
|
|
3883
3440
|
}
|
|
3884
3441
|
});
|
|
3442
|
+
`
|
|
3443
|
+
},
|
|
3444
|
+
{
|
|
3445
|
+
"name": "selectMenu.tsx",
|
|
3446
|
+
"content": `import {
|
|
3447
|
+
createContext,
|
|
3448
|
+
useCallback,
|
|
3449
|
+
useContext,
|
|
3450
|
+
useEffect,
|
|
3451
|
+
type KeyboardEvent,
|
|
3452
|
+
type MouseEvent,
|
|
3453
|
+
type MutableRefObject,
|
|
3454
|
+
type ReactElement
|
|
3455
|
+
} from "react";
|
|
3456
|
+
import {
|
|
3457
|
+
components,
|
|
3458
|
+
type GroupBase,
|
|
3459
|
+
type MenuProps
|
|
3460
|
+
} from "react-select";
|
|
3461
|
+
|
|
3462
|
+
import { ReloadButton } from "../button/reloadButton";
|
|
3463
|
+
import { Loader } from "../loader";
|
|
3464
|
+
import { focusMenuInput, getControlInput, handleMenuKey } from "./selectKeyboard";
|
|
3465
|
+
import { type IOption, type ISelectMenuContext } from "./types";
|
|
3466
|
+
|
|
3467
|
+
export const SelectMenuContext = createContext<ISelectMenuContext | null>( null );
|
|
3468
|
+
|
|
3469
|
+
/**
|
|
3470
|
+
* Menu with in-dropdown search. Stable module identity (keeps focus/caret/scroll); search sits
|
|
3471
|
+
* outside MenuList to avoid react-select's focus war. Live values via {@link SelectMenuContext}.
|
|
3472
|
+
*/
|
|
3473
|
+
export function SelectMenu<
|
|
3474
|
+
IsMulti extends boolean = boolean,
|
|
3475
|
+
Group extends GroupBase<IOption> = GroupBase<IOption>
|
|
3476
|
+
>( props: MenuProps<IOption, IsMulti, Group> ): ReactElement {
|
|
3477
|
+
const { children, innerProps, innerRef } = props;
|
|
3478
|
+
const ctx = useContext( SelectMenuContext );
|
|
3479
|
+
const searchInputRef = ctx?.searchInputRef ?? null;
|
|
3480
|
+
const menuNodeRef = ctx?.menuNodeRef ?? null;
|
|
3481
|
+
const containerRef = ctx?.containerRef ?? null;
|
|
3482
|
+
|
|
3483
|
+
useEffect(() => {
|
|
3484
|
+
if ( searchInputRef && containerRef ) {
|
|
3485
|
+
focusMenuInput({ searchInputRef, containerRef });
|
|
3486
|
+
}
|
|
3487
|
+
}, [ searchInputRef, containerRef ]);
|
|
3488
|
+
|
|
3489
|
+
// Captures the menu DOM for the outside-click check while still handing the node to react-select.
|
|
3490
|
+
// MenuPlacer passes a ref OBJECT, not a callback; dropping it strands its layout effect on
|
|
3491
|
+
// \`if (!menuEl) return\`, killing auto placement and the maxHeight clamp. Memoised: this re-renders
|
|
3492
|
+
// on every keystroke, and React re-attaches a callback ref whose identity changed.
|
|
3493
|
+
const setMenuRef = useCallback(( node: HTMLDivElement | null ) => {
|
|
3494
|
+
if ( menuNodeRef ) {
|
|
3495
|
+
menuNodeRef.current = node;
|
|
3496
|
+
}
|
|
3497
|
+
if ( typeof innerRef === "function" ) {
|
|
3498
|
+
innerRef( node );
|
|
3499
|
+
} else if ( innerRef ) {
|
|
3500
|
+
( innerRef as MutableRefObject<HTMLDivElement | null> ).current = node;
|
|
3501
|
+
}
|
|
3502
|
+
}, [ menuNodeRef, innerRef ]);
|
|
3503
|
+
|
|
3504
|
+
// Fall back to the plain menu if used without the provider.
|
|
3505
|
+
if ( !ctx ) {
|
|
3506
|
+
return <components.Menu {...props}>{children}</components.Menu>;
|
|
3507
|
+
}
|
|
3508
|
+
|
|
3509
|
+
const {
|
|
3510
|
+
searchable,
|
|
3511
|
+
filterQuery,
|
|
3512
|
+
onFilterInput,
|
|
3513
|
+
onFilterKeyDown,
|
|
3514
|
+
onFilterKeyUp,
|
|
3515
|
+
onFilterBlur,
|
|
3516
|
+
searchPlaceholder,
|
|
3517
|
+
menuFooter,
|
|
3518
|
+
searchContainerClass,
|
|
3519
|
+
searchInputClass,
|
|
3520
|
+
loaderClass,
|
|
3521
|
+
isLoading,
|
|
3522
|
+
loadError,
|
|
3523
|
+
errorClass,
|
|
3524
|
+
onReload,
|
|
3525
|
+
isReloading,
|
|
3526
|
+
reloadTooltip
|
|
3527
|
+
} = ctx;
|
|
3528
|
+
|
|
3529
|
+
const handleSearchKeyDown = ( e: KeyboardEvent<HTMLInputElement> ) => {
|
|
3530
|
+
onFilterKeyDown( e );
|
|
3531
|
+
// Stop bubbling to SelectContainer so Backspace doesn't remove multi-select values.
|
|
3532
|
+
e.stopPropagation();
|
|
3533
|
+
if ( handleMenuKey( e, ctx ) !== "navigate" ) {
|
|
3534
|
+
return;
|
|
3535
|
+
}
|
|
3536
|
+
// Focus sits in the search box, so react-select's container handler never sees the key: relay it
|
|
3537
|
+
// to the control input it listens behind.
|
|
3538
|
+
const rsInput = getControlInput( ctx.containerRef );
|
|
3539
|
+
if ( rsInput ) {
|
|
3540
|
+
rsInput.dispatchEvent(
|
|
3541
|
+
new KeyboardEvent( "keydown", { key: e.key, code: e.code, bubbles: true, cancelable: true })
|
|
3542
|
+
);
|
|
3543
|
+
e.preventDefault();
|
|
3544
|
+
}
|
|
3545
|
+
};
|
|
3546
|
+
|
|
3547
|
+
// Override react-select's onMenuMouseDown so the focused input keeps focus.
|
|
3548
|
+
const handleMenuMouseDown = ( e: MouseEvent<HTMLDivElement> ) => {
|
|
3549
|
+
if ( e.button !== 0 ) {
|
|
3550
|
+
return;
|
|
3551
|
+
}
|
|
3552
|
+
const target = e.target as Node;
|
|
3553
|
+
if ( searchInputRef?.current && searchInputRef.current.contains( target )) {
|
|
3554
|
+
return;
|
|
3555
|
+
}
|
|
3556
|
+
e.preventDefault();
|
|
3557
|
+
focusMenuInput( ctx );
|
|
3558
|
+
};
|
|
3559
|
+
|
|
3560
|
+
return (
|
|
3561
|
+
<components.Menu
|
|
3562
|
+
{...props}
|
|
3563
|
+
innerRef={setMenuRef}
|
|
3564
|
+
innerProps={{ ...innerProps, onMouseDown: handleMenuMouseDown }}
|
|
3565
|
+
>
|
|
3566
|
+
{/* The strip carries the search input, the reload button, or both. \`onReload\` is the resolved
|
|
3567
|
+
control (an async load failure forces it on), so it is the same truth ReloadButton reads and
|
|
3568
|
+
the two can never disagree about whether the strip has anything to hold. */}
|
|
3569
|
+
{( searchable || typeof onReload === "function" ) && (
|
|
3570
|
+
<div className={searchContainerClass}>
|
|
3571
|
+
{searchable && (
|
|
3572
|
+
<input
|
|
3573
|
+
ref={searchInputRef}
|
|
3574
|
+
type="text"
|
|
3575
|
+
value={filterQuery}
|
|
3576
|
+
onChange={onFilterInput}
|
|
3577
|
+
onKeyDown={handleSearchKeyDown}
|
|
3578
|
+
onKeyUp={onFilterKeyUp}
|
|
3579
|
+
onBlur={onFilterBlur}
|
|
3580
|
+
placeholder={searchPlaceholder}
|
|
3581
|
+
className={searchInputClass}
|
|
3582
|
+
aria-label="Search options"
|
|
3583
|
+
/>
|
|
3584
|
+
)}
|
|
3585
|
+
<ReloadButton onReload={onReload} isReloading={isReloading} tooltip={reloadTooltip} />
|
|
3586
|
+
</div>
|
|
3587
|
+
)}
|
|
3588
|
+
{/* Loader, then error, then rows. All three are mutually exclusive by construction, so no two
|
|
3589
|
+
live regions ever coexist. The first two replace the list so stale rows can't be clicked;
|
|
3590
|
+
that also hides "No options". role="alert" on the error is deliberately assertive \u2014 the
|
|
3591
|
+
user's action did not do what they asked. */}
|
|
3592
|
+
{isLoading ? (
|
|
3593
|
+
<div className={loaderClass} role="status" aria-label="Loading">
|
|
3594
|
+
<Loader size="sm" />
|
|
3595
|
+
</div>
|
|
3596
|
+
) : loadError ? (
|
|
3597
|
+
<div className={errorClass} role="alert">{loadError}</div>
|
|
3598
|
+
) : children}
|
|
3599
|
+
{menuFooter}
|
|
3600
|
+
</components.Menu>
|
|
3601
|
+
);
|
|
3602
|
+
}
|
|
3603
|
+
|
|
3604
|
+
SelectMenu.displayName = "SelectMenu";
|
|
3605
|
+
`
|
|
3606
|
+
},
|
|
3607
|
+
{
|
|
3608
|
+
"name": "selectKeyboard.ts",
|
|
3609
|
+
"content": `import { type KeyboardEvent, type RefObject } from "react";
|
|
3610
|
+
|
|
3611
|
+
import { keyboardKeys } from "@constants";
|
|
3612
|
+
import { type ISelectMenuContext } from "./types";
|
|
3613
|
+
|
|
3614
|
+
// The keys react-select's own option navigation acts on wherever focus sits.
|
|
3615
|
+
const menuNavKeys = new Set([
|
|
3616
|
+
keyboardKeys.arrowDown,
|
|
3617
|
+
keyboardKeys.arrowUp,
|
|
3618
|
+
keyboardKeys.enter,
|
|
3619
|
+
keyboardKeys.pageDown,
|
|
3620
|
+
keyboardKeys.pageUp
|
|
3621
|
+
]);
|
|
3622
|
+
|
|
3623
|
+
// react-select navigates on these too, but only once no search box owns the typing: in a text field
|
|
3624
|
+
// Space is a character and Home/End are caret moves, and the field keeps them to itself.
|
|
3625
|
+
const controlNavKeys = new Set([
|
|
3626
|
+
keyboardKeys.space,
|
|
3627
|
+
keyboardKeys.home,
|
|
3628
|
+
keyboardKeys.end
|
|
3629
|
+
]);
|
|
3630
|
+
|
|
3631
|
+
/** What the shared handler leaves for its caller to do. */
|
|
3632
|
+
export type TSelectKeyOutcome = "handled" | "navigate" | "ignored";
|
|
3633
|
+
|
|
3634
|
+
/** The slice of the menu context the shared handler reads, so callers can pass the context whole. */
|
|
3635
|
+
export type TSelectKeyContext = Pick<
|
|
3636
|
+
ISelectMenuContext,
|
|
3637
|
+
"closeMenu" | "commitAndClose" | "containerRef" | "searchable" | "searchInputRef" | "isLoading" | "loadError" |
|
|
3638
|
+
"onInteractionMode"
|
|
3639
|
+
>;
|
|
3640
|
+
|
|
3641
|
+
/** The refs that locate the two inputs focus can live in. */
|
|
3642
|
+
export type TSelectFocusRefs = Pick<ISelectMenuContext, "searchInputRef" | "containerRef">;
|
|
3643
|
+
|
|
3644
|
+
/**
|
|
3645
|
+
* react-select's hidden control input \u2014 the focus holder whenever the search box is absent. Queried
|
|
3646
|
+
* fresh every time: react-select rebuilds this node whenever the custom Input's identity changes.
|
|
3647
|
+
*/
|
|
3648
|
+
export function getControlInput( containerRef: RefObject<HTMLDivElement> ): HTMLInputElement | null {
|
|
3649
|
+
return containerRef.current?.querySelector<HTMLInputElement>( ".select__control input" ) ?? null;
|
|
3650
|
+
}
|
|
3651
|
+
|
|
3652
|
+
/** Focus follows the search box while it exists, and the control input otherwise. */
|
|
3653
|
+
export function focusMenuInput({ searchInputRef, containerRef }: TSelectFocusRefs ): void {
|
|
3654
|
+
( searchInputRef.current ?? getControlInput( containerRef ))?.focus();
|
|
3655
|
+
}
|
|
3656
|
+
|
|
3657
|
+
/**
|
|
3658
|
+
* The open menu's keyboard model, shared by the search box and by the control. Escape discards the
|
|
3659
|
+
* draft and closes, Tab commits it and closes, and navigation keys are refused while the loader or
|
|
3660
|
+
* the error notice stands in for the list. "navigate" means react-select's own option navigation
|
|
3661
|
+
* still has to see the key.
|
|
3662
|
+
*/
|
|
3663
|
+
export function handleMenuKey( e: KeyboardEvent<Element>, ctx: TSelectKeyContext ): TSelectKeyOutcome {
|
|
3664
|
+
if ( e.key === keyboardKeys.escape ) {
|
|
3665
|
+
e.preventDefault();
|
|
3666
|
+
ctx.closeMenu();
|
|
3667
|
+
// The search box unmounts with the menu, so the control input is the only landing place.
|
|
3668
|
+
getControlInput( ctx.containerRef )?.focus();
|
|
3669
|
+
return "handled";
|
|
3670
|
+
}
|
|
3671
|
+
// Tab commits like an outside click; Escape above still cancels.
|
|
3672
|
+
if ( e.key === keyboardKeys.tab ) {
|
|
3673
|
+
ctx.commitAndClose();
|
|
3674
|
+
return "handled";
|
|
3675
|
+
}
|
|
3676
|
+
if ( !menuNavKeys.has( e.key ) && !( !ctx.searchable && controlNavKeys.has( e.key ))) {
|
|
3677
|
+
return "ignored";
|
|
3678
|
+
}
|
|
3679
|
+
// Block nav while loading OR while the error has taken the list's place \u2014 react-select still
|
|
3680
|
+
// tracks the previous focusedOption, so Enter would select a row that has left the screen.
|
|
3681
|
+
if ( ctx.isLoading || ctx.loadError ) {
|
|
3682
|
+
e.preventDefault();
|
|
3683
|
+
return "handled";
|
|
3684
|
+
}
|
|
3685
|
+
ctx.onInteractionMode( "keyboard" );
|
|
3686
|
+
return "navigate";
|
|
3687
|
+
}
|
|
3885
3688
|
`
|
|
3886
3689
|
},
|
|
3887
3690
|
{
|
|
3888
3691
|
"name": "selectComponents.tsx",
|
|
3889
|
-
"content": 'import * as React from "react";\nimport { type ReactElement } from "react";\nimport {\n components,\n type GroupBase,\n type OptionProps,\n type MultiValueProps,\n type MultiValueRemoveProps,\n type DropdownIndicatorProps,\n type ValueContainerProps,\n type InputProps,\n type MenuProps\n} from "react-select";\nimport { cx } from "tailwind-variants";\n\nimport { useIsTruncated } from "@hooks";\nimport { Checkbox } from "../checkbox";\nimport { Button } from "../button";\nimport { Tooltip } from "../tooltip";\nimport { ADPIcon, iconList, type TIconType } from "../adpIcon";\nimport { areAllSelectableSelected } from "./utils";\nimport {\n type IOption,\n type ISelectOptionContext,\n type ISelectMenuContext,\n type IOptionLabelOverlayProps,\n type ITruncatedMultiValueProps,\n type ISelectComponentsConfig\n} from "./types";\n\nexport const SelectOptionContext = React.createContext<ISelectOptionContext>({\n optionLabelWrapClass: "",\n optionLabelClass: "",\n optionOverlayClass: "",\n interactionModeRef: { current: "pointer" }\n});\n\n// Keys forwarded from the in-dropdown search input to react-select\'s hidden control input so\n// keyboard option navigation/selection still works while focus lives in the search box.\nconst forwardedKeys = new Set([ "ArrowDown", "ArrowUp", "Enter", "PageDown", "PageUp" ]);\n\nexport const SelectMenuContext = React.createContext<ISelectMenuContext | null>( null );\n\n/**\n * react-select\'s Menu with an in-dropdown search input (plus optional reload button and footer)\n * above the option list. Defined at module level with a stable identity so react-select never\n * remounts it - which is what keeps the search input\'s focus, caret, and the MenuList scroll\n * position alive across keystrokes. All live values arrive via {@link SelectMenuContext}.\n *\n * The search input sits inside the Menu but OUTSIDE the MenuList on purpose: react-select\'s\n * onInputBlur refocuses its own control input if the active element is inside the MenuList, so\n * keeping the search field outside stops that focus war; the caller\'s controlled menuIsOpen keeps\n * the menu open.\n */\nexport function SelectMenu<\n IsMulti extends boolean = boolean,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>( props: MenuProps<IOption, IsMulti, Group> ): ReactElement {\n const { children, innerProps, innerRef } = props;\n const ctx = React.useContext( SelectMenuContext );\n const searchInputRef = ctx?.searchInputRef ?? null;\n\n React.useEffect(() => {\n searchInputRef?.current?.focus();\n }, [searchInputRef]);\n\n // Only ever rendered under the provider; fall back to the plain menu if used without one.\n if ( !ctx ) {\n return <components.Menu {...props}>{children}</components.Menu>;\n }\n\n const {\n filterQuery,\n onFilterChange,\n searchPlaceholder,\n menuFooter,\n closeMenu,\n commitAndClose,\n searchContainerClass,\n searchInputClass,\n menuNodeRef,\n containerRef,\n onReload,\n isReloading,\n reloadTooltip,\n interactionModeRef\n } = ctx;\n\n // Capture the menu\'s DOM node (needed for the outside-click check when portaled) while\n // preserving react-select\'s own ref so menu placement still works.\n const setMenuRef = ( node: HTMLDivElement | null ) => {\n menuNodeRef.current = node;\n if ( typeof innerRef === "function" ) {\n innerRef( node );\n }\n };\n\n const handleSearchKeyDown = ( e: React.KeyboardEvent<HTMLInputElement> ) => {\n // react-select binds its onKeyDown to the SelectContainer, which wraps this menu. Stop\n // search-input keydowns from bubbling there, otherwise keys like Backspace act on the control\n // (e.g. removing the last selected value when the search is empty).\n e.stopPropagation();\n if ( e.key === "Escape" ) {\n e.preventDefault();\n closeMenu();\n // Closing unmounts this search input, so move focus back to react-select\'s control input\n // (openMenuOnFocus is off, so this won\'t reopen) - otherwise a keyboard user is stranded on\n // <body> with nothing focused.\n containerRef.current?.querySelector<HTMLInputElement>( ".select__control input" )?.focus();\n return;\n }\n // Tab is the keyboard analog of clicking away: commit the draft and let focus move on\n // naturally (no preventDefault). Escape above still cancels/discards.\n if ( e.key === "Tab" ) {\n commitAndClose();\n return;\n }\n if ( forwardedKeys.has( e.key )) {\n // A navigation/selection key means the user is driving by keyboard, so the full-text overlay\n // should follow react-select\'s focused option rather than a stale pointer hover.\n interactionModeRef.current = "keyboard";\n // Re-dispatch to react-select\'s input so it handles option navigation/selection.\n const rsInput = containerRef.current?.querySelector<HTMLInputElement>( ".select__control input" );\n if ( rsInput ) {\n rsInput.dispatchEvent(\n new KeyboardEvent( "keydown", { key: e.key, code: e.code, bubbles: true, cancelable: true })\n );\n e.preventDefault();\n }\n }\n };\n\n // Override react-select\'s onMenuMouseDown (innerProps.onMouseDown), which does preventDefault +\n // focusInput() - pulling focus to the trigger and blocking the search field from receiving\n // focus/caret. Instead, let the search field focus normally and keep focus on it for any other\n // in-menu click.\n const handleMenuMouseDown = ( e: React.MouseEvent<HTMLDivElement> ) => {\n if ( e.button !== 0 ) {\n return;\n }\n const target = e.target as Node;\n if ( searchInputRef?.current && searchInputRef.current.contains( target )) {\n return;\n }\n e.preventDefault();\n searchInputRef?.current?.focus();\n };\n\n return (\n <components.Menu\n {...props}\n innerRef={setMenuRef}\n innerProps={{ ...innerProps, onMouseDown: handleMenuMouseDown }}\n >\n <div className={searchContainerClass}>\n <input\n ref={searchInputRef}\n type="text"\n value={filterQuery}\n onChange={( e ) => onFilterChange( e.target.value )}\n onKeyDown={handleSearchKeyDown}\n placeholder={searchPlaceholder}\n className={searchInputClass}\n aria-label="Search options"\n />\n {typeof onReload === "function" && (\n <Button\n variant="shade"\n color="secondary"\n className="p-1"\n size="sm"\n onClick={onReload}\n disabled={isReloading}\n tooltip={reloadTooltip}\n aria-label={reloadTooltip}\n >\n <ADPIcon icon={iconList.reload} size="xs" spin={isReloading} />\n </Button>\n )}\n </div>\n {children}\n {menuFooter}\n </components.Menu>\n );\n}\n\nSelectMenu.displayName = "SelectMenu";\n\n/**\n * The full-text overlay shown for a truncated option on hover/focus. Rendered `position:fixed`\n * and positioned from the label wrapper\'s viewport rect, so it escapes the scrollable menu\'s\n * overflow clipping (no ancestor establishes a containing block via transform/filter/etc.) - a\n * plain absolute overlay stays trapped inside the menu and gets clipped at whichever edge it\n * grows toward. It stays in the option\'s DOM subtree (not portaled) so it still inherits the\n * theme (`.dark`) and RTL context. The height is measured at the final width, then the top is\n * clamped so the box never spills past the viewport bottom (it shifts up for the last options).\n * pointer-events:none keeps the hover on the row beneath it, so it can\'t cause a hover flicker.\n */\nfunction OptionLabelOverlay({ anchorRef, className, children }: IOptionLabelOverlayProps ): ReactElement {\n const overlayRef = React.useRef<HTMLDivElement>( null );\n const [ style, setStyle ] = React.useState<React.CSSProperties | null>( null );\n\n React.useLayoutEffect(() => {\n const anchor = anchorRef.current;\n const overlay = overlayRef.current;\n if ( !anchor || !overlay ) {\n return undefined;\n }\n const position = () => {\n const rect = anchor.getBoundingClientRect();\n // Size the overlay to the label width first, so its wrapped height is measured correctly.\n overlay.style.position = "fixed";\n overlay.style.left = `${rect.left}px`;\n overlay.style.width = `${rect.width}px`;\n overlay.style.top = `${rect.top}px`;\n overlay.style.visibility = "hidden";\n const margin = 8;\n const maxTop = window.innerHeight - margin - overlay.offsetHeight;\n const top = rect.top > maxTop ? Math.max( margin, maxTop ) : rect.top;\n setStyle({ position: "fixed", left: rect.left, top, width: rect.width, zIndex: 9999 });\n };\n position();\n // A position:fixed box doesn\'t follow its anchor, so re-pin it whenever the anchor moves:\n // scrolling the menu (capture=true catches the scrollable ancestor, whose scroll doesn\'t\n // bubble) or a viewport resize. Without this the overlay floats away from its option row.\n window.addEventListener( "scroll", position, true );\n window.addEventListener( "resize", position );\n return () => {\n window.removeEventListener( "scroll", position, true );\n window.removeEventListener( "resize", position );\n };\n }, [ anchorRef, children ]);\n\n return (\n <div\n ref={overlayRef}\n className={className}\n style={style ?? { position: "fixed", top: 0, left: 0, visibility: "hidden" }}\n >\n {children}\n </div>\n );\n}\n\n/**\n * A single dropdown option (handles Select All, multi-select checkboxes, and the selected\n * checkmark). Defined at module level with a stable identity so react-select never remounts it;\n * live selection state arrives via {@link SelectOptionContext}. The label truncates to one line\n * and, only when genuinely clipped (`useIsTruncated`), shows its full text on hover/focus in a\n * `position:fixed` overlay - see {@link OptionLabelOverlay}.\n */\nexport function SelectOption<\n IsMulti extends boolean = boolean,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>( props: OptionProps<IOption, IsMulti, Group> ): ReactElement {\n const {\n draftValues,\n onToggleDraftOption,\n onSelectAll,\n optionLabelWrapClass,\n optionLabelClass,\n optionOverlayClass,\n interactionModeRef\n } = React.useContext( SelectOptionContext );\n const { ref: labelRef, containerRef: labelWrapRef, isTruncated: isLabelTruncated } = useIsTruncated<HTMLSpanElement>();\n const [ isHovered, setIsHovered ] = React.useState( false );\n\n const optionStyles = props.getStyles( "option", props );\n const isSelectAllRow = props.data.value === "select-all";\n // Multi-select selection is driven by the in-progress draft (not react-select\'s value, which is\n // the committed selection feeding the control). Single-select keeps react-select\'s own state.\n const draft = draftValues ?? [];\n // "All selected" is a membership check over the SELECTABLE (enabled) options - matching\n // handleSelectAllDraft (via the shared areAllSelectableSelected), which never adds disabled\n // options. Only the Select All row consumes this, so short-circuit skips the full-list scan on\n // every other option render (otherwise O(N^2) across the list).\n const areAllSelected = isSelectAllRow && areAllSelectableSelected( props.options, draft );\n const optionSelected = props.isMulti\n ? ( isSelectAllRow ? areAllSelected : draft.some(( o ) => o.value === props.data.value ))\n : props.isSelected;\n\n const baseClassName = props.cx(\n {\n option: true,\n "option--is-disabled": props.isDisabled,\n "option--is-focused": props.isFocused,\n "option--is-selected": optionSelected\n },\n props.className\n );\n\n // Toggle the draft for multi-select (mouse path). stopPropagation keeps react-select from also\n // firing its own onChange against the committed value.\n const handleToggle = ( e: React.SyntheticEvent ) => {\n e.stopPropagation();\n if ( props.isDisabled || props.data.isFixed ) {\n return;\n }\n if ( isSelectAllRow ) {\n onSelectAll?.();\n } else {\n onToggleDraftOption?.( props.data );\n }\n };\n\n // react-select\'s own `state.isSelected` reflects the *committed* value, not the in-progress\n // multi-select draft - so it never lights up a checked-but-uncommitted row, and the inline\n // `style` from `optionStyles` can\'t respond to that anyway (nested selectors like `.dark &`\n // are dropped when applied as a plain `style` attribute). Drive the background entirely from\n // our own `optionSelected` (checked-aware for multi, same as isSelected for single) via\n // classes instead, so it\'s consistent for both select modes and both themes.\n const bgClass = optionSelected\n ? "!bg-frostBlue dark:!bg-secondary-700"\n : props.isFocused\n ? "!bg-frostBlue dark:!bg-secondary-800"\n : "!bg-transparent dark:!bg-iridium";\n\n // Show the full-text overlay only for genuinely-clipped labels. Which signal drives it depends on\n // the current input modality: the pointer path uses local `isHovered` (which clears on\n // mouseleave, so only the row actually under the cursor shows, never a stale one); the keyboard\n // path uses react-select\'s `isFocused`. Honoring `isFocused` unconditionally would leave the\n // overlay stuck on the last-focused row after the mouse moved off it (react-select keeps that\n // focus, and sets it on hover too), which is the "both overlays stay visible" bug.\n const showOverlay = isLabelTruncated &&\n ( interactionModeRef.current === "keyboard" ? props.isFocused : isHovered );\n\n return (\n <div\n style={optionStyles as React.CSSProperties}\n onMouseEnter={() => {\n interactionModeRef.current = "pointer";\n setIsHovered( true );\n }}\n onMouseLeave={() => setIsHovered( false )}\n className={cx(\n baseClassName,\n "select__custom-option",\n bgClass,\n props.isMulti && "select__custom-option--is-multi"\n )}\n >\n {props.isMulti && (\n <Checkbox\n className="me-2"\n onChange={handleToggle}\n checked={optionSelected}\n disabled={props.isDisabled || props.data.isFixed}\n />\n )}\n <components.Option\n {...props}\n className={cx( "!p-0 !bg-transparent", props.isMulti && "flex-1 min-w-0" )}\n innerProps={{\n ...props.innerProps,\n ...( props.isMulti ? { onClick: handleToggle } : {})\n }}\n >\n <span ref={labelWrapRef} className={optionLabelWrapClass}>\n <span ref={labelRef} className={optionLabelClass}>{props.children}</span>\n </span>\n {showOverlay && (\n <OptionLabelOverlay anchorRef={labelWrapRef} className={optionOverlayClass}>\n {props.children}\n </OptionLabelOverlay>\n )}\n </components.Option>\n </div>\n );\n}\n\nSelectOption.displayName = "SelectOption";\n\n/**\n * Wraps a multi-select chip so its full label is surfaced in a Tooltip, but only when the chip\'s\n * label is actually clipped by react-select\'s `maxWidth` (measured against the rendered\n * `.select__multi-value__label`, whose class comes from `classNamePrefix="select"`). The Tooltip\n * always wraps the chip and is gated via its `canOpen` prop rather than being swapped in and out,\n * so the measured label node stays mounted and the ResizeObserver never loses its target. The\n * `contents` wrapper carries no box of its own, so the chip lays out exactly as it would\n * unwrapped; it exists only to scope the label lookup to this chip.\n */\nfunction TruncatedMultiValue({ label, chip }: ITruncatedMultiValueProps ): ReactElement {\n const wrapRef = React.useRef<HTMLSpanElement>( null );\n const [ isTruncated, setIsTruncated ] = React.useState( false );\n\n React.useLayoutEffect(() => {\n const labelEl = wrapRef.current?.querySelector<HTMLElement>( ".select__multi-value__label" ) ?? null;\n if ( !labelEl ) {\n return undefined;\n }\n const measure = () => setIsTruncated( labelEl.scrollWidth > labelEl.clientWidth );\n measure();\n const observer = new ResizeObserver( measure );\n observer.observe( labelEl );\n return () => observer.disconnect();\n }, [label]);\n\n return (\n <Tooltip\n placement="top"\n canOpen={isTruncated}\n title={label}\n trigger={<span ref={wrapRef} className="contents">{chip}</span>}\n />\n );\n}\n\nTruncatedMultiValue.displayName = "TruncatedMultiValue";\n\n/**\n * Builds the react-select custom components that are independent of the in-dropdown\n * search/focus machinery (kept in select.tsx) and of per-option selection state (the Option is\n * the stable {@link SelectOption} above). These are stateless, so recreating them per render is\n * harmless - react-select only remounts the focus-sensitive Menu component.\n */\nexport function createSelectComponents<\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>( config: ISelectComponentsConfig ) {\n const {\n prefixIcon,\n suffixIcon,\n maxVisibleValues,\n maxVisibleValuesMsg,\n disabled\n } = config;\n\n // Dropdown indicator icon\n const DropdownIndicator = ( props: DropdownIndicatorProps<IOption, IsMulti, Group> ) => {\n const {\n selectProps: { menuIsOpen }\n } = props;\n return (\n <ADPIcon size="xs" icon={menuIsOpen ? iconList.upArrow : iconList.downArrow} />\n );\n };\n\n // Custom value container to handle prefix/suffix icons and truncation\n const ValueContainer = (\n { children, ...props }: ValueContainerProps<IOption, IsMulti, Group>\n ) => {\n const values = props.getValue();\n // Split the chips (which carry `props.data`) from the search input in a single pass.\n const withData: React.ReactNode[] = [];\n const inputChild: React.ReactNode[] = [];\n React.Children.toArray( children ).forEach(( c ) => {\n const target = ( c as ReactElement ).props.data ? withData : inputChild;\n target.push( c );\n });\n return (\n <>\n {prefixIcon &&\n ( typeof prefixIcon === "string" ? (\n <ADPIcon icon={prefixIcon as TIconType} size="xs" />\n ) : (\n prefixIcon\n ))}\n <components.ValueContainer {...props}>\n {withData}\n {values.length > maxVisibleValues && (\n <div\n className={cx(\n "text-secondary-400 dark:text-secondary-300",\n "select__truncated-multi-value",\n disabled && "select__truncated-multi-value--is-disabled"\n )}\n >\n +{values.length - maxVisibleValues}{" "}\n {maxVisibleValuesMsg ?? "More"}\n </div>\n )}\n {inputChild}\n </components.ValueContainer>\n {suffixIcon &&\n ( typeof suffixIcon === "string" ? (\n <ADPIcon icon={suffixIcon as TIconType} size="xs" />\n ) : (\n suffixIcon\n ))}\n </>\n );\n };\n\n // Hide extra MultiValue components\n const MultiValue = ( props: MultiValueProps<IOption> ) => {\n if ( props.index !== undefined && props.index >= maxVisibleValues ) {\n return null;\n }\n const chip = <components.MultiValue {...props} />;\n // Surface the full label in a Tooltip, but only when the chip\'s label is actually truncated\n // (see TruncatedMultiValue). Non-string labels have no text to show, so render the chip as-is.\n if ( typeof props.data.label !== "string" ) {\n return chip;\n }\n return <TruncatedMultiValue label={props.data.label} chip={chip} />;\n };\n\n // react-select\'s default remove control is a mouse-only `<div role="button">` with no tabIndex,\n // so a pill\'s "x" can never be reached or activated by keyboard. Make it a real tab stop\n // (per chip, regardless of truncation) that removes on Enter/Space. stopPropagation keeps the\n // key from bubbling to the control, which would otherwise treat Enter/Space as open/select.\n const MultiValueRemove = ( props: MultiValueRemoveProps<IOption, IsMulti, Group> ) => {\n const { onClick } = props.innerProps;\n return (\n <components.MultiValueRemove\n {...props}\n innerProps={{\n ...props.innerProps,\n tabIndex: disabled ? -1 : 0,\n onKeyDown: ( e: React.KeyboardEvent ) => {\n if ( e.key === "Enter" || e.key === " " ) {\n e.preventDefault();\n e.stopPropagation();\n onClick?.( e as unknown as React.MouseEvent<HTMLDivElement> );\n }\n }\n }}\n />\n );\n };\n\n /*\n * The control input must remain present and focusable so react-select\'s click-to-open\n * flow works (onControlMouseDown \u2192 focusInput \u2192 onInputFocus \u2192 openMenu). We make it\n * read-only and visually hidden so all actual typing happens in the dropdown search input.\n */\n const Input = ( props: InputProps<IOption, IsMulti, Group> ) => {\n const handleKeyDown = ( e: React.KeyboardEvent<HTMLInputElement> ) => {\n if ( e.key === "Backspace" ) {\n const vals = props.getValue();\n if ( vals.length > maxVisibleValues ) {\n e.stopPropagation();\n e.preventDefault();\n }\n }\n };\n return (\n <components.Input\n {...props}\n readOnly\n onKeyDown={handleKeyDown}\n style={{ ...( props.style as React.CSSProperties ), opacity: 0, width: 0, position: "absolute" }}\n />\n );\n };\n\n return { DropdownIndicator, ValueContainer, MultiValue, MultiValueRemove, Input };\n}\n'
|
|
3692
|
+
"content": 'import * as React from "react";\nimport { type ReactElement } from "react";\nimport {\n components,\n type GroupBase,\n type OptionProps,\n type MultiValueProps,\n type MultiValueRemoveProps,\n type DropdownIndicatorProps,\n type ValueContainerProps,\n type InputProps\n} from "react-select";\nimport { cx } from "tailwind-variants";\n\nimport { keyboardKeys } from "@constants";\nimport { useIsTruncated } from "@hooks";\nimport { Checkbox } from "../checkbox";\nimport { Tooltip } from "../tooltip";\nimport { ADPIcon, iconList, type TIconType } from "../adpIcon";\nimport { isCreateOption, SELECT_ALL_VALUE } from "./utils";\nimport {\n type IOption,\n type ISelectOptionContext,\n type IOptionLabelOverlayProps,\n type ITruncatedMultiValueProps,\n type ISelectComponentsConfig\n} from "./types";\n\n// One shared identity for "no draft", so a single-select option never allocates one per render.\nconst EMPTY_DRAFT: ReadonlySet<IOption["value"]> = new Set();\n\nexport const SelectOptionContext = React.createContext<ISelectOptionContext>({\n optionLabelWrapClass: "",\n optionLabelClass: "",\n optionOverlayClass: "",\n interactionMode: "pointer",\n onInteractionMode: () => {}\n});\n\n/**\n * The full-text overlay shown for a truncated option on hover/focus. Rendered `position:fixed`\n * and positioned from the label wrapper\'s viewport rect, so it escapes the scrollable menu\'s\n * overflow clipping (no ancestor establishes a containing block via transform/filter/etc.) - a\n * plain absolute overlay stays trapped inside the menu and gets clipped at whichever edge it\n * grows toward. It stays in the option\'s DOM subtree (not portaled) so it still inherits the\n * theme (`.dark`) and RTL context. The height is measured at the final width, then the top is\n * clamped so the box never spills past the viewport bottom (it shifts up for the last options).\n * pointer-events:none keeps the hover on the row beneath it, so it can\'t cause a hover flicker.\n */\nfunction OptionLabelOverlay({ anchorRef, className, children }: IOptionLabelOverlayProps ): ReactElement {\n const overlayRef = React.useRef<HTMLDivElement>( null );\n const [ style, setStyle ] = React.useState<React.CSSProperties | null>( null );\n\n React.useLayoutEffect(() => {\n const anchor = anchorRef.current;\n const overlay = overlayRef.current;\n if ( !anchor || !overlay ) {\n return undefined;\n }\n const position = () => {\n const rect = anchor.getBoundingClientRect();\n // Size the overlay to the label width first, so its wrapped height is measured correctly.\n overlay.style.position = "fixed";\n overlay.style.left = `${rect.left}px`;\n overlay.style.width = `${rect.width}px`;\n overlay.style.top = `${rect.top}px`;\n overlay.style.visibility = "hidden";\n const margin = 8;\n const maxTop = window.innerHeight - margin - overlay.offsetHeight;\n const top = rect.top > maxTop ? Math.max( margin, maxTop ) : rect.top;\n setStyle({ position: "fixed", left: rect.left, top, width: rect.width, zIndex: 9999 });\n };\n position();\n // A position:fixed box doesn\'t follow its anchor, so re-pin it whenever the anchor moves:\n // scrolling the menu (capture=true catches the scrollable ancestor, whose scroll doesn\'t\n // bubble) or a viewport resize. Without this the overlay floats away from its option row.\n window.addEventListener( "scroll", position, true );\n window.addEventListener( "resize", position );\n return () => {\n window.removeEventListener( "scroll", position, true );\n window.removeEventListener( "resize", position );\n };\n }, [ anchorRef, children ]);\n\n return (\n <div\n ref={overlayRef}\n className={className}\n style={style ?? { position: "fixed", top: 0, left: 0, visibility: "hidden" }}\n >\n {children}\n </div>\n );\n}\n\n/**\n * A single dropdown option (handles Select All, multi-select checkboxes, and the selected\n * checkmark). Defined at module level with a stable identity so react-select never remounts it;\n * live selection state arrives via {@link SelectOptionContext}. The label truncates to one line\n * and, only when genuinely clipped (`useIsTruncated`), shows its full text on hover/focus in a\n * `position:fixed` overlay - see {@link OptionLabelOverlay}.\n */\nexport function SelectOption<\n IsMulti extends boolean = boolean,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>( props: OptionProps<IOption, IsMulti, Group> ): ReactElement {\n const {\n draftValues,\n areAllSelected,\n onToggleDraftOption,\n onSelectAll,\n optionLabelWrapClass,\n optionLabelClass,\n optionOverlayClass,\n interactionMode,\n onInteractionMode\n } = React.useContext( SelectOptionContext );\n const { ref: labelRef, containerRef: labelWrapRef, isTruncated: isLabelTruncated } = useIsTruncated<HTMLSpanElement>();\n const [ isHovered, setIsHovered ] = React.useState( false );\n\n const optionStyles = props.getStyles( "option", props );\n const isSelectAllRow = props.data.value === SELECT_ALL_VALUE;\n // The Create row makes an option that does not exist yet, so there is nothing for a checkbox to\n // report on and nothing in the draft to toggle. It is left to react-select, whose Creatable turns\n // the click into the create action, exactly as in single-select.\n const isDraftRow = Boolean( props.isMulti ) && !isCreateOption( props.data );\n // Multi-select selection is driven by the in-progress draft (not react-select\'s value, which is\n // the committed selection feeding the control). Single-select keeps react-select\'s own state.\n const draft = draftValues ?? EMPTY_DRAFT;\n const optionSelected = isDraftRow\n ? ( isSelectAllRow ? Boolean( areAllSelected ) : draft.has( props.data.value ))\n : props.isSelected;\n\n const baseClassName = props.cx(\n {\n option: true,\n "option--is-disabled": props.isDisabled,\n "option--is-focused": props.isFocused,\n "option--is-selected": optionSelected\n },\n props.className\n );\n\n // Toggle the draft for multi-select (mouse path). stopPropagation keeps react-select from also\n // firing its own onChange against the committed value.\n const handleToggle = ( e: React.SyntheticEvent ) => {\n e.stopPropagation();\n if ( props.isDisabled || props.data.isFixed ) {\n return;\n }\n if ( isSelectAllRow ) {\n onSelectAll?.();\n } else {\n onToggleDraftOption?.( props.data );\n }\n };\n\n // react-select\'s own `state.isSelected` reflects the *committed* value, not the in-progress\n // multi-select draft - so it never lights up a checked-but-uncommitted row, and the inline\n // `style` from `optionStyles` can\'t respond to that anyway (nested selectors like `.dark &`\n // are dropped when applied as a plain `style` attribute). Drive the background entirely from\n // our own `optionSelected` (checked-aware for multi, same as isSelected for single) via\n // classes instead, so it\'s consistent for both select modes and both themes.\n const bgClass = optionSelected\n ? "!bg-frostBlue dark:!bg-secondary-700"\n : props.isFocused\n ? "!bg-frostBlue dark:!bg-secondary-800"\n : "!bg-transparent dark:!bg-iridium";\n\n // Show the full-text overlay only for genuinely-clipped labels. Which signal drives it depends on\n // the current input modality: the pointer path uses local `isHovered` (which clears on\n // mouseleave, so only the row actually under the cursor shows, never a stale one); the keyboard\n // path uses react-select\'s `isFocused`. Honoring `isFocused` unconditionally would leave the\n // overlay stuck on the last-focused row after the mouse moved off it (react-select keeps that\n // focus, and sets it on hover too), which is the "both overlays stay visible" bug.\n const showOverlay = isLabelTruncated &&\n ( interactionMode === "keyboard" ? props.isFocused : isHovered );\n\n return (\n <div\n style={optionStyles as React.CSSProperties}\n onMouseEnter={() => {\n onInteractionMode( "pointer" );\n setIsHovered( true );\n }}\n onMouseLeave={() => setIsHovered( false )}\n className={cx(\n baseClassName,\n "select__custom-option",\n bgClass,\n props.isMulti && "select__custom-option--is-multi"\n )}\n >\n {isDraftRow && (\n <Checkbox\n className="me-2"\n onChange={handleToggle}\n checked={optionSelected}\n disabled={props.isDisabled || props.data.isFixed}\n />\n )}\n <components.Option\n {...props}\n className={cx( "!p-0 !bg-transparent", props.isMulti && "flex-1 min-w-0" )}\n innerProps={{\n ...props.innerProps,\n ...( isDraftRow ? { onClick: handleToggle } : {})\n }}\n >\n <span ref={labelWrapRef} className={optionLabelWrapClass}>\n <span ref={labelRef} className={optionLabelClass}>{props.children}</span>\n </span>\n {showOverlay && (\n <OptionLabelOverlay anchorRef={labelWrapRef} className={optionOverlayClass}>\n {props.children}\n </OptionLabelOverlay>\n )}\n </components.Option>\n </div>\n );\n}\n\nSelectOption.displayName = "SelectOption";\n\n/**\n * Wraps a multi-select chip so its full label is surfaced in a Tooltip, but only when the chip\'s\n * label is actually clipped by react-select\'s `maxWidth` (measured against the rendered\n * `.select__multi-value__label`, whose class comes from `classNamePrefix="select"`). The Tooltip\n * always wraps the chip and is gated via its `canOpen` prop rather than being swapped in and out,\n * so the measured label node stays mounted and the ResizeObserver never loses its target. The\n * `contents` wrapper carries no box of its own, so the chip lays out exactly as it would\n * unwrapped; it exists only to scope the label lookup to this chip.\n */\nfunction TruncatedMultiValue({ label, chip }: ITruncatedMultiValueProps ): ReactElement {\n const wrapRef = React.useRef<HTMLSpanElement>( null );\n const [ isTruncated, setIsTruncated ] = React.useState( false );\n\n React.useLayoutEffect(() => {\n const labelEl = wrapRef.current?.querySelector<HTMLElement>( ".select__multi-value__label" ) ?? null;\n if ( !labelEl ) {\n return undefined;\n }\n const measure = () => setIsTruncated( labelEl.scrollWidth > labelEl.clientWidth );\n measure();\n const observer = new ResizeObserver( measure );\n observer.observe( labelEl );\n return () => observer.disconnect();\n }, [label]);\n\n return (\n <Tooltip\n placement="top"\n canOpen={isTruncated}\n title={label}\n trigger={<span ref={wrapRef} className="contents">{chip}</span>}\n />\n );\n}\n\nTruncatedMultiValue.displayName = "TruncatedMultiValue";\n\n/**\n * Builds the react-select custom components that are independent of the in-dropdown\n * search/focus machinery (kept in select.tsx) and of per-option selection state (the Option is\n * the stable {@link SelectOption} above). These are stateless, so recreating them per render is\n * harmless - react-select only remounts the focus-sensitive Menu component.\n */\nexport function createSelectComponents<\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>( config: ISelectComponentsConfig ) {\n const {\n prefixIcon,\n suffixIcon,\n maxVisibleValues,\n maxVisibleValuesMsg,\n disabled\n } = config;\n\n // Dropdown indicator icon\n const DropdownIndicator = ( props: DropdownIndicatorProps<IOption, IsMulti, Group> ) => {\n const {\n selectProps: { menuIsOpen }\n } = props;\n return (\n <ADPIcon size="xs" icon={menuIsOpen ? iconList.upArrow : iconList.downArrow} />\n );\n };\n\n // Custom value container to handle prefix/suffix icons and truncation\n const ValueContainer = (\n { children, ...props }: ValueContainerProps<IOption, IsMulti, Group>\n ) => {\n const values = props.getValue();\n // Split the chips (which carry `props.data`) from the search input in a single pass.\n const withData: React.ReactNode[] = [];\n const inputChild: React.ReactNode[] = [];\n React.Children.toArray( children ).forEach(( c ) => {\n const target = ( c as ReactElement ).props.data ? withData : inputChild;\n target.push( c );\n });\n return (\n <>\n {prefixIcon &&\n ( typeof prefixIcon === "string" ? (\n <ADPIcon icon={prefixIcon as TIconType} size="xs" />\n ) : (\n prefixIcon\n ))}\n <components.ValueContainer {...props}>\n {withData}\n {values.length > maxVisibleValues && (\n <div\n className={cx(\n "text-secondary-400 dark:text-secondary-300",\n "select__truncated-multi-value",\n disabled && "select__truncated-multi-value--is-disabled"\n )}\n >\n +{values.length - maxVisibleValues}{" "}\n {maxVisibleValuesMsg ?? "More"}\n </div>\n )}\n {inputChild}\n </components.ValueContainer>\n {suffixIcon &&\n ( typeof suffixIcon === "string" ? (\n <ADPIcon icon={suffixIcon as TIconType} size="xs" />\n ) : (\n suffixIcon\n ))}\n </>\n );\n };\n\n // Hide extra MultiValue components\n const MultiValue = ( props: MultiValueProps<IOption> ) => {\n if ( props.index !== undefined && props.index >= maxVisibleValues ) {\n return null;\n }\n const chip = <components.MultiValue {...props} />;\n // Surface the full label in a Tooltip, but only when the chip\'s label is actually truncated\n // (see TruncatedMultiValue). Non-string labels have no text to show, so render the chip as-is.\n if ( typeof props.data.label !== "string" ) {\n return chip;\n }\n return <TruncatedMultiValue label={props.data.label} chip={chip} />;\n };\n\n // react-select\'s default remove control is a mouse-only `<div role="button">` with no tabIndex,\n // so a pill\'s "x" can never be reached or activated by keyboard. Make it a real tab stop\n // (per chip, regardless of truncation) that removes on Enter/Space. stopPropagation keeps the\n // key from bubbling to the control, which would otherwise treat Enter/Space as open/select.\n const MultiValueRemove = ( props: MultiValueRemoveProps<IOption, IsMulti, Group> ) => {\n const { onClick } = props.innerProps;\n return (\n <components.MultiValueRemove\n {...props}\n innerProps={{\n ...props.innerProps,\n tabIndex: disabled ? -1 : 0,\n onKeyDown: ( e: React.KeyboardEvent ) => {\n if ( e.key === keyboardKeys.enter || e.key === keyboardKeys.space ) {\n e.preventDefault();\n e.stopPropagation();\n onClick?.( e as unknown as React.MouseEvent<HTMLDivElement> );\n }\n }\n }}\n />\n );\n };\n\n return { DropdownIndicator, ValueContainer, MultiValue, MultiValueRemove };\n}\n\n/**\n * The control input, which must remain present and focusable so react-select\'s click-to-open flow\n * works (onControlMouseDown \u2192 focusInput \u2192 onInputFocus \u2192 openMenu). It is read-only and visually\n * hidden, so all actual typing happens in the dropdown search input \u2014 and with no search input on\n * screen it is where focus lives for as long as the menu is open.\n *\n * Built apart from the components above, on `maxVisibleValues` alone: react-select unmounts and\n * remounts a custom component whose identity changed, and remounting this one destroys that focus.\n * Sharing the icon props\' identity would put the focus at the mercy of a consumer passing a fresh\n * `prefixIcon` element on every render.\n */\nexport function createSelectInput<\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>( maxVisibleValues: number ) {\n return function Input( props: InputProps<IOption, IsMulti, Group> ): ReactElement {\n const handleKeyDown = ( e: React.KeyboardEvent<HTMLInputElement> ) => {\n if ( e.key === keyboardKeys.backspace ) {\n const vals = props.getValue();\n if ( vals.length > maxVisibleValues ) {\n e.stopPropagation();\n e.preventDefault();\n }\n }\n };\n return (\n <components.Input\n {...props}\n readOnly\n onKeyDown={handleKeyDown}\n style={{ ...( props.style as React.CSSProperties ), opacity: 0, width: 0, position: "absolute" }}\n />\n );\n };\n}\n\n/** react-select renders a separator between the indicators; this component has none. */\nexport const NoIndicatorSeparator = (): null => null;\n'
|
|
3890
3693
|
},
|
|
3891
3694
|
{
|
|
3892
3695
|
"name": "select.tsx",
|
|
3893
|
-
"content": 'import * as React from "react";\nimport { type ReactElement, useId, useRef, useState, type ComponentType } from "react";\nimport ReactSelect, {\n type Props as ReactSelectProps,\n type GroupBase\n} from "react-select";\nimport CreatableSelect from "react-select/creatable";\nimport { cx } from "tailwind-variants";\n\nimport { matchesQuery } from "@utils";\nimport { reactSelectCustomStyles, getSelectableOptions, areAllSelectableSelected } from "./utils";\nimport { selectVariants } from "./selectVariants";\nimport {\n createSelectComponents,\n SelectOption,\n SelectOptionContext,\n SelectMenu,\n SelectMenuContext\n} from "./selectComponents";\n\nimport { ESelectSizes, type IOption, type ISelectProps, type ISelectMenuContext } from "./types";\n\n/**\n * Select component for single or multi selection\n */\nexport function Select<\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>(\n selectProps: ISelectProps<IsMulti, Group>\n): ReactElement {\n const {\n id,\n className,\n label,\n size = ESelectSizes.MD,\n options = [],\n value,\n helperText,\n error = false,\n disabled = false,\n creatable = false,\n maxVisibleValues = 3,\n maxVisibleValuesMsg,\n menuFooter,\n prefixIcon,\n suffixIcon,\n searchPlaceholder = "Search...",\n reloadTooltip = "Reload",\n onReload,\n isReloading,\n ...restProps\n } = selectProps;\n\n const [ filterQuery, setFilterQuery ] = useState( "" );\n // We control menuIsOpen ourselves. react-select\'s built-in menu management closes\n // the menu whenever its internal input blurs, and focusing our in-dropdown search\n // input always blurs that input. Owning the open state decouples the menu lifecycle\n // from react-select\'s focus/blur logic.\n const [ menuOpen, setMenuOpen ] = useState( false );\n const containerRef = useRef<HTMLDivElement>( null );\n const searchInputRef = useRef<HTMLInputElement>( null );\n // The menu can render in a portal (menuPortalTarget), so it is not always a descendant\n // of containerRef. Track its DOM node separately for the outside-click check below.\n const menuNodeRef = useRef<HTMLDivElement | null>( null );\n // Latest input modality, shared by every option\'s full-text overlay (see SelectOptionContext).\n // A ref, not state: the reads that matter already re-render on isHovered / isFocused changes, and\n // flipping it must not itself trigger a render.\n const interactionModeRef = useRef<"pointer" | "keyboard">( "pointer" );\n\n // Extract props we compose ourselves so the spread doesn\'t override them\n const {\n onMenuClose: externalOnMenuClose,\n onMenuOpen: externalOnMenuOpen,\n onChange: externalOnChange,\n ...otherRestProps\n } = restProps;\n\n const { isMulti } = otherRestProps;\n\n // Committed multi-select value shown as chips in the control. When the consumer passes `value`\n // the component is controlled and this tracks it; otherwise (uncontrolled) we own it internally\n // and update it on commit so chips still render.\n const isControlled = value !== undefined;\n // Seed committed/draft state from defaultValue when uncontrolled, so an uncontrolled multi-select\n // starts in sync with what react-select renders rather than an empty draft that would wipe the\n // defaults on the first commit. Only read on the initial render.\n const initialMultiValue = value !== undefined ? value : ( otherRestProps.defaultValue as typeof value );\n const [ committedValue, setCommittedValue ] = useState( initialMultiValue );\n // When controlled, `multiControlValue` reads `value` directly, so `committedValue` is only ever\n // consumed in the uncontrolled path \u2014 no effect mirroring `value` into it is needed.\n const multiControlValue = isControlled ? value : committedValue;\n\n // Draft selection for multi-select. While the menu is open, option toggles update this draft\n // instead of calling onChange; the draft is committed only when the menu closes via an outside\n // click. Pressing Escape discards it. Single-select keeps its live onChange behavior.\n const [ pendingValue, setPendingValue ] = useState( initialMultiValue );\n const pendingValueRef = useRef( pendingValue );\n pendingValueRef.current = pendingValue;\n\n // Keep the draft synced with the committed value while the menu is closed, so external updates\n // are reflected on next open.\n React.useEffect(() => {\n if ( isMulti && !menuOpen ) {\n setPendingValue( multiControlValue );\n }\n }, [ isMulti, menuOpen, multiControlValue ]);\n\n const closeMenu = React.useCallback(() => {\n setMenuOpen( false );\n setFilterQuery( "" );\n externalOnMenuClose?.();\n }, [externalOnMenuClose]);\n\n // Commit the multi-select draft, then close. Used by the outside-click handler. Updates the\n // internal committed value (so uncontrolled chips render) and notifies the consumer.\n const commitAndClose = React.useCallback(() => {\n if ( isMulti ) {\n setCommittedValue( pendingValueRef.current );\n ( externalOnChange as ( ...args: unknown[]) => void )?.(\n pendingValueRef.current,\n { action: "set-value" }\n );\n }\n closeMenu();\n }, [ isMulti, externalOnChange, closeMenu ]);\n\n const openMenu = React.useCallback(() => {\n // No need to seed the draft here: the effect above keeps pendingValue synced to the committed\n // value the whole time the menu is closed, so it is already current at open.\n setMenuOpen( true );\n externalOnMenuOpen?.();\n }, [externalOnMenuOpen]);\n\n // Multi-select draft mutators. The control is fed the committed `value` (so chips only appear\n // once the selection is committed), while these update the in-progress draft that drives the\n // menu\'s checkboxes and Select All. Selection is committed to onChange on outside-click close.\n const toggleDraftOption = React.useCallback(( option: IOption ) => {\n setPendingValue(( prev ) => {\n const arr = ( prev as IOption[] | undefined ) ?? [];\n const exists = arr.some(( o ) => o.value === option.value );\n const next = exists ? arr.filter(( o ) => o.value !== option.value ) : [ ...arr, option ];\n return next as typeof pendingValue;\n });\n requestAnimationFrame(() => searchInputRef.current?.focus());\n }, []);\n\n const setDraft = React.useCallback(( vals: IOption[]) => {\n setPendingValue( vals as typeof pendingValue );\n requestAnimationFrame(() => searchInputRef.current?.focus());\n }, []);\n\n // Single source of truth for the "Select All" toggle, shared by the mouse path (Option\n // component) and the keyboard path (react-select onChange). If every real option is already\n // in the draft it deselects down to the fixed ones; otherwise it selects them all.\n const handleSelectAllDraft = React.useCallback(() => {\n const selectable = getSelectableOptions( options );\n const selectableValues = new Set( selectable.map(( o ) => o.value ));\n const draft = ( pendingValueRef.current as IOption[] | undefined ) ?? [];\n const draftValues = new Set( draft.map(( o ) => o.value ));\n const next = areAllSelectableSelected( options, draft )\n // Deselect: drop selectable, non-fixed options; keep fixed and disabled ones untouched.\n ? draft.filter(( o ) => o.isFixed || !selectableValues.has( o.value ))\n // Select: add every selectable (enabled) option not already present.\n : [ ...draft, ...selectable.filter(( o ) => !draftValues.has( o.value )) ];\n setDraft( next );\n }, [ options, setDraft ]);\n\n // Close the dropdown on interaction outside the component. react-select\'s own\n // outside-click handling relies on its input being focused (it is not \u2014 focus lives\n // in the dropdown search input), so we handle it ourselves.\n React.useEffect(() => {\n if ( !menuOpen ) {\n return undefined;\n }\n const handlePointerDown = ( e: MouseEvent ) => {\n const target = e.target as HTMLElement | null;\n // Ignore events whose target detached during a re-render \u2014 react-select swaps its\n // control input when the menu opens, so the opening mousedown\'s target leaves the\n // DOM and would otherwise be mistaken for an outside click.\n if ( !target || !target.isConnected ) {\n return;\n }\n // Clicks inside the (possibly portaled) menu keep it open.\n const insideMenu = menuNodeRef.current?.contains( target );\n if ( insideMenu ) {\n return;\n }\n // The per-chip remove "\xD7" and the clear-all control have their own react-select handlers;\n // don\'t hijack those into a menu close.\n if ( target.closest( ".select__multi-value__remove, .select__clear-indicator" )) {\n return;\n }\n // Everything else \u2014 the control body/chevron (toggle-closed) or a truly outside click \u2014\n // commits the draft and closes.\n commitAndClose();\n };\n // Defer attaching the listener so the click that opened the menu cannot immediately\n // close it.\n const raf = requestAnimationFrame(() => {\n document.addEventListener( "mousedown", handlePointerDown );\n });\n return () => {\n cancelAnimationFrame( raf );\n document.removeEventListener( "mousedown", handlePointerDown );\n };\n }, [ menuOpen, commitAndClose ]);\n\n const {\n DropdownIndicator,\n ValueContainer,\n MultiValue,\n MultiValueRemove,\n Input\n } = createSelectComponents<IsMulti, Group>({\n prefixIcon,\n suffixIcon,\n maxVisibleValues,\n maxVisibleValuesMsg,\n disabled\n });\n\n const {\n base,\n label: labelClass,\n helperText: helperTextClass,\n menuSearchContainer,\n menuSearchInput,\n optionLabelWrap,\n optionLabel,\n optionOverlay\n } = selectVariants({ error });\n\n // Live option config for the stable SelectOption (see selectComponents.tsx). Rebuilt each\n // render so checkbox / Select-All state tracks the draft; the component identity stays stable.\n const optionContextValue = React.useMemo(\n () => ({\n draftValues: isMulti ? ( pendingValue as IOption[] | undefined ) : undefined,\n onToggleDraftOption: toggleDraftOption,\n onSelectAll: handleSelectAllDraft,\n optionLabelWrapClass: optionLabelWrap(),\n optionLabelClass: optionLabel(),\n optionOverlayClass: optionOverlay(),\n interactionModeRef\n }),\n [ isMulti, pendingValue, toggleDraftOption, handleSelectAllDraft, optionLabelWrap, optionLabel, optionOverlay ]\n );\n\n // Live values the stable, module-level SelectMenu reads via context. SelectMenu must keep a\n // stable identity (react-select remounts custom components on reference change, which would\n // destroy the search input\'s focus/caret and the MenuList scroll on every keystroke), so it\n // cannot close over these directly \u2014 context lets it re-render with current values instead.\n const menuContextValue = React.useMemo<ISelectMenuContext>(\n () => ({\n filterQuery,\n onFilterChange: setFilterQuery,\n searchPlaceholder,\n menuFooter,\n closeMenu,\n commitAndClose,\n searchContainerClass: menuSearchContainer(),\n searchInputClass: menuSearchInput(),\n searchInputRef,\n menuNodeRef,\n containerRef,\n onReload,\n isReloading,\n reloadTooltip,\n interactionModeRef\n }),\n [ filterQuery, searchPlaceholder, menuFooter, closeMenu, commitAndClose, menuSearchContainer, menuSearchInput, onReload, isReloading, reloadTooltip ]\n );\n\n const customComponents = {\n IndicatorSeparator: () => null,\n DropdownIndicator,\n Option: SelectOption,\n ValueContainer,\n MultiValue,\n MultiValueRemove,\n Input,\n Menu: SelectMenu\n };\n\n const inputId = useId();\n // unify component type for creatable and default select\n type TRSComponent = ComponentType<ReactSelectProps<IOption, IsMulti, Group>>;\n const SelectType: TRSComponent = creatable\n ? ( CreatableSelect as TRSComponent )\n : ( ReactSelect as TRSComponent );\n\n return (\n <div className={base({ class: className })} ref={containerRef}>\n {label !== undefined && (\n <label\n htmlFor={id || inputId}\n className={labelClass()}\n >\n {label}\n </label>\n )}\n <SelectMenuContext.Provider value={menuContextValue}>\n <SelectOptionContext.Provider value={optionContextValue}>\n <SelectType\n classNamePrefix="select"\n inputId={id || inputId}\n options={\n otherRestProps.isMulti && ( options as IOption[]).length\n ? ([{ value: "select-all", label: "Select All" }] as IOption[]).concat(\n options as IOption[]\n )\n : options\n }\n value={isMulti ? multiControlValue : value}\n hideSelectedOptions={false}\n menuPlacement="auto"\n components={customComponents}\n className={cx( "select", `select-${size}` )}\n styles={\n reactSelectCustomStyles<IsMulti, Group>(\n error,\n size,\n otherRestProps.isMulti as boolean\n )\n }\n isDisabled={disabled}\n // Default search matcher. Placed before the spread so a consumer-supplied `filterOption`\n // still overrides it. `candidate.data` is the IOption, so a custom (ReactNode) label is\n // searchable via its `searchValue` - react-select\'s default filter stringifies such a\n // label to "[object Object]" and matches nothing.\n filterOption={( candidate, input ) => matchesQuery( candidate.data, input )}\n {...otherRestProps}\n // Controlled props are applied AFTER the spread so a consumer cannot accidentally\n // override the menu/search mechanism this component owns.\n inputValue={filterQuery}\n menuIsOpen={menuOpen}\n onMenuOpen={openMenu}\n /*\n * No-op: react-select calls onMenuClose from its input-blur handler, which\n * fires every time focus moves to the dropdown search input. Honoring it\n * would close the menu immediately. We close explicitly instead \u2014 via\n * outside-click, Escape, and single-select onChange.\n */\n onMenuClose={() => {}}\n onChange={( newValue: unknown, actionMeta: unknown ) => {\n if ( isMulti ) {\n // The control is fed the committed value, so option toggles must route into the draft\n // rather than onChange. Mouse clicks are handled directly in SelectOption; this path\n // only fires for keyboard selection (Enter forwarded to react-select\'s input), which we\n // translate into a draft toggle. The draft is committed when the menu closes via an\n // outside click.\n const meta = actionMeta as { action: string; option?: IOption; removedValue?: IOption };\n // Control-level actions act on the committed value (chips), not the in-menu draft:\n // clearing all, removing a single pill via its X, or popping the last value with\n // Backspace. These commit immediately and notify the consumer; otherwise the change\n // would only land on the next outside-click close (and never reach a controlled\n // `value`). Keyboard option toggles (Enter forwarded to react-select\'s input) are the\n // only path that should buffer into the draft.\n if ( meta.action === "clear" || meta.action === "remove-value" || meta.action === "pop-value" ) {\n setPendingValue( newValue as typeof pendingValue );\n setCommittedValue( newValue as typeof committedValue );\n ( externalOnChange as ( ...args: unknown[]) => void )?.( newValue, actionMeta );\n } else if ( meta.option ) {\n // The injected "Select All" row has no dedicated onChange semantics in react-select,\n // so keyboard selection reports it like any option. Route it through the shared\n // handler instead of buffering the synthetic {value:"select-all"} into the draft.\n if ( meta.option.value === "select-all" ) {\n handleSelectAllDraft();\n } else {\n toggleDraftOption( meta.option );\n }\n }\n } else {\n // Close the menu and commit immediately after a single-value selection.\n closeMenu();\n ( externalOnChange as ( ...args: unknown[]) => void )?.( newValue, actionMeta );\n }\n }}\n closeMenuOnSelect={!isMulti}\n />\n </SelectOptionContext.Provider>\n </SelectMenuContext.Provider>\n {helperText && (\n <div className={helperTextClass()}>\n {helperText}\n </div>\n )}\n </div>\n );\n}\n\nSelect.displayName = "Select";\n'
|
|
3696
|
+
"content": 'import * as React from "react";\nimport {\n type ComponentType,\n type ForwardedRef,\n type ReactElement,\n type RefAttributes,\n useId,\n useMemo,\n useRef,\n useState\n} from "react";\nimport ReactSelect, {\n type Props as ReactSelectProps,\n type GroupBase,\n type FilterOptionOption\n} from "react-select";\nimport CreatableSelect from "react-select/creatable";\nimport mergeRefs from "react-merge-refs";\nimport { cx } from "tailwind-variants";\n\nimport { useFilterQuery, useIgnoredPropWarning, useOnValueChange, usePrefetchBaseline } from "@hooks";\nimport { matchesQuery } from "@utils";\nimport {\n reactSelectCustomStyles,\n getSelectableOptions,\n getPooledValues,\n areAllSelectableSelected,\n isCreateOption,\n toPoolOption,\n SELECT_ALL_VALUE\n} from "./utils";\nimport { selectVariants } from "./selectVariants";\nimport {\n createSelectComponents,\n createSelectInput,\n NoIndicatorSeparator,\n SelectOption,\n SelectOptionContext\n} from "./selectComponents";\nimport { SelectMenu, SelectMenuContext } from "./selectMenu";\nimport { focusMenuInput, handleMenuKey } from "./selectKeyboard";\nimport { useSelectOptionSource } from "./useSelectOptionSource";\nimport { useSelectOutsideClose } from "./useSelectOutsideClose";\n\nimport {\n ESelectSizes,\n type IOption,\n type ISelectProps,\n type ISelectMenuContext,\n type TSelectInteractionMode\n} from "./types";\n\n// Stable empty identity for the created-option pool, so an untouched creatable Select never rebuilds\n// the list it hands react-select.\nconst EMPTY_CREATED: readonly IOption[] = [];\n\n// The synthetic Select-All row, hoisted so `selectOptions` keeps a stable array identity while the\n// row is shown.\nconst SELECT_ALL_OPTION: IOption = { value: SELECT_ALL_VALUE, label: "Select All" };\n\n// `filterOption` deprecation notices, hoisted so the warning hook\'s message dependency stays stable.\nconst FILTER_OPTION_DEPRECATED =\n "Select: `filterOption` is deprecated and will be removed in the next major. Use `onFilterChange` " +\n "instead: hold the options in state, filter them with your own predicate, and pass the result as " +\n "`options` (with `filterDebounceMs={0}` to stay synchronous).";\nconst FILTER_OPTION_IGNORED =\n "Select: `filterOption` is deprecated and is ignored while filtering is server-side \u2014 the options " +\n "you return for the query already are the result set.";\nconst SEARCHABLE_FILTER_IGNORED =\n "Select: `onFilterChange` / `filterValue` have nothing to drive while `searchable={false}` \u2014 with no " +\n "search input the query can never change, and a seeded `filterValue` hides rows the user has no way " +\n "to bring back. Filter the `options` you pass instead, or keep the search input.";\n\nfunction SelectComponent<\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>(\n selectProps: ISelectProps<IsMulti, Group>,\n forwardedRef: ForwardedRef<HTMLDivElement>\n): ReactElement {\n const {\n id,\n className,\n label,\n size = ESelectSizes.MD,\n options,\n value,\n helperText,\n error = false,\n disabled = false,\n creatable = false,\n maxVisibleValues = 3,\n maxVisibleValuesMsg,\n menuFooter,\n prefixIcon,\n suffixIcon,\n searchable = true,\n searchPlaceholder = "Search...",\n reloadTooltip = "Reload",\n onReload,\n isReloading,\n filterValue,\n onFilterChange,\n filterDebounceMs = 300,\n // Intercepted \u2014 not forwarded (avoids react-select\'s own loading UI).\n isLoading = false,\n loadOptions,\n initialOptions,\n // Left undefined here, not defaulted: sync mode warns on a `prefetch` the consumer actually passed,\n // which an eager default would erase. Resolved at the one place that reads it as a trigger.\n prefetch,\n refetchOnClear = false,\n optionsKey,\n loadErrorMessage,\n showReloadButton = false,\n onLoadError,\n ...restProps\n } = selectProps;\n\n // Owns the async/sync mode decision and every derived option/loading/error value. Declared before\n // useFilterQuery because it supplies that hook\'s handler.\n const optionSource = useSelectOptionSource<Group>({\n options,\n loadOptions,\n initialOptions,\n prefetch,\n refetchOnClear,\n optionsKey,\n loadErrorMessage,\n showReloadButton,\n onLoadError,\n isLoading,\n onReload,\n isReloading,\n onFilterChange\n });\n\n // Filter query state: the raw input value plus the debounced query the option source sees.\n const {\n filterQuery,\n handleFilterInput,\n handleFilterKeyDown,\n handleFilterKeyUp,\n handleFilterBlur,\n resetFilter\n } = useFilterQuery({\n filterValue,\n onFilterChange: optionSource.onFilterQueryChange,\n filterDebounceMs\n });\n // We control menuIsOpen ourselves. react-select\'s built-in menu management closes\n // the menu whenever its internal input blurs, and focusing our in-dropdown search\n // input always blurs that input. Owning the open state decouples the menu lifecycle\n // from react-select\'s focus/blur logic.\n const [ menuOpen, setMenuOpen ] = useState( false );\n const containerRef = useRef<HTMLDivElement>( null );\n const searchInputRef = useRef<HTMLInputElement>( null );\n // The wrapper is both the consumer\'s ref target and ours (the search box reaches react-select\'s\n // hidden control input through it). Memoised so React does not re-attach it every render.\n const rootRef = useMemo(() => mergeRefs([ forwardedRef, containerRef ]), [forwardedRef]);\n // The menu can render in a portal (menuPortalTarget), so it is not always a descendant\n // of containerRef. Track its DOM node separately for the outside-click check below.\n const menuNodeRef = useRef<HTMLDivElement | null>( null );\n // Latest input modality, shared by every option\'s full-text overlay (see SelectOptionContext).\n // State, not a ref: it decides what an option renders. Re-setting the current mode is a no-op React\n // bails out of, so this only re-renders on a genuine pointer\u2194keyboard switch.\n const [ interactionMode, setInteractionMode ] = useState<TSelectInteractionMode>( "pointer" );\n\n // Extract props we compose ourselves so the spread doesn\'t override them\n const {\n onMenuClose: externalOnMenuClose,\n onMenuOpen: externalOnMenuOpen,\n onChange: externalOnChange,\n onKeyDown: externalOnKeyDown,\n filterOption: externalFilterOption,\n ...otherRestProps\n } = restProps;\n\n const { isMulti } = otherRestProps;\n\n // Committed multi-select value shown as chips in the control. When the consumer passes `value`\n // the component is controlled and this tracks it; otherwise (uncontrolled) we own it internally\n // and update it on commit so chips still render.\n const isControlled = value !== undefined;\n // Seed committed/draft state from defaultValue when uncontrolled, so an uncontrolled multi-select\n // starts in sync with what react-select renders rather than an empty draft that would wipe the\n // defaults on the first commit. Only read on the initial render.\n const initialMultiValue = value !== undefined ? value : ( otherRestProps.defaultValue as typeof value );\n const [ committedValue, setCommittedValue ] = useState( initialMultiValue );\n // When controlled, `multiControlValue` reads `value` directly, so `committedValue` is only ever\n // consumed in the uncontrolled path \u2014 no effect mirroring `value` into it is needed.\n const multiControlValue = isControlled ? value : committedValue;\n\n // Draft selection for multi-select. While the menu is open, option toggles update this draft\n // instead of calling onChange; the draft is committed only when the menu closes via an outside\n // click. Pressing Escape discards it. Single-select keeps its live onChange behavior.\n const [ pendingValue, setPendingValue ] = useState( initialMultiValue );\n const pendingValueRef = useRef( pendingValue );\n pendingValueRef.current = pendingValue;\n\n // Keep the draft synced with the committed value while the menu is closed, so external updates\n // are reflected on next open.\n React.useEffect(() => {\n if ( isMulti && !menuOpen ) {\n setPendingValue( multiControlValue );\n }\n }, [ isMulti, menuOpen, multiControlValue ]);\n\n const closeMenu = React.useCallback(() => {\n setMenuOpen( false );\n resetFilter();\n externalOnMenuClose?.();\n }, [ externalOnMenuClose, resetFilter ]);\n\n // Focus returns to whichever input the menu is currently driven from. Deferred a frame because the\n // re-render these callers trigger can rebuild the node focus sits on.\n const refocusMenuInput = React.useCallback(() => {\n requestAnimationFrame(() => focusMenuInput({ searchInputRef, containerRef }));\n }, []);\n\n // The single definition of committing: the draft becomes the value the control renders (so\n // uncontrolled chips appear) and the consumer hears about it once. Every caller differs only in\n // what it commits and what it does afterwards.\n const commitSelection = React.useCallback(( next: typeof pendingValue, actionMeta: unknown ) => {\n setPendingValue( next );\n setCommittedValue( next as typeof committedValue );\n ( externalOnChange as ( ...args: unknown[]) => void )?.( next, actionMeta );\n }, [externalOnChange]);\n\n // Commit the multi-select draft, then close \u2014 what both ways of leaving the menu with the selection\n // intact do: an outside click and Tab.\n const commitAndClose = React.useCallback(() => {\n if ( isMulti ) {\n commitSelection( pendingValueRef.current, { action: "set-value" });\n }\n closeMenu();\n }, [ isMulti, commitSelection, closeMenu ]);\n\n const openMenu = React.useCallback(() => {\n // No need to seed the draft here: the effect above keeps pendingValue synced to the committed\n // value the whole time the menu is closed, so it is already current at open.\n setMenuOpen( true );\n externalOnMenuOpen?.();\n }, [externalOnMenuOpen]);\n\n // Multi-select draft mutators. The control is fed the committed `value` (so chips only appear\n // once the selection is committed), while these update the in-progress draft that drives the\n // menu\'s checkboxes and Select All. Selection is committed to onChange on outside-click close.\n const toggleDraftOption = React.useCallback(( option: IOption ) => {\n setPendingValue(( prev ) => {\n const arr = ( prev as IOption[] | undefined ) ?? [];\n const exists = arr.some(( o ) => o.value === option.value );\n const next = exists ? arr.filter(( o ) => o.value !== option.value ) : [ ...arr, option ];\n return next as typeof pendingValue;\n });\n refocusMenuInput();\n }, [refocusMenuInput]);\n\n // Creating commits on the spot rather than buffering into the draft: the consumer often has to act on\n // a new value at once \u2014 persisting the entity it stands for \u2014 and react-select reports the create as a\n // value-level action for that reason. It is appended to the draft first, so ticks made since the menu\n // opened travel with it instead of being overwritten by a value built from the committed one.\n const commitCreatedOption = React.useCallback(( option: IOption, actionMeta: unknown ) => {\n const draft = ( pendingValueRef.current as IOption[] | undefined ) ?? [];\n // The Create row is only offered for text the selection does not already hold, so a repeat of the\n // same text is the user asking for it again, not asking to take it back.\n const next = draft.some(( o ) => o.value === option.value ) ? draft : [ ...draft, option ];\n commitSelection( next as typeof pendingValue, actionMeta );\n refocusMenuInput();\n }, [ commitSelection, refocusMenuInput ]);\n\n // Removing a chip acts on what the user can see \u2014 the committed chips \u2014 but it must not undo the\n // ticks the menu has collected since it opened. react-select builds its replacement value from the\n // control\'s value, which knows nothing about the draft, so the removal is replayed against the draft\n // instead. With the menu closed the two are in sync, so this lands on the value react-select computed.\n const commitRemovedOption = React.useCallback(( removed: IOption, actionMeta: unknown ) => {\n const draft = ( pendingValueRef.current as IOption[] | undefined ) ?? [];\n commitSelection( draft.filter(( o ) => o.value !== removed.value ) as typeof pendingValue, actionMeta );\n }, [commitSelection]);\n\n const setDraft = React.useCallback(( vals: IOption[]) => {\n setPendingValue( vals as typeof pendingValue );\n refocusMenuInput();\n }, [refocusMenuInput]);\n\n // Async mode, or the presence of onFilterChange, is the client/server mode switch.\n const { isServerFiltered } = optionSource;\n\n // react-select derives the candidate it hands `filterOption` from `getOptionLabel`/`getOptionValue`,\n // so mirror that construction for the Select-All path, where there is no react-select candidate to\n // pass through. Reading them off the spread rather than destructuring keeps them flowing to\n // react-select untouched.\n const { getOptionLabel: externalGetOptionLabel, getOptionValue: externalGetOptionValue } = otherRestProps;\n const toCandidate = React.useCallback(\n ( option: IOption ): FilterOptionOption<IOption> => ({\n // react-select types the candidate label as a string but passes whatever getOptionLabel returns,\n // so an unresolved ReactNode label reaches a consumer predicate here exactly as it does there.\n label: externalGetOptionLabel ? externalGetOptionLabel( option ) : ( option.label as string ),\n value: externalGetOptionValue ? externalGetOptionValue( option ) : option.value,\n data: option\n }),\n [ externalGetOptionLabel, externalGetOptionValue ]\n );\n\n // Options the user has made with the Create row. react-select only ever puts the new value in the\n // selection \u2014 keeping them here is what gives each one an ordinary row in the list, so it can be\n // unticked and ticked again, counts towards "Select All", and stops the Create row being offered for\n // the same text twice. They last as long as the component: a row the user made does not disappear\n // because they cleared it.\n const [ createdOptions, setCreatedOptions ] = useState<readonly IOption[]>( EMPTY_CREATED );\n // Takes the option in the form the consumer is handed, so the row in the list and the value they hold\n // are the same thing \u2014 there is one `toPoolOption` per create, at the callback that reports it.\n const rememberCreatedOption = React.useCallback(( option: IOption ) => {\n setCreatedOptions(( prev ) => (\n prev.some(( o ) => o.value === option.value ) ? prev : [ ...prev, option ]\n ));\n }, []);\n\n // The created options still standing in for a value nothing upstream knows about. A consumer who\n // persists the new entity and passes it back in `options` takes ownership of it from that point: it\n // keeps their row, their grouping and their filtering, and drops out of everything below.\n const unclaimedCreated = React.useMemo(() => {\n if ( createdOptions.length === 0 ) {\n return EMPTY_CREATED;\n }\n const known = getPooledValues( optionSource.options );\n return createdOptions.filter(( o ) => !known.has( o.value ));\n }, [ optionSource.options, createdOptions ]);\n\n // The list react-select is given: the consumer\'s own options, then the created ones they do not\n // already account for.\n const pooledOptions = React.useMemo(\n () => ( unclaimedCreated.length === 0\n ? optionSource.options\n : [ ...optionSource.options, ...unclaimedCreated ]),\n [ optionSource.options, unclaimedCreated ]\n );\n\n const createdValues = React.useMemo(\n () => new Set( unclaimedCreated.map(( o ) => o.value )),\n [unclaimedCreated]\n );\n\n // Deprecated: a second filtering axis alongside `onFilterChange`, which already covers it \u2014 that hands\n // the consumer the query and treats `options` as the answer, so a custom predicate belongs in their own\n // memo rather than in a react-select callback. Still honoured client-side until the next major, since\n // it reached react-select through the prop spread before filtering was owned here. Server-filtered mode\n // ignores it outright: a local predicate there could only hide rows the server deliberately returned,\n // and it cannot see the fields the server matched on.\n useIgnoredPropWarning(\n externalFilterOption !== undefined,\n isServerFiltered ? FILTER_OPTION_IGNORED : FILTER_OPTION_DEPRECATED\n );\n\n // No search input means no query: a seeded `filterValue` narrows the list behind the user\'s back, and\n // `onFilterChange` can only ever fire the one reset on close.\n useIgnoredPropWarning(\n !searchable && ( typeof onFilterChange === "function" || ( filterValue !== undefined && filterValue !== "" )),\n SEARCHABLE_FILTER_IGNORED\n );\n\n // The predicate react-select filters rows with, resolved once so the menu and Select All can never\n // disagree about what is visible. Precedence, highest first: server-filtered mode and\n // `filterOption={null}` (react-select\'s documented opt-out) both do no local pass at all; a consumer\n // `filterOption` then decides; otherwise the library default applies. Keyed on the prop\'s identity, so\n // a predicate that changes behaviour re-narrows the visible set instead of leaving Select All acting on\n // a stale one. The candidate argument is react-select\'s own on the path that has one, so the consumer\n // sees exactly what react-select built there and the Select-All path constructs one only when a\n // predicate is actually going to read it.\n const isOptionVisible = React.useCallback(\n ( option: IOption, input: string, candidate?: FilterOptionOption<IOption> ): boolean => {\n // A created row is the library\'s own, built out of typed text. Every mode that hands narrowing to\n // someone else hands it to someone who has never seen these rows \u2014 the server did not return them,\n // and a consumer predicate is written for the consumer\'s data \u2014 so they are matched here in all of\n // them, or a created row would sit under every unrelated query.\n if ( createdValues.has( option.value )) {\n return matchesQuery( option, input );\n }\n if ( isServerFiltered || externalFilterOption === null ) {\n return true;\n }\n return typeof externalFilterOption === "function"\n ? externalFilterOption( candidate ?? toCandidate( option ), input )\n : matchesQuery( option, input );\n },\n [ externalFilterOption, isServerFiltered, toCandidate, createdValues ]\n );\n\n // The enabled options in the pool, groups flattened. Kept apart from the narrowing below so a\n // keystroke re-runs only the query pass, not the flatten.\n const selectableOptions = React.useMemo(\n () => getSelectableOptions( pooledOptions ),\n [pooledOptions]\n );\n\n // What Select All acts on: the enabled options currently ON SCREEN, so it can never reach an option\n // the query has hidden. Both no-op modes (server-filtered, `filterOption={null}`) are folded into the\n // predicate itself, so there is one pass here regardless of mode.\n const visibleSelectable = React.useMemo(\n () => selectableOptions.filter(( o ) => isOptionVisible( o, filterQuery )),\n [ selectableOptions, isOptionVisible, filterQuery ]\n );\n\n // Read through a ref so handleSelectAllDraft survives every keystroke with its identity intact \u2014\n // see useSelectOptionSource\'s note on what a churning callback costs the whole option context.\n const visibleSelectableRef = useRef( visibleSelectable );\n visibleSelectableRef.current = visibleSelectable;\n\n // Single source of truth for the "Select All" toggle, shared by the mouse path (Option\n // component) and the keyboard path (react-select onChange). If every visible option is already\n // in the draft it deselects down to the fixed ones; otherwise it selects them all. Both\n // directions leave options hidden by the query untouched, so a selection made under one query\n // survives the next.\n const handleSelectAllDraft = React.useCallback(() => {\n const selectable = visibleSelectableRef.current;\n const selectableValues = new Set( selectable.map(( o ) => o.value ));\n const draft = ( pendingValueRef.current as IOption[] | undefined ) ?? [];\n const draftKeys = new Set( draft.map(( o ) => o.value ));\n const next = areAllSelectableSelected( selectable, draftKeys )\n // Deselect: drop selectable, non-fixed options; keep fixed and disabled ones untouched.\n ? draft.filter(( o ) => o.isFixed || !selectableValues.has( o.value ))\n // Select: add every selectable (enabled) option not already present.\n : [ ...draft, ...selectable.filter(( o ) => !draftKeys.has( o.value )) ];\n setDraft( next );\n }, [setDraft]);\n\n useSelectOutsideClose({ menuOpen, menuNodeRef, commitAndClose });\n\n // Prefetch the baseline on first OPEN by default, not on mount: a form with six server-filtered\n // Selects would otherwise fire six requests on paint for menus the user may never open.\n // `prefetch="mount"` opts into the baseline at render, for a Select that would otherwise sit\n // visibly empty.\n usePrefetchBaseline({\n prefetch: prefetch ?? "open",\n isOpen: menuOpen,\n optionsKey,\n ensureDefaults: optionSource.ensureDefaults\n });\n\n // Route an optionsKey CHANGE into the clear path (resetFilter \u2192 onFilterChange("")), which drops the\n // search view and lets ensureDefaults lazily repopulate. Skipped on mount: resetFilter notifies the\n // consumer whenever the query is non-empty, and a seeded `filterValue` must not fire that on paint.\n useOnValueChange( optionsKey, resetFilter );\n\n const {\n base,\n label: labelClass,\n helperText: helperTextClass,\n menuSearchContainer,\n menuSearchInput,\n menuLoader,\n menuError,\n optionLabelWrap,\n optionLabel,\n optionOverlay\n } = selectVariants({ error, searchable });\n\n const searchContainerClass = menuSearchContainer();\n const searchInputClass = menuSearchInput();\n const loaderClass = menuLoader();\n const errorClass = menuError();\n const optionLabelWrapClass = optionLabelWrap();\n const optionLabelClass = optionLabel();\n const optionOverlayClass = optionOverlay();\n\n // Live option config for the stable SelectOption (see selectComponents.tsx). Rebuilt whenever the\n // draft changes so checkbox / Select-All state tracks it; the component identity stays stable.\n const draftValues = React.useMemo(\n () => ( isMulti ? new Set((( pendingValue as IOption[] | undefined ) ?? []).map(( o ) => o.value )) : undefined ),\n [ isMulti, pendingValue ]\n );\n // Computed here, where the visible set lives, rather than in SelectOption from react-select\'s\n // unfiltered `props.options` \u2014 which would leave the row unchecked even with every visible option\n // ticked. A boolean in the context also keeps its identity stable across keystrokes.\n const areAllSelected = React.useMemo(\n () => draftValues !== undefined && areAllSelectableSelected( visibleSelectable, draftValues ),\n [ visibleSelectable, draftValues ]\n );\n const optionContextValue = React.useMemo(\n () => ({\n draftValues,\n areAllSelected,\n onToggleDraftOption: toggleDraftOption,\n onSelectAll: handleSelectAllDraft,\n optionLabelWrapClass,\n optionLabelClass,\n optionOverlayClass,\n interactionMode,\n onInteractionMode: setInteractionMode\n }),\n [ draftValues, areAllSelected, toggleDraftOption, handleSelectAllDraft, optionLabelWrapClass,\n optionLabelClass, optionOverlayClass, interactionMode ]\n );\n\n // Live values the stable, module-level SelectMenu reads via context. SelectMenu must keep a\n // stable identity (react-select remounts custom components on reference change, which would\n // destroy the search input\'s focus/caret and the MenuList scroll on every keystroke), so it\n // cannot close over these directly \u2014 context lets it re-render with current values instead.\n const menuContextValue = React.useMemo<ISelectMenuContext>(\n () => ({\n searchable,\n filterQuery,\n onFilterInput: handleFilterInput,\n onFilterKeyDown: handleFilterKeyDown,\n onFilterKeyUp: handleFilterKeyUp,\n onFilterBlur: handleFilterBlur,\n searchPlaceholder,\n menuFooter,\n closeMenu,\n commitAndClose,\n searchContainerClass,\n searchInputClass,\n loaderClass,\n isLoading: optionSource.isLoading,\n loadError: optionSource.loadError,\n errorClass,\n searchInputRef,\n menuNodeRef,\n containerRef,\n onReload: optionSource.onReload,\n isReloading: optionSource.isReloading,\n reloadTooltip,\n onInteractionMode: setInteractionMode\n }),\n [ searchable, filterQuery, handleFilterInput, handleFilterKeyDown, handleFilterKeyUp, handleFilterBlur,\n searchPlaceholder, menuFooter, closeMenu, commitAndClose, searchContainerClass, searchInputClass,\n loaderClass, errorClass, optionSource.isLoading, optionSource.loadError, optionSource.onReload,\n optionSource.isReloading, reloadTooltip ]\n );\n\n // Without a search box the control carries the menu\'s keyboard model, so the shared handler runs from\n // react-select\'s own container listener instead of from the search input. A consumer handler goes\n // first and can opt out of the built-ins by preventing default \u2014 the contract react-select itself\n // applies to this prop. Tab through a CLOSED multi-select must stay inert, hence the menuOpen guard.\n const handleControlKeyDown = ( e: React.KeyboardEvent<HTMLDivElement> ) => {\n externalOnKeyDown?.( e );\n if ( e.defaultPrevented || searchable || !menuOpen ) {\n return;\n }\n // Nothing to relay here: the control input is where react-select listens, so a key the handler\n // leaves alone reaches it by bubbling.\n handleMenuKey( e, menuContextValue );\n };\n\n // The synthetic Select-All row is prepended to the option set so it keyboard-navigates like any\n // other row. Keyed on the boolean rather than on `visibleSelectable` itself: react-select rebuilds\n // its whole focusable-option index whenever this array\'s identity changes, so it must churn only\n // when the row genuinely appears or disappears \u2014 not on every keystroke.\n const showSelectAll = Boolean( isMulti ) && visibleSelectable.length >= 2;\n const selectOptions = React.useMemo(\n () => ( showSelectAll\n ? [SELECT_ALL_OPTION].concat( pooledOptions as IOption[])\n : pooledOptions ),\n [ showSelectAll, pooledOptions ]\n );\n\n // `Input` holds the DOM focus for as long as a search-less menu is open, and react-select remounts\n // any custom component whose identity changed \u2014 so it is memoised on its own narrow input rather\n // than alongside components that rebuild whenever a consumer passes a fresh icon element.\n const Input = useMemo(() => createSelectInput<IsMulti, Group>( maxVisibleValues ), [maxVisibleValues]);\n\n const customComponents = useMemo(\n () => ({\n ...createSelectComponents<IsMulti, Group>({\n prefixIcon,\n suffixIcon,\n maxVisibleValues,\n maxVisibleValuesMsg,\n disabled\n }),\n IndicatorSeparator: NoIndicatorSeparator,\n Option: SelectOption,\n Input,\n Menu: SelectMenu\n }),\n [ prefixIcon, suffixIcon, maxVisibleValues, maxVisibleValuesMsg, disabled, Input ]\n );\n\n // Select-All and Create are affordances over the result set, not members of it, so neither is ever\n // query-matched \u2014 whether they render at all is decided by `showSelectAll` above and by react-select\'s\n // own `isValidNewOption`. Every real row goes through the resolved predicate, handed react-select\'s own\n // candidate so a consumer predicate sees the label react-select built rather than a reconstruction of it.\n const filterOption = ( candidate: FilterOptionOption<IOption>, input: string ): boolean =>\n ( candidate.data.value === SELECT_ALL_VALUE ||\n isCreateOption( candidate.data ) ||\n isOptionVisible( candidate.data, input, candidate ));\n\n const inputId = useId();\n // unify component type for creatable and default select\n type TRSComponent = ComponentType<ReactSelectProps<IOption, IsMulti, Group>>;\n const SelectType: TRSComponent = creatable\n ? ( CreatableSelect as TRSComponent )\n : ( ReactSelect as TRSComponent );\n\n return (\n <div className={base({ class: className })} ref={rootRef}>\n {label !== undefined && (\n <label\n htmlFor={id || inputId}\n className={labelClass()}\n >\n {label}\n </label>\n )}\n <SelectMenuContext.Provider value={menuContextValue}>\n <SelectOptionContext.Provider value={optionContextValue}>\n <SelectType\n classNamePrefix="select"\n inputId={id || inputId}\n options={selectOptions}\n value={isMulti ? multiControlValue : value}\n hideSelectedOptions={false}\n menuPlacement="auto"\n components={customComponents}\n className={cx( "select", `select-${size}` )}\n styles={\n reactSelectCustomStyles<IsMulti, Group>(\n error,\n size,\n otherRestProps.isMulti as boolean\n )\n }\n isDisabled={disabled}\n {...otherRestProps}\n // Controlled props are applied AFTER the spread so a consumer cannot accidentally\n // override the menu/search mechanism this component owns.\n // A consumer `filterOption` is resolved into this wrapper (see `isOptionVisible`) rather\n // than forwarded, so their predicate still decides every real row while the Select-All row\n // stays exempt from it.\n filterOption={filterOption}\n onKeyDown={handleControlKeyDown}\n // Tab commits the multi-select draft and leaves; letting react-select select the focused\n // option on the way out would toggle a value the user never chose.\n tabSelectsValue={false}\n // Empty when closed \u2014 react-select blanks placeholder/value for a non-empty inputValue.\n inputValue={menuOpen ? filterQuery : ""}\n menuIsOpen={menuOpen}\n onMenuOpen={openMenu}\n /*\n * No-op: react-select calls onMenuClose from its input-blur handler, which\n * fires every time focus moves to the dropdown search input. Honoring it\n * would close the menu immediately. We close explicitly instead \u2014 via\n * outside-click, Escape, and single-select onChange.\n */\n onMenuClose={() => {}}\n onChange={( newValue: unknown, actionMeta: unknown ) => {\n if ( isMulti ) {\n // The control is fed the committed value, so option toggles must route into the draft\n // rather than onChange. Mouse clicks are handled directly in SelectOption; this path\n // only fires for keyboard selection (Enter forwarded to react-select\'s input), which we\n // translate into a draft toggle. The draft is committed when the menu closes via an\n // outside click.\n const meta = actionMeta as { action: string; option?: IOption; removedValue?: IOption };\n // Control-level actions are aimed at the chips rather than at the menu: clearing all,\n // removing a single pill via its X, or popping the last one with Backspace. These\n // commit immediately and notify the consumer; otherwise the change would only land on\n // the next outside-click close (and never reach a controlled `value`). Keyboard option\n // toggles (Enter forwarded to react-select\'s input) are the only path that buffers.\n if ( meta.action === "clear" ) {\n commitSelection( newValue as typeof pendingValue, actionMeta );\n } else if (( meta.action === "remove-value" || meta.action === "pop-value" ) && meta.removedValue ) {\n commitRemovedOption( meta.removedValue, actionMeta );\n } else if ( meta.action === "create-option" && meta.option ) {\n // react-select hands over the finished option \u2014 labelled with the text the user typed,\n // not with the "Create ..." prompt. Clearing the query retires the row that produced it\n // and brings the full list back, the same consumption of the search text a single-select\n // create performs on its way closed.\n const created = toPoolOption( meta.option );\n rememberCreatedOption( created );\n commitCreatedOption( created, { ...meta, option: created });\n resetFilter();\n } else if ( meta.option ) {\n // The injected Select-All row has no dedicated onChange semantics in react-select,\n // so keyboard selection reports it like any option. Route it through the shared\n // handler instead of buffering the synthetic row into the draft.\n if ( meta.option.value === SELECT_ALL_VALUE ) {\n handleSelectAllDraft();\n } else {\n toggleDraftOption( meta.option );\n }\n }\n } else {\n // Single-select reports a create through the same callback as any other pick, so the new\n // row is recorded here rather than on a branch of its own.\n const meta = actionMeta as { action: string; option?: IOption };\n const created = meta.action === "create-option" && meta.option\n ? toPoolOption( meta.option )\n : undefined;\n if ( created ) {\n rememberCreatedOption( created );\n }\n // Close the menu and commit immediately after a single-value selection.\n closeMenu();\n ( externalOnChange as ( ...args: unknown[]) => void )?.(\n created ?? newValue,\n created ? { ...meta, option: created } : actionMeta\n );\n }\n }}\n closeMenuOnSelect={!isMulti}\n />\n </SelectOptionContext.Provider>\n </SelectMenuContext.Provider>\n {helperText && (\n <div className={helperTextClass()}>\n {helperText}\n </div>\n )}\n </div>\n );\n}\n\nconst SelectWithRef = React.forwardRef( SelectComponent );\nSelectWithRef.displayName = "Select";\n\n/**\n * Select component for single or multi selection. The forwarded ref lands on the wrapper `<div>`; the\n * cast is what stops `forwardRef` \u2014 whose own signature is not generic \u2014 from collapsing `IsMulti` /\n * `Group` to their defaults.\n */\nexport const Select = SelectWithRef as unknown as <\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>(\n props: ISelectProps<IsMulti, Group> & RefAttributes<HTMLDivElement>\n) => ReactElement;\n'
|
|
3894
3697
|
},
|
|
3895
3698
|
{
|
|
3896
3699
|
"name": "index.ts",
|
|
3897
|
-
"content": 'export { Select } from "./select";\nexport { selectVariants } from "./selectVariants";\nexport type { IOption, ISelectProps } from "./types";'
|
|
3700
|
+
"content": 'export { Select } from "./select";\nexport { selectVariants } from "./selectVariants";\nexport type { IOption, ISelectProps, TSelectLoadOptions } from "./types";'
|
|
3898
3701
|
},
|
|
3899
3702
|
{
|
|
3900
3703
|
"name": "README.md",
|
|
3901
|
-
"content": '# Select Component\n\n## Component Overview\n\nThe Select component provides a dropdown selection interface for choosing one option from a list. It includes search functionality, custom rendering, and keyboard navigation.\n\n**When to use:**\n- Form fields requiring single selection from options\n- Filtering interfaces\n- Settings and preferences selection\n- Any scenario requiring choice from predefined list\n\n**Component Architecture:**\n- Built with @floating-ui for positioning\n- Styled with Tailwind CSS and class-variance-authority (cva)\n- Supports search (type-ahead filtering of options)\n- Keyboard navigation support\n- Accessible with proper ARIA attributes\n\n## Basic Usage\n\n```tsx\nimport { Select } from "@components";\n\nexport function Example() {\n const options = [\n { label: "Option 1", value: "1" },\n { label: "Option 2", value: "2" },\n { label: "Option 3", value: "3" }\n ];\n \n return (\n <Select \n label="Choose Option"\n options={options}\n onChange={(value) => console.log(value)}\n />\n );\n}\n```\n\n**Note:** Update the import path based on your project structure. If you used the Astral UI CLI, the typical import path would be `@components/ui/select` or `@components/select`.\n\n## Component Props\n\n| Prop | Type | Default | Required | Description |\n|------|------|---------|----------|-------------|\n| `options` | `IOption[] \\| GroupBase<IOption>[]` | `[]` | No | Array of selectable options or option groups |\n| `value` | `IOption \\| IOption[] \\| null` | `undefined` | No | Controlled value (single option or array for multi-select) |\n| `onChange` | `(value: any) => void` | - | No | Callback when selection changes |\n| `label` | `React.ReactNode` | `undefined` | No | Label displayed above the select |\n| `size` | `\'md\' \\| \'lg\'` | `\'md\'` | No | Select size variant |\n| `helperText` | `React.ReactNode` | `undefined` | No | Helper text displayed below the select |\n| `error` | `boolean` | `false` | No | Display error styling |\n| `disabled` | `boolean` | `false` | No | Disable the select |\n| `creatable` | `boolean` | `false` | No | Enable creatable select (allows creating new options) |\n| `touched` | `boolean` | `undefined` | No | Field touched state (useful for form validation) |\n| `maxVisibleValues` | `number` | `3` | No | Max number of visible values in multi-select before truncating |\n| `maxVisibleValuesMsg` | `string` | `undefined` | No | Label for truncated values (e.g., "+2 more") |\n| `menuFooter` | `React.ReactNode` | `undefined` | No | Custom footer content in the dropdown menu |\n| `prefixIcon` | `IconType \\| React.ReactNode` | `undefined` | No | Icon displayed at the start of the select control |\n| `suffixIcon` | `IconType \\| React.ReactNode` | `undefined` | No | Icon displayed at the end of the select control |\n| `id` | `string` | `undefined` | No | Unique id for the select input |\n| `placeholder` | `string` | `"Select..."` | No | Placeholder text |\n| `isSearchable` | `boolean` | `true` | No | Enable search functionality |\n| `isClearable` | `boolean` | `false` | No | Show clear button |\n| `isMulti` | `boolean` | `false` | No | Enable multi-select mode |\n| `className` | `string` | `undefined` | No | Additional CSS classes for wrapper |\n\n### Option Object (IOption)\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `label` | `ReactNode` | Yes | Display content for the option (plain text or custom JSX) |\n| `value` | `any` | Yes | Value of the option |\n| `searchValue` | `string` | No | Plain text used for search matching. Set this when `label` is custom JSX, otherwise the option can\'t be found by typing its visible text. Takes precedence over `label`/`value`. |\n| `isDisabled` | `boolean` | No | Whether option is disabled |\n\n## Practical Examples\n\n### Form Field\n\n```tsx\nimport { Select } from "@components";\nimport { useState } from "react";\n\nfunction FormWithSelect() {\n const [country, setCountry] = useState("");\n \n const countries = [\n { label: "United States", value: "us" },\n { label: "Canada", value: "ca" },\n { label: "United Kingdom", value: "uk" },\n { label: "Germany", value: "de" }\n ];\n \n return (\n <form>\n <Select\n label="Country"\n options={countries}\n value={country}\n onChange={setCountry}\n required\n searchable\n />\n </form>\n );\n}\n```\n\n### Filter with Clear\n\n```tsx\nimport { Select } from "@components";\nimport { useState } from "react";\n\nfunction FilterSelect() {\n const [status, setStatus] = useState("");\n \n const statusOptions = [\n { label: "Active", value: "active" },\n { label: "Inactive", value: "inactive" },\n { label: "Pending", value: "pending" }\n ];\n \n return (\n <Select\n label="Filter by Status"\n options={statusOptions}\n value={status}\n onChange={setStatus}\n clearable\n placeholder="All statuses"\n />\n );\n}\n```\n\n### Disabled State\n\n```tsx\n<Select\n label="Disabled Select"\n options={options}\n disabled\n value="option1"\n/>\n```\n\n## Technical Details\n\n### State Management\n\n- Supports both controlled and uncontrolled modes\n- Use `value` + `onChange` for controlled\n- Use `defaultValue` for uncontrolled\n\n## Accessibility\n\n**Implemented:**\n- ARIA attributes for screen readers\n- Keyboard navigation (Arrow keys, Enter, ESC)\n- Focus management\n- Proper labeling\n\n**Best Practices:**\n- Always provide a label\n- Use descriptive option labels\n- Mark required fields\n- Provide error messages\n'
|
|
3704
|
+
"content": '# Select Component\n\n## Component Overview\n\nThe Select component provides a dropdown selection interface for choosing one option from a list. It includes search functionality (hidden with `searchable={false}`), custom rendering, and keyboard navigation.\n\n**When to use:**\n- Form fields requiring single selection from options\n- Filtering interfaces\n- Settings and preferences selection\n- Any scenario requiring choice from predefined list\n\n**Component Architecture:**\n- Built on `react-select`, which handles positioning (`menuPlacement="auto"`) and keyboard navigation\n- Styled with Tailwind CSS and `tailwind-variants` (`tv()`)\n- Search input lives inside the dropdown unless `searchable={false}` hides it; filtering is\n client-side by default, or delegated to the parent via `onFilterChange` (see [Filtering](#filtering))\n- Accessible with proper ARIA attributes\n\n## Basic Usage\n\n```tsx\nimport { Select } from "@components";\n\nexport function Example() {\n const options = [\n { label: "Option 1", value: "1" },\n { label: "Option 2", value: "2" },\n { label: "Option 3", value: "3" }\n ];\n \n return (\n <Select \n label="Choose Option"\n options={options}\n onChange={(value) => console.log(value)}\n />\n );\n}\n```\n\n**Note:** Update the import path based on your project structure. If you used the Astral UI CLI, the typical import path would be `@components/ui/select` or `@components/select`.\n\n## Component Props\n\n| Prop | Type | Default | Required | Description |\n|------|------|---------|----------|-------------|\n| `options` | `IOption[] \\| GroupBase<IOption>[]` | `[]` | No | Array of selectable options or option groups |\n| `value` | `IOption \\| IOption[] \\| null` | `undefined` | No | Controlled value (single option or array for multi-select) |\n| `onChange` | `(value: any) => void` | - | No | Callback when selection changes |\n| `label` | `React.ReactNode` | `undefined` | No | Label displayed above the select |\n| `size` | `\'md\' \\| \'lg\'` | `\'md\'` | No | Select size variant |\n| `helperText` | `React.ReactNode` | `undefined` | No | Helper text displayed below the select |\n| `error` | `boolean` | `false` | No | Display error styling |\n| `disabled` | `boolean` | `false` | No | Disable the select |\n| `creatable` | `boolean` | `false` | No | Enable creatable select (allows creating new options) |\n| `touched` | `boolean` | `undefined` | No | Field touched state (useful for form validation) |\n| `maxVisibleValues` | `number` | `3` | No | Max number of visible values in multi-select before truncating |\n| `maxVisibleValuesMsg` | `string` | `undefined` | No | Label for truncated values (e.g., "+2 more") |\n| `menuFooter` | `React.ReactNode` | `undefined` | No | Custom footer content in the dropdown menu |\n| `searchable` | `boolean` | `true` | No | Renders the search input inside the dropdown. `false` hides it and nothing else \u2014 the reload button, `menuFooter`, "Select All" and the whole keyboard model stay, with focus sitting on the control\'s own input. Suits lists short enough to scan; with no query, `onFilterChange` can never fire (dev warning) |\n| `searchPlaceholder` | `string` | `"Search..."` | No | Placeholder for the search input inside the dropdown. Ignored when `searchable={false}` |\n| `filterValue` | `string` | `undefined` | No | Seeds the dropdown\'s search input and re-syncs it whenever this value changes (not fully controlled \u2014 see [Filtering](#filtering)) |\n| `onFilterChange` | `(query: string) => void` | - | No | Server-side filter handler. When provided, client-side filtering is skipped |\n| `filterDebounceMs` | `number` | `300` | No | Debounce delay (ms) for `onFilterChange`. Set to `0` to fire synchronously |\n| `isLoading` | `boolean` | `false` | No | Replaces the option list with a loader while a fetch is in flight |\n| `loadOptions` | `(query: string, meta: ILoadOptionsMeta) => Promise<IOption[] \\| IOptionPage<IOption>>` | - | No | Async option source. Switches the component into [async mode](#filtering--async-loading): it owns the option list, the request lifecycle and the loading state |\n| `initialOptions` | `readonly IOption[]` | `undefined` | No | Seed rows for a list you already have (SSR payload, route loader, warm cache). Painted on the first frame and kept on screen while the baseline fetch revalidates over them \u2014 see [Seeding with `initialOptions`](#seeding-with-initialoptions). Async mode only |\n| `prefetch` | `"mount" \\| "open" \\| "never"` | `"open"` | No | When to fetch the unfiltered baseline. `"open"` on first menu open; `"mount"` at render, before any interaction; `"never"` only once the user types. Async mode only |\n| `refetchOnClear` | `boolean` | `false` | No | Clearing the search revalidates the cached baseline instead of only restoring it. Costs one request per menu close |\n| `optionsKey` | `string \\| number` | `undefined` | No | Identity of the option set, for dependent selects. A change drops cached results and repopulates. Does **not** clear the selection |\n| `loadErrorMessage` | `React.ReactNode` | `"Couldn\'t load options."` | No | Shown in the menu when `loadOptions` rejects |\n| `showReloadButton` | `boolean` | `false` | No | Shows the menu\'s reload button in async mode, wired to re-run the current query |\n| `onLoadError` | `(error: unknown) => void` | - | No | Notified when a load rejects (the component renders `loadErrorMessage` and swallows it) |\n| `onReload` | `() => void` | - | No | Shows a reload button in the dropdown header; fired on click |\n| `isReloading` | `boolean` | `undefined` | No | Spins and disables the reload button |\n| `reloadTooltip` | `string` | `"Reload"` | No | Tooltip / aria-label for the reload button |\n| `prefixIcon` | `IconType \\| React.ReactNode` | `undefined` | No | Icon displayed at the start of the select control |\n| `suffixIcon` | `IconType \\| React.ReactNode` | `undefined` | No | Icon displayed at the end of the select control |\n| `id` | `string` | `undefined` | No | Unique id for the select input |\n| `placeholder` | `string` | `"Select..."` | No | Placeholder text |\n| `isClearable` | `boolean` | `false` | No | Show clear button |\n| `isMulti` | `boolean` | `false` | No | Enable multi-select mode |\n| `className` | `string` | `undefined` | No | Additional CSS classes for wrapper |\n| `ref` | `Ref<HTMLDivElement>` | `undefined` | No | Forwarded to the wrapper `<div>` \u2014 for programmatic focus/scroll and form libraries that bind by ref |\n\n### Option Object (IOption)\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `label` | `ReactNode` | Yes | Display content for the option (plain text or custom JSX) |\n| `value` | `any` | Yes | Value of the option |\n| `searchValue` | `string` | No | Plain text used for search matching. Set this when `label` is custom JSX, otherwise the option can\'t be found by typing its visible text. Takes precedence over `label`/`value`. |\n| `isDisabled` | `boolean` | No | Whether option is disabled |\n\n## Filtering & async loading\n\nThree modes, picked by which props you pass:\n\n| Mode | Pass | Who filters | Who fetches |\n|---|---|---|---|\n| **Client-side** (default) | nothing | Select, via `matchesQuery` | \u2014 |\n| **You own the list** | `onFilterChange` + `options` | you | you (if any) |\n| **Async** | `loadOptions` | your server | Select |\n\n- **Client-side** \u2014 the search box filters `options` locally. Matching checks an option\'s `searchValue`\n first, then a string `label`, then its `value` \u2014 set `searchValue` on options whose `label` is custom\n JSX so they stay findable by their visible text.\n- **`onFilterChange`** \u2014 Select stops filtering and hands you the (debounced) query; whatever you pass\n as `options` is taken as the answer for it. Use it to fetch from a server, **and equally for a\n local list whose matching rules are your own** (fuzzy, scoped to a field, ranked) \u2014 pair it with\n `filterDebounceMs={0}` and no fetch. Pass `isLoading` while a fetch is in flight.\n- **`loadOptions`** \u2014 for a server-backed list you don\'t want to hold in state: Select owns the option\n list, the request lifecycle and the loading state. `options` is ignored (dev warning) and\n `onFilterChange`, if still passed, becomes notification-only. See [Async mode](#async-mode-loadoptions).\n- **No search at all** \u2014 `searchable={false}` removes the search box, and that is the only change: the\n reload button, `menuFooter`, "Select All" and Arrow/Enter/Escape/Tab all behave as before, because\n react-select\'s control input \u2014 not the in-dropdown box \u2014 is what owns focus and option navigation\n while the menu is open. Space and Home/End join them there: with no field to type into, Space\n activates the focused row and Home/End jump to the ends of the list. With no box there is no query, so `filterValue`, `filterDebounceMs` and\n `onFilterChange` have nothing to act on; passing them alongside it raises a dev warning.\n\n```tsx\nfunction ServerSideSelect() {\n const [options, setOptions] = useState<IOption[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n\n const handleFilterChange = async (query: string) => {\n setIsLoading(true);\n setOptions(await fetchOptions(query));\n setIsLoading(false);\n };\n\n return (\n <Select\n label="User"\n placeholder="Select a user..."\n options={options}\n onFilterChange={handleFilterChange}\n filterDebounceMs={300}\n isLoading={isLoading}\n />\n );\n}\n```\n\nBehaviour worth knowing:\n\n- **The query is cleared when the dropdown closes, and `onFilterChange("")` fires** (only if the\n query was non-empty), so your `options` never stay filtered by a query the user can no longer see.\n Any pending debounced query is dropped first, so the reset always wins.\n- A pending debounce is also cancelled on unmount and whenever `filterValue` changes.\n- **Backspace/Delete holds defer the debounce.** The OS key-repeat gap (~500ms) is longer than the\n default `filterDebounceMs` (300), so debouncing each mid-hold change would fire `onFilterChange`\n with a half-cleared query before the key is released. While either key is held the input still\n updates live, but the debounce only starts on keyup (or blur if focus leaves mid-hold).\n- **`filterValue` is a seed plus an external sync, not a fully controlled value.** The search box\n owns its own text: it updates as the user types and when the component clears it on close. Passing\n a *new* `filterValue` overwrites it; re-passing the same one does not pull it back. Wiring\n `onFilterChange` back into the state you pass as `filterValue` keeps the two in step.\n- **`isLoading` replaces the option list with a loader**, keeping the search input (where shown) and\n `menuFooter` in place. The rows underneath belong to the previous query, so leaving them clickable would let the\n user pick an option the incoming result set no longer contains. It also means an empty-and-loading\n dropdown shows the loader alone rather than "No options". Arrow/Enter are ignored for the same\n reason while the loader is up \u2014 otherwise the keyboard could still reach a row that is off screen.\n- `isLoading` is **not forwarded to react-select**, so its own control indicator and "Loading..."\n message never appear and `loadingMessage` has no effect.\n- **"Select All"** (multi-select) covers the options the active search leaves **visible** \u2014 in server\n mode, every option the server returned for the current query. It is not "all server-side matches".\n The row itself is never query-matched, so it stays put while you type; it is hidden only when\n fewer than two selectable options are on screen, where it would duplicate a single row\'s own\n checkbox or have nothing to act on. Toggling it off removes only those visible options, so a\n selection made under an earlier query survives. **Grouped options are included**: groups are\n flattened, so a list that mixes loose options and groups is covered in render order.\n- With `creatable`, the Create row is no longer auto-suppressed while loading (react-select gates\n that on the `isLoading` it never receives). Gate it with `isValidNewOption` if you need that. In\n server mode the Create row is also matched against the *loaded* options, which lag the query by\n `filterDebounceMs`, so it can flash mid-typing.\n- **The Create row is an action, not an option**, in multi-select as much as in single-select: it\n stands for a value that does not exist yet, so it carries no checkbox and nothing in the draft\n answers for it. Picking it reports the created option straight away \u2014 `onChange( [...selection,\n created], { action: "create-option" } )`, with the option labelled by what was typed rather than by\n the prompt \u2014 instead of waiting for the menu to close, and clears the search text that produced it.\n Ticks made since the menu opened commit along with it. The option you are handed is a plain\n `{ label, value }`: react-select\'s `__isNew__` marker is stripped, because here that flag means "this\n row is the Create affordance" and would turn the option into one. `action: "create-option"` is the\n signal that it is new.\n- **What a create produces then joins the list**, in both modes. react-select leaves the new value in\n the selection alone and expects you to put it back into `options` yourself (its docs\' Advanced\n example does exactly that from `onCreateOption`); Select owns the option list already, so it keeps\n created options for you. Each one becomes an ordinary row: it has a checkbox in multi-select, can be\n unticked and picked again, counts towards "Select All", is matched by the search, and stops the\n Create row being offered a second time for the same text. They last as long as the component \u2014\n clearing the selection does not take the row away. Supplying the same value in `options` later (say\n after persisting it) takes ownership of it, leaving one row rather than two. Passing your own\n `onCreateOption` opts out of all of this: react-select hands the text to you and nothing is created\n or recorded here.\n- Never pass `noOptionsMessage={() => null}` \u2014 react-select bails out of rendering the menu entirely\n and the dropdown, search input included, disappears. That is unrelated to `searchable`, which hides\n the search box and leaves the menu in place.\n\n## Async mode (`loadOptions`)\n\nServer-side filtering above is a two-part contract: the component debounces the query, you own the\nresults. But **debouncing limits how often a request starts, not how many are in flight** \u2014 type\n`sal`, pause past the debounce, type `es`, and if the first response arrives last it overwrites the\nsecond. Every server-filtered call site therefore has to hand-write the same monotonic-ticket guard,\nand the one that forgets ships a bug that is invisible on a fast connection.\n\n`loadOptions` moves that, the results state and the `isLoading` bookkeeping into the component:\n\n```tsx\n<Select\n label="Dataset"\n isMulti\n loadOptions={async (query, { signal }) => {\n const res = await fetchDatasets({ filterExpression: `DatasetName:*${query}*`, signal });\n return res.datasets\n .filter(isWriteAccessible) // domain rules stay yours\n .map((d) => ({ value: d.DatasetId, label: `${d.Domain} : ${d.DisplayName}`, name: d.DatasetName }));\n }}\n/>\n```\n\n`loadOptions` **fetches and maps**. Response envelopes, pagination shapes and domain filtering are all\nthe consumer\'s business \u2014 the component never sees the raw payload. A fresh inline arrow costs nothing:\nthe loader is read through a ref, so it never re-triggers a fetch or invalidates a memo.\n\n`meta` carries `{ signal, cursor, page, reason }`. Return either a bare `IOption[]` or a page envelope\n`{ options, cursor?, hasMore?, total? }`.\n\nBehaviour worth knowing:\n\n1. **Ordering is guaranteed.** A response is accepted only if it is still the newest request for its\n slot. Honouring `meta.signal` is **optional** \u2014 it only saves you paying for a response nobody\n wants; correctness comes from the internal guard either way.\n2. **Clearing the search restores the cached baseline, with no request.** The empty-query result and\n the current-query result live in separate buckets, so a menu close (which fires\n `onFilterChange("")`) restores rather than destroys. Pass `refetchOnClear` to *also* revalidate;\n the stale rows stay on screen while that request runs, so the list never blanks.\n3. **`filterValue` does not trigger fetches in async mode.** The shared filter hook deliberately\n cancels the debounce *without* notifying when `filterValue` changes, so a programmatic query change\n updates the search box only. Changing that would alter `MultiSelectTransfer`\'s behaviour too. If you\n need to force a reload, use `optionsKey`.\n4. **`optionsKey` does not clear the committed selection.** Whether a stale child value is invalid is a\n domain rule, and clearing a controlled `value` from inside the component means firing an `onChange`\n the consumer never asked for \u2014 unblockable in Formik or React Hook Form. **Watch for this:** options\n pass through opaquely, so a stale selection renders its own label perfectly and fails silently at\n submit. Clear it yourself in the parent when your domain says it is invalid.\n5. **Page one only.** `cursor` / `hasMore` / `total` in the resolved page are ignored, and a page\n reporting `hasMore: true` raises a one-time dev warning \u2014 there is no infinite-scroll surface in\n react-select\'s menu. Use `MultiSelectTransfer` for a paged source.\n6. **Option groups are unsupported in async mode.** The loader returns `readonly IOption[]`; groups are\n a sync-mode-only shape.\n7. **"Select All"** (multi-select) still covers only what is currently loaded and visible \u2014 every\n option the server returned for the current query, not "all server-side matches".\n8. A rejection replaces the rows with `loadErrorMessage` in `role="alert"`, blocks Arrow/Enter for the\n same reason the loader does, and auto-shows the reload button as the retry affordance. `onLoadError`\n receives the raw cause for logging.\n\n### Seeding with `initialOptions`\n\n`initialOptions` is for the case where **you already have the rows** \u2014 an SSR payload, a route loader, a\nwarm query cache. They are painted on the first frame, so there is no loader to sit through, and they stay\non screen while the baseline fetch revalidates over them. This is the one thing `prefetch` cannot do:\n`prefetch="mount"` still costs a round trip before anything appears.\n\n```tsx\n<Select\n label="Dataset"\n initialOptions={ssrDatasets} // painted immediately\n loadOptions={fetchDatasets} // still runs, and replaces them when it lands\n/>\n```\n\nIt does **not** suppress the baseline fetch. If the seed *is* the whole list until the user types \u2014 a heavy\nsource you do not want to hit on open \u2014 pair it with `prefetch="never"`:\n\n```tsx\n<Select initialOptions={recentlyUsed} prefetch="never" loadOptions={searchEverything} />\n```\n\nWithout `initialOptions`, that combination opens to an empty menu.\n\nA *search* replaces seed rows, because they are not results for a query; clearing the search brings them\nback until a fetched baseline lands. And seed rows only mean something to the async source \u2014 passing\n`initialOptions` without `loadOptions` is ignored with a dev warning, because those rows belong in\n`options`.\n\n`prefetch` is async-only for the same reason: it schedules the baseline fetch and nothing else, so\nwithout `loadOptions` there is no fetch to schedule. Passing it there is ignored with a dev warning.\n\n## Practical Examples\n\n### Form Field\n\n```tsx\nimport { Select } from "@components";\nimport { useState } from "react";\n\nfunction FormWithSelect() {\n const [country, setCountry] = useState("");\n \n const countries = [\n { label: "United States", value: "us" },\n { label: "Canada", value: "ca" },\n { label: "United Kingdom", value: "uk" },\n { label: "Germany", value: "de" }\n ];\n \n return (\n <form>\n <Select\n label="Country"\n options={countries}\n value={country}\n onChange={setCountry}\n />\n </form>\n );\n}\n```\n\n### Filter with Clear\n\n```tsx\nimport { Select } from "@components";\nimport { useState } from "react";\n\nfunction FilterSelect() {\n const [status, setStatus] = useState("");\n \n const statusOptions = [\n { label: "Active", value: "active" },\n { label: "Inactive", value: "inactive" },\n { label: "Pending", value: "pending" }\n ];\n \n return (\n <Select\n label="Filter by Status"\n options={statusOptions}\n value={status}\n onChange={setStatus}\n clearable\n placeholder="All statuses"\n />\n );\n}\n```\n\n### Disabled State\n\n```tsx\n<Select\n label="Disabled Select"\n options={options}\n disabled\n value="option1"\n/>\n```\n\n## Technical Details\n\n### State Management\n\n- Supports both controlled and uncontrolled modes\n- Use `value` + `onChange` for controlled\n- Use `defaultValue` for uncontrolled\n- The search query is owned internally and seeded from `filterValue`; a *change* to `filterValue`\n overwrites it and cancels any in-flight debounced `onFilterChange`\n\n### Filtering\n\n- Without `onFilterChange`, options are filtered locally via the shared `matchesQuery` helper, which\n is also used by `TransferList` and `MultiSelectTransfer`.\n- With `onFilterChange`, filtering is delegated to the parent and the query is debounced\n (`filterDebounceMs`). A pending debounce is cancelled on unmount, on an external `filterValue`\n reset, and when the dropdown closes \u2014 where `onFilterChange("")` fires instead so the parent\'s\n result set matches the now-empty search box. While Backspace/Delete is held the debounce is\n deferred until keyup (or blur), so a long-press cannot fire mid-hold. This lives in the shared\n `useFilterQuery` hook, which `MultiSelectTransfer` also uses, so its identically-named filter\n props behave identically.\n- `isLoading` renders the loader in place of react-select\'s menu list, which also keeps it out of the\n list\'s `role="listbox"` subtree (that role only accepts option children). Suppressing the "No\n options" notice this way is deliberate: returning `null` from react-select\'s `noOptionsMessage`\n makes it skip rendering the menu altogether, taking the search input with it.\n- `MultiSelectTransfer` behaves the same for a search fetch, but keeps appending the loader below the\n rows for a load-more it triggered itself, so pagination doesn\'t lose the scroll position.\n- `searchable={false}` removes the only source of a query, so the whole filtering axis goes quiet:\n client-side matching runs against an empty query (every option visible), the debounce never starts,\n and the close-time `onFilterChange("")` has nothing to reset. Focus and option navigation are\n unaffected \u2014 they belong to react-select\'s control input, which the in-dropdown box only ever\n forwards keys to.\n\n## Accessibility\n\n**Implemented:**\n- ARIA attributes for screen readers\n- Keyboard navigation (Arrow keys, Enter, ESC)\n- Focus management\n- Proper labeling\n- With `searchable={false}` the dropdown contains no text field of its own. Focus stays on the\n control\'s input, where react-select already keeps the listbox link and the active-option cursor, so\n Arrow/Enter/Escape/Tab are unchanged, and Space/Home/End become available because no text field is\n claiming them\n\n**Best Practices:**\n- Always provide a label\n- Use descriptive option labels\n- Mark required fields\n- Provide error messages\n- Keep the search on for anything longer than a screenful \u2014 without it the arrow keys are the only way\n to reach the bottom of the list\n'
|
|
3902
3705
|
}
|
|
3903
3706
|
],
|
|
3904
3707
|
"directories": []
|
|
@@ -4134,17 +3937,26 @@ export const selectVariants = tv({
|
|
|
4134
3937
|
"tailwind-merge"
|
|
4135
3938
|
],
|
|
4136
3939
|
"internalDependencies": [
|
|
3940
|
+
"button",
|
|
3941
|
+
"adpIcon",
|
|
4137
3942
|
"scrollbar",
|
|
4138
3943
|
"loader",
|
|
4139
3944
|
"checkbox",
|
|
4140
|
-
"
|
|
4141
|
-
"
|
|
4142
|
-
"emptyState"
|
|
3945
|
+
"emptyState",
|
|
3946
|
+
"card"
|
|
4143
3947
|
],
|
|
4144
3948
|
"files": [
|
|
3949
|
+
{
|
|
3950
|
+
"name": "useTransferListSource.ts",
|
|
3951
|
+
"content": 'import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";\n\nimport {\n useAsyncOptions,\n useAvailableProjection,\n useFilterQuery,\n useIgnoredPropWarning,\n useOnValueChange,\n usePrefetchBaseline\n} from "@hooks";\nimport { resolveLoadErrors } from "@utils";\nimport type {\n ITransferListItem,\n TTransferListLoadOptions,\n TTransferListPrefetch,\n TTransferListValue\n} from "./types";\n\n// One shared identity for the empty case: TransferList memoises several passes over this array, and a\n// fresh `[]` per render would invalidate every one of them.\nconst EMPTY_ITEMS: ITransferListItem[] = [];\n\n/**\n * Items previously seen in `selectedItems`, tagged with the `optionsKey` they were seen under. Held\n * as both a map (the identity check below is a lookup, not a scan) and the list the projection wants,\n * built once here rather than materialised on every read.\n */\ninterface ISeenSelected {\n key: string | number | undefined;\n items: Map<TTransferListValue, ITransferListItem>;\n list: ITransferListItem[];\n}\n\nconst EMPTY_SEEN: Map<TTransferListValue, ITransferListItem> = new Map();\n\ninterface IUseTransferListSourceArgs {\n availableItems?: ITransferListItem[];\n /** Controlled by the consumer in every mode \u2014 the selection is the whole point of the component. */\n selectedItems: ITransferListItem[];\n\n loadAvailableOptions?: TTransferListLoadOptions;\n initialAvailableOptions?: readonly ITransferListItem[];\n prefetch?: TTransferListPrefetch;\n refetchOnClear?: boolean;\n optionsKey?: string | number;\n availableFilterDebounceMs?: number;\n loadErrorMessage?: ReactNode;\n loadMoreErrorMessage?: ReactNode;\n onLoadError?: ( error: unknown ) => void;\n\n // Consumer-driven equivalents, used verbatim when there is no loader.\n hasMoreAvailable?: boolean;\n onLoadMoreAvailable?: () => void;\n isLoadingMoreAvailable?: boolean;\n isLoadingAvailable?: boolean;\n availableLoadError?: ReactNode;\n availableLoadMoreError?: ReactNode;\n onRetryLoadMoreAvailable?: () => void;\n availableTotalCount?: number;\n availableSearchTerm?: string;\n onAvailableSearchChange?: ( query: string ) => void;\n}\n\ninterface ITransferListSource {\n /** The available pool: derived from the loaded pages in async mode, the prop otherwise. */\n availableItems: ITransferListItem[];\n hasMoreAvailable: boolean;\n onLoadMoreAvailable?: () => void;\n isLoadingMoreAvailable: boolean;\n isLoadingAvailable: boolean;\n availableLoadError?: ReactNode;\n availableLoadMoreError?: ReactNode;\n onRetryLoadMoreAvailable?: () => void;\n availableTotalCount?: number;\n /** In async mode these make the panel\'s search controlled and server-driven. */\n availableSearchTerm?: string;\n onAvailableSearchChange?: ( query: string ) => void;\n}\n\n/**\n * `TransferList`\'s available-panel source. In async mode it owns a `useAsyncOptions` instance, a\n * debounced `useFilterQuery` for the panel\'s search (which is a raw `onChange` otherwise), the\n * mount/`optionsKey` prefetch, and the pool \u2192 available projection. Without a loader every value is\n * the corresponding prop, unchanged.\n */\nexport function useTransferListSource({\n availableItems,\n selectedItems,\n loadAvailableOptions,\n initialAvailableOptions,\n prefetch,\n refetchOnClear = false,\n optionsKey,\n availableFilterDebounceMs = 300,\n loadErrorMessage,\n loadMoreErrorMessage,\n onLoadError,\n hasMoreAvailable = false,\n onLoadMoreAvailable,\n isLoadingMoreAvailable = false,\n isLoadingAvailable = false,\n availableLoadError,\n availableLoadMoreError,\n onRetryLoadMoreAvailable,\n availableTotalCount,\n availableSearchTerm,\n onAvailableSearchChange\n}: IUseTransferListSourceArgs ): ITransferListSource {\n const isAsync = typeof loadAvailableOptions === "function";\n\n const asyncOptions = useAsyncOptions<ITransferListItem>({\n loadOptions: loadAvailableOptions,\n initialOptions: initialAvailableOptions,\n prefetchDefaults: prefetch !== "never",\n refetchOnClear,\n optionsKey,\n onLoadError,\n getOptionKey: ( item ) => item.value\n });\n\n const { filterQuery, setFilterQuery, resetFilter } = useFilterQuery({\n onFilterChange: asyncOptions.onFilterChange,\n filterDebounceMs: availableFilterDebounceMs\n });\n\n // Stable identity, because TransferList feeds this handler to the memo that guards the available\n // panel\'s per-render filter passes \u2014 and the drag-over path that memo exists for re-renders often\n // enough that a fresh arrow per render would defeat it. The consumer\'s own handler is read through\n // a ref, so an inline prop costs nothing here either.\n const onAvailableSearchChangeRef = useRef( onAvailableSearchChange );\n onAvailableSearchChangeRef.current = onAvailableSearchChange;\n const handleAsyncAvailableSearch = useCallback(( query: string ) => {\n onAvailableSearchChangeRef.current?.( query );\n setFilterQuery( query );\n }, [setFilterQuery]);\n\n // The panel has no open/close \u2014 its list is always visible \u2014 so mount is the only prefetch trigger\n // it has, which is why no `isOpen` is passed.\n usePrefetchBaseline({ prefetch: prefetch ?? "mount", optionsKey, ensureDefaults: asyncOptions.ensureDefaults });\n\n // Route an optionsKey CHANGE into the clear path. Skipped on mount.\n useOnValueChange( optionsKey, resetFilter );\n\n useIgnoredPropWarning(\n isAsync && availableItems !== undefined,\n "TransferList: `availableItems` is ignored when `loadAvailableOptions` is set \u2014 " +\n "use `initialAvailableOptions` to seed the list."\n );\n // The mirror of the above: seed rows only mean anything to the async source, so without a loader they\n // vanish silently \u2014 the same mistake, and just as quiet.\n useIgnoredPropWarning(\n !isAsync && initialAvailableOptions !== undefined,\n "TransferList: `initialAvailableOptions` is ignored without `loadAvailableOptions` \u2014 " +\n "pass those rows as `availableItems` instead."\n );\n // Same class of mistake: `prefetch` only ever schedules the baseline fetch, so with the rows already\n // in `availableItems` there is nothing for it to trigger and it silently does nothing.\n useIgnoredPropWarning(\n !isAsync && prefetch !== undefined,\n "TransferList: `prefetch` is ignored without `loadAvailableOptions` \u2014 " +\n "`availableItems` are already on screen, so there is nothing to fetch."\n );\n\n // Items the loaded pool may not contain: everything that has ever appeared in `selectedItems`.\n // Without this, moving a selected-but-never-fetched item back to Available would make it vanish \u2014\n // the pool and `selectedItems` are the only two ways an item can be in the component. State, not a\n // ref accumulated from the projection below: a `useMemo` is a calculation React may discard and\n // re-run. The key travels WITH the map, so a stale key is a pure comparison at read time rather than\n // an effect-based clear that would paint one frame of the previous set.\n const [ seenSelected, setSeenSelected ] = useState<ISeenSelected>(\n () => ({ key: optionsKey, items: EMPTY_SEEN, list: EMPTY_ITEMS })\n );\n\n useEffect(() => {\n if ( !isAsync ) {\n return;\n }\n setSeenSelected(( previous ) => {\n const carried = previous.key === optionsKey ? previous.items : null;\n // Nothing new to remember: `previous` keeps the projection\'s memo intact, so a re-render that\n // did not change the selection costs one pass and no extra render.\n if ( carried && selectedItems.every(( item ) => carried.get( item.value ) === item )) {\n return previous;\n }\n const items = new Map( carried ?? []);\n selectedItems.forEach(( item ) => items.set( item.value, item ));\n return { key: optionsKey, items, list: Array.from( items.values()) };\n });\n }, [ isAsync, selectedItems, optionsKey ]);\n\n // An `optionsKey` change drops the pool, so the items remembered for the previous option set go\n // with it \u2014 otherwise the new set\'s Available panel is polluted by the old one\'s rows.\n const remembered = seenSelected.key === optionsKey ? seenSelected.list : EMPTY_ITEMS;\n // Sync consumers never read this, hence the `isAsync` gate.\n const derivedAvailable = useAvailableProjection(\n isAsync,\n asyncOptions.options,\n remembered,\n selectedItems,\n filterQuery\n );\n\n if ( !isAsync ) {\n return {\n // Passed through by identity: TransferList memoises several O(n) passes over this array, and a\n // per-render copy would defeat every one of them.\n availableItems: availableItems ?? EMPTY_ITEMS,\n hasMoreAvailable,\n onLoadMoreAvailable,\n isLoadingMoreAvailable,\n isLoadingAvailable,\n availableLoadError,\n availableLoadMoreError,\n onRetryLoadMoreAvailable,\n availableTotalCount,\n availableSearchTerm,\n onAvailableSearchChange\n };\n }\n\n const { loadError, loadMoreError } = resolveLoadErrors({\n errorKind: asyncOptions.errorKind,\n loadErrorMessage,\n loadMoreErrorMessage\n });\n return {\n availableItems: derivedAvailable,\n hasMoreAvailable: asyncOptions.hasMore,\n onLoadMoreAvailable: asyncOptions.loadMore,\n isLoadingMoreAvailable: asyncOptions.isLoadingMore,\n isLoadingAvailable: isLoadingAvailable || asyncOptions.isReplacing,\n availableLoadError: loadError,\n availableLoadMoreError: loadMoreError,\n onRetryLoadMoreAvailable: asyncOptions.retryMore,\n availableTotalCount: availableTotalCount ?? asyncOptions.total,\n // Defined, so transferList.tsx\'s existing controlled-search path takes over and the local matcher\n // stands down \u2014 over a paged pool it would only ever search the pages that happen to be loaded.\n availableSearchTerm: filterQuery,\n onAvailableSearchChange: handleAsyncAvailableSearch\n };\n}\n'
|
|
3952
|
+
},
|
|
3953
|
+
{
|
|
3954
|
+
"name": "useTransferListPanelKeys.ts",
|
|
3955
|
+
"content": 'import type { KeyboardEvent } from "react";\n\nimport { keyboardKeys } from "@constants";\nimport type { ITransferListItem, TTransferListValue } from "./types";\n\ninterface IUseTransferListPanelKeysArgs {\n items: ITransferListItem[];\n activeIndex: number;\n setActiveIndex: ( index: number ) => void;\n moveActive: ( direction: 1 | -1 ) => void;\n firstEnabledIndex: ( from: number, direction: 1 | -1 ) => number;\n reorderable: boolean;\n onToggle: ( value: TTransferListValue ) => void;\n onRemove?: ( value: TTransferListValue ) => void;\n onMoveUp?: ( index: number ) => void;\n onMoveDown?: ( index: number ) => void;\n setIsFocused: ( focused: boolean ) => void;\n /**\n * The rows the arrow keys are addressing are about to be replaced (a search fetch is in flight, or\n * an error has taken the list\'s place), so every key is swallowed. The single place this gate is\n * expressed.\n */\n isBlocked: boolean;\n}\n\n/**\n * The listbox key handler for one transfer-list panel: arrow/Home/End navigation over\n * `aria-activedescendant`, Enter/Space to toggle, Delete/Backspace to remove, and Alt+Arrow to\n * reorder.\n */\nexport function useTransferListPanelKeys({\n items,\n activeIndex,\n setActiveIndex,\n moveActive,\n firstEnabledIndex,\n reorderable,\n onToggle,\n onRemove,\n onMoveUp,\n onMoveDown,\n setIsFocused,\n isBlocked\n}: IUseTransferListPanelKeysArgs ): ( e: KeyboardEvent<HTMLDivElement> ) => void {\n return ( e: KeyboardEvent<HTMLDivElement> ) => {\n if ( isBlocked ) {\n return;\n }\n // Any key interaction is keyboard mode, so light the active row - covers the case where focus\n // arrived by pointer (which is not :focus-visible, so onFocus left it dark) and the user then\n // starts navigating with the arrows. onMouseDown turns it back off when they switch to pointer.\n setIsFocused( true );\n const activeItem = items[activeIndex];\n\n // Alt+Arrow reorders the active row (reorderable selected panel), keeping it active as it\n // moves. Checked before the plain Arrow navigation below.\n if ( e.altKey && ( e.key === keyboardKeys.arrowUp || e.key === keyboardKeys.arrowDown )) {\n if ( !reorderable || !activeItem ) {\n return;\n }\n e.preventDefault();\n if ( e.key === keyboardKeys.arrowUp && activeIndex > 0 ) {\n onMoveUp?.( activeIndex );\n setActiveIndex( activeIndex - 1 );\n } else if ( e.key === keyboardKeys.arrowDown && activeIndex < items.length - 1 ) {\n onMoveDown?.( activeIndex );\n setActiveIndex( activeIndex + 1 );\n }\n return;\n }\n\n switch ( e.key ) {\n case keyboardKeys.arrowDown:\n e.preventDefault();\n moveActive( 1 );\n break;\n case keyboardKeys.arrowUp:\n e.preventDefault();\n moveActive( -1 );\n break;\n case keyboardKeys.home:\n e.preventDefault();\n setActiveIndex( firstEnabledIndex( 0, 1 ));\n break;\n case keyboardKeys.end:\n e.preventDefault();\n setActiveIndex( firstEnabledIndex( items.length - 1, -1 ));\n break;\n case keyboardKeys.enter:\n case keyboardKeys.space:\n if ( activeItem && !activeItem.isDisabled ) {\n e.preventDefault();\n onToggle( activeItem.value );\n }\n break;\n // Delete / Backspace removes the active row back to Available (selected panel only). On a\n // Mac keyboard the "delete" key reports as Backspace, so both are accepted.\n case keyboardKeys.delete:\n case keyboardKeys.backspace:\n if ( onRemove && activeItem && !activeItem.isDisabled ) {\n e.preventDefault();\n onRemove( activeItem.value );\n }\n break;\n default:\n break;\n }\n };\n}\n'
|
|
3956
|
+
},
|
|
4145
3957
|
{
|
|
4146
3958
|
"name": "useTransferList.ts",
|
|
4147
|
-
"content": 'import { useCallback, useState } from "react";\n\nimport type { ITransferListItem, TTransferListValue, TTransferPanel } from "./types";\n\ninterface IUseTransferListArgs {\n availableItems: ITransferListItem[];\n selectedItems: ITransferListItem[];\n onChange: ( availableItems: ITransferListItem[], selectedItems: ITransferListItem[]) => void;\n}\n\ninterface IDragState {\n value: TTransferListValue;\n panel: TTransferPanel;\n}\n\n/**\n * Holds the transient UI state for a TransferList: per-panel checkbox sets and\n * the active drag descriptor. The item arrays themselves stay controlled by the\n * parent \u2014 every mutation here is forwarded through `onChange`.\n */\nexport function useTransferList({ availableItems, selectedItems, onChange }: IUseTransferListArgs ) {\n const [ availableChecked, setAvailableChecked ] = useState<Set<TTransferListValue>>( new Set());\n const [ selectedChecked, setSelectedChecked ] = useState<Set<TTransferListValue>>( new Set());\n const [ drag, setDrag ] = useState<IDragState | null>( null );\n\n const clearChecks = useCallback(() => {\n setAvailableChecked( new Set());\n setSelectedChecked( new Set());\n }, []);\n\n const isChecked = useCallback(\n ( panel: TTransferPanel, value: TTransferListValue ) =>\n ( panel === "available" ? availableChecked : selectedChecked ).has( value ),\n [ availableChecked, selectedChecked ]\n );\n\n const toggleCheck = useCallback(( panel: TTransferPanel, value: TTransferListValue ) => {\n const setter = panel === "available" ? setAvailableChecked : setSelectedChecked;\n setter(( prev ) => {\n const next = new Set( prev );\n if ( next.has( value )) {\n next.delete( value );\n } else {\n next.add( value );\n }\n return next;\n });\n }, []);\n\n //
|
|
3959
|
+
"content": 'import { useCallback, useState } from "react";\n\nimport type { ITransferListItem, TTransferListValue, TTransferPanel } from "./types";\n\ninterface IUseTransferListArgs {\n availableItems: ITransferListItem[];\n selectedItems: ITransferListItem[];\n onChange: ( availableItems: ITransferListItem[], selectedItems: ITransferListItem[]) => void;\n}\n\ninterface IDragState {\n value: TTransferListValue;\n panel: TTransferPanel;\n}\n\n/**\n * Holds the transient UI state for a TransferList: per-panel checkbox sets and\n * the active drag descriptor. The item arrays themselves stay controlled by the\n * parent \u2014 every mutation here is forwarded through `onChange`.\n */\nexport function useTransferList({ availableItems, selectedItems, onChange }: IUseTransferListArgs ) {\n const [ availableChecked, setAvailableChecked ] = useState<Set<TTransferListValue>>( new Set());\n const [ selectedChecked, setSelectedChecked ] = useState<Set<TTransferListValue>>( new Set());\n const [ drag, setDrag ] = useState<IDragState | null>( null );\n\n const clearChecks = useCallback(() => {\n setAvailableChecked( new Set());\n setSelectedChecked( new Set());\n }, []);\n\n const isChecked = useCallback(\n ( panel: TTransferPanel, value: TTransferListValue ) =>\n ( panel === "available" ? availableChecked : selectedChecked ).has( value ),\n [ availableChecked, selectedChecked ]\n );\n\n const toggleCheck = useCallback(( panel: TTransferPanel, value: TTransferListValue ) => {\n const setter = panel === "available" ? setAvailableChecked : setSelectedChecked;\n setter(( prev ) => {\n const next = new Set( prev );\n if ( next.has( value )) {\n next.delete( value );\n } else {\n next.add( value );\n }\n return next;\n });\n }, []);\n\n // Check or uncheck the given values in a panel, leaving every other value in the set alone.\n // Powers the per-panel "Select all" checkbox, which addresses only the search-visible rows \u2014 a\n // replace would silently drop checks the user made under a previous query.\n const setPanelChecked = useCallback(\n ( panel: TTransferPanel, values: TTransferListValue[], checked: boolean ) => {\n const setter = panel === "available" ? setAvailableChecked : setSelectedChecked;\n setter(( prev ) => {\n const next = new Set( prev );\n values.forEach(( value ) => ( checked ? next.add( value ) : next.delete( value )));\n return next;\n });\n },\n []\n );\n\n // Forward the next arrays to the parent in the correct (available, selected)\n // order given the panel a move originated from, then reset the checkboxes.\n const commit = useCallback(\n ( from: TTransferPanel, nextSource: ITransferListItem[], nextTarget: ITransferListItem[]) => {\n if ( from === "available" ) {\n onChange( nextSource, nextTarget );\n } else {\n onChange( nextTarget, nextSource );\n }\n clearChecks();\n },\n [ onChange, clearChecks ]\n );\n\n // Move the given items from one panel to the other (appended). Disabled items\n // are skipped. Used by the \u203A/\xBB (from available) and \u2039/\xAB (from selected) controls.\n const moveMany = useCallback(\n ( values: TTransferListValue[], from: TTransferPanel ) => {\n const [ source, target ] = from === "available" ? [ availableItems, selectedItems ] : [ selectedItems, availableItems ];\n const wanted = new Set( values );\n const moving = source.filter(( item ) => wanted.has( item.value ) && !item.isDisabled );\n if ( moving.length === 0 ) {\n return;\n }\n const movingValues = new Set( moving.map(( item ) => item.value ));\n commit( from, source.filter(( item ) => !movingValues.has( item.value )), [ ...target, ...moving ]);\n },\n [ availableItems, selectedItems, commit ]\n );\n\n const moveRight = useCallback(( values: TTransferListValue[]) => moveMany( values, "available" ), [moveMany]);\n const moveLeft = useCallback(( values: TTransferListValue[]) => moveMany( values, "selected" ), [moveMany]);\n\n // Cross-panel drag drop: transfer a single item to the other panel at an\n // optional insert index (appends when omitted).\n const transferOne = useCallback(\n ( value: TTransferListValue, from: TTransferPanel, insertIndex?: number ) => {\n const [ source, target ] = from === "available" ? [ availableItems, selectedItems ] : [ selectedItems, availableItems ];\n const item = source.find(( entry ) => entry.value === value );\n if ( !item || item.isDisabled ) {\n return;\n }\n const nextTarget = [...target];\n nextTarget.splice( insertIndex ?? nextTarget.length, 0, item );\n commit( from, source.filter(( entry ) => entry.value !== value ), nextTarget );\n },\n [ availableItems, selectedItems, commit ]\n );\n\n const transferToSelected = useCallback(\n ( value: TTransferListValue, insertIndex?: number ) => transferOne( value, "available", insertIndex ),\n [transferOne]\n );\n const transferToAvailable = useCallback(\n ( value: TTransferListValue ) => transferOne( value, "selected" ), [transferOne]);\n\n // Reorder within the selected panel (drag-reorder or up/down arrows).\n const reorderSelected = useCallback(\n ( from: number, to: number ) => {\n if ( from === to || from < 0 || to < 0 || from >= selectedItems.length || to >= selectedItems.length ) {\n return;\n }\n const next = [...selectedItems];\n const [moved] = next.splice( from, 1 );\n next.splice( to, 0, moved );\n onChange( availableItems, next );\n clearChecks();\n },\n [ availableItems, selectedItems, onChange, clearChecks ]\n );\n\n return {\n isChecked,\n toggleCheck,\n setPanelChecked,\n moveRight,\n moveLeft,\n transferToSelected,\n transferToAvailable,\n reorderSelected,\n drag,\n setDrag\n };\n}\n'
|
|
4148
3960
|
},
|
|
4149
3961
|
{
|
|
4150
3962
|
"name": "useDragAutoScroll.ts",
|
|
@@ -4152,19 +3964,23 @@ export const selectVariants = tv({
|
|
|
4152
3964
|
},
|
|
4153
3965
|
{
|
|
4154
3966
|
"name": "types.ts",
|
|
4155
|
-
"content": 'import type { ReactNode } from "react";\n\n/**\n * Which of the two panels an item or action belongs to.\n */\nexport type TTransferPanel = "available" | "selected";\n\n/**\n * Unique identifier for a transferable item. Kept intentionally permissive so\n * consumers can key items off primitive ids (e.g. numeric database ids) without\n * having to stringify them first. Must be unique across both panels.\n */\nexport type TTransferListValue = string | number;\n\n/**\n * A single transferable item.
|
|
3967
|
+
"content": 'import type { ReactNode } from "react";\n\nimport type { TLoadOptions, TPrefetch } from "@hooks";\n\n/**\n * `TPrefetch` minus `"open"`: the panel\'s list is always visible, so it has no open event to hang a\n * fetch on. Narrowed rather than redefined, so the family shares one vocabulary.\n */\nexport type TTransferListPrefetch = Exclude<TPrefetch, "open">;\n\n/**\n * Which of the two panels an item or action belongs to.\n */\nexport type TTransferPanel = "available" | "selected";\n\n/**\n * Unique identifier for a transferable item. Kept intentionally permissive so\n * consumers can key items off primitive ids (e.g. numeric database ids) without\n * having to stringify them first. Must be unique across both panels.\n */\nexport type TTransferListValue = string | number;\n\n/**\n * A single transferable item. The shape composing components alias rather than redeclare, so an\n * option and a transfer-list item stay structurally identical.\n */\nexport interface ITransferListItem {\n value: TTransferListValue;\n label: ReactNode;\n /** Plain-text used for searching when `label` is a ReactNode. Takes precedence over label/value. */\n searchValue?: string;\n isDisabled?: boolean;\n}\n\n/** Async source for the available panel. Paged: `cursor`, `hasMore` and `total` are all honoured. */\nexport type TTransferListLoadOptions = TLoadOptions<ITransferListItem>;\n\nexport interface ITransferListProps {\n /**\n * Items in the available (left) panel. Controlled. Optional and **ignored** (with a dev warning)\n * when `loadAvailableOptions` is set \u2014 in that mode the component owns the available pool.\n */\n availableItems?: ITransferListItem[];\n /** Items in the selected (right) panel. Order is preserved when reorderable. Controlled. */\n selectedItems: ITransferListItem[];\n /** Fired on every move/reorder with the next available + selected arrays. */\n onChange: ( availableItems: ITransferListItem[], selectedItems: ITransferListItem[]) => void;\n\n /** Heading for the available panel. @default "Available Items" */\n availablePanelTitle?: ReactNode;\n /** Heading for the selected panel. @default "Selected Items" */\n selectedPanelTitle?: ReactNode;\n\n /** Show the per-panel search inputs. @default true */\n searchable?: boolean;\n /** Controlled search term for the available panel. Overridden when `loadAvailableOptions` is set. */\n availableSearchTerm?: string;\n /**\n * Controlled-search change handler for the available panel. Fires on every keystroke (no built-in\n * debounce).\n *\n * Without `loadAvailableOptions`: switches off the panel\'s local filtering \u2014 `availableItems` is\n * treated as already filtered for the query \u2014 so the debounce, the fetch, the loading state, the\n * response ordering, and subtracting `selectedItems` from the result are the consumer\'s\n * responsibility.\n *\n * With `loadAvailableOptions`: notification-only, for analytics.\n */\n onAvailableSearchChange?: ( query: string ) => void;\n /** Controlled search term for the selected panel. */\n selectedSearchTerm?: string;\n /** Controlled-search change handler for the selected panel. */\n onSelectedSearchChange?: ( query: string ) => void;\n /** Placeholder for both search inputs. @default "Search here" */\n searchPlaceholder?: string;\n\n /** Custom content rendered under the available panel search input. */\n availablePanelHeaderSlot?: ReactNode;\n /** Custom content rendered under the selected panel search input. */\n selectedPanelHeaderSlot?: ReactNode;\n\n /** Label for the available panel\'s move button. A `(count)` suffix is appended when items are checked. @default "Add to select" */\n moveToSelectedLabel?: string;\n /** Label for the selected panel\'s move button. A `(count)` suffix is appended when items are checked. @default "Remove from selected" */\n moveToAvailableLabel?: string;\n\n /** Enable drag handles, position badges and up/down arrows on the selected panel. @default false */\n reorderable?: boolean;\n\n /** Tooltip for the transfer list reload button. */\n reloadTooltip?: string;\n /** Fired when the reload button is clicked. */\n onReload?: () => void;\n /** Spins the reload icon and disables the button. */\n isReloading?: boolean;\n\n // Consumer-owned paging and load state \u2014 the escape-hatch counterpart to `onAvailableSearchChange`\n // above. All of these are derived internally when `loadAvailableOptions` is set, and the ones marked\n // below are ignored in that mode rather than merged.\n /** More available items can be loaded (drives the infinite-scroll sentinel). Ignored when `loadAvailableOptions` is set. */\n hasMoreAvailable?: boolean;\n /** Fired when the available list sentinel scrolls into view. Ignored when `loadAvailableOptions` is set. */\n onLoadMoreAvailable?: () => void;\n /** Renders a loader row at the bottom of the available list. Ignored when `loadAvailableOptions` is set. */\n isLoadingMoreAvailable?: boolean;\n\n /**\n * Loader REPLACES the available rows (a search/refresh fetch, not a page append). OR-ed with the\n * loader\'s own state, so it still applies in async mode. @default false\n */\n isLoadingAvailable?: boolean;\n /** Replaces the available rows when set: the available source failed to load. Ignored in async mode \u2014 use `loadErrorMessage`. */\n availableLoadError?: ReactNode;\n /**\n * Shown under the loaded rows when a page append failed; renders a retry button. Ignored in async\n * mode \u2014 use `loadMoreErrorMessage`.\n */\n availableLoadMoreError?: ReactNode;\n /** Fired by the retry button under `availableLoadMoreError`. Ignored when `loadAvailableOptions` is set. */\n onRetryLoadMoreAvailable?: () => void;\n /** Label for that retry button. @default "Retry" */\n retryLabel?: string;\n /** Server-side total for the available panel; the header count becomes "(loaded of total)". Takes precedence over the loader\'s own total. */\n availableTotalCount?: number;\n\n /**\n * Async source for the available panel. When provided, the component owns that panel\'s pool, paging,\n * request lifecycle and loading/error state; `availableItems` is ignored (dev warning) and the\n * panel\'s search becomes server-driven. `selectedItems` stays controlled \u2014 the consumer owns the\n * selection \u2014 and `onChange` still fires with both arrays.\n */\n loadAvailableOptions?: TTransferListLoadOptions;\n /**\n * Seed rows for a pool you already have \u2014 an SSR payload, a route loader, a warm cache. They paint on the\n * first frame, so the panel is never briefly empty, and they stay put while the mount fetch revalidates over\n * them. They go through the same pool-minus-`selectedItems` projection as fetched rows. They do not suppress\n * that fetch: pair with `prefetch="never"` if the seed is the whole pool until the user searches. Seed rows\n * carry no cursor, so nothing pages until a real page lands. A *search* replaces them, since seed rows are\n * not results for a query. Async mode only \u2014 ignored (dev warning) without `loadAvailableOptions`, where the\n * rows belong in `availableItems`.\n */\n initialAvailableOptions?: readonly ITransferListItem[];\n /**\n * When to fetch the unfiltered available list. `"mount"` fires at render \u2014 the panel has no\n * open/close, so mount is the only trigger it has. `"never"` defers everything until the user\n * searches, for a heavy list that should stay untouched otherwise.\n *\n * Async mode only \u2014 ignored (dev warning) without `loadAvailableOptions`, where `availableItems` are\n * already on screen and there is nothing to fetch. @default "mount"\n */\n prefetch?: TTransferListPrefetch;\n /** Clearing the available search revalidates the cached baseline instead of just restoring it. @default false */\n refetchOnClear?: boolean;\n /** Identity of the available option set. A change drops cached pages and repopulates. Does NOT clear the selection. */\n optionsKey?: string | number;\n /** Debounce for the available panel\'s search when it is server-driven. @default 300 */\n availableFilterDebounceMs?: number;\n /** Shown in place of the available rows when the loader rejects. @default "Couldn\'t load options." */\n loadErrorMessage?: ReactNode;\n /** Shown under the loaded rows when a page append rejects. @default "Couldn\'t load more." */\n loadMoreErrorMessage?: ReactNode;\n /** Notified when a load rejects (the component renders the message and swallows it). */\n onLoadError?: ( error: unknown ) => void;\n\n /** Disable all interaction. */\n disabled?: boolean;\n\n /** Empty-state copy for the available panel. @default "No Data Found!" */\n availableEmptyText?: ReactNode;\n /** Empty-state copy for the selected panel. @default "No Data Found!" */\n selectedEmptyText?: ReactNode;\n\n className?: string;\n}\n'
|
|
4156
3968
|
},
|
|
4157
3969
|
{
|
|
4158
3970
|
"name": "transferListVariants.ts",
|
|
4159
|
-
"content": 'import { tv } from "tailwind-variants";\n\nexport const transferListVariants = tv({\n slots: {\n base: "flex flex-col gap-3 w-full sm:flex-row sm:items-stretch sm:gap-4 sm:h-[30rem]",\n // `flex-1` is intentionally gated behind `sm:`: on desktop the base is a fixed-height flex-row\n // and flex-1 makes the two panels share the width. On mobile the base is an auto-height column,\n // where flex-1 (flex-basis:0%) would override the `h-[30rem]` height bound and let the panel grow\n // to its full content height - collapsing the virtualizer\'s viewport so it renders every row and\n // freezes on large lists. Keeping flex-1 desktop-only lets `h-[30rem]` bound the scroll container.\n panel: "flex flex-col min-w-0 h-[30rem] rounded-md border border-secondary-100 overflow-hidden bg-white" +\n " dark:bg-iridium dark:border-secondary-500 sm:flex-1 sm:h-full",\n panelHeader: "flex items-center justify-between gap-2 px-4 py-3 border-b dark:border-b-0 border-secondary-100 dark:bg-secondary-800",\n panelTitle: "flex items-center gap-1 font-medium text-base text-secondary-500 dark:text-secondary-50",\n panelCount: "text-base text-secondary-500 dark:text-secondary-50",\n searchArea: "p-3 border-b border-secondary-100 dark:border-secondary-500 dark:bg-secondary-800",\n searchBox: "flex items-center gap-2 px-3 py-2 rounded border border-secondary-100 bg-frostBlue dark:bg-iridium dark:border-secondary-500",\n search: "w-full outline-none bg-transparent dark:bg-iridium text-base text-secondary-500 placeholder:text-secondary-300 dark:text-secondary-200",\n headerSlot: "px-3 py-2 border-b border-secondary-100 dark:border-secondary-500",\n selectAllRow: "flex items-center px-4 pt-4",\n listRegion: "relative flex flex-col flex-1 min-h-0 outline-none" +\n " focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary-400",\n listWrap: "flex-1 min-h-0",\n list: "flex flex-col gap-3 p-3",\n // Windowed (virtualized) list: the scroll element itself carries the padding (the sizer\n // below is absolutely-positioned content), and the sizer reserves the full scroll height.\n virtualScroll: "flex-1 min-h-0 overflow-y-auto p-3",\n virtualSizer: "relative w-full",\n emptyWrap: "flex flex-col flex-1 items-center justify-center gap-4 p-4",\n emptyText: "text-base font-medium text-center text-secondary-400 dark:text-secondary-300",\n loaderRow: "flex justify-center py-3",\n row: "group relative flex items-center gap-2 px-3 py-2 rounded border outline-none cursor-pointer select-none transition-colors",\n dragHandle: "shrink-0 text-gray-800 dark:text-gray-200 cursor-grab",\n badge: "absolute -top-2 -start-1 p-1 flex items-center justify-center min-w-4 h-4 rounded-full bg-white border border-primary-100" +\n " !text-primary-600 dark:!text-primary-300 text-xxs leading-none dark:bg-secondary-600 dark:border-primary-400",\n // min-h-5 reserves one text-base line (~20px) so the row keeps its height when the label\n // leaves flow (position:absolute) on hover. Without it the row\'s cross-size would collapse to\n // the shorter size="sm" checkbox / size="xs" drag handle, shrinking every hovered row by ~4px\n // and shifting the rows below. self-stretch then pins the wrapper to that reserved cross-size. The expand\n // is gated on data-truncated (set by useIsTruncated), so labels that already fit are untouched.\n rowLabelWrap: "relative flex flex-1 min-w-0 min-h-5 items-center self-stretch",\n rowLabel: "block w-full min-w-0 truncate text-base leading-5 text-secondary-500 dark:text-secondary-200" +\n " group-data-[truncated=true]:group-hover:absolute group-data-[truncated=true]:group-hover:inset-x-0" +\n " group-data-[truncated=true]:group-hover:top-1/2 group-data-[truncated=true]:group-hover:-translate-y-1/2" +\n " group-data-[truncated=true]:group-hover:z-20 group-data-[truncated=true]:group-hover:whitespace-normal" +\n " group-data-[truncated=true]:group-hover:overflow-visible group-data-[truncated=true]:group-hover:break-words" +\n " group-data-[truncated=true]:group-hover:rounded group-data-[truncated=true]:group-hover:border" +\n " group-data-[truncated=true]:group-hover:border-secondary-200 group-data-[truncated=true]:group-hover:bg-white" +\n " group-data-[truncated=true]:group-hover:shadow-md group-data-[truncated=true]:group-hover:p-2" +\n " group-data-[truncated=true]:group-focus-visible:absolute group-data-[truncated=true]:group-focus-visible:inset-x-0" +\n " group-data-[truncated=true]:group-focus-visible:top-1/2 group-data-[truncated=true]:group-focus-visible:-translate-y-1/2" +\n " group-data-[truncated=true]:group-focus-visible:z-20 group-data-[truncated=true]:group-focus-visible:whitespace-normal" +\n " group-data-[truncated=true]:group-focus-visible:overflow-visible group-data-[truncated=true]:group-focus-visible:break-words" +\n " group-data-[truncated=true]:group-focus-visible:rounded group-data-[truncated=true]:group-focus-visible:border" +\n " group-data-[truncated=true]:group-focus-visible:border-secondary-200 group-data-[truncated=true]:group-focus-visible:bg-white" +\n " group-data-[truncated=true]:group-focus-visible:shadow-md" +\n " dark:group-data-[truncated=true]:group-hover:border-primary-400 dark:group-data-[truncated=true]:group-hover:bg-iridium" +\n " dark:group-data-[truncated=true]:group-focus-visible:border-primary-400" +\n " dark:group-data-[truncated=true]:group-focus-visible:bg-iridium",\n rowActions: "flex items-center gap-1 shrink-0 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100",\n removeButton: "flex items-center text-gray-800 hover:text-error-500 dark:text-secondary-400",\n reorderButton: "flex items-center text-gray-800 hover:text-primary-500 disabled:opacity-30 dark:text-secondary-400",\n panelFooter: "flex items-center justify-end px-4 py-3 border-t border-secondary-100 dark:border-secondary-500",\n dropIndicator: "absolute inset-x-1 z-10 h-0.5 rounded bg-primary-500 pointer-events-none",\n dropOverlay: "absolute inset-2 z-10 flex items-center justify-center pointer-events-none rounded-md border-2 border-dashed" +\n " border-primary-300 bg-primary-50/95 text-base font-medium text-primary-600 dark:border-primary-400" +\n " dark:bg-secondary-700/95 dark:text-primary-300"\n },\n variants: {\n panel: {\n available: {\n row: "bg-white border-secondary-100 hover:bg-primary-50 hover:border-primary-200 focus-visible:border-primary-500" +\n " dark:bg-iridium dark:border-secondary-500 dark:hover:bg-secondary-800"\n },\n selected: {\n listRegion: "m-4 rounded-lg bg-frostBlue overflow-hidden dark:bg-secondary-900",\n virtualScroll: "p-4",\n row: "bg-primary-50 border-primary-100 hover:border-primary-200 focus-visible:border-primary-500 dark:bg-secondary-700 dark:border-secondary-500"\n }\n },\n checked: {\n true: { row: "bg-primary-50 border-primary-200 dark:bg-secondary-700 dark:border-primary-400" },\n false: {}\n },\n // Keyboard-active row (the one aria-activedescendant points at). Rows aren\'t individually\n // focusable under the listbox\'s activedescendant navigation, so this stands in for the\n // focus-visible ring the row would otherwise get.\n active: {\n true: { row: "border-primary-500 dark:border-primary-400" },\n false: {}\n },\n isDisabled: {\n true: { row: "opacity-50 cursor-not-allowed pointer-events-none" },\n false: {}\n },\n // Anchors the drop indicator to the row\'s top or bottom edge, centered in the flex gap\n // between rows. "before" is the common case (dropIndex === index); "after" only applies\n // to the last row, when dropIndex === items.length.\n dropIndicatorPosition: {\n before: { dropIndicator: "-top-[7px]" },\n after: { dropIndicator: "-bottom-[7px]" }\n }\n },\n defaultVariants: {\n panel: "available",\n checked: false,\n active: false,\n isDisabled: false,\n dropIndicatorPosition: "before"\n }\n});\n'
|
|
3971
|
+
"content": 'import { tv } from "tailwind-variants";\n\nexport const transferListVariants = tv({\n slots: {\n base: "flex flex-col gap-3 w-full sm:flex-row sm:items-stretch sm:gap-4 sm:h-[30rem]",\n // `flex-1` is intentionally gated behind `sm:`: on desktop the base is a fixed-height flex-row\n // and flex-1 makes the two panels share the width. On mobile the base is an auto-height column,\n // where flex-1 (flex-basis:0%) would override the `h-[30rem]` height bound and let the panel grow\n // to its full content height - collapsing the virtualizer\'s viewport so it renders every row and\n // freezes on large lists. Keeping flex-1 desktop-only lets `h-[30rem]` bound the scroll container.\n panel: "flex flex-col min-w-0 h-[30rem] rounded-md border border-secondary-100 overflow-hidden bg-white" +\n " dark:bg-iridium dark:border-secondary-500 sm:flex-1 sm:h-full",\n panelHeader: "flex items-center justify-between gap-2 px-4 py-3 border-b dark:border-b-0 border-secondary-100 dark:bg-secondary-800",\n panelTitle: "flex items-center gap-1 font-medium text-base text-secondary-500 dark:text-secondary-50",\n panelCount: "text-base text-secondary-500 dark:text-secondary-50",\n searchArea: "p-3 border-b border-secondary-100 dark:border-secondary-500 dark:bg-secondary-800",\n searchBox: "flex items-center gap-2 px-3 py-2 rounded border border-secondary-100 bg-frostBlue dark:bg-iridium dark:border-secondary-500",\n search: "w-full outline-none bg-transparent dark:bg-iridium text-base text-secondary-500 placeholder:text-secondary-300 dark:text-secondary-200",\n headerSlot: "px-3 py-2 border-b border-secondary-100 dark:border-secondary-500",\n selectAllRow: "flex items-center px-4 pt-4",\n listRegion: "relative flex flex-col flex-1 min-h-0 outline-none" +\n " focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary-400",\n listWrap: "flex-1 min-h-0",\n list: "flex flex-col gap-3 p-3",\n // Windowed (virtualized) list: the scroll element itself carries the padding (the sizer\n // below is absolutely-positioned content), and the sizer reserves the full scroll height.\n virtualScroll: "flex-1 min-h-0 overflow-y-auto p-3",\n virtualSizer: "relative w-full",\n emptyWrap: "flex flex-col flex-1 items-center justify-center gap-4 p-4",\n emptyText: "text-base font-medium text-center text-secondary-400 dark:text-secondary-300",\n loaderRow: "flex justify-center py-3",\n // The replace loader fills the list region, unlike loaderRow which appends below the rows.\n replaceLoader: "flex flex-1 items-center justify-center py-3",\n // "Error instead of rows" for the whole panel, and the recoverable "that page failed" row that\n // replaces the append loader at the bottom of the list.\n panelError: "flex flex-1 items-center justify-center px-4 py-3 text-base text-center text-error-700 dark:text-error-400",\n loadMoreErrorRow: "flex items-center justify-center gap-2 py-3 text-base text-error-700 dark:text-error-400",\n row: "group relative flex items-center gap-2 px-3 py-2 rounded border outline-none cursor-pointer select-none transition-colors",\n dragHandle: "shrink-0 text-gray-800 dark:text-gray-200 cursor-grab",\n badge: "absolute -top-2 -start-1 p-1 flex items-center justify-center min-w-4 h-4 rounded-full bg-white border border-primary-100" +\n " !text-primary-600 dark:!text-primary-300 text-xxs leading-none dark:bg-secondary-600 dark:border-primary-400",\n // min-h-5 reserves one text-base line (~20px) so the row keeps its height when the label\n // leaves flow (position:absolute) on hover. Without it the row\'s cross-size would collapse to\n // the shorter size="sm" checkbox / size="xs" drag handle, shrinking every hovered row by ~4px\n // and shifting the rows below. self-stretch then pins the wrapper to that reserved cross-size. The expand\n // is gated on data-truncated (set by useIsTruncated), so labels that already fit are untouched.\n rowLabelWrap: "relative flex flex-1 min-w-0 min-h-5 items-center self-stretch",\n rowLabel: "block w-full min-w-0 truncate text-base leading-5 text-secondary-500 dark:text-secondary-200" +\n " group-data-[truncated=true]:group-hover:absolute group-data-[truncated=true]:group-hover:inset-x-0" +\n " group-data-[truncated=true]:group-hover:top-1/2 group-data-[truncated=true]:group-hover:-translate-y-1/2" +\n " group-data-[truncated=true]:group-hover:z-20 group-data-[truncated=true]:group-hover:whitespace-normal" +\n " group-data-[truncated=true]:group-hover:overflow-visible group-data-[truncated=true]:group-hover:break-words" +\n " group-data-[truncated=true]:group-hover:rounded group-data-[truncated=true]:group-hover:border" +\n " group-data-[truncated=true]:group-hover:border-secondary-200 group-data-[truncated=true]:group-hover:bg-white" +\n " group-data-[truncated=true]:group-hover:shadow-md group-data-[truncated=true]:group-hover:p-2" +\n " group-data-[truncated=true]:group-focus-visible:absolute group-data-[truncated=true]:group-focus-visible:inset-x-0" +\n " group-data-[truncated=true]:group-focus-visible:top-1/2 group-data-[truncated=true]:group-focus-visible:-translate-y-1/2" +\n " group-data-[truncated=true]:group-focus-visible:z-20 group-data-[truncated=true]:group-focus-visible:whitespace-normal" +\n " group-data-[truncated=true]:group-focus-visible:overflow-visible group-data-[truncated=true]:group-focus-visible:break-words" +\n " group-data-[truncated=true]:group-focus-visible:rounded group-data-[truncated=true]:group-focus-visible:border" +\n " group-data-[truncated=true]:group-focus-visible:border-secondary-200 group-data-[truncated=true]:group-focus-visible:bg-white" +\n " group-data-[truncated=true]:group-focus-visible:shadow-md" +\n " dark:group-data-[truncated=true]:group-hover:border-primary-400 dark:group-data-[truncated=true]:group-hover:bg-iridium" +\n " dark:group-data-[truncated=true]:group-focus-visible:border-primary-400" +\n " dark:group-data-[truncated=true]:group-focus-visible:bg-iridium",\n rowActions: "flex items-center gap-1 shrink-0 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100",\n removeButton: "flex items-center text-gray-800 hover:text-error-500 dark:text-secondary-400",\n reorderButton: "flex items-center text-gray-800 hover:text-primary-500 disabled:opacity-30 dark:text-secondary-400",\n panelFooter: "flex items-center justify-end px-4 py-3 border-t border-secondary-100 dark:border-secondary-500",\n dropIndicator: "absolute inset-x-1 z-10 h-0.5 rounded bg-primary-500 pointer-events-none",\n dropOverlay: "absolute inset-2 z-10 flex items-center justify-center pointer-events-none rounded-md border-2 border-dashed" +\n " border-primary-300 bg-primary-50/95 text-base font-medium text-primary-600 dark:border-primary-400" +\n " dark:bg-secondary-700/95 dark:text-primary-300"\n },\n variants: {\n panel: {\n available: {\n row: "bg-white border-secondary-100 hover:bg-primary-50 hover:border-primary-200 focus-visible:border-primary-500" +\n " dark:bg-iridium dark:border-secondary-500 dark:hover:bg-secondary-800"\n },\n selected: {\n listRegion: "m-4 rounded-lg bg-frostBlue overflow-hidden dark:bg-secondary-900",\n virtualScroll: "p-4",\n row: "bg-primary-50 border-primary-100 hover:border-primary-200 focus-visible:border-primary-500 dark:bg-secondary-700 dark:border-secondary-500"\n }\n },\n checked: {\n true: { row: "bg-primary-50 border-primary-200 dark:bg-secondary-700 dark:border-primary-400" },\n false: {}\n },\n // Keyboard-active row (the one aria-activedescendant points at). Rows aren\'t individually\n // focusable under the listbox\'s activedescendant navigation, so this stands in for the\n // focus-visible ring the row would otherwise get.\n active: {\n true: { row: "border-primary-500 dark:border-primary-400" },\n false: {}\n },\n isDisabled: {\n true: { row: "opacity-50 cursor-not-allowed pointer-events-none" },\n false: {}\n },\n // Anchors the drop indicator to the row\'s top or bottom edge, centered in the flex gap\n // between rows. "before" is the common case (dropIndex === index); "after" only applies\n // to the last row, when dropIndex === items.length.\n dropIndicatorPosition: {\n before: { dropIndicator: "-top-[7px]" },\n after: { dropIndicator: "-bottom-[7px]" }\n }\n },\n defaultVariants: {\n panel: "available",\n checked: false,\n active: false,\n isDisabled: false,\n dropIndicatorPosition: "before"\n }\n});\n'
|
|
3972
|
+
},
|
|
3973
|
+
{
|
|
3974
|
+
"name": "transferListPanelHeader.tsx",
|
|
3975
|
+
"content": 'import * as React from "react";\n\nimport { ReloadButton } from "../button/reloadButton";\nimport { ADPIcon, iconList } from "../adpIcon";\nimport { transferListVariants } from "./transferListVariants";\nimport type { TTransferPanel } from "./types";\n\ninterface ITransferListPanelHeaderProps {\n panel: TTransferPanel;\n title: React.ReactNode;\n /** Rows currently loaded in this panel. */\n count: number;\n /** Server-side total; the count becomes "(loaded of total)" when it exceeds `count`. */\n totalCount?: number;\n disabled: boolean;\n\n searchable: boolean;\n searchValue: string;\n searchPlaceholder: string;\n onSearchChange: ( query: string ) => void;\n headerSlot?: React.ReactNode;\n\n reloadTooltip?: string;\n onReload?: () => void;\n isReloading?: boolean;\n}\n\n/**\n * The non-interactive chrome above a transfer-list panel\'s listbox: title + count, the optional\n * reload button, the search input, and the consumer\'s header slot. It shares no state with the\n * listbox below it.\n */\nexport function TransferListPanelHeader({\n panel,\n title,\n count,\n totalCount,\n disabled,\n searchable,\n searchValue,\n searchPlaceholder,\n onSearchChange,\n headerSlot,\n reloadTooltip,\n onReload,\n isReloading\n}: ITransferListPanelHeaderProps ): React.ReactElement {\n const {\n panelHeader,\n panelTitle,\n panelCount,\n searchArea,\n searchBox,\n search,\n headerSlot: headerSlotClass\n } = transferListVariants({ panel });\n\n return (\n <>\n <div className={panelHeader()}>\n <span className={panelTitle()}>\n {title}\n {/* A paged panel that reports "(20)" when the server holds 4 000 matches is lying. */}\n <span className={panelCount()}>\n {totalCount !== undefined && totalCount > count ? `(${count} of ${totalCount})` : `(${count})`}\n </span>\n </span>\n <ReloadButton\n onReload={onReload}\n isReloading={isReloading}\n disabled={disabled}\n tooltip={reloadTooltip}\n className="-m-2 p-2"\n />\n </div>\n\n {searchable && (\n <div className={searchArea()}>\n <div className={searchBox()}>\n <ADPIcon icon={iconList.search} size="xs" className="text-gray-800 dark:text-gray-300" />\n <input\n type="text"\n value={searchValue}\n placeholder={searchPlaceholder}\n disabled={disabled}\n aria-label={`Search ${panel} items`}\n id={`transferListSearch-${panel}`}\n className={search()}\n onChange={( e ) => onSearchChange( e.target.value )}\n />\n </div>\n </div>\n )}\n\n {headerSlot && <div className={headerSlotClass()}>{headerSlot}</div>}\n </>\n );\n}\n\nTransferListPanelHeader.displayName = "TransferListPanelHeader";\n'
|
|
4160
3976
|
},
|
|
4161
3977
|
{
|
|
4162
3978
|
"name": "transferListPanel.tsx",
|
|
4163
|
-
"content": 'import * as React from "react";\nimport { useEffect, useId, useMemo, useRef, useState } from "react";\n\nimport { useInfiniteScroll, useListboxKeyboardNav } from "@hooks";\nimport { Scrollbar } from "../scrollbar";\nimport { Loader } from "../loader";\nimport { Checkbox } from "../checkbox";\nimport { Button } from "../button";\nimport { ADPIcon, iconList } from "../adpIcon";\nimport { EmptyState } from "../emptyState";\nimport { TransferListItem } from "./transferListItem";\nimport { useDragAutoScroll } from "./useDragAutoScroll";\nimport { transferListVariants } from "./transferListVariants";\nimport type { ITransferListItem, TTransferListValue, TTransferPanel } from "./types";\n\n// Above this many rows the panel switches from rendering every row to a windowed (virtualized)\n// list. Below it, the list renders in full inside the custom Scrollbar exactly as before, so\n// small lists keep full drag-and-drop and the original scrollbar chrome with zero behaviour change.\nconst VIRTUALIZE_THRESHOLD = 100;\n// Approximate row height (px) used before real rows are measured; measureElement corrects it.\nconst ESTIMATED_ROW_HEIGHT = 38;\n// Vertical gap between rows, matching the `gap-3` (0.75rem) of the non-virtualized list.\nconst ROW_GAP = 12;\n\n// `:focus-visible` isolates genuine keyboard focus from pointer/drag focus. jsdom may not support\n// the selector, so fall back to treating focus as keyboard focus there (tests assert on\n// aria-activedescendant, not the active-row border).\nconst isKeyboardFocus = ( el: HTMLElement ): boolean => {\n try {\n return el.matches( ":focus-visible" );\n } catch {\n return true;\n }\n};\n\ninterface ITransferListPanelProps {\n panel: TTransferPanel;\n title: React.ReactNode;\n items: ITransferListItem[];\n reorderable: boolean;\n disabled: boolean;\n emptyText: React.ReactNode;\n\n searchable: boolean;\n searchValue: string;\n searchPlaceholder: string;\n onSearchChange: ( query: string ) => void;\n headerSlot?: React.ReactNode;\n\n reloadTooltip?: string;\n onReload?: () => void;\n isReloading?: boolean;\n\n hasMore?: boolean;\n onLoadMore?: () => void;\n isLoadingMore?: boolean;\n\n selectAllChecked: boolean;\n selectAllIndeterminate: boolean;\n selectAllCount: number;\n onToggleSelectAll: () => void;\n\n moveLabel: string;\n moveCount: number;\n moveDisabled: boolean;\n moveIconSide: "left" | "right";\n onMove: () => void;\n\n isChecked: ( value: TTransferListValue ) => boolean;\n onToggle: ( value: TTransferListValue ) => void;\n onRemove?: ( value: TTransferListValue ) => void;\n onMoveUp?: ( index: number ) => void;\n onMoveDown?: ( index: number ) => void;\n\n dropIndex: number | null;\n showDropOverlay: boolean;\n onItemDragStart: ( e: React.DragEvent, value: TTransferListValue ) => void;\n onItemDragEnd: () => void;\n onItemDragOver: ( e: React.DragEvent, index: number ) => void;\n onListDragOver: ( e: React.DragEvent ) => void;\n onListDrop: ( e: React.DragEvent ) => void;\n}\n\n/**\n * One panel of the transfer list: header (title, count, optional reload),\n * optional search + header slot, and a scrollable list of rows or an empty state.\n */\nexport function TransferListPanel({\n panel,\n title,\n items,\n reorderable,\n disabled,\n emptyText,\n searchable,\n searchValue,\n searchPlaceholder,\n onSearchChange,\n headerSlot,\n reloadTooltip,\n onReload,\n isReloading,\n hasMore,\n onLoadMore,\n isLoadingMore,\n selectAllChecked,\n selectAllIndeterminate,\n selectAllCount,\n onToggleSelectAll,\n moveLabel,\n moveCount,\n moveDisabled,\n moveIconSide,\n onMove,\n isChecked,\n onToggle,\n onRemove,\n onMoveUp,\n onMoveDown,\n dropIndex,\n showDropOverlay,\n onItemDragStart,\n onItemDragEnd,\n onItemDragOver,\n onListDragOver,\n onListDrop\n}: ITransferListPanelProps ): React.ReactElement {\n const {\n panel: panelClass,\n panelHeader,\n panelTitle,\n panelCount,\n searchArea,\n searchBox,\n search,\n headerSlot: headerSlotClass,\n selectAllRow,\n panelFooter,\n listRegion,\n listWrap,\n list,\n virtualScroll,\n virtualSizer,\n emptyWrap,\n emptyText: emptyTextClass,\n loaderRow,\n dropOverlay\n } = transferListVariants({ panel });\n\n // Infinite-scroll sentinel (available panel only). Fires onLoadMore when the\n // bottom of the list scrolls into view.\n const sentinelRef = useInfiniteScroll({ hasMore, isLoading: isLoadingMore, onLoadMore });\n\n // Windowing scroll container: the virtualizer (owned by useListboxKeyboardNav) measures and\n // scrolls it, and useDragAutoScroll edge-scrolls it during a drag.\n const virtualScrollRef = useRef<HTMLDivElement>( null );\n const autoScroll = useDragAutoScroll( virtualScrollRef );\n\n // \u2500\u2500 Keyboard navigation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // The list is a single tab stop (role="listbox"); arrow keys move an "active" row via\n // aria-activedescendant instead of every row being its own tab stop - so a long list no longer\n // forces the user to Tab through every option to reach the next control/panel.\n const listboxId = useId();\n const listRegionRef = useRef<HTMLDivElement>( null );\n const optionId = ( index: number ): string => `${listboxId}-opt-${index}`;\n\n // The active row is the keyboard-navigation cursor, so it should only be shown while the list\n // actually holds focus - otherwise the first row of every panel paints its active border on\n // mount and reads as a stray focus ring.\n const [ isFocused, setIsFocused ] = useState( false );\n\n // Reset key for the active row: keyed on the sorted values, so a pure reorder (same set, new\n // order) does not fire the reset and yank the active row back to the top mid-keyboard-reorder.\n // Memoized so the sort runs only when the item set actually changes, not on every re-render.\n const itemsKey = useMemo(\n () => items.map(( item ) => String( item.value )).sort().join( "\\n" ),\n [items]\n );\n\n const {\n activeIndex,\n setActiveIndex,\n moveActive,\n firstEnabledIndex,\n virtualizer: rowVirtualizer,\n shouldVirtualize\n } = useListboxKeyboardNav({\n itemCount: items.length,\n isItemDisabled: ( index ) => Boolean( items[index]?.isDisabled ),\n resetKey: itemsKey,\n scrollElementRef: virtualScrollRef,\n queryElementRef: listRegionRef,\n optionId,\n estimateSize: ESTIMATED_ROW_HEIGHT,\n gap: ROW_GAP,\n virtualizeThreshold: VIRTUALIZE_THRESHOLD\n });\n\n const isListFocusable = !disabled && items.length > 0;\n\n const handleListKeyDown = ( e: React.KeyboardEvent<HTMLDivElement> ) => {\n // Any key interaction is keyboard mode, so light the active row - covers the case where focus\n // arrived by pointer (which is not :focus-visible, so onFocus left it dark) and the user then\n // starts navigating with the arrows. onMouseDown turns it back off when they switch to pointer.\n setIsFocused( true );\n const activeItem = items[activeIndex];\n\n // Alt+Arrow reorders the active row (reorderable selected panel), keeping it active as it\n // moves. Checked before the plain Arrow navigation below.\n if ( e.altKey && ( e.key === "ArrowUp" || e.key === "ArrowDown" )) {\n if ( !reorderable || !activeItem ) {\n return;\n }\n e.preventDefault();\n if ( e.key === "ArrowUp" && activeIndex > 0 ) {\n onMoveUp?.( activeIndex );\n setActiveIndex( activeIndex - 1 );\n } else if ( e.key === "ArrowDown" && activeIndex < items.length - 1 ) {\n onMoveDown?.( activeIndex );\n setActiveIndex( activeIndex + 1 );\n }\n return;\n }\n\n switch ( e.key ) {\n case "ArrowDown":\n e.preventDefault();\n moveActive( 1 );\n break;\n case "ArrowUp":\n e.preventDefault();\n moveActive( -1 );\n break;\n case "Home":\n e.preventDefault();\n setActiveIndex( firstEnabledIndex( 0, 1 ));\n break;\n case "End":\n e.preventDefault();\n setActiveIndex( firstEnabledIndex( items.length - 1, -1 ));\n break;\n case "Enter":\n case " ":\n if ( activeItem && !activeItem.isDisabled ) {\n e.preventDefault();\n onToggle( activeItem.value );\n }\n break;\n // Delete / Backspace removes the active row back to Available (selected panel only). On a\n // Mac keyboard the "delete" key reports as Backspace, so both are accepted.\n case "Delete":\n case "Backspace":\n if ( onRemove && activeItem && !activeItem.isDisabled ) {\n e.preventDefault();\n onRemove( activeItem.value );\n }\n break;\n default:\n break;\n }\n };\n\n // Shared row renderer so the windowed and full-render paths produce identical rows.\n const renderItem = ( item: ITransferListItem, index: number ): React.ReactElement => (\n <TransferListItem\n key={item.value}\n item={item}\n panel={panel}\n index={index}\n id={optionId( index )}\n active={isFocused && index === activeIndex}\n checked={isChecked( item.value )}\n reorderable={reorderable}\n disabled={disabled || Boolean( item.isDisabled )}\n isFirst={index === 0}\n isLast={index === items.length - 1}\n showTopIndicator={dropIndex === index}\n showBottomIndicator={index === items.length - 1 && dropIndex === items.length}\n onToggle={() => onToggle( item.value )}\n onRemove={onRemove ? () => onRemove( item.value ) : undefined}\n onMoveUp={onMoveUp ? () => onMoveUp( index ) : undefined}\n onMoveDown={onMoveDown ? () => onMoveDown( index ) : undefined}\n onDragStart={( e ) => onItemDragStart( e, item.value )}\n onDragEnd={onItemDragEnd}\n onDragOver={( e ) => onItemDragOver( e, index )}\n onDrop={onListDrop}\n />\n );\n\n const handleVirtualDragOver = ( e: React.DragEvent ) => {\n onListDragOver( e );\n autoScroll.onDragOver( e );\n };\n\n // `Checkbox` renders a native input and has no `indeterminate` prop; it\'s a DOM\n // property, so reflect the "some but not all checked" state through the ref.\n const selectAllRef = useRef<HTMLInputElement>( null );\n useEffect(() => {\n if ( selectAllRef.current ) {\n selectAllRef.current.indeterminate = selectAllIndeterminate;\n }\n }, [selectAllIndeterminate]);\n\n return (\n <div className={panelClass()} data-testid={`transferListPanel-${panel}`}>\n <div className={panelHeader()}>\n <span className={panelTitle()}>\n {title}\n <span className={panelCount()}>{`(${items.length})`}</span>\n </span>\n {typeof onReload === "function" && (\n <Button\n variant="shade"\n color="secondary"\n className="-m-2 p-2"\n size="sm"\n aria-label={reloadTooltip}\n disabled={disabled || isReloading}\n onClick={onReload}\n tooltip={reloadTooltip}\n >\n <ADPIcon icon={iconList.reload} size="xs" spin={isReloading} />\n </Button>\n )}\n </div>\n\n {searchable && (\n <div className={searchArea()}>\n <div className={searchBox()}>\n <ADPIcon icon={iconList.search} size="xs" className="text-gray-800 dark:text-gray-300" />\n <input\n type="text"\n value={searchValue}\n placeholder={searchPlaceholder}\n disabled={disabled}\n aria-label={`Search ${panel} items`}\n id={`transferListSearch-${panel}`}\n className={search()}\n onChange={( e ) => onSearchChange( e.target.value )}\n />\n </div>\n </div>\n )}\n\n {headerSlot && <div className={headerSlotClass()}>{headerSlot}</div>}\n\n <div\n ref={listRegionRef}\n className={listRegion()}\n role="listbox"\n aria-multiselectable="true"\n aria-label={typeof title === "string" ? title : undefined}\n tabIndex={isListFocusable ? 0 : -1}\n aria-activedescendant={isListFocusable && activeIndex >= 0 ? optionId( activeIndex ) : undefined}\n // Only light the active row for genuine keyboard focus. Starting a drag on a row also\n // focuses its listbox (a pointer interaction, so not :focus-visible); without this guard the\n // active cursor would paint a stray focus border on the new first row once the dragged row\n // leaves on drop.\n onFocus={( e ) => {\n if ( isKeyboardFocus( e.currentTarget )) {\n setIsFocused( true );\n }\n }}\n // A pointer interaction (including grabbing a row to drag) exits keyboard mode, mirroring\n // :focus-visible - so a drag never leaves the active-row border lit on the row that shifts\n // under the pointer once the dragged row is gone.\n onMouseDown={() => setIsFocused( false )}\n onBlur={() => setIsFocused( false )}\n onKeyDown={handleListKeyDown}\n >\n {selectAllCount > 0 && <div className={selectAllRow()}>\n <Checkbox\n ref={selectAllRef}\n size="sm"\n checked={selectAllChecked}\n disabled={disabled}\n label={`Select all (${selectAllCount})`}\n onChange={onToggleSelectAll}\n />\n </div>\n }\n {items.length === 0 && !isLoadingMore ? (\n <div className={emptyWrap()} onDragOver={onListDragOver} onDrop={onListDrop}>\n <EmptyState imageVariant="no-data">\n <EmptyState.Content className={emptyTextClass()}>\n {emptyText}\n </EmptyState.Content>\n </EmptyState>\n </div>\n ) : shouldVirtualize ? (\n <div ref={virtualScrollRef} className={virtualScroll()} onDragOver={handleVirtualDragOver} onDrop={onListDrop}>\n <div className={virtualSizer()} style={{ height: rowVirtualizer.getTotalSize() }}>\n {rowVirtualizer.getVirtualItems().map(( virtualRow ) => (\n <div\n key={items[virtualRow.index].value}\n data-index={virtualRow.index}\n ref={rowVirtualizer.measureElement}\n className="absolute inset-x-0 top-0"\n style={{ transform: `translateY(${virtualRow.start}px)` }}\n >\n {renderItem( items[virtualRow.index], virtualRow.index )}\n </div>\n ))}\n {/* Sentinel pinned to the bottom of the full scroll height: clipped by the scroll\n container until the user reaches the end, where it triggers onLoadMore. */}\n <div ref={sentinelRef} className="absolute bottom-0 h-px w-px" aria-hidden="true" />\n </div>\n {isLoadingMore && (\n <div className={loaderRow()}>\n <Loader size="sm" />\n </div>\n )}\n </div>\n ) : (\n <Scrollbar className={listWrap()} onDragOver={onListDragOver} onDrop={onListDrop}>\n <div className={list()}>\n {items.map(( item, index ) => renderItem( item, index ))}\n {isLoadingMore && (\n <div className={loaderRow()}>\n <Loader size="sm" />\n </div>\n )}\n <div ref={sentinelRef} className="h-px" aria-hidden="true" />\n </div>\n </Scrollbar>\n )}\n {showDropOverlay && (\n <div className={dropOverlay()} data-testid="transferListDropOverlay" aria-hidden="true">\n Drop Here\n </div>\n )}\n </div>\n\n <div className={panelFooter()}>\n <Button\n size="xs"\n variant="outline"\n color="primary"\n disabled={moveDisabled}\n prefixIcon={moveIconSide === "left" ? iconList.leftArrowLong : undefined}\n suffixIcon={moveIconSide === "right" ? iconList.rightArrowLong : undefined}\n onClick={onMove}\n >\n {moveCount > 0 ? `${moveLabel} (${moveCount})` : moveLabel}\n </Button>\n </div>\n </div>\n );\n}\n\nTransferListPanel.displayName = "TransferListPanel";\n'
|
|
3979
|
+
"content": 'import * as React from "react";\nimport { useCallback, useId, useMemo, useRef, useState } from "react";\n\nimport { useInfiniteScroll, useListboxKeyboardNav } from "@hooks";\nimport { Scrollbar } from "../scrollbar";\nimport { Loader } from "../loader";\nimport { Checkbox } from "../checkbox";\nimport { Button } from "../button";\nimport { iconList } from "../adpIcon";\nimport { EmptyState } from "../emptyState";\nimport { TransferListItem } from "./transferListItem";\nimport { TransferListPanelHeader } from "./transferListPanelHeader";\nimport { useDragAutoScroll } from "./useDragAutoScroll";\nimport { useTransferListPanelKeys } from "./useTransferListPanelKeys";\nimport { transferListVariants } from "./transferListVariants";\nimport type { ITransferListItem, TTransferListValue, TTransferPanel } from "./types";\n\n// Above this many rows the panel renders a windowed (virtualized) list. Below it, the list renders\n// in full inside the custom Scrollbar, with full drag-and-drop support.\nconst VIRTUALIZE_THRESHOLD = 100;\n// Approximate row height (px) used before real rows are measured; measureElement corrects it.\nconst ESTIMATED_ROW_HEIGHT = 38;\n// Vertical gap between rows, matching the `gap-3` (0.75rem) of the non-virtualized list.\nconst ROW_GAP = 12;\n\n// `:focus-visible` isolates genuine keyboard focus from pointer/drag focus. jsdom may not support\n// the selector, so fall back to treating focus as keyboard focus there (tests assert on\n// aria-activedescendant, not the active-row border).\nconst isKeyboardFocus = ( el: HTMLElement ): boolean => {\n try {\n return el.matches( ":focus-visible" );\n } catch {\n return true;\n }\n};\n\ninterface ITransferListPanelProps {\n panel: TTransferPanel;\n title: React.ReactNode;\n items: ITransferListItem[];\n reorderable: boolean;\n disabled: boolean;\n emptyText: React.ReactNode;\n\n searchable: boolean;\n searchValue: string;\n searchPlaceholder: string;\n onSearchChange: ( query: string ) => void;\n headerSlot?: React.ReactNode;\n\n reloadTooltip?: string;\n onReload?: () => void;\n isReloading?: boolean;\n\n hasMore?: boolean;\n onLoadMore?: () => void;\n isLoadingMore?: boolean;\n\n /** Loader REPLACES the rows (a search/refresh fetch, not a page append). */\n isLoading?: boolean;\n /** Replaces the rows when set: the panel\'s source failed to load. */\n loadError?: React.ReactNode;\n /** Shown under the loaded rows when a page append failed; renders a retry button. */\n loadMoreError?: React.ReactNode;\n /** Fired by the retry button under `loadMoreError`. */\n onRetryLoadMore?: () => void;\n /** Label for that retry button. */\n retryLabel?: string;\n /** Server-side total; the header count becomes "(loaded of total)". */\n totalCount?: number;\n\n selectAllChecked: boolean;\n selectAllIndeterminate: boolean;\n /** Search-visible, non-disabled row count \u2014 the scope the select-all checkbox acts on. */\n selectAllCount: number;\n onToggleSelectAll: () => void;\n\n moveLabel: string;\n moveCount: number;\n moveDisabled: boolean;\n moveIconSide: "left" | "right";\n onMove: () => void;\n\n isChecked: ( value: TTransferListValue ) => boolean;\n onToggle: ( value: TTransferListValue ) => void;\n onRemove?: ( value: TTransferListValue ) => void;\n onMoveUp?: ( index: number ) => void;\n onMoveDown?: ( index: number ) => void;\n\n dropIndex: number | null;\n showDropOverlay: boolean;\n onItemDragStart: ( e: React.DragEvent, value: TTransferListValue ) => void;\n onItemDragEnd: () => void;\n onItemDragOver: ( e: React.DragEvent, index: number ) => void;\n onListDragOver: ( e: React.DragEvent ) => void;\n onListDrop: ( e: React.DragEvent ) => void;\n}\n\n/**\n * One panel of the transfer list: header (title, count, optional reload),\n * optional search + header slot, and a scrollable list of rows or an empty state.\n */\nexport function TransferListPanel({\n panel,\n title,\n items,\n reorderable,\n disabled,\n emptyText,\n searchable,\n searchValue,\n searchPlaceholder,\n onSearchChange,\n headerSlot,\n reloadTooltip,\n onReload,\n isReloading,\n hasMore,\n onLoadMore,\n isLoadingMore,\n isLoading,\n loadError,\n loadMoreError,\n onRetryLoadMore,\n retryLabel = "Retry",\n totalCount,\n selectAllChecked,\n selectAllIndeterminate,\n selectAllCount,\n onToggleSelectAll,\n moveLabel,\n moveCount,\n moveDisabled,\n moveIconSide,\n onMove,\n isChecked,\n onToggle,\n onRemove,\n onMoveUp,\n onMoveDown,\n dropIndex,\n showDropOverlay,\n onItemDragStart,\n onItemDragEnd,\n onItemDragOver,\n onListDragOver,\n onListDrop\n}: ITransferListPanelProps ): React.ReactElement {\n const {\n panel: panelClass,\n selectAllRow,\n panelFooter,\n listRegion,\n listWrap,\n list,\n virtualScroll,\n virtualSizer,\n emptyWrap,\n emptyText: emptyTextClass,\n loaderRow,\n replaceLoader,\n panelError,\n loadMoreErrorRow,\n dropOverlay\n } = transferListVariants({ panel });\n\n // While the rows are being replaced (or an error stands in for them) the arrow keys are addressing\n // rows that are about to leave, so navigation, activedescendant and Enter/Space are all suppressed.\n const isReplacing = Boolean( isLoading ) || loadError !== undefined;\n\n // Infinite-scroll sentinel (available panel only). Fires onLoadMore when the\n // bottom of the list scrolls into view.\n const sentinelRef = useInfiniteScroll({ hasMore, isLoading: isLoadingMore, onLoadMore });\n\n // No rows does not mean exhausted: with a paged source the panel can run dry while the server\n // still holds pages \u2014 every loaded row moved to the other panel, or filtered out. The panel is\n // then BETWEEN pages, not empty, so it renders the list (with its sentinel and the append loader)\n // rather than the empty state: "no data" would be untrue, and the sentinel is the only thing that\n // can pull the next page \u2014 dropping it with the rows would kill paging for good, with no list\n // left to scroll to bring it back.\n const isPagingIntoEmptyList = items.length === 0 && Boolean( hasMore );\n\n // Windowing scroll container: the virtualizer (owned by useListboxKeyboardNav) measures and\n // scrolls it, and useDragAutoScroll edge-scrolls it during a drag.\n const virtualScrollRef = useRef<HTMLDivElement>( null );\n const autoScroll = useDragAutoScroll( virtualScrollRef );\n\n // \u2500\u2500 Keyboard navigation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // The list is a single tab stop (role="listbox"); arrow keys move an "active" row via\n // aria-activedescendant instead of every row being its own tab stop - so Tab reaches the next\n // control/panel in one step regardless of list length.\n const listboxId = useId();\n const listRegionRef = useRef<HTMLDivElement>( null );\n const optionId = ( index: number ): string => `${listboxId}-opt-${index}`;\n\n // The active row is the keyboard-navigation cursor, so it should only be shown while the list\n // actually holds focus - otherwise the first row of every panel paints its active border on\n // mount and reads as a stray focus ring.\n const [ isFocused, setIsFocused ] = useState( false );\n\n // Reset key for the active row: keyed on the sorted values, so a pure reorder (same set, new\n // order) does not fire the reset and yank the active row back to the top mid-keyboard-reorder.\n // Memoized so the sort runs only when the item set actually changes, not on every re-render.\n const itemsKey = useMemo(\n () => items.map(( item ) => String( item.value )).sort().join( "\\n" ),\n [items]\n );\n\n const {\n activeIndex,\n setActiveIndex,\n moveActive,\n firstEnabledIndex,\n virtualizer: rowVirtualizer,\n shouldVirtualize\n } = useListboxKeyboardNav({\n itemCount: items.length,\n isItemDisabled: ( index ) => Boolean( items[index]?.isDisabled ),\n resetKey: itemsKey,\n scrollElementRef: virtualScrollRef,\n queryElementRef: listRegionRef,\n optionId,\n estimateSize: ESTIMATED_ROW_HEIGHT,\n gap: ROW_GAP,\n virtualizeThreshold: VIRTUALIZE_THRESHOLD\n });\n\n const isListFocusable = !disabled && items.length > 0;\n\n const handleListKeyDown = useTransferListPanelKeys({\n items,\n activeIndex,\n setActiveIndex,\n moveActive,\n firstEnabledIndex,\n reorderable,\n onToggle,\n onRemove,\n onMoveUp,\n onMoveDown,\n setIsFocused,\n isBlocked: isReplacing\n });\n\n // Shared row renderer so the windowed and full-render paths produce identical rows.\n const renderItem = ( item: ITransferListItem, index: number ): React.ReactElement => (\n <TransferListItem\n key={item.value}\n item={item}\n panel={panel}\n index={index}\n id={optionId( index )}\n active={isFocused && index === activeIndex}\n checked={isChecked( item.value )}\n reorderable={reorderable}\n disabled={disabled || Boolean( item.isDisabled )}\n isFirst={index === 0}\n isLast={index === items.length - 1}\n showTopIndicator={dropIndex === index}\n showBottomIndicator={index === items.length - 1 && dropIndex === items.length}\n onToggle={() => onToggle( item.value )}\n onRemove={onRemove ? () => onRemove( item.value ) : undefined}\n onMoveUp={onMoveUp ? () => onMoveUp( index ) : undefined}\n onMoveDown={onMoveDown ? () => onMoveDown( index ) : undefined}\n onDragStart={( e ) => onItemDragStart( e, item.value )}\n onDragEnd={onItemDragEnd}\n onDragOver={( e ) => onItemDragOver( e, index )}\n onDrop={onListDrop}\n />\n );\n\n // Below the loaded rows: the failed-page notice with its Retry, or the append loader. Only this\n // button retries, so a sentinel that never left the viewport cannot hammer a failing endpoint.\n const renderListFooter = (): React.ReactNode => {\n if ( loadMoreError !== undefined ) {\n return (\n <div className={loadMoreErrorRow()} role="alert">\n <span>{loadMoreError}</span>\n {typeof onRetryLoadMore === "function" && (\n <Button size="xs" variant="outline" color="secondary" onClick={onRetryLoadMore}>\n {retryLabel}\n </Button>\n )}\n </div>\n );\n }\n // Also spins in the gap between pages of an emptied list, so the cascade reads as one\n // continuous load instead of flickering an empty state between every page.\n return isLoadingMore || isPagingIntoEmptyList ? (\n <div className={loaderRow()} role="status" aria-label="Loading">\n <Loader size="sm" />\n </div>\n ) : null;\n };\n\n const handleVirtualDragOver = ( e: React.DragEvent ) => {\n onListDragOver( e );\n autoScroll.onDragOver( e );\n };\n\n // `Checkbox` renders a native input and has no `indeterminate` prop; it\'s a DOM property, so it has\n // to be written to the node. A callback ref, not an effect on `[selectAllIndeterminate]`: this row\n // unmounts whenever the panel replaces its rows, and a remount with the flag unchanged would not\n // re-run that effect \u2014 leaving a determinate checkbox over a partially-checked list. A callback ref\n // fires on every attach AND on identity change, covering both.\n const selectAllRef = useCallback(( node: HTMLInputElement | null ) => {\n if ( node ) {\n node.indeterminate = selectAllIndeterminate;\n }\n }, [selectAllIndeterminate]);\n\n return (\n <div className={panelClass()} data-testid={`transferListPanel-${panel}`}>\n <TransferListPanelHeader\n panel={panel}\n title={title}\n count={items.length}\n totalCount={totalCount}\n disabled={disabled}\n searchable={searchable}\n searchValue={searchValue}\n searchPlaceholder={searchPlaceholder}\n onSearchChange={onSearchChange}\n headerSlot={headerSlot}\n reloadTooltip={reloadTooltip}\n onReload={onReload}\n isReloading={isReloading}\n />\n\n <div\n ref={listRegionRef}\n className={listRegion()}\n role="listbox"\n aria-multiselectable="true"\n aria-label={typeof title === "string" ? title : undefined}\n tabIndex={isListFocusable ? 0 : -1}\n aria-busy={isLoading}\n // Dropped while replacing, so it never points at an id that is about to leave the DOM.\n aria-activedescendant={\n isListFocusable && !isReplacing && activeIndex >= 0 ? optionId( activeIndex ) : undefined\n }\n // Only light the active row for genuine keyboard focus. Starting a drag on a row also\n // focuses its listbox (a pointer interaction, so not :focus-visible); without this guard the\n // active cursor would paint a stray focus border on the new first row once the dragged row\n // leaves on drop.\n onFocus={( e ) => {\n if ( isKeyboardFocus( e.currentTarget )) {\n setIsFocused( true );\n }\n }}\n // A pointer interaction (including grabbing a row to drag) exits keyboard mode, mirroring\n // :focus-visible - so a drag never leaves the active-row border lit on the row that shifts\n // under the pointer once the dragged row is gone.\n onMouseDown={() => setIsFocused( false )}\n onBlur={() => setIsFocused( false )}\n onKeyDown={handleListKeyDown}\n >\n {selectAllCount >= 2 && !isReplacing && <div className={selectAllRow()}>\n <Checkbox\n ref={selectAllRef}\n size="sm"\n checked={selectAllChecked}\n disabled={disabled}\n label={`Select all (${selectAllCount})`}\n onChange={onToggleSelectAll}\n />\n </div>\n }\n {/* Loader, then error, then rows. The first two take the list\'s place so stale rows can\'t be\n clicked, but both keep the drag handlers: an error in Available must not break dragging\n items back out of Selected. role="alert" is assertive \u2014 the load did not do what was asked. */}\n {isLoading ? (\n <div\n className={replaceLoader()}\n role="status"\n aria-label="Loading"\n onDragOver={onListDragOver}\n onDrop={onListDrop}\n >\n <Loader size="sm" />\n </div>\n ) : loadError !== undefined ? (\n <div className={panelError()} role="alert" onDragOver={onListDragOver} onDrop={onListDrop}>\n {loadError}\n </div>\n ) : items.length === 0 && !isLoadingMore && !isPagingIntoEmptyList && loadMoreError === undefined ? (\n <div className={emptyWrap()} onDragOver={onListDragOver} onDrop={onListDrop}>\n <EmptyState imageVariant="no-data">\n <EmptyState.Content className={emptyTextClass()}>\n {emptyText}\n </EmptyState.Content>\n </EmptyState>\n </div>\n ) : shouldVirtualize ? (\n <div ref={virtualScrollRef} className={virtualScroll()} onDragOver={handleVirtualDragOver} onDrop={onListDrop}>\n <div className={virtualSizer()} style={{ height: rowVirtualizer.getTotalSize() }}>\n {rowVirtualizer.getVirtualItems().map(( virtualRow ) => (\n <div\n key={items[virtualRow.index].value}\n data-index={virtualRow.index}\n ref={rowVirtualizer.measureElement}\n className="absolute inset-x-0 top-0"\n style={{ transform: `translateY(${virtualRow.start}px)` }}\n >\n {renderItem( items[virtualRow.index], virtualRow.index )}\n </div>\n ))}\n {/* Sentinel pinned to the bottom of the full scroll height: clipped by the scroll\n container until the user reaches the end, where it triggers onLoadMore. */}\n <div ref={sentinelRef} className="absolute bottom-0 h-px w-px" aria-hidden="true" />\n </div>\n {renderListFooter()}\n </div>\n ) : (\n <Scrollbar className={listWrap()} onDragOver={onListDragOver} onDrop={onListDrop}>\n <div className={list()}>\n {items.map(( item, index ) => renderItem( item, index ))}\n {renderListFooter()}\n <div ref={sentinelRef} className="h-px" aria-hidden="true" />\n </div>\n </Scrollbar>\n )}\n {showDropOverlay && (\n <div className={dropOverlay()} data-testid="transferListDropOverlay" aria-hidden="true">\n Drop Here\n </div>\n )}\n </div>\n\n <div className={panelFooter()}>\n <Button\n size="xs"\n variant="outline"\n color="primary"\n disabled={moveDisabled}\n prefixIcon={moveIconSide === "left" ? iconList.leftArrowLong : undefined}\n suffixIcon={moveIconSide === "right" ? iconList.rightArrowLong : undefined}\n onClick={onMove}\n >\n {moveCount > 0 ? `${moveLabel} (${moveCount})` : moveLabel}\n </Button>\n </div>\n </div>\n );\n}\n\nTransferListPanel.displayName = "TransferListPanel";\n'
|
|
4164
3980
|
},
|
|
4165
3981
|
{
|
|
4166
3982
|
"name": "transferListItem.tsx",
|
|
4167
|
-
"content": 'import * as React from "react";\n\nimport { useIsTruncated } from "@hooks";\nimport { Checkbox } from "../checkbox";\nimport { ADPIcon, iconList } from "../adpIcon";\nimport { transferListVariants } from "./transferListVariants";\nimport type { ITransferListItem, TTransferPanel } from "./types";\n\ninterface ITransferListItemProps {\n item: ITransferListItem;\n panel: TTransferPanel;\n index: number;\n /** Row element id, referenced by the panel listbox\'s aria-activedescendant. */\n id: string;\n checked: boolean;\n /** The row the keyboard navigation has landed on (highlighted, no DOM focus). */\n active: boolean;\n reorderable: boolean;\n disabled: boolean;\n isFirst: boolean;\n isLast: boolean;\n showTopIndicator: boolean;\n showBottomIndicator: boolean;\n onToggle: () => void;\n onRemove?: () => void;\n onMoveUp?: () => void;\n onMoveDown?: () => void;\n onDragStart: ( e: React.DragEvent ) => void;\n onDragEnd: () => void;\n onDragOver: ( e: React.DragEvent ) => void;\n onDrop: ( e: React.DragEvent ) => void;\n}\n\nconst stopPropagation = ( e: React.SyntheticEvent ) => e.stopPropagation();\n\n/**\n * A single transfer list row: drag handle + position badge (selected, reorderable\n * only), checkbox, label, and remove / reorder controls.\n */\nexport function TransferListItem({\n item,\n panel,\n index,\n id,\n checked,\n active,\n reorderable,\n disabled,\n isFirst,\n isLast,\n showTopIndicator,\n showBottomIndicator,\n onToggle,\n onRemove,\n onMoveUp,\n onMoveDown,\n onDragStart,\n onDragEnd,\n onDragOver,\n onDrop\n}: ITransferListItemProps ): React.ReactElement {\n const {\n row,\n dragHandle,\n badge,\n rowLabelWrap,\n rowLabel,\n rowActions,\n removeButton,\n reorderButton,\n dropIndicator: topDropIndicator\n } = transferListVariants({ panel, checked, active, isDisabled: disabled, dropIndicatorPosition: "before" });\n const { dropIndicator: bottomDropIndicator } = transferListVariants({\n panel, checked, isDisabled: disabled, dropIndicatorPosition: "after"\n });\n\n const { ref: labelRef, containerRef: labelWrapRef, isTruncated: isLabelTruncated } = useIsTruncated<HTMLSpanElement>();\n\n const isSelectedPanel = panel === "selected";\n // The position badge and up/down arrows only appear on the reorderable\n // selected panel; the grip drag affordance shows on every enabled row.\n const showReorderAffordances = isSelectedPanel && reorderable;\n\n return (\n <div\n id={id}\n role="option"\n aria-selected={checked}\n aria-disabled={disabled}\n // Rows are not individual tab stops: the panel\'s list is a single tab stop and arrow keys\n // drive navigation via aria-activedescendant (see TransferListPanel), so
|
|
3983
|
+
"content": 'import * as React from "react";\n\nimport { useIsTruncated } from "@hooks";\nimport { Checkbox } from "../checkbox";\nimport { ADPIcon, iconList } from "../adpIcon";\nimport { transferListVariants } from "./transferListVariants";\nimport type { ITransferListItem, TTransferPanel } from "./types";\n\ninterface ITransferListItemProps {\n item: ITransferListItem;\n panel: TTransferPanel;\n index: number;\n /** Row element id, referenced by the panel listbox\'s aria-activedescendant. */\n id: string;\n checked: boolean;\n /** The row the keyboard navigation has landed on (highlighted, no DOM focus). */\n active: boolean;\n reorderable: boolean;\n disabled: boolean;\n isFirst: boolean;\n isLast: boolean;\n showTopIndicator: boolean;\n showBottomIndicator: boolean;\n onToggle: () => void;\n onRemove?: () => void;\n onMoveUp?: () => void;\n onMoveDown?: () => void;\n onDragStart: ( e: React.DragEvent ) => void;\n onDragEnd: () => void;\n onDragOver: ( e: React.DragEvent ) => void;\n onDrop: ( e: React.DragEvent ) => void;\n}\n\nconst stopPropagation = ( e: React.SyntheticEvent ) => e.stopPropagation();\n\n/**\n * A single transfer list row: drag handle + position badge (selected, reorderable\n * only), checkbox, label, and remove / reorder controls.\n */\nexport function TransferListItem({\n item,\n panel,\n index,\n id,\n checked,\n active,\n reorderable,\n disabled,\n isFirst,\n isLast,\n showTopIndicator,\n showBottomIndicator,\n onToggle,\n onRemove,\n onMoveUp,\n onMoveDown,\n onDragStart,\n onDragEnd,\n onDragOver,\n onDrop\n}: ITransferListItemProps ): React.ReactElement {\n const {\n row,\n dragHandle,\n badge,\n rowLabelWrap,\n rowLabel,\n rowActions,\n removeButton,\n reorderButton,\n dropIndicator: topDropIndicator\n } = transferListVariants({ panel, checked, active, isDisabled: disabled, dropIndicatorPosition: "before" });\n const { dropIndicator: bottomDropIndicator } = transferListVariants({\n panel, checked, isDisabled: disabled, dropIndicatorPosition: "after"\n });\n\n const { ref: labelRef, containerRef: labelWrapRef, isTruncated: isLabelTruncated } = useIsTruncated<HTMLSpanElement>();\n\n const isSelectedPanel = panel === "selected";\n // The position badge and up/down arrows only appear on the reorderable\n // selected panel; the grip drag affordance shows on every enabled row.\n const showReorderAffordances = isSelectedPanel && reorderable;\n\n return (\n <div\n id={id}\n role="option"\n aria-selected={checked}\n aria-disabled={disabled}\n // Rows are not individual tab stops: the panel\'s list is a single tab stop and arrow keys\n // drive navigation via aria-activedescendant (see TransferListPanel), so Tab never gets\n // trapped inside a long list. Enter/Space toggling is handled at the listbox level.\n tabIndex={-1}\n draggable={!disabled}\n data-index={index}\n data-active={active || undefined}\n data-truncated={isLabelTruncated || undefined}\n className={row()}\n onClick={onToggle}\n onDragStart={onDragStart}\n onDragEnd={onDragEnd}\n onDragOver={onDragOver}\n onDrop={onDrop}\n >\n {/* Absolutely positioned relative to the row: the dragover handler reads this row\'s\n bounding rect on every tick, so the indicator itself must never affect that layout. */}\n {showTopIndicator && <div className={topDropIndicator()} data-testid="transferListDropIndicator" aria-hidden="true" />}\n {showBottomIndicator && <div className={bottomDropIndicator()} data-testid="transferListDropIndicator" aria-hidden="true" />}\n {showReorderAffordances && <span className={badge()}>{index + 1}</span>}\n {!disabled && (\n <span className={dragHandle()} aria-hidden="true">\n <ADPIcon icon={iconList.grip} size="xs" />\n </span>\n )}\n {/* Row-internal controls are not individual tab stops (tabIndex -1): the panel listbox is\n the single tab stop and drives them from the active row (Enter/Space toggles, Delete\n removes, Alt+Arrow reorders). This keeps a long list from trapping Tab. */}\n <span className="flex" onClick={stopPropagation}>\n <Checkbox checked={checked} disabled={disabled} size="sm" tabIndex={-1} onChange={onToggle} />\n </span>\n <span ref={labelWrapRef} className={rowLabelWrap()}>\n <span ref={labelRef} className={rowLabel()}>{item.label}</span>\n </span>\n <span className={rowActions()}>\n {showReorderAffordances && (\n <>\n <button\n type="button"\n aria-label="Move up"\n tabIndex={-1}\n disabled={isFirst}\n className={reorderButton()}\n onClick={( e ) => {\n stopPropagation( e );\n onMoveUp?.();\n }}\n >\n <ADPIcon icon={iconList.upArrow} size="xs" />\n </button>\n <button\n type="button"\n aria-label="Move down"\n tabIndex={-1}\n disabled={isLast}\n className={reorderButton()}\n onClick={( e ) => {\n stopPropagation( e );\n onMoveDown?.();\n }}\n >\n <ADPIcon icon={iconList.downArrow} size="xs" />\n </button>\n </>\n )}\n {isSelectedPanel && (\n <button\n type="button"\n aria-label={`Remove ${item.value}`}\n tabIndex={-1}\n className={removeButton()}\n onClick={( e ) => {\n stopPropagation( e );\n onRemove?.();\n }}\n >\n <ADPIcon icon={iconList.cross} size="xs" />\n </button>\n )}\n </span>\n </div>\n );\n}\n\nTransferListItem.displayName = "TransferListItem";\n'
|
|
4168
3984
|
},
|
|
4169
3985
|
{
|
|
4170
3986
|
"name": "transferList.tsx",
|
|
@@ -4173,18 +3989,20 @@ import { useMemo, useState } from "react";
|
|
|
4173
3989
|
|
|
4174
3990
|
import { TransferListPanel } from "./transferListPanel";
|
|
4175
3991
|
import { useTransferList } from "./useTransferList";
|
|
3992
|
+
import { useTransferListSource } from "./useTransferListSource";
|
|
4176
3993
|
import { transferListVariants } from "./transferListVariants";
|
|
4177
3994
|
import { matchesQuery } from "@utils";
|
|
3995
|
+
import { useIgnoredPropWarning } from "@hooks";
|
|
4178
3996
|
import type { ITransferListProps, TTransferListValue, TTransferPanel } from "./types";
|
|
4179
3997
|
|
|
4180
3998
|
/**
|
|
4181
3999
|
* A fully-controlled two-panel transfer list. Move items between the Available
|
|
4182
4000
|
* and Selected panels via checkboxes + arrow controls or native drag-and-drop.
|
|
4183
4001
|
* Rendering and ownership of any surrounding chrome (modal, footer) is left to
|
|
4184
|
-
* the consumer.
|
|
4002
|
+
* the consumer. The forwarded ref lands on the wrapper \`<div>\`.
|
|
4185
4003
|
*/
|
|
4186
|
-
export function TransferList({
|
|
4187
|
-
availableItems,
|
|
4004
|
+
export const TransferList = React.forwardRef<HTMLDivElement, ITransferListProps>( function TransferList({
|
|
4005
|
+
availableItems: availableItemsProp,
|
|
4188
4006
|
selectedItems,
|
|
4189
4007
|
onChange,
|
|
4190
4008
|
availablePanelTitle = "Available Items",
|
|
@@ -4206,11 +4024,67 @@ export function TransferList({
|
|
|
4206
4024
|
hasMoreAvailable = false,
|
|
4207
4025
|
onLoadMoreAvailable,
|
|
4208
4026
|
isLoadingMoreAvailable = false,
|
|
4027
|
+
isLoadingAvailable = false,
|
|
4028
|
+
availableLoadError,
|
|
4029
|
+
availableLoadMoreError,
|
|
4030
|
+
onRetryLoadMoreAvailable,
|
|
4031
|
+
retryLabel = "Retry",
|
|
4032
|
+
availableTotalCount,
|
|
4033
|
+
loadAvailableOptions,
|
|
4034
|
+
initialAvailableOptions,
|
|
4035
|
+
// Left undefined here, not defaulted: sync mode warns on a \`prefetch\` the consumer actually passed,
|
|
4036
|
+
// which an eager default would erase. Resolved in useTransferListSource, where it becomes a trigger.
|
|
4037
|
+
prefetch,
|
|
4038
|
+
refetchOnClear = false,
|
|
4039
|
+
optionsKey,
|
|
4040
|
+
availableFilterDebounceMs = 300,
|
|
4041
|
+
loadErrorMessage,
|
|
4042
|
+
loadMoreErrorMessage,
|
|
4043
|
+
onLoadError,
|
|
4209
4044
|
disabled = false,
|
|
4210
4045
|
availableEmptyText = "No Data Found!",
|
|
4211
4046
|
selectedEmptyText = "No Data Found!",
|
|
4212
4047
|
className
|
|
4213
|
-
}
|
|
4048
|
+
}, forwardedRef ) {
|
|
4049
|
+
// Resolves the available panel's source. In async mode the component owns that pool (and its
|
|
4050
|
+
// debounced, server-driven search); otherwise every value below is the corresponding prop verbatim.
|
|
4051
|
+
const availableSource = useTransferListSource({
|
|
4052
|
+
availableItems: availableItemsProp,
|
|
4053
|
+
selectedItems,
|
|
4054
|
+
loadAvailableOptions,
|
|
4055
|
+
initialAvailableOptions,
|
|
4056
|
+
prefetch,
|
|
4057
|
+
refetchOnClear,
|
|
4058
|
+
optionsKey,
|
|
4059
|
+
availableFilterDebounceMs,
|
|
4060
|
+
loadErrorMessage,
|
|
4061
|
+
loadMoreErrorMessage,
|
|
4062
|
+
onLoadError,
|
|
4063
|
+
hasMoreAvailable,
|
|
4064
|
+
onLoadMoreAvailable,
|
|
4065
|
+
isLoadingMoreAvailable,
|
|
4066
|
+
isLoadingAvailable,
|
|
4067
|
+
availableLoadError,
|
|
4068
|
+
availableLoadMoreError,
|
|
4069
|
+
onRetryLoadMoreAvailable,
|
|
4070
|
+
availableTotalCount,
|
|
4071
|
+
availableSearchTerm,
|
|
4072
|
+
onAvailableSearchChange
|
|
4073
|
+
});
|
|
4074
|
+
const {
|
|
4075
|
+
availableItems,
|
|
4076
|
+
availableSearchTerm: availableSearchValue,
|
|
4077
|
+
onAvailableSearchChange: onAvailableSearch
|
|
4078
|
+
} = availableSource;
|
|
4079
|
+
|
|
4080
|
+
// No search input on either panel means nothing can produce a query, so a controlled-search pair has
|
|
4081
|
+
// no input to drive and no keystroke to report.
|
|
4082
|
+
useIgnoredPropWarning(
|
|
4083
|
+
!searchable && ( onAvailableSearchChange !== undefined || onSelectedSearchChange !== undefined ),
|
|
4084
|
+
"TransferList: the controlled-search props are ignored when \`searchable={false}\` \u2014 " +
|
|
4085
|
+
"there are no search inputs to drive."
|
|
4086
|
+
);
|
|
4087
|
+
|
|
4214
4088
|
const {
|
|
4215
4089
|
isChecked,
|
|
4216
4090
|
toggleCheck,
|
|
@@ -4228,12 +4102,12 @@ export function TransferList({
|
|
|
4228
4102
|
const [ selectedQuery, setSelectedQuery ] = useState( "" );
|
|
4229
4103
|
const [ dropTarget, setDropTarget ] = useState<{ panel: TTransferPanel; index: number } | null>( null );
|
|
4230
4104
|
|
|
4231
|
-
const availableValue =
|
|
4105
|
+
const availableValue = availableSearchValue === undefined ? availableQuery : availableSearchValue;
|
|
4232
4106
|
const selectedValue = selectedSearchTerm === undefined ? selectedQuery : selectedSearchTerm;
|
|
4233
4107
|
|
|
4234
4108
|
const handleAvailableSearch = ( query: string ) => {
|
|
4235
4109
|
setAvailableQuery( query );
|
|
4236
|
-
|
|
4110
|
+
onAvailableSearch?.( query );
|
|
4237
4111
|
};
|
|
4238
4112
|
const handleSelectedSearch = ( query: string ) => {
|
|
4239
4113
|
setSelectedQuery( query );
|
|
@@ -4242,32 +4116,51 @@ export function TransferList({
|
|
|
4242
4116
|
|
|
4243
4117
|
// When a search handler is supplied the parent owns filtering; otherwise filter
|
|
4244
4118
|
// the loaded items client-side. Memoized so the repeated filter passes don't re-run on
|
|
4245
|
-
// every render (drag-over/hover updates fire frequently and the lists can be large).
|
|
4119
|
+
// every render (drag-over/hover updates fire frequently and the lists can be large). Keyed on
|
|
4120
|
+
// WHETHER a handler exists rather than on its identity: an inline handler prop \u2014 or the async
|
|
4121
|
+
// source's own \u2014 would otherwise change every render and defeat the memo entirely.
|
|
4122
|
+
const isAvailableSearchExternal = onAvailableSearch !== undefined;
|
|
4123
|
+
const isSelectedSearchExternal = onSelectedSearchChange !== undefined;
|
|
4246
4124
|
const visibleAvailable = useMemo(
|
|
4247
|
-
() => (
|
|
4248
|
-
[
|
|
4125
|
+
() => ( isAvailableSearchExternal ? availableItems : availableItems.filter(( item ) => matchesQuery( item, availableValue ))),
|
|
4126
|
+
[ isAvailableSearchExternal, availableItems, availableValue ]
|
|
4249
4127
|
);
|
|
4250
4128
|
const visibleSelected = useMemo(
|
|
4251
|
-
() => (
|
|
4252
|
-
[
|
|
4129
|
+
() => ( isSelectedSearchExternal ? selectedItems : selectedItems.filter(( item ) => matchesQuery( item, selectedValue ))),
|
|
4130
|
+
[ isSelectedSearchExternal, selectedItems, selectedValue ]
|
|
4253
4131
|
);
|
|
4254
4132
|
|
|
4255
|
-
// "Select all"
|
|
4256
|
-
//
|
|
4257
|
-
//
|
|
4258
|
-
const
|
|
4259
|
-
const
|
|
4133
|
+
// "Select all" addresses only what the search leaves VISIBLE, so it can never reach an item the
|
|
4134
|
+
// user cannot see. It checks and unchecks that subset without touching the rest of the panel's
|
|
4135
|
+
// checked set, which is what lets a selection made under one query survive the next.
|
|
4136
|
+
const visibleMovableAvailable = useMemo(() => visibleAvailable.filter(( item ) => !item.isDisabled ), [visibleAvailable]);
|
|
4137
|
+
const visibleMovableSelected = useMemo(() => visibleSelected.filter(( item ) => !item.isDisabled ), [visibleSelected]);
|
|
4138
|
+
|
|
4139
|
+
// The move buttons keep the wider scope: they move everything currently checked, including rows
|
|
4140
|
+
// the active filter is hiding, so their count stays an honest tally of the selection. With a
|
|
4141
|
+
// paged source that scope is what has been LOADED, not what the server holds.
|
|
4260
4142
|
const checkedAvailable = useMemo(
|
|
4261
|
-
() =>
|
|
4262
|
-
[
|
|
4143
|
+
() => availableItems.filter(( item ) => !item.isDisabled && isChecked( "available", item.value )),
|
|
4144
|
+
[ availableItems, isChecked ]
|
|
4263
4145
|
);
|
|
4264
4146
|
const checkedSelected = useMemo(
|
|
4265
|
-
() =>
|
|
4266
|
-
[
|
|
4147
|
+
() => selectedItems.filter(( item ) => !item.isDisabled && isChecked( "selected", item.value )),
|
|
4148
|
+
[ selectedItems, isChecked ]
|
|
4267
4149
|
);
|
|
4268
4150
|
|
|
4269
|
-
const
|
|
4270
|
-
|
|
4151
|
+
const visibleCheckedAvailableCount = useMemo(
|
|
4152
|
+
() => visibleMovableAvailable.filter(( item ) => isChecked( "available", item.value )).length,
|
|
4153
|
+
[ visibleMovableAvailable, isChecked ]
|
|
4154
|
+
);
|
|
4155
|
+
const visibleCheckedSelectedCount = useMemo(
|
|
4156
|
+
() => visibleMovableSelected.filter(( item ) => isChecked( "selected", item.value )).length,
|
|
4157
|
+
[ visibleMovableSelected, isChecked ]
|
|
4158
|
+
);
|
|
4159
|
+
|
|
4160
|
+
const availableAllChecked =
|
|
4161
|
+
visibleMovableAvailable.length > 0 && visibleCheckedAvailableCount === visibleMovableAvailable.length;
|
|
4162
|
+
const selectedAllChecked =
|
|
4163
|
+
visibleMovableSelected.length > 0 && visibleCheckedSelectedCount === visibleMovableSelected.length;
|
|
4271
4164
|
|
|
4272
4165
|
const makeDragStart = ( panel: TTransferPanel ) => ( e: React.DragEvent, value: TTransferListValue ) => {
|
|
4273
4166
|
if ( disabled ) {
|
|
@@ -4387,7 +4280,7 @@ export function TransferList({
|
|
|
4387
4280
|
const { base } = transferListVariants();
|
|
4388
4281
|
|
|
4389
4282
|
return (
|
|
4390
|
-
<div className={base({ class: className })}>
|
|
4283
|
+
<div ref={forwardedRef} className={base({ class: className })}>
|
|
4391
4284
|
<TransferListPanel
|
|
4392
4285
|
panel="available"
|
|
4393
4286
|
title={availablePanelTitle}
|
|
@@ -4403,14 +4296,20 @@ export function TransferList({
|
|
|
4403
4296
|
reloadTooltip={reloadTooltip}
|
|
4404
4297
|
onReload={onReload}
|
|
4405
4298
|
isReloading={isReloading}
|
|
4406
|
-
hasMore={hasMoreAvailable}
|
|
4407
|
-
onLoadMore={onLoadMoreAvailable}
|
|
4408
|
-
isLoadingMore={isLoadingMoreAvailable}
|
|
4299
|
+
hasMore={availableSource.hasMoreAvailable}
|
|
4300
|
+
onLoadMore={availableSource.onLoadMoreAvailable}
|
|
4301
|
+
isLoadingMore={availableSource.isLoadingMoreAvailable}
|
|
4302
|
+
isLoading={availableSource.isLoadingAvailable}
|
|
4303
|
+
loadError={availableSource.availableLoadError}
|
|
4304
|
+
loadMoreError={availableSource.availableLoadMoreError}
|
|
4305
|
+
onRetryLoadMore={availableSource.onRetryLoadMoreAvailable}
|
|
4306
|
+
retryLabel={retryLabel}
|
|
4307
|
+
totalCount={availableSource.availableTotalCount}
|
|
4409
4308
|
selectAllChecked={availableAllChecked}
|
|
4410
|
-
selectAllIndeterminate={
|
|
4411
|
-
selectAllCount={
|
|
4309
|
+
selectAllIndeterminate={visibleCheckedAvailableCount > 0 && !availableAllChecked}
|
|
4310
|
+
selectAllCount={visibleMovableAvailable.length}
|
|
4412
4311
|
onToggleSelectAll={() =>
|
|
4413
|
-
setPanelChecked( "available",
|
|
4312
|
+
setPanelChecked( "available", visibleMovableAvailable.map(( item ) => item.value ), !availableAllChecked )
|
|
4414
4313
|
}
|
|
4415
4314
|
moveLabel={moveToSelectedLabel}
|
|
4416
4315
|
moveCount={checkedAvailable.length}
|
|
@@ -4441,10 +4340,10 @@ export function TransferList({
|
|
|
4441
4340
|
onSearchChange={handleSelectedSearch}
|
|
4442
4341
|
headerSlot={selectedPanelHeaderSlot}
|
|
4443
4342
|
selectAllChecked={selectedAllChecked}
|
|
4444
|
-
selectAllIndeterminate={
|
|
4445
|
-
selectAllCount={
|
|
4343
|
+
selectAllIndeterminate={visibleCheckedSelectedCount > 0 && !selectedAllChecked}
|
|
4344
|
+
selectAllCount={visibleMovableSelected.length}
|
|
4446
4345
|
onToggleSelectAll={() =>
|
|
4447
|
-
setPanelChecked( "selected",
|
|
4346
|
+
setPanelChecked( "selected", visibleMovableSelected.map(( item ) => item.value ), !selectedAllChecked )
|
|
4448
4347
|
}
|
|
4449
4348
|
moveLabel={moveToAvailableLabel}
|
|
4450
4349
|
moveCount={checkedSelected.length}
|
|
@@ -4466,18 +4365,18 @@ export function TransferList({
|
|
|
4466
4365
|
/>
|
|
4467
4366
|
</div>
|
|
4468
4367
|
);
|
|
4469
|
-
}
|
|
4368
|
+
});
|
|
4470
4369
|
|
|
4471
4370
|
TransferList.displayName = "TransferList";
|
|
4472
4371
|
`
|
|
4473
4372
|
},
|
|
4474
4373
|
{
|
|
4475
4374
|
"name": "index.ts",
|
|
4476
|
-
"content": 'export { TransferList } from "./transferList";\nexport { transferListVariants } from "./transferListVariants";\nexport type {\n ITransferListProps,\n ITransferListItem,\n TTransferListValue,\n TTransferPanel\n} from "./types";\n'
|
|
4375
|
+
"content": 'export { TransferList } from "./transferList";\nexport { transferListVariants } from "./transferListVariants";\nexport type {\n ITransferListProps,\n ITransferListItem,\n TTransferListValue,\n TTransferPanel,\n TTransferListLoadOptions,\n TTransferListPrefetch\n} from "./types";\n'
|
|
4477
4376
|
},
|
|
4478
4377
|
{
|
|
4479
4378
|
"name": "README.md",
|
|
4480
|
-
"content": '# TransferList Component\n\n## Component Overview\n\nThe TransferList is a fully-controlled two-panel widget for moving items between an\n**Available** list and a **Selected** list. Each panel has a **"Select all" checkbox**\nabove its list and a **move button** below it that transfers the currently-checked items\nto the other panel \u2014 "Add to select" on Available, "Remove from selected" on Selected.\nItems can also be moved by native HTML5 drag-and-drop. It is intentionally decoupled\nfrom any surrounding chrome \u2014 render it inside a `Modal`, a `Card`, or a page section\nand own the surrounding layout yourself. `MultiSelectTransfer` composes it inside a modal.\n\n**When to use:**\n- Assigning a subset of items (permissions, columns, members) from a larger pool\n- Building an ordered selection where position matters (enable `reorderable`)\n- Any "pick from a long, possibly paginated list" workflow\n\n**Component Architecture:**\n- Fully controlled: `availableItems`, `selectedItems`, and `onChange` are owned by the consumer\n- Styled with `tailwind-variants` (`tv()`) slots\n- Native drag-and-drop (no extra dependency) for cross-panel transfer and reorder\n- Infinite scroll on the Available panel via an `IntersectionObserver` sentinel\n- Responsive: panels sit side-by-side on `sm`+ and stack vertically on small screens\n- Reuses `Checkbox`, `Button`, `Scrollbar`, `Loader`, and `ADPIcon`\n\n## Basic Usage\n\n```tsx\nimport { useState } from "react";\nimport { TransferList, type ITransferListItem } from "@cloudwick/astral-ui";\n\nexport function Example() {\n const [available, setAvailable] = useState<ITransferListItem[]>([\n { value: "apple", label: "Apple" },\n { value: "banana", label: "Banana" }\n ]);\n const [selected, setSelected] = useState<ITransferListItem[]>([]);\n\n return (\n <TransferList\n availableItems={available}\n selectedItems={selected}\n onChange={( nextAvailable, nextSelected ) => {\n setAvailable( nextAvailable );\n setSelected( nextSelected );\n }}\n />\n );\n}\n```\n\n## Props\n\n| Prop | Type | Default | Description |\n|---|---|---|---|\n| `availableItems` | `ITransferListItem[]` | \u2014 | Items in the left panel. Controlled. |\n| `selectedItems` | `ITransferListItem[]` | \u2014 | Items in the right panel. Controlled. |\n| `onChange` | `( availableItems, selectedItems ) => void` | \u2014 | Fired on every move/reorder. |\n| `availablePanelTitle` / `selectedPanelTitle` | `ReactNode` | `"Available Items"` / `"Selected Items"` | Panel headings. |\n| `searchable` | `boolean` | `true` | Show the per-panel search inputs. |\n| `availableSearchTerm` / `onAvailableSearchChange` | `string` / `fn` | \u2014 | Controlled search for the available panel (parent owns filtering). |\n| `selectedSearchTerm` / `onSelectedSearchChange` | `string` / `fn` | \u2014 | Controlled search for the selected panel. |\n| `searchPlaceholder` | `string` | `"Search here"` | Placeholder for both inputs. |\n| `availablePanelHeaderSlot` / `selectedPanelHeaderSlot` | `ReactNode` | \u2014 | Custom content under each search input. |\n| `moveToSelectedLabel` | `string` | `"Add to select"` | Label for the available panel\'s move button. A `(count)` suffix is appended when items are checked. |\n| `moveToAvailableLabel` | `string` | `"Remove from selected"` | Label for the selected panel\'s move button. A `(count)` suffix is appended when items are checked. |\n| `reorderable` | `boolean` | `false` | Enable drag handles, position badges and up/down arrows on the selected panel. |\n| `showReload` / `onReload` / `isReloading` | `boolean` / `fn` / `boolean` | \u2014 | Reload button on the available panel header. |\n| `hasMoreAvailable` / `onLoadMoreAvailable` / `isLoadingMoreAvailable` | `boolean` / `fn` / `boolean` | \u2014 | Infinite scroll for the available panel. |\n| `disabled` | `boolean` | `false` | Disable all interaction. |\n| `availableEmptyText` / `selectedEmptyText` | `ReactNode` | `"No Data Found!"` | Empty-state copy. |\n| `className` | `string` | \u2014 | Extra classes on the root. |\n\n## Selecting and moving items\n\n- **Per-row checkboxes:** check individual rows in either panel.\n- **Select all:** the checkbox above each list checks/clears every non-disabled item in\n that panel. It reflects an indeterminate state when only some rows are checked, and\n operates on the **full list** \u2014 items hidden by an active search/filter are still\n included.\n- **Move button:** the button below each list moves the currently-checked items to the\n other panel (skipping disabled items) and clears the checkboxes. It shows the checked\n count and is disabled when nothing is checked. To move everything, click "Select all"\n then the move button.\n\n## Drag-and-drop\n\n- **Cross-panel transfer:** drag any row onto the opposite panel to move it (honoring\n `isDisabled`). Same effect as checking the row and clicking the move button. While a drag is in progress, every\n panel that is a valid, position-irrelevant drop target shows a sticky "Drop Here"\n overlay across its whole content area, for the entire drag \u2014 not just while hovering\n it. This is consistent on both panels: dragging a Selected row always shows the\n overlay on Available, and dragging an Available row shows it on Selected whenever\n `reorderable` is not set (the drop always appends, regardless of which row is\n hovered).\n- **Reorder within Selected:** only when `reorderable` \u2014 drop a selected row (or an\n incoming available row) at a new position, tracked with a precise per-row insertion\n line instead of the overlay, or use the up/down arrows. Without `reorderable`,\n dragging a selected row within Selected is a no-op and shows neither the overlay nor\n an indicator.\n- The **Available panel is never sortable**: Available rows are draggable solely to enable\n transfer to Selected; dropping an Available row within Available is a no-op and shows\n no overlay or indicator.\n\n## Notes\n\n- Search is both controlled and uncontrolled per panel. When a search-change handler is\n provided the parent owns filtering; otherwise items are filtered client-side.\n- Client-side search matches an item\'s `searchValue` first, then a string `label`, then its\n `value`. Set `searchValue` on items whose `label` is custom JSX so they remain findable by\n their visible text (a ReactNode `label` is otherwise matched only against `value`).\n- Because the component is controlled, "pending until confirm" semantics (e.g. a modal\n with Cancel/Done) are owned by the parent \u2014 see `MultiSelectTransfer`.\n'
|
|
4379
|
+
"content": '# TransferList Component\n\n## Component Overview\n\nThe TransferList is a fully-controlled two-panel widget for moving items between an\n**Available** list and a **Selected** list. Each panel has a **"Select all" checkbox**\nabove its list and a **move button** below it that transfers the currently-checked items\nto the other panel \u2014 "Add to select" on Available, "Remove from selected" on Selected.\nItems can also be moved by native HTML5 drag-and-drop. It is intentionally decoupled\nfrom any surrounding chrome \u2014 render it inside a `Modal`, a `Card`, or a page section\nand own the surrounding layout yourself. `MultiSelectTransfer` composes it inside a modal.\n\n**When to use:**\n- Assigning a subset of items (permissions, columns, members) from a larger pool\n- Building an ordered selection where position matters (enable `reorderable`)\n- Any "pick from a long, possibly paginated list" workflow\n\n**Component Architecture:**\n- Fully controlled: `availableItems`, `selectedItems`, and `onChange` are owned by the consumer\n- Styled with `tailwind-variants` (`tv()`) slots\n- Native drag-and-drop (no extra dependency) for cross-panel transfer and reorder\n- Infinite scroll on the Available panel via an `IntersectionObserver` sentinel\n- Responsive: panels sit side-by-side on `sm`+ and stack vertically on small screens\n- Reuses `Checkbox`, `Button`, `Scrollbar`, `Loader`, and `ADPIcon`\n\n## Basic Usage\n\n```tsx\nimport { useState } from "react";\nimport { TransferList, type ITransferListItem } from "@cloudwick/astral-ui";\n\nexport function Example() {\n const [available, setAvailable] = useState<ITransferListItem[]>([\n { value: "apple", label: "Apple" },\n { value: "banana", label: "Banana" }\n ]);\n const [selected, setSelected] = useState<ITransferListItem[]>([]);\n\n return (\n <TransferList\n availableItems={available}\n selectedItems={selected}\n onChange={( nextAvailable, nextSelected ) => {\n setAvailable( nextAvailable );\n setSelected( nextSelected );\n }}\n />\n );\n}\n```\n\n## Props\n\n| Prop | Type | Default | Description |\n|---|---|---|---|\n| `availableItems` | `ITransferListItem[]` | \u2014 | Items in the left panel. Controlled. Optional and **ignored** (dev warning) when `loadAvailableOptions` is set. |\n| `selectedItems` | `ITransferListItem[]` | \u2014 | Items in the right panel. Controlled. |\n| `onChange` | `( availableItems, selectedItems ) => void` | \u2014 | Fired on every move/reorder. |\n| `availablePanelTitle` / `selectedPanelTitle` | `ReactNode` | `"Available Items"` / `"Selected Items"` | Panel headings. |\n| `searchable` | `boolean` | `true` | Show the per-panel search inputs. `false` hides both; each panel\'s listbox owns focus either way, so keyboard navigation, drag-and-drop, "Select all" and the move buttons are untouched \u2014 only narrowing a panel is lost. `MultiSelectTransfer` forwards its own `searchable` here. |\n| `availableSearchTerm` / `onAvailableSearchChange` | `string` / `fn` | \u2014 | Controlled search for the available panel (parent owns filtering). |\n| `selectedSearchTerm` / `onSelectedSearchChange` | `string` / `fn` | \u2014 | Controlled search for the selected panel. |\n| `searchPlaceholder` | `string` | `"Search here"` | Placeholder for both inputs. |\n| `availablePanelHeaderSlot` / `selectedPanelHeaderSlot` | `ReactNode` | \u2014 | Custom content under each search input. |\n| `moveToSelectedLabel` | `string` | `"Add to select"` | Label for the available panel\'s move button. A `(count)` suffix is appended when items are checked. |\n| `moveToAvailableLabel` | `string` | `"Remove from selected"` | Label for the selected panel\'s move button. A `(count)` suffix is appended when items are checked. |\n| `reorderable` | `boolean` | `false` | Enable drag handles, position badges and up/down arrows on the selected panel. |\n| `showReload` / `onReload` / `isReloading` | `boolean` / `fn` / `boolean` | \u2014 | Reload button on the available panel header. |\n| `hasMoreAvailable` / `onLoadMoreAvailable` / `isLoadingMoreAvailable` | `boolean` / `fn` / `boolean` | \u2014 | Infinite scroll for the available panel. The loader **appends** below the rows. While `hasMoreAvailable` is true the panel never shows its empty state: with no rows left it keeps the sentinel and the append loader, so moving the whole loaded page across pulls the next one instead of dead-ending. |\n| `isLoadingAvailable` | `boolean` | `false` | Loader **replaces** the available rows (a search/refresh fetch, not a page append). |\n| `availableLoadError` | `ReactNode` | \u2014 | Replaces the available rows: that panel\'s source failed to load. |\n| `availableLoadMoreError` | `ReactNode` | \u2014 | Shown under the loaded rows when a page append failed; renders a retry button. |\n| `onRetryLoadMoreAvailable` | `fn` | \u2014 | Fired by that retry button. |\n| `retryLabel` | `string` | `"Retry"` | Label for the retry button. |\n| `availableTotalCount` | `number` | \u2014 | Server-side total; the available panel\'s header count becomes `(loaded of total)`. |\n| `loadAvailableOptions` | `(query, meta) => Promise<ITransferListItem[] \\| IOptionPage<...>>` | \u2014 | Async, paged source for the available panel. See [Async available panel](#async-available-panel). |\n| `initialAvailableOptions` | `readonly ITransferListItem[]` | \u2014 | Seed rows for a pool you already have (SSR payload, route loader, warm cache). Painted on the first frame and kept on screen while the mount fetch revalidates over them \u2014 see [Seeding the pool](#seeding-the-pool). Async mode only. |\n| `prefetch` | `"mount" \\| "never"` | `"mount"` | When to fetch the unfiltered available list. `"mount"` at render \u2014 the panel has no open/close, so mount is the only trigger it has; `"never"` only once the user searches. Async mode only. |\n| `refetchOnClear` | `boolean` | `false` | Clearing the available search revalidates the cached baseline instead of only restoring it. |\n| `optionsKey` | `string \\| number` | \u2014 | Identity of the available option set. A change drops cached pages and repopulates. Does **not** clear the selection. |\n| `availableFilterDebounceMs` | `number` | `300` | Debounce for the available panel\'s search when it is server-driven. |\n| `loadErrorMessage` / `loadMoreErrorMessage` | `ReactNode` | `"Couldn\'t load options."` / `"Couldn\'t load more."` | Async-mode copy for the two failure states above. |\n| `onLoadError` | `(error: unknown) => void` | \u2014 | Notified when a load rejects. |\n| `disabled` | `boolean` | `false` | Disable all interaction. |\n| `availableEmptyText` / `selectedEmptyText` | `ReactNode` | `"No Data Found!"` | Empty-state copy. |\n| `className` | `string` | \u2014 | Extra classes on the root. |\n| `ref` | `Ref<HTMLDivElement>` | \u2014 | Forwarded to the root \u2014 for programmatic focus/scroll and form libraries that bind by ref. |\n\n## Selecting and moving items\n\n- **Per-row checkboxes:** check individual rows in either panel.\n- **Select all:** the checkbox above each list checks/clears the non-disabled items the\n active search leaves **visible** \u2014 its label counts exactly that scope, and it reflects\n an indeterminate state when only some of them are checked. Items hidden by the filter are\n left as they are in both directions, so checks made under an earlier query survive. The\n row is shown only when there are at least two visible items to act on; below that it would\n duplicate a single row\'s own checkbox or have nothing to check.\n- **Move button:** the button below each list moves **every** currently-checked item to the\n other panel (skipping disabled items) and clears the checkboxes \u2014 including items the\n active filter is hiding, so its count stays an honest tally of the selection. It is\n disabled when nothing is checked. To move everything, clear the search, click "Select all",\n then the move button.\n\n## Drag-and-drop\n\n- **Cross-panel transfer:** drag any row onto the opposite panel to move it (honoring\n `isDisabled`). Same effect as checking the row and clicking the move button. While a drag is in progress, every\n panel that is a valid, position-irrelevant drop target shows a sticky "Drop Here"\n overlay across its whole content area, for the entire drag \u2014 not just while hovering\n it. This is consistent on both panels: dragging a Selected row always shows the\n overlay on Available, and dragging an Available row shows it on Selected whenever\n `reorderable` is not set (the drop always appends, regardless of which row is\n hovered).\n- **Reorder within Selected:** only when `reorderable` \u2014 drop a selected row (or an\n incoming available row) at a new position, tracked with a precise per-row insertion\n line instead of the overlay, or use the up/down arrows. Without `reorderable`,\n dragging a selected row within Selected is a no-op and shows neither the overlay nor\n an indicator.\n- The **Available panel is never sortable**: Available rows are draggable solely to enable\n transfer to Selected; dropping an Available row within Available is a no-op and shows\n no overlay or indicator.\n\n## Loading and error states on the available panel\n\nThese are plain prop additions, usable by any controlled consumer without touching async mode:\n\n- **`isLoadingAvailable`** shows a centred loader *instead of* the rows. Use it for a search or refresh\n fetch \u2014 the rows on screen belong to the previous query, so leaving them navigable would let the user\n act on something the incoming result set no longer contains. Arrow/Enter/Space are swallowed and\n `aria-activedescendant` is dropped while it is up. `isLoadingMoreAvailable` is the opposite: the\n loader *appends* below the rows, because a page fetch adds to what is already there.\n- **`availableLoadError`** replaces the rows with `role="alert"` copy. The drop targets stay live \u2014 an\n error in Available must not break dragging items back out of Selected.\n- **`availableLoadMoreError`** + **`onRetryLoadMoreAvailable`** render below the loaded rows, replacing\n the append loader. This is the affordance that makes a failed page recoverable; because only this\n button retries, a sentinel that never left the viewport cannot hammer a failing endpoint.\n- **`availableTotalCount`** turns the header count into `(loaded of total)` when it exceeds what is\n loaded. A paged panel reporting `(20)` when the server holds 4,000 matches is lying.\n\n## Async available panel\n\n`loadAvailableOptions` makes the component own the Available pool \u2014 its paging, request ordering and\nloading/error state \u2014 instead of every consumer hand-writing a monotonic-ticket guard and a page\naccumulator:\n\n```tsx\nconst [selected, setSelected] = useState<ITransferListItem[]>([]);\n\n<TransferList\n selectedItems={selected}\n onChange={(_available, nextSelected) => setSelected(nextSelected)}\n loadAvailableOptions={async (query, { cursor, signal }) => {\n const res = await fetchRows({ query, cursor, signal });\n return { options: res.rows, cursor: res.nextToken, total: res.totalCount };\n }}\n/>\n```\n\n- It fetches on **mount**, not on open: the panel has no open/close, so its list is always visible.\n That is why `prefetch` here is `"mount" | "never"` rather than the `"mount" | "open" | "never"` that\n `Select` and `MultiSelectTransfer` accept \u2014 there is no open event to hang a fetch on.\n `prefetch="never"` defers everything until the user searches.\n- The panel\'s search becomes **debounced and server-driven** (`availableFilterDebounceMs`); the local\n matcher stands down, since over a paged pool it could only search the pages that happen to be loaded.\n- Available is **derived** as the loaded pool minus `selectedItems`, so moving an item across needs no\n refetch. An item that was in `selectedItems` but never in the pool still returns to Available when\n moved back \u2014 the component remembers every item it has seen on the selected side. Those remembered\n items are matched locally against the active query, so one cannot surface as a result for a search it\n does not match, and they are forgotten on an `optionsKey` change along with the pool itself.\n- **`availableItems` becomes optional and is ignored** (with a dev warning), which sits a little\n awkwardly with the component\'s fully-controlled identity. `selectedItems` stays controlled \u2014 the\n consumer owns the selection, which is the whole point of the component \u2014 and `onChange` still fires\n with both arrays, so no existing call site breaks.\n- The paging, dedupe, failed-page/Retry and `optionsKey` semantics are identical to\n `MultiSelectTransfer`\'s; see its README for the full list.\n\n### Seeding the pool\n\n`initialAvailableOptions` is for the case where **you already have the rows** \u2014 an SSR payload, a route\nloader, a warm query cache. They are painted on the first frame, so the panel is never briefly empty,\nand they stay on screen while the mount fetch revalidates over them. They go through the same\npool-minus-`selectedItems` projection as fetched rows, so an already-selected seed row correctly starts\non the right-hand side.\n\n```tsx\n<TransferList\n selectedItems={selected}\n onChange={(_available, nextSelected) => setSelected(nextSelected)}\n initialAvailableOptions={ssrRows} // painted immediately\n loadAvailableOptions={fetchRows} // still runs at mount, and replaces them when page one lands\n/>\n```\n\nIt does **not** suppress that fetch. If the seed *is* the whole pool until the user searches \u2014 a heavy\nsource you do not want to hit on render \u2014 pair it with `prefetch="never"`, which otherwise leaves the\npanel empty:\n\n```tsx\n<TransferList\n selectedItems={selected}\n onChange={...}\n initialAvailableOptions={recentlyUsed}\n prefetch="never"\n loadAvailableOptions={searchEverything}\n/>\n```\n\nSeed rows carry no cursor, so the infinite-scroll sentinel stays disarmed until a real page lands \u2014 a\nseed is not page one. A *search* replaces them, because they are not results for a query. And seed rows\nonly mean something to the async source \u2014 passing `initialAvailableOptions` without\n`loadAvailableOptions` is ignored with a dev warning, because those rows belong in `availableItems`.\n\n`prefetch` is async-only for the same reason: it schedules the baseline fetch and nothing else, so\nwithout `loadAvailableOptions` there is no fetch to schedule. Passing it there is ignored with a dev\nwarning.\n\n## Notes\n\n- With a paged source, "the full list" that Select-all and the move buttons operate on is what has\n been **loaded**, not what the server holds.\n- Search is both controlled and uncontrolled per panel. When a search-change handler is\n provided the parent owns filtering; otherwise items are filtered client-side.\n- With `searchable={false}` there are no search inputs to drive, so the controlled-search props\n (`availableSearchTerm` / `onAvailableSearchChange` and the selected-panel pair) have no effect and\n are dev-warned; an async Available panel then only ever sees an empty query \u2014 it still pages, it\n just cannot be searched.\n- Client-side search matches an item\'s `searchValue` first, then a string `label`, then its\n `value`. Set `searchValue` on items whose `label` is custom JSX so they remain findable by\n their visible text (a ReactNode `label` is otherwise matched only against `value`).\n- Because the component is controlled, "pending until confirm" semantics (e.g. a modal\n with Cancel/Done) are owned by the parent \u2014 see `MultiSelectTransfer`.\n'
|
|
4481
4380
|
}
|
|
4482
4381
|
],
|
|
4483
4382
|
"directories": []
|