Skip to content
Snippets Groups Projects
Palette.tsx 2.25 KiB
Newer Older
Grant's avatar
Grant committed
import { useEffect, useState } from "react";
Grant's avatar
Grant committed
import { useAppContext } from "../../contexts/AppContext";
import { Canvas } from "../../lib/canvas";
Grant's avatar
Grant committed
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faXmark } from "@fortawesome/free-solid-svg-icons";
import { IPaletteContext } from "@sc07-canvas/lib/src/net";
Grant's avatar
Grant committed
import { KeybindManager } from "../../lib/keybinds";
Grant's avatar
Grant committed
export const Palette = () => {
Grant's avatar
Grant committed
  const { config, user, setCursor } = useAppContext<true>();
  const [pallete, setPallete] = useState<IPaletteContext>({});
Grant's avatar
Grant committed

  useEffect(() => {
Grant's avatar
Grant committed
    Canvas.instance?.updatePallete(pallete);
Grant's avatar
Grant committed
    setCursor((v) => ({
      ...v,
      color: pallete.color,
    }));
Grant's avatar
Grant committed
  }, [pallete]);

Grant's avatar
Grant committed
  useEffect(() => {
    const handleDeselect = () => {
      setCursor((v) => ({
        ...v,
        color: undefined,
      }));
    };

    KeybindManager.addListener("DESELECT_COLOR", handleDeselect);

    return () => {
      KeybindManager.removeListener("DESELECT_COLOR", handleDeselect);
    };
  }, []);

Grant's avatar
Grant committed
  return (
    <div id="pallete">
      <div className="pallete-colors">
        <button
          aria-label="Deselect Color"
          className="pallete-color--deselect"
          title="Deselect Color"
          onClick={() => {
            setPallete(({ color, ...pallete }) => {
              return pallete;
            });
          }}
        >
          <FontAwesomeIcon icon={faXmark} />
        </button>
        {config.pallete.colors.map((color) => (
          <button
            key={color.id}
            aria-label={color.name}
            className={["pallete-color", color.id === pallete.color && "active"]
              .filter((a) => a)
              .join(" ")}
            style={{
              backgroundColor: "#" + color.hex,
            }}
            title={color.name}
            onClick={() => {
              setPallete((pallete) => {
                return {
                  ...pallete,
                  color: color.id,
                };
              });
            }}
          ></button>
        ))}
      </div>

      {!user && (
        <div className="pallete-user-overlay">
          You are not logged in
          <a href="/api/login" className="user-login">
            Login
          </a>
        </div>
      )}
    </div>
  );
};