2 Commits

Author SHA1 Message Date
f6393c9a59 suspending 2025-09-21 15:54:24 +01:00
561064a194 using resources to always have a valid access token 2025-09-21 15:51:33 +01:00
4 changed files with 230 additions and 229 deletions

View File

@ -1,5 +1,5 @@
import { Component, createSignal } from "solid-js"; import { Component, createResource, createSignal, Suspense } from "solid-js";
import { base } from "../../network"; import { base, getAccessToken } from "../../network";
import { A } from "@solidjs/router"; import { A } from "@solidjs/router";
import { Dialog } from "@kobalte/core"; import { Dialog } from "@kobalte/core";
@ -11,19 +11,15 @@ type ImageComponentProps = {
export const ImageComponent: Component<ImageComponentProps> = (props) => { export const ImageComponent: Component<ImageComponentProps> = (props) => {
const [isOpen, setIsOpen] = createSignal(false); const [isOpen, setIsOpen] = createSignal(false);
// TODO: make sure this is up to date. Put it behind a resource. const [accessToken] = createResource(getAccessToken);
const accessToken = localStorage.getItem("access");
if (accessToken == null) {
return <>Ermm... Access token is not set :(</>
}
return ( return (
<> <Suspense fallback={<></>}>
<div class="relative w-full flex justify-center h-[300px]"> <div class="relative w-full flex justify-center h-[300px]">
<A href={`/image/${props.ID}`} class="flex w-full"> <A href={`/image/${props.ID}`} class="flex w-full">
<img <img
class="flex w-full object-cover rounded-xl" class="flex w-full object-cover rounded-xl"
src={`${base}/images/${props.ID}?token=${accessToken}`} src={`${base}/images/${props.ID}?token=${accessToken()}`}
/> />
</A> </A>
<button <button
@ -58,7 +54,7 @@ export const ImageComponent: Component<ImageComponentProps> = (props) => {
</Dialog.Content> </Dialog.Content>
</Dialog.Portal> </Dialog.Portal>
</Dialog.Root> </Dialog.Root>
</> </Suspense>
); );
}; };
@ -68,11 +64,7 @@ export const ImageComponent: Component<ImageComponentProps> = (props) => {
export const ImageComponentFullHeight: Component<ImageComponentProps> = (props) => { export const ImageComponentFullHeight: Component<ImageComponentProps> = (props) => {
const [isOpen, setIsOpen] = createSignal(false); const [isOpen, setIsOpen] = createSignal(false);
// TODO: make sure this is up to date. Put it behind a resource. const [accessToken] = createResource(getAccessToken);
const accessToken = localStorage.getItem("access");
if (accessToken == null) {
return <>Ermm... Access token is not set :(</>
}
return ( return (
<> <>
@ -80,7 +72,7 @@ export const ImageComponentFullHeight: Component<ImageComponentProps> = (props)
<A href={`/image/${props.ID}`} class="flex w-full"> <A href={`/image/${props.ID}`} class="flex w-full">
<img <img
class="flex w-full object-cover rounded-xl" class="flex w-full object-cover rounded-xl"
src={`${base}/images/${props.ID}?token=${accessToken}`} src={`${base}/images/${props.ID}?token=${accessToken()}`}
/> />
</A> </A>
<button <button

View File

@ -2,154 +2,159 @@ import { InferOutput, safeParse } from "valibot";
import { useSearchImageContext } from "./SearchImageContext"; import { useSearchImageContext } from "./SearchImageContext";
import { createStore } from "solid-js/store"; import { createStore } from "solid-js/store";
import { import {
Component, Component,
createContext, createContext,
createEffect, createEffect,
onCleanup, createResource,
ParentProps, onCleanup,
useContext, ParentProps,
useContext,
} from "solid-js"; } from "solid-js";
import { base } from "@network/index"; import { base, getAccessToken } from "@network/index";
import { import {
notificationValidator, notificationValidator,
processingImagesValidator, processingImagesValidator,
processingListValidator, processingListValidator,
} from "@network/notifications"; } from "@network/notifications";
type NotificationState = { type NotificationState = {
ProcessingImages: Record< ProcessingImages: Record<
string, string,
InferOutput<typeof processingImagesValidator> | undefined InferOutput<typeof processingImagesValidator> | undefined
>; >;
ProcessingLists: Record< ProcessingLists: Record<
string, string,
InferOutput<typeof processingListValidator> | undefined InferOutput<typeof processingListValidator> | undefined
>; >;
}; };
export const Notifications = (onCompleteImage: () => void) => { export const Notifications = (onCompleteImage: () => void) => {
const [state, setState] = createStore<NotificationState>({ const [state, setState] = createStore<NotificationState>({
ProcessingImages: {}, ProcessingImages: {},
ProcessingLists: {}, ProcessingLists: {},
}); });
const { processingImages } = useSearchImageContext(); const { processingImages } = useSearchImageContext();
const access = localStorage.getItem("access"); const [accessToken] = createResource(getAccessToken);
if (access == null) {
throw new Error("Access token not defined");
}
const dataEventListener = (e: MessageEvent<unknown>) => { const dataEventListener = (e: MessageEvent<unknown>) => {
if (typeof e.data !== "string") { if (typeof e.data !== "string") {
console.error("Error type is not string"); console.error("Error type is not string");
return; return;
} }
let jsonData: object = {}; let jsonData: object = {};
try { try {
jsonData = JSON.parse(e.data); jsonData = JSON.parse(e.data);
} catch (e) { } catch (e) {
console.error(e); console.error(e);
return; return;
} }
const notification = safeParse(notificationValidator, jsonData); const notification = safeParse(notificationValidator, jsonData);
if (!notification.success) { if (!notification.success) {
console.error("Processing image could not be parsed.", e.data); console.error("Processing image could not be parsed.", e.data);
return; return;
} }
console.log("SSE: ", notification); console.log("SSE: ", notification);
if (notification.output.Type === "image") { if (notification.output.Type === "image") {
const { ImageID, Status } = notification.output; const { ImageID, Status } = notification.output;
if (Status === "complete") { if (Status === "complete") {
setState("ProcessingImages", ImageID, undefined); setState("ProcessingImages", ImageID, undefined);
onCompleteImage(); onCompleteImage();
} else { } else {
setState("ProcessingImages", ImageID, notification.output); setState("ProcessingImages", ImageID, notification.output);
} }
} else if (notification.output.Type === "list") { } else if (notification.output.Type === "list") {
const { ListID, Status } = notification.output; const { ListID, Status } = notification.output;
if (Status === "complete") { if (Status === "complete") {
setState("ProcessingLists", ListID, undefined); setState("ProcessingLists", ListID, undefined);
onCompleteImage(); onCompleteImage();
} else { } else {
setState("ProcessingLists", ListID, notification.output); setState("ProcessingLists", ListID, notification.output);
} }
} }
}; };
const upsertImageProcessing = ( const upsertImageProcessing = (
images: NotificationState["ProcessingImages"], images: NotificationState["ProcessingImages"],
) => { ) => {
setState("ProcessingImages", (currentImages) => ({ setState("ProcessingImages", (currentImages) => ({
...currentImages, ...currentImages,
...images, ...images,
})); }));
}; };
createEffect(() => { createEffect(() => {
const images = processingImages(); const images = processingImages();
if (images == null) { if (images == null) {
return; return;
} }
upsertImageProcessing( upsertImageProcessing(
Object.fromEntries( Object.fromEntries(
images.map((i) => [ images.map((i) => [
i.ImageID, i.ImageID,
{ {
Type: "image", Type: "image",
ImageID: i.ImageID, ImageID: i.ImageID,
ImageName: i.Image.ImageName, ImageName: i.Image.ImageName,
Status: i.Status, Status: i.Status,
}, },
]), ]),
), ),
); );
}); });
const events = new EventSource(`${base}/notifications?token=${access}`); let events: EventSource | undefined;
events.addEventListener("data", dataEventListener); createEffect(() => {
const token = accessToken();
if (token) {
events = new EventSource(`${base}/notifications?token=${token}`);
events.addEventListener("data", dataEventListener);
events.onerror = (e) => {
console.error(e);
};
}
});
events.onerror = (e) => { onCleanup(() => {
console.error(e); if (events) {
}; events.removeEventListener("data", dataEventListener);
events.close();
}
});
onCleanup(() => { return {
events.removeEventListener("data", dataEventListener); state,
events.close(); };
});
return {
state,
};
}; };
export const NotificationsContext = export const NotificationsContext =
createContext<ReturnType<typeof Notifications>>(); createContext<ReturnType<typeof Notifications>>();
export const useNotifications = () => { export const useNotifications = () => {
const notifications = useContext(NotificationsContext); const notifications = useContext(NotificationsContext);
if (notifications == null) { if (notifications == null) {
throw new Error("Cannot use this hook with an unmounted notifications"); throw new Error("Cannot use this hook with an unmounted notifications");
} }
return notifications; return notifications;
}; };
export const WithNotifications: Component<ParentProps> = (props) => { export const WithNotifications: Component<ParentProps> = (props) => {
const { onRefetchImages } = useSearchImageContext(); const { onRefetchImages } = useSearchImageContext();
const notifications = Notifications(onRefetchImages); const notifications = Notifications(onRefetchImages);
return ( return (
<NotificationsContext.Provider value={notifications}> <NotificationsContext.Provider value={notifications}>
{props.children} {props.children}
</NotificationsContext.Provider> </NotificationsContext.Provider>
); );
}; };

View File

@ -38,11 +38,7 @@ const refreshTokenValidator = strictObject({
access: string(), access: string(),
}) })
const getBaseAuthorizedRequest = async ({ export const getAccessToken = async (): Promise<string> => {
path,
body,
method,
}: BaseRequestParams): Promise<Request> => {
let accessToken = localStorage.getItem("access")?.toString(); let accessToken = localStorage.getItem("access")?.toString();
const refreshToken = localStorage.getItem("refresh")?.toString(); const refreshToken = localStorage.getItem("refresh")?.toString();
@ -65,6 +61,16 @@ const getBaseAuthorizedRequest = async ({
accessToken = access accessToken = access
} }
return accessToken!
}
const getBaseAuthorizedRequest = async ({
path,
body,
method,
}: BaseRequestParams): Promise<Request> => {
const accessToken = await getAccessToken();
return new Request(`${base}/${path}`, { return new Request(`${base}/${path}`, {
headers: { headers: {
Authorization: `Bearer ${accessToken}`, Authorization: `Bearer ${accessToken}`,

View File

@ -1,7 +1,7 @@
import { useSearchImageContext } from "@contexts/SearchImageContext"; import { useSearchImageContext } from "@contexts/SearchImageContext";
import { useParams } from "@solidjs/router"; import { useParams } from "@solidjs/router";
import { Component, For, Show, createSignal } from "solid-js"; import { Component, For, Show, Suspense, createResource, createSignal } from "solid-js";
import { base } from "../../network"; import { base, getAccessToken } from "../../network";
import { Dialog } from "@kobalte/core"; import { Dialog } from "@kobalte/core";
const DeleteButton: Component<{ onDelete: () => void }> = (props) => { const DeleteButton: Component<{ onDelete: () => void }> = (props) => {
@ -52,104 +52,102 @@ export const List: Component = () => {
const { lists, onDeleteImageFromStack } = useSearchImageContext(); const { lists, onDeleteImageFromStack } = useSearchImageContext();
// TODO: make sure this is up to date. Put it behind a resource. const [accessToken] = createResource(getAccessToken);
const accessToken = localStorage.getItem("access");
if (accessToken == null) {
return <>Ermm... Access token is not set :(</>
}
const list = () => lists().find((l) => l.ID === listId); const list = () => lists().find((l) => l.ID === listId);
return ( return (
<Show when={list()} fallback="List could not be found"> <Suspense>
{(l) => ( <Show when={list()} fallback="List could not be found">
<div class="w-full h-full bg-white rounded-lg shadow-sm border border-neutral-200 overflow-hidden"> {(l) => (
<div class="overflow-x-auto overflow-y-auto h-full"> <div class="w-full h-full bg-white rounded-lg shadow-sm border border-neutral-200 overflow-hidden">
<table class="w-full min-w-full"> <div class="overflow-x-auto overflow-y-auto h-full">
<thead class="bg-neutral-50 border-b border-neutral-200 sticky top-0 z-10"> <table class="w-full min-w-full">
<tr> <thead class="bg-neutral-50 border-b border-neutral-200 sticky top-0 z-10">
<th class="px-6 py-4 text-left text-sm font-semibold text-neutral-900 border-r border-neutral-200 min-w-40"> <tr>
Image <th class="px-6 py-4 text-left text-sm font-semibold text-neutral-900 border-r border-neutral-200 min-w-40">
</th> Image
<For each={l().Schema.SchemaItems}> </th>
{(item, index) => ( <For each={l().Schema.SchemaItems}>
<th {(item, index) => (
class={`px-6 py-4 text-left text-sm font-semibold text-neutral-900 min-w-32 ${index() < <th
l().Schema.SchemaItems class={`px-6 py-4 text-left text-sm font-semibold text-neutral-900 min-w-32 ${index() <
.length - l().Schema.SchemaItems
1 .length -
? "border-r border-neutral-200" 1
: "" ? "border-r border-neutral-200"
: ""
}`}
>
{item.Item}
</th>
)}
</For>
</tr>
</thead>
<tbody class="divide-y divide-neutral-200">
<For each={l().Images}>
{(image, rowIndex) => (
<tr
class={`hover:bg-neutral-50 transition-colors ${rowIndex() % 2 === 0
? "bg-white"
: "bg-neutral-25"
}`} }`}
> >
{item.Item} <td class="px-6 py-4 border-r border-neutral-200">
</th> <div class="flex items-center gap-2">
<a
href={`/image/${image.ImageID}`}
class="w-32 h-24 flex justify-center rounded-lg overflow-hidden"
>
<img
class="w-full h-full object-cover rounded-lg"
src={`${base}/images/${image.ImageID}?token=${accessToken()}`}
alt="List item"
/>
</a>
<DeleteButton onDelete={() => onDeleteImageFromStack(l().ID, image.ImageID)} />
</div>
</td>
<For each={image.Items}>
{(item, colIndex) => (
<td
class={`px-6 py-4 text-sm text-neutral-700 ${colIndex() <
image.Items.length -
1
? "border-r border-neutral-200"
: ""
}`}
>
<div
class="max-w-xs truncate"
title={item.Value}
>
{item.Value}
</div>
</td>
)}
</For>
</tr>
)} )}
</For> </For>
</tr> </tbody>
</thead> </table>
<tbody class="divide-y divide-neutral-200"> <Show when={l().Images.length === 0}>
<For each={l().Images}> <div class="px-6 py-12 text-center text-neutral-500">
{(image, rowIndex) => ( <p class="text-lg">
<tr No images in this list yet
class={`hover:bg-neutral-50 transition-colors ${rowIndex() % 2 === 0 </p>
? "bg-white" <p class="text-sm mt-1">
: "bg-neutral-25" Images will appear here once added to the
}`} list
> </p>
<td class="px-6 py-4 border-r border-neutral-200"> </div>
<div class="flex items-center gap-2"> </Show>
<a </div>
href={`/image/${image.ImageID}`}
class="w-32 h-24 flex justify-center rounded-lg overflow-hidden"
>
<img
class="w-full h-full object-cover rounded-lg"
src={`${base}/images/${image.ImageID}`}
alt="List item"
/>
</a>
<DeleteButton onDelete={() => onDeleteImageFromStack(l().ID, image.ImageID)} />
</div>
</td>
<For each={image.Items}>
{(item, colIndex) => (
<td
class={`px-6 py-4 text-sm text-neutral-700 ${colIndex() <
image.Items.length -
1
? "border-r border-neutral-200"
: ""
}`}
>
<div
class="max-w-xs truncate"
title={item.Value}
>
{item.Value}
</div>
</td>
)}
</For>
</tr>
)}
</For>
</tbody>
</table>
<Show when={l().Images.length === 0}>
<div class="px-6 py-12 text-center text-neutral-500">
<p class="text-lg">
No images in this list yet
</p>
<p class="text-sm mt-1">
Images will appear here once added to the
list
</p>
</div>
</Show>
</div> </div>
</div> )}
)} </Show>
</Show> </Suspense>
); );
}; };