π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
feat(photos):add-search-result-category-tabs
Aswin Asok68c8fba9e362
diff --git a/web/apps/photos/src/components/SearchBar.tsx b/web/apps/photos/src/components/SearchBar.tsxindex 17fc64e3c7..38afe662fd 100644--- a/web/apps/photos/src/components/SearchBar.tsx+++ b/web/apps/photos/src/components/SearchBar.tsx@@ -1,4 +1,10 @@import { sidebarTheme } from "@/components/sidebar/theme";+import {+ matchesSearchCategory,+ searchCategories,+ searchCategoryCounts,+ type SearchCategory,+} from "@/services/search/search-categories";import { sidebarSearchOptionsForString } from "@/services/search/sidebar-search-registry";import { Search01Icon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";@@ -16,6 +22,8 @@ import {IconButton,Stack,styled,+ Tab,+ Tabs,ThemeProvider,Tooltip,Typography,@@ -47,12 +55,21 @@ import type { SearchOption } from "ente-new/photos/services/search/types";import { nullToUndefined } from "ente-utils/transform";import { t } from "i18next";import pDebounce from "p-debounce";-import React, { useEffect, useMemo, useRef, useState } from "react";+import React, {+ createContext,+ useContext,+ useEffect,+ useId,+ useMemo,+ useRef,+ useState,+} from "react";import {components as SelectComponents,type ControlProps,type InputActionMeta,type InputProps,+ type MenuProps,type OptionProps,type SelectInstance,type StylesConfig,@@ -195,6 +212,7 @@ const SearchInput: React.FC<// undefined makes react-select switch from controlled to uncontrolled.const [value, setValue] = useState<SearchOption | null>(null);const [inputValue, setInputValue] = useState("");+ const [category, setCategory] = useState<SearchCategory>("all");const [isKeyboardNavigating, setIsKeyboardNavigating] = useState(false);const theme = useTheme();@@ -203,7 +221,10 @@ const SearchInput: React.FC<() => createSelectStyles(theme, isKeyboardNavigating),[theme, isKeyboardNavigating],);- const components = useMemo(() => ({ Control, Input, Option }), []);+ const components = useMemo(+ () => ({ Control, Input, Option, Menu: SearchMenu }),+ [],+ );useEffect(() => {if (open) selectRef.current?.focus();@@ -219,9 +240,11 @@ const SearchInput: React.FC<) {setValue(null);setInputValue("");+ setCategory("all");} else {setValue(value);setInputValue(value?.suggestion.label ?? "");+ if (!value) setCategory("all");}onSelectSearchOption(nullToUndefined(value), {@@ -259,6 +282,7 @@ const SearchInput: React.FC<setInputValue(value);if (value === "") {+ setCategory("all");setValue(null);setInputValue("");onSelectSearchOption(undefined, {@@ -278,6 +302,7 @@ const SearchInput: React.FC<setValue(null);setInputValue("");+ setCategory("all");onSelectSearchOption(undefined, { shouldExitSearchMode: true });onClose();@@ -318,46 +343,157 @@ const SearchInput: React.FC<};return (- <SearchInputWrapper onMouseMove={() => setIsKeyboardNavigating(false)}>- <AsyncSelect- ref={selectRef}- value={value}- components={components}- styles={styles}- loadOptions={loadOptions}- onChange={handleChange}- inputValue={inputValue}- onInputChange={handleInputChange}- onKeyDown={handleKeyDown}- isClearable- aria-label={t("search")}- escapeClearsValue- menuIsOpen={- open && (inputValue !== "" || shouldShowEmptyState(""))- }- onFocus={handleFocus}- onBlur={handleBlur}- placeholder={t("search_hint")}- loadingMessage={() => null}- noOptionsMessage={({ inputValue }) => {- if (inputValue) {- return t("no_results");+ <SearchCategoryContext.Provider value={{ category, setCategory }}>+ <SearchInputWrapper+ onMouseMove={() => setIsKeyboardNavigating(false)}+ >+ <AsyncSelect+ ref={selectRef}+ // A fresh value also refreshes react-select's filtered keyboard targets.+ value={value ? [value] : []}+ components={components}+ styles={styles}+ loadOptions={loadOptions}+ // Moving focus to a tab must not reload the current query.+ cacheOptions={open ? inputValue : undefined}+ filterOption={({ data }) =>+ matchesSearchCategory(data, category)}- if (shouldShowEmptyState(inputValue)) {- return (- <EmptyState- onSelectPeople={handleSelectPeople}- onSelectPerson={handleSelectPerson}- />- );+ onChange={handleChange}+ inputValue={inputValue}+ onInputChange={handleInputChange}+ onKeyDown={handleKeyDown}+ isClearable+ tabSelectsValue={false}+ aria-label={t("search")}+ escapeClearsValue+ menuIsOpen={+ open && (inputValue !== "" || shouldShowEmptyState(""))}- return null;- }}- />- </SearchInputWrapper>+ onFocus={handleFocus}+ onBlur={handleBlur}+ placeholder={t("search_hint")}+ loadingMessage={() => t("loading")}+ noOptionsMessage={({ inputValue }) => {+ if (inputValue) {+ return t("no_results");+ }+ if (shouldShowEmptyState(inputValue)) {+ return (+ <EmptyState+ onSelectPeople={handleSelectPeople}+ onSelectPerson={handleSelectPerson}+ />+ );+ }+ return null;+ }}+ />+ </SearchInputWrapper>+ </SearchCategoryContext.Provider>);};+const SearchCategoryContext = createContext<+ | {+ category: SearchCategory;+ setCategory: (category: SearchCategory) => void;+ }+ | undefined+>(undefined);++function SearchMenu(props: MenuProps<SearchOption, false>) {+ const { category, setCategory } = useContext(SearchCategoryContext)!;+ const id = useId();+ const hasQuery = !!props.selectProps.inputValue.trim();+ const counts = searchCategoryCounts(+ props.options as readonly SearchOption[],+ );++ return (+ <SelectComponents.Menu {...props}>+ {hasQuery && (+ <Tabs+ value={category}+ onChange={(_, value: SearchCategory) => setCategory(value)}+ onMouseDown={(event) => event.stopPropagation()}+ onKeyDown={(event) => {+ if (event.key !== "Escape") event.stopPropagation();+ }}+ variant="scrollable"+ scrollButtons="auto"+ aria-label={t("search_results")}+ sx={{+ minHeight: 36,+ mb: 2,+ borderBottom: "1px solid",+ borderColor: "stroke.faint",+ "& .MuiTabs-indicator": { bgcolor: "text.base" },+ "& .MuiTab-root": {+ minWidth: 0,+ minHeight: 36,+ p: 0,+ mr: "24px",+ fontSize: 14,+ textTransform: "none",+ color: "text.muted",+ },+ "& .MuiTab-root.Mui-selected": {+ color: "text.base",+ fontWeight: 600,+ },+ }}+ >+ {searchCategories.map((category) => (+ <Tab+ key={category}+ value={category}+ id={`${id}-${category}`}+ aria-controls={`${id}-results`}+ label={+ <Stack+ direction="row"+ sx={{ alignItems: "center", gap: 0.5 }}+ >+ {t(+ category === "places"+ ? "search_places"+ : category,+ )}+ {counts[category] > 0 && (+ <Typography+ component="span"+ variant="mini"+ sx={{ color: "text.muted" }}+ >+ {counts[category]}+ </Typography>+ )}+ </Stack>+ }+ />+ ))}+ </Tabs>+ )}+ <div+ id={`${id}-results`}+ role={hasQuery ? "tabpanel" : undefined}+ aria-labelledby={hasQuery ? `${id}-${category}` : undefined}+ >+ {props.isLoading && counts[category] > 0 && (+ <Typography+ role="status"+ sx={{ color: "text.muted", textAlign: "center", p: 1 }}+ >+ {t("loading")}+ </Typography>+ )}+ {props.children}+ </div>+ </SelectComponents.Menu>+ );+}+const SearchInputWrapper = styled("div")`display: flex;width: 100%;@@ -379,7 +515,7 @@ const createSelectStyles = (theme: Theme,isKeyboardNavigating: boolean,): StylesConfig<SearchOption, false> => ({- container: (style) => ({ ...style, flex: 1 }),+ container: (style) => ({ ...style, flex: 1, minWidth: 0 }),control: (style) => ({...style,minHeight: "52px",diff --git a/web/apps/photos/src/services/search/search-categories.ts b/web/apps/photos/src/services/search/search-categories.tsnew file mode 100644index 0000000000..f2a29ea39d--- /dev/null+++ b/web/apps/photos/src/services/search/search-categories.ts@@ -0,0 +1,54 @@+import type {+ SearchOption,+ SearchSuggestion,+} from "ente-new/photos/services/search/types";++export const searchCategories = [+ "all",+ "albums",+ "people",+ "places",+ "photos",+ "settings",+] as const;++export type SearchCategory = (typeof searchCategories)[number];++export const searchCategoryForType = (+ type: SearchSuggestion["type"],+): Exclude<SearchCategory, "all"> => {+ switch (type) {+ case "collection":+ return "albums";+ case "person":+ return "people";+ case "location":+ case "city":+ return "places";+ case "sidebarAction":+ return "settings";+ default:+ return "photos";+ }+};++export const matchesSearchCategory = (+ option: SearchOption,+ category: SearchCategory,+) =>+ category === "all" ||+ searchCategoryForType(option.suggestion.type) === category;++export const searchCategoryCounts = (options: readonly SearchOption[]) => {+ const counts = {+ all: options.length,+ albums: 0,+ people: 0,+ places: 0,+ photos: 0,+ settings: 0,+ };+ for (const option of options)+ counts[searchCategoryForType(option.suggestion.type)]++;+ return counts;+};diff --git a/web/apps/photos/tests/search-categories.test.ts b/web/apps/photos/tests/search-categories.test.tsnew file mode 100644index 0000000000..6ce8518de1--- /dev/null+++ b/web/apps/photos/tests/search-categories.test.ts@@ -0,0 +1,100 @@+import type {+ SearchOption,+ SearchSuggestion,+} from "ente-new/photos/services/search/types";+import { describe, expect, test } from "vitest";+import {+ matchesSearchCategory,+ searchCategories,+ searchCategoryCounts,+ searchCategoryForType,+ type SearchCategory,+} from "../src/services/search/search-categories";++const categoriesByType = {+ collection: "albums",+ person: "people",+ location: "places",+ city: "places",+ sidebarAction: "settings",+ fileType: "photos",+ fileName: "photos",+ fileCaption: "photos",+ cameraMake: "photos",+ cameraModel: "photos",+ date: "photos",+ noLocation: "photos",+ clip: "photos",+} satisfies Record<SearchSuggestion["type"], Exclude<SearchCategory, "all">>;++const option = (type: SearchSuggestion["type"], fileCount = 100) =>+ ({+ suggestion: { type, label: type },+ fileCount,+ previewFiles: [],+ }) as SearchOption;++describe("search categories", () => {+ test.each(Object.entries(categoriesByType))(+ "maps %s to %s",+ (type, category) => {+ expect(+ searchCategoryForType(type as SearchSuggestion["type"]),+ ).toBe(category);+ },+ );++ test("filters without reordering or changing the source results", () => {+ const options = [+ option("city"),+ option("fileName"),+ option("collection"),+ option("location"),+ option("person"),+ option("sidebarAction"),+ option("clip"),+ ];+ const original = [...options];+ for (const category of searchCategories) {+ const expected =+ category === "all"+ ? options+ : options.filter(+ (o) =>+ categoriesByType[o.suggestion.type] === category,+ );+ const filtered = options.filter((o) =>+ matchesSearchCategory(o, category),+ );+ expect(filtered).toEqual(expected);+ filtered.forEach((o, index) => expect(o).toBe(expected[index]));+ }+ expect(options).toEqual(original);+ });++ test("counts suggestions across the complete list, including empty categories", () => {+ expect(+ searchCategoryCounts([+ option("city", 200),+ option("location", 300),+ option("clip", 500),+ option("collection", 1000),+ ]),+ ).toEqual({+ all: 4,+ albums: 1,+ people: 0,+ places: 2,+ photos: 1,+ settings: 0,+ });+ expect(searchCategoryCounts([])).toEqual({+ all: 0,+ albums: 0,+ people: 0,+ places: 0,+ photos: 0,+ settings: 0,+ });+ });+});diff --git a/web/packages/base/locales/en-US/translation.json b/web/packages/base/locales/en-US/translation.jsonindex 215c39ebd7..1a822f3450 100644--- a/web/packages/base/locales/en-US/translation.json+++ b/web/packages/base/locales/en-US/translation.json@@ -477,6 +477,7 @@"search": "Search","people_search_hint": "Search people","search_results": "Search results",+ "search_places": "Places","no_results": "No results found","no_photos_found_here": "No photos found here","zoom_out_to_see_photos": "Zoom out to see photos",