Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Rearrange

Manav Rathif958b16343d4
diff --git a/web/apps/photos/src/services/searchService.ts b/web/apps/photos/src/services/searchService.ts
index cf50458926..f869b1e931 100644
--- a/web/apps/photos/src/services/searchService.ts
+++ b/web/apps/photos/src/services/searchService.ts
@@ -30,6 +30,8 @@ import { getUniqueFiles } from "utils/file";
import { getLatestEntities } from "./entityService";
import locationSearchService from "./locationSearchService";
+// Suggestions shown in the search dropdown's empty state, i.e. when the user
+// selects the search bar but does not provide any input.
export const getDefaultOptions = async () => {
return [
await getMLStatusSuggestion(),
@@ -37,6 +39,7 @@ export const getDefaultOptions = async () => {
].filter((t) => !!t);
};
+// Suggestions shown in the search dropdown when the user has typed something.
export const getAutoCompleteSuggestions =
(files: EnteFile[], collections: Collection[]) =>
async (searchPhrase: string): Promise<SearchOption[]> => {
@@ -157,13 +160,6 @@ export async function getMLStatusSuggestion(): Promise<Suggestion> {
};
}
-const getDateSuggestion = (searchPhrase: string): Suggestion[] =>
- parseDateComponents(searchPhrase).map(({ components, label }) => ({
- type: SuggestionType.DATE,
- value: components,
- label,
- }));
-
function getCollectionSuggestion(
searchPhrase: string,
collections: Collection[],
diff --git a/web/packages/new/photos/services/search/index.ts b/web/packages/new/photos/services/search/index.ts
index 4c9cb9550d..8f1919974e 100644
--- a/web/packages/new/photos/services/search/index.ts
+++ b/web/packages/new/photos/services/search/index.ts
@@ -1,11 +1,7 @@
-import { nullToUndefined } from "@/utils/transform";
-import type { Component } from "chrono-node";
-import * as chrono from "chrono-node";
-import i18n, { t } from "i18next";
-import type { SearchDateComponents, SearchQuery } from "./types";
-
import { ComlinkWorker } from "@/base/worker/comlink-worker";
+import i18n, { t } from "i18next";
import type { EnteFile } from "../../types/file";
+import type { DateSearchResult, SearchQuery } from "./types";
import type { SearchWorker } from "./worker";
/**
@@ -34,6 +30,17 @@ const createComlinkWorker = () =>
export const setSearchableFiles = (enteFiles: EnteFile[]) =>
void worker().then((w) => w.setEnteFiles(enteFiles));
+/**
+ * Convert a search string into a reusable "search query" that can be passed on
+ * to the {@link search} function.
+ *
+ * @param searchString The string we want to search for.
+ */
+export const createSearchQuery = (searchString: string) =>
+ worker().then((w) =>
+ w.createSearchQuery(searchString, i18n.language, holidays()),
+ );
+
/**
* Search for and return the list of {@link EnteFile}s that match the given
* {@link search} query.
@@ -41,83 +48,21 @@ export const setSearchableFiles = (enteFiles: EnteFile[]) =>
export const search = async (search: SearchQuery) =>
worker().then((w) => w.search(search));
-interface DateSearchResult {
- components: SearchDateComponents;
- label: string;
-}
-
/**
- * Try to parse an arbitrary search string into sets of date components.
- *
- * e.g. "December 2022" will be parsed into a
+ * A list of holidays - their yearly dates and localized names.
*
- * [(year 2022, month 12, day undefined)]
+ * ---
*
- * while "22 December 2022" will be parsed into
+ * We keep this on the main thread since it uses the t() function for
+ * localization (although I haven't tried that in a web worker, it might work
+ * there too).
*
- * [(year 2022, month 12, day 22)]
- *
- * In addition, also return a formatted representation of the "best" guess at
- * the date that was intended by the search string.
+ * Also, this cannot be a const since it needs to be evaluated lazily for the
+ * t() to work.
*/
-export const parseDateComponents = (s: string): DateSearchResult[] =>
- parseChrono(s)
- .concat(parseYearComponents(s))
- .concat(parseHolidayComponents(s));
-
-export const parseChrono = (s: string): DateSearchResult[] =>
- chrono
- .parse(s)
- .map((result) => {
- const p = result.start;
- const component = (s: Component) =>
- p.isCertain(s) ? nullToUndefined(p.get(s)) : undefined;
-
- const year = component("year");
- const month = component("month");
- const day = component("day");
- const weekday = component("weekday");
- const hour = component("hour");
-
- if (!year && !month && !day && !weekday && !hour) return undefined;
- const components = { year, month, day, weekday, hour };
-
- const format: Intl.DateTimeFormatOptions = {};
- if (year) format.year = "numeric";
- if (month) format.month = "long";
- if (day) format.day = "numeric";
- if (weekday) format.weekday = "long";
- if (hour) {
- format.hour = "numeric";
- format.dayPeriod = "short";
- }
-
- const formatter = new Intl.DateTimeFormat(i18n.language, format);
- const label = formatter.format(p.date());
- return { components, label };
- })
- .filter((x) => x !== undefined);
-
-/** chrono does not parse years like "2024", so do it manually. */
-const parseYearComponents = (s: string): DateSearchResult[] => {
- // s is already trimmed.
- if (s.length == 4) {
- const year = parseInt(s);
- if (year && year <= 9999) {
- const components = { year };
- return [{ components, label: s }];
- }
- }
- return [];
-};
-
-// This cannot be a const, it needs to be evaluated lazily for the t() to work.
const holidays = (): DateSearchResult[] => [
{ components: { month: 12, day: 25 }, label: t("CHRISTMAS") },
{ components: { month: 12, day: 24 }, label: t("CHRISTMAS_EVE") },
{ components: { month: 1, day: 1 }, label: t("NEW_YEAR") },
{ components: { month: 12, day: 31 }, label: t("NEW_YEAR_EVE") },
];
-
-const parseHolidayComponents = (s: string) =>
- holidays().filter(({ label }) => label.toLowerCase().includes(s));
diff --git a/web/packages/new/photos/services/search/types.ts b/web/packages/new/photos/services/search/types.ts
index 03cd7a504b..a80799ab0e 100644
--- a/web/packages/new/photos/services/search/types.ts
+++ b/web/packages/new/photos/services/search/types.ts
@@ -7,6 +7,11 @@ import { FileType } from "@/media/file-type";
import type { MLStatus } from "@/new/photos/services/ml";
import type { EnteFile } from "@/new/photos/types/file";
+export interface DateSearchResult {
+ components: SearchDateComponents;
+ label: string;
+}
+
/**
* A parsed version of a potential natural language date time string.
*
diff --git a/web/packages/new/photos/services/search/worker.ts b/web/packages/new/photos/services/search/worker.ts
index 549477d8fb..5f19f91dba 100644
--- a/web/packages/new/photos/services/search/worker.ts
+++ b/web/packages/new/photos/services/search/worker.ts
@@ -3,15 +3,22 @@
/* eslint-disable @typescript-eslint/prefer-includes */
/* eslint-disable @typescript-eslint/no-unnecessary-condition */
import { getUICreationDate } from "@/media/file-metadata";
+import type { EnteFile } from "@/new/photos/types/file";
+import { wait } from "@/utils/promise";
+import { nullToUndefined } from "@/utils/transform";
+import { getPublicMagicMetadataSync } from "@ente/shared/file-metadata";
+import type { Component } from "chrono-node";
+import * as chrono from "chrono-node";
+import { expose } from "comlink";
import type {
City,
Location,
LocationTagData,
-} from "@/new/photos/services/search/types";
-import type { EnteFile } from "@/new/photos/types/file";
-import { getPublicMagicMetadataSync } from "@ente/shared/file-metadata";
-import { expose } from "comlink";
-import type { SearchDateComponents, SearchQuery } from "./types";
+ SearchDateComponents,
+ SearchQuery,
+ Suggestion,
+} from "./types";
+import { SuggestionType } from "./types";
/**
* A web worker that runs the search asynchronously so that the main thread
@@ -28,8 +35,18 @@ export class SearchWorker {
}
/**
- * Return {@link EnteFile}s that satisfy the given {@link searchQuery}
- * query.
+ * Convert a search string into a reusable query.
+ */
+ async createSearchQuery(
+ searchString: string,
+ locale: string,
+ holidays: DateSearchResult[],
+ ) {
+ return createSearchQuery(searchString, locale, holidays);
+ }
+
+ /**
+ * Return {@link EnteFile}s that satisfy the given {@link searchQuery}.
*/
search(searchQuery: SearchQuery) {
return this.enteFiles.filter((f) => isMatch(f, searchQuery));
@@ -38,6 +55,113 @@ export class SearchWorker {
expose(SearchWorker);
+const createSearchQuery = async (
+ searchString: string,
+ locale: string,
+ holidays: DateSearchResult[],
+): Promise<Suggestion[]> => {
+ // Normalize it by trimming whitespace and converting to lowercase.
+ const s = searchString.trim().toLowerCase();
+ if (s.length == 0) return [];
+
+ // TODO Temp
+ await wait(0);
+ return [dateSuggestion(s, locale, holidays)].flat();
+};
+
+const dateSuggestion = (
+ s: string,
+ locale: string,
+ holidays: DateSearchResult[],
+) =>
+ parseDateComponents(s, locale, holidays).map(({ components, label }) => ({
+ type: SuggestionType.DATE,
+ value: components,
+ label,
+ }));
+
+interface DateSearchResult {
+ components: SearchDateComponents;
+ label: string;
+}
+
+/**
+ * Try to parse an arbitrary search string into sets of date components.
+ *
+ * e.g. "December 2022" will be parsed into a
+ *
+ * [(year 2022, month 12, day undefined)]
+ *
+ * while "22 December 2022" will be parsed into
+ *
+ * [(year 2022, month 12, day 22)]
+ *
+ * In addition, also return a formatted representation of the "best" guess at
+ * the date that was intended by the search string.
+ */
+export const parseDateComponents = (
+ s: string,
+ locale: string,
+ holidays: DateSearchResult[],
+): DateSearchResult[] =>
+ [
+ parseChrono(s, locale),
+ parseYearComponents(s),
+ parseHolidayComponents(s, holidays),
+ ].flat();
+
+const parseChrono = (s: string, locale: string): DateSearchResult[] =>
+ chrono
+ .parse(s)
+ .map((result) => {
+ const p = result.start;
+ const component = (s: Component) =>
+ p.isCertain(s) ? nullToUndefined(p.get(s)) : undefined;
+
+ const year = component("year");
+ const month = component("month");
+ const day = component("day");
+ const weekday = component("weekday");
+ const hour = component("hour");
+
+ if (!year && !month && !day && !weekday && !hour) return undefined;
+ const components = { year, month, day, weekday, hour };
+
+ const format: Intl.DateTimeFormatOptions = {};
+ if (year) format.year = "numeric";
+ if (month) format.month = "long";
+ if (day) format.day = "numeric";
+ if (weekday) format.weekday = "long";
+ if (hour) {
+ format.hour = "numeric";
+ format.dayPeriod = "short";
+ }
+
+ // TODO Temp
+ console.log("locale", locale);
+
+ const formatter = new Intl.DateTimeFormat(locale, format);
+ const label = formatter.format(p.date());
+ return { components, label };
+ })
+ .filter((x) => x !== undefined);
+
+/** chrono does not parse years like "2024", so do it manually. */
+const parseYearComponents = (s: string): DateSearchResult[] => {
+ // s is already trimmed.
+ if (s.length == 4) {
+ const year = parseInt(s);
+ if (year && year <= 9999) {
+ const components = { year };
+ return [{ components, label: s }];
+ }
+ }
+ return [];
+};
+
+const parseHolidayComponents = (s: string, holidays: DateSearchResult[]) =>
+ holidays.filter(({ label }) => label.toLowerCase().includes(s));
+
function isMatch(file: EnteFile, query: SearchQuery) {
if (query?.collection) {
return query.collection === file.collectionID;