Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

👥 add user selector component (#1)

Brad Barbindd54ed53ee49
diff --git a/README.md b/README.md
index 2affc03336..1171ab67fa 100644
--- a/README.md
+++ b/README.md
@@ -48,12 +48,12 @@ The monorepo follows the Turborepo covention of grouping packages into one of tw
## Tech Stack
-- [Turborepo](https://turbo.build)
- [Remix](https://remix.run)
+- [Chakra UI](https://chakra-ui.com/)
- [Supabase](https://supabase.com/)
- [Postgres](https://postgresql.org/)
-- [Chakra UI](https://chakra-ui.com/)
- [Redis](https://redis.io)
+- [Turborepo](https://turbo.build)
- [Prisma](https://prisma.io/)
## Local Development
diff --git a/apps/carbon/app/components/Data/Table/components/Pagination.tsx b/apps/carbon/app/components/Data/Table/components/Pagination.tsx
index 9dbfcbca05..f4504a4529 100644
--- a/apps/carbon/app/components/Data/Table/components/Pagination.tsx
+++ b/apps/carbon/app/components/Data/Table/components/Pagination.tsx
@@ -38,6 +38,7 @@ export function Pagination({
setPageSize,
}: PaginationProps) {
const pageSizes = [10, 25, 50, 100];
+ const pageSizeLabel = "results per page";
if (!pageSizes.includes(pageSize)) {
pageSizes.push(pageSize);
pageSizes.sort();
@@ -53,7 +54,9 @@ export function Pagination({
>
<Stack direction="row" spacing={2}>
<Menu>
- <MenuButton as={Button}>{pageSize} per page</MenuButton>
+ <MenuButton as={Button}>
+ {pageSize} {pageSizeLabel}
+ </MenuButton>
<MenuList fontSize="sm" boxShadow="xl" minW={48}>
{pageSizes.map((size) => (
<MenuItem
@@ -62,7 +65,7 @@ export function Pagination({
setPageSize(size);
}}
>
- {size} per page
+ {size} {pageSizeLabel}
</MenuItem>
))}
</MenuList>
diff --git a/apps/carbon/app/components/Selectors/UserSelect/UserSelect.tsx b/apps/carbon/app/components/Selectors/UserSelect/UserSelect.tsx
new file mode 100644
index 0000000000..fdb29d1b37
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/UserSelect/UserSelect.tsx
@@ -0,0 +1,57 @@
+/**
+ * Welcome to UserSelect
+ *
+ * Controlled, accessible, multi-user select component for groups and people.
+ *
+ * A combobox is the combination of an `<input type="text"/>` and a list. In
+ * this case, the list conforms to the `treeselect` pattern.
+ *
+ * @see WAI-ARIA Comobox https://www.w3.org/WAI/ARIA/apg/patterns/combobox/
+ * @see WAI-ARIA Tree View https://www.w3.org/WAI/ARIA/apg/patterns/treeview/
+ */
+
+import { FormLabel } from "@chakra-ui/react";
+import Combobox from "./components/Combobox";
+import Container from "./components/Container";
+import Input from "./components/Input";
+import Popover from "./components/Popover";
+import SelectionList from "./components/SelectionList";
+import TreeSelect from "./components/TreeSelect";
+import type { UserSelectProps } from "./types";
+import { UserSelectContext } from "./provider";
+import useUserSelect from "./useUserSelect";
+
+export default function Component(props: UserSelectProps) {
+ const state = useUserSelect(props);
+ return <UserSelect {...state} />;
+}
+
+const UserSelect = (state: ReturnType<typeof useUserSelect>) => {
+ const {
+ dropdown,
+ innerProps: { hideSelections, isMulti, label, readOnly, testID, width },
+ refs: { containerRef },
+ selectionItemsById,
+ } = state;
+
+ return (
+ <UserSelectContext.Provider value={state}>
+ {label && <FormLabel>{label}</FormLabel>}
+ <Container ref={containerRef} width={width} testID={testID}>
+ {!readOnly && (
+ <Combobox>
+ <Input />
+ {dropdown.isOpen && (
+ <Popover>
+ <TreeSelect />
+ </Popover>
+ )}
+ </Combobox>
+ )}
+ {!hideSelections &&
+ isMulti &&
+ Object.keys(selectionItemsById).length > 0 && <SelectionList />}
+ </Container>
+ </UserSelectContext.Provider>
+ );
+};
diff --git a/apps/carbon/app/components/Selectors/UserSelect/components/Combobox.tsx b/apps/carbon/app/components/Selectors/UserSelect/components/Combobox.tsx
new file mode 100644
index 0000000000..c2861cbcea
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/UserSelect/components/Combobox.tsx
@@ -0,0 +1,10 @@
+import { Box } from "@chakra-ui/react";
+import type { PropsWithChildren } from "react";
+import useUserSelectContext from "../provider";
+
+const Combobox = ({ children }: PropsWithChildren) => {
+ const { onKeyDown } = useUserSelectContext();
+ return <Box onKeyDown={onKeyDown}>{children}</Box>;
+};
+
+export default Combobox;
diff --git a/apps/carbon/app/components/Selectors/UserSelect/components/Container.tsx b/apps/carbon/app/components/Selectors/UserSelect/components/Container.tsx
new file mode 100644
index 0000000000..11e6b62cd7
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/UserSelect/components/Container.tsx
@@ -0,0 +1,27 @@
+import { Box } from "@chakra-ui/react";
+import type { ReactNode } from "react";
+import { forwardRef } from "react";
+
+interface ContainerProps {
+ children: ReactNode;
+ testID?: string;
+ width?: number;
+}
+
+const Container = forwardRef<HTMLDivElement, ContainerProps>(
+ ({ width, testID, children }, ref) => (
+ <Box
+ ref={ref}
+ data-testid={testID}
+ display="inline-block"
+ position="relative"
+ maxW={width}
+ w="full"
+ >
+ {children}
+ </Box>
+ )
+);
+
+Container.displayName = "Container";
+export default Container;
diff --git a/apps/carbon/app/components/Selectors/UserSelect/components/Input.tsx b/apps/carbon/app/components/Selectors/UserSelect/components/Input.tsx
new file mode 100644
index 0000000000..4394d8dd2f
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/UserSelect/components/Input.tsx
@@ -0,0 +1,84 @@
+import {
+ Avatar,
+ AvatarGroup,
+ HStack,
+ IconButton,
+ Input,
+ InputGroup,
+ InputLeftElement,
+ InputRightElement,
+ Spinner,
+} from "@chakra-ui/react";
+import { MdOutlineClear } from "react-icons/md";
+import useUserSelectContext from "../provider";
+
+const SelectInput = () => {
+ const {
+ aria: { inputProps },
+ innerProps: { disabled, isMulti, placeholder, testID },
+ inputValue,
+ instanceId,
+ loading,
+ refs: { inputRef },
+ onClearInput,
+ onInputBlur,
+ onInputChange,
+ onInputFocus,
+ } = useUserSelectContext();
+
+ return (
+ <InputGroup>
+ {isMulti ? (
+ <InputLeftElement left={2}>
+ <AvatarGroup size="xs" max={2}>
+ <Avatar />
+ <Avatar />
+ </AvatarGroup>
+ </InputLeftElement>
+ ) : (
+ <InputLeftElement>
+ <Avatar size="xs" />
+ </InputLeftElement>
+ )}
+
+ <Input
+ {...inputProps}
+ id={`${instanceId}:UserSelectionInput:searchInput:${testID}`}
+ data-testid={`UserSelectionInput:searchInput:${testID}`}
+ readOnly={disabled}
+ disabled={disabled}
+ onBlur={onInputBlur}
+ onChange={onInputChange}
+ onFocus={onInputFocus}
+ placeholder={placeholder}
+ spellCheck="false"
+ ref={inputRef}
+ type="text"
+ value={inputValue}
+ pl={isMulti ? "3.175rem" : undefined}
+ pr="2.5rem"
+ />
+
+ <InputRightElement w="auto">
+ <HStack spacing={1} mr={2}>
+ {loading && <Spinner size="sm" />}
+ {!loading && inputValue.length > 0 && (
+ <IconButton
+ aria-label="Clear search query"
+ icon={<MdOutlineClear />}
+ onClick={onClearInput}
+ colorScheme="gray"
+ h={8}
+ w={8}
+ borderRadius={4}
+ size="sm"
+ variant="ghost"
+ />
+ )}
+ </HStack>
+ </InputRightElement>
+ </InputGroup>
+ );
+};
+
+export default SelectInput;
diff --git a/apps/carbon/app/components/Selectors/UserSelect/components/Popover.tsx b/apps/carbon/app/components/Selectors/UserSelect/components/Popover.tsx
new file mode 100644
index 0000000000..e31fbb8d41
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/UserSelect/components/Popover.tsx
@@ -0,0 +1,99 @@
+import { Box, useMultiStyleConfig } from "@chakra-ui/react";
+import type { PropsWithChildren } from "react";
+import { useEffect } from "react";
+import useUserSelectContext from "../provider";
+
+const Popover = ({ children }: PropsWithChildren) => {
+ const {
+ aria: { popoverProps },
+ refs: { listBoxRef, popoverRef, focusableNodes },
+ } = useUserSelectContext();
+
+ const menuStyles = useMultiStyleConfig("Menu");
+
+ useEffect(() => {
+ /* Build a triple linked-list (TreeNode[]) of focusable DOM Elements that are children
+
+ type TreeNode {
+ id: string;
+ expandable: boolean;
+ previousId?: string;
+ nextId?: string;
+ parentId? string;
+ }
+
+ */
+
+ focusableNodes.current = {};
+
+ /* First get the parents */
+ const parents: Element[] = [];
+ if (listBoxRef.current) {
+ let node = listBoxRef.current.firstElementChild;
+ let lastNode = listBoxRef.current.lastElementChild;
+
+ while (node && node !== lastNode) {
+ parents.push(node);
+ node = node.nextElementSibling;
+ }
+
+ if (node) {
+ parents.push(node);
+ }
+ }
+
+ /* Then make a flat list with the children spliced in */
+ const nodes: [string, string | undefined][] = [];
+
+ parents.forEach((parent) => {
+ nodes.push([parent.id, undefined]);
+ const group = parent.getElementsByTagName("ul");
+ if (group?.[0]) {
+ let child = group[0].firstElementChild;
+ let lastChild = group[0].lastElementChild;
+
+ while (child && child !== lastChild) {
+ nodes.push([child.id, parent.id]);
+ child = child.nextElementSibling;
+ }
+
+ if (child) {
+ nodes.push([child.id, parent.id]);
+ }
+ }
+ });
+
+ /* Finally, create the triple linked list */
+ for (let i = 0; i < nodes.length; i++) {
+ const [node, parent] = nodes[i];
+ const previous = nodes?.[i - 1];
+ const next = nodes?.[i + 1];
+
+ focusableNodes.current[node] = {
+ uid: node,
+ expandable: parent === undefined,
+ parentId: parent,
+ previousId: previous?.[0] || undefined,
+ nextId: next?.[0] || undefined,
+ };
+ }
+ }, [children, focusableNodes, listBoxRef]);
+
+ return (
+ <Box
+ {...popoverProps}
+ ref={popoverRef}
+ sx={{
+ ...menuStyles.list,
+ position: "absolute",
+ width: "100%",
+ marginTop: 1,
+ px: 2,
+ }}
+ >
+ {children}
+ </Box>
+ );
+};
+
+export default Popover;
diff --git a/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx b/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx
new file mode 100644
index 0000000000..5d57aac3ae
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx
@@ -0,0 +1,115 @@
+import { useColor } from "@carbon/react";
+import {
+ Avatar,
+ Box,
+ Checkbox,
+ Flex,
+ IconButton,
+ List,
+ ListItem,
+ Text,
+ Tooltip,
+} from "@chakra-ui/react";
+import { useMemo } from "react";
+import { MdPlaylistAdd, MdOutlineClear } from "react-icons/md";
+import useUserSelectContext from "../provider";
+import { isGroup } from "../useUserSelect";
+
+const SelectionList = () => {
+ const {
+ innerProps: { checkedSelections, readOnly, selectionsMaxHeight, width },
+ instanceId,
+ selectionItemsById,
+ onDeselect,
+ onExplode,
+ onToggleChecked,
+ } = useUserSelectContext();
+
+ const selected = useMemo(
+ () =>
+ Object.values(selectionItemsById).sort((a, b) =>
+ a.label < b.label ? -1 : 0
+ ),
+ [selectionItemsById]
+ );
+
+ const background = useColor("gray.100");
+
+ return (
+ <List
+ w="full"
+ maxW={width}
+ mt={1}
+ maxH={selectionsMaxHeight}
+ overflowY={selectionsMaxHeight ? "auto" : undefined}
+ >
+ {selected.map((item) => {
+ const id = `UserSelection:SelectedItem-${item.id}`;
+ const canExpand = !checkedSelections && !readOnly && isGroup(item);
+
+ return (
+ <ListItem
+ key={item.id}
+ p={2}
+ borderRadius="md"
+ _hover={{ background }}
+ >
+ <Flex direction="row" gap={2} data-testid={`${id}`}>
+ {checkedSelections ? (
+ <>
+ <Checkbox
+ id={`${instanceId}:${id}:checkbox`}
+ data-testid={id}
+ isChecked={item.isChecked}
+ onChange={() => onToggleChecked(item)}
+ size="lg"
+ flexGrow={2}
+ >
+ <Text fontSize={14} noOfLines={1}>
+ {item.label}
+ </Text>
+ </Checkbox>
+ </>
+ ) : (
+ <>
+ <Avatar size="sm" />
+ <Box display="flex" alignItems="center" flexGrow={2}>
+ <Text fontSize={14} noOfLines={1}>
+ {item.label}
+ </Text>
+ </Box>
+ </>
+ )}
+
+ {canExpand && (
+ <Tooltip label="Expand">
+ <IconButton
+ aria-label={`Expand ${item.label}`}
+ icon={<MdPlaylistAdd />}
+ size="sm"
+ onClick={() => onExplode(item)}
+ variant="outline"
+ />
+ </Tooltip>
+ )}
+
+ {!readOnly && (
+ <Tooltip label="Remove">
+ <IconButton
+ aria-label={`Remove ${item.label}`}
+ icon={<MdOutlineClear />}
+ size="sm"
+ onClick={() => onDeselect(item)}
+ variant="outline"
+ />
+ </Tooltip>
+ )}
+ </Flex>
+ </ListItem>
+ );
+ })}
+ </List>
+ );
+};
+
+export default SelectionList;
diff --git a/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx b/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx
new file mode 100644
index 0000000000..d6ffcf736f
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx
@@ -0,0 +1,160 @@
+import { Loading } from "@carbon/react";
+import type { IconProps } from "@chakra-ui/react";
+import { Box, Icon, List, ListItem, MenuIcon, Text } from "@chakra-ui/react";
+import { FaCheck, FaChevronRight } from "react-icons/fa";
+import Empty from "~/components/Data/Empty";
+import type { OptionGroup, SelectionItemInterface } from "../types";
+import useUserSelectContext from "../provider";
+import { useGroupStyles, useOptionStyles } from "./useUserSelectStyles";
+
+const UserTreeSelect = () => {
+ const {
+ aria: { listBoxProps },
+ groups,
+ innerProps: { isMulti },
+ loading,
+ onMouseOver,
+ refs: { listBoxRef },
+ } = useUserSelectContext();
+
+ return (
+ <List
+ {...listBoxProps}
+ aria-multiselectable={isMulti}
+ ref={listBoxRef}
+ onMouseOver={onMouseOver}
+ overflow="auto"
+ maxH={300}
+ my="1"
+ display="flex"
+ flexDirection="column"
+ >
+ {loading ? (
+ <Loading />
+ ) : groups.length > 0 ? (
+ groups.map((group) => <Group key={group.uid} group={group} />)
+ ) : (
+ <Empty text={"No options available"} />
+ )}
+ </List>
+ );
+};
+
+const MoreIcon = ({ isExpanded }: { isExpanded: boolean }) => (
+ <Icon
+ as={FaChevronRight}
+ w={4}
+ h={4}
+ transition="transform .25s ease"
+ transform={isExpanded ? "rotate(-0.25turn)" : undefined}
+ />
+);
+
+const Group = ({ group }: { group: OptionGroup }) => {
+ const {
+ onGroupCollapse,
+ onGroupExpand,
+ focusedId,
+ onSelect,
+ onDeselect,
+ selectionItemsById,
+ } = useUserSelectContext();
+
+ const isFocused = group.uid === focusedId;
+ const isExpanded = group.expanded && group.items.length > 0;
+ const sx = useGroupStyles(isFocused, isExpanded);
+
+ return (
+ <ListItem
+ as="li"
+ id={group.uid}
+ tabIndex={0}
+ role="treeitem"
+ aria-expanded={isExpanded}
+ borderRadius="md"
+ outline="none"
+ >
+ <Box
+ role="treeitem"
+ onClick={() =>
+ group.expanded ? onGroupCollapse(group.uid) : onGroupExpand(group.uid)
+ }
+ sx={sx}
+ >
+ <Text noOfLines={1}>{group.name}</Text>
+ <MoreIcon isExpanded={isExpanded} />
+ </Box>
+ {isExpanded && (
+ <List role="group" display="flex" flexDirection="column">
+ {group.items.map((item) => {
+ const isDisabled = item.id in []; // TODO
+ const isFocused = item.uid === focusedId;
+ const isSelected = item.id in selectionItemsById;
+
+ return (
+ <Option
+ key={item.uid}
+ id={item.uid}
+ item={item}
+ isDisabled={isDisabled}
+ isFocused={isFocused}
+ isSelected={isSelected}
+ onClick={() => (isSelected ? onDeselect(item) : onSelect(item))}
+ />
+ );
+ })}
+ </List>
+ )}
+ </ListItem>
+ );
+};
+
+const CheckIcon = (iconProps: IconProps) => (
+ <Icon as={FaCheck} {...iconProps} />
+);
+
+const Option = ({
+ id,
+ item,
+ isDisabled,
+ isFocused,
+ isSelected,
+ onClick,
+}: {
+ id?: string;
+ item: SelectionItemInterface;
+ isDisabled: boolean;
+ isFocused: boolean;
+ isSelected: boolean;
+ onClick: () => void;
+}) => {
+ const sx = useOptionStyles(isFocused, isSelected, isDisabled);
+ const name = item.label;
+
+ return (
+ <ListItem
+ as="li"
+ id={id}
+ background={"red.100"}
+ tabIndex={0}
+ aria-selected={isSelected}
+ role="treeitem"
+ onClick={onClick}
+ sx={sx}
+ >
+ <MenuIcon>
+ <CheckIcon
+ display="block"
+ marginEnd="0.75rem"
+ fontSize="0.8rem"
+ w={4}
+ h={4}
+ opacity={isSelected ? 1 : 0}
+ />
+ </MenuIcon>
+ <Text noOfLines={1}>{name}</Text>
+ </ListItem>
+ );
+};
+
+export default UserTreeSelect;
diff --git a/apps/carbon/app/components/Selectors/UserSelect/components/useUserSelectStyles.ts b/apps/carbon/app/components/Selectors/UserSelect/components/useUserSelectStyles.ts
new file mode 100644
index 0000000000..ec36d083fb
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/UserSelect/components/useUserSelectStyles.ts
@@ -0,0 +1,89 @@
+import { useColor } from "@carbon/react";
+import type { SystemStyleObject } from "@chakra-ui/react";
+import { useMultiStyleConfig } from "@chakra-ui/react";
+import type { ThemeObject } from "~/types/chakra";
+
+export const useGroupStyles = (isFocused: boolean, isSticky: boolean) => {
+ const menuItemStyles = useMultiStyleConfig("Menu").item as ThemeObject;
+ const selectedBg = useColor("gray.200");
+ const selectedColor = useColor("black");
+
+ const sx: SystemStyleObject = {
+ ...menuItemStyles,
+ transition: "none",
+ cursor: "pointer",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ width: "100%",
+ textAlign: "start",
+ padding: "8px 12px",
+ marginBottom: "3px",
+ bg: "transparent",
+ borderRadius: "md",
+
+ ...(isFocused && menuItemStyles._focus),
+ ...(isFocused && {
+ bg: selectedBg,
+ color: selectedColor,
+ _active: { bg: selectedBg },
+ }),
+ _hover: {
+ bg: selectedBg,
+ color: selectedColor,
+ ...menuItemStyles._focus,
+ },
+ _focus: {
+ boxShadow: "none",
+ outlineWeight: "3px",
+ },
+ };
+
+ return sx;
+};
+
+export const useOptionStyles = (
+ isFocused: boolean,
+ isSelected?: boolean,
+ isDisabled?: boolean
+) => {
+ const menuItemStyles = useMultiStyleConfig("Menu").item as ThemeObject;
+ const selectedBg = useColor("gray.700");
+ const selectedColor = useColor("white");
+
+ const sx: SystemStyleObject = {
+ ...menuItemStyles,
+ fontSize: "0.9em",
+ transition: "none",
+ cursor: "pointer",
+ display: "flex",
+ alignItems: "center",
+ width: "100%",
+ textAlign: "start",
+ padding: "8px 12px",
+ marginBottom: "3px",
+ bg: "transparent",
+ borderRadius: "md",
+ outlineOffset: "3px",
+ ...(isFocused && menuItemStyles._focus),
+ ...(isSelected && {
+ // bg: selectedBg,
+ // color: selectedColor,
+ // _active: { bg: selectedBg },
+ ...menuItemStyles._focus,
+ }),
+ ...(isFocused && { bg: selectedBg, color: selectedColor }),
+ ...(isDisabled && menuItemStyles._disabled),
+ ...(isDisabled && { _active: {} }),
+ _hover: {
+ bg: selectedBg,
+ color: selectedColor,
+ },
+ _focus: {
+ boxShadow: "none",
+ outline: "none",
+ },
+ };
+
+ return sx;
+};
diff --git a/apps/carbon/app/components/Selectors/UserSelect/index.ts b/apps/carbon/app/components/Selectors/UserSelect/index.ts
new file mode 100644
index 0000000000..a9dc477a34
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/UserSelect/index.ts
@@ -0,0 +1,3 @@
+import UserSelect from "./UserSelect";
+
+export default UserSelect;
diff --git a/apps/carbon/app/components/Selectors/UserSelect/provider.ts b/apps/carbon/app/components/Selectors/UserSelect/provider.ts
new file mode 100644
index 0000000000..1e0ee4a1af
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/UserSelect/provider.ts
@@ -0,0 +1,16 @@
+import { createContext, useContext } from "react";
+import type useUserSelect from "./useUserSelect";
+
+type ContextType = ReturnType<typeof useUserSelect>;
+
+export const UserSelectContext = createContext<ContextType>({} as ContextType);
+
+export default function useUserSelectContext() {
+ const context = useContext(UserSelectContext);
+ if (context === undefined) {
+ throw new Error(
+ "useUserSelectContext must be used within a UserSelectContext.Provider"
+ );
+ }
+ return context;
+}
diff --git a/apps/carbon/app/components/Selectors/UserSelect/types.ts b/apps/carbon/app/components/Selectors/UserSelect/types.ts
new file mode 100644
index 0000000000..0847a8856b
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/UserSelect/types.ts
@@ -0,0 +1,131 @@
+import type {
+ ChangeEvent,
+ HTMLAttributes,
+ InputHTMLAttributes,
+ KeyboardEvent,
+ MutableRefObject,
+ ReactNode,
+ RefObject,
+} from "react";
+
+import type { User, Group } from "~/modules/Users/types";
+
+export type ComboBoxRefs = {
+ containerRef: RefObject<HTMLDivElement>;
+ inputRef: RefObject<HTMLInputElement>;
+ listBoxRef: RefObject<HTMLUListElement>;
+ popoverRef: RefObject<HTMLDivElement>;
+ buttonRef: RefObject<Element>;
+ focusableNodes: MutableRefObject<Record<string, TreeNode>>;
+};
+
+export interface UserSelectProps {
+ accessibilityLabel?: string;
+ checkedSelections?: boolean;
+ disabled?: boolean;
+ hideSelections?: boolean;
+ id?: string;
+ innerInputRender?:
+ | ((props: UserSelectProps) => JSX.Element | JSX.Element[])
+ | ReactNode
+ | null;
+ isMulti?: boolean;
+ label?: string;
+ placeholder?: string;
+ showAvatars?: boolean;
+ queryFilters?: UserSelectionQueryFilters;
+ readOnly?: boolean;
+ renderInput?: ReactNode;
+ resetAfterSelection?: boolean;
+ selections?: SelectionItemInterface[];
+ selectionsMaxHeight?: string | number;
+ testID?: string;
+ usersOnly?: boolean;
+ value?: string[] | string; // Will be set when used as a controlled input
+ width?: number;
+ onBlur?: (e: any) => void;
+ onCancel?: () => void;
+ onChange?: (selectionsList: SelectionItemInterface[]) => void;
+ onCheckedSelectionsChange?: (
+ checkedSelectionsList: SelectionItemInterface[]
+ ) => void;
+}
+
+export type OptionGroup = {
+ uid: string;
+ expanded: boolean;
+ items: SelectionItemInterface[];
+ name: string;
+};
+
+export type TreeNode = {
+ uid: string;
+ expandable: boolean;
+ parentId?: string;
+ previousId?: string;
+ nextId?: string;
+};
+export interface PopoverProps {
+ aria: HTMLAttributes<HTMLDivElement>;
+ children: ReactNode;
+ innerProps: UserSelectProps;
+ refs: ComboBoxRefs;
+}
+
+interface SelectionOptions {
+ uid: string;
+ label: string;
+ isChecked?: boolean;
+ isPersistent?: boolean;
+}
+
+type UserWithOptions = User & SelectionOptions;
+type SelectionGroupWithOptions = Group["data"] & {
+ children?: Group[];
+} & SelectionOptions;
+
+export type SelectionItemInterface =
+ | UserWithOptions
+ | SelectionGroupWithOptions;
+
+export type SelectionItemsById = Record<string, SelectionItemInterface>;
+
+export interface SelectInputProps {
+ aria?: Omit<InputHTMLAttributes<HTMLInputElement>, "size">;
+ errors?: unknown; // TODO
+ inputValue: string;
+ innerProps: UserSelectProps;
+ loading: boolean;
+ isMulti: boolean;
+ refs: ComboBoxRefs;
+ onClearSearchInput: () => void;
+ onInputOnChange: (e: ChangeEvent<HTMLInputElement>) => void;
+ onInputKeyDown: (e: KeyboardEvent<HTMLInputElement>) => void;
+ onInputBlur: () => void;
+ onInputFocus: () => void;
+}
+
+export interface UserTreeSelectProps {
+ aria: HTMLAttributes<HTMLUListElement>;
+ disabledSelections?: string[];
+ focusedId: string | null;
+ groups: OptionGroup[];
+ groupTypeFilter?: string;
+ innerProps: UserSelectProps;
+ instanceId: string;
+ itemOnSelect?: (selectableItem: SelectionItemInterface) => void;
+ itemOnStage?: (selectableItem: SelectionItemInterface) => void;
+ loading: boolean;
+ multi?: boolean;
+ refs: ComboBoxRefs;
+ searchFilter?: string;
+ selectionItemsById: SelectionItemsById;
+ stagedSelectionsById?: SelectionItemsById;
+ visible?: boolean;
+}
+
+export interface UserSelectionQueryFilters {
+ excludeSelf?: boolean;
+ onlyEmployeeTypes?: string[];
+ allowedIds?: string[];
+}
diff --git a/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts b/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts
new file mode 100644
index 0000000000..7bb99ea733
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts
@@ -0,0 +1,832 @@
+import { useDisclosure, useOutsideClick, useId } from "@chakra-ui/react";
+import { useFetcher } from "@remix-run/react";
+import type { PostgrestError } from "@supabase/supabase-js";
+import debounce from "lodash/debounce";
+import words from "lodash/words";
+import type { AriaAttributes, ChangeEvent, KeyboardEvent } from "react";
+import { useEffect, useState, useMemo, useCallback, useRef } from "react";
+import type { Group } from "~/modules/Users/types";
+
+import type {
+ OptionGroup,
+ SelectionItemsById,
+ SelectionItemInterface,
+ UserSelectionQueryFilters,
+ UserSelectProps,
+ TreeNode,
+} from "./types";
+
+const defaultProps = {
+ accessibilityLabel: "User selector",
+ checkedSelections: false,
+ disabled: false,
+ hideSelections: false,
+ id: "MultiUserSelect",
+ innerInputRender: null,
+ isMulti: false,
+ placeholder: "",
+ queryFilters: {} as UserSelectionQueryFilters,
+ readOnly: false,
+ resetAfterSelection: false,
+ selections: [] as SelectionItemInterface[],
+ selectionsMaxHeight: "auto",
+ showAvatars: false,
+ testID: "UserSelect",
+ usersOnly: false,
+ onCancel: () => {},
+};
+
+export default function useUserSelect(props: UserSelectProps) {
+ /* Inner Props */
+ const innerProps = useMemo(
+ () => ({
+ ...defaultProps,
+ ...props,
+ }),
+ [props]
+ );
+
+ /* Data Fetching */
+ const groupsFetcher = useFetcher<{
+ groups: Group[];
+ errors?: PostgrestError;
+ }>();
+
+ useEffect(() => {
+ const params: Record<string, string> = {};
+ const query = new URLSearchParams(params).toString();
+ groupsFetcher.load(`/resource/groups?${query}`);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ /* Refs */
+ const containerRef = useRef<HTMLDivElement>(null);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const listBoxRef = useRef<HTMLUListElement>(null);
+ const popoverRef = useRef<HTMLDivElement>(null);
+ const buttonRef = useRef<Element>(null);
+ const focusableNodes = useRef<Record<string, TreeNode>>({});
+ const instanceId = useId();
+
+ /* Disclosures */
+ const dropdown = useDisclosure();
+
+ /* Input */
+ const [controlledValue, setControlledValue] = useState("");
+
+ /* Output */
+ const [filteredOptionGroups, setFilteredOptionGroups] = useState<
+ OptionGroup[]
+ >([]);
+
+ /* Focus */
+ const [focusedId, setFocusedId] = useState<string | null>(null);
+
+ /* Selections */
+ const [selectionItemsById, setSelectionItemsById] =
+ useState<SelectionItemsById>(
+ innerProps.selections && innerProps.selections.length > 0
+ ? makeSelectionItemsById(innerProps.selections, innerProps.isMulti)
+ : {}
+ );
+
+ // Convert the tree from the server into a format that is easier to work with
+ const optionGroups = useMemo<OptionGroup[]>(() => {
+ const makeGroupItems = (
+ group: Group,
+ groupId: string
+ ): SelectionItemInterface[] => {
+ const result: SelectionItemInterface[] = [];
+
+ if (!innerProps.usersOnly) {
+ result.push({
+ ...group.data,
+ uid: getOptionId(groupId, group.data.id),
+ label: group.data.name || "",
+ children: group.children,
+ });
+
+ const subgroups = group.children.map((subgroup) => ({
+ ...subgroup.data,
+ uid: getOptionId(groupId, subgroup.data.id),
+ label: subgroup.data.name || "",
+ children: subgroup.children,
+ }));
+
+ result.push(...subgroups);
+ }
+
+ const users = group.data.users.map((user) => {
+ return {
+ ...user,
+ uid: getOptionId(groupId, user.id),
+ label: user.fullName || "",
+ };
+ });
+
+ result.push(...users);
+
+ return result;
+ };
+
+ // TODO filter for employeeTypes only and allowedUsers
+
+ return !groupsFetcher.data || !groupsFetcher.data.groups
+ ? []
+ : groupsFetcher.data.groups.reduce<OptionGroup[]>((acc, group) => {
+ if (
+ !innerProps.usersOnly ||
+ (group.data.users && group.data.users.length)
+ ) {
+ const uid = getGroupId(instanceId, group.data.id);
+ return acc.concat({
+ uid,
+ expanded: false,
+ items: makeGroupItems(group, uid),
+ name: group.data.name || "",
+ });
+ }
+ return acc;
+ }, []);
+ }, [groupsFetcher.data, innerProps.usersOnly, instanceId]);
+
+ /* Pre-populate controlled component after data loads */
+ useEffect(() => {
+ if (innerProps.value && optionGroups && optionGroups.length > 0) {
+ const flattened = optionGroups.reduce(
+ (acc, group) => acc.concat(group.items),
+ [] as SelectionItemInterface[]
+ );
+ if (Array.isArray(innerProps.value)) {
+ const selections = flattened.reduce((acc, item) => {
+ if (innerProps.value!.includes(item.id)) {
+ return {
+ ...acc,
+ [item.id]: item,
+ };
+ }
+ return acc;
+ }, {} as SelectionItemsById);
+ if (Object.keys(selections).length > 0) {
+ setSelectionItemsById(selections);
+ }
+ } else {
+ const selection = flattened.find(
+ (item) => item.id === innerProps.value
+ );
+ if (selection) {
+ setSelectionItemsById({
+ [selection?.id]: selection,
+ });
+ }
+ }
+ }
+ }, [optionGroups, innerProps.value]);
+
+ const makeFilteredOptionGroups = useCallback(
+ (filter?: string): OptionGroup[] =>
+ optionGroups.reduce((acc, group) => {
+ if (filter?.trim()) {
+ const matches = group.items.filter((item) =>
+ searchTermStartsWordInString(item.label, filter)
+ );
+ if (matches && matches.length) {
+ return acc.concat({
+ ...group,
+ expanded: true,
+ items: matches,
+ });
+ } else {
+ return acc;
+ }
+ } else {
+ return acc.concat(group);
+ }
+ }, [] as OptionGroup[]),
+ [optionGroups]
+ );
+
+ useEffect(() => {
+ setFilteredOptionGroups(makeFilteredOptionGroups());
+ }, [optionGroups, makeFilteredOptionGroups, setFilteredOptionGroups]);
+
+ /* Event Handlers */
+
+ const commit = useCallback(() => {
+ dropdown.onClose();
+ setFocusedId(null);
+ }, [dropdown, setFocusedId]);
+
+ useOutsideClick({
+ ref: containerRef,
+ handler: () => {
+ clear();
+ commit();
+ },
+ });
+
+ const focusInput = useCallback(() => {
+ if (inputRef.current) {
+ inputRef.current.focus();
+ }
+ }, []);
+
+ const clear = useCallback(() => {
+ setFilteredOptionGroups(makeFilteredOptionGroups());
+ setControlledValue("");
+ }, [makeFilteredOptionGroups, setControlledValue, setFilteredOptionGroups]);
+
+ const resetFocus = useCallback(() => {
+ setFocusedId(null);
+ focusInput();
+ if (listBoxRef) {
+ listBoxRef.current?.scrollTo(0, 0);
+ }
+ }, [focusInput]);
+
+ const onGroupExpand = useCallback(
+ (uid: string) =>
+ setFilteredOptionGroups((previousGroups) =>
+ previousGroups.map((group) =>
+ group.uid === uid ? { ...group, expanded: true } : group
+ )
+ ),
+ [setFilteredOptionGroups]
+ );
+
+ const onGroupCollapse = useCallback(
+ (uid: string) =>
+ setFilteredOptionGroups((previousGroups) =>
+ previousGroups.map((group) =>
+ group.uid === uid ? { ...group, expanded: false } : group
+ )
+ ),
+ [setFilteredOptionGroups]
+ );
+
+ const isExpanded = useCallback(
+ (uid: string) =>
+ filteredOptionGroups.some((g) => g.uid === uid && g.expanded),
+ [filteredOptionGroups]
+ );
+
+ const getFirstNode = useCallback(() => {
+ return Object.values(focusableNodes.current).find(
+ (node) => node !== undefined && node.previousId === undefined
+ );
+ }, []);
+
+ const getLastNode = useCallback(() => {
+ return Object.values(focusableNodes.current).find(
+ (node) => node !== undefined && node.nextId === undefined
+ );
+ }, []);
+
+ const getNextNode = useCallback(
+ (currentId: string | null) => {
+ if (currentId === null) {
+ if (!dropdown.isOpen) dropdown.onOpen();
+ return getFirstNode();
+ }
+
+ const { nextId } = focusableNodes.current[currentId];
+ if (nextId) {
+ return focusableNodes.current[nextId];
+ }
+ resetFocus();
+ return null;
+ },
+ [dropdown, getFirstNode, resetFocus]
+ );
+
+ const getPreviousNode = useCallback(
+ (currentId: string | null) => {
+ if (currentId === null) return getLastNode();
+
+ const { previousId } = focusableNodes.current[currentId];
+ if (previousId) {
+ return focusableNodes.current[previousId];
+ }
+ resetFocus();
+ return null;
+ },
+ [getLastNode, resetFocus]
+ );
+
+ const hasParent = useCallback(
+ (id: string) => {
+ const { parentId } = focusableNodes.current[id];
+ return parentId !== undefined;
+ },
+ [focusableNodes]
+ );
+
+ const hasChildren = useCallback((id: string) => {
+ return focusableNodes.current[id].expandable ?? false;
+ }, []);
+
+ const scrollTo = useCallback((elementId: string, delay: boolean) => {
+ const element = document.getElementById(elementId);
+ const block = "nearest";
+ if (element) {
+ if (delay) {
+ setTimeout(() => {
+ element.scrollIntoView({ block });
+ }, 80);
+ } else {
+ element.scrollIntoView({ block });
+ }
+ }
+ }, []);
+
+ const getSelectionById = useCallback(
+ (uid: string) => {
+ for (const group of filteredOptionGroups) {
+ const result = group.items.find((item) => item.uid === uid);
+ if (result) return result;
+ }
+
+ return undefined;
+ },
+ [filteredOptionGroups]
+ );
+
+ const setFocus = useCallback(
+ (command: string) => {
+ let nextFocusedId = focusedId;
+ let scrollDelay = false;
+ switch (command) {
+ case "first":
+ nextFocusedId = getFirstNode()?.uid ?? null;
+ break;
+ case "last":
+ nextFocusedId = getLastNode()?.uid ?? null;
+ break;
+ case "previous":
+ nextFocusedId = getPreviousNode(focusedId)?.uid ?? null;
+ break;
+ case "next":
+ nextFocusedId = getNextNode(focusedId)?.uid ?? null;
+ break;
+ default:
+ nextFocusedId = command;
+ scrollDelay = true;
+ }
+
+ setFocusedId(nextFocusedId);
+
+ if (nextFocusedId) {
+ const element = document.getElementById(nextFocusedId);
+ if (element) element.focus();
+ scrollTo(nextFocusedId, scrollDelay);
+ }
+ },
+ [
+ focusedId,
+ getFirstNode,
+ getLastNode,
+ getPreviousNode,
+ getNextNode,
+ scrollTo,
+ setFocusedId,
+ ]
+ );
+
+ const debouncedInputChange = useMemo(() => {
+ return debounce((search: string) => {
+ setFilteredOptionGroups(makeFilteredOptionGroups(search));
+ resetFocus();
+ }, 240);
+ }, [makeFilteredOptionGroups, resetFocus, setFilteredOptionGroups]);
+
+ const onInputFocus = useCallback(() => {
+ dropdown.onOpen();
+ resetFocus();
+ }, [dropdown, resetFocus]);
+
+ const onInputBlur = useCallback(
+ (e: any) => {
+ if (innerProps.onBlur && typeof innerProps.onBlur === "function") {
+ innerProps.onBlur(e);
+ }
+ },
+ [innerProps]
+ );
+
+ const onMouseOver = useCallback(() => {
+ setFocusedId(null);
+ }, []);
+
+ const onChange = useCallback(
+ (selections: SelectionItemInterface[]) => {
+ if (innerProps.onChange && typeof innerProps.onChange === "function") {
+ innerProps.onChange(selections);
+ }
+ },
+ [innerProps]
+ );
+
+ const onCheckedChange = useCallback(
+ (selections: SelectionItemInterface[]) => {
+ if (
+ innerProps.onCheckedSelectionsChange &&
+ typeof innerProps.onChange === "function"
+ ) {
+ innerProps.onCheckedSelectionsChange(selections);
+ }
+ },
+ [innerProps]
+ );
+
+ const onSelect = useCallback(
+ (selectionItem?: SelectionItemInterface) => {
+ if (selectionItem === undefined) return;
+ setSelectionItemsById((previousSelections) => {
+ const nextSelections = innerProps.isMulti
+ ? {
+ ...previousSelections,
+ }
+ : {};
+
+ nextSelections[selectionItem.id] = checked(selectionItem);
+
+ onChange(Object.values(nextSelections));
+ return nextSelections;
+ });
+ if (innerProps.isMulti && !innerProps.resetAfterSelection) {
+ setFocusedId(selectionItem.uid!);
+ } else {
+ console.log("resetting");
+ commit();
+ clear();
+ }
+ },
+ [
+ clear,
+ commit,
+ innerProps.isMulti,
+ innerProps.resetAfterSelection,
+ onChange,
+ setFocusedId,
+ setSelectionItemsById,
+ ]
+ );
+
+ const onDeselect = useCallback(
+ (selectionItem: SelectionItemInterface) => {
+ if (selectionItem === undefined) return;
+ const { id } = selectionItem;
+ setSelectionItemsById((previousSelections) => {
+ if (id in previousSelections) {
+ const { [id]: removed, ...newSelectionCodes } = previousSelections;
+
+ onChange(Object.values(newSelectionCodes));
+ return newSelectionCodes;
+ }
+
+ return previousSelections;
+ });
+ },
+ [onChange, setSelectionItemsById]
+ );
+
+ const onToggle = useCallback(
+ (selectionItem?: SelectionItemInterface) => {
+ if (selectionItem === undefined) return;
+ if (selectionItem.id in selectionItemsById) {
+ onDeselect(selectionItem);
+ } else {
+ onSelect(selectionItem);
+ }
+ },
+ [onDeselect, onSelect, selectionItemsById]
+ );
+
+ const onToggleChecked = useCallback(
+ (selectionItem?: SelectionItemInterface) => {
+ if (selectionItem === undefined) return;
+ setSelectionItemsById((previousSelections) => {
+ const nextSelections = {
+ ...previousSelections,
+ [selectionItem.id]: toggleChecked(selectionItem),
+ };
+
+ onCheckedChange(Object.values(nextSelections));
+ return nextSelections;
+ });
+ },
+ []
+ );
+
+ const removeSelections = useCallback(() => {
+ Object.values(selectionItemsById).forEach((item) => {
+ onDeselect(item);
+ });
+ }, [onDeselect, selectionItemsById]);
+
+ const onClearInput = useCallback(() => {
+ clear();
+ if (!innerProps.isMulti) {
+ removeSelections();
+ }
+ }, [clear, innerProps.isMulti, removeSelections]);
+
+ const onInputChange = useCallback(
+ ({ target }: ChangeEvent<HTMLInputElement>): void => {
+ setControlledValue(target.value);
+ debouncedInputChange(target.value);
+
+ if (target.value?.length > 0) {
+ dropdown.onOpen();
+ } else if (!innerProps.isMulti) {
+ removeSelections();
+ }
+ },
+ [
+ debouncedInputChange,
+ dropdown,
+ innerProps.isMulti,
+ removeSelections,
+ setControlledValue,
+ ]
+ );
+
+ const onExplode = useCallback(
+ (selectionItem: SelectionItemInterface) => {
+ if (!("users" in selectionItem)) return;
+
+ const { id, users, children } = selectionItem;
+
+ setSelectionItemsById((prevSelectionItems) => {
+ if (id in prevSelectionItems) {
+ const { [id]: removed, ...newSelectionItems } = prevSelectionItems;
+
+ users.forEach((user) => {
+ newSelectionItems[user.id] = {
+ ...user,
+ uid: getOptionId(id, user.id),
+ label: user.fullName || "",
+ };
+ });
+
+ children?.forEach((group) => {
+ newSelectionItems[group.data.id] = {
+ ...group.data,
+ uid: getOptionId(id, group.data.id),
+ label: group.data.name || "",
+ };
+ });
+
+ onChange(Object.values(newSelectionItems));
+ return newSelectionItems;
+ }
+
+ return prevSelectionItems;
+ });
+ },
+ [onChange, setSelectionItemsById]
+ );
+
+ const onKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLInputElement>) => {
+ if (innerProps.disabled) {
+ return;
+ }
+
+ switch (event.key) {
+ case "ArrowLeft":
+ if (focusedId) {
+ if (hasParent(focusedId)) {
+ const { parentId } = focusableNodes.current[focusedId];
+ onGroupCollapse(parentId!);
+ setFocus(parentId!);
+ } else {
+ onGroupCollapse(focusedId);
+ }
+ break;
+ } else {
+ return;
+ }
+
+ case "ArrowRight":
+ if (focusedId && hasChildren(focusedId)) {
+ if (isExpanded(focusedId)) {
+ setFocus("next");
+ } else {
+ onGroupExpand(focusedId);
+ }
+ break;
+ } else {
+ return;
+ }
+
+ case "Tab":
+ clear();
+ commit();
+ return;
+ case "Enter":
+ if (focusedId && hasParent(focusedId)) {
+ onSelect(getSelectionById(focusedId));
+ clear();
+ commit();
+ break;
+ }
+ break;
+ case "Escape":
+ if (dropdown.isOpen) {
+ commit();
+ } else {
+ clear();
+ }
+ break;
+ case " ": // space
+ if (focusedId) {
+ if (hasParent(focusedId)) {
+ onToggle(getSelectionById(focusedId));
+ }
+ break;
+ }
+ return;
+ case "ArrowUp":
+ setFocus("previous");
+ break;
+ case "ArrowDown":
+ if (dropdown.isOpen) {
+ setFocus("next");
+ } else {
+ dropdown.onOpen();
+ }
+ break;
+ case "Home":
+ if (!dropdown.isOpen) return;
+ setFocus("first");
+ break;
+ case "End":
+ if (!dropdown.isOpen) return;
+ setFocus("last");
+ break;
+ default:
+ resetFocus();
+ return;
+ }
+ event.preventDefault();
+ },
+ [
+ commit,
+ dropdown,
+ focusedId,
+ getSelectionById,
+ hasParent,
+ hasChildren,
+ isExpanded,
+ innerProps.disabled,
+ clear,
+ onGroupCollapse,
+ onGroupExpand,
+ onSelect,
+ onToggle,
+ resetFocus,
+ setFocus,
+ ]
+ );
+
+ /* Accessibility */
+
+ const popoverProps = useMemo<AriaAttributes>(() => ({}), []);
+
+ const listBoxProps = useMemo<AriaAttributes & { id: string }>(
+ () => ({
+ id: instanceId,
+ role: "tree",
+ tabIndex: -1,
+ }),
+ [instanceId]
+ );
+
+ const inputProps = useMemo<AriaAttributes>(
+ () => ({
+ role: "combobox",
+ "aria-expanded": dropdown.isOpen,
+ "aria-controls": dropdown.isOpen ? instanceId : undefined,
+ "aria-haspopup": "tree",
+ "aria-autocomplete": "list",
+ "aria-activedescendant": undefined, // TODO
+ autoComplete: "off",
+ autoCorrect: "off",
+ }),
+ [instanceId, dropdown.isOpen]
+ );
+
+ const aria = useMemo(
+ () => ({
+ inputProps,
+ listBoxProps,
+ popoverProps,
+ }),
+ [inputProps, listBoxProps, popoverProps]
+ );
+
+ let inputValue =
+ innerProps.isMulti || focusedId || controlledValue
+ ? controlledValue
+ : Object.values(selectionItemsById)?.[0]?.label ?? "";
+
+ return {
+ aria,
+ groups: filteredOptionGroups,
+ errors: groupsFetcher.data?.errors,
+ loading: groupsFetcher.state === "loading",
+ selectionItemsById,
+ // focus
+ instanceId,
+ focusedId,
+ // filters
+ inputValue,
+ // disclosures
+ dropdown,
+ // props
+ innerProps,
+ refs: {
+ containerRef,
+ inputRef,
+ listBoxRef,
+ popoverRef,
+ buttonRef,
+ focusableNodes,
+ },
+ // event handlers
+ onClearInput,
+ onKeyDown,
+ onGroupCollapse,
+ onGroupExpand,
+ onInputChange,
+ onInputBlur,
+ onInputFocus,
+ onSelect,
+ onDeselect,
+ onToggleChecked,
+ onExplode,
+ onMouseOver,
+ setControlledValue,
+ setSelectionItemsById,
+ };
+}
+
+function getOptionId(groupId: string, optionId: string) {
+ return `${groupId}_${optionId}_option`;
+}
+
+function getGroupId(instanceId: string, groupId: string) {
+ return `${instanceId}_${groupId}_group`;
+}
+
+function checked(item: SelectionItemInterface): SelectionItemInterface {
+ return {
+ ...item,
+ isChecked: true,
+ };
+}
+
+export function isGroup(item: SelectionItemInterface) {
+ return (
+ ("users" in item && item.users?.length > 0) ||
+ ("children" in item && item?.children?.length)
+ );
+}
+
+function toggleChecked(item: SelectionItemInterface): SelectionItemInterface {
+ return {
+ ...item,
+ isChecked: !item.isChecked || false,
+ };
+}
+
+function makeSelectionItemsById(
+ input: SelectionItemInterface[],
+ isMulti: boolean
+): SelectionItemsById {
+ const result: SelectionItemsById = {};
+ input.forEach((item) => {
+ if (!(item.id in result)) {
+ result[item.id] = checked(item);
+ // early exit for signle user select
+ if (!isMulti) return result;
+ }
+ });
+ return result;
+}
+
+function searchTermStartsWordInString(string: string, searchTerm: string) {
+ const stringLowerCase = string.toLocaleLowerCase().trim();
+ const searchTermLowerCase = searchTerm.toLocaleLowerCase().trim();
+ if (stringLowerCase.startsWith(searchTermLowerCase)) {
+ return true;
+ }
+ const searchTermWords = words(searchTermLowerCase);
+ const stringWords = words(stringLowerCase);
+ return stringWords.some((stringWord) =>
+ searchTermWords.some((searchTermWord) =>
+ stringWord.startsWith(searchTermWord)
+ )
+ );
+}
diff --git a/apps/carbon/app/components/Selectors/index.ts b/apps/carbon/app/components/Selectors/index.ts
new file mode 100644
index 0000000000..a6719e57fb
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/index.ts
@@ -0,0 +1,3 @@
+import UserSelect from "./UserSelect";
+
+export { UserSelect };
diff --git a/apps/carbon/app/modules/Users/types.ts b/apps/carbon/app/modules/Users/types.ts
index 13c6500cd5..535951882f 100644
--- a/apps/carbon/app/modules/Users/types.ts
+++ b/apps/carbon/app/modules/Users/types.ts
@@ -25,6 +25,15 @@ export type Feature = NonNullable<
Awaited<ReturnType<typeof getFeatures>>["data"]
>[number];
+export type Group = {
+ data: {
+ id: string;
+ name: string;
+ users: User[];
+ };
+ children: Group[];
+};
+
export type Permission = {
view: boolean;
create: boolean;
diff --git a/apps/carbon/app/routes/app.index.tsx b/apps/carbon/app/routes/app.index.tsx
new file mode 100644
index 0000000000..e429c20202
--- /dev/null
+++ b/apps/carbon/app/routes/app.index.tsx
@@ -0,0 +1,14 @@
+import { Box } from "@chakra-ui/react";
+import { UserSelect } from "~/components/Selectors";
+
+export default function AppRoute() {
+ return (
+ <Box maxW={400} p={4}>
+ <UserSelect
+ isMulti
+ placeholder="Select users"
+ value={"00000000-0000-0000-0000-000000000000"}
+ />
+ </Box>
+ );
+}
diff --git a/apps/carbon/app/routes/app.tsx b/apps/carbon/app/routes/app.tsx
index 169c3255fb..342f10f269 100644
--- a/apps/carbon/app/routes/app.tsx
+++ b/apps/carbon/app/routes/app.tsx
@@ -1,5 +1,6 @@
import { useNotification } from "@carbon/react";
import { Box, Grid, GridItem } from "@chakra-ui/react";
+import { SkipNavContent } from "@chakra-ui/skip-nav";
import type { LoaderArgs } from "@remix-run/node";
import { json } from "@remix-run/node";
import { Outlet, useLoaderData } from "@remix-run/react";
@@ -71,6 +72,7 @@ export default function AppRoute() {
<Grid templateColumns="auto 1fr" h="full" w="full">
<IconSidebar />
<Box w="full" h="full">
+ <SkipNavContent />
<Outlet />
</Box>
</Grid>
diff --git a/apps/carbon/app/routes/app.users.tsx b/apps/carbon/app/routes/app.users.tsx
index 7fcbe58bc8..91a66e7423 100644
--- a/apps/carbon/app/routes/app.users.tsx
+++ b/apps/carbon/app/routes/app.users.tsx
@@ -1,6 +1,5 @@
import { useColor } from "@carbon/react";
import { Box, Button, Grid, Text, VStack } from "@chakra-ui/react";
-import { SkipNavContent } from "@chakra-ui/skip-nav";
import type { MetaFunction } from "@remix-run/node";
import { Link, Outlet, useMatches } from "@remix-run/react";
import { ContentSidebar } from "~/components/Navigation/Sidebar";
@@ -19,7 +18,6 @@ export default function UsersRoute() {
return (
<Grid w="full" h="full" templateColumns="auto 1fr" overflow="auto">
<ContentSidebar>
- <SkipNavContent />
<VStack spacing={2}>
{links.map((groups) =>
Object.entries(groups).map(([group, routes]) => (
diff --git a/apps/carbon/app/routes/resource.groups.tsx b/apps/carbon/app/routes/resource.groups.tsx
index ae1177d4b2..a930044a4e 100644
--- a/apps/carbon/app/routes/resource.groups.tsx
+++ b/apps/carbon/app/routes/resource.groups.tsx
@@ -2,6 +2,7 @@ import type { LoaderArgs } from "@remix-run/node";
import { json } from "@remix-run/node";
import { arrayToTree } from "performant-array-to-tree";
import { getSupabase } from "~/lib/supabase";
+import type { Group } from "~/modules/Users/types";
import { requireAuthSession, setSessionFlash } from "~/services/session";
export async function loader({ request }: LoaderArgs) {
@@ -11,7 +12,7 @@ export async function loader({ request }: LoaderArgs) {
const groups = await client.from("groups_view").select("*");
if (groups.error) {
return json(
- { groups: [] },
+ { groups: [], error: groups.error },
await setSessionFlash(request, {
success: false,
message: "Failed to load groups",
@@ -20,6 +21,6 @@ export async function loader({ request }: LoaderArgs) {
}
return json({
- groups: arrayToTree(groups.data),
+ groups: arrayToTree(groups.data) as Group[],
});
}
diff --git a/apps/carbon/app/services/users/users.server.ts b/apps/carbon/app/services/users/users.server.ts
index 4ba585d3ff..5072dd4d18 100644
--- a/apps/carbon/app/services/users/users.server.ts
+++ b/apps/carbon/app/services/users/users.server.ts
@@ -99,7 +99,10 @@ export async function createEmployeeAccount(
};
}
-async function createUser(client: SupabaseClient<Database>, user: User) {
+async function createUser(
+ client: SupabaseClient<Database>,
+ user: Omit<User, "fullName">
+) {
const { data, error } = await insertUser(client, user);
if (error) {
@@ -295,7 +298,7 @@ export async function getUserByEmail(email: string) {
export async function getUsers(client: SupabaseClient<Database>) {
return client
.from("user")
- .select("id, firstName, lastName, email")
+ .select("id, firstName, lastName, fullName, email")
.order("lastName");
}
@@ -306,7 +309,10 @@ export async function insertEmployee(
return client.from("employee").insert([employee]);
}
-async function insertUser(client: SupabaseClient<Database>, user: User) {
+async function insertUser(
+ client: SupabaseClient<Database>,
+ user: Omit<User, "fullName">
+) {
return client.from("user").insert([user]).select("*");
}
diff --git a/apps/carbon/app/types/aria.ts b/apps/carbon/app/types/aria.ts
new file mode 100644
index 0000000000..412c0dbe3a
--- /dev/null
+++ b/apps/carbon/app/types/aria.ts
@@ -0,0 +1 @@
+export type AriaLiveValues = "polite" | "assertive" | "off";
diff --git a/apps/carbon/app/types/chakra.ts b/apps/carbon/app/types/chakra.ts
new file mode 100644
index 0000000000..c598841b39
--- /dev/null
+++ b/apps/carbon/app/types/chakra.ts
@@ -0,0 +1,14 @@
+import type { CSSWithMultiValues, RecursiveCSSObject } from "@chakra-ui/react";
+
+export interface SizeProps<PropType = string | number> {
+ sm: PropType;
+ md: PropType;
+ lg: PropType;
+}
+
+export interface SxProps extends CSSWithMultiValues {
+ _disabled?: CSSWithMultiValues;
+ _focus?: CSSWithMultiValues;
+}
+
+export type ThemeObject = RecursiveCSSObject<SxProps>;
diff --git a/apps/carbon/app/types/index.ts b/apps/carbon/app/types/index.ts
index 3de0f0b77f..cbe182edde 100644
--- a/apps/carbon/app/types/index.ts
+++ b/apps/carbon/app/types/index.ts
@@ -3,15 +3,15 @@ import type { TypedResponse } from "@remix-run/node";
import type { ReactElement } from "react";
import type { ValidationErrorResponseData } from "remix-validated-form";
-export type FormActionData = Promise<
- TypedResponse<ValidationErrorResponseData> | TypedResponse<Result>
->;
-
export type Authenticated<T> = T & {
permission?: string;
action?: "view" | "create" | "update" | "delete";
};
+export type FormActionData = Promise<
+ TypedResponse<ValidationErrorResponseData> | TypedResponse<Result>
+>;
+
export type NavItem = Omit<Route, "icon"> & {
icon: ReactElement;
};
diff --git a/apps/carbon/package.json b/apps/carbon/package.json
index bd80e52552..1f6616c910 100644
--- a/apps/carbon/package.json
+++ b/apps/carbon/package.json
@@ -28,6 +28,8 @@
"@supabase/supabase-js": "^2.1.0",
"@vercel/node": "^2.8.0",
"framer-motion": "^7.6.19",
+ "lodash/words": "^4.2.2",
+ "lodash/debounce": "^4.0.8",
"performant-array-to-tree": "1.11.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
diff --git a/packages/carbon-database/prisma/migrations/20221208201232_groups/migration.sql b/packages/carbon-database/prisma/migrations/20221208201232_groups/migration.sql
index d4254b0f98..939bbdbe76 100644
--- a/packages/carbon-database/prisma/migrations/20221208201232_groups/migration.sql
+++ b/packages/carbon-database/prisma/migrations/20221208201232_groups/migration.sql
@@ -204,7 +204,7 @@ CREATE VIEW groups_view AS
FROM groups_recursive
WHERE "isIdentityGroup" = false
GROUP BY "groupId", "name", "parentId", "isEmployeeTypeGroup"
- ORDER BY "isEmployeeTypeGroup" DESC;
+ ORDER BY "isEmployeeTypeGroup" DESC, "name" ASC;
CREATE OR REPLACE FUNCTION groups_for_user(uid text) RETURNS "jsonb"
diff --git a/packages/carbon-react/src/Inputs/Select/components/menu.tsx b/packages/carbon-react/src/Inputs/Select/components/menu.tsx
index c596ef0530..e1384d758a 100644
--- a/packages/carbon-react/src/Inputs/Select/components/menu.tsx
+++ b/packages/carbon-react/src/Inputs/Select/components/menu.tsx
@@ -1,9 +1,9 @@
+import { useColor } from "@carbon/react";
import type { IconProps, SystemStyleObject } from "@chakra-ui/react";
import {
Box,
Icon,
MenuIcon,
- useColorModeValue,
useMultiStyleConfig,
useTheme,
} from "@chakra-ui/react";
@@ -131,7 +131,7 @@ export const LoadingMessage = <
*
* @see {@link https://github.com/chakra-ui/chakra-ui/blob/13c6d2e08b61e179773be4722bb81173dd599306/packages/theme/src/styles.ts#L13}
*/
- const color = useColorModeValue("gray.400", "whiteAlpha.400");
+ const color = useColor("gray.400");
const fontSizes: SizeProps = {
sm: "0.875rem",
@@ -193,7 +193,7 @@ export const NoOptionsMessage = <
*
* @see {@link https://github.com/chakra-ui/chakra-ui/blob/13c6d2e08b61e179773be4722bb81173dd599306/packages/theme/src/styles.ts#L13}
*/
- const color = useColorModeValue("gray.400", "whiteAlpha.400");
+ const color = useColor("gray.400");
const fontSizes: SizeProps = {
sm: "0.875rem",
@@ -374,19 +374,9 @@ export const Option = <
lg: "0.5rem 1rem",
};
- /**
- * Use the same selected color as the border of the select component
- *
- * @see {@link https://github.com/chakra-ui/chakra-ui/blob/13c6d2e08b61e179773be4722bb81173dd599306/packages/theme/src/components/input.ts#L73}
- */
- const selectedBg = useColorModeValue(
- `${selectedOptionColor}.500`,
- `${selectedOptionColor}.300`
- );
- const selectedColor = useColorModeValue("white", "black");
+ const selectedBg = useColor("gray.500");
+ const selectedColor = useColor("white");
- // Don't create exta space for the checkmark if using a multi select with
- // options that dissapear when they're selected
const showCheckIcon: boolean =
selectedOptionStyle === "check" &&
(!isMulti || hideSelectedOptions === false);
diff --git a/packages/carbon-react/src/Loading/Loading.tsx b/packages/carbon-react/src/Loading/Loading.tsx
new file mode 100644
index 0000000000..7b424f667a
--- /dev/null
+++ b/packages/carbon-react/src/Loading/Loading.tsx
@@ -0,0 +1,22 @@
+import { Center, Spinner, useColorMode } from "@chakra-ui/react";
+
+type LoadingProps = {
+ size?: "sm" | "md" | "lg" | "xl";
+};
+
+export default function Loading({ size = "lg" }: LoadingProps) {
+ const { colorMode } = useColorMode();
+ const emptyColor = colorMode !== "dark" ? "gray.200" : "whiteAlpha.300";
+
+ return (
+ <Center h="full" w="full">
+ <Spinner
+ thickness="4px"
+ speed="1s"
+ emptyColor={emptyColor}
+ color="brand.500"
+ size={size}
+ />
+ </Center>
+ );
+}
diff --git a/packages/carbon-react/src/Loading/index.ts b/packages/carbon-react/src/Loading/index.ts
new file mode 100644
index 0000000000..e1c0ccbd7b
--- /dev/null
+++ b/packages/carbon-react/src/Loading/index.ts
@@ -0,0 +1,3 @@
+import Loading from "./Loading";
+
+export default Loading;
diff --git a/packages/carbon-react/src/index.tsx b/packages/carbon-react/src/index.tsx
index 5dbe6c40f5..44611388f4 100644
--- a/packages/carbon-react/src/index.tsx
+++ b/packages/carbon-react/src/index.tsx
@@ -1,5 +1,6 @@
import type { OptionBase, GroupBase } from "./Inputs";
import { Select } from "./Inputs";
+import Loading from "./Loading";
import { ActionMenu } from "./Overlay";
import { useNotification } from "./Message";
import ThemeProvider, { theme } from "./Theme";
@@ -11,6 +12,7 @@ export type { OptionBase, GroupBase };
export {
ActionMenu,
ClientOnly,
+ Loading,
Select,
ThemeProvider,
theme,