flotilla/src/lib/components/DateTimeInput.svelte

78 lines
1.7 KiB
Svelte
Raw Normal View History

2024-09-12 23:56:33 +00:00
<script lang="ts">
import {DateInput} from "date-picker-svelte"
2024-09-23 20:58:01 +00:00
import Icon from "@lib/components/Icon.svelte"
import Button from "@lib/components/Button.svelte"
2024-09-12 23:56:33 +00:00
2025-02-04 00:37:14 +00:00
interface Props {
initialValue?: Date | undefined
value?: Date | undefined
}
let {initialValue = undefined, value = $bindable<Date | undefined>(initialValue)}: Props =
$props()
2024-09-12 23:56:33 +00:00
2025-01-29 01:43:26 +00:00
const pad = (n: number) => ("00" + String(n)).slice(-2)
const defaultTime = `${pad(new Date().getHours())}:00`
const focusDate = () => element.querySelector("input")?.focus()
const syncTime = (d: Date) => {
if (!time) {
time = defaultTime
}
const [hours, minutes] = time.split(":").map(x => parseInt(x))
d.setHours(hours, minutes, 0, 0)
return d
}
const onChange = () => {
if (value) {
value = syncTime(value)
2024-09-12 23:56:33 +00:00
}
}
const clear = () => {
value = undefined
2025-01-29 01:43:26 +00:00
time = ""
}
let time = ""
let element: HTMLElement
$: {
if (value) {
value = syncTime(value)
}
2024-09-12 23:56:33 +00:00
}
</script>
2025-01-29 01:43:26 +00:00
<div class="relative grid grid-cols-2 gap-2" bind:this={element}>
<div class="relative">
<DateInput format="yyyy-MM-dd" placeholder="" bind:value on:change={onChange} />
<div class="absolute right-2 top-0 flex h-12 cursor-pointer items-center gap-2">
{#if value}
<Button on:click={clear} class="h-5">
<Icon icon="close-circle" />
</Button>
{:else}
<Button on:click={focusDate} class="h-5">
<Icon icon="calendar-minimalistic" />
</Button>
{/if}
</div>
2024-09-12 23:56:33 +00:00
</div>
2025-01-29 01:43:26 +00:00
<label class="input input-bordered flex items-center">
<input
list="time-options"
class="grow"
type="time"
step="300"
bind:value={time}
on:change={onChange} />
</label>
</div>