Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(ui): add shared date token parser
joshistoast6c36a09cb4b0
diff --git a/invokeai/frontend/webv2/src/platform/search/dateTokens.test.ts b/invokeai/frontend/webv2/src/platform/search/dateTokens.test.tsnew file mode 100644index 0000000000..9c6934c3ee--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/search/dateTokens.test.ts@@ -0,0 +1,198 @@+import { describe, expect, it } from 'vitest';++import {+ completeTrailingDateToken,+ formatDateRangeLabel,+ formatIsoDate,+ isPossibleDatePrefix,+ isTimestampInRange,+ matchTrailingDateToken,+ parseDateTokens,+} from './dateTokens';++// Tuesday 2026-07-21, mid-day local time.+const NOW = new Date(2026, 6, 21, 13, 30, 0);++describe('parseDateTokens', () => {+ it('returns plain text untouched', () => {+ const parse = parseDateTokens('sunset boulevard', NOW);++ expect(parse).toEqual({+ hasDateTokens: false,+ invalidTokens: [],+ range: undefined,+ text: 'sunset boulevard',+ });+ });++ it('parses ISO from/to and strips the tokens from text', () => {+ const parse = parseDateTokens('sunset from:2026-07-01 to:2026-07-15 boulevard', NOW);++ expect(parse.range).toEqual({ from: '2026-07-01', to: '2026-07-15' });+ expect(parse.text).toBe('sunset boulevard');+ expect(parse.hasDateTokens).toBe(true);+ expect(parse.invalidTokens).toEqual([]);+ });++ it('resolves today and yesterday against the provided now', () => {+ expect(parseDateTokens('from:today', NOW).range).toEqual({ from: '2026-07-21', to: undefined });+ expect(parseDateTokens('from:yesterday', NOW).range).toEqual({ from: '2026-07-20', to: undefined });+ });++ it('resolves Nd and Nw as days ago', () => {+ expect(parseDateTokens('from:7d', NOW).range).toEqual({ from: '2026-07-14', to: undefined });+ expect(parseDateTokens('from:2w', NOW).range).toEqual({ from: '2026-07-07', to: undefined });+ });++ it('resolves Nm as calendar months ago, clamping the day', () => {+ expect(parseDateTokens('from:1m', NOW).range).toEqual({ from: '2026-06-21', to: undefined });+ // Mar 31 − 1m clamps to the end of February.+ expect(parseDateTokens('from:1m', new Date(2026, 2, 31)).range).toEqual({ from: '2026-02-28', to: undefined });+ expect(parseDateTokens('from:1m', new Date(2028, 2, 31)).range).toEqual({ from: '2028-02-29', to: undefined });+ });++ it('is case-insensitive for keys and values', () => {+ const parse = parseDateTokens('FROM:Today TO:YESTERDAY', NOW);++ // from > to, so the bounds swap.+ expect(parse.range).toEqual({ from: '2026-07-20', to: '2026-07-21' });+ });++ it('expands date: into both bounds', () => {+ expect(parseDateTokens('date:2026-07-18', NOW).range).toEqual({ from: '2026-07-18', to: '2026-07-18' });+ });++ it('applies tokens left-to-right with last write per bound winning', () => {+ expect(parseDateTokens('from:2026-07-01 from:2026-07-05', NOW).range).toEqual({+ from: '2026-07-05',+ to: undefined,+ });+ expect(parseDateTokens('date:2026-07-10 to:2026-07-15', NOW).range).toEqual({+ from: '2026-07-10',+ to: '2026-07-15',+ });+ });++ it('swaps bounds when from is after to', () => {+ expect(parseDateTokens('from:2026-07-15 to:2026-07-01', NOW).range).toEqual({+ from: '2026-07-01',+ to: '2026-07-15',+ });+ });++ it('keeps invalid values in text and reports them', () => {+ const parse = parseDateTokens('sunset from:lastweek', NOW);++ expect(parse.range).toBeUndefined();+ expect(parse.text).toBe('sunset from:lastweek');+ expect(parse.hasDateTokens).toBe(true);+ expect(parse.invalidTokens).toEqual([{ key: 'from', raw: 'lastweek' }]);+ });++ it('rejects impossible calendar dates', () => {+ const parse = parseDateTokens('from:2026-02-31', NOW);++ expect(parse.range).toBeUndefined();+ expect(parse.invalidTokens).toEqual([{ key: 'from', raw: '2026-02-31' }]);+ });++ it('mixes valid and invalid tokens without losing either', () => {+ const parse = parseDateTokens('from:7d to:zzz sunset', NOW);++ expect(parse.range).toEqual({ from: '2026-07-14', to: undefined });+ expect(parse.text).toBe('to:zzz sunset');+ expect(parse.invalidTokens).toEqual([{ key: 'to', raw: 'zzz' }]);+ });++ it('ignores tokens without a leading boundary', () => {+ const parse = parseDateTokens('wherefrom:2026-07-01', NOW);++ expect(parse.hasDateTokens).toBe(false);+ expect(parse.text).toBe('wherefrom:2026-07-01');+ });++ it('reports an empty trailing value as invalid', () => {+ const parse = parseDateTokens('from:', NOW);++ expect(parse.range).toBeUndefined();+ expect(parse.invalidTokens).toEqual([{ key: 'from', raw: '' }]);+ });++ it('allows future dates', () => {+ expect(parseDateTokens('from:2030-01-01', NOW).range).toEqual({ from: '2030-01-01', to: undefined });+ });++ it('collapses leftover whitespace after stripping tokens', () => {+ expect(parseDateTokens(' sunset from:7d boulevard ', NOW).text).toBe('sunset boulevard');+ });+});++describe('isTimestampInRange', () => {+ it('accepts both space- and T-separated timestamps', () => {+ const range = { from: '2026-07-14', to: '2026-07-21' };++ expect(isTimestampInRange('2026-07-14 00:00:00.000', range)).toBe(true);+ expect(isTimestampInRange('2026-07-21T23:59:59.999', range)).toBe(true);+ expect(isTimestampInRange('2026-07-13 23:59:59.999', range)).toBe(false);+ expect(isTimestampInRange('2026-07-22T00:00:00.000', range)).toBe(false);+ });++ it('treats bounds as optional', () => {+ expect(isTimestampInRange('2026-07-01 10:00:00', { from: '2026-06-01' })).toBe(true);+ expect(isTimestampInRange('2026-07-01 10:00:00', { to: '2026-06-30' })).toBe(false);+ });++ it('fails closed for empty or malformed timestamps', () => {+ expect(isTimestampInRange('', { from: '2026-07-14' })).toBe(false);+ expect(isTimestampInRange('not-a-date', { from: '2026-07-14' })).toBe(false);+ });+});++describe('matchTrailingDateToken / completeTrailingDateToken', () => {+ it('matches an in-progress trailing token with its source index', () => {+ expect(matchTrailingDateToken('sunset from:y')).toEqual({ key: 'from', partialValue: 'y', start: 7 });+ expect(matchTrailingDateToken('date:')).toEqual({ key: 'date', partialValue: '', start: 0 });+ });++ it('does not match mid-query or boundary-less tokens', () => {+ expect(matchTrailingDateToken('from:7d sunset')).toBeNull();+ expect(matchTrailingDateToken('wherefrom:7d')).toBeNull();+ expect(matchTrailingDateToken('sunset')).toBeNull();+ });++ it('completes the trailing token in place with a trailing space', () => {+ expect(completeTrailingDateToken('sunset from:y', 'yesterday')).toBe('sunset from:yesterday ');+ expect(completeTrailingDateToken('from:', '7d')).toBe('from:7d ');+ expect(completeTrailingDateToken('no token here', 'today')).toBe('no token here');+ });+});++describe('isPossibleDatePrefix', () => {+ it('accepts prefixes of keywords, relative values, and ISO dates', () => {+ for (const value of ['', 'y', 'yester', 'today', 't', '7', '7d', '202', '2026', '2026-', '2026-07-', '2026-07-2']) {+ expect(isPossibleDatePrefix(value), value).toBe(true);+ }+ });++ it('rejects values that can no longer become valid', () => {+ for (const value of ['lastweek', 'yesterdays', '7x', '2026-07-21x', '20260721000']) {+ expect(isPossibleDatePrefix(value), value).toBe(false);+ }+ });+});++describe('formatIsoDate / formatDateRangeLabel', () => {+ it('formats the calendar day itself regardless of timezone offset', () => {+ // A UTC-based Date('2026-07-21') would render Jul 20 in negative offsets;+ // parts-based construction must always yield the written day.+ expect(formatIsoDate('2026-07-21', 'en-US')).toBe('Jul 21');+ });++ it('covers all four range shapes', () => {+ expect(formatDateRangeLabel({ from: '2026-07-14', to: '2026-07-21' }, 'en-US')).toBe('Jul 14 – Jul 21');+ expect(formatDateRangeLabel({ from: '2026-07-14' }, 'en-US')).toBe('From Jul 14');+ expect(formatDateRangeLabel({ to: '2026-07-21' }, 'en-US')).toBe('Through Jul 21');+ expect(formatDateRangeLabel({ from: '2026-07-21', to: '2026-07-21' }, 'en-US')).toBe('Jul 21');+ expect(formatDateRangeLabel({}, 'en-US')).toBe('');+ });+});diff --git a/invokeai/frontend/webv2/src/platform/search/dateTokens.ts b/invokeai/frontend/webv2/src/platform/search/dateTokens.tsnew file mode 100644index 0000000000..a0d155d639--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/search/dateTokens.ts@@ -0,0 +1,246 @@+/**+ * Closed grammar for date-filter search tokens: `from:`, `to:`, and `date:`+ * accepting ISO `YYYY-MM-DD` or the relative values `today`, `yesterday`, and+ * `Nd`/`Nw`/`Nm` (that many days/weeks/calendar-months ago — a single date,+ * not a span). Shared by the gallery search box and the command palette.+ *+ * Invalid token values are never silently dropped: they are reported in+ * `invalidTokens` AND left in `text`, so plain text search still runs over+ * them (this also keeps prompts that literally contain `from:something`+ * findable). Only valid tokens are stripped from `text`.+ *+ * All dates are calendar days. Relative values resolve against the user's+ * local calendar; the backend compares the resulting date-only strings+ * against UTC timestamps, so day boundaries are effectively UTC — the same+ * semantics as the `by_date:` virtual boards.+ */++export type DateTokenKey = 'from' | 'to' | 'date';++export interface DateRange {+ /** Inclusive lower-bound calendar day, YYYY-MM-DD. */+ from?: string;+ /** Inclusive upper-bound calendar day, YYYY-MM-DD. */+ to?: string;+}++export interface InvalidDateToken {+ key: DateTokenKey;+ /** The unparseable value as typed, without the `key:` prefix. */+ raw: string;+}++export interface DateTokenParse {+ /** Query with recognized valid tokens removed and whitespace collapsed. */+ text: string;+ /** Resolved bounds; present only when at least one valid token resolved. */+ range?: DateRange;+ invalidTokens: readonly InvalidDateToken[];+ /** Any from:/to:/date: token present, valid or not. */+ hasDateTokens: boolean;+}++const TOKEN_PATTERN = /(^|\s)(from|to|date):(\S*)/gi;+const TRAILING_TOKEN_PATTERN = /(^|\s)(from|to|date):(\S*)$/i;+const ISO_DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;+const RELATIVE_PATTERN = /^(\d{1,3})(d|w|m)$/;++const pad = (value: number): string => String(value).padStart(2, '0');++const toIsoDate = (date: Date): string => `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;++/** Days N months before `now`, clamping the day-of-month (Mar 31 − 1m → Feb 28/29). */+const monthsAgo = (now: Date, months: number): Date => {+ const target = new Date(now.getFullYear(), now.getMonth() - months, 1);+ const lastDay = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate();+ target.setDate(Math.min(now.getDate(), lastDay));+ return target;+};++const resolveDateValue = (value: string, now: Date): string | null => {+ const lower = value.toLowerCase();++ if (lower === 'today') {+ return toIsoDate(now);+ }++ if (lower === 'yesterday') {+ return toIsoDate(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1));+ }++ const relative = RELATIVE_PATTERN.exec(lower);++ if (relative) {+ const count = Number(relative[1]);++ if (relative[2] === 'm') {+ return toIsoDate(monthsAgo(now, count));+ }++ const days = relative[2] === 'w' ? count * 7 : count;++ return toIsoDate(new Date(now.getFullYear(), now.getMonth(), now.getDate() - days));+ }++ const iso = ISO_DATE_PATTERN.exec(lower);++ if (iso) {+ const year = Number(iso[1]);+ const month = Number(iso[2]);+ const day = Number(iso[3]);+ const candidate = new Date(year, month - 1, day);+ const isRealDate =+ candidate.getFullYear() === year && candidate.getMonth() === month - 1 && candidate.getDate() === day;++ return isRealDate ? lower : null;+ }++ return null;+};++export const parseDateTokens = (query: string, now: Date = new Date()): DateTokenParse => {+ const invalidTokens: InvalidDateToken[] = [];+ let from: string | undefined;+ let to: string | undefined;+ let hasValidToken = false;+ let hasDateTokens = false;++ const text = query+ .replace(TOKEN_PATTERN, (match, boundary: string, rawKey: string, rawValue: string) => {+ hasDateTokens = true;+ const key = rawKey.toLowerCase() as DateTokenKey;+ const resolved = resolveDateValue(rawValue, now);++ if (resolved === null) {+ invalidTokens.push({ key, raw: rawValue });+ return match;+ }++ hasValidToken = true;++ // Tokens apply left-to-right; the last write per bound wins.+ if (key === 'from' || key === 'date') {+ from = resolved;+ }+ if (key === 'to' || key === 'date') {+ to = resolved;+ }++ return boundary;+ })+ .replace(/\s+/g, ' ')+ .trim();++ if (from !== undefined && to !== undefined && from > to) {+ [from, to] = [to, from];+ }++ return {+ hasDateTokens,+ invalidTokens,+ range: hasValidToken ? { from, to } : undefined,+ text,+ };+};++/**+ * True when the timestamp's calendar day falls within the range (bounds+ * inclusive and optional). Works for both space- and T-separated ISO+ * timestamps; empty/absent timestamps fail closed.+ */+export const isTimestampInRange = (isoTimestamp: string, range: DateRange): boolean => {+ const day = isoTimestamp.slice(0, 10);++ if (!ISO_DATE_PATTERN.test(day)) {+ return false;+ }++ return (range.from === undefined || day >= range.from) && (range.to === undefined || day <= range.to);+};++/** The in-progress token at the end of the query, if any, for suggestion UIs. */+export const matchTrailingDateToken = (+ query: string+): { key: DateTokenKey; partialValue: string; start: number } | null => {+ const match = TRAILING_TOKEN_PATTERN.exec(query);++ if (!match || match.index === undefined) {+ return null;+ }++ return {+ key: match[2]?.toLowerCase() as DateTokenKey,+ partialValue: match[3] ?? '',+ start: match.index + (match[1]?.length ?? 0),+ };+};++/** Replaces the trailing token's value with `value` and appends a space. */+export const completeTrailingDateToken = (query: string, value: string): string => {+ const trailing = matchTrailingDateToken(query);++ if (!trailing) {+ return query;+ }++ return `${query.slice(0, trailing.start)}${trailing.key}:${value} `;+};++/**+ * True while `partialValue` could still become a valid value with more+ * typing — used to suppress invalid-token feedback during normal entry.+ */+export const isPossibleDatePrefix = (partialValue: string): boolean => {+ const lower = partialValue.toLowerCase();++ if ('today'.startsWith(lower) || 'yesterday'.startsWith(lower)) {+ return true;+ }++ if (/^\d{1,3}[dwm]?$/.test(lower)) {+ return true;+ }++ // An in-progress ISO date: any prefix of the YYYY-MM-DD shape.+ return /^\d{1,4}(-(\d{0,2}(-\d{0,2})?)?)?$/.test(lower) && lower.length <= 10;+};++/**+ * Formats a YYYY-MM-DD string as a short local date ("Jul 14"). Builds the+ * Date from parts in local time — never via `new Date(isoString)`, which+ * would parse as UTC and shift the day in negative-offset timezones.+ */+export const formatIsoDate = (isoDate: string, locale?: string): string => {+ const parts = ISO_DATE_PATTERN.exec(isoDate);++ if (!parts) {+ return isoDate;+ }++ const local = new Date(Number(parts[1]), Number(parts[2]) - 1, Number(parts[3]));++ return new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' }).format(local);+};++/**+ * Human-readable label for an applied range, e.g. "From Jul 14",+ * "Through Jul 21", "Jul 14 – Jul 21", or "Jul 21" for a single day.+ * English-only; i18n surfaces compose their own labels from formatIsoDate.+ */+export const formatDateRangeLabel = (range: DateRange, locale?: string): string => {+ if (range.from !== undefined && range.to !== undefined) {+ return range.from === range.to+ ? formatIsoDate(range.from, locale)+ : `${formatIsoDate(range.from, locale)} – ${formatIsoDate(range.to, locale)}`;+ }++ if (range.from !== undefined) {+ return `From ${formatIsoDate(range.from, locale)}`;+ }++ if (range.to !== undefined) {+ return `Through ${formatIsoDate(range.to, locale)}`;+ }++ return '';+};