"use client"; import type { FocusEventHandler, KeyboardEventHandler } from "react"; import { startTransition, useEffect, useMemo, useState } from "react"; import { ActionIcon, Box, Button, CloseButton, Combobox, Group, Image, InputBase, Loader, Paper, SimpleGrid, Skeleton, Stack, Text, ThemeIcon, Tooltip, useCombobox, } from "@mantine/core"; import { useDebouncedValue, useUncontrolled } from "@mantine/hooks"; import { IconCheck, IconCloud, IconMoodEmpty, IconPhoto, IconPhotoOff, IconSearchOff, IconUpload, } from "@tabler/icons-react"; import { clientApi } from "@homarr/api/client"; import { useSession } from "@homarr/auth/client"; import { supportedLanguages } from "@homarr/translation"; import { useScopedI18n } from "@homarr/translation/client"; import { UploadMedia } from "../upload-media/upload-media"; import { arrangeIconPickerSections, isDirectImageUrl, isImageSource, isSvgImage } from "./icon-picker.utils"; import classes from "./icon-picker.module.css"; interface IconPickerProps { value?: string; onChange: (iconUrl: string) => void; error?: string | null; onFocus?: FocusEventHandler; onBlur?: FocusEventHandler; label?: string; placeholder?: string; suggestedSearch?: string | null; withAsterisk?: boolean; } type PreviewState = "idle" | "loading" | "ready" | "error"; export const IconPicker = ({ value: propsValue, onChange, error, onFocus, onBlur, withAsterisk = true, label, placeholder, suggestedSearch, }: IconPickerProps) => { const [value, setValue] = useUncontrolled({ value: propsValue, onChange, defaultValue: "" }); const [draft, setDraft] = useState(propsValue ?? ""); const [hasEdited, setHasEdited] = useState(false); const [keyboardIndex, setKeyboardIndex] = useState(-1); const [previewState, setPreviewState] = useState("idle"); const { data: session } = useSession(); const tCommon = useScopedI18n("common"); const [debouncedDraft] = useDebouncedValue(draft, 250); const directUrl = isDirectImageUrl(draft) ? draft.trim() : null; const isCommittedValueDraft = debouncedDraft === (value ?? ""); const searchText = directUrl !== null || isCommittedValueDraft ? "" : debouncedDraft.trim(); const canUpload = session?.user.permissions.includes("media-upload") ?? false; const query = clientApi.icon.findIcons.useQuery( { searchText, limitPerGroup: 24 }, { enabled: directUrl === null, placeholderData: (previous) => previous }, ); const combobox = useCombobox({ onDropdownClose: () => combobox.resetSelectedOption(), onDropdownOpen: () => combobox.updateSelectedOptionIndex("active"), }); useEffect(() => { setDraft(value ?? ""); setHasEdited(false); }, [value]); useEffect(() => { setPreviewState(directUrl ? "loading" : "idle"); }, [directUrl]); const sections = useMemo( () => arrangeIconPickerSections(query.data?.icons ?? [], searchText), [query.data?.icons, searchText], ); const orderedOptions = useMemo( () => [...sections.local, ...sections.svg, ...sections.other], [sections.local, sections.svg, sections.other], ); const totalOptions = sections.local.length + sections.svg.length + sections.other.length; const commitValue = (nextValue: string) => { startTransition(() => { setValue(nextValue); setDraft(nextValue); setHasEdited(false); setKeyboardIndex(-1); }); }; const clearValue = () => { commitValue(""); combobox.openDropdown("keyboard"); }; const openWithSuggestedSearch = () => { if (!draft && !value && !hasEdited && suggestedSearch?.trim()) { setDraft(suggestedSearch.trim()); } combobox.openDropdown(); }; const handleKeyDown: KeyboardEventHandler = (event) => { if ((event.metaKey || event.ctrlKey) && event.key === "Backspace") { event.preventDefault(); clearValue(); return; } if (event.key === "Escape") { setDraft(value ?? ""); setHasEdited(false); combobox.closeDropdown("keyboard"); return; } if (!directUrl && orderedOptions.length > 0 && (event.key === "ArrowDown" || event.key === "ArrowUp")) { event.preventDefault(); combobox.openDropdown("keyboard"); setKeyboardIndex((current) => { const next = event.key === "ArrowDown" ? current >= orderedOptions.length - 1 ? 0 : current + 1 : current <= 0 ? orderedOptions.length - 1 : current - 1; combobox.selectOption(next); return next; }); return; } if (event.key === "Enter") { if (keyboardIndex >= 0 && orderedOptions[keyboardIndex]) { event.preventDefault(); commitValue(orderedOptions[keyboardIndex].url); combobox.closeDropdown("keyboard"); } else if (isImageSource(draft)) { event.preventDefault(); commitValue(draft.trim()); combobox.closeDropdown("keyboard"); } } }; const renderIconOptions = (icons: typeof sections.local, offset: number) => ( {icons.map((icon, index) => ( {isSvgImage(icon.url) && SVG} ))} ); const renderSearchResults = () => { if (query.isError) { return ( } title={tCommon("iconPicker.error")} action={ } /> ); } if (query.isLoading) { return ( {Array.from({ length: 12 }, (_, index) => ( ))} ); } if (totalOptions === 0) { return ( } title={tCommon("iconPicker.noResults", { search: debouncedDraft.trim() })} /> ); } return ( {sections.local.length > 0 && ( } label={tCommon("iconPicker.localImages")}> {renderIconOptions(sections.local, 0)} )} {sections.svg.length > 0 && ( {renderIconOptions(sections.svg, sections.local.length)} )} {sections.other.length > 0 && ( } label={tCommon("iconPicker.otherImages")}> {renderIconOptions(sections.other, sections.local.length + sections.svg.length)} )} ); }; const leftSection = (() => { if (directUrl && previewState === "loading") return ; if (directUrl && previewState === "error") return ; if (shouldShowPreview(value)) { return ( directUrl && setPreviewState("ready")} onError={() => directUrl && setPreviewState("error")} /> ); } return ; })(); const placeholderText = placeholder ?? (query.data ? tCommon("iconPicker.header", { countIcons: String(query.data.countIcons) }) : tCommon("iconPicker.headerLoading")); return ( { commitValue(url); combobox.closeDropdown(); }} > {canUpload && ( { const first = medias.at(0); if (!first) return; commitValue(first.url); combobox.closeDropdown(); }} > {({ onClick, loading }) => ( { event.stopPropagation(); onClick(); }} loading={loading} size="sm" variant="subtle" aria-label={tCommon("iconPicker.uploadImage")} > )} )} {(draft || value) && ( event.preventDefault()} onClick={clearValue} /> )} {query.isFetching && !directUrl ? : } } rightSectionWidth={canUpload ? 86 : 56} rightSectionPointerEvents="all" value={draft} onChange={(event) => { const nextValue = event.currentTarget.value; setDraft(nextValue); setHasEdited(true); setKeyboardIndex(-1); combobox.openDropdown("keyboard"); combobox.updateSelectedOptionIndex(); if (!nextValue) { setValue(""); } else if (isImageSource(nextValue)) { setValue(nextValue.trim()); } }} onKeyDown={handleKeyDown} onClick={openWithSuggestedSearch} onFocus={(event) => { onFocus?.(event); openWithSuggestedSearch(); }} onBlur={(event) => { onBlur?.(event); combobox.closeDropdown(); setDraft(value ?? ""); setHasEdited(false); }} withAsterisk={withAsterisk} error={error} label={label ?? tCommon("iconPicker.label")} description={tCommon("iconPicker.description")} styles={{ description: { color: "var(--mantine-color-text)" }, input: { color: "var(--mantine-color-text)" }, error: { color: "light-dark(var(--mantine-color-red-9), var(--mantine-color-red-2))" }, }} placeholder={placeholderText} autoComplete="off" spellCheck={false} /> {directUrl ? ( {previewState === "loading" && } {previewState === "error" ? ( ) : ( setPreviewState("ready")} onError={() => setPreviewState("error")} /> )} {previewState === "error" ? tCommon("iconPicker.urlError") : previewState === "ready" ? tCommon("iconPicker.urlReady") : tCommon("iconPicker.urlLoading")} {directUrl} {previewState === "ready" && ( )} ) : ( renderSearchResults() )} ); }; interface PickerSectionProps { label: string; icon?: React.ReactNode; badge?: string; children: React.ReactNode; } const PickerSection = ({ label, icon, badge, children }: PickerSectionProps) => ( {icon} {label} {badge && {badge}} {children} ); interface PickerMessageProps { icon: React.ReactNode; title: string; action?: React.ReactNode; } const PickerMessage = ({ icon, title, action }: PickerMessageProps) => ( {icon} {title} {action} ); const localizationPathRegex = new RegExp(`^/?(${supportedLanguages.join("|")})(/.*)?$`, "i"); const shouldShowPreview = (value: string | null | undefined): value is string => { if (!value) return false; return !localizationPathRegex.test(value); };