Allow searching events
Also upgrade Fresh
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
import { useSignal } from '@preact/signals';
|
||||
import { useEffect } from 'preact/hooks';
|
||||
|
||||
import { Calendar, CalendarEvent } from '/lib/types.ts';
|
||||
import { baseUrl, capitalizeWord } from '/lib/utils.ts';
|
||||
@@ -15,6 +14,7 @@ import CalendarViewWeek from './CalendarViewWeek.tsx';
|
||||
import CalendarViewMonth from './CalendarViewMonth.tsx';
|
||||
import AddEventModal, { NewCalendarEvent } from './AddEventModal.tsx';
|
||||
import ViewEventModal from './ViewEventModal.tsx';
|
||||
import SearchEvents from './SearchEvents.tsx';
|
||||
|
||||
interface MainCalendarProps {
|
||||
initialCalendars: Pick<Calendar, 'id' | 'name' | 'color' | 'is_visible'>[];
|
||||
@@ -28,12 +28,10 @@ export default function MainCalendar({ initialCalendars, initialCalendarEvents,
|
||||
const isDeleting = useSignal<boolean>(false);
|
||||
const isExporting = useSignal<boolean>(false);
|
||||
const isImporting = useSignal<boolean>(false);
|
||||
const isSearching = useSignal<boolean>(false);
|
||||
const calendars = useSignal<Pick<Calendar, 'id' | 'name' | 'color' | 'is_visible'>[]>(initialCalendars);
|
||||
const isViewOptionsDropdownOpen = useSignal<boolean>(false);
|
||||
const isImportExportOptionsDropdownOpen = useSignal<boolean>(false);
|
||||
const calendarEvents = useSignal<CalendarEvent[]>(initialCalendarEvents);
|
||||
const searchTimeout = useSignal<ReturnType<typeof setTimeout>>(0);
|
||||
const openEventModal = useSignal<
|
||||
{ isOpen: boolean; calendar?: typeof initialCalendars[number]; calendarEvent?: CalendarEvent }
|
||||
>({ isOpen: false });
|
||||
@@ -344,44 +342,6 @@ export default function MainCalendar({ initialCalendars, initialCalendarEvents,
|
||||
isExporting.value = false;
|
||||
}
|
||||
|
||||
function searchEvents(searchTerms: string) {
|
||||
if (searchTimeout.value) {
|
||||
clearTimeout(searchTimeout.value);
|
||||
}
|
||||
|
||||
searchTimeout.value = setTimeout(async () => {
|
||||
isSearching.value = true;
|
||||
|
||||
// TODO: Remove this
|
||||
await new Promise((resolve) => setTimeout(() => resolve(true), 1000));
|
||||
|
||||
// try {
|
||||
// const requestBody: RequestBody = { search: searchTerms };
|
||||
// const response = await fetch(`/api/calendar/search-events`, {
|
||||
// method: 'POST',
|
||||
// body: JSON.stringify(requestBody),
|
||||
// });
|
||||
// const result = await response.json() as ResponseBody;
|
||||
|
||||
// if (!result.success) {
|
||||
// throw new Error('Failed to search events!');
|
||||
// }
|
||||
// } catch (error) {
|
||||
// console.error(error);
|
||||
// }
|
||||
|
||||
isSearching.value = false;
|
||||
}, 500);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (searchTimeout.value) {
|
||||
clearTimeout(searchTimeout.value);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const visibleCalendars = calendars.value.filter((calendar) => calendar.is_visible);
|
||||
|
||||
return (
|
||||
@@ -390,14 +350,7 @@ export default function MainCalendar({ initialCalendars, initialCalendarEvents,
|
||||
<section class='relative inline-block text-left mr-2'>
|
||||
<section class='flex flex-row items-center justify-start'>
|
||||
<a href='/calendars' class='mr-4 whitespace-nowrap'>Manage calendars</a>
|
||||
<input
|
||||
class='input-field w-72 mr-2'
|
||||
type='search'
|
||||
name='search'
|
||||
placeholder='Search events...'
|
||||
onInput={(event) => searchEvents(event.currentTarget.value)}
|
||||
/>
|
||||
{isSearching.value ? <img src='/images/loading.svg' class='white mr-2' width={18} height={18} /> : null}
|
||||
<SearchEvents calendars={calendars.value} onClickOpenEvent={onClickOpenEvent} />
|
||||
</section>
|
||||
</section>
|
||||
|
||||
|
||||
149
components/calendar/SearchEvents.tsx
Normal file
149
components/calendar/SearchEvents.tsx
Normal file
@@ -0,0 +1,149 @@
|
||||
import { useSignal } from '@preact/signals';
|
||||
import { useEffect } from 'preact/hooks';
|
||||
|
||||
import { Calendar, CalendarEvent } from '/lib/types.ts';
|
||||
import { RequestBody, ResponseBody } from '/routes/api/calendar/search-events.tsx';
|
||||
interface SearchEventsProps {
|
||||
calendars: Pick<Calendar, 'id' | 'name' | 'color' | 'is_visible'>[];
|
||||
onClickOpenEvent: (calendarEvent: CalendarEvent) => void;
|
||||
}
|
||||
|
||||
export default function SearchEvents({ calendars, onClickOpenEvent }: SearchEventsProps) {
|
||||
const isSearching = useSignal<boolean>(false);
|
||||
const areResultsVisible = useSignal<boolean>(false);
|
||||
const calendarEvents = useSignal<CalendarEvent[]>([]);
|
||||
const searchTimeout = useSignal<ReturnType<typeof setTimeout>>(0);
|
||||
const closeTimeout = useSignal<ReturnType<typeof setTimeout>>(0);
|
||||
|
||||
const dateFormat = new Intl.DateTimeFormat('en-GB', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit',
|
||||
});
|
||||
|
||||
const calendarIds = calendars.map((calendar) => calendar.id);
|
||||
|
||||
function searchEvents(searchTerm: string) {
|
||||
if (searchTimeout.value) {
|
||||
clearTimeout(searchTimeout.value);
|
||||
}
|
||||
|
||||
if (searchTerm.trim().length < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
areResultsVisible.value = false;
|
||||
|
||||
searchTimeout.value = setTimeout(async () => {
|
||||
isSearching.value = true;
|
||||
|
||||
try {
|
||||
const requestBody: RequestBody = { calendarIds, searchTerm };
|
||||
const response = await fetch(`/api/calendar/search-events`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
const result = await response.json() as ResponseBody;
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error('Failed to search events!');
|
||||
}
|
||||
|
||||
calendarEvents.value = result.matchingCalendarEvents;
|
||||
|
||||
if (calendarEvents.value.length > 0) {
|
||||
areResultsVisible.value = true;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
isSearching.value = false;
|
||||
}, 500);
|
||||
}
|
||||
|
||||
function onFocus() {
|
||||
if (calendarEvents.value.length > 0) {
|
||||
areResultsVisible.value = true;
|
||||
}
|
||||
}
|
||||
|
||||
function onBlur() {
|
||||
if (closeTimeout.value) {
|
||||
clearTimeout(closeTimeout.value);
|
||||
}
|
||||
|
||||
closeTimeout.value = setTimeout(() => {
|
||||
areResultsVisible.value = false;
|
||||
}, 300);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (searchTimeout.value) {
|
||||
clearTimeout(searchTimeout.value);
|
||||
}
|
||||
|
||||
if (closeTimeout.value) {
|
||||
clearTimeout(closeTimeout.value);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<input
|
||||
class='input-field w-72 mr-2'
|
||||
type='search'
|
||||
name='search'
|
||||
placeholder='Search events...'
|
||||
onInput={(event) => searchEvents(event.currentTarget.value)}
|
||||
onFocus={() => onFocus()}
|
||||
onBlur={() => onBlur()}
|
||||
/>
|
||||
{isSearching.value ? <img src='/images/loading.svg' class='white mr-2' width={18} height={18} /> : null}
|
||||
{areResultsVisible.value
|
||||
? (
|
||||
<section class='relative inline-block text-left ml-2 text-xs'>
|
||||
<section
|
||||
class={`absolute right-0 z-10 mt-2 w-56 origin-top-right rounded-md bg-slate-700 shadow-lg ring-1 ring-black ring-opacity-15 focus:outline-none`}
|
||||
role='menu'
|
||||
aria-orientation='vertical'
|
||||
aria-labelledby='view-button'
|
||||
tabindex={-1}
|
||||
>
|
||||
<section class='py-1'>
|
||||
<ol class='mt-2'>
|
||||
{calendarEvents.value.map((calendarEvent) => (
|
||||
<li class='mb-1'>
|
||||
<a
|
||||
href='javascript:void(0);'
|
||||
class={`block px-2 py-2 hover:no-underline hover:opacity-60 ${
|
||||
calendars.find((calendar) => calendar.id === calendarEvent.calendar_id)
|
||||
?.color || 'bg-gray-700'
|
||||
}`}
|
||||
onClick={() => onClickOpenEvent(calendarEvent)}
|
||||
>
|
||||
<time
|
||||
datetime={new Date(calendarEvent.start_date).toISOString()}
|
||||
class='mr-2 flex-none text-slate-100 block'
|
||||
>
|
||||
{dateFormat.format(new Date(calendarEvent.start_date))}
|
||||
</time>
|
||||
<p class='flex-auto truncate font-medium text-white'>
|
||||
{calendarEvent.title}
|
||||
</p>
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</section>
|
||||
</section>
|
||||
</section>
|
||||
)
|
||||
: null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
27
deno.json
27
deno.json
@@ -10,30 +10,15 @@
|
||||
"update": "deno run -A -r https://fresh.deno.dev/update .",
|
||||
"test": "deno test -A --check"
|
||||
},
|
||||
"fmt": {
|
||||
"useTabs": false,
|
||||
"lineWidth": 120,
|
||||
"indentWidth": 2,
|
||||
"singleQuote": true,
|
||||
"proseWrap": "preserve"
|
||||
},
|
||||
"fmt": { "useTabs": false, "lineWidth": 120, "indentWidth": 2, "singleQuote": true, "proseWrap": "preserve" },
|
||||
"lint": {
|
||||
"rules": {
|
||||
"tags": [
|
||||
"fresh",
|
||||
"recommended"
|
||||
],
|
||||
"tags": ["fresh", "recommended"],
|
||||
"exclude": ["no-explicit-any", "no-empty-interface", "ban-types", "no-window"]
|
||||
}
|
||||
},
|
||||
"exclude": [
|
||||
"./_fresh/*",
|
||||
"./node_modules/*"
|
||||
],
|
||||
"importMap": "./import_map.json",
|
||||
"compilerOptions": {
|
||||
"jsx": "react-jsx",
|
||||
"jsxImportSource": "preact"
|
||||
},
|
||||
"nodeModulesDir": true
|
||||
"exclude": ["./_fresh/*", "./node_modules/*", "**/_fresh/*"],
|
||||
"compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "preact" },
|
||||
"nodeModulesDir": true,
|
||||
"importMap": "./import_map.json"
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import * as $api_calendar_add_event from './routes/api/calendar/add-event.tsx';
|
||||
import * as $api_calendar_add from './routes/api/calendar/add.tsx';
|
||||
import * as $api_calendar_delete_event from './routes/api/calendar/delete-event.tsx';
|
||||
import * as $api_calendar_delete from './routes/api/calendar/delete.tsx';
|
||||
import * as $api_calendar_search_events from './routes/api/calendar/search-events.tsx';
|
||||
import * as $api_calendar_update from './routes/api/calendar/update.tsx';
|
||||
import * as $api_contacts_add from './routes/api/contacts/add.tsx';
|
||||
import * as $api_contacts_delete from './routes/api/contacts/delete.tsx';
|
||||
@@ -69,6 +70,7 @@ const manifest = {
|
||||
'./routes/api/calendar/add.tsx': $api_calendar_add,
|
||||
'./routes/api/calendar/delete-event.tsx': $api_calendar_delete_event,
|
||||
'./routes/api/calendar/delete.tsx': $api_calendar_delete,
|
||||
'./routes/api/calendar/search-events.tsx': $api_calendar_search_events,
|
||||
'./routes/api/calendar/update.tsx': $api_calendar_update,
|
||||
'./routes/api/contacts/add.tsx': $api_contacts_add,
|
||||
'./routes/api/contacts/delete.tsx': $api_contacts_delete,
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
"./": "./",
|
||||
"xml/": "https://deno.land/x/xml@2.1.3/",
|
||||
|
||||
"fresh/": "https://deno.land/x/fresh@1.6.5/",
|
||||
"$fresh/": "https://deno.land/x/fresh@1.6.5/",
|
||||
"preact": "https://esm.sh/preact@10.19.2",
|
||||
"preact/": "https://esm.sh/preact@10.19.2/",
|
||||
"@preact/signals": "https://esm.sh/*@preact/signals@1.2.1",
|
||||
"@preact/signals-core": "https://esm.sh/*@preact/signals-core@1.5.0",
|
||||
"fresh/": "https://deno.land/x/fresh@1.6.8/",
|
||||
"$fresh/": "https://deno.land/x/fresh@1.6.8/",
|
||||
"preact": "https://esm.sh/preact@10.19.6",
|
||||
"preact/": "https://esm.sh/preact@10.19.6/",
|
||||
"@preact/signals": "https://esm.sh/*@preact/signals@1.2.2",
|
||||
"@preact/signals-core": "https://esm.sh/*@preact/signals-core@1.5.1",
|
||||
"tailwindcss": "npm:tailwindcss@3.4.1",
|
||||
"tailwindcss/": "npm:/tailwindcss@3.4.1/",
|
||||
"tailwindcss/plugin": "npm:/tailwindcss@3.4.1/plugin.js",
|
||||
|
||||
@@ -288,3 +288,20 @@ export async function deleteCalendarEvent(id: string, calendarId: string, userId
|
||||
|
||||
await updateCalendarRevision(calendar);
|
||||
}
|
||||
|
||||
export async function searchCalendarEvents(
|
||||
searchTerm: string,
|
||||
userId: string,
|
||||
calendarIds: string[],
|
||||
): Promise<CalendarEvent[]> {
|
||||
const calendarEvents = await db.query<CalendarEvent>(
|
||||
sql`SELECT * FROM "bewcloud_calendar_events" WHERE "user_id" = $1 AND "calendar_id" = ANY($2) AND ("title" ILIKE $3 OR "extra"::text ILIKE $3) ORDER BY "start_date" ASC`,
|
||||
[
|
||||
userId,
|
||||
calendarIds,
|
||||
`%${searchTerm.split(' ').join('%')}%`,
|
||||
],
|
||||
);
|
||||
|
||||
return calendarEvents;
|
||||
}
|
||||
|
||||
@@ -28,13 +28,13 @@ export async function getContactsCount(userId: string) {
|
||||
return Number(results[0]?.count || 0);
|
||||
}
|
||||
|
||||
export async function searchContacts(search: string, userId: string, pageIndex: number) {
|
||||
export async function searchContacts(searchTerm: string, userId: string, pageIndex: number) {
|
||||
const contacts = await db.query<Pick<Contact, 'id' | 'first_name' | 'last_name'>>(
|
||||
sql`SELECT "id", "first_name", "last_name" FROM "bewcloud_contacts" WHERE "user_id" = $1 AND ("first_name" ILIKE $3 OR "last_name" ILIKE $3 OR "extra"::text ILIKE $3) ORDER BY "first_name" ASC, "last_name" ASC LIMIT ${CONTACTS_PER_PAGE_COUNT} OFFSET $2`,
|
||||
[
|
||||
userId,
|
||||
pageIndex * CONTACTS_PER_PAGE_COUNT,
|
||||
`%${search}%`,
|
||||
`%${searchTerm.split(' ').join('%')}%`,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
42
routes/api/calendar/search-events.tsx
Normal file
42
routes/api/calendar/search-events.tsx
Normal file
@@ -0,0 +1,42 @@
|
||||
import { Handlers } from 'fresh/server.ts';
|
||||
|
||||
import { CalendarEvent, FreshContextState } from '/lib/types.ts';
|
||||
import { searchCalendarEvents } from '/lib/data/calendar.ts';
|
||||
|
||||
interface Data {}
|
||||
|
||||
export interface RequestBody {
|
||||
calendarIds: string[];
|
||||
searchTerm: string;
|
||||
}
|
||||
|
||||
export interface ResponseBody {
|
||||
success: boolean;
|
||||
matchingCalendarEvents: CalendarEvent[];
|
||||
}
|
||||
|
||||
export const handler: Handlers<Data, FreshContextState> = {
|
||||
async POST(request, context) {
|
||||
if (!context.state.user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
const requestBody = await request.clone().json() as RequestBody;
|
||||
|
||||
if (
|
||||
!requestBody.calendarIds || !requestBody.searchTerm
|
||||
) {
|
||||
return new Response('Bad Request', { status: 400 });
|
||||
}
|
||||
|
||||
const matchingCalendarEvents = await searchCalendarEvents(
|
||||
requestBody.searchTerm,
|
||||
context.state.user.id,
|
||||
requestBody.calendarIds,
|
||||
);
|
||||
|
||||
const responseBody: ResponseBody = { success: true, matchingCalendarEvents };
|
||||
|
||||
return new Response(JSON.stringify(responseBody));
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user