Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(properties): add keyboard first picker for date type properties (#1093)
Seamus67970dffd559
diff --git a/js/app/bun.lock b/js/app/bun.lockindex d4bdc26ed5..8e831de73e 100644--- a/js/app/bun.lock+++ b/js/app/bun.lock@@ -72,6 +72,7 @@"cmdk-solid": "^1.1.2","codemirror": "^6.0.2","colorjs.io": "^0.5.2",+ "date-fns": "^4.1.0","detect-browser": "^5.3.0","email-validator": "^2.0.4","emojilib": "^4.0.2",@@ -1745,6 +1746,8 @@"datadog-metrics": ["[email protected]", "", { "dependencies": { "debug": "3.1.0", "dogapi": "2.8.4" } }, "sha512-BVsBX2t+4yA3tHs7DnB5H01cHVNiGJ/bHA8y6JppJDyXG7s2DLm6JaozPGpgsgVGd42Is1CHRG/yMDQpt877Xg=="],+ "date-fns": ["[email protected]", "", {}, "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg=="],+"dayjs": ["[email protected]", "", {}, "sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg=="],"debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ=="],diff --git a/js/app/package.json b/js/app/package.jsonindex 6bf8c6b310..f2bc0d885f 100644--- a/js/app/package.json+++ b/js/app/package.json@@ -87,6 +87,7 @@"cmdk-solid": "^1.1.2","codemirror": "^6.0.2","colorjs.io": "^0.5.2",+ "date-fns": "^4.1.0","detect-browser": "^5.3.0","email-validator": "^2.0.4","emojilib": "^4.0.2",diff --git a/js/app/packages/core/component/DatePicker/DatePickerUI.tsx b/js/app/packages/core/component/DatePicker/DatePickerUI.tsxnew file mode 100644index 0000000000..60b7b63c0a--- /dev/null+++ b/js/app/packages/core/component/DatePicker/DatePickerUI.tsx@@ -0,0 +1,237 @@+import CaretLeft from '@icon/regular/caret-left.svg';+import CaretRight from '@icon/regular/caret-right.svg';+import { createSignal, For, Show } from 'solid-js';++export type DatePickerUIProps = {+ value: Date;+ onChange: (date: Date) => void;+};++const MONTHS = [+ 'January',+ 'February',+ 'March',+ 'April',+ 'May',+ 'June',+ 'July',+ 'August',+ 'September',+ 'October',+ 'November',+ 'December',+];++const WEEKDAYS = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];++type PickerMode = 'calendar' | 'month' | 'year';++export function DatePickerUI(props: DatePickerUIProps) {+ const [displayMonth, setDisplayMonth] = createSignal(props.value.getMonth());+ const [displayYear, setDisplayYear] = createSignal(props.value.getFullYear());+ const [pickerMode, setPickerMode] = createSignal<PickerMode>('calendar');++ const getDaysInMonth = (year: number, month: number) => {+ return new Date(year, month + 1, 0).getDate();+ };++ const getFirstDayOfMonth = (year: number, month: number) => {+ return new Date(year, month, 1).getDay();+ };++ const handlePrevMonth = () => {+ if (displayMonth() === 0) {+ setDisplayMonth(11);+ setDisplayYear(displayYear() - 1);+ } else {+ setDisplayMonth(displayMonth() - 1);+ }+ };++ const handleNextMonth = () => {+ if (displayMonth() === 11) {+ setDisplayMonth(0);+ setDisplayYear(displayYear() + 1);+ } else {+ setDisplayMonth(displayMonth() + 1);+ }+ };++ const handleDateClick = (day: number) => {+ const newDate = new Date(displayYear(), displayMonth(), day);+ props.onChange(newDate);+ };++ const isToday = (day: number) => {+ const today = new Date();+ return (+ displayYear() === today.getFullYear() &&+ displayMonth() === today.getMonth() &&+ day === today.getDate()+ );+ };++ const isSelected = (day: number) => {+ return (+ displayYear() === props.value.getFullYear() &&+ displayMonth() === props.value.getMonth() &&+ day === props.value.getDate()+ );+ };++ const daysInMonth = () => getDaysInMonth(displayYear(), displayMonth());+ const firstDay = () => getFirstDayOfMonth(displayYear(), displayMonth());++ // Generate calendar days+ const calendarDays = () => {+ const days: (number | null)[] = [];++ // Add empty cells for days before month starts+ for (let i = 0; i < firstDay(); i++) {+ days.push(null);+ }++ // Add days of the month+ for (let i = 1; i <= daysInMonth(); i++) {+ days.push(i);+ }++ return days;+ };++ const handleYearSelect = (year: number) => {+ setDisplayYear(year);+ setPickerMode('month');+ };++ const handleMonthSelect = (month: number) => {+ setDisplayMonth(month);+ setPickerMode('calendar');+ };++ // Generate years for year picker (current year ± 50 years)+ const yearOptions = () => {+ const currentYear = new Date().getFullYear();+ const years: number[] = [];+ for (let i = currentYear - 50; i <= currentYear + 50; i++) {+ years.push(i);+ }+ return years;+ };++ return (+ <div class="p-4 w-80">+ <Show when={pickerMode() === 'calendar'}>+ {/* Month/Year header */}+ <div class="flex items-center justify-between mb-3">+ <button+ class="p-1 hover:bg-active transition-colors"+ onClick={handlePrevMonth}+ >+ <CaretLeft class="w-4 h-4" />+ </button>++ <button+ class="font-semibold hover:bg-active px-2 py-1 transition-colors"+ onClick={() => setPickerMode('month')}+ >+ {MONTHS[displayMonth()]} {displayYear()}+ </button>++ <button+ class="p-1 hover:bg-active transition-colors"+ onClick={handleNextMonth}+ >+ <CaretRight class="w-4 h-4" />+ </button>+ </div>++ {/* Weekday headers */}+ <div class="grid grid-cols-7 gap-1 mb-2">+ <For each={WEEKDAYS}>+ {(day) => (+ <div class="text-center font-medium text-ink-muted">{day}</div>+ )}+ </For>+ </div>++ {/* Calendar days */}+ <div class="grid grid-cols-7 gap-1">+ <For each={calendarDays()}>+ {(day) => (+ <Show when={day !== null} fallback={<div class="h-8" />}>+ <button+ class="h-8 w-8 hover:bg-active transition-colors"+ classList={{+ 'bg-accent text-dialog hover:bg-accent-ink': isSelected(+ day!+ ),+ 'ring-1 ring-accent': isToday(day!),+ }}+ onClick={() => handleDateClick(day!)}+ >+ {day}+ </button>+ </Show>+ )}+ </For>+ </div>+ </Show>++ <Show when={pickerMode() === 'month'}>+ {/* Month picker */}+ <div class="mb-3">+ <button+ class="w-full font-semibold hover:bg-active px-2 py-1 transition-colors text-center"+ onClick={() => setPickerMode('year')}+ >+ {displayYear()}+ </button>+ </div>++ <div class="grid grid-cols-3 gap-2">+ <For each={MONTHS}>+ {(month, index) => (+ <button+ class="px-3 py-2 hover:bg-active transition-colors"+ classList={{+ 'bg-accent text-dialog hover:bg-accent-ink':+ displayMonth() === index(),+ }}+ onClick={() => handleMonthSelect(index())}+ >+ {month.slice(0, 3)}+ </button>+ )}+ </For>+ </div>+ </Show>++ <Show when={pickerMode() === 'year'}>+ {/* Year picker */}+ <div class="mb-3">+ <div class="font-semibold text-center">Select Year</div>+ </div>++ <div class="h-64 overflow-y-auto">+ <div class="grid grid-cols-3 gap-2">+ <For each={yearOptions()}>+ {(year) => (+ <button+ class="px-3 py-2 hover:bg-active transition-colors"+ classList={{+ 'bg-accent text-dialog hover:bg-accent-ink':+ displayYear() === year,+ }}+ onClick={() => handleYearSelect(year)}+ >+ {year}+ </button>+ )}+ </For>+ </div>+ </div>+ </Show>+ </div>+ );+}diff --git a/js/app/packages/core/component/DatePicker/index.tsx b/js/app/packages/core/component/DatePicker/index.tsxindex 76422222ef..6414defbac 100644--- a/js/app/packages/core/component/DatePicker/index.tsx+++ b/js/app/packages/core/component/DatePicker/index.tsx@@ -1,8 +1,6 @@import { floatWithElement } from '@core/component/LexicalMarkdown/directive/floatWithElement';import clickOutside from '@core/directive/clickOutside';-import CaretLeft from '@icon/regular/caret-left.svg';-import CaretRight from '@icon/regular/caret-right.svg';-import { createSignal, For, Show } from 'solid-js';+import { DatePickerUI } from './DatePickerUI';false && floatWithElement;false && clickOutside;@@ -14,250 +12,14 @@ export type DatePickerProps = {anchorRef: HTMLElement;};-const MONTHS = [- 'January',- 'February',- 'March',- 'April',- 'May',- 'June',- 'July',- 'August',- 'September',- 'October',- 'November',- 'December',-];--const WEEKDAYS = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];--type PickerMode = 'calendar' | 'month' | 'year';-export function DatePicker(props: DatePickerProps) {- const [displayMonth, setDisplayMonth] = createSignal(props.value.getMonth());- const [displayYear, setDisplayYear] = createSignal(props.value.getFullYear());- const [pickerMode, setPickerMode] = createSignal<PickerMode>('calendar');-- const getDaysInMonth = (year: number, month: number) => {- return new Date(year, month + 1, 0).getDate();- };-- const getFirstDayOfMonth = (year: number, month: number) => {- return new Date(year, month, 1).getDay();- };-- const handlePrevMonth = () => {- if (displayMonth() === 0) {- setDisplayMonth(11);- setDisplayYear(displayYear() - 1);- } else {- setDisplayMonth(displayMonth() - 1);- }- };-- const handleNextMonth = () => {- if (displayMonth() === 11) {- setDisplayMonth(0);- setDisplayYear(displayYear() + 1);- } else {- setDisplayMonth(displayMonth() + 1);- }- };-- const handleDateClick = (day: number) => {- const newDate = new Date(displayYear(), displayMonth(), day);- props.onChange(newDate);- };-- const isToday = (day: number) => {- const today = new Date();- return (- displayYear() === today.getFullYear() &&- displayMonth() === today.getMonth() &&- day === today.getDate()- );- };-- const isSelected = (day: number) => {- return (- displayYear() === props.value.getFullYear() &&- displayMonth() === props.value.getMonth() &&- day === props.value.getDate()- );- };-- const daysInMonth = () => getDaysInMonth(displayYear(), displayMonth());- const firstDay = () => getFirstDayOfMonth(displayYear(), displayMonth());-- // Generate calendar days- const calendarDays = () => {- const days: (number | null)[] = [];-- // Add empty cells for days before month starts- for (let i = 0; i < firstDay(); i++) {- days.push(null);- }-- // Add days of the month- for (let i = 1; i <= daysInMonth(); i++) {- days.push(i);- }-- return days;- };-- // Quick date options- const today = new Date();- today.setHours(0, 0, 0, 0);-- const tomorrow = new Date(today);- tomorrow.setDate(tomorrow.getDate() + 1);-- const nextWeek = new Date(today);- nextWeek.setDate(nextWeek.getDate() + 7);-- const nextMonth = new Date(today);- nextMonth.setMonth(nextMonth.getMonth() + 1);-- const handleYearSelect = (year: number) => {- setDisplayYear(year);- setPickerMode('month');- };-- const handleMonthSelect = (month: number) => {- setDisplayMonth(month);- setPickerMode('calendar');- };-- // Generate years for year picker (current year ± 50 years)- const yearOptions = () => {- const currentYear = new Date().getFullYear();- const years: number[] = [];- for (let i = currentYear - 50; i <= currentYear + 50; i++) {- years.push(i);- }- return years;- };-return (<div- class="absolute z-action-menu bg-dialog ring-1 ring-edge-muted p-4 w-80 font-mono"+ class="absolute z-action-menu bg-dialog ring-1 ring-edge-muted font-mono text-sm"use:floatWithElement={{ element: () => props.anchorRef }}use:clickOutside={props.onClose}>- <Show when={pickerMode() === 'calendar'}>- {/* Month/Year header */}- <div class="flex items-center justify-between mb-3">- <button- class="p-1 hover:bg-active transition-colors"- onClick={handlePrevMonth}- >- <CaretLeft class="w-4 h-4" />- </button>-- <button- class="font-semibold text-sm hover:bg-active px-2 py-1 transition-colors"- onClick={() => setPickerMode('month')}- >- {MONTHS[displayMonth()]} {displayYear()}- </button>-- <button- class="p-1 hover:bg-active transition-colors"- onClick={handleNextMonth}- >- <CaretRight class="w-4 h-4" />- </button>- </div>-- {/* Weekday headers */}- <div class="grid grid-cols-7 gap-1 mb-2">- <For each={WEEKDAYS}>- {(day) => (- <div class="text-center text-xs font-medium text-ink-muted">- {day}- </div>- )}- </For>- </div>-- {/* Calendar days */}- <div class="grid grid-cols-7 gap-1">- <For each={calendarDays()}>- {(day) => (- <Show when={day !== null} fallback={<div class="h-8" />}>- <button- class="h-8 w-8 text-sm hover:bg-active transition-colors"- classList={{- 'bg-accent text-dialog hover:bg-accent-ink': isSelected(- day!- ),- 'ring-1 ring-accent': isToday(day!),- }}- onClick={() => handleDateClick(day!)}- >- {day}- </button>- </Show>- )}- </For>- </div>- </Show>-- <Show when={pickerMode() === 'month'}>- {/* Month picker */}- <div class="mb-3">- <button- class="w-full font-semibold text-sm hover:bg-active px-2 py-1 transition-colors text-center"- onClick={() => setPickerMode('year')}- >- {displayYear()}- </button>- </div>-- <div class="grid grid-cols-3 gap-2">- <For each={MONTHS}>- {(month, index) => (- <button- class="px-3 py-2 text-sm hover:bg-active transition-colors"- classList={{- 'bg-accent text-dialog hover:bg-accent-ink':- displayMonth() === index(),- }}- onClick={() => handleMonthSelect(index())}- >- {month.slice(0, 3)}- </button>- )}- </For>- </div>- </Show>-- <Show when={pickerMode() === 'year'}>- {/* Year picker */}- <div class="mb-3">- <div class="font-semibold text-sm text-center">Select Year</div>- </div>-- <div class="h-64 overflow-y-auto">- <div class="grid grid-cols-3 gap-2">- <For each={yearOptions()}>- {(year) => (- <button- class="px-3 py-2 text-sm hover:bg-active transition-colors"- classList={{- 'bg-accent text-dialog hover:bg-accent-ink':- displayYear() === year,- }}- onClick={() => handleYearSelect(year)}- >- {year}- </button>- )}- </For>- </div>- </div>- </Show>+ <DatePickerUI value={props.value} onChange={props.onChange} /></div>);}diff --git a/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx b/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsxindex 7e8314854d..4f27b76be6 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx@@ -39,6 +39,7 @@ import {type SelectionData,selectionDataPlugin,tabIndentationPlugin,+ textPastePlugin,} from '../../plugins';import { checkboxToTaskPlugin } from '../../plugins/checkbox-to-task';import { restoreFocusPlugin } from '../../plugins/restore-focus';@@ -193,6 +194,7 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {: selectionDataPlugin(lexicalWrapper)).use(tabIndentationPlugin())+ .use(textPastePlugin()).use(mentionsPlugin({menu: mentionsMenuOperations,diff --git a/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx b/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsxindex 51b01c84d1..c2fac870a3 100644--- a/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx+++ b/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx@@ -15,14 +15,16 @@ import {} from '../../utils/entityConversion';import { PropertyEntitySelector } from './shared/PropertyEntitySelector';import { PropertyOptionSelector } from './shared/PropertyOptionSelector';+import { PropertyDateSelector } from './shared/PropertyDateSelector';import {useAddPropertyOptionMutation,usePropertyOptionsQuery,} from '@queries/properties/options';+import type { DateProperty } from '../../types';// Common CSS classesconst MODAL_BASE =- 'absolute z-action-menu bg-menu border border-edge-muted max-h-96 overflow-hidden flex flex-col w-full max-w-md';+ 'absolute z-action-menu bg-menu border border-edge-muted max-h-96 overflow-hidden flex flex-col w-full max-w-sm';export function EditPropertyValueModal(props: PropertyEditorProps) {const propertyOptionsQuery = usePropertyOptionsQuery(@@ -61,6 +63,12 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {: []);+ const [selectedDate, setSelectedDate] = createSignal<Date | null>(+ props.property.valueType === 'DATE' && props.property.value != null+ ? new Date(props.property.value)+ : null+ );+const {selectedOptions,hasChanges,@@ -99,8 +107,15 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {};break;}+ case 'DATE': {+ const date = selectedDate();+ apiValues = {+ valueType: 'DATE',+ value: date ? date.toISOString() : null,+ };+ break;+ }default:- // Should not reach here as modal only handles select and entity typesconsole.error('PropertyEditor.saveChanges:',new Error(@@ -140,9 +155,24 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {);};+ const hasDateChanges = () => {+ if (props.property.valueType !== 'DATE') return false;++ const currentDate = selectedDate();+ const originalDate = props.property.value+ ? new Date(props.property.value)+ : null;++ if (!currentDate && !originalDate) return false;++ if (!currentDate || !originalDate) return true;++ return currentDate.getTime() !== originalDate.getTime();+ };+const handleClose = async () => {- // All properties that reach this modal (select and entity types) should auto-save- const hasUnsavedChanges = hasChanges() || hasEntityChanges();+ const hasUnsavedChanges =+ hasChanges() || hasEntityChanges() || hasDateChanges();if (hasUnsavedChanges) {await saveChanges();} else {@@ -180,6 +210,7 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {class={MODAL_BASE}tabIndex={-1}use:floatWithElement={{ element: () => props.anchorRef }}+ // All properties that reach this modal (select, entity, and date types) should auto-saveonClick={(e) => e.stopPropagation()}><Show when={!isLoading()}>@@ -191,7 +222,19 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {props.property.valueType === 'SELECT_NUMBER'}fallback={- <Show when={props.property.valueType === 'ENTITY'}>+ <Show+ when={props.property.valueType === 'ENTITY'}+ fallback={+ <Show when={props.property.valueType === 'DATE'}>+ <PropertyDateSelector+ property={props.property as DateProperty}+ selectedDate={selectedDate()}+ onSelectDate={(date) => setSelectedDate(date)}+ onClose={handleClose}+ />+ </Show>+ }+ ><PropertyEntitySelectorproperty={props.property}selectedOptions={() => {diff --git a/js/app/packages/core/component/Properties/component/modal/Modals.tsx b/js/app/packages/core/component/Properties/component/modal/Modals.tsxindex 89f0e4bc96..3297d49b85 100644--- a/js/app/packages/core/component/Properties/component/modal/Modals.tsx+++ b/js/app/packages/core/component/Properties/component/modal/Modals.tsx@@ -1,9 +1,6 @@-import { DatePicker } from '@core/component/DatePicker';-import { ScopedPortal } from '@core/component/ScopedPortal';import { type Component, createMemo } from 'solid-js';import { Show } from 'solid-js/web';import { usePropertiesContext } from '../../context/PropertiesContext';-import type { Property } from '../../types';import { CreatePropertyModal } from './CreatePropertyModal';import { EditPropertyValueModal } from './EditPropertyValueModal';import { SelectPropertyModal } from './SelectPropertyModal';@@ -14,14 +11,11 @@ export const Modals: Component = () => {onPropertyAdded,properties,onRefresh,- saveHandler,propertySelectorModal,propertyEditorModal,- datePickerModal,createPropertyModal,closePropertySelector,closePropertyEditor,- closeDatePicker,closeCreateProperty,} = usePropertiesContext();@@ -34,16 +28,6 @@ export const Modals: Component = () => {closePropertyEditor();};- const handleDateSaved = async (newDate: Date, property: Property) => {- try {- await saveHandler.saveDate(property, newDate);- onRefresh();- } catch (error) {- console.error('Failed to save date property:', error);- }- closeDatePicker();- };-const handlePropertyCreated = () => {onPropertyAdded();closeCreateProperty();@@ -71,26 +55,6 @@ export const Modals: Component = () => {)}</Show>- <Show when={datePickerModal()}>- {(state) => {- const property = state().property;- const dateValue =- property.value != null ? new Date(property.value) : new Date();- const anchor = state().anchor;-- return anchor ? (- <ScopedPortal scope="local">- <DatePicker- value={dateValue}- onChange={(newDate) => handleDateSaved(newDate, property)}- onClose={closeDatePicker}- anchorRef={anchor}- />- </ScopedPortal>- ) : null;- }}- </Show>-<Show when={createPropertyModal()}><CreatePropertyModalisOpen={true}diff --git a/js/app/packages/core/component/Properties/component/modal/shared/PropertyDateSelector.tsx b/js/app/packages/core/component/Properties/component/modal/shared/PropertyDateSelector.tsxnew file mode 100644index 0000000000..591e256e30--- /dev/null+++ b/js/app/packages/core/component/Properties/component/modal/shared/PropertyDateSelector.tsx@@ -0,0 +1,284 @@+import { useDateSearch } from '@core/util/dateSearch/useDateSearch';+import { useSearchInputFocus } from '@core/component/Properties/utils';+import { DatePickerUI } from '@core/component/DatePicker/DatePickerUI';+import SearchIcon from '@icon/regular/magnifying-glass.svg';+import { format } from 'date-fns';+import {+ createEffect,+ createMemo,+ createSignal,+ For,+ Match,+ on,+ onCleanup,+ onMount,+ Show,+ Switch,+} from 'solid-js';+import type { DateProperty } from '@core/component/Properties/types';+import { useKeyPressed } from '@core/util/useKeyPressed';++type DateSelectorMode = 'search' | 'calendar';++type DateSelectorProps = {+ property: DateProperty;+ selectedDate?: Date | null;+ onSelectDate: (date: Date | null) => void;+ onClose?: () => void;+};++export const PropertyDateSelector = (props: DateSelectorProps) => {+ const [mode, setMode] = createSignal<DateSelectorMode>('search');+ const [searchQuery, setSearchQuery] = createSignal('');+ const [selectedIndex, setSelectedIndex] = createSignal(0);+ let searchInputRef!: HTMLInputElement;+ const keyboardMode = useKeyPressed(100);++ const dateOptions = useDateSearch({+ query: searchQuery,+ });++ const totalOptions = createMemo(() => dateOptions().length + 1); // +1 for calendar button++ createEffect(+ on(dateOptions, (options) => {+ if (options.length === 0) {+ setSelectedIndex(0);+ } else {+ setSelectedIndex(Math.min(selectedIndex(), totalOptions() - 1));+ }+ })+ );++ const handleSelectDate = (date: Date) => {+ props.onSelectDate(date);+ if (props.onClose) {+ props.onClose();+ }+ };++ const handleClearDate = (andClose = true) => {+ props.onSelectDate(null);+ if (props.onClose && andClose) {+ props.onClose();+ }+ };++ const scrollSelectedIntoView = () => {+ const options = dateOptions();+ const currentIndex = selectedIndex();+ if (currentIndex >= 0 && currentIndex < options.length) {+ const element = document.querySelector(+ `[data-date-index="${currentIndex}"]`+ );+ if (element) {+ element.scrollIntoView({ block: 'nearest' });+ }+ }+ };++ const handleKeyDown = (e: KeyboardEvent) => {+ const options = dateOptions();+ const total = totalOptions();++ if (+ (e.key === 'Delete' || e.key === 'Backspace') &&+ !searchQuery().trim()+ ) {+ handleClearDate(false);+ e.preventDefault();+ return;+ }++ if (e.key === 'ArrowDown' || (e.ctrlKey && e.key === 'j')) {+ e.preventDefault();+ setSelectedIndex((prev) => (prev + 1) % total);+ scrollSelectedIntoView();+ } else if (e.key === 'ArrowUp' || (e.ctrlKey && e.key === 'k')) {+ e.preventDefault();+ setSelectedIndex((prev) => (prev - 1 + total) % total);+ scrollSelectedIntoView();+ } else if (e.key === 'Enter') {+ e.preventDefault();+ const currentIndex = selectedIndex();++ if (currentIndex === options.length) {+ setMode('calendar');+ } else {+ const selectedOption = options[currentIndex];+ if (selectedOption) {+ handleSelectDate(selectedOption.date);+ }+ }+ }+ };++ onMount(() => {+ document.addEventListener('keydown', handleKeyDown);+ });++ onCleanup(() => {+ document.removeEventListener('keydown', handleKeyDown);+ });++ useSearchInputFocus(+ () => searchInputRef,+ () => true+ );++ const currentDateDisplay = createMemo(() => {+ if (!props.selectedDate) return 'No date set';+ try {+ return format(props.selectedDate, "MMMM d, yyyy 'at' h:mm a");+ } catch {+ return 'Invalid date';+ }+ });++ const handleCalendarChange = (date: Date) => {+ handleSelectDate(date);+ };++ return (+ <div class="relative">+ <div class="flex w-full items-center py-1 gap-2 px-2 border-b border-edge-muted">+ <SearchIcon class="h-4 w-4 text-ink-muted" />+ <input+ class="w-full caret-accent"+ ref={searchInputRef}+ type="text"+ value={searchQuery()}+ onInput={(e) => setSearchQuery(e.currentTarget.value)}+ onKeyDown={(e) => {+ if (e.key === 'Escape') {+ e.preventDefault();+ e.stopPropagation();+ if (props.onClose) {+ props.onClose();+ }+ }+ }}+ placeholder={`Set ${props.property.displayName.toLowerCase()}...`}+ disabled={mode() !== 'search'}+ />+ </div>+ <Switch>+ <Match when={mode() === 'search'}>+ <Show when={props.selectedDate}>+ <div class="px-3 py-2 border-b border-edge-muted pattern pattern-edge-muted pattern-dot-4">+ <div class="flex items-center justify-between">+ <div class="flex items-center gap-2">+ <span class="text-xs text-ink-muted">Current:</span>+ <span class="text-xs font-medium">+ {currentDateDisplay()}+ </span>+ </div>+ <button+ onClick={() => handleClearDate(true)}+ class="text-xs text-ink-muted hover:text-ink underline"+ >+ Clear+ </button>+ </div>+ </div>+ </Show>++ <div class="p-1">+ <div class="max-h-[200px] overflow-y-auto overflow-x-hidden scrollbar-hidden">+ <Show+ when={dateOptions().length > 0}+ fallback={+ <Show+ when={searchQuery().trim()}+ fallback={+ <div class="text-center py-2 text-ink-muted text-sm">+ Enter a date or duration+ </div>+ }+ >+ <div class="text-center py-2 text-ink-muted text-sm">+ No dates match "{searchQuery()}"+ </div>+ </Show>+ }+ >+ <For each={dateOptions()}>+ {(option, index) => (+ <div+ data-date-index={index()}+ class={`flex flex-row w-full justify-between items-center gap-2 py-1.5 px-2 cursor-pointer ${+ index() === selectedIndex() ? 'bg-hover' : ''+ }`}+ onClick={() => handleSelectDate(option.date)}+ onMouseEnter={() => {+ if (!keyboardMode()) {+ setSelectedIndex(index());+ }+ }}+ >+ <div class="flex items-center gap-2 flex-1 min-w-0">+ <p class="text-sm font-medium truncate">+ {option.displayText}+ </p>+ </div>++ <span class="text-xs text-ink-muted">+ {option.secondaryText}+ </span>+ </div>+ )}+ </For>+ </Show>++ <div class="border-t border-edge-muted mt-1 pt-1">+ <div+ data-date-index={dateOptions().length}+ class={`flex flex-row w-full justify-between items-center gap-2 py-1.5 px-2 cursor-pointer ${+ selectedIndex() === dateOptions().length ? 'bg-hover' : ''+ }`}+ onClick={() => setMode('calendar')}+ onMouseEnter={() => {+ if (!keyboardMode()) {+ setSelectedIndex(dateOptions().length);+ }+ }}+ >+ <div class="flex items-center gap-2 flex-1 min-w-0">+ <div class="flex-1 min-w-0">+ <p class="text-sm font-medium truncate">Custom date...</p>+ </div>+ </div>+ <div class="flex items-center gap-2 flex-shrink-0">+ <span class="text-xs text-ink-muted">+ Pick from calendar+ </span>+ </div>+ </div>+ </div>+ </div>+ </div>++ {/* Help text */}+ <div class="px-2 py-1.5 border-t border-edge-muted">+ <div class="text-xs text-ink-muted">+ <span>Use queries like </span>+ <code class="bg-active px-1">3d</code>,{' '}+ <code class="bg-active px-1">1w</code>,{' '}+ <code class="bg-active px-1">feb 17</code>, or{' '}+ <code class="bg-active px-1">tomorrow</code>+ </div>+ </div>+ </Match>++ <Match when={mode() === 'calendar'}>+ <div class="border-b border-edge-muted text-sm flex justify-center">+ <DatePickerUI+ value={props.selectedDate || new Date()}+ onChange={handleCalendarChange}+ />+ </div>+ </Match>+ </Switch>+ </div>+ );+};diff --git a/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx b/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsxindex 56f8a52e39..37a0bb777d 100644--- a/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx+++ b/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx@@ -46,6 +46,7 @@ import {threadMapper,} from './entityUtils';import { OptionCheckBox } from './OptionCheckBox';+import { useKeyPressed } from '@core/util/useKeyPressed';type EntityInputProps = {property: Property;@@ -136,8 +137,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {const [inputValue, setInputValue] = createSignal('');const [searchTerm, setSearchTerm] = createSignal('');const [selectedIndex, setSelectedIndex] = createSignal(0);- const [keyboardNavigationTimeout, setKeyboardNavigationTimeout] =- createSignal<number | null>(null);+ const keyboardMode = useKeyPressed(100);// Debounce search term updates (60ms like MentionsMenu)const debouncedSetSearchTerm = debounce(@@ -430,11 +430,6 @@ export function PropertyEntitySelector(props: EntityInputProps) {}});- const isKeyboardNavigating = () => {- const timeout = keyboardNavigationTimeout();- return timeout !== null && Date.now() - timeout < 150;- };-const scrollSelectedIntoView = () => {const entities = sortedEntities();const currentIndex = selectedIndex();@@ -454,12 +449,10 @@ export function PropertyEntitySelector(props: EntityInputProps) {if (e.key === 'ArrowDown' || (e.ctrlKey && e.key === 'j')) {e.preventDefault();- setKeyboardNavigationTimeout(Date.now());setSelectedIndex((prev) => (prev + 1) % entities.length);scrollSelectedIntoView();} else if (e.key === 'ArrowUp' || (e.ctrlKey && e.key === 'k')) {e.preventDefault();- setKeyboardNavigationTimeout(Date.now());setSelectedIndex((prev) => (prev - 1 + entities.length) % entities.length);@@ -527,7 +520,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {onClick={() => toggleEntity(entity)}onKeyDown={(e) => e.key === 'Enter' && toggleEntity(entity)}onMouseEnter={() => {- if (!isKeyboardNavigating()) {+ if (!keyboardMode()) {setSelectedIndex(index());}}}diff --git a/js/app/packages/core/component/Properties/component/modal/shared/PropertyOptionSelector.tsx b/js/app/packages/core/component/Properties/component/modal/shared/PropertyOptionSelector.tsxindex e0f8ba5827..866c09fd75 100644--- a/js/app/packages/core/component/Properties/component/modal/shared/PropertyOptionSelector.tsx+++ b/js/app/packages/core/component/Properties/component/modal/shared/PropertyOptionSelector.tsx@@ -18,6 +18,7 @@ import { formatOptionValue, useSearchInputFocus } from '../../../utils';import { ERROR_MESSAGES } from '../../../utils/errorHandling';import { PropertyValueIcon } from '../../propertyValue';import { OptionCheckBox } from './OptionCheckBox';+import { useKeyPressed } from '@core/util/useKeyPressed';type PropertyOption = z.infer<typeof schemas.getPropertyOptionsResponseItem>;@@ -36,8 +37,8 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {const [searchQuery, setSearchQuery] = createSignal('');const [isAddingOption, setIsAddingOption] = createSignal(false);const [selectedIndex, setSelectedIndex] = createSignal(0);- const [keyboardNavigationTimeout, setKeyboardNavigationTimeout] =- createSignal<number | null>(null);++ const keyboardMode = useKeyPressed(100);let searchInputRef!: HTMLInputElement;@@ -154,11 +155,6 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {}});- const isKeyboardNavigating = () => {- const timeout = keyboardNavigationTimeout();- return timeout !== null && Date.now() - timeout < 150;- };-const shouldShowHotkeys = createMemo(() => {return !searchQuery().trim() && selectableItems().length <= 9;});@@ -189,11 +185,9 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {if (e.key === 'ArrowDown' || (e.ctrlKey && e.key === 'j')) {e.preventDefault();- setKeyboardNavigationTimeout(Date.now());setSelectedIndex((prev) => (prev + 1) % items.length);} else if (e.key === 'ArrowUp' || (e.ctrlKey && e.key === 'k')) {e.preventDefault();- setKeyboardNavigationTimeout(Date.now());setSelectedIndex((prev) => (prev - 1 + items.length) % items.length);} else if (e.key === 'Enter') {e.preventDefault();@@ -347,7 +341,7 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {}}}onMouseEnter={() => {- if (!isKeyboardNavigating()) {+ if (!keyboardMode()) {setSelectedIndex(index());}}}@@ -376,7 +370,7 @@ export const PropertyOptionSelector = (props: SelectOptionsProps) => {><divonMouseEnter={() => {- if (!isKeyboardNavigating()) {+ if (!keyboardMode()) {setSelectedIndex(index());}}}diff --git a/js/app/packages/core/component/Properties/component/panel/PropertyGrid.tsx b/js/app/packages/core/component/Properties/component/panel/PropertyGrid.tsxindex 42fcc62fa5..a27adb10d2 100644--- a/js/app/packages/core/component/Properties/component/panel/PropertyGrid.tsx+++ b/js/app/packages/core/component/Properties/component/panel/PropertyGrid.tsx@@ -11,7 +11,7 @@ interface PropertiesListProps {}export const PropertyGrid: Component<PropertiesListProps> = (props) => {- const { openPropertyEditor, openDatePicker } = usePropertiesContext();+ const { openPropertyEditor } = usePropertiesContext();const blockName = useMaybeBlockAliasedName();const builtinPropertyIds = blockName ? getBuiltinPropertyIds(blockName) : [];@@ -59,9 +59,8 @@ export const PropertyGrid: Component<PropertiesListProps> = (props) => {);const handleValueClick = (property: Property, anchor?: HTMLElement) => {- if (property.valueType === 'DATE') {- openDatePicker(property, anchor);- } else if (+ if (+ property.valueType === 'DATE' ||property.valueType === 'SELECT_STRING' ||property.valueType === 'SELECT_NUMBER' ||property.valueType === 'ENTITY'diff --git a/js/app/packages/core/component/Properties/component/propertyValue/CondensedPropertyValue.tsx b/js/app/packages/core/component/Properties/component/propertyValue/CondensedPropertyValue.tsxindex 9618620194..018d02337d 100644--- a/js/app/packages/core/component/Properties/component/propertyValue/CondensedPropertyValue.tsx+++ b/js/app/packages/core/component/Properties/component/propertyValue/CondensedPropertyValue.tsx@@ -6,7 +6,6 @@ import type { Component } from 'solid-js';import { Show } from 'solid-js';import type { Property } from '../../types';import {- isDateProperty,hasValue,isSelectProperty,isEntityProperty,@@ -27,8 +26,7 @@ type CondensedPropertyValueProps = {export const CondensedPropertyValue: Component<CondensedPropertyValueProps> = (props) => {- const { canEdit, openPropertyEditor, openDatePicker } =- usePropertiesContext();+ const { canEdit, openPropertyEditor } = usePropertiesContext();const validValue = () => hasValue(props.property);@@ -37,11 +35,7 @@ export const CondensedPropertyValue: Component<CondensedPropertyValueProps> = (e.preventDefault();e.stopPropagation();const target = e.currentTarget as HTMLElement;- if (isDateProperty(props.property)) {- openDatePicker(props.property, target);- } else {- openPropertyEditor(props.property, target);- }+ openPropertyEditor(props.property, target);};return (diff --git a/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsx b/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsxindex 8a6860ced4..71017ac901 100644--- a/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsx+++ b/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsx@@ -3,6 +3,7 @@ import { createSignal, Show } from 'solid-js';import { usePropertiesContext } from '../../context/PropertiesContext';import { formatDate } from '../../utils';import {+ EmptyValue,PropertyValueDeleteButton,type PropertyValueProps,} from './ValueComponents';@@ -57,18 +58,14 @@ export const DateValue: Component<PropertyValueProps> = (props) => {<buttononClick={handleClick}class={cn(- 'inline-flex items-center text-xs leading-none text-ink-muted shrink-0 py-1.5 h-6.5 transition-colors border border-edge-muted/50 px-1.5',+ 'inline-flex items-center leading-none shrink-0 py-1.5 h-6.5 transition-colors border border-edge-muted px-1.5',{'cursor-pointer hover:border-edge-muted hover:bg-hover/50':props.canEdit,- 'opacity-50': !displayValue,})}>- <Show- when={displayValue}- fallback={<span class="opacity-20">Due Date</span>}- >+ <Show when={displayValue} fallback={<EmptyValue />}><span class="block truncate max-w-full">{displayValue}</span></Show></button>diff --git a/js/app/packages/core/util/dateSearch/dateParser.test.ts b/js/app/packages/core/util/dateSearch/dateParser.test.tsnew file mode 100644index 0000000000..cf202cf187--- /dev/null+++ b/js/app/packages/core/util/dateSearch/dateParser.test.ts@@ -0,0 +1,222 @@+import { describe, expect, it } from 'vitest';+import {+ addDays,+ addHours,+ addMinutes,+ addMonths,+ addWeeks,+ addYears,+} from 'date-fns';+import {+ applyDurationToDate,+ couldBeDurationString,+ formatDuration,+ parseDateFromDuration,+ parseDurationString,+ type ParsedDuration,+} from './dateParser';++describe('parseDurationString', () => {+ it('should parse hours correctly', () => {+ expect(parseDurationString('1h')).toEqual({ value: 1, unit: 'h' });+ expect(parseDurationString('24h')).toEqual({ value: 24, unit: 'h' });+ expect(parseDurationString('36h')).toEqual({ value: 36, unit: 'h' });+ expect(parseDurationString('0.5h')).toEqual({ value: 0.5, unit: 'h' });+ });++ it('should parse days correctly', () => {+ expect(parseDurationString('1d')).toEqual({ value: 1, unit: 'd' });+ expect(parseDurationString('3d')).toEqual({ value: 3, unit: 'd' });+ expect(parseDurationString('7d')).toEqual({ value: 7, unit: 'd' });+ expect(parseDurationString('1.5d')).toEqual({ value: 1.5, unit: 'd' });+ });++ it('should parse weeks correctly', () => {+ expect(parseDurationString('1w')).toEqual({ value: 1, unit: 'w' });+ expect(parseDurationString('2w')).toEqual({ value: 2, unit: 'w' });+ expect(parseDurationString('4.5w')).toEqual({ value: 4.5, unit: 'w' });+ });++ it('should parse months correctly', () => {+ expect(parseDurationString('1m')).toEqual({ value: 1, unit: 'm' });+ expect(parseDurationString('3m')).toEqual({ value: 3, unit: 'm' });+ expect(parseDurationString('12m')).toEqual({ value: 12, unit: 'm' });+ });++ it('should parse years correctly', () => {+ expect(parseDurationString('1y')).toEqual({ value: 1, unit: 'y' });+ expect(parseDurationString('2y')).toEqual({ value: 2, unit: 'y' });+ expect(parseDurationString('0.5y')).toEqual({ value: 0.5, unit: 'y' });+ });++ it('should parse minutes correctly', () => {+ expect(parseDurationString('30min')).toEqual({ value: 30, unit: 'min' });+ expect(parseDurationString('45min')).toEqual({ value: 45, unit: 'min' });+ expect(parseDurationString('90min')).toEqual({ value: 90, unit: 'min' });+ });++ it('should handle whitespace', () => {+ expect(parseDurationString(' 3d ')).toEqual({ value: 3, unit: 'd' });+ expect(parseDurationString('3 d')).toEqual({ value: 3, unit: 'd' });+ expect(parseDurationString(' 1 h ')).toEqual({ value: 1, unit: 'h' });+ });++ it('should be case insensitive', () => {+ expect(parseDurationString('3D')).toEqual({ value: 3, unit: 'd' });+ expect(parseDurationString('1W')).toEqual({ value: 1, unit: 'w' });+ expect(parseDurationString('2H')).toEqual({ value: 2, unit: 'h' });+ expect(parseDurationString('30MIN')).toEqual({ value: 30, unit: 'min' });+ });++ it('should return null for invalid input', () => {+ expect(parseDurationString('')).toBeNull();+ expect(parseDurationString('abc')).toBeNull();+ expect(parseDurationString('3')).toBeNull();+ expect(parseDurationString('d')).toBeNull();+ expect(parseDurationString('3x')).toBeNull();+ expect(parseDurationString('-3d')).toBeNull();+ expect(parseDurationString('0d')).toBeNull();+ });+});++describe('applyDurationToDate', () => {+ const baseDate = new Date('2024-01-15T10:00:00');++ it('should add hours correctly', () => {+ const duration: ParsedDuration = { value: 3, unit: 'h' };+ const result = applyDurationToDate(baseDate, duration);+ expect(result).toEqual(addHours(baseDate, 3));+ });++ it('should add days correctly', () => {+ const duration: ParsedDuration = { value: 5, unit: 'd' };+ const result = applyDurationToDate(baseDate, duration);+ expect(result).toEqual(addDays(baseDate, 5));+ });++ it('should add weeks correctly', () => {+ const duration: ParsedDuration = { value: 2, unit: 'w' };+ const result = applyDurationToDate(baseDate, duration);+ expect(result).toEqual(addWeeks(baseDate, 2));+ });++ it('should add months correctly', () => {+ const duration: ParsedDuration = { value: 3, unit: 'm' };+ const result = applyDurationToDate(baseDate, duration);+ expect(result).toEqual(addMonths(baseDate, 3));+ });++ it('should add years correctly', () => {+ const duration: ParsedDuration = { value: 1, unit: 'y' };+ const result = applyDurationToDate(baseDate, duration);+ expect(result).toEqual(addYears(baseDate, 1));+ });++ it('should add minutes correctly', () => {+ const duration: ParsedDuration = { value: 45, unit: 'min' };+ const result = applyDurationToDate(baseDate, duration);+ expect(result).toEqual(addMinutes(baseDate, 45));+ });++ it('should round decimal values', () => {+ const duration: ParsedDuration = { value: 1.7, unit: 'h' };+ const result = applyDurationToDate(baseDate, duration);+ // 1.7 hours should round to 2 hours+ expect(result).toEqual(addHours(baseDate, 2));+ });+});++describe('parseDateFromDuration', () => {+ it('should parse and apply duration from string', () => {+ const baseDate = new Date('2024-01-15T10:00:00');++ const result1 = parseDateFromDuration('3d', baseDate);+ expect(result1).toEqual(addDays(baseDate, 3));++ const result2 = parseDateFromDuration('1w', baseDate);+ expect(result2).toEqual(addWeeks(baseDate, 1));++ const result3 = parseDateFromDuration('24h', baseDate);+ expect(result3).toEqual(addHours(baseDate, 24));+ });++ it('should use current date when base date not provided', () => {+ const now = new Date();+ const result = parseDateFromDuration('1d');++ // Check that it's approximately 1 day in the future+ const expectedMin = addDays(now, 1).getTime() - 1000; // Allow 1 second tolerance+ const expectedMax = addDays(now, 1).getTime() + 1000;++ expect(result!.getTime()).toBeGreaterThanOrEqual(expectedMin);+ expect(result!.getTime()).toBeLessThanOrEqual(expectedMax);+ });++ it('should return null for invalid input', () => {+ expect(parseDateFromDuration('invalid')).toBeNull();+ expect(parseDateFromDuration('')).toBeNull();+ expect(parseDateFromDuration('3')).toBeNull();+ });+});++describe('couldBeDurationString', () => {+ it('should return true for valid duration strings', () => {+ expect(couldBeDurationString('3d')).toBe(true);+ expect(couldBeDurationString('1w')).toBe(true);+ expect(couldBeDurationString('24h')).toBe(true);+ expect(couldBeDurationString('30min')).toBe(true);+ });++ it('should return true for partial duration strings', () => {+ expect(couldBeDurationString('')).toBe(true);+ expect(couldBeDurationString('3')).toBe(true);+ expect(couldBeDurationString('3.')).toBe(true);+ expect(couldBeDurationString('3.5')).toBe(true);+ expect(couldBeDurationString('3d')).toBe(true);+ });++ it('should return true for partial "min" strings', () => {+ expect(couldBeDurationString('30m')).toBe(true);+ expect(couldBeDurationString('30mi')).toBe(true);+ expect(couldBeDurationString('30min')).toBe(true);+ });++ it('should return false for invalid strings', () => {+ expect(couldBeDurationString('abc')).toBe(false);+ expect(couldBeDurationString('3x')).toBe(false);+ expect(couldBeDurationString('d3')).toBe(false);+ expect(couldBeDurationString('hello')).toBe(false);+ });++ it('should handle whitespace', () => {+ expect(couldBeDurationString(' ')).toBe(true);+ expect(couldBeDurationString(' 3 ')).toBe(true);+ expect(couldBeDurationString('3 d')).toBe(true);+ });+});++describe('formatDuration', () => {+ it('should format singular units correctly', () => {+ expect(formatDuration({ value: 1, unit: 'h' })).toBe('1 hour');+ expect(formatDuration({ value: 1, unit: 'd' })).toBe('1 day');+ expect(formatDuration({ value: 1, unit: 'w' })).toBe('1 week');+ expect(formatDuration({ value: 1, unit: 'm' })).toBe('1 month');+ expect(formatDuration({ value: 1, unit: 'y' })).toBe('1 year');+ expect(formatDuration({ value: 1, unit: 'min' })).toBe('1 minute');+ });++ it('should format plural units correctly', () => {+ expect(formatDuration({ value: 2, unit: 'h' })).toBe('2 hours');+ expect(formatDuration({ value: 3, unit: 'd' })).toBe('3 days');+ expect(formatDuration({ value: 4, unit: 'w' })).toBe('4 weeks');+ expect(formatDuration({ value: 5, unit: 'm' })).toBe('5 months');+ expect(formatDuration({ value: 2, unit: 'y' })).toBe('2 years');+ expect(formatDuration({ value: 30, unit: 'min' })).toBe('30 minutes');+ });++ it('should handle decimal values', () => {+ expect(formatDuration({ value: 1.5, unit: 'h' })).toBe('1.5 hours');+ expect(formatDuration({ value: 0.5, unit: 'd' })).toBe('0.5 days');+ expect(formatDuration({ value: 2.5, unit: 'w' })).toBe('2.5 weeks');+ });+});diff --git a/js/app/packages/core/util/dateSearch/dateParser.ts b/js/app/packages/core/util/dateSearch/dateParser.tsnew file mode 100644index 0000000000..86fb36d159--- /dev/null+++ b/js/app/packages/core/util/dateSearch/dateParser.ts@@ -0,0 +1,113 @@+import {+ addDays,+ addHours,+ addMinutes,+ addMonths,+ addWeeks,+ addYears,+} from 'date-fns';+import { match } from 'ts-pattern';++export type TimeUnit = 'h' | 'd' | 'w' | 'm' | 'y' | 'min';++export interface ParsedDuration {+ value: number;+ unit: TimeUnit;+}++const UNITS = new Set<TimeUnit>(['h', 'd', 'w', 'm', 'y', 'min']);++/**+ * Parses a duration string like "3d", "1w", "36h", "2m", "1y", "30min"+ * Returns null if the input doesn't match the expected format+ */+export function parseDurationString(input: string): ParsedDuration | null {+ const s = input.trim().toLowerCase();+ if (!s) return null;++ const firstLetter = s.search(/[a-z]/);+ if (firstLetter <= 0) return null;++ const numPart = s.slice(0, firstLetter).trim();+ const unitPart = s.slice(firstLetter).trim() as TimeUnit;++ if (!UNITS.has(unitPart)) return null;++ const value = Number(numPart);+ if (!Number.isFinite(value) || value <= 0) return null;++ return { value, unit: unitPart };+}++/**+ * Converts a parsed duration to a Date object relative to a base date+ */+export function applyDurationToDate(+ baseDate: Date,+ duration: ParsedDuration+): Date {+ const value = Math.round(duration.value);+ const unit = duration.unit;++ return match(unit)+ .with('min', () => addMinutes(baseDate, value))+ .with('h', () => addHours(baseDate, value))+ .with('d', () => addDays(baseDate, value))+ .with('w', () => addWeeks(baseDate, value))+ .with('m', () => addMonths(baseDate, value))+ .with('y', () => addYears(baseDate, value))+ .otherwise(() => baseDate);+}++/**+ * Main parser function that takes a duration string and returns a Date+ */+export function parseDateFromDuration(+ input: string,+ baseDate: Date = new Date()+): Date | null {+ const parsed = parseDurationString(input);+ if (!parsed) {+ return null;+ }+ return applyDurationToDate(baseDate, parsed);+}++/**+ * Checks if a string could be a duration string (for real-time validation)+ */+export function couldBeDurationString(input: string): boolean {+ const trimmed = input.trim().toLowerCase();++ // empty string could become a duration+ if (trimmed === '') return true;++ // just a number could become a duration (including partial decimals like "3.")+ if (/^\d+(?:\.\d*)?$/.test(trimmed)) return true;++ // number followed by valid unit letters+ if (/^\d+(?:\.\d+)?\s*[hdwmy]?$/.test(trimmed)) return true;++ // special case for "min"+ if (/^\d+(?:\.\d+)?\s*m?i?n?$/.test(trimmed)) return true;++ return false;+}++/**+ * Format a duration for display+ */+export function formatDuration(duration: ParsedDuration): string {+ const { value, unit } = duration;++ const unitLabels: Record<TimeUnit, string> = {+ min: value === 1 ? 'minute' : 'minutes',+ h: value === 1 ? 'hour' : 'hours',+ d: value === 1 ? 'day' : 'days',+ w: value === 1 ? 'week' : 'weeks',+ m: value === 1 ? 'month' : 'months',+ y: value === 1 ? 'year' : 'years',+ };++ return `${value} ${unitLabels[unit]}`;+}diff --git a/js/app/packages/core/util/dateSearch/presets.ts b/js/app/packages/core/util/dateSearch/presets.tsnew file mode 100644index 0000000000..f5e02a04bd--- /dev/null+++ b/js/app/packages/core/util/dateSearch/presets.ts@@ -0,0 +1,84 @@+import { addDays, addWeeks, endOfDay, endOfWeek } from 'date-fns';++export interface DatePreset {+ id: string;+ label: string;+ shortLabel?: string;+ keywords: string[];+ getDate: (baseDate?: Date) => Date;+ category?: 'quick' | 'week' | 'month' | 'year';+}++export const DATE_PRESETS: DatePreset[] = [+ {+ id: 'today',+ label: 'Today (end of day)',+ shortLabel: 'Today',+ keywords: ['today', 'end', 'end of day', 'eod'],+ getDate: (baseDate = new Date()) => endOfDay(baseDate),+ category: 'quick',+ },+ {+ id: 'tomorrow',+ label: 'Tomorrow (end of day)',+ shortLabel: 'Tom',+ keywords: ['tomorrow', 'tmrw', 'tom'],+ getDate: (baseDate = new Date()) => addDays(endOfDay(baseDate), 1),+ category: 'quick',+ },+ {+ id: 'in-2-days',+ label: 'In 2 days',+ shortLabel: '2d',+ keywords: ['2 days', '2d', 'two days'],+ getDate: (baseDate = new Date()) => addDays(endOfDay(baseDate), 2),+ category: 'quick',+ },+ {+ id: 'end-of-week',+ label: 'End of week',+ shortLabel: 'EOW',+ keywords: ['end of week', 'eow', 'weekend', 'friday'],+ getDate: (baseDate = new Date()) =>+ endOfWeek(baseDate, { weekStartsOn: 1 }),+ category: 'week',+ },+ {+ id: 'in-1-week',+ label: 'In 1 week',+ shortLabel: '1w',+ keywords: ['1 week', '1w', 'one week', 'week'],+ getDate: (baseDate = new Date()) => addWeeks(baseDate, 1),+ category: 'week',+ },+ {+ id: 'in-2-weeks',+ label: 'In 2 weeks',+ shortLabel: '2w',+ keywords: ['2 weeks', '2w', 'two weeks', 'fortnight'],+ getDate: (baseDate = new Date()) => addWeeks(baseDate, 2),+ category: 'week',+ },+];++export function searchPresets(query: string): DatePreset[] {+ const normalizedQuery = query.toLowerCase().trim();++ if (!normalizedQuery) {+ return DATE_PRESETS;+ }++ return DATE_PRESETS.filter((preset) => {+ if (preset.label.toLowerCase().includes(normalizedQuery)) {+ return true;+ }++ if (preset.shortLabel?.toLowerCase().includes(normalizedQuery)) {+ return true;+ }++ return preset.keywords.some((keyword) =>+ keyword.toLowerCase().includes(normalizedQuery)+ );+ });+}diff --git a/js/app/packages/core/util/dateSearch/useDateSearch.test.ts b/js/app/packages/core/util/dateSearch/useDateSearch.test.tsnew file mode 100644index 0000000000..31c1023119--- /dev/null+++ b/js/app/packages/core/util/dateSearch/useDateSearch.test.ts@@ -0,0 +1,390 @@+import { describe, expect, it } from 'vitest';+import { createRoot, createSignal } from 'solid-js';+import { addDays } from 'date-fns';+import {+ useDateSearch,+ parseNaturalDate,+ formatDateWithContext,+} from './useDateSearch';++describe('parseNaturalDate', () => {+ const baseDate = new Date('2024-06-15T10:00:00');++ it('should parse month and day formats', () => {+ const feb17 = parseNaturalDate('feb 17', baseDate);+ expect(feb17).toBeTruthy();+ expect(feb17?.getMonth()).toBe(1); // February is month 1+ expect(feb17?.getDate()).toBe(17);++ const march3 = parseNaturalDate('march 3', baseDate);+ expect(march3).toBeTruthy();+ expect(march3?.getMonth()).toBe(2); // March is month 2+ expect(march3?.getDate()).toBe(3);++ const jan1 = parseNaturalDate('January 1', baseDate);+ expect(jan1).toBeTruthy();+ expect(jan1?.getMonth()).toBe(0); // January is month 0+ expect(jan1?.getDate()).toBe(1);+ });++ it('should handle dates with explicit years', () => {+ const feb172025 = parseNaturalDate('feb 17 2025', baseDate);+ expect(feb172025).toBeTruthy();+ expect(feb172025?.getFullYear()).toBe(2025);+ expect(feb172025?.getMonth()).toBe(1);+ expect(feb172025?.getDate()).toBe(17);++ const jan12024 = parseNaturalDate('January 1 2024', baseDate);+ expect(jan12024).toBeTruthy();+ expect(jan12024?.getFullYear()).toBe(2024);+ });++ it('should intelligently select year for dates without year', () => {+ // Date in the near future should use current year+ const july4 = parseNaturalDate('july 4', baseDate);+ expect(july4?.getFullYear()).toBe(2024);++ // Date far in the past should use next year+ const jan1 = parseNaturalDate('jan 1', baseDate);+ // Jan 1 is 5.5 months before June 15, which is less than 6 months,+ // so it should stay in the current year (2024)+ expect(jan1?.getFullYear()).toBe(2024);++ // A date that's definitely more than 6 months in the past should use next year+ const nov1 = parseNaturalDate('nov 1', baseDate);+ // Nov 1, 2023 would be 7+ months before June 15, 2024, so should become Nov 1, 2024+ expect(nov1?.getFullYear()).toBe(2024);+ });++ it('should parse numeric date formats', () => {+ const date1 = parseNaturalDate('3/15', baseDate);+ expect(date1?.getMonth()).toBe(2); // March+ expect(date1?.getDate()).toBe(15);++ const date2 = parseNaturalDate('12/25/2024', baseDate);+ expect(date2?.getFullYear()).toBe(2024);+ expect(date2?.getMonth()).toBe(11); // December+ expect(date2?.getDate()).toBe(25);++ const date3 = parseNaturalDate('2024-03-15', baseDate);+ expect(date3?.getFullYear()).toBe(2024);+ expect(date3?.getMonth()).toBe(2); // March+ expect(date3?.getDate()).toBe(15);+ });++ it('should parse relative day names', () => {+ // parseNaturalDate doesn't handle relative keywords like 'today', 'tomorrow', 'yesterday'+ // These are handled by presets in the useDateSearch hook+ const today = parseNaturalDate('today', baseDate);+ expect(today).toBeNull();++ const tomorrow = parseNaturalDate('tomorrow', baseDate);+ expect(tomorrow).toBeNull();++ const yesterday = parseNaturalDate('yesterday', baseDate);+ expect(yesterday).toBeNull();+ });++ it('should parse day of week names', () => {+ // Base date is Saturday June 15, 2024+ const monday = parseNaturalDate('monday', baseDate);+ expect(monday).toBeTruthy();+ // Next Monday should be June 17+ expect(monday?.getDate()).toBe(17);++ const fri = parseNaturalDate('fri', baseDate);+ expect(fri).toBeTruthy();+ // Next Friday should be June 21+ expect(fri?.getDate()).toBe(21);+ });++ it('should handle case insensitivity', () => {+ const date1 = parseNaturalDate('FEB 17', baseDate);+ const date2 = parseNaturalDate('feb 17', baseDate);+ const date3 = parseNaturalDate('Feb 17', baseDate);++ expect(date1?.getTime()).toBe(date2?.getTime());+ expect(date2?.getTime()).toBe(date3?.getTime());++ const today1 = parseNaturalDate('TODAY', baseDate);+ const today2 = parseNaturalDate('today', baseDate);+ expect(today1?.getTime()).toBe(today2?.getTime());+ });++ it('should return null for invalid dates', () => {+ expect(parseNaturalDate('invalid', baseDate)).toBeNull();+ expect(parseNaturalDate('feb 30', baseDate)).toBeNull();+ expect(parseNaturalDate('13/32', baseDate)).toBeNull();+ expect(parseNaturalDate('', baseDate)).toBeNull();+ });++ it('should handle European date format', () => {+ const date = parseNaturalDate('15-03-2024', baseDate);+ expect(date?.getFullYear()).toBe(2024);+ expect(date?.getMonth()).toBe(2); // March+ expect(date?.getDate()).toBe(15);+ });++ it('should handle day-month format', () => {+ const date1 = parseNaturalDate('17 Feb', baseDate);+ expect(date1?.getMonth()).toBe(1); // February+ expect(date1?.getDate()).toBe(17);++ const date2 = parseNaturalDate('3 March 2025', baseDate);+ expect(date2?.getFullYear()).toBe(2025);+ expect(date2?.getMonth()).toBe(2); // March+ expect(date2?.getDate()).toBe(3);+ });+});++describe('formatDateWithContext', () => {+ const baseDate = new Date('2024-06-15T14:00:00');++ it('should format today correctly', () => {+ const today = new Date('2024-06-15T18:30:00');+ const formatted = formatDateWithContext(today, baseDate);+ expect(formatted).toContain('Today');+ expect(formatted).toContain('6:30 PM');+ });++ it('should format tomorrow correctly', () => {+ const tomorrow = new Date('2024-06-16T09:00:00');+ const formatted = formatDateWithContext(tomorrow, baseDate);+ expect(formatted).toContain('Tomorrow');+ expect(formatted).toContain('9:00 AM');+ });++ it('should format yesterday correctly', () => {+ const yesterday = new Date('2024-06-14T15:45:00');+ const formatted = formatDateWithContext(yesterday, baseDate);+ expect(formatted).toContain('Yesterday');+ expect(formatted).toContain('3:45 PM');+ });++ it('should format dates within a week with day name', () => {+ const nextWednesday = new Date('2024-06-19T12:00:00');+ const formatted = formatDateWithContext(nextWednesday, baseDate);+ expect(formatted).toContain('Wednesday');+ expect(formatted).toContain('Jun 19');+ expect(formatted).toContain('12:00 PM');+ });++ it('should format dates in same year without year', () => {+ const futureDate = new Date('2024-08-20T10:00:00');+ const formatted = formatDateWithContext(futureDate, baseDate);+ expect(formatted).toContain('Aug 20');+ expect(formatted).not.toContain('2024');+ expect(formatted).toContain('10:00 AM');+ });++ it('should format dates in different year with year', () => {+ const nextYear = new Date('2025-01-15T14:30:00');+ const formatted = formatDateWithContext(nextYear, baseDate);+ expect(formatted).toContain('Jan 15, 2025');+ expect(formatted).toContain('2:30 PM');+ });+});++describe('useDateSearch', () => {+ it('should return default presets when query is empty', () => {+ createRoot((dispose) => {+ const [query] = createSignal('');+ const options = useDateSearch({ query });++ const result = options();+ expect(result.length).toBeGreaterThan(0);+ expect(result.length).toBeLessThanOrEqual(10);+ expect(result[0].type).toBe('preset');++ dispose();+ });+ });++ it('should parse duration DSL', () => {+ createRoot((dispose) => {+ const [query] = createSignal('3d');+ const baseDate = new Date('2024-06-15T10:00:00');+ const options = useDateSearch({ query, baseDate });++ const result = options();+ expect(result.length).toBeGreaterThan(0);++ const durationOption = result.find((opt) => opt.type === 'duration');+ expect(durationOption).toBeTruthy();+ expect(durationOption?.displayText).toBe('3d (3 days from now)');++ // Should be 3 days from base date+ const expectedDate = addDays(baseDate, 3);+ expect(durationOption?.date.toDateString()).toBe(+ expectedDate.toDateString()+ );++ dispose();+ });+ });++ it('should parse natural dates', () => {+ createRoot((dispose) => {+ const [query] = createSignal('feb 17');+ const baseDate = new Date('2024-06-15T10:00:00');+ const options = useDateSearch({ query, baseDate });++ const result = options();+ const naturalOption = result.find((opt) => opt.type === 'natural');+ expect(naturalOption).toBeTruthy();+ expect(naturalOption?.displayText).toBe('feb 17');+ expect(naturalOption?.date.getMonth()).toBe(1); // February+ expect(naturalOption?.date.getDate()).toBe(17);++ dispose();+ });+ });++ it('should search presets', () => {+ createRoot((dispose) => {+ const [query] = createSignal('tomorrow');+ const options = useDateSearch({ query });++ const result = options();+ const tomorrowOption = result.find((opt) =>+ opt.displayText.toLowerCase().includes('tomorrow')+ );+ expect(tomorrowOption).toBeTruthy();++ dispose();+ });+ });++ it('should handle relative date queries', () => {+ createRoot((dispose) => {+ const [query] = createSignal('week');+ const baseDate = new Date('2024-06-15T10:00:00');+ const options = useDateSearch({ query, baseDate });++ const result = options();++ // Should find preset options that match "week"+ const weekOptions = result.filter((opt) =>+ opt.displayText.toLowerCase().includes('week')+ );+ expect(weekOptions.length).toBeGreaterThan(0);+ expect(weekOptions[0].type).toBe('preset');++ dispose();+ });+ });++ it('should handle different query types', () => {+ const baseDate = new Date('2024-06-15T10:00:00');++ // Test duration query+ createRoot((dispose) => {+ const [query] = createSignal('3d');+ const options = useDateSearch({ query, baseDate });+ const result = options();+ const durationOption = result.find((opt) => opt.type === 'duration');+ expect(durationOption?.displayText).toBe('3d (3 days from now)');+ dispose();+ });++ // Test week duration+ createRoot((dispose) => {+ const [query] = createSignal('1w');+ const options = useDateSearch({ query, baseDate });+ const result = options();+ const weekOption = result.find((opt) => opt.type === 'duration');+ expect(weekOption?.displayText).toBe('1w (1 week from now)');+ dispose();+ });++ // Test natural date+ createRoot((dispose) => {+ const [query] = createSignal('march 15');+ const options = useDateSearch({ query, baseDate });+ const result = options();+ const naturalOption = result.find((opt) => opt.type === 'natural');+ expect(naturalOption?.displayText).toBe('march 15');+ expect(naturalOption?.date.getMonth()).toBe(2); // March+ expect(naturalOption?.date.getDate()).toBe(15);+ dispose();+ });+ });++ it('should score and sort results appropriately', () => {+ createRoot((dispose) => {+ const [query] = createSignal('tom');+ const options = useDateSearch({ query });++ const result = options();+ // Results starting with 'tom' should come first+ const topResults = result.slice(0, 3);+ topResults.forEach((opt) => {+ expect(opt.displayText.toLowerCase().includes('tom')).toBe(true);+ });++ dispose();+ });+ });++ it('should limit results to 15 options', () => {+ createRoot((dispose) => {+ const [query] = createSignal('e'); // Common letter that matches many presets+ const options = useDateSearch({ query });++ const result = options();+ expect(result.length).toBeLessThanOrEqual(15);++ dispose();+ });+ });++ it('should handle multiple matching types', () => {+ createRoot((dispose) => {+ const [query] = createSignal('1d');+ const baseDate = new Date('2024-06-15T10:00:00');+ const options = useDateSearch({ query, baseDate });++ const result = options();++ // Should have duration option+ const durationOption = result.find((opt) => opt.type === 'duration');+ expect(durationOption).toBeTruthy();+ expect(durationOption?.displayText).toBe('1d (1 day from now)');++ // Might also have preset options that match+ const presetOptions = result.filter((opt) => opt.type === 'preset');+ expect(presetOptions.length).toBeGreaterThanOrEqual(0);++ dispose();+ });+ });++ it('should include secondary text with formatted dates', () => {+ createRoot((dispose) => {+ const [query] = createSignal('3d');+ const baseDate = new Date('2024-06-15T10:00:00');+ const options = useDateSearch({ query, baseDate });++ const result = options();+ const durationOption = result.find((opt) => opt.type === 'duration');++ expect(durationOption?.secondaryText).toBeTruthy();+ expect(durationOption?.secondaryText).toContain('Jun 18'); // 3 days from June 15++ dispose();+ });+ });++ it('should handle edge cases gracefully', () => {+ createRoot((dispose) => {+ const [query] = createSignal('!@#$%^&*()');+ const options = useDateSearch({ query });++ const result = options();+ // Should return empty or only exact text matches+ expect(result.length).toBeGreaterThanOrEqual(0);++ dispose();+ });+ });+});diff --git a/js/app/packages/core/util/dateSearch/useDateSearch.ts b/js/app/packages/core/util/dateSearch/useDateSearch.tsnew file mode 100644index 0000000000..6f153f4a8e--- /dev/null+++ b/js/app/packages/core/util/dateSearch/useDateSearch.ts@@ -0,0 +1,252 @@+import { createMemo, type Accessor } from 'solid-js';+import { format, parse, isValid, setYear, getYear, addYears } from 'date-fns';+import {+ formatDuration,+ parseDateFromDuration,+ parseDurationString,+} from './dateParser';+import { searchPresets } from './presets';++// Max number of presets to include+const PRESET_COUNT = 5;++const DEFAULT_MAX_ITEMS = 10;++export interface DateOption {+ id: string;+ displayText: string;+ secondaryText?: string;+ date: Date;+ type: 'duration' | 'preset' | 'natural' | 'absolute';+ score?: number;+}++const possibleDateFormats = [+ 'MMM d', // "Jan 15"+ 'MMMM d', // "January 15"+ 'MMM d yyyy', // "Jan 15 2024"+ 'MMMM d yyyy', // "January 15 2024"+ 'M/d', // "1/15"+ 'M/d/yyyy', // "1/15/2024"+ 'MM/dd', // "01/15"+ 'MM/dd/yyyy', // "01/15/2024"+ 'd MMM', // "15 Jan"+ 'd MMMM', // "15 January"+ 'd MMM yyyy', // "15 Jan 2024"+ 'd MMMM yyyy', // "15 January 2024"+ 'yyyy-MM-dd', // "2024-01-15"+ 'dd-MM-yyyy', // "15-01-2024"+];++/**+ * Parse natural date strings like "feb 17", "march 3", "jan 1 2025", etc.+ */+function parseNaturalDate(+ input: string,+ baseDate: Date = new Date()+): Date | null {+ const trimmed = input.trim();+ if (!trimmed) return null;++ for (const formatStr of possibleDateFormats) {+ try {+ const parsed = parse(trimmed, formatStr, baseDate);+ if (isValid(parsed)) {+ const hasYear = /\d{4}/.test(trimmed);+ if (!hasYear) {+ const currentYear = getYear(baseDate);+ let adjustedDate = setYear(parsed, currentYear);++ const sixMonthsAgo = new Date(baseDate);+ sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);++ const adjustedDateOnly = new Date(adjustedDate);+ adjustedDateOnly.setHours(0, 0, 0, 0);+ const sixMonthsAgoDateOnly = new Date(sixMonthsAgo);+ sixMonthsAgoDateOnly.setHours(0, 0, 0, 0);++ if (adjustedDateOnly < sixMonthsAgoDateOnly) {+ adjustedDate = addYears(adjustedDate, 1);+ }++ return adjustedDate;+ }++ return parsed;+ }+ } catch {}+ }++ const lowerInput = trimmed.toLowerCase();+ const now = new Date(baseDate);++ const daysOfWeek = [+ 'sunday',+ 'monday',+ 'tuesday',+ 'wednesday',+ 'thursday',+ 'friday',+ 'saturday',+ ];++ const dayIndex = daysOfWeek.findIndex(+ (day) => lowerInput === day || lowerInput === day.slice(0, 3)+ );++ if (dayIndex !== -1) {+ const currentDay = now.getDay();+ let daysToAdd = dayIndex - currentDay;++ if (daysToAdd <= 0) {+ daysToAdd += 7;+ }++ const result = new Date(now);+ result.setDate(result.getDate() + daysToAdd);+ return result;+ }++ return null;+}++/**+ * Score how well an option matches the query+ */+function scoreMatch(option: DateOption, query: string): number {+ const lowerQuery = query.toLowerCase();+ const lowerDisplay = option.displayText.toLowerCase();++ if (lowerDisplay === lowerQuery) return 100;+ if (lowerDisplay.startsWith(lowerQuery)) return 90;+ if (lowerDisplay.includes(lowerQuery)) return 70;+ if (option.secondaryText) {+ const lowerSecondary = option.secondaryText.toLowerCase();+ if (lowerSecondary.includes(lowerQuery)) return 50;+ }++ return 0;+}++/**+ * Format a date for display with relative context+ */+function formatDateWithContext(+ date: Date,+ baseDate: Date = new Date()+): string {+ const now = new Date(baseDate);+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());+ const dateOnly = new Date(+ date.getFullYear(),+ date.getMonth(),+ date.getDate()+ );++ const diffDays = Math.floor(+ (dateOnly.getTime() - today.getTime()) / (1000 * 60 * 60 * 24)+ );++ if (diffDays === 0) {+ return `Today, ${format(date, 'h:mm a')}`;+ } else if (diffDays === 1) {+ return `Tomorrow, ${format(date, 'h:mm a')}`;+ } else if (diffDays === -1) {+ return `Yesterday, ${format(date, 'h:mm a')}`;+ } else if (diffDays > 0 && diffDays <= 7) {+ return format(date, "EEEE, MMM d 'at' h:mm a");+ } else {+ const sameYear = date.getFullYear() === now.getFullYear();+ return sameYear+ ? format(date, "MMM d 'at' h:mm a")+ : format(date, "MMM d, yyyy 'at' h:mm a");+ }+}++export function useDateSearch(params: {+ query: Accessor<string>;+ baseDate?: Date;+ maxItems?: number;+}) {+ const baseDate = params.baseDate || new Date();++ const dateOptions = createMemo(() => {+ const query = params.query().trim();+ const options: DateOption[] = [];++ if (!query) {+ const presets = searchPresets('');+ return presets.slice(0, PRESET_COUNT).map(+ (preset): DateOption => ({+ id: preset.id,+ displayText: preset.label,+ secondaryText: format(preset.getDate(baseDate), 'MMM d, yyyy'),+ date: preset.getDate(baseDate),+ type: 'preset',+ score: 0,+ })+ );+ }++ // 1. Try parsing as duration DSL (3d, 1w, etc.)+ const parsedDuration = parseDurationString(query);+ if (parsedDuration) {+ const durationDate = parseDateFromDuration(query, baseDate);+ if (durationDate) {+ options.push({+ id: `duration-${query}`,+ displayText: `${query} (${formatDuration(parsedDuration)} from now)`,+ secondaryText: formatDateWithContext(durationDate, baseDate),+ date: durationDate,+ type: 'duration',+ score: 100,+ });+ }+ }++ // 2. Try parsing as natural date (feb 17, march 3, etc.)+ const naturalDate = parseNaturalDate(query, baseDate);+ if (naturalDate) {+ options.push({+ id: `natural-${query}`,+ displayText: query,+ secondaryText: formatDateWithContext(naturalDate, baseDate),+ date: naturalDate,+ type: 'natural',+ score: 95,+ });+ }++ const matchingPresets = searchPresets(query);+ matchingPresets.forEach((preset) => {+ const date = preset.getDate(baseDate);+ const option: DateOption = {+ id: `preset-${preset.id}`,+ displayText: preset.label,+ secondaryText: formatDateWithContext(date, baseDate),+ date,+ type: 'preset',+ score: 0,+ };++ option.score = scoreMatch(option, query);++ if (option.score > 0) {+ options.push(option);+ }+ });++ options.sort((a, b) => {+ const scoreDiff = (b.score || 0) - (a.score || 0);+ if (scoreDiff !== 0) return scoreDiff;+ return a.date.getTime() - b.date.getTime();+ });++ return options.slice(0, params.maxItems ?? DEFAULT_MAX_ITEMS);+ });++ return dateOptions;+}++// Export helper functions for testing+export { parseNaturalDate, formatDateWithContext };diff --git a/js/app/packages/core/util/useIsKeyPressActive.ts b/js/app/packages/core/util/useIsKeyPressActive.tsindex 31ce67bf26..90fca704e2 100644--- a/js/app/packages/core/util/useIsKeyPressActive.ts+++ b/js/app/packages/core/util/useIsKeyPressActive.ts@@ -16,6 +16,7 @@ const onKeyup = () => {setKeypressActive(false);};let init = false;+export const useIsKeyPressActive = () => {if (!init) {init = true;diff --git a/js/app/packages/core/util/useKeyPressed.ts b/js/app/packages/core/util/useKeyPressed.tsnew file mode 100644index 0000000000..192bd34600--- /dev/null+++ b/js/app/packages/core/util/useKeyPressed.ts@@ -0,0 +1,66 @@+import { debounce } from '@solid-primitives/scheduled';+import { createSignal, onCleanup, onMount } from 'solid-js';++let listeners = new Set<(e?: KeyboardEvent) => void>();+let isListening = false;++const startGlobalListener = () => {+ if (isListening) return;+ isListening = true;+ const onKeydown = (e: KeyboardEvent) => {+ listeners.forEach((listener) => listener(e));+ };+ document.addEventListener('keydown', onKeydown, { capture: true });+ return () => {+ document.removeEventListener('keydown', onKeydown, { capture: true });+ isListening = false;+ };+};++/**+ * Hook to generate a readonly signal that will be true for durationMs after a+ * key is pressed. If no key or key array arg is passed, then will be true for+ * all keys pressed. Currently the utility of this is for temporarily suspending+ * mouse-based hover selection when scrolling a list of items with keyboard or+ * list filtering.+ * @param durationMs+ * @param key+ * @returns A readonly boolean signal+ */+export const useKeyPressed = (+ durationMs: number,+ key?: KeyboardEvent['key'] | KeyboardEvent['key'][]+) => {+ const [state, setState] = createSignal(false);+ const debouncedSetState = debounce(setState, durationMs);++ const handler = (e: KeyboardEvent) => {+ if (key) {+ if (Array.isArray(key)) {+ if (!key.includes(e.key)) return;+ } else {+ if (key !== e.key) return;+ }+ }+ debouncedSetState.clear();+ setState(true);+ debouncedSetState(false);+ };++ let cleanup: (() => void) | undefined;++ onMount(() => {+ listeners.add(handler);+ if (listeners.size === 1) {+ cleanup = startGlobalListener();+ }+ onCleanup(() => {+ listeners.delete(handler);+ if (listeners.size === 0) {+ cleanup?.();+ cleanup = undefined;+ }+ });+ });+ return state;+};