refactor zo zod and felte
This commit is contained in:
@@ -1,8 +1,10 @@
|
||||
<script lang="ts">
|
||||
import { _ } from "svelte-i18n";
|
||||
|
||||
export let name: string = "";
|
||||
export let value: string | Date = "";
|
||||
export let label: string = "";
|
||||
export let error: string = "";
|
||||
export let error: string | string[] | null = "";
|
||||
</script>
|
||||
|
||||
<div>
|
||||
@@ -15,15 +17,17 @@
|
||||
<input
|
||||
{name}
|
||||
class="bg-input-background border border-input-border rounded-md p-3 transition-colors focus:border-input-border-focus focus:outline-none focus:ring-0 w-full"
|
||||
class:border-red-400={error.length > 0}
|
||||
class:bg-red-50={error.length > 0}
|
||||
class:border-red-400={(error?.length ?? 0) > 0}
|
||||
class:bg-input-background-error={(error?.length ?? 0) > 0}
|
||||
type="date"
|
||||
bind:value
|
||||
on:change
|
||||
/>
|
||||
</div>
|
||||
|
||||
<span class="textfield-error text-xs text-red-400">
|
||||
{error}
|
||||
</span>
|
||||
{#if error}
|
||||
<span class="textfield-error text-xs text-red-400">
|
||||
{error instanceof Array ? $_(error[0]) : error}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
import { createEventDispatcher } from "svelte";
|
||||
|
||||
export let name: string = "";
|
||||
export let value: any;
|
||||
export let items: SelectItem[] = [];
|
||||
export let value: any = items.at(0)?.value ?? "";
|
||||
export let label: string = "";
|
||||
export let disabled: boolean = false;
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
<script lang="ts">
|
||||
import { _ } from "svelte-i18n";
|
||||
|
||||
export let name: string = "";
|
||||
export let value: string | number = "";
|
||||
export let placeholder: string = "";
|
||||
export let disabled: boolean = false;
|
||||
export let label: string = "";
|
||||
export let error: string = "";
|
||||
export let error: string | string[] | null = "";
|
||||
export let icon: string = "";
|
||||
export let extraClasses: string = "";
|
||||
export let type: "text" | "password" | "search" = "text";
|
||||
@@ -29,8 +31,8 @@
|
||||
<input
|
||||
{name}
|
||||
class="bg-input-background border border-input-border rounded-md p-3 transition-colors focus:border-input-border-focus focus:outline-none focus:ring-0 w-full {extraClasses}"
|
||||
class:border-red-400={error.length > 0}
|
||||
class:bg-input-background-error={error.length > 0}
|
||||
class:border-red-400={(error?.length ?? 0) > 0}
|
||||
class:bg-input-background-error={(error?.length ?? 0) > 0}
|
||||
class:text-gray-500={disabled}
|
||||
{disabled}
|
||||
{autocomplete}
|
||||
@@ -44,7 +46,9 @@
|
||||
/>
|
||||
</div>
|
||||
|
||||
<span class="textfield-error text-xs text-red-400">
|
||||
{error}
|
||||
</span>
|
||||
{#if error}
|
||||
<span class="textfield-error text-xs text-red-400">
|
||||
{error instanceof Array ? $_(error[0]) : error}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
<script lang="ts">
|
||||
import { _ } from "svelte-i18n";
|
||||
|
||||
export let name: string = "";
|
||||
export let value: string | number = "";
|
||||
export let placeholder: string = "";
|
||||
export let rows: number = 3;
|
||||
export let label: string = "";
|
||||
export let error: string = "";
|
||||
export let error: string | string[] | null = "";
|
||||
export let extraClasses: string = "";
|
||||
</script>
|
||||
|
||||
@@ -19,12 +21,14 @@
|
||||
class="bg-input-background border border-input-border rounded-md p-3 resize-none transition-colors focus:border-input-border-focus focus:outline-none focus:ring-0 w-full {extraClasses}"
|
||||
{rows}
|
||||
{placeholder}
|
||||
class:border-red-400={error.length > 0}
|
||||
class:bg-red-50={error.length > 0}
|
||||
class:border-red-400={(error?.length ?? 0) > 0}
|
||||
class:bg-input-background-error={(error?.length ?? 0) > 0}
|
||||
bind:value
|
||||
on:change
|
||||
/>
|
||||
<span class="textfield-error text-xs text-red-400">
|
||||
{error}
|
||||
</span>
|
||||
{#if error}
|
||||
<span class="textfield-error text-xs text-red-400">
|
||||
{error instanceof Array ? $_(error[0]) : error}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -125,13 +125,17 @@
|
||||
{#each { length: 5 } as _, index}
|
||||
<SkeletonNotificationCard></SkeletonNotificationCard>
|
||||
{/each}
|
||||
{:else}
|
||||
{:else if notifications.length}
|
||||
{#each notifications as notification}
|
||||
<NotificationCard
|
||||
on:click={handleNotificationClick}
|
||||
{notification}
|
||||
></NotificationCard>
|
||||
{/each}
|
||||
{:else}
|
||||
<p class="text-gray-500 text-sm text-center py-6">
|
||||
No notifications
|
||||
</p>
|
||||
{/if}
|
||||
</ul>
|
||||
{/if}
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
<script lang="ts">
|
||||
import Modal from "$lib/components/base/modal.svelte";
|
||||
import { validator } from "@felte/validator-zod";
|
||||
import { createForm } from "felte";
|
||||
import { createEventDispatcher } from "svelte";
|
||||
import { _ } from "svelte-i18n";
|
||||
import { z } from "zod";
|
||||
import TextField from "../base/text_field.svelte";
|
||||
import { createForm } from "$lib/vendor/svelte-form-lib";
|
||||
import { object, string } from "yup";
|
||||
|
||||
let _openModal: (() => void) | undefined = undefined;
|
||||
export let closeModal: (() => void) | undefined = undefined;
|
||||
export function openModal() {
|
||||
$form.email = email
|
||||
$errors.email = "";
|
||||
setFields("email", email);
|
||||
setErrors("email", []);
|
||||
_openModal!();
|
||||
}
|
||||
|
||||
@@ -18,17 +19,20 @@
|
||||
|
||||
const dispatch = createEventDispatcher();
|
||||
|
||||
const { form, errors, handleChange, handleSubmit } = createForm<{
|
||||
const { form, errors, setFields, setErrors } = createForm<{
|
||||
email: string;
|
||||
}>({
|
||||
initialValues: { email: email },
|
||||
validationSchema: object({
|
||||
email: string()
|
||||
.email($_("not-a-valid-email-address"))
|
||||
.required($_("required")),
|
||||
extend: validator({
|
||||
schema: z.object({
|
||||
email: z
|
||||
.string()
|
||||
.min(1, "required")
|
||||
.email("not-a-valid-email-address"),
|
||||
}),
|
||||
}),
|
||||
onSubmit: async (_) => {
|
||||
dispatch("save", $form.email);
|
||||
onSubmit: async (form) => {
|
||||
dispatch("save", form.email);
|
||||
closeModal!();
|
||||
},
|
||||
});
|
||||
@@ -41,13 +45,8 @@
|
||||
bind:openModal={_openModal}
|
||||
bind:closeModal
|
||||
>
|
||||
<form id="email-form" slot="content" on:submit={handleSubmit}>
|
||||
<TextField
|
||||
name="email"
|
||||
bind:value={$form.email}
|
||||
error={$errors.email}
|
||||
on:change={handleChange}
|
||||
></TextField>
|
||||
<form id="email-form" slot="content" use:form>
|
||||
<TextField name="email" error={$errors.email}></TextField>
|
||||
</form>
|
||||
<div slot="footer" class="flex items-center gap-4">
|
||||
<button class="btn-secondary" on:click={closeModal}
|
||||
|
||||
@@ -3,46 +3,61 @@
|
||||
import { createEventDispatcher } from "svelte";
|
||||
import { _ } from "svelte-i18n";
|
||||
import TextField from "../base/text_field.svelte";
|
||||
import { createForm } from "$lib/vendor/svelte-form-lib";
|
||||
import { object, string } from "yup";
|
||||
import { validator } from "@felte/validator-zod";
|
||||
import { createForm } from "felte";
|
||||
import { z } from "zod";
|
||||
|
||||
let _openModal: (() => void) | undefined = undefined;
|
||||
export let closeModal: (() => void) | undefined = undefined;
|
||||
export function openModal() {
|
||||
$form.password = ""
|
||||
$errors.password = "";
|
||||
$form.oldPassword = ""
|
||||
$errors.oldPassword = "";
|
||||
setFields("password", "")
|
||||
setFields("oldPassword", "")
|
||||
setErrors("password", [])
|
||||
setErrors("oldPassword", [])
|
||||
_openModal!();
|
||||
}
|
||||
|
||||
const dispatch = createEventDispatcher();
|
||||
|
||||
const { form, errors, handleChange, handleSubmit } = createForm<{
|
||||
const { form, errors, setFields, setErrors } = createForm<{
|
||||
oldPassword: string;
|
||||
password: string;
|
||||
passwordConfirm: string;
|
||||
}>({
|
||||
initialValues: { oldPassword: "", password: "" },
|
||||
validationSchema: object({
|
||||
oldPassword: string()
|
||||
.min(
|
||||
8,
|
||||
$_("must-be-at-least-n-characters-long", {
|
||||
values: { n: 8 },
|
||||
}),
|
||||
)
|
||||
.required($_("required")),
|
||||
password: string()
|
||||
.min(
|
||||
8,
|
||||
$_("must-be-at-least-n-characters-long", {
|
||||
values: { n: 8 },
|
||||
}),
|
||||
)
|
||||
.required($_("required")),
|
||||
extend: validator({
|
||||
schema: z
|
||||
.object({
|
||||
oldPassword: z.string().min(
|
||||
8,
|
||||
$_("must-be-at-least-n-characters-long", {
|
||||
values: { n: 8 },
|
||||
}),
|
||||
),
|
||||
password: z.string().min(
|
||||
8,
|
||||
$_("must-be-at-least-n-characters-long", {
|
||||
values: { n: 8 },
|
||||
}),
|
||||
),
|
||||
passwordConfirm: z.string().min(
|
||||
8,
|
||||
$_("must-be-at-least-n-characters-long", {
|
||||
values: { n: 8 },
|
||||
}),
|
||||
),
|
||||
})
|
||||
.refine((d) => d.password === d.passwordConfirm, {
|
||||
message: "passwords-must-match",
|
||||
path: ["passwordConfirm"],
|
||||
}),
|
||||
}),
|
||||
onSubmit: async (_) => {
|
||||
dispatch("save", {oldPassword: $form.oldPassword, password: $form.password, passwordConfirm: $form.password});
|
||||
onSubmit: async (form) => {
|
||||
dispatch("save", {
|
||||
oldPassword: form.oldPassword,
|
||||
password: form.password,
|
||||
passwordConfirm: form.password,
|
||||
});
|
||||
closeModal!();
|
||||
},
|
||||
});
|
||||
@@ -55,30 +70,35 @@
|
||||
bind:openModal={_openModal}
|
||||
bind:closeModal
|
||||
>
|
||||
<form id="password-form" slot="content" on:submit={handleSubmit}>
|
||||
<form id="password-form" slot="content" use:form>
|
||||
<TextField
|
||||
name="oldPassword"
|
||||
label={$_("current-password")}
|
||||
type="password"
|
||||
bind:value={$form.oldPassword}
|
||||
error={$errors.oldPassword}
|
||||
on:change={handleChange}
|
||||
></TextField>
|
||||
<TextField
|
||||
name="password"
|
||||
label={$_("new-password")}
|
||||
type="password"
|
||||
bind:value={$form.password}
|
||||
error={$errors.password}
|
||||
on:change={handleChange}
|
||||
></TextField>
|
||||
<TextField
|
||||
name="passwordConfirm"
|
||||
label={$_("password-confirm")}
|
||||
type="password"
|
||||
error={$errors.passwordConfirm}
|
||||
></TextField>
|
||||
</form>
|
||||
<div slot="footer" class="flex items-center gap-4">
|
||||
<button class="btn-secondary" on:click={closeModal}
|
||||
>{$_("cancel")}</button
|
||||
>
|
||||
<button class="btn-primary" type="submit" form="password-form" name="save"
|
||||
>{$_("save")}</button
|
||||
<button
|
||||
class="btn-primary"
|
||||
type="submit"
|
||||
form="password-form"
|
||||
name="save">{$_("save")}</button
|
||||
>
|
||||
</div></Modal
|
||||
>
|
||||
|
||||
@@ -1,41 +1,50 @@
|
||||
<script lang="ts">
|
||||
import { createEventDispatcher } from "svelte";
|
||||
|
||||
import { type SummitLog } from "$lib/models/summit_log";
|
||||
import {
|
||||
SummitLogCreateSchema,
|
||||
} from "$lib/models/api/summit_log_schema";
|
||||
import GPX from "$lib/models/gpx/gpx";
|
||||
import { summitLog } from "$lib/stores/summit_log_store";
|
||||
import { createForm } from "$lib/vendor/svelte-form-lib/index";
|
||||
import { util } from "$lib/vendor/svelte-form-lib/util";
|
||||
import { createForm } from "felte";
|
||||
import { validator } from "@felte/validator-zod";
|
||||
import { _ } from "svelte-i18n";
|
||||
import { date, object, string } from "yup";
|
||||
import { z } from "zod";
|
||||
import Datepicker from "../base/datepicker.svelte";
|
||||
import Modal from "../base/modal.svelte";
|
||||
import Textarea from "../base/textarea.svelte";
|
||||
import TrailPicker from "../trail/trail_picker.svelte";
|
||||
import GPX from "$lib/models/gpx/gpx";
|
||||
import PhotoPicker from "../trail/photo_picker.svelte";
|
||||
import TrailPicker from "../trail/trail_picker.svelte";
|
||||
import { cloneDeep } from "$lib/util/deep_util";
|
||||
export let openModal: (() => void) | undefined = undefined;
|
||||
export let closeModal: (() => void) | undefined = undefined;
|
||||
|
||||
const dispatch = createEventDispatcher();
|
||||
|
||||
const summitLogSchema = object<SummitLog>({
|
||||
id: string().optional(),
|
||||
date: date().required("Required").typeError($_("invalid-date")),
|
||||
text: string().optional(),
|
||||
const ClientSummitLogCreateSchema = SummitLogCreateSchema.extend({
|
||||
_photos: z.array(z.instanceof(File)).optional(),
|
||||
_gpx: z.instanceof(File).optional().nullable(),
|
||||
expand: z
|
||||
.object({
|
||||
gpx_data: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const { form, errors, handleChange, handleSubmit } = createForm<SummitLog>({
|
||||
const { form, errors, data, setFields } = createForm<
|
||||
z.infer<typeof ClientSummitLogCreateSchema>
|
||||
>({
|
||||
initialValues: $summitLog,
|
||||
validationSchema: summitLogSchema,
|
||||
onSubmit: async (submittedValues) => {
|
||||
if (!$form.expand.gpx_data) {
|
||||
$form.gpx = "";
|
||||
extend: validator({ schema: ClientSummitLogCreateSchema }),
|
||||
onSubmit: async (form) => {
|
||||
if (!form.expand?.gpx_data) {
|
||||
form.gpx = "";
|
||||
}
|
||||
|
||||
if (
|
||||
!$form._photos?.length &&
|
||||
!$form.photos?.length &&
|
||||
$form.expand?.gpx_data
|
||||
!form._photos?.length &&
|
||||
!form.photos?.length &&
|
||||
form.expand?.gpx_data
|
||||
) {
|
||||
const canvas = document.querySelector(
|
||||
"#trail-picker-map .maplibregl-canvas",
|
||||
@@ -44,25 +53,25 @@
|
||||
const dataURL = canvas.toDataURL();
|
||||
const response = await fetch(dataURL);
|
||||
const blob = await response.blob();
|
||||
$form._photos = [new File([blob], "route")];
|
||||
form._photos = [new File([blob], "route")];
|
||||
}
|
||||
|
||||
dispatch("save", submittedValues);
|
||||
dispatch("save", form);
|
||||
closeModal!();
|
||||
},
|
||||
});
|
||||
$: form.set(util.cloneDeep($summitLog));
|
||||
$: setFields(cloneDeep($summitLog));
|
||||
|
||||
$: if ($summitLog._gpx) {
|
||||
$form._gpx = $summitLog._gpx;
|
||||
$data._gpx = $summitLog._gpx;
|
||||
}
|
||||
|
||||
async function handleTrailSelection(trailData: string | null) {
|
||||
if (!trailData) {
|
||||
$form.duration = undefined;
|
||||
$form.elevation_gain = undefined;
|
||||
$form.elevation_loss = undefined;
|
||||
$form.distance = undefined;
|
||||
$data.duration = undefined;
|
||||
$data.elevation_gain = undefined;
|
||||
$data.elevation_loss = undefined;
|
||||
$data.distance = undefined;
|
||||
return;
|
||||
}
|
||||
const gpxObject = await GPX.parse(trailData);
|
||||
@@ -72,16 +81,15 @@
|
||||
|
||||
const totals = gpxObject.getTotals();
|
||||
|
||||
$form.duration = totals.duration / 1000;
|
||||
$form.elevation_gain = totals.elevationGain;
|
||||
$form.elevation_loss = totals.elevationLoss;
|
||||
$form.distance = totals.distance;
|
||||
$data.duration = totals.duration / 1000;
|
||||
$data.elevation_gain = totals.elevationGain;
|
||||
$data.elevation_loss = totals.elevationLoss;
|
||||
$data.distance = totals.distance;
|
||||
}
|
||||
</script>
|
||||
|
||||
<Modal
|
||||
id="summit-log-modal"
|
||||
title={$form.id ? $_("edit-entry") : $_("add-entry")}
|
||||
title={$data.id ? $_("edit-entry") : $_("add-entry")}
|
||||
let:openModal
|
||||
bind:openModal
|
||||
bind:closeModal
|
||||
@@ -91,15 +99,10 @@
|
||||
id="summit-log-form"
|
||||
slot="content"
|
||||
class="modal-content space-y-4"
|
||||
on:submit={handleSubmit}
|
||||
use:form
|
||||
>
|
||||
<div class="flex">
|
||||
<Datepicker
|
||||
name="date"
|
||||
label={$_("date")}
|
||||
bind:value={$form.date}
|
||||
error={$errors.date}
|
||||
on:change={handleChange}
|
||||
<Datepicker name="date" label={$_("date")} error={$errors.date}
|
||||
></Datepicker>
|
||||
</div>
|
||||
<div>
|
||||
@@ -108,27 +111,27 @@
|
||||
</label>
|
||||
<PhotoPicker
|
||||
id="summitlog-photo-input"
|
||||
parent={$form}
|
||||
bind:photos={$form.photos}
|
||||
bind:photoFiles={$form._photos}
|
||||
parent={$data}
|
||||
bind:photos={$data.photos}
|
||||
bind:photoFiles={$data._photos}
|
||||
showThumbnailControls={false}
|
||||
></PhotoPicker>
|
||||
</div>
|
||||
<div class="flex gap-4">
|
||||
<TrailPicker
|
||||
bind:trailFile={$form._gpx}
|
||||
bind:trailData={$form.expand.gpx_data}
|
||||
label={$_("trail", { values: { n: 1 } })}
|
||||
on:change={(e) => handleTrailSelection(e.detail)}
|
||||
></TrailPicker>
|
||||
{#if $data.expand}
|
||||
<TrailPicker
|
||||
bind:trailFile={$data._gpx}
|
||||
bind:trailData={$data.expand.gpx_data}
|
||||
label={$_("trail", { values: { n: 1 } })}
|
||||
on:change={(e) => handleTrailSelection(e.detail)}
|
||||
></TrailPicker>
|
||||
{/if}
|
||||
<div class="basis-full">
|
||||
<Textarea
|
||||
name="text"
|
||||
extraClasses="h-28"
|
||||
label={$_("text")}
|
||||
bind:value={$form.text}
|
||||
error={$errors.text}
|
||||
on:change={handleChange}
|
||||
></Textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import { fromFile, toGeoJson } from "$lib/util/gpx_util";
|
||||
import { createEventDispatcher, onMount } from "svelte";
|
||||
export let trailFile: File | null;
|
||||
export let trailFile: File | undefined | null;
|
||||
export let trailData: string | undefined;
|
||||
export let label: string = "";
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
attributionControl: false,
|
||||
dragPan: false,
|
||||
scrollZoom: false,
|
||||
preserveDrawingBuffer: true
|
||||
preserveDrawingBuffer: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -95,9 +95,12 @@
|
||||
},
|
||||
});
|
||||
layer = map.getLayer(layerId) as M.LineLayerSpecification;
|
||||
source = map.getSource(sourceId) as M.GeoJSONSource;
|
||||
map.resize()
|
||||
map.fitBounds(geojson.bbox as M.LngLatBoundsLike, {animate: false, padding: 8});
|
||||
source = map.getSource(sourceId) as M.GeoJSONSource;
|
||||
map.resize();
|
||||
map.fitBounds(geojson.bbox as M.LngLatBoundsLike, {
|
||||
animate: false,
|
||||
padding: 8,
|
||||
});
|
||||
}
|
||||
|
||||
function removeTrailFromMap() {
|
||||
|
||||
@@ -1,42 +1,58 @@
|
||||
<script lang="ts">
|
||||
import { Waypoint, waypointSchema } from "$lib/models/waypoint";
|
||||
import { createEventDispatcher } from "svelte";
|
||||
|
||||
import { WaypointCreateSchema } from "$lib/models/api/waypoint_schema";
|
||||
import { convertDMSToDD } from "$lib/models/gpx/utils";
|
||||
import { show_toast } from "$lib/stores/toast_store";
|
||||
import { waypoint } from "$lib/stores/waypoint_store";
|
||||
import { cloneDeep } from "$lib/util/deep_util";
|
||||
import { icons } from "$lib/util/icon_util";
|
||||
import EXIF from "$lib/vendor/exif-js/exif";
|
||||
import { createForm } from "$lib/vendor/svelte-form-lib/index";
|
||||
import { util } from "$lib/vendor/svelte-form-lib/util";
|
||||
import { validator } from "@felte/validator-zod";
|
||||
import { createForm } from "felte";
|
||||
import { _ } from "svelte-i18n";
|
||||
import { z } from "zod";
|
||||
import Combobox from "../base/combobox.svelte";
|
||||
import Modal from "../base/modal.svelte";
|
||||
import TextField from "../base/text_field.svelte";
|
||||
import Textarea from "../base/textarea.svelte";
|
||||
import PhotoPicker from "../trail/photo_picker.svelte";
|
||||
import { show_toast } from "$lib/stores/toast_store";
|
||||
import { convertDMSToDD } from "$lib/models/gpx/utils";
|
||||
|
||||
export let openModal: (() => void) | undefined = undefined;
|
||||
export let closeModal: (() => void) | undefined = undefined;
|
||||
|
||||
const dispatch = createEventDispatcher();
|
||||
|
||||
const { form, errors, handleChange, handleSubmit } = createForm<Waypoint>({
|
||||
const ClientWaypointCreateSchema = WaypointCreateSchema.extend({
|
||||
_photos: z.array(z.instanceof(File)).optional(),
|
||||
});
|
||||
|
||||
const { form, errors, data, setFields } = createForm<
|
||||
z.infer<typeof ClientWaypointCreateSchema>
|
||||
>({
|
||||
initialValues: $waypoint,
|
||||
validationSchema: waypointSchema,
|
||||
onSubmit: async (submittedWaypoint) => {
|
||||
dispatch("save", submittedWaypoint);
|
||||
extend: validator({ schema: ClientWaypointCreateSchema }),
|
||||
onSubmit: async (form) => {
|
||||
dispatch("save", form);
|
||||
|
||||
closeModal!();
|
||||
},
|
||||
transform: (values: unknown) => {
|
||||
const v = values as any;
|
||||
return {
|
||||
...v,
|
||||
lat: parseFloat(v.lat),
|
||||
lon: parseFloat(v.lon),
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
$: form.set(util.cloneDeep($waypoint));
|
||||
$: setFields(cloneDeep($waypoint));
|
||||
|
||||
$: filteredIcons =
|
||||
($form.icon?.length ?? 0) > 2
|
||||
($data.icon?.length ?? 0) > 2
|
||||
? icons
|
||||
.filter((i) => i.includes($form.icon ?? ""))
|
||||
.filter((i) => i.includes($data.icon ?? ""))
|
||||
.map((i) => ({ text: i, value: i, icon: i }))
|
||||
: [];
|
||||
|
||||
@@ -48,8 +64,8 @@
|
||||
const lonDir = EXIF.getTag(p, "GPSLongitudeRef");
|
||||
|
||||
if (lat && lon) {
|
||||
$form.lat = convertDMSToDD(lat, latDir);
|
||||
$form.lon = convertDMSToDD(lon, lonDir);
|
||||
setFields("lat", convertDMSToDD(lat, latDir));
|
||||
setFields("lon", convertDMSToDD(lon, lonDir));
|
||||
} else {
|
||||
show_toast({
|
||||
text: "No GPS data in image",
|
||||
@@ -63,7 +79,7 @@
|
||||
|
||||
<Modal
|
||||
id="waypoint-modal"
|
||||
title={$form.id ? $_("edit-waypoint") : $_("add-waypoint")}
|
||||
title={$data.id ? $_("edit-waypoint") : $_("add-waypoint")}
|
||||
let:openModal
|
||||
bind:openModal
|
||||
bind:closeModal
|
||||
@@ -73,50 +89,31 @@
|
||||
id="waypoint-form"
|
||||
slot="content"
|
||||
class="modal-content space-y-4"
|
||||
on:submit={handleSubmit}
|
||||
use:form
|
||||
>
|
||||
<div class="flex gap-4">
|
||||
<div class="basis-2/3">
|
||||
<TextField
|
||||
name="name"
|
||||
label={$_("name")}
|
||||
bind:value={$form.name}
|
||||
error={$errors.name}
|
||||
on:change={handleChange}
|
||||
<TextField name="name" label={$_("name")} error={$errors.name}
|
||||
></TextField>
|
||||
</div>
|
||||
|
||||
<Combobox
|
||||
name="icon"
|
||||
bind:value={$form.icon}
|
||||
icon={$form.icon}
|
||||
icon={$data.icon}
|
||||
items={filteredIcons}
|
||||
label={$_("icon")}
|
||||
on:change={handleChange}
|
||||
></Combobox>
|
||||
</div>
|
||||
|
||||
<Textarea
|
||||
name="description"
|
||||
label={$_("description")}
|
||||
bind:value={$form.description}
|
||||
error={$errors.description}
|
||||
on:change={handleChange}
|
||||
></Textarea>
|
||||
<div class="flex gap-4">
|
||||
<TextField
|
||||
name="lat"
|
||||
label={$_("latitude")}
|
||||
bind:value={$form.lat}
|
||||
error={$errors.lat}
|
||||
on:change={handleChange}
|
||||
<TextField name="lat" label={$_("latitude")} error={$errors.lat}
|
||||
></TextField>
|
||||
<TextField
|
||||
name="lon"
|
||||
label={$_("longitude")}
|
||||
bind:value={$form.lon}
|
||||
error={$errors.lat}
|
||||
on:change={handleChange}
|
||||
<TextField name="lon" label={$_("longitude")} error={$errors.lat}
|
||||
></TextField>
|
||||
</div>
|
||||
<div>
|
||||
@@ -125,10 +122,10 @@
|
||||
</label>
|
||||
<PhotoPicker
|
||||
id="waypoint-photo-input"
|
||||
parent={$form}
|
||||
parent={$data}
|
||||
on:exif={(e) => getCoordinatesFromPhoto(e.detail)}
|
||||
bind:photos={$form.photos}
|
||||
bind:photoFiles={$form._photos}
|
||||
bind:photos={$data.photos}
|
||||
bind:photoFiles={$data._photos}
|
||||
showThumbnailControls={false}
|
||||
showExifControls={true}
|
||||
></PhotoPicker>
|
||||
|
||||
@@ -83,6 +83,7 @@
|
||||
"elevation-gain": "Höhenunterschied (aufw.)",
|
||||
"elevation-loss": "Höhenunterschied (abw.)",
|
||||
"email": "Email",
|
||||
"email-updated": "",
|
||||
"empty-activities": "{username} hat noch keine Aktivitäten",
|
||||
"empty-bio": "{username} hat noch keine Biographie hinzugefügt",
|
||||
"empty-lists": "{username} hat keine öffentlichen Listen",
|
||||
@@ -175,6 +176,7 @@
|
||||
"no-grid": "Kein Gitter",
|
||||
"no-preference": "Keine Präferenz",
|
||||
"no-results": "Keine Ergebnisse gefunden",
|
||||
"no-routes-added": "",
|
||||
"not-a-valid-email-address": "Keine gültige Email-Adresse",
|
||||
"not-completed": "Nicht abgeschlossen",
|
||||
"notification-list-create": "",
|
||||
|
||||
@@ -83,6 +83,7 @@
|
||||
"elevation-gain": "Elevation Gain",
|
||||
"elevation-loss": "Elevation Loss",
|
||||
"email": "Email",
|
||||
"email-updated": "Email updated",
|
||||
"empty-activities": "{username} has no activity yet",
|
||||
"empty-bio": "{username} has not added a bio yet",
|
||||
"empty-lists": "{username} has no public lists",
|
||||
@@ -175,6 +176,7 @@
|
||||
"no-grid": "No Grid",
|
||||
"no-preference": "No preference",
|
||||
"no-results": "No results found",
|
||||
"no-routes-added": "No routes added",
|
||||
"not-a-valid-email-address": "Not a valid email address",
|
||||
"not-completed": "Not completed",
|
||||
"notification-list-create": "{user} created a new list",
|
||||
|
||||
@@ -83,6 +83,7 @@
|
||||
"elevation-gain": "Gain d'altitude",
|
||||
"elevation-loss": "",
|
||||
"email": "Email",
|
||||
"email-updated": "",
|
||||
"empty-activities": "",
|
||||
"empty-bio": "",
|
||||
"empty-lists": "",
|
||||
@@ -175,6 +176,7 @@
|
||||
"no-grid": "",
|
||||
"no-preference": "Pas de préférence",
|
||||
"no-results": "Pas de résultat",
|
||||
"no-routes-added": "",
|
||||
"not-a-valid-email-address": "Adresse email invalide",
|
||||
"not-completed": "Pas terminé",
|
||||
"notification-list-create": "",
|
||||
|
||||
@@ -83,6 +83,7 @@
|
||||
"elevation-gain": "Magasságnövekedés",
|
||||
"elevation-loss": "",
|
||||
"email": "Email",
|
||||
"email-updated": "",
|
||||
"empty-activities": "",
|
||||
"empty-bio": "",
|
||||
"empty-lists": "",
|
||||
@@ -175,6 +176,7 @@
|
||||
"no-grid": "",
|
||||
"no-preference": "Nincs preferált",
|
||||
"no-results": "Nincs eredmény",
|
||||
"no-routes-added": "",
|
||||
"not-a-valid-email-address": "Érvénytelen e-mail cím",
|
||||
"not-completed": "Nem teljesített",
|
||||
"notification-list-create": "",
|
||||
|
||||
@@ -83,6 +83,7 @@
|
||||
"elevation-gain": "Guadagno di quota",
|
||||
"elevation-loss": "",
|
||||
"email": "Email",
|
||||
"email-updated": "",
|
||||
"empty-activities": "",
|
||||
"empty-bio": "",
|
||||
"empty-lists": "",
|
||||
@@ -175,6 +176,7 @@
|
||||
"no-grid": "",
|
||||
"no-preference": "Nessuna preferenza",
|
||||
"no-results": "Nessun risultato trovato",
|
||||
"no-routes-added": "",
|
||||
"not-a-valid-email-address": "Indirizzo email non valido",
|
||||
"not-completed": "Non completato",
|
||||
"notification-list-create": "",
|
||||
|
||||
@@ -83,6 +83,7 @@
|
||||
"elevation-gain": "Hoogteverschil",
|
||||
"elevation-loss": "",
|
||||
"email": "E-mail",
|
||||
"email-updated": "",
|
||||
"empty-activities": "",
|
||||
"empty-bio": "",
|
||||
"empty-lists": "",
|
||||
@@ -175,6 +176,7 @@
|
||||
"no-grid": "",
|
||||
"no-preference": "Geen voorkeur",
|
||||
"no-results": "Er zijn geen zoekresultaten",
|
||||
"no-routes-added": "",
|
||||
"not-a-valid-email-address": "Het e-mailadres is ongeldig",
|
||||
"not-completed": "Niet voltooid",
|
||||
"notification-list-create": "",
|
||||
|
||||
@@ -83,6 +83,7 @@
|
||||
"elevation-gain": "Wzrost Wysokości",
|
||||
"elevation-loss": "",
|
||||
"email": "Email",
|
||||
"email-updated": "",
|
||||
"empty-activities": "",
|
||||
"empty-bio": "",
|
||||
"empty-lists": "",
|
||||
@@ -175,6 +176,7 @@
|
||||
"no-grid": "",
|
||||
"no-preference": "Brak preferencji",
|
||||
"no-results": "Brak wyników",
|
||||
"no-routes-added": "",
|
||||
"not-a-valid-email-address": "Nieprawidłowy adres email",
|
||||
"not-completed": "Nie dokończono",
|
||||
"notification-list-create": "",
|
||||
|
||||
@@ -83,6 +83,7 @@
|
||||
"elevation-gain": "Ganho de elevação",
|
||||
"elevation-loss": "",
|
||||
"email": "Email",
|
||||
"email-updated": "",
|
||||
"empty-activities": "",
|
||||
"empty-bio": "",
|
||||
"empty-lists": "",
|
||||
@@ -175,6 +176,7 @@
|
||||
"no-grid": "",
|
||||
"no-preference": "Nenhuma preferência",
|
||||
"no-results": "Nenhum resultado encontrado",
|
||||
"no-routes-added": "",
|
||||
"not-a-valid-email-address": "Não um endereço de e-mail válido",
|
||||
"not-completed": "Não preenchido",
|
||||
"notification-list-create": "",
|
||||
|
||||
@@ -83,6 +83,7 @@
|
||||
"elevation-gain": "上升海拔",
|
||||
"elevation-loss": "",
|
||||
"email": "电子邮箱",
|
||||
"email-updated": "",
|
||||
"empty-activities": "",
|
||||
"empty-bio": "",
|
||||
"empty-lists": "",
|
||||
@@ -175,6 +176,7 @@
|
||||
"no-grid": "",
|
||||
"no-preference": "尚未规划",
|
||||
"no-results": "没有找到结果",
|
||||
"no-routes-added": "",
|
||||
"not-a-valid-email-address": "无效电子邮箱地址",
|
||||
"not-completed": "未完成",
|
||||
"notification-list-create": "",
|
||||
|
||||
@@ -2,11 +2,11 @@ import { z, ZodType } from "zod";
|
||||
import type { List } from "../list";
|
||||
|
||||
const ListCreateSchema = z.object({
|
||||
name: z.string(),
|
||||
id: z.string().length(15).optional(),
|
||||
name: z.string().min(1, "required"),
|
||||
public: z.boolean(),
|
||||
description: z.string().optional(),
|
||||
trails: z.array(z.string().length(15)),
|
||||
avatar: z.string().optional(),
|
||||
author: z.string()
|
||||
}) satisfies ZodType<List>
|
||||
|
||||
@@ -17,7 +17,6 @@ const ListUpdateSchema = z.object({
|
||||
trails: z.array(z.string().length(15)).optional(),
|
||||
"trails-": z.string().optional(),
|
||||
"trails+": z.string().optional(),
|
||||
avatar: z.string().optional(),
|
||||
}) satisfies ZodType<Partial<List>>
|
||||
|
||||
export { ListCreateSchema, ListUpdateSchema };
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { SummitLog } from "../summit_log";
|
||||
|
||||
const SummitLogCreateSchema = z.object({
|
||||
id: z.string().length(15).optional(),
|
||||
date: z.string().date(),
|
||||
date: z.string().date().refine((val) => !isNaN(Date.parse(val)), "invalid-date"),
|
||||
text: z.string().optional(),
|
||||
gpx: z.string().optional(),
|
||||
distance: z.number().nonnegative().optional(),
|
||||
@@ -16,7 +16,7 @@ const SummitLogCreateSchema = z.object({
|
||||
}) satisfies ZodType<SummitLog>
|
||||
|
||||
const SummitLogUpdateSchema = z.object({
|
||||
date: z.string().date().optional(),
|
||||
date: z.string().date().refine((val) => !val || !isNaN(Date.parse(val)), "invalid-date").optional(),
|
||||
text: z.string().optional(),
|
||||
gpx: z.string().optional(),
|
||||
distance: z.number().nonnegative().optional(),
|
||||
|
||||
@@ -3,10 +3,11 @@ import type { Trail } from "../trail";
|
||||
|
||||
|
||||
const TrailCreateSchema = z.object({
|
||||
name: z.string(),
|
||||
id: z.string().length(15).optional(),
|
||||
name: z.string().min(1, "required"),
|
||||
description: z.string().optional(),
|
||||
location: z.string().optional(),
|
||||
date: z.string().date(),
|
||||
date: z.string().optional().refine((val) => !val || !isNaN(Date.parse(val)), "invalid-date"),
|
||||
public: z.boolean(),
|
||||
difficulty: z.enum(["easy", "moderate", "difficult"]).optional(),
|
||||
lat: z.number().optional(),
|
||||
@@ -29,7 +30,7 @@ const TrailUpdateSchema = z.object({
|
||||
name: z.string(),
|
||||
description: z.string().optional(),
|
||||
location: z.string().optional(),
|
||||
date: z.string().date(),
|
||||
date: z.string().optional().refine((val) => !val || !isNaN(Date.parse(val)), "invalid-date"),
|
||||
public: z.boolean().optional(),
|
||||
difficulty: z.enum(["easy", "moderate", "difficult"]).optional(),
|
||||
lat: z.number().optional(),
|
||||
|
||||
@@ -17,8 +17,8 @@ const WaypointUpdateSchema = z.object({
|
||||
name: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
text: z.string().optional(),
|
||||
lat: z.number().optional(),
|
||||
lon: z.number().optional(),
|
||||
lat: z.number({coerce: true}).optional(),
|
||||
lon: z.number({coerce: true}).optional(),
|
||||
icon: z.string().optional(),
|
||||
photos: z.array(z.string()),
|
||||
"photos-": z.string().optional(),
|
||||
|
||||
@@ -16,7 +16,7 @@ export class List {
|
||||
author?: UserAnonymous;
|
||||
|
||||
}
|
||||
author?: string;
|
||||
author: string;
|
||||
|
||||
constructor(name: string, trails: Trail[], params?: { description?: string, public?: boolean, avatar?: string, author?: string }) {
|
||||
this.name = name;
|
||||
@@ -24,8 +24,8 @@ export class List {
|
||||
this.expand = { trails: trails };
|
||||
this.trails = trails.map(t => t.id!);
|
||||
this.description = params?.description;
|
||||
this.avatar = params?.description;
|
||||
this.author = params?.author;
|
||||
this.avatar = params?.avatar;
|
||||
this.author = params?.author ?? "000000000000000";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ class SummitLog {
|
||||
elevation_gain?: number
|
||||
elevation_loss?: number
|
||||
duration?: number
|
||||
author?: string;
|
||||
author: string;
|
||||
|
||||
expand?: {
|
||||
gpx_data?: string;
|
||||
@@ -33,6 +33,7 @@ class SummitLog {
|
||||
this._gpx = null
|
||||
this.photos = params?.photos ?? []
|
||||
this._photos = [];
|
||||
this.author = "000000000000000"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ class Trail {
|
||||
}
|
||||
tags?: string[];
|
||||
description?: string;
|
||||
author?: string;
|
||||
author: string;
|
||||
|
||||
constructor(name: string,
|
||||
params?: {
|
||||
@@ -70,10 +70,10 @@ class Trail {
|
||||
this.location = params?.location;
|
||||
this.date = params?.date ?? new Date().toISOString().split('T')[0];
|
||||
this.public = params?.public ?? false
|
||||
this.distance = params?.distance;
|
||||
this.elevation_gain = params?.elevation_gain;
|
||||
this.elevation_loss = params?.elevation_loss;
|
||||
this.duration = params?.duration;
|
||||
this.distance = params?.distance ?? 0;
|
||||
this.elevation_gain = params?.elevation_gain ?? 0;
|
||||
this.elevation_loss = params?.elevation_loss ?? 0;
|
||||
this.duration = params?.duration ?? 0;
|
||||
this.difficulty = params?.difficulty ?? "easy";
|
||||
this.lat = params?.lat;
|
||||
this.lon = params?.lon;
|
||||
@@ -92,6 +92,7 @@ class Trail {
|
||||
this.tags = params?.tags ?? []
|
||||
this.description = params?.description ?? "";
|
||||
this.created = params?.created;
|
||||
this.author = "000000000000000"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { Marker } from "maplibre-gl";
|
||||
import * as M from "maplibre-gl";
|
||||
import { number, object, string } from "yup";
|
||||
|
||||
@@ -12,7 +11,7 @@ class Waypoint {
|
||||
marker?: M.Marker;
|
||||
photos: string[];
|
||||
_photos?: File[];
|
||||
author?: string;
|
||||
author: string;
|
||||
|
||||
constructor(lat: number, lon: number, params?: {
|
||||
id?: string, name?: string, description?: string, icon?: string, marker?: M.Marker, photos?: string[];
|
||||
@@ -26,16 +25,8 @@ class Waypoint {
|
||||
this.marker = params?.marker;
|
||||
this.photos = params?.photos ?? []
|
||||
this._photos = [];
|
||||
this.author = "000000000000000"
|
||||
}
|
||||
}
|
||||
|
||||
const waypointSchema = object<Waypoint>({
|
||||
id: string().optional(),
|
||||
name: string().optional(),
|
||||
description: string().optional(),
|
||||
lat: number().required('Required').typeError('Invalid latitude'),
|
||||
lon: number().required('Required').typeError('Invalid longitude'),
|
||||
icon: string().optional()
|
||||
});
|
||||
|
||||
export { Waypoint, waypointSchema };
|
||||
export { Waypoint };
|
||||
|
||||
@@ -2,14 +2,14 @@ import type { SummitLog } from "$lib/models/summit_log";
|
||||
import { Trail, type TrailFilter, type TrailFilterValues } from "$lib/models/trail";
|
||||
import type { Waypoint } from "$lib/models/waypoint";
|
||||
import { pb } from "$lib/pocketbase";
|
||||
import { deepEqual } from "$lib/util/deep_util";
|
||||
import { getFileURL } from "$lib/util/file_util";
|
||||
import { util } from "$lib/vendor/svelte-form-lib/util";
|
||||
import * as M from "maplibre-gl";
|
||||
import type { Hits } from "meilisearch";
|
||||
import { ClientResponseError, type ListResult } from "pocketbase";
|
||||
import { writable, type Writable } from "svelte/store";
|
||||
import { summit_logs_create, summit_logs_delete, summit_logs_update } from "./summit_log_store";
|
||||
import { waypoints_create, waypoints_delete, waypoints_update } from "./waypoint_store";
|
||||
import type { Hits, SearchResponse } from "meilisearch";
|
||||
|
||||
let trails: Trail[] = []
|
||||
export const trail: Writable<Trail> = writable(new Trail(""));
|
||||
@@ -469,7 +469,7 @@ function compareObjectArrays<T extends { id?: string }>(oldArray: T[], newArray:
|
||||
const oldObj = oldArray.find(oldObj => oldObj.id === newObj.id)
|
||||
if (!oldObj) {
|
||||
newObjects.push(newObj);
|
||||
} else if (!util.deepEqual(newObj, oldObj)) {
|
||||
} else if (!deepEqual(newObj, oldObj)) {
|
||||
updatedObjects.push(newObj);
|
||||
} else {
|
||||
unchangedObjects.push(newObj);
|
||||
|
||||
37
web/src/lib/util/deep_util.ts
Normal file
37
web/src/lib/util/deep_util.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
const has = Object.prototype.hasOwnProperty;
|
||||
|
||||
export function deepEqual(foo: any, bar: any) {
|
||||
var ctor, len;
|
||||
if (foo === bar) return true;
|
||||
|
||||
if (foo && bar && (ctor = foo.constructor) === bar.constructor) {
|
||||
if (ctor === Date) return foo.getTime() === bar.getTime();
|
||||
if (ctor === RegExp) return foo.toString() === bar.toString();
|
||||
|
||||
if (ctor === Array) {
|
||||
if ((len = foo.length) === bar.length) {
|
||||
while (len-- && deepEqual(foo[len], bar[len]));
|
||||
}
|
||||
return len === -1;
|
||||
}
|
||||
|
||||
if (!ctor || typeof foo === 'object') {
|
||||
len = 0;
|
||||
for (ctor in foo) {
|
||||
if (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false;
|
||||
if (!(ctor in bar) || !deepEqual(foo[ctor], bar[ctor])) return false;
|
||||
}
|
||||
return Object.keys(bar).length === len;
|
||||
}
|
||||
}
|
||||
|
||||
return foo !== foo && bar !== bar;
|
||||
}
|
||||
|
||||
export function cloneDeep(foo: any) {
|
||||
try {
|
||||
return structuredClone(foo);
|
||||
} catch (e) {
|
||||
return foo;
|
||||
}
|
||||
}
|
||||
261
web/src/lib/vendor/svelte-form-lib/create-form.js
vendored
261
web/src/lib/vendor/svelte-form-lib/create-form.js
vendored
@@ -1,261 +0,0 @@
|
||||
import {derived, writable, get} from 'svelte/store';
|
||||
import {util} from './util';
|
||||
|
||||
const NO_ERROR = '';
|
||||
const IS_TOUCHED = true;
|
||||
|
||||
function isCheckbox(element) {
|
||||
return element.getAttribute && element.getAttribute('type') === 'checkbox';
|
||||
}
|
||||
|
||||
function isFileInput(element) {
|
||||
return element.getAttribute && element.getAttribute('type') === 'file';
|
||||
}
|
||||
|
||||
function resolveValue(element) {
|
||||
if (isFileInput(element)) {
|
||||
return element.files;
|
||||
} else if (isCheckbox(element)) {
|
||||
return element.checked;
|
||||
} else {
|
||||
return element.value;
|
||||
}
|
||||
}
|
||||
|
||||
export const createForm = (config) => {
|
||||
let initialValues = config.initialValues || {};
|
||||
|
||||
const validationSchema = config.validationSchema;
|
||||
const validateFunction = config.validate;
|
||||
const onSubmit = config.onSubmit;
|
||||
const onError = config.onError;
|
||||
|
||||
const getInitial = {
|
||||
values: () => util.cloneDeep(initialValues),
|
||||
errors: () =>
|
||||
validationSchema
|
||||
? util.getErrorsFromSchema(initialValues, validationSchema.fields)
|
||||
: util.assignDeep(initialValues, NO_ERROR),
|
||||
touched: () => util.assignDeep(initialValues, !IS_TOUCHED),
|
||||
};
|
||||
|
||||
const form = writable(getInitial.values());
|
||||
const errors = writable(getInitial.errors());
|
||||
const touched = writable(getInitial.touched());
|
||||
|
||||
const isSubmitting = writable(false);
|
||||
const isValidating = writable(false);
|
||||
|
||||
const isValid = derived(errors, ($errors) => {
|
||||
const noErrors = util
|
||||
.getValues($errors)
|
||||
.every((field) => field === NO_ERROR);
|
||||
return noErrors;
|
||||
});
|
||||
|
||||
const modified = derived(form, ($form) => {
|
||||
const object = util.assignDeep($form, false);
|
||||
|
||||
for (let key in $form) {
|
||||
object[key] = !util.deepEqual($form[key], initialValues[key]);
|
||||
}
|
||||
|
||||
return object;
|
||||
});
|
||||
|
||||
const isModified = derived(modified, ($modified) => {
|
||||
return util.getValues($modified).includes(true);
|
||||
});
|
||||
|
||||
function validateField(field) {
|
||||
return util
|
||||
.subscribeOnce(form)
|
||||
.then((values) => validateFieldValue(field, values[field]));
|
||||
}
|
||||
|
||||
function validateFieldValue(field, value) {
|
||||
updateTouched(field, true);
|
||||
|
||||
if (validationSchema) {
|
||||
isValidating.set(true);
|
||||
|
||||
return validationSchema
|
||||
.validateAt(field, get(form))
|
||||
.then(() => util.update(errors, field, ''))
|
||||
.catch((error) => util.update(errors, field, error.message))
|
||||
.finally(() => {
|
||||
isValidating.set(false);
|
||||
});
|
||||
}
|
||||
|
||||
if (validateFunction) {
|
||||
isValidating.set(true);
|
||||
return Promise.resolve()
|
||||
.then(() => validateFunction({[field]: value}))
|
||||
.then((errs) =>
|
||||
util.update(errors, field, !util.isNullish(errs) ? errs[field] : ''),
|
||||
)
|
||||
.finally(() => {
|
||||
isValidating.set(false);
|
||||
});
|
||||
}
|
||||
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
function updateValidateField(field, value) {
|
||||
updateField(field, value);
|
||||
return validateFieldValue(field, value);
|
||||
}
|
||||
|
||||
function handleChange(event) {
|
||||
const element = event.target;
|
||||
const field = element.name || element.id;
|
||||
const value = resolveValue(element);
|
||||
|
||||
return updateValidateField(field, value);
|
||||
}
|
||||
|
||||
function handleSubmit(event) {
|
||||
if (event && event.preventDefault) {
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
isSubmitting.set(true);
|
||||
|
||||
return util.subscribeOnce(form).then((values) => {
|
||||
if (typeof validateFunction === 'function') {
|
||||
isValidating.set(true);
|
||||
|
||||
return Promise.resolve()
|
||||
.then(() => validateFunction(values))
|
||||
.then((error) => {
|
||||
if (util.isNullish(error) || util.getValues(error).length === 0) {
|
||||
return clearErrorsAndSubmit(values);
|
||||
} else {
|
||||
errors.set(error);
|
||||
if(onError) {
|
||||
onError(error)
|
||||
}
|
||||
isSubmitting.set(false);
|
||||
}
|
||||
})
|
||||
.finally(() => isValidating.set(false));
|
||||
}
|
||||
|
||||
if (validationSchema) {
|
||||
isValidating.set(true);
|
||||
|
||||
return (
|
||||
validationSchema
|
||||
.validate(values, {abortEarly: false})
|
||||
.then(() => clearErrorsAndSubmit(values))
|
||||
// eslint-disable-next-line unicorn/catch-error-name
|
||||
.catch((yupErrors) => {
|
||||
if (yupErrors && yupErrors.inner) {
|
||||
const updatedErrors = getInitial.errors();
|
||||
|
||||
yupErrors.inner.map((error) =>
|
||||
util.set(updatedErrors, error.path, error.message),
|
||||
);
|
||||
if(onError) {
|
||||
onError(updatedErrors)
|
||||
}
|
||||
errors.set(updatedErrors);
|
||||
}
|
||||
isSubmitting.set(false);
|
||||
})
|
||||
.finally(() => isValidating.set(false))
|
||||
);
|
||||
}
|
||||
|
||||
return clearErrorsAndSubmit(values);
|
||||
});
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
form.set(getInitial.values());
|
||||
errors.set(getInitial.errors());
|
||||
touched.set(getInitial.touched());
|
||||
}
|
||||
|
||||
function clearErrorsAndSubmit(values) {
|
||||
return Promise.resolve()
|
||||
.then(() => errors.set(getInitial.errors()))
|
||||
.then(() => onSubmit(values, form, errors))
|
||||
.finally(() => isSubmitting.set(false));
|
||||
}
|
||||
|
||||
/**
|
||||
* Handler to imperatively update the value of a form field
|
||||
*/
|
||||
function updateField(field, value) {
|
||||
util.update(form, field, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handler to imperatively update the touched value of a form field
|
||||
*/
|
||||
function updateTouched(field, value) {
|
||||
util.update(touched, field, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the initial values and reset form. Used to dynamically display new form values
|
||||
*/
|
||||
function updateInitialValues(newValues) {
|
||||
initialValues = newValues;
|
||||
|
||||
handleReset();
|
||||
}
|
||||
|
||||
return {
|
||||
form,
|
||||
errors,
|
||||
touched,
|
||||
modified,
|
||||
isValid,
|
||||
isSubmitting,
|
||||
isValidating,
|
||||
isModified,
|
||||
handleChange,
|
||||
handleSubmit,
|
||||
handleReset,
|
||||
updateField,
|
||||
updateValidateField,
|
||||
updateTouched,
|
||||
validateField,
|
||||
updateInitialValues,
|
||||
state: derived(
|
||||
[
|
||||
form,
|
||||
errors,
|
||||
touched,
|
||||
modified,
|
||||
isValid,
|
||||
isValidating,
|
||||
isSubmitting,
|
||||
isModified,
|
||||
],
|
||||
([
|
||||
$form,
|
||||
$errors,
|
||||
$touched,
|
||||
$modified,
|
||||
$isValid,
|
||||
$isValidating,
|
||||
$isSubmitting,
|
||||
$isModified,
|
||||
]) => ({
|
||||
form: $form,
|
||||
errors: $errors,
|
||||
touched: $touched,
|
||||
modified: $modified,
|
||||
isValid: $isValid,
|
||||
isSubmitting: $isSubmitting,
|
||||
isValidating: $isValidating,
|
||||
isModified: $isModified,
|
||||
}),
|
||||
),
|
||||
};
|
||||
};
|
||||
103
web/src/lib/vendor/svelte-form-lib/index.d.ts
vendored
103
web/src/lib/vendor/svelte-form-lib/index.d.ts
vendored
@@ -1,103 +0,0 @@
|
||||
/// <reference lib="svelte2tsx" />
|
||||
import type {SvelteComponentTyped} from 'svelte';
|
||||
import type {Readable, Writable} from 'svelte/store';
|
||||
import type {ObjectSchema} from 'yup';
|
||||
|
||||
export type FormProps<Inf = Record<string, unknown>> = {
|
||||
context?: FormState;
|
||||
initialValues?: Inf;
|
||||
onSubmit?: ((values: Inf) => any) | ((values: Inf) => Promise<any>);
|
||||
validate?: (values: Inf) => any | undefined;
|
||||
validationSchema?: ObjectSchema<any>;
|
||||
} & svelte.JSX.HTMLAttributes<HTMLFormElement>;
|
||||
|
||||
type FieldProperties = {
|
||||
name: string;
|
||||
type?: string;
|
||||
value?: string;
|
||||
} & svelte.JSX.HTMLProps<HTMLInputElement>;
|
||||
|
||||
type SelectProperties = {
|
||||
name: string;
|
||||
} & svelte.JSX.HTMLProps<HTMLSelectElement>;
|
||||
|
||||
type ErrorProperties = {
|
||||
name: string;
|
||||
} & svelte.JSX.HTMLProps<HTMLDivElement>;
|
||||
|
||||
type TextareaProperties = {
|
||||
name: string;
|
||||
} & svelte.JSX.HTMLProps<HTMLTextAreaElement>;
|
||||
|
||||
type FormState<Inf = Record<string, any>> = {
|
||||
form: Writable<Inf>;
|
||||
errors: Writable<Record<keyof Inf, string>>;
|
||||
touched: Writable<Record<keyof Inf, boolean>>;
|
||||
modified: Readable<Record<keyof Inf, boolean>>;
|
||||
isValid: Readable<boolean>;
|
||||
isSubmitting: Writable<boolean>;
|
||||
isValidating: Writable<boolean>;
|
||||
isModified: Readable<boolean>;
|
||||
updateField: (field: keyof Inf, value: any) => void;
|
||||
updateValidateField: (field: keyof Inf, value: any) => void;
|
||||
updateTouched: (field: keyof Inf, value: any) => void;
|
||||
validateField: (field: keyof Inf) => Promise<any>;
|
||||
updateInitialValues: (newValues: Inf) => void;
|
||||
handleReset: () => void;
|
||||
state: Readable<{
|
||||
form: Inf;
|
||||
errors: Record<keyof Inf, string>;
|
||||
touched: Record<keyof Inf, boolean>;
|
||||
modified: Record<keyof Inf, boolean>;
|
||||
isValid: boolean;
|
||||
isSubmitting: boolean;
|
||||
isValidating: boolean;
|
||||
isModified: boolean;
|
||||
}>;
|
||||
handleChange: (event: Event) => any;
|
||||
handleSubmit: (event: Event) => any;
|
||||
};
|
||||
|
||||
declare function createForm<Inf = Record<string, any>>(formProperties: {
|
||||
initialValues: Inf;
|
||||
onSubmit: (values: Inf) => any | Promise<any>;
|
||||
onError?: (errors: Record<string, any>) => any | Promise<any>;
|
||||
validate?: (values: Inf) => any | undefined;
|
||||
validationSchema?: ObjectSchema<any>;
|
||||
}): FormState<Inf>;
|
||||
|
||||
declare class Form extends SvelteComponentTyped<
|
||||
FormProps,
|
||||
Record<string, unknown>,
|
||||
{
|
||||
default: FormState;
|
||||
}
|
||||
> {}
|
||||
|
||||
declare class Field extends SvelteComponentTyped<
|
||||
FieldProperties,
|
||||
Record<string, unknown>,
|
||||
Record<string, unknown>
|
||||
> {}
|
||||
|
||||
declare class Textarea extends SvelteComponentTyped<
|
||||
TextareaProperties,
|
||||
Record<string, unknown>,
|
||||
Record<string, unknown>
|
||||
> {}
|
||||
|
||||
declare class Select extends SvelteComponentTyped<
|
||||
SelectProperties,
|
||||
Record<string, unknown>,
|
||||
{default: any}
|
||||
> {}
|
||||
|
||||
declare class ErrorMessage extends SvelteComponentTyped<
|
||||
ErrorProperties,
|
||||
Record<string, unknown>,
|
||||
{default: any}
|
||||
> {}
|
||||
|
||||
declare const key: {};
|
||||
|
||||
export {createForm, key, Form, Field, Select, ErrorMessage, Textarea};
|
||||
1
web/src/lib/vendor/svelte-form-lib/index.js
vendored
1
web/src/lib/vendor/svelte-form-lib/index.js
vendored
@@ -1 +0,0 @@
|
||||
export {createForm} from './create-form';
|
||||
134
web/src/lib/vendor/svelte-form-lib/util.js
vendored
134
web/src/lib/vendor/svelte-form-lib/util.js
vendored
@@ -1,134 +0,0 @@
|
||||
import { dequal as isEqual } from 'dequal/lite';
|
||||
|
||||
function subscribeOnce(observable) {
|
||||
return new Promise((resolve) => {
|
||||
observable.subscribe(resolve)(); // immediately invoke to unsubscribe
|
||||
});
|
||||
}
|
||||
|
||||
function update(object, path, value) {
|
||||
object.update((o) => {
|
||||
set(o, path, value);
|
||||
return o;
|
||||
});
|
||||
}
|
||||
|
||||
function cloneDeep(object) {
|
||||
try {
|
||||
return structuredClone(object);
|
||||
} catch (e) {
|
||||
return object;
|
||||
}
|
||||
}
|
||||
|
||||
function isNullish(value) {
|
||||
return value === undefined || value === null;
|
||||
}
|
||||
|
||||
function isEmpty(object) {
|
||||
return isNullish(object) || Object.keys(object).length <= 0;
|
||||
}
|
||||
|
||||
function getValues(object) {
|
||||
let results = [];
|
||||
|
||||
for (const [, value] of Object.entries(object)) {
|
||||
const values = typeof value === 'object' ? getValues(value) : [value];
|
||||
results = [...results, ...values];
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
// TODO: refactor this so as not to rely directly on yup's API
|
||||
// This should use dependency injection, with a default callback which may assume
|
||||
// yup as the validation schema
|
||||
function getErrorsFromSchema(initialValues, schema, errors = {}) {
|
||||
for (const key in schema) {
|
||||
switch (true) {
|
||||
case schema[key].type === 'object' && !isEmpty(schema[key].fields): {
|
||||
errors[key] = getErrorsFromSchema(
|
||||
initialValues[key],
|
||||
schema[key].fields,
|
||||
{ ...errors[key] },
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
case schema[key].type === 'array': {
|
||||
const values =
|
||||
initialValues && initialValues[key] ? initialValues[key] : [];
|
||||
errors[key] = values.map((value) => {
|
||||
const innerError = getErrorsFromSchema(
|
||||
value,
|
||||
schema[key].innerType.fields,
|
||||
{ ...errors[key] },
|
||||
);
|
||||
|
||||
return Object.keys(innerError).length > 0 ? innerError : '';
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
default: {
|
||||
errors[key] = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
const deepEqual = isEqual;
|
||||
|
||||
function assignDeep(object, value) {
|
||||
if (Array.isArray(object)) {
|
||||
return object.map((o) => assignDeep(o, value));
|
||||
}
|
||||
const copy = {};
|
||||
for (const key in object) {
|
||||
copy[key] =
|
||||
typeof object[key] === 'object' && !isNullish(object[key]) ? assignDeep(object[key], value) : value;
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
function set(object, path, value) {
|
||||
if (new Object(object) !== object) return object;
|
||||
|
||||
if (!Array.isArray(path)) {
|
||||
path = path.toString().match(/[^.[\]]+/g) || [];
|
||||
}
|
||||
|
||||
const result = path
|
||||
.slice(0, -1)
|
||||
// TODO: replace this reduce with something more readable
|
||||
// eslint-disable-next-line unicorn/no-array-reduce
|
||||
.reduce(
|
||||
(accumulator, key, index) =>
|
||||
new Object(accumulator[key]) === accumulator[key]
|
||||
? accumulator[key]
|
||||
: (accumulator[key] =
|
||||
Math.trunc(Math.abs(path[index + 1])) === +path[index + 1]
|
||||
? []
|
||||
: {}),
|
||||
object,
|
||||
);
|
||||
|
||||
result[path[path.length - 1]] = value;
|
||||
|
||||
return object;
|
||||
}
|
||||
|
||||
export const util = {
|
||||
assignDeep,
|
||||
cloneDeep,
|
||||
deepEqual,
|
||||
getErrorsFromSchema,
|
||||
getValues,
|
||||
isEmpty,
|
||||
isNullish,
|
||||
set,
|
||||
subscribeOnce,
|
||||
update,
|
||||
};
|
||||
Reference in New Issue
Block a user