A free, open source, and extensible speech-to-text application that works completely offline.
better pref languages
CJ Pais693aa634b43c
diff --git a/src/components/settings/PreferredLanguages.tsx b/src/components/settings/PreferredLanguages.tsxindex e354c5ee..ba8a7b61 100644--- a/src/components/settings/PreferredLanguages.tsx+++ b/src/components/settings/PreferredLanguages.tsx@@ -1,15 +1,12 @@-import React, { useEffect, useRef, useState } from "react";+import React, { useEffect, useLayoutEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { SettingContainer } from "../ui/SettingContainer";-import {- LanguageOptions,- LanguageSearchField,- useLanguagePicker,-} from "../shared/LanguagePicker";+import { LanguageChip, useLanguagePicker } from "../shared/LanguagePicker";import { suggestedLanguages } from "@/lib/utils/languageSuggestions";import { isWeakLanguage } from "@/lib/models/catalog";import { useSettings } from "../../hooks/useSettings";import { isComposingKeyEvent } from "@/lib/utils/keyboard";+import { cjkSubsetFont } from "@/lib/utils/cjkFont";import { languageList } from "../../lib/constants/languages";interface PreferredLanguagesProps {@@ -17,7 +14,198 @@ interface PreferredLanguagesProps {grouped?: boolean;}-/** Edits `spoken_languages`; leaves the model's own Language as is. */+type Picker = ReturnType<typeof useLanguagePicker>;++const PlusIcon = () => (+ <svg+ width="12"+ height="12"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth={2.2}+ strokeLinecap="round"+ aria-hidden="true"+ >+ <path d="M12 5v14M5 12h14" />+ </svg>+);++const SearchIcon = () => (+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth={2}+ strokeLinecap="round"+ aria-hidden="true"+ >+ <circle cx="11" cy="11" r="6.5" />+ <path d="M16 16l4 4" />+ </svg>+);++const CheckIcon = () => (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth={2.2}+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden="true"+ >+ <path d="M5 12.5l4.5 4.5L19 7.5" />+ </svg>+);++// Matches the row's gap-1.+const CHIP_GAP = 4;++/**+ * How many of `measure`'s chips fit in `box`, leaving room for "+N" (the+ * last child of `measure`) when some don't.+ */+const useChipsThatFit = (+ box: React.RefObject<HTMLDivElement | null>,+ measure: React.RefObject<HTMLDivElement | null>,+ languages: string[],+) => {+ const [count, setCount] = useState(languages.length);+ const key = languages.join();+ useLayoutEffect(() => {+ const b = box.current;+ const m = measure.current;+ if (!b || !m) return;+ const fit = () => {+ const kids = [...m.children] as HTMLElement[];+ const more = kids.pop()?.offsetWidth ?? 0;+ const room = b.clientWidth;+ let used = 0;+ let n = 0;+ for (const [i, kid] of kids.entries()) {+ const left = kids.length - i - 1;+ if (used + kid.offsetWidth + (left ? CHIP_GAP + more : 0) > room) break;+ used += kid.offsetWidth + CHIP_GAP;+ n++;+ }+ setCount(n);+ };+ fit();+ // CJK endonyms can arrive in a web font after the first measure.+ document.fonts?.ready.then(fit);+ const observer = new ResizeObserver(fit);+ observer.observe(b);+ return () => observer.disconnect();+ }, [box, measure, key]);+ return count;+};++/** The menu under +: a search over every language, the picked ones first and ticked. */+const LanguageMenu: React.FC<{+ picker: Picker;+ /** The picked languages when the menu opened: they lead, and stay put as they're toggled. */+ pinned: string[];+ /** Highlight the first addable even with nothing typed (it's the suggestion). */+ highlightFirst: boolean;+}> = ({ picker, pinned, highlightFirst }) => {+ const { t } = useTranslation();+ const { inputRef, query, languages, matches } = picker;+ // Picked ones in the chips' order, then the rest in search order.+ const rows = [+ ...pinned.flatMap((code) => matches.filter((l) => l.code === code)),+ ...matches.filter((l) => !pinned.includes(l.code)),+ ];+ const firstAddable = rows.find((l) => !languages.includes(l.code))?.code;++ return (+ <div+ // Keep focus in the search: WebKit doesn't focus a pressed button, so+ // the blur would close the menu before the click lands.+ onMouseDown={(e) => {+ if (e.target !== inputRef.current) e.preventDefault();+ }}+ className="absolute end-0 top-full z-50 mt-1 w-[248px] overflow-hidden rounded-lg border border-line bg-background text-start shadow-lg"+ >+ <label className="flex items-center gap-2 border-b border-line px-3 text-ink-3">+ <SearchIcon />+ <input+ ref={inputRef}+ type="text"+ autoComplete="off"+ spellCheck={false}+ aria-label={t("languagePicker.search")}+ placeholder={t("languagePicker.search")}+ value={query}+ onChange={(e) => picker.setQuery(e.target.value)}+ onKeyDown={(e) => {+ if (isComposingKeyEvent(e.nativeEvent)) return;+ // Escape with a query clears it; without one, the menu closes.+ if (picker.onKeyDown(e)) e.stopPropagation();+ }}+ className="h-9 w-full min-w-0 bg-transparent text-sm text-text outline-none placeholder:text-ink-3"+ />+ </label>+ <div className="max-h-56 overflow-y-auto p-1">+ {rows.map((l) => {+ const name = picker.nameOf(l.code);+ const picked = languages.includes(l.code);+ const locked = picked && !picker.removable;+ const highlighted =+ (!!query || highlightFirst) && l.code === firstAddable;+ return (+ <button+ key={l.code}+ type="button"+ aria-pressed={picked}+ disabled={locked}+ onClick={() => picker.toggle(l.code)}+ // Picked rows are only ticked: unlike Dropdown's one choice,+ // several fills would stack into stripes.+ className={`flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-start text-sm transition-colors disabled:cursor-default ${+ highlighted+ ? "bg-wash"+ : "hover:bg-wash disabled:hover:bg-transparent"+ }`}+ >+ <span+ lang={l.code}+ className={`shrink-0 ${picked ? "font-semibold" : ""} ${cjkSubsetFont(l.native) ?? ""}`}+ >+ {l.native}+ </span>+ {l.native !== name && (+ <span className="truncate text-xs text-ink-3">{name}</span>+ )}+ <span+ className={`ms-auto flex w-4 shrink-0 ${locked ? "text-ink-3" : "text-ink-2"}`}+ >+ {picked && <CheckIcon />}+ </span>+ </button>+ );+ })}+ {!rows.length && (+ <div className="px-2 py-3 text-center text-xs text-ink-3">+ {t("settings.general.preferredLanguages.noMatch", {+ query: query.trim(),+ })}+ </div>+ )}+ </div>+ </div>+ );+};++/**+ * Edits `spoken_languages`; leaves the model's own Language as is. One line+ * like its neighbours: as many chips as fit, "+N" for the rest, and + to+ * open the menu that adds and removes.+ */export const PreferredLanguages: React.FC<PreferredLanguagesProps> = ({descriptionMode = "tooltip",grouped = false,@@ -25,117 +213,156 @@ export const PreferredLanguages: React.FC<PreferredLanguagesProps> = ({const { t, i18n } = useTranslation();const { getSetting, updateSetting } = useSettings();const languages = getSetting("spoken_languages") ?? [];- const [focused, setFocused] = useState(false);- const rootRef = useRef<HTMLDivElement>(null);- const gridRef = useRef<HTMLDivElement>(null);-const ui = i18n.language;// Nothing picked yet (onboarded before this setting): suggest their language.const suggestion = languages.length ? null : suggestedLanguages()[0];const picker = useLanguagePicker({languages,- onChange: (next) => {- updateSetting("spoken_languages", next);- gridRef.current?.scrollTo({ top: 0 });- },+ onChange: (next) => updateSetting("spoken_languages", next),// At least one language, once there is one.keepOne: true,suggestion,});- const { available, inputRef } = picker;- const open = focused || !languages.length;- // A closed grid is out of the tab order (React 18 has no `inert` prop).- const drawerRef = useRef<HTMLDivElement>(null);- useEffect(() => {- drawerRef.current?.toggleAttribute("inert", !open);- }, [open]);+ const [open, setOpen] = useState(false);+ const [pinned, setPinned] = useState<string[]>([]);+ const rootRef = useRef<HTMLDivElement>(null);+ const addRef = useRef<HTMLButtonElement>(null);+ const boxRef = useRef<HTMLDivElement>(null);+ const measureRef = useRef<HTMLDivElement>(null);- // The grid's foot fades only when there's more to scroll to.- const [overflows, setOverflows] = useState(false);- useEffect(() => {- const grid = gridRef.current;- if (grid) setOverflows(grid.scrollHeight > grid.clientHeight + 1);- }, [available.length, open]);+ const fit = useChipsThatFit(boxRef, measureRef, languages);+ const shown = languages.slice(0, fit);+ const hidden = languages.slice(fit);- const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {- if (isComposingKeyEvent(e.nativeEvent)) return;- if (!picker.onKeyDown(e) && e.key === "Escape") inputRef.current?.blur();+ const openMenu = () => {+ setPinned(languages);+ setOpen(true);};+ const closeMenu = () => {+ setOpen(false);+ picker.setQuery("");+ };+ const toggleMenu = () => (open ? closeMenu() : openMenu());++ useEffect(() => {+ if (open) picker.inputRef.current?.focus({ preventScroll: true });+ }, [open, picker.inputRef]);++ const chip = (code: string) => (+ <LanguageChip+ key={code}+ variant="soft"+ code={code}+ removeLabel={t("languagePicker.remove", {+ language: picker.nameOf(code),+ })}+ onRemove={() => {+ picker.toggle(code);+ // The chip goes, and with the menu shut there's no search to take+ // focus: give it to +.+ if (!open) addRef.current?.focus({ preventScroll: true });+ }}+ locked={!picker.removable}+ />+ );+ const moreLabel = hidden.length ? languageList(hidden, ui) : undefined;+ const moreClasses =+ "inline-flex h-[26px] shrink-0 items-center rounded-md px-2 text-xs font-medium tabular-nums";const weak = languages.filter(isWeakLanguage);return (- <SettingContainer- title={t("settings.general.preferredLanguages.title")}- description={t("settings.general.preferredLanguages.description")}- descriptionMode={descriptionMode}- grouped={grouped}- layout="stacked"- >- <div- ref={rootRef}- onFocus={() => setFocused(true)}- onBlur={(e) => {- if (rootRef.current?.contains(e.relatedTarget as Node)) return;- setFocused(false);- picker.setQuery("");- }}- className={`mt-[2px] overflow-hidden rounded-card border-[1.5px] bg-background transition-colors duration-200 ${- focused ? "border-ink-3" : "border-line-strong"- }`}+ <div>+ <SettingContainer+ title={t("settings.general.preferredLanguages.title")}+ description={t("settings.general.preferredLanguages.description")}+ descriptionMode={descriptionMode}+ grouped={grouped}+ grow>- <LanguageSearchField- picker={picker}- inputClassName="min-w-[140px] text-small"- onKeyDown={onKeyDown}- aria-expanded={open}- />-- {/* The grid opens under the chips: its height eases from nothing. */}<div- className={`grid transition-[grid-template-rows] duration-300 ease-glide motion-reduce:transition-none ${- open ? "grid-rows-[1fr]" : "grid-rows-[0fr]"- }`}+ ref={rootRef}+ onBlur={(e) => {+ if (rootRef.current?.contains(e.relatedTarget as Node)) return;+ closeMenu();+ }}+ onKeyDown={(e) => {+ if (e.key !== "Escape" || !open) return;+ e.preventDefault();+ e.stopPropagation();+ closeMenu();+ addRef.current?.focus();+ }}+ className="relative flex min-w-0 flex-1 items-center gap-1">- <div ref={drawerRef} className="min-h-0">+ <div+ ref={boxRef}+ className="relative flex min-w-0 flex-1 items-center justify-end gap-1 overflow-hidden"+ >+ {/* Every chip, unseen, to measure how many fit. */}<div- ref={gridRef}- // Keep focus in the search: WebKit doesn't focus a pressed button,- // so the blur would close the grid before the click lands.- onMouseDown={(e) => {- if ((e.target as HTMLElement).closest("button"))- e.preventDefault();- }}- role="group"- aria-label={t("languagePicker.search")}- className={`grid max-h-[214px] grid-cols-[repeat(auto-fill,minmax(150px,1fr))] content-start gap-[2px] overflow-y-auto border-t border-line p-[6px] ${- overflows- ? "pb-[14px] [mask-image:linear-gradient(to_bottom,black_calc(100%-36px),transparent_calc(100%-4px))]"- : ""- }`}+ ref={measureRef}+ aria-hidden="true"+ className="invisible absolute start-0 top-0 flex gap-1">- <LanguageOptions- picker={picker}- highlightFirst={!!suggestion}- noMatch={t("settings.general.preferredLanguages.noMatch", {- query: picker.query.trim(),- })}- emptyClassName="p-[20px]"- />+ {languages.map(chip)}+ <span className={moreClasses}>{`+${languages.length}`}</span></div>+ {shown.map(chip)}+ {hidden.length > 0 && (+ <button+ type="button"+ title={moreLabel}+ aria-label={moreLabel}+ aria-expanded={open}+ onMouseDown={(e) => e.preventDefault()}+ onClick={toggleMenu}+ className={`${moreClasses} cursor-pointer transition-colors hover:bg-line hover:text-text ${+ open ? "bg-line text-text" : "bg-wash text-ink-2"+ }`}+ >+ {`+${hidden.length}`}+ </button>+ )}</div>+ <button+ ref={addRef}+ type="button"+ aria-label={+ languages.length+ ? t("languagePicker.addAnother")+ : t("languagePicker.search")+ }+ aria-expanded={open}+ onMouseDown={(e) => e.preventDefault()}+ onClick={toggleMenu}+ className={`inline-flex h-[26px] shrink-0 cursor-pointer items-center justify-center gap-1 whitespace-nowrap rounded-md text-xs font-medium transition-colors hover:bg-wash hover:text-text ${+ languages.length ? "w-[26px]" : "px-2"+ } ${open ? "bg-wash text-text" : "text-ink-2"}`}+ >+ <PlusIcon />+ {/* With nothing picked, + alone would say too little. */}+ {!languages.length && t("languagePicker.search")}+ </button>+ {open && (+ <LanguageMenu+ picker={picker}+ pinned={pinned}+ highlightFirst={!!suggestion}+ />+ )}</div>- </div>+ </SettingContainer>{weak.length > 0 && (- <p className="mt-[4px] mb-0 text-small text-ink-3">+ <p className="-mt-1 mb-0 px-4 pb-2 text-end text-xs text-ink-3">{t("settings.general.preferredLanguages.weak", {languages: languageList(weak, ui),})}</p>)}- </SettingContainer>+ </div>);};diff --git a/src/components/shared/LanguagePicker.tsx b/src/components/shared/LanguagePicker.tsxindex f399d4f9..15acf2c8 100644--- a/src/components/shared/LanguagePicker.tsx+++ b/src/components/shared/LanguagePicker.tsx@@ -34,6 +34,8 @@ interface LanguageChipProps {onRemove: () => void;/** The last language can't go: the chip stays, without its ×. */locked?: boolean;+ /** `soft`: Settings' small borderless tag, beside its Dropdowns. */+ variant?: "pill" | "soft";}/** A picked language by its endonym, with a remove button that keeps focus in the search. */@@ -42,6 +44,7 @@ export const LanguageChip: React.FC<LanguageChipProps> = ({removeLabel,onRemove,locked = false,+ variant = "pill",}) => {const { native } = getLanguage(code);const name = (@@ -49,6 +52,25 @@ export const LanguageChip: React.FC<LanguageChipProps> = ({{native}</bdi>);+ if (variant === "soft") {+ const soft =+ "inline-flex h-[26px] shrink-0 items-center gap-1 whitespace-nowrap rounded-md bg-wash text-xs font-medium text-text";+ if (locked) return <span className={`${soft} px-2.5`}>{name}</span>;+ return (+ <button+ type="button"+ aria-label={removeLabel}+ onMouseDown={(e) => e.preventDefault()}+ onClick={onRemove}+ className={`group ${soft} cursor-pointer ps-2.5 pe-1.5 transition-colors hover:bg-line`}+ >+ {name}+ <span className="grid size-[14px] place-items-center text-ink-3 transition-colors group-hover:text-text">+ <RemoveIcon />+ </span>+ </button>+ );+ }if (locked)return (<span className="inline-flex h-[28px] items-center rounded-full border-[1.5px] border-line-strong bg-background px-[12px] text-small font-semibold text-text">diff --git a/src/components/ui/Dropdown.tsx b/src/components/ui/Dropdown.tsxindex e7ff7f99..2a765a97 100644--- a/src/components/ui/Dropdown.tsx+++ b/src/components/ui/Dropdown.tsx@@ -53,9 +53,10 @@ export const Dropdown: React.FC<DropdownProps> = ({return () => document.removeEventListener("mousedown", handleClickOutside);}, []);+ // The trigger's hover; in the menu, hover is grey so it never looks chosen.const hover =tone === "neutral" ? "hover:bg-wash" : "hover:bg-logo-primary/10";- const selected = tone === "neutral" ? "bg-line" : "bg-logo-primary/20";+ const chosen = tone === "neutral" ? "bg-line" : "bg-logo-primary/15";const selectedOption = options.find((option) => option.value === selectedValue,@@ -115,43 +116,62 @@ export const Dropdown: React.FC<DropdownProps> = ({</button>{isOpen && !disabled && (<div- className={`absolute ${placement === "above" ? "bottom-full mb-1" : "top-full mt-1"} bg-background border border-line-strong rounded-md shadow-lg z-50 max-h-60 overflow-y-auto ${+ className={`absolute ${placement === "above" ? "bottom-full mb-1" : "top-full mt-1"} bg-background border border-line rounded-lg shadow-lg z-50 max-h-60 overflow-y-auto p-1 ${menuClassName ?? "left-0 right-0"}`}>{options.length === 0 ? (- <div className="px-2 py-1 text-sm text-ink-3">+ <div className="px-2 py-1.5 text-sm text-ink-3">{t("common.noOptionsFound")}</div>) : (- options.map((option) => (- <button- key={option.value}- type="button"- className={`w-full text-sm text-start ${hover} transition-colors duration-150 ${- option.description ? "px-3 py-2" : "px-2 py-1"- } ${- selectedValue === option.value ? selected : ""- } ${option.disabled ? "opacity-50 cursor-not-allowed" : ""}`}- onClick={() => handleSelect(option.value)}- disabled={option.disabled}- >- <span- className={`block whitespace-normal break-words ${- option.description || selectedValue === option.value- ? "font-semibold"- : ""+ options.map((option) => {+ const isChosen = selectedValue === option.value;+ return (+ <button+ key={option.value}+ type="button"+ className={`flex w-full items-center gap-2 rounded-md px-2 text-sm text-start transition-colors duration-150 ${+ option.description ? "py-2" : "py-1.5"+ } ${isChosen ? chosen : "hover:bg-wash"} ${+ option.disabled ? "opacity-50 cursor-not-allowed" : ""}`}+ onClick={() => handleSelect(option.value)}+ disabled={option.disabled}>- {option.label}- </span>- {option.description && (- <span className="mt-0.5 block whitespace-normal text-xs font-normal leading-snug text-ink-3">- {option.description}+ <span className="min-w-0 flex-1">+ <span+ className={`block whitespace-normal break-words ${+ isChosen ? "font-semibold" : ""+ }`}+ >+ {option.label}+ </span>+ {option.description && (+ <span className="mt-0.5 block whitespace-normal text-xs font-normal leading-snug text-ink-3">+ {option.description}+ </span>+ )}</span>- )}- </button>- ))+ {isChosen && (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth={2.2}+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden="true"+ className="shrink-0 text-ink-2"+ >+ <path d="M5 12.5l4.5 4.5L19 7.5" />+ </svg>+ )}+ </button>+ );+ }))}</div>)}diff --git a/src/components/ui/SettingContainer.tsx b/src/components/ui/SettingContainer.tsxindex 913e331b..5d14243d 100644--- a/src/components/ui/SettingContainer.tsx+++ b/src/components/ui/SettingContainer.tsx@@ -10,6 +10,8 @@ interface SettingContainerProps {layout?: "horizontal" | "stacked";disabled?: boolean;tooltipPosition?: "top" | "bottom";+ /** Horizontal only: the control takes the row's free width, for content that fits itself to it. */+ grow?: boolean;}export const SettingContainer: React.FC<SettingContainerProps> = ({@@ -21,6 +23,7 @@ export const SettingContainer: React.FC<SettingContainerProps> = ({layout = "horizontal",disabled = false,tooltipPosition = "top",+ grow = false,}) => {const info = (<InfoTooltip@@ -66,14 +69,20 @@ export const SettingContainer: React.FC<SettingContainerProps> = ({}// Horizontal layout (default)- const horizontalContainerClasses = grouped- ? "flex items-center justify-between min-h-12 px-4 p-2"- : "flex items-center justify-between min-h-12 px-4 p-2 rounded-lg border border-line";+ const horizontalContainerClasses = `${+ grouped+ ? "flex items-center justify-between min-h-12 px-4 p-2"+ : "flex items-center justify-between min-h-12 px-4 p-2 rounded-lg border border-line"+ }${grow ? " gap-4" : ""}`;+ const titleClasses = grow ? "max-w-2/3 shrink-0" : "max-w-2/3";+ const controlClasses = grow+ ? "relative flex min-w-0 flex-1 justify-end"+ : "relative";if (descriptionMode === "tooltip") {return (<div className={horizontalContainerClasses}>- <div className="max-w-2/3">+ <div className={titleClasses}><div className="flex items-center gap-2"><h3className={`text-sm font-medium ${disabled ? "opacity-50" : ""}`}@@ -83,14 +92,14 @@ export const SettingContainer: React.FC<SettingContainerProps> = ({{info}</div></div>- <div className="relative">{children}</div>+ <div className={controlClasses}>{children}</div></div>);}return (<div className={horizontalContainerClasses}>- <div className="max-w-2/3">+ <div className={titleClasses}><h3 className={`text-sm font-medium ${disabled ? "opacity-50" : ""}`}>{title}</h3>@@ -98,7 +107,7 @@ export const SettingContainer: React.FC<SettingContainerProps> = ({{description}</p></div>- <div className="relative">{children}</div>+ <div className={controlClasses}>{children}</div></div>);};