1
0
Fork 0
mirror of https://github.com/seanmorley15/AdventureLog.git synced 2025-07-22 22:39:36 +02:00

universal image fetcher

This commit is contained in:
Sean Morley 2024-07-16 15:38:07 -04:00
parent e643362011
commit b39ac34b68
4 changed files with 193 additions and 22 deletions

View file

@ -12,17 +12,21 @@
let originalName = adventureToEdit.name; let originalName = adventureToEdit.name;
let isPointModalOpen: boolean = false; let isPointModalOpen: boolean = false;
let isImageFetcherOpen: boolean = false;
let fileInput: HTMLInputElement;
let image: File;
import MapMarker from '~icons/mdi/map-marker'; import MapMarker from '~icons/mdi/map-marker';
import Calendar from '~icons/mdi/calendar'; import Calendar from '~icons/mdi/calendar';
import Notebook from '~icons/mdi/notebook'; import Notebook from '~icons/mdi/notebook';
import ClipboardList from '~icons/mdi/clipboard-list'; import ClipboardList from '~icons/mdi/clipboard-list';
import Image from '~icons/mdi/image';
import Star from '~icons/mdi/star'; import Star from '~icons/mdi/star';
import Attachment from '~icons/mdi/attachment'; import Attachment from '~icons/mdi/attachment';
import PointSelectionModal from './PointSelectionModal.svelte'; import PointSelectionModal from './PointSelectionModal.svelte';
import Earth from '~icons/mdi/earth'; import Earth from '~icons/mdi/earth';
import Wikipedia from '~icons/mdi/wikipedia'; import Wikipedia from '~icons/mdi/wikipedia';
import ImageFetcher from './ImageFetcher.svelte';
onMount(async () => { onMount(async () => {
modal = document.getElementById('my_modal_1') as HTMLDialogElement; modal = document.getElementById('my_modal_1') as HTMLDialogElement;
@ -88,6 +92,23 @@
} }
} }
} }
function handleImageFetch(event: CustomEvent) {
const file = event.detail.file;
if (file && fileInput) {
// Create a DataTransfer object and add the file
const dataTransfer = new DataTransfer();
dataTransfer.items.add(file);
// Set the files property of the file input
fileInput.files = dataTransfer.files;
// Update the adventureToEdit object
adventureToEdit.image = file;
}
isImageFetcherOpen = false;
}
function setLongLat(event: CustomEvent<[number, number]>) { function setLongLat(event: CustomEvent<[number, number]>) {
console.log(event.detail); console.log(event.detail);
adventureToEdit.latitude = event.detail[1]; adventureToEdit.latitude = event.detail[1];
@ -105,6 +126,10 @@
/> />
{/if} {/if}
{#if isImageFetcherOpen}
<ImageFetcher on:image={handleImageFetch} on:close={() => (isImageFetcherOpen = false)} />
{/if}
<dialog id="my_modal_1" class="modal"> <dialog id="my_modal_1" class="modal">
<!-- svelte-ignore a11y-no-noninteractive-element-interactions --> <!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<!-- svelte-ignore a11y-no-noninteractive-tabindex --> <!-- svelte-ignore a11y-no-noninteractive-tabindex -->
@ -193,14 +218,23 @@
/> />
</div> </div>
<div class="mb-2"> <div class="mb-2">
<label for="image">Image <Image class="inline-block -mt-1 mb-1 w-6 h-6" /></label><br /> <label for="image">Image </label><br />
<div class="flex">
<input <input
type="file" type="file"
id="image" id="image"
name="image" name="image"
bind:value={adventureToEdit.image} bind:value={image}
bind:this={fileInput}
class="file-input file-input-bordered w-full max-w-xs mt-1" class="file-input file-input-bordered w-full max-w-xs mt-1"
/> />
<button
class="btn btn-neutral ml-2"
type="button"
on:click={() => (isImageFetcherOpen = true)}
><Wikipedia class="inline-block -mt-1 mb-1 w-6 h-6" />Image Search</button
>
</div>
</div> </div>
<div class="mb-2"> <div class="mb-2">
<label for="link">Link <Attachment class="inline-block -mt-1 mb-1 w-6 h-6" /></label><br <label for="link">Link <Attachment class="inline-block -mt-1 mb-1 w-6 h-6" /></label><br

View file

@ -0,0 +1,90 @@
<script lang="ts">
import { addToast } from '$lib/toasts';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
import { onMount } from 'svelte';
let modal: HTMLDialogElement;
let url: string = '';
let query: string = '';
let error = '';
onMount(() => {
modal = document.getElementById('my_modal_1') as HTMLDialogElement;
if (modal) {
modal.showModal();
}
});
async function fetchImage() {
let res = await fetch(url);
let data = await res.blob();
if (!data) {
error = 'No image found at that URL.';
return;
}
let file = new File([data], 'image.jpg', { type: 'image/jpeg' });
close();
dispatch('image', { file });
}
async function fetchWikiImage() {
let res = await fetch(`/api/generate/img/?name=${query}`);
let data = await res.json();
if (data.source) {
let imageUrl = data.source;
let res = await fetch(imageUrl);
let blob = await res.blob();
let file = new File([blob], `${query}.jpg`, { type: 'image/jpeg' });
close();
dispatch('image', { file });
} else {
error = 'No image found for that Wikipedia article.';
}
}
function close() {
dispatch('close');
}
function handleKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') {
dispatch('close');
}
}
</script>
<dialog id="my_modal_1" class="modal">
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<!-- svelte-ignore a11y-no-noninteractive-tabindex -->
<div class="modal-box" role="dialog" on:keydown={handleKeydown} tabindex="0">
<h3 class="font-bold text-lg">Image Fetcher with URL</h3>
<form>
<input
type="text"
class="input input-bordered w-full max-w-xs"
bind:value={url}
placeholder="Enter a URL"
/>
<button class="btn btn-primary" on:click={fetchImage}>Submit</button>
</form>
<h3 class="font-bold text-lg">Image Fetcher from Wikipedia</h3>
<form>
<input
type="text"
class="input input-bordered w-full max-w-xs"
bind:value={query}
placeholder="Enter a Wikipedia Article Name"
/>
<button class="btn btn-primary" on:click={fetchWikiImage}>Submit</button>
</form>
{#if error}
<p class="text-red-500">{error}</p>
{/if}
<button class="btn btn-primary" on:click={close}>Close</button>
</div>
</dialog>

View file

@ -5,6 +5,7 @@
import { enhance } from '$app/forms'; import { enhance } from '$app/forms';
import { addToast } from '$lib/toasts'; import { addToast } from '$lib/toasts';
import PointSelectionModal from './PointSelectionModal.svelte'; import PointSelectionModal from './PointSelectionModal.svelte';
import ImageFetcher from './ImageFetcher.svelte';
export let type: string = 'visited'; export let type: string = 'visited';
@ -28,8 +29,10 @@
}; };
let image: File; let image: File;
let fileInput: HTMLInputElement;
let isPointModalOpen: boolean = false; let isPointModalOpen: boolean = false;
let isImageFetcherOpen: boolean = false;
const dispatch = createEventDispatcher(); const dispatch = createEventDispatcher();
let modal: HTMLDialogElement; let modal: HTMLDialogElement;
@ -102,6 +105,22 @@
} }
} }
function handleImageFetch(event: CustomEvent) {
const file = event.detail.file;
if (file && fileInput) {
// Create a DataTransfer object and add the file
const dataTransfer = new DataTransfer();
dataTransfer.items.add(file);
// Set the files property of the file input
fileInput.files = dataTransfer.files;
// Update the adventureToEdit object
newAdventure.image = file;
}
isImageFetcherOpen = false;
}
function setLongLat(event: CustomEvent<[number, number]>) { function setLongLat(event: CustomEvent<[number, number]>) {
console.log(event.detail); console.log(event.detail);
newAdventure.latitude = event.detail[1]; newAdventure.latitude = event.detail[1];
@ -114,6 +133,10 @@
<PointSelectionModal on:close={() => (isPointModalOpen = false)} on:submit={setLongLat} /> <PointSelectionModal on:close={() => (isPointModalOpen = false)} on:submit={setLongLat} />
{/if} {/if}
{#if isImageFetcherOpen}
<ImageFetcher on:image={handleImageFetch} on:close={() => (isImageFetcherOpen = false)} />
{/if}
<!-- svelte-ignore a11y-no-noninteractive-tabindex --> <!-- svelte-ignore a11y-no-noninteractive-tabindex -->
<dialog id="my_modal_1" class="modal"> <dialog id="my_modal_1" class="modal">
<!-- svelte-ignore a11y-no-noninteractive-tabindex --> <!-- svelte-ignore a11y-no-noninteractive-tabindex -->
@ -234,16 +257,23 @@
/> />
</div> </div>
<div class="mb-2"> <div class="mb-2">
<label for="image" <label for="image">Image </label><br />
>Image <iconify-icon icon="mdi:image" class="text-xl -mb-1"></iconify-icon></label <div class="flex">
><br />
<input <input
type="file" type="file"
id="image" id="image"
name="image" name="image"
bind:value={image} bind:value={image}
bind:this={fileInput}
class="file-input file-input-bordered w-full max-w-xs mt-1" class="file-input file-input-bordered w-full max-w-xs mt-1"
/> />
<button
class="btn btn-neutral ml-2"
type="button"
on:click={() => (isImageFetcherOpen = true)}
><Wikipedia class="inline-block -mt-1 mb-1 w-6 h-6" />Image Search</button
>
</div>
</div> </div>
<div class="mb-2"> <div class="mb-2">
<input <input

View file

@ -4,6 +4,12 @@ import { json } from '@sveltejs/kit';
/** @type {import('./$types').RequestHandler} */ /** @type {import('./$types').RequestHandler} */
export async function GET({ url, params, request, fetch, cookies }) { export async function GET({ url, params, request, fetch, cookies }) {
// add the param format = json to the url or add additional if anothre param is already present
if (url.search) {
url.search = url.search + '&format=json';
} else {
url.search = '?format=json';
}
return handleRequest(url, params, request, fetch, cookies); return handleRequest(url, params, request, fetch, cookies);
} }
@ -13,7 +19,7 @@ export async function POST({ url, params, request, fetch, cookies }) {
} }
export async function PATCH({ url, params, request, fetch, cookies }) { export async function PATCH({ url, params, request, fetch, cookies }) {
return handleRequest(url, params, request, fetch, cookies); return handleRequest(url, params, request, fetch, cookies, true);
} }
export async function PUT({ url, params, request, fetch, cookies }) { export async function PUT({ url, params, request, fetch, cookies }) {
@ -26,9 +32,20 @@ export async function DELETE({ url, params, request, fetch, cookies }) {
// Implement other HTTP methods as needed (PUT, DELETE, etc.) // Implement other HTTP methods as needed (PUT, DELETE, etc.)
async function handleRequest(url: any, params: any, request: any, fetch: any, cookies: any) { async function handleRequest(
url: any,
params: any,
request: any,
fetch: any,
cookies: any,
requreTrailingSlash: boolean | undefined = false
) {
const path = params.path; const path = params.path;
const targetUrl = `${endpoint}/api/${path}${url.search}/`; let targetUrl = `${endpoint}/api/${path}${url.search}`;
if (requreTrailingSlash && !targetUrl.endsWith('/')) {
targetUrl += '/';
}
const headers = new Headers(request.headers); const headers = new Headers(request.headers);