UNPKG

@1771technologies/lytenyte-pro

Version:

Blazingly fast headless React data grid with 100s of features.

80 lines (79 loc) 3.41 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { createContext, forwardRef, useContext } from "react"; import { useSlot } from "../../hooks/use-slot/index.js"; import { useChipContext } from "./chip-context.js"; import { useSmartSelect } from "./context.js"; import { useEvent } from "@1771technologies/lytenyte-core/internal"; const context = createContext(null); export const useChip = () => useContext(context); function ChipBase({ render, option, ...props }, ref) { const { activeChip, setActiveChip } = useChipContext(); const { kindAndValue: { value }, onOptionsChange, preventNextOpen, rtl, trigger, inputRef, } = useSmartSelect(); const v = value; const remove = useEvent(() => { onOptionsChange(v.filter((x) => x.id !== option.id)); preventNextOpen.current = true; }); const r = useSlot({ props: [ props, { tabIndex: -1, "data-ln-smart-select-chip": option.id }, { onKeyDown: (ev) => { const start = rtl ? "ArrowRight" : "ArrowLeft"; const end = rtl ? "ArrowLeft" : "ArrowRight"; const chips = Array.from(trigger.querySelectorAll("[data-ln-smart-select-chip]")); const thisIndex = chips.indexOf(ev.currentTarget); if (thisIndex === -1) return; if (ev.key === "Backspace" || ev.key === "Delete") { remove(); const dir = ev.key === "Backspace" ? 1 : -1; let next = chips[thisIndex + dir]; if (!next) next = chips[thisIndex - dir]; if (!next) { setActiveChip(null); inputRef.current?.focus(); } else { next.focus(); setActiveChip(next.getAttribute("data-ln-smart-select-chip")); } return; } if (ev.key === "Delete" || ev.key === "Backspace") { console.log(" i ran"); } if (ev.key === start) { const next = chips[thisIndex - 1]; if (!next) return; next.focus(); setActiveChip(next.getAttribute("data-ln-smart-select-chip")); } else if (ev.key === end) { const next = chips[thisIndex + 1]; if (!next) { setActiveChip(null); inputRef.current?.focus(); } else { next.focus(); setActiveChip(next.getAttribute("data-ln-smart-select-chip")); } } }, }, ], ref: ref, slot: render ?? _jsx("div", {}), state: { option, active: activeChip === option.id, remove, }, }); return _jsx(context.Provider, { value: remove, children: r }); } export const Chip = forwardRef(ChipBase);