fix: 优化日期选择器状态同步与日历列表渲染
continuous-integration/drone/push Build is passing

This commit is contained in:
seahi committed 2026-08-14 18:05:12 +08:00
1 parent 0714b565da
commit 7bc1907e9d
1 file changed
+15 -10
+15 -10
View File
@@ -9,22 +9,25 @@
let isOpen = $state(false); let isOpen = $state(false);
let displayDate = $state(new Date()); let currentMonth = $state(new Date().getMonth());
let currentYear = $state(new Date().getFullYear());
$effect(() => { $effect(() => {
if (isOpen) {
if (value) { if (value) {
const parsed = new Date(value); const parsed = new Date(value);
if (!isNaN(parsed.getTime())) { if (!isNaN(parsed.getTime())) {
displayDate = parsed; currentMonth = parsed.getMonth();
currentYear = parsed.getFullYear();
} }
} else { } else {
displayDate = new Date(); const now = new Date();
currentMonth = now.getMonth();
currentYear = now.getFullYear();
}
} }
}); });
let currentMonth = $state(displayDate.getMonth());
let currentYear = $state(displayDate.getFullYear());
let container: HTMLDivElement; let container: HTMLDivElement;
function handleOutsideClick(e: MouseEvent) { function handleOutsideClick(e: MouseEvent) {
@@ -66,6 +69,9 @@
let daysInMonth = $derived(new Date(currentYear, currentMonth + 1, 0).getDate()); let daysInMonth = $derived(new Date(currentYear, currentMonth + 1, 0).getDate());
let firstDayOfWeek = $derived(new Date(currentYear, currentMonth, 1).getDay()); // 0 is Sunday let firstDayOfWeek = $derived(new Date(currentYear, currentMonth, 1).getDay()); // 0 is Sunday
let emptyDays = $derived(Array.from({ length: firstDayOfWeek }).map((v, i) => i));
let monthDays = $derived(Array.from({ length: daysInMonth }).map((v, i) => i + 1));
const weekDays = ['日', '一', '二', '三', '四', '五', '六']; const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
</script> </script>
@@ -100,16 +106,15 @@
</div> </div>
<div class="calendar-grid"> <div class="calendar-grid">
{#each weekDays as wd} {#each weekDays as wd (wd)}
<div class="weekday">{wd}</div> <div class="weekday">{wd}</div>
{/each} {/each}
{#each Array(firstDayOfWeek) as _} {#each emptyDays as i (i)}
<div class="empty-day"></div> <div class="empty-day"></div>
{/each} {/each}
{#each Array(daysInMonth) as _, i} {#each monthDays as day (day)}
{@const day = i + 1}
{@const isSelected = {@const isSelected =
value === value ===
`${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`} `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`}