All files / src/components/forms PaletteSelectButton.tsx

81.25% Statements 65/80
43.05% Branches 31/72
77.77% Functions 21/27
82.27% Lines 65/79

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 2262x 2x 2x       2x 2x 2x 2x 2x 2x                               2x                   2x               2x 3x 3x 3x 3x 3x             3x         3x 3x 3x       2x       2x                       3x 3x   3x 3x     3x         3x   3x 3x 3x   3x 2x 1x   2x 2x       3x 3x 1x   3x 3x       3x           3x             3x 1x 1x     3x 1x     3x 1x 1x 1x     3x 1x     3x 1x     3x       3x           3x 1x         3x 3x               3x                                                                                 2x      
import React, { memo, useEffect, useRef, useState } from "react";
import styled from "styled-components";
import {
  getLocalisedDMGPalette,
  getLocalisedPaletteById,
} from "store/features/entities/entitiesSelectors";
import PaletteBlock, { PaletteBlockType } from "components/forms/PaletteBlock";
import { SelectMenu, selectMenuStyleProps } from "ui/form/Select";
import { RelativePortal } from "ui/layout/RelativePortal";
import { PaletteSelect } from "./PaletteSelect";
import navigationActions from "store/features/navigation/navigationActions";
import { useAppDispatch, useAppSelector } from "store/hooks";
import { Palette } from "shared/lib/resources/types";
 
type PaletteSelectProps = {
  name: string;
  value?: string;
  type?: PaletteBlockType;
  onChange?: (newId: string) => void;
  slotNumber?: number;
  optional?: boolean;
  optionalLabel?: string;
  optionalDefaultPaletteId?: string;
  canAuto?: boolean;
  autoPalette?: Palette;
};
 
const Wrapper = styled.div`
  position: relative;
  display: inline-flex;
  min-width: 0;
  flex-shrink: 0;
  & * {
    min-width: 0;
  }
`;
 
const ButtonCover = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 28px;
  height: 28px;
`;
 
const Button = styled.button`
  background: ${(props) => props.theme.colors.input.background};
  color: ${(props) => props.theme.colors.input.text};
  border: 1px solid ${(props) => props.theme.colors.input.border};
  font-size: ${(props) => props.theme.typography.fontSize};
  border-radius: ${(props) => props.theme.borderRadius}px;
  padding: 1px;
  box-sizing: border-box;
  height: 28px;
  flex-shrink: 0;
 
  &:hover {
    background: ${(props) => props.theme.colors.input.hoverBackground};
  }
 
  &:focus,
  &&&:focus:not(.focus-visible) {
    border: 1px solid ${(props) => props.theme.colors.highlight};
    background: ${(props) => props.theme.colors.input.activeBackground};
    box-shadow: 0 0 0px 2px ${(props) => props.theme.colors.highlight} !important;
  }
`;
 
const NoValue = styled.div`
  width: 24px;
`;
 
const PaletteSelectButtonComponent = ({
  name,
  value,
  type,
  slotNumber,
  onChange,
  optional,
  optionalLabel,
  optionalDefaultPaletteId,
  canAuto,
  autoPalette,
}: PaletteSelectProps) => {
  const buttonRef = useRef<HTMLButtonElement>(null);
  const timerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
 
  let paletteId = value || "";
  Iif (optional && !value) {
    paletteId = optionalDefaultPaletteId || "";
  }
  Iif (paletteId === "auto" && !autoPalette) {
    paletteId = optionalDefaultPaletteId || "";
  }
 
  const palette =
    useAppSelector((state) => getLocalisedPaletteById(state, paletteId)) ||
    (value === "auto" && autoPalette ? autoPalette : getLocalisedDMGPalette());
  const [isOpen, setIsOpen] = useState<boolean>(false);
  const [buttonFocus, setButtonFocus] = useState<boolean>(false);
  const dispatch = useAppDispatch();
 
  useEffect(() => {
    if (buttonFocus) {
      window.addEventListener("keydown", onKeyDownClosed);
    }
    return () => {
      window.removeEventListener("keydown", onKeyDownClosed);
    };
  }, [buttonFocus]);
 
  useEffect(() => {
    if (isOpen) {
      window.addEventListener("keydown", onKeyDownOpen);
    }
    return () => {
      window.removeEventListener("keydown", onKeyDownOpen);
    };
  }, [isOpen]);
 
  const onKeyDownClosed = (e: KeyboardEvent) => {
    if (e.key === "ArrowDown" || e.key === "ArrowUp") {
      setIsOpen(true);
    }
  };
 
  const onKeyDownOpen = (e: KeyboardEvent) => {
    if (e.key === "Escape") {
      setIsOpen(false);
      buttonRef.current?.focus();
    }
  };
 
  const openMenu = () => {
    setIsOpen(true);
    cancelDelayedButtonFocus();
  };
 
  const closeMenu = () => {
    setIsOpen(false);
  };
 
  const onSelectChange = (newValue: string) => {
    closeMenu();
    onChange?.(newValue);
    buttonRef.current?.focus();
  };
 
  const onCreatePalette = (newValue: string) => {
    onChange?.(newValue);
  };
 
  const onButtonFocus = () => {
    setButtonFocus(true);
  };
 
  const onButtonBlur = () => {
    setButtonFocus(false);
  };
 
  const delayedButtonFocus = () => {
    timerRef.current = setTimeout(() => {
      buttonRef.current?.focus();
    }, 100);
  };
 
  const cancelDelayedButtonFocus = () => {
    Iif (timerRef.current) {
      clearTimeout(timerRef.current);
    }
  };
 
  const onJumpToPalette = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    Iif (e.altKey) {
      if (palette) {
        dispatch(navigationActions.setSection("palettes"));
        dispatch(navigationActions.setNavigationId(palette.id || ""));
      }
    }
  };
 
  return (
    <Wrapper onClick={onJumpToPalette}>
      <Button
        id={name}
        ref={buttonRef}
        onClick={openMenu}
        onFocus={onButtonFocus}
        onBlur={onButtonBlur}
        title={slotNumber ? `${slotNumber}: ${palette.name}` : palette.name}
      >
        {palette ? (
          <PaletteBlock type={type} colors={palette?.colors || []} size={22} />
        ) : (
          <NoValue />
        )}
      </Button>
      {isOpen && <ButtonCover onMouseDown={delayedButtonFocus} />}
      <RelativePortal pin="top-right" offsetY={28}>
        {isOpen && (
          <SelectMenu>
            <PaletteSelect
              name={name}
              value={value}
              type={type}
              onChange={onSelectChange}
              onCreate={onCreatePalette}
              onBlur={closeMenu}
              optional={optional}
              optionalLabel={optionalLabel}
              optionalDefaultPaletteId={optionalDefaultPaletteId}
              canAuto={canAuto}
              autoPalette={autoPalette}
              {...selectMenuStyleProps}
            />
          </SelectMenu>
        )}
      </RelativePortal>
    </Wrapper>
  );
};
 
export const PaletteSelectButton = memo<PaletteSelectProps>(
  PaletteSelectButtonComponent,
);