網站導覽

v2.1.0
表單

月曆

以月份呈現可選的日期:可選一天、多天或一段範圍,可顯示一個月份,或並排顯示兩個月份。

本頁內容

月曆以月份呈現可選的日期:可以選一天、一段範圍或多個日期,可以顯示一個月,也可以兩個月並排。它是由按鈕組成的 ARIA 格線:樣式表負責呈現各種狀態,calendar 行為則提供日期、月份切換按鈕和方向鍵操作。月曆本身沒有獨立的背景樣式,可以放在卡片內,或放進彈出面板做成日期選擇器。

月曆

<div class="sheet p-md">  <div class="calendar">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" />        </svg>      </button>      <h3 class="calendar-title" id="cal-title" aria-live="polite">        <button type="button" class="calendar-title-button" aria-description="Choose a month or a year"></button>      </h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" />        </svg>      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="cal-title"></div>  </div></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-react/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-react/native/16/soft/chevron-right'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="sheet p-md">      <div className="calendar">        <div className="calendar-header">          <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Previous month">            <ChevronLeftIcon className="icon" />          </button>          <h3 className="calendar-title" id="cal-title" aria-live="polite">            <button type="button" className="calendar-title-button" aria-description="Choose a month or a year"></button>          </h3>          <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Next month">            <ChevronRightIcon className="icon" />          </button>        </div>        <div className="calendar-grid" role="grid" aria-labelledby="cal-title"></div>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import ChevronLeftIcon from '@master/icons-svelte/native/16/soft/chevron-left'  import ChevronRightIcon from '@master/icons-svelte/native/16/soft/chevron-right'</script><div class="sheet p-md" {@attach attach}>  <div class="calendar">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <ChevronLeftIcon class="icon" />      </button>      <h3 class="calendar-title" id="cal-title" aria-live="polite">        <button type="button" class="calendar-title-button" aria-description="Choose a month or a year"></button>      </h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <ChevronRightIcon class="icon" />      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="cal-title"></div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-vue/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-vue/native/16/soft/chevron-right'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="sheet p-md">    <div class="calendar">      <div class="calendar-header">        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">          <ChevronLeftIcon class="icon" />        </button>        <h3 class="calendar-title" id="cal-title" aria-live="polite">          <button type="button" class="calendar-title-button" aria-description="Choose a month or a year"></button>        </h3>        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">          <ChevronRightIcon class="icon" />        </button>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="cal-title"></div>    </div>  </div></template>
按一下日期即可選取,用兩個按鈕切換月份,也可以將焦點移到日期上,再用方向鍵移動。按一下標題可以跳到其他月份或年份。

標記包含標頭和空白格線。行為會將月份名稱寫入 calendar-title,將星期名稱及各週日期寫入 calendar-grid,並預設顯示今天所在的月份。沒有腳本時,格線會維持標記原有的內容。如果月曆需要在腳本執行前就能閱讀,請像下方的日期範圍範例一樣,在伺服器端產生各週的標記。行為掛載後會取代這些內容。

#月份與年份

上方月曆的標題是一個按鈕,也就是位在 calendar-title 內的 calendar-title-button。按一下它,格線會變成該年的十二個月;再按一下,會變成該十年間的各個年份,前後各多出一年,以淡化的墨色呈現。選取年份後會顯示該年的月份,選取月份後會顯示該月的日期,焦點會落在同一天。Escape 會回到原本的日期檢視。

月份與年份都是同一個格線中的 calendar-period 按鈕,每列三個,沿用日期按鈕的樣式。格線維持六週月份的高度,因此月曆不會跳動。標題始終說明格線目前的位置:November 2026、2026、2020 – 2029。月份切換按鈕在月份檢視中會切換一年,在年份檢視中會切換十年,其名稱取自 labels 選項。在年份檢視中標題按鈕會停用,因為十年已是最上層。

沒有按鈕的標題仍是一般標題,月曆也不會離開日期檢視。這種跳轉適用於只顯示一個月的月曆。

另一種做法是在標頭放原生的月份和年份下拉選單,但我們沒有採用:有些語言的兩個下拉選單加上兩個月份切換按鈕,放不進七個 36px 欄位的總寬度;一百年的清單在下拉選單中要捲很久;而且自訂樣式下拉選單的清單尚未在所有瀏覽器中提供。月份與年份的格線沿用月曆的樣式,並沿用讀者正在使用的按鍵操作。

#狀態

每種狀態都由日期按鈕上的屬性或類別表示。行為會設定這些標記,手寫或由伺服器產生的標記也使用同一套設定。

狀態標記方式外觀
今天aria-current="date"數字下方有一個圓點
已選取aria-selected="true"以墨色填滿,如同勾選的核取方塊
非本月calendar-day-outside淡化的墨色
無法選取disabled停用狀態的墨色

跳轉中的月份或年份也帶有相同的標記:今天所在的月份或年份加上 aria-current="date",包含已選日期的那一個加上 aria-selected="true",在 min 與 max 之間沒有任何日期的則加上 disabled。calendar-period-outside 標示十年範圍前後的年份。

日期會像選單的項目一樣,即時回應指標。選取今天時仍會保留圓點,圓點會採用該日期狀態的墨色。

#日期範圍

日期範圍的兩端以墨色填滿,中間以膠囊標籤底色的色帶相連。起始日使用 calendar-day-range-start,結束日使用 calendar-day-range-end,兩者之間的日期使用 calendar-day-range。範圍內的日期都設為 aria-selected="true"。

這個預覽只使用標記,未掛載腳本,因此可以在「程式碼」檢視中看到各種狀態的寫法。它依照行為產生標記的方式呈現一整個月,包含一段日期範圍、今天和兩個無法選取的日期。

日期範圍

<div class="sheet p-md">  <div class="calendar">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" />        </svg>      </button>      <h3 class="calendar-title" id="range-title" aria-live="polite">November 2026</h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" />        </svg>      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="range-title">      <div class="calendar-week" role="row">        <span class="calendar-weekday" role="columnheader" aria-label="Sunday">Sun</span>        <span class="calendar-weekday" role="columnheader" aria-label="Monday">Mon</span>        <span class="calendar-weekday" role="columnheader" aria-label="Tuesday">Tue</span>        <span class="calendar-weekday" role="columnheader" aria-label="Wednesday">Wed</span>        <span class="calendar-weekday" role="columnheader" aria-label="Thursday">Thu</span>        <span class="calendar-weekday" role="columnheader" aria-label="Friday">Fri</span>        <span class="calendar-weekday" role="columnheader" aria-label="Saturday">Sat</span>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 1, 2026">          1        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 2, 2026">          2        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 3, 2026">          3        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 4, 2026">          4        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 5, 2026">          5        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 6, 2026" disabled>          6        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 7, 2026" disabled>          7        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 8, 2026">          8        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 9, 2026">          9        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 10, 2026">          10        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 11, 2026" aria-current="date">          11        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 12, 2026">          12        </button>        <button type="button" class="calendar-day calendar-day-range-start" role="gridcell" tabindex="0" aria-label="Friday, November 13, 2026" aria-selected="true">          13        </button>        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Saturday, November 14, 2026" aria-selected="true">          14        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Sunday, November 15, 2026" aria-selected="true">          15        </button>        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Monday, November 16, 2026" aria-selected="true">          16        </button>        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Tuesday, November 17, 2026" aria-selected="true">          17        </button>        <button type="button" class="calendar-day calendar-day-range-end" role="gridcell" tabindex="-1" aria-label="Wednesday, November 18, 2026" aria-selected="true">          18        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 19, 2026">          19        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 20, 2026">          20        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 21, 2026">          21        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 22, 2026">          22        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 23, 2026">          23        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 24, 2026">          24        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 25, 2026">          25        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 26, 2026">          26        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 27, 2026">          27        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 28, 2026">          28        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 29, 2026">          29        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 30, 2026">          30        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Tuesday, December 1, 2026">          1        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Wednesday, December 2, 2026">          2        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Thursday, December 3, 2026">          3        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Friday, December 4, 2026">          4        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Saturday, December 5, 2026">          5        </button>      </div>    </div>  </div></div>
import ChevronLeftIcon from '@master/icons-react/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-react/native/16/soft/chevron-right'<div className="sheet p-md">  <div className="calendar">    <div className="calendar-header">      <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <ChevronLeftIcon className="icon" />      </button>      <h3 className="calendar-title" id="range-title" aria-live="polite">November 2026</h3>      <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <ChevronRightIcon className="icon" />      </button>    </div>    <div className="calendar-grid" role="grid" aria-labelledby="range-title">      <div className="calendar-week" role="row">        <span className="calendar-weekday" role="columnheader" aria-label="Sunday">Sun</span>        <span className="calendar-weekday" role="columnheader" aria-label="Monday">Mon</span>        <span className="calendar-weekday" role="columnheader" aria-label="Tuesday">Tue</span>        <span className="calendar-weekday" role="columnheader" aria-label="Wednesday">Wed</span>        <span className="calendar-weekday" role="columnheader" aria-label="Thursday">Thu</span>        <span className="calendar-weekday" role="columnheader" aria-label="Friday">Fri</span>        <span className="calendar-weekday" role="columnheader" aria-label="Saturday">Sat</span>      </div>      <div className="calendar-week" role="row">        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Sunday, November 1, 2026">          1        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Monday, November 2, 2026">          2        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Tuesday, November 3, 2026">          3        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Wednesday, November 4, 2026">          4        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Thursday, November 5, 2026">          5        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Friday, November 6, 2026" disabled>          6        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Saturday, November 7, 2026" disabled>          7        </button>      </div>      <div className="calendar-week" role="row">        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Sunday, November 8, 2026">          8        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Monday, November 9, 2026">          9        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Tuesday, November 10, 2026">          10        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Wednesday, November 11, 2026" aria-current="date">          11        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Thursday, November 12, 2026">          12        </button>        <button type="button" className="calendar-day calendar-day-range-start" role="gridcell" tabIndex={0} aria-label="Friday, November 13, 2026" aria-selected="true">          13        </button>        <button type="button" className="calendar-day calendar-day-range" role="gridcell" tabIndex={-1} aria-label="Saturday, November 14, 2026" aria-selected="true">          14        </button>      </div>      <div className="calendar-week" role="row">        <button type="button" className="calendar-day calendar-day-range" role="gridcell" tabIndex={-1} aria-label="Sunday, November 15, 2026" aria-selected="true">          15        </button>        <button type="button" className="calendar-day calendar-day-range" role="gridcell" tabIndex={-1} aria-label="Monday, November 16, 2026" aria-selected="true">          16        </button>        <button type="button" className="calendar-day calendar-day-range" role="gridcell" tabIndex={-1} aria-label="Tuesday, November 17, 2026" aria-selected="true">          17        </button>        <button type="button" className="calendar-day calendar-day-range-end" role="gridcell" tabIndex={-1} aria-label="Wednesday, November 18, 2026" aria-selected="true">          18        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Thursday, November 19, 2026">          19        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Friday, November 20, 2026">          20        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Saturday, November 21, 2026">          21        </button>      </div>      <div className="calendar-week" role="row">        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Sunday, November 22, 2026">          22        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Monday, November 23, 2026">          23        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Tuesday, November 24, 2026">          24        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Wednesday, November 25, 2026">          25        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Thursday, November 26, 2026">          26        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Friday, November 27, 2026">          27        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Saturday, November 28, 2026">          28        </button>      </div>      <div className="calendar-week" role="row">        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Sunday, November 29, 2026">          29        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Monday, November 30, 2026">          30        </button>        <button type="button" className="calendar-day calendar-day-outside" role="gridcell" tabIndex={-1} aria-label="Tuesday, December 1, 2026">          1        </button>        <button type="button" className="calendar-day calendar-day-outside" role="gridcell" tabIndex={-1} aria-label="Wednesday, December 2, 2026">          2        </button>        <button type="button" className="calendar-day calendar-day-outside" role="gridcell" tabIndex={-1} aria-label="Thursday, December 3, 2026">          3        </button>        <button type="button" className="calendar-day calendar-day-outside" role="gridcell" tabIndex={-1} aria-label="Friday, December 4, 2026">          4        </button>        <button type="button" className="calendar-day calendar-day-outside" role="gridcell" tabIndex={-1} aria-label="Saturday, December 5, 2026">          5        </button>      </div>    </div>  </div></div>
<script>  import ChevronLeftIcon from '@master/icons-svelte/native/16/soft/chevron-left'  import ChevronRightIcon from '@master/icons-svelte/native/16/soft/chevron-right'</script><div class="sheet p-md">  <div class="calendar">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <ChevronLeftIcon class="icon" />      </button>      <h3 class="calendar-title" id="range-title" aria-live="polite">November 2026</h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <ChevronRightIcon class="icon" />      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="range-title">      <div class="calendar-week" role="row">        <span class="calendar-weekday" role="columnheader" aria-label="Sunday">Sun</span>        <span class="calendar-weekday" role="columnheader" aria-label="Monday">Mon</span>        <span class="calendar-weekday" role="columnheader" aria-label="Tuesday">Tue</span>        <span class="calendar-weekday" role="columnheader" aria-label="Wednesday">Wed</span>        <span class="calendar-weekday" role="columnheader" aria-label="Thursday">Thu</span>        <span class="calendar-weekday" role="columnheader" aria-label="Friday">Fri</span>        <span class="calendar-weekday" role="columnheader" aria-label="Saturday">Sat</span>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 1, 2026">          1        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 2, 2026">          2        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 3, 2026">          3        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 4, 2026">          4        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 5, 2026">          5        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 6, 2026" disabled>          6        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 7, 2026" disabled>          7        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 8, 2026">          8        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 9, 2026">          9        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 10, 2026">          10        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 11, 2026" aria-current="date">          11        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 12, 2026">          12        </button>        <button type="button" class="calendar-day calendar-day-range-start" role="gridcell" tabindex="0" aria-label="Friday, November 13, 2026" aria-selected="true">          13        </button>        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Saturday, November 14, 2026" aria-selected="true">          14        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Sunday, November 15, 2026" aria-selected="true">          15        </button>        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Monday, November 16, 2026" aria-selected="true">          16        </button>        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Tuesday, November 17, 2026" aria-selected="true">          17        </button>        <button type="button" class="calendar-day calendar-day-range-end" role="gridcell" tabindex="-1" aria-label="Wednesday, November 18, 2026" aria-selected="true">          18        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 19, 2026">          19        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 20, 2026">          20        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 21, 2026">          21        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 22, 2026">          22        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 23, 2026">          23        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 24, 2026">          24        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 25, 2026">          25        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 26, 2026">          26        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 27, 2026">          27        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 28, 2026">          28        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 29, 2026">          29        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 30, 2026">          30        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Tuesday, December 1, 2026">          1        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Wednesday, December 2, 2026">          2        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Thursday, December 3, 2026">          3        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Friday, December 4, 2026">          4        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Saturday, December 5, 2026">          5        </button>      </div>    </div>  </div></div>
<script setup>import ChevronLeftIcon from '@master/icons-vue/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-vue/native/16/soft/chevron-right'</script><template>  <div class="sheet p-md">    <div class="calendar">      <div class="calendar-header">        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">          <ChevronLeftIcon class="icon" />        </button>        <h3 class="calendar-title" id="range-title" aria-live="polite">November 2026</h3>        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">          <ChevronRightIcon class="icon" />        </button>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="range-title">        <div class="calendar-week" role="row">          <span class="calendar-weekday" role="columnheader" aria-label="Sunday">Sun</span>          <span class="calendar-weekday" role="columnheader" aria-label="Monday">Mon</span>          <span class="calendar-weekday" role="columnheader" aria-label="Tuesday">Tue</span>          <span class="calendar-weekday" role="columnheader" aria-label="Wednesday">Wed</span>          <span class="calendar-weekday" role="columnheader" aria-label="Thursday">Thu</span>          <span class="calendar-weekday" role="columnheader" aria-label="Friday">Fri</span>          <span class="calendar-weekday" role="columnheader" aria-label="Saturday">Sat</span>        </div>        <div class="calendar-week" role="row">          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 1, 2026">            1          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 2, 2026">            2          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 3, 2026">            3          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 4, 2026">            4          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 5, 2026">            5          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 6, 2026" disabled>            6          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 7, 2026" disabled>            7          </button>        </div>        <div class="calendar-week" role="row">          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 8, 2026">            8          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 9, 2026">            9          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 10, 2026">            10          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 11, 2026" aria-current="date">            11          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 12, 2026">            12          </button>          <button type="button" class="calendar-day calendar-day-range-start" role="gridcell" tabindex="0" aria-label="Friday, November 13, 2026" aria-selected="true">            13          </button>          <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Saturday, November 14, 2026" aria-selected="true">            14          </button>        </div>        <div class="calendar-week" role="row">          <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Sunday, November 15, 2026" aria-selected="true">            15          </button>          <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Monday, November 16, 2026" aria-selected="true">            16          </button>          <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Tuesday, November 17, 2026" aria-selected="true">            17          </button>          <button type="button" class="calendar-day calendar-day-range-end" role="gridcell" tabindex="-1" aria-label="Wednesday, November 18, 2026" aria-selected="true">            18          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 19, 2026">            19          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 20, 2026">            20          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 21, 2026">            21          </button>        </div>        <div class="calendar-week" role="row">          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 22, 2026">            22          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 23, 2026">            23          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 24, 2026">            24          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 25, 2026">            25          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 26, 2026">            26          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 27, 2026">            27          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 28, 2026">            28          </button>        </div>        <div class="calendar-week" role="row">          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 29, 2026">            29          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 30, 2026">            30          </button>          <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Tuesday, December 1, 2026">            1          </button>          <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Wednesday, December 2, 2026">            2          </button>          <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Thursday, December 3, 2026">            3          </button>          <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Friday, December 4, 2026">            4          </button>          <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Saturday, December 5, 2026">            5          </button>        </div>      </div>    </div>  </div></template>

色帶透過以下做法維持連續的外觀:

  • 欄與欄之間沒有間距,色帶可以跨越相鄰的儲存格。列與列之間保留 2px,讓每週各自形成一段色帶。
  • 日期範圍延續到下一週時,色帶在本週末端以圓角收尾。
  • 色帶在範圍兩端各覆蓋朝向範圍內側的半個儲存格,以墨色填滿的日期按鈕則獨立疊在色帶上方。因此色帶會接到按鈕中央,而不是止於按鈕的圓角邊緣。

啟用 range 選項即可選取日期範圍。第一次按下時設定起點,第二次設定終點,第三次則開始新的範圍。若第二次選的日期比較早,行為會將兩個日期按先後排序。

選取日期範圍

<div class="sheet p-md">  <div class="calendar" id="stay">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" />        </svg>      </button>      <h3 class="calendar-title" id="stay-title" aria-live="polite"></h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" />        </svg>      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="stay-title"></div>  </div></div><script>addEventListener('DOMContentLoaded', function () {MasterUI.calendar(document.getElementById('stay'), { range: true, value: ['2026-11-13', '2026-11-18'] })})</script><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach, calendar } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-react/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-react/native/16/soft/chevron-right'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => {    const detach = [      attach(root.current!),      calendar(document.getElementById('stay')!, { range: true, value: ['2026-11-13', '2026-11-18'] }),    ]    return () => detach.forEach(stop => stop())  }, [])  return (    <div ref={root} className="sheet p-md">      <div className="calendar" id="stay">        <div className="calendar-header">          <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Previous month">            <ChevronLeftIcon className="icon" />          </button>          <h3 className="calendar-title" id="stay-title" aria-live="polite"></h3>          <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Next month">            <ChevronRightIcon className="icon" />          </button>        </div>        <div className="calendar-grid" role="grid" aria-labelledby="stay-title"></div>      </div>    </div>  )}
<script>  import { attach, calendar } from '@master/ui/behaviors'  import ChevronLeftIcon from '@master/icons-svelte/native/16/soft/chevron-left'  import ChevronRightIcon from '@master/icons-svelte/native/16/soft/chevron-right'  function mounted(root) {    const detach = [      attach(root),      calendar(document.getElementById('stay'), { range: true, value: ['2026-11-13', '2026-11-18'] }),    ]    return () => detach.forEach(stop => stop())  }</script><div class="sheet p-md" {@attach mounted}>  <div class="calendar" id="stay">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <ChevronLeftIcon class="icon" />      </button>      <h3 class="calendar-title" id="stay-title" aria-live="polite"></h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <ChevronRightIcon class="icon" />      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="stay-title"></div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach, calendar } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-vue/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-vue/native/16/soft/chevron-right'const root = ref(null)let detach = []onMounted(() => {  detach = [    attach(root.value),    calendar(document.getElementById('stay'), { range: true, value: ['2026-11-13', '2026-11-18'] }),  ]})onUnmounted(() => detach.forEach(stop => stop()))</script><template>  <div ref="root" class="sheet p-md">    <div class="calendar" id="stay">      <div class="calendar-header">        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">          <ChevronLeftIcon class="icon" />        </button>        <h3 class="calendar-title" id="stay-title" aria-live="polite"></h3>        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">          <ChevronRightIcon class="icon" />        </button>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="stay-title"></div>    </div>  </div></template>
按一下日期設定起點,再按一下另一個日期設定終點。

attach() 不會傳入任何選項,因此這個預覽會在 attach() 執行後自行呼叫 calendar。對同一個根元素再次呼叫時,第二次掛載的行為會取代第一次。MasterUI 是預覽載入的套件組合。在專案中,請依照行為一節的範例匯入 calendar。

#多個日期

使用 multiple 選項時,行為可以選取任意數量的不連續日期。按一下、Enter 或 Space 會切換日期的選取狀態,每個已選日期都帶有 aria-selected="true",格線則帶有 aria-multiselectable="true"。值是已選日期的清單,格式為 YYYY-MM-DD 並經過排序,每次變更都會派送所有已選日期。

多個日期

<div class="sheet p-md">  <div class="calendar" id="shifts">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" />        </svg>      </button>      <h3 class="calendar-title" id="shifts-title" aria-live="polite"></h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" />        </svg>      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="shifts-title"></div>  </div></div><script>addEventListener('DOMContentLoaded', function () {MasterUI.calendar(document.getElementById('shifts'), {  multiple: true,  value: ['2026-11-09', '2026-11-12', '2026-11-20'],  disabled: function (date) { return date.getDay() === 0 || date.getDay() === 6 }})})</script><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach, calendar } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-react/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-react/native/16/soft/chevron-right'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => {    const detach = [      attach(root.current!),      calendar(document.getElementById('shifts')!, {        multiple: true,        value: ['2026-11-09', '2026-11-12', '2026-11-20'],        disabled: function (date) { return date.getDay() === 0 || date.getDay() === 6 }      }),    ]    return () => detach.forEach(stop => stop())  }, [])  return (    <div ref={root} className="sheet p-md">      <div className="calendar" id="shifts">        <div className="calendar-header">          <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Previous month">            <ChevronLeftIcon className="icon" />          </button>          <h3 className="calendar-title" id="shifts-title" aria-live="polite"></h3>          <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Next month">            <ChevronRightIcon className="icon" />          </button>        </div>        <div className="calendar-grid" role="grid" aria-labelledby="shifts-title"></div>      </div>    </div>  )}
<script>  import { attach, calendar } from '@master/ui/behaviors'  import ChevronLeftIcon from '@master/icons-svelte/native/16/soft/chevron-left'  import ChevronRightIcon from '@master/icons-svelte/native/16/soft/chevron-right'  function mounted(root) {    const detach = [      attach(root),      calendar(document.getElementById('shifts'), {        multiple: true,        value: ['2026-11-09', '2026-11-12', '2026-11-20'],        disabled: function (date) { return date.getDay() === 0 || date.getDay() === 6 }      }),    ]    return () => detach.forEach(stop => stop())  }</script><div class="sheet p-md" {@attach mounted}>  <div class="calendar" id="shifts">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <ChevronLeftIcon class="icon" />      </button>      <h3 class="calendar-title" id="shifts-title" aria-live="polite"></h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <ChevronRightIcon class="icon" />      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="shifts-title"></div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach, calendar } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-vue/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-vue/native/16/soft/chevron-right'const root = ref(null)let detach = []onMounted(() => {  detach = [    attach(root.value),    calendar(document.getElementById('shifts'), {      multiple: true,      value: ['2026-11-09', '2026-11-12', '2026-11-20'],      disabled: function (date) { return date.getDay() === 0 || date.getDay() === 6 }    }),  ]})onUnmounted(() => detach.forEach(stop => stop()))</script><template>  <div ref="root" class="sheet p-md">    <div class="calendar" id="shifts">      <div class="calendar-header">        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">          <ChevronLeftIcon class="icon" />        </button>        <h3 class="calendar-title" id="shifts-title" aria-live="polite"></h3>        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">          <ChevronRightIcon class="icon" />        </button>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="shifts-title"></div>    </div>  </div></template>
按一下平日即可選取或取消選取。週末無法選取。

min、max 和 disabled 的作用與選取單一日期時相同。同時設定 range 時,以 range 為準。

#多個月份

兩個月並排可以顯示從一個月跨到另一個月的範圍。每個月都是一個 calendar-month,各有自己的標頭和格線:第一個標頭放切換到上個月的按鈕,最後一個標頭放切換到下個月的按鈕,每個標題都位在自己的格線上方。行為會依序填入各個月份,按鈕則一次讓所有月份一起切換一個月。

兩個月份

<div class="sheet p-md">  <div class="calendar" id="trip">    <div class="calendar-month">      <div class="calendar-header">        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">          <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">            <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" />          </svg>        </button>        <h3 class="calendar-title" id="trip-first" aria-live="polite"></h3>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="trip-first"></div>    </div>    <div class="calendar-month">      <div class="calendar-header">        <h3 class="calendar-title" id="trip-second" aria-live="polite"></h3>        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">          <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">            <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" />          </svg>        </button>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="trip-second"></div>    </div>  </div></div><script>addEventListener('DOMContentLoaded', function () {MasterUI.calendar(document.getElementById('trip'), { range: true, value: ['2026-11-26', '2026-12-04'] })})</script><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach, calendar } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-react/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-react/native/16/soft/chevron-right'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => {    const detach = [      attach(root.current!),      calendar(document.getElementById('trip')!, { range: true, value: ['2026-11-26', '2026-12-04'] }),    ]    return () => detach.forEach(stop => stop())  }, [])  return (    <div ref={root} className="sheet p-md">      <div className="calendar" id="trip">        <div className="calendar-month">          <div className="calendar-header">            <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Previous month">              <ChevronLeftIcon className="icon" />            </button>            <h3 className="calendar-title" id="trip-first" aria-live="polite"></h3>          </div>          <div className="calendar-grid" role="grid" aria-labelledby="trip-first"></div>        </div>        <div className="calendar-month">          <div className="calendar-header">            <h3 className="calendar-title" id="trip-second" aria-live="polite"></h3>            <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Next month">              <ChevronRightIcon className="icon" />            </button>          </div>          <div className="calendar-grid" role="grid" aria-labelledby="trip-second"></div>        </div>      </div>    </div>  )}
<script>  import { attach, calendar } from '@master/ui/behaviors'  import ChevronLeftIcon from '@master/icons-svelte/native/16/soft/chevron-left'  import ChevronRightIcon from '@master/icons-svelte/native/16/soft/chevron-right'  function mounted(root) {    const detach = [      attach(root),      calendar(document.getElementById('trip'), { range: true, value: ['2026-11-26', '2026-12-04'] }),    ]    return () => detach.forEach(stop => stop())  }</script><div class="sheet p-md" {@attach mounted}>  <div class="calendar" id="trip">    <div class="calendar-month">      <div class="calendar-header">        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">          <ChevronLeftIcon class="icon" />        </button>        <h3 class="calendar-title" id="trip-first" aria-live="polite"></h3>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="trip-first"></div>    </div>    <div class="calendar-month">      <div class="calendar-header">        <h3 class="calendar-title" id="trip-second" aria-live="polite"></h3>        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">          <ChevronRightIcon class="icon" />        </button>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="trip-second"></div>    </div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach, calendar } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-vue/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-vue/native/16/soft/chevron-right'const root = ref(null)let detach = []onMounted(() => {  detach = [    attach(root.value),    calendar(document.getElementById('trip'), { range: true, value: ['2026-11-26', '2026-12-04'] }),  ]})onUnmounted(() => detach.forEach(stop => stop()))</script><template>  <div ref="root" class="sheet p-md">    <div class="calendar" id="trip">      <div class="calendar-month">        <div class="calendar-header">          <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">            <ChevronLeftIcon class="icon" />          </button>          <h3 class="calendar-title" id="trip-first" aria-live="polite"></h3>        </div>        <div class="calendar-grid" role="grid" aria-labelledby="trip-first"></div>      </div>      <div class="calendar-month">        <div class="calendar-header">          <h3 class="calendar-title" id="trip-second" aria-live="polite"></h3>          <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">            <ChevronRightIcon class="icon" />          </button>        </div>        <div class="calendar-grid" role="grid" aria-labelledby="trip-second"></div>      </div>    </div>  </div></template>
選取跨越兩個月的範圍,或用方向鍵從一個月移到下一個月。

這些月份共用一個 Tab 停駐點和同一套按鍵操作:在第一個月的最後一天按方向鍵會移到第二個月的第一天,移動超過最後一個月時兩個月會一起切換。不屬於某個月的日期會留白,因為旁邊的月份已顯示那一天;留白讓星期欄位保持對齊。一列放不下時,月份會換行排成一欄。

#日期選擇器

日期選擇器由一個欄位、一個按鈕,以及放在彈出面板內的月曆組成。彈出面板無需腳本即可開啟或關閉,並會相對於按鈕定位。行為會呈現月曆並指出選取的日期,頁面自己的腳本則將日期填入欄位,再關閉彈出面板。

日期選擇器

<div class="field max-w(280) mx-auto">  <label for="starts">Starts</label>  <div class="input-group">    <input class="input-group-field" id="starts" value="2026-11-04" readonly>    <button type="button" class="btn btn-quiet btn-square" popovertarget="starts-calendar" aria-label="Choose a date">      <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">        <rect x="2.5" y="3.5" width="11" height="10.5" rx="1" /><path d="M2.5 6.5L13.5 6.5" /><path d="M5.5 2L5.5 4.5" /><path d="M10.5 2L10.5 4.5" /><circle cx="6" cy="9.5" r="0.5" fill="currentColor" stroke="none" /><circle cx="10" cy="9.5" r="0.5" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="0.5" fill="currentColor" stroke="none" />      </svg>    </button>    <div id="starts-calendar" popover class="popover popover-end">      <div class="calendar">        <div class="calendar-header">          <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">            <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">              <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" />            </svg>          </button>          <h3 class="calendar-title" id="picker-title" aria-live="polite"></h3>          <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">            <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">              <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" />            </svg>          </button>        </div>        <div class="calendar-grid" role="grid" aria-labelledby="picker-title"></div>      </div>    </div>  </div></div><script>addEventListener('DOMContentLoaded', function () {var popover = document.getElementById('starts-calendar')MasterUI.calendar(popover.querySelector('.calendar'), { value: '2026-11-04' })popover.addEventListener('change', function (event) {  document.getElementById('starts').value = event.detail.value  popover.hidePopover()})})</script><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>

月曆的 change 事件會向上冒泡,因此可在彈出面板上監聽。事件的 detail.value 是 YYYY-MM-DD 格式的日期,也是表單所需的日期值格式。

在手機上,或表單只需要一般日期欄位時,使用原生 <input type="date"> 即可讓使用者使用裝置內建的日期選擇器。

#行為

calendar 接收根元素和選項物件,並回傳可卸載此行為的函式。

app.js
import { calendar } from '@master/ui/behaviors/calendar.js'const root = document.querySelector('.calendar')const picker = calendar(root, { value: '2026-11-04', min: '2026-11-01', max: '2026-12-31' })root.addEventListener('change', (event) => console.log(event.detail.value))
選項設定內容
value選取的日期,格式為 YYYY-MM-DD;日期範圍的起訖日期;或使用 multiple 時選取的各個日期
month首次顯示的月份,格式為 YYYY-MM。預設使用所選日期的月份,未選取時使用今天所在的月份
min, max最早和最晚可選的日期,格式為 YYYY-MM-DD。無法再往某個方向切換月份時,該方向的按鈕會停用
range設為 true 即可選取兩個日期及其間的所有日期
multiple設為 true 即可選取任意數量的不連續日期;同時設定時以 range 為準
labels月份與年份檢視中月份切換按鈕的名稱:previousYear、nextYear、previousDecade、nextDecade。預設為英文
weekStart第一欄的星期,星期日為 0,星期六為 6。預設採用地區設定中的每週起始日,瀏覽器無法提供時則使用星期一
locale指定月份和星期名稱所用的 BCP 47 語言標籤。預設採用月曆所在位置的 lang
disabled接收 Date 並判斷該日期是否無法選取的函式
draw代替內建腳本產生格線的函式。呼叫時會傳入要顯示的月份(格式為 YYYY-MM)和檢視:days、months 或 years。在日期檢視中,它寫入該月,並在後續的格線中寫入之後的月份;calendarMonth(month, { offset }) 會提供每個月的內容。在月份或年份檢視中,它寫入 calendarPeriods(month, { view }) 提供的儲存格。請參閱自訂格線
  • 寫入的內容。 行為會寫入星期名稱、所顯示的每個月份的各週日期,以及各月份的名稱;在跳轉中則寫入月份或年份及對應的標題。日期按鈕的 value 會設為該日期,今天會加上 aria-current="date",選取的日期會加上 aria-selected="true" 和適用的範圍類別,無法選取的日期會加上 disabled。完整日期會寫入 aria-label,並用 tabindex 讓其中一天進入 Tab 鍵巡覽順序。使用 draw 時,由樣板或框架產生日期,腳本只負責設定日期的標記。
  • 事件。 選取日期時,根元素會依序派送可向上冒泡的 input 和 change 事件。兩個事件都帶有 detail.value。選取單一日期時,值為 YYYY-MM-DD 格式的日期;選齊範圍兩端後,值為 [start, end];使用 multiple 時,值為排序後的日期清單。選取範圍的第一端時只會派送 input,值為 [start, null]:值已經變動,但要等選取第二端後才算完整。跳轉到月份或年份時不會派送事件。
  • 值。 值由腳本保存,標記中沒有這個值。請透過回傳函式的 value 讀取,例如 picker.value。在選取結束日期前,範圍的終點是 null;使用 multiple 時,未選取任何日期的值是 []。從外部設定值即可選取日期。例如,picker.value = '2026-11-20' 會顯示新日期所在的月份,且不會派送事件。
  • 日期。 採用本地時區與公曆。

#結構

  • calendar-grid 統一定義七欄。每個 calendar-week 都是沿用這些欄位的子格線列,因此星期名稱和日期不用表格也能對齊。
  • calendar-weekday 是欄標題,其 aria-label 使用完整的星期名稱。
  • calendar-day 是帶有 role="gridcell" 的 <button>。
  • calendar-title-button 在標題有按鈕時,是位在 calendar-title 內的 <button>;行為會把標題寫入其中。
  • calendar-period 是跳轉中的月份或年份:帶有 role="gridcell" 的 <button>,值為 YYYY-MM 或 YYYY,每個 calendar-week 放三個。
  • calendar-month 包含多個月份中其中一個月的標頭和格線。

#鍵盤操作

行為讓格線支援日期格線的鍵盤操作。移動超出當月時,月曆會切換到相鄰月份,並將焦點留在移動後的日期。焦點不會停在無法選取的日期,也不會越過 min 或 max。在月份與年份檢視中,方向鍵一次移動一格或一列三格,Enter 會選取並往下切換一層(從年份到月份、從月份到日期)。

按鍵動作
ArrowLeft, ArrowRight將焦點移到前一天或後一天,文字從右向左排列時方向相反。從某月的最後一天會移到下個月的第一天;同時顯示多個月時,會移到旁邊的格線。在月份或年份檢視中,移到前一個或後一個項目
ArrowUp, ArrowDown將焦點移到上一週或下一週的同一個星期幾。在月份或年份檢視中,移到上一列或下一列,也就是往前或往後三個項目
Home, End將焦點移到一週的第一天或最後一天;在月份或年份檢視中,則移到該列的第一個或最後一個項目
PageUp, PageDown顯示上個月或下個月,並將焦點移到同一天。若該月沒有這一天,則移到當月最後一天。在月份檢視中改為顯示前一年或後一年,在年份檢視中則顯示前一個或後一個十年
Shift+PageUp, Shift+PageDown顯示前一年或後一年的同一個月,並將焦點移到同一天
Enter, Space選取目前取得焦點的日期;使用 multiple 時則切換該日期的選取狀態。在月份或年份上按下時,會顯示該月的日期或該年的月份。格子是按鈕,瀏覽器會將按鍵操作轉為點擊
Escape在月份或年份檢視中,返回日期檢視,焦點回到原本的日期。在日期檢視中則不處理,交由包住月曆的元件處理,例如彈出面板
Tab按 Tab 進入格線時,焦點優先落在已選取的日期(有多個時為第一個),其次是今天。兩者皆不在顯示的月份內時,焦點落在所顯示月份的第一天。多個月份的格線合起來只占一個 Tab 停駐點

#無障礙

  • 格線使用 role="grid",並以月份標題作為標籤。每週使用 role="row"。
  • Tab 鍵巡覽順序只包含一天,依序優先使用已選日期(多個時為第一個)、今天,兩者都不在顯示的月份中時則使用顯示月份的第一天。其餘日期設為 tabindex="-1"。多個並排的月份合起來只有一個 Tab 停駐點,每個格線以各自的標題作為標籤。
  • 可選取範圍或多個日期的格線帶有 aria-multiselectable="true"。
  • 標題按鈕以它顯示的標題命名,這個標題也是格線的標籤。請用 aria-description 說明按鈕的作用,例如「選擇月份或年份」,不要用 aria-label,否則格線也會跟著改名。
  • 在標題加上 aria-live="polite",讓螢幕閱讀器在切換月份時播報。
  • 在觸控螢幕上,日期仍維持 36px:格線保持一個月的形狀,日期的大小也仍超過手指所需。
  • 請在月曆旁說明日期的意義:例如以「週末不開放」說明哪些日期無法選取的原因;選取範圍時,也要說明兩端各代表什麼,例如入住日與退房日。停用的日期或墨色的端點都無法傳達這些資訊。

#React、Svelte 和 Vue

calendar 元件使用與行為相同的資料產生月份內容,因此初始 HTML 就包含月曆,也支援從外部設定及讀取所選日期。使用 range 時,值會傳出兩次:選取第一端時是 [start, null],選取第二端時是 [start, end]。它接受 range 和 multiple,以 months 並排顯示多個月份,只顯示一個月時會有標題按鈕;jumpLabel 是該按鈕的說明,labels 是月份與年份檢視中月份切換按鈕的名稱。用 npx master-ui add calendar 將它複製到專案中,並參閱 React、Svelte 和 Vue 了解元件的實作及用法。

ui/calendar.tsx
'use client'import { Fragment, useId, useMemo, useState, type ComponentProps } from 'react'import { calendar, calendarMonth, calendarPeriods, type CalendarLabels, type CalendarView } from '@master/ui/behaviors/calendar.js'import { useBehavior } from './use-behavior'/** A day as `YYYY-MM-DD`; in a range, its two ends, the second null until it is chosen; with `multiple`, the days chosen, sorted. */export type CalendarValue = string | [string, string | null] | string[] | nullexport interface CalendarProps extends Omit<ComponentProps<'div'>, 'defaultValue' | 'children' | 'ref'> {  value?: CalendarValue  defaultValue?: CalendarValue  onValueChange?: (value: CalendarValue) => void  /** Choose two days and every day between them. */  range?: boolean  /** Choose any number of separate days; the value is their list. `range` wins over it. */  multiple?: boolean  /** How many months to show side by side, 1 by default. A calendar of one month has a title that jumps to the months and the years. */  months?: number  /** The first and the last day that can be chosen, as `YYYY-MM-DD`. */  min?: string  max?: string  /** The month to show first, as `YYYY-MM`. The month of the value, or this month, by default. */  month?: string  /** The day in the first column, 0 for Sunday to 6 for Saturday. The locale's own by default. */  weekStart?: number  /** A BCP 47 tag for the names. Give it when the calendar is rendered on a server, so both sides agree. */  locale?: string  /** Says whether a day cannot be chosen. */  disabled?: (date: Date) => boolean  previousLabel?: string  nextLabel?: string  /** What the title button does, said to assistive technology. */  jumpLabel?: string  /** The names of the month buttons while the grid shows months or years. */  labels?: CalendarLabels}/** * A calendar. React writes the months, from the same data the behavior uses, so they are in the first HTML; * the behavior marks today, the chosen days and the day in the tab order, and asks for other months, or for * the months of a year or the years of a decade when the title jumps. */export function Calendar({ value, defaultValue, onValueChange, range, multiple, months = 1, min, max, month, weekStart, locale, disabled, previousLabel = 'Previous month', nextLabel = 'Next month', jumpLabel = 'Choose a month or a year', labels, className, ...root }: CalendarProps) {  const id = useId()  const [first] = useState(value ?? defaultValue)  const [shown, setShown] = useState(() => calendarMonth(month, { value: first }).month)  const [view, setView] = useState<CalendarView>('days')  const count = Math.max(1, Math.floor(months))  // The first value's days are marked in the first render; after that the behavior marks what is chosen.  const grids = useMemo(() => Array.from({ length: count }, (_, offset) => calendarMonth(shown, { weekStart, locale, value: first, range, multiple, offset })), [count, shown, weekStart, locale, first, range, multiple])  const periods = view === 'days' ? null : calendarPeriods(shown, { view, locale })  const ref = useBehavior(calendar, {    value: (first ?? undefined) as string | string[] | undefined,    range,    multiple,    min,    max,    month,    weekStart,    locale,    disabled,    labels,    draw: (next: string, nextView: CalendarView) => { setShown(next); setView(nextView) },  }, { value, onValueChange })  const several = range || multiple || undefined  const previous = (    <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label={previousLabel}>      <svg className="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" /></svg>    </button>  )  const next = (    <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label={nextLabel}>      <svg className="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" /></svg>    </button>  )  return (    <div className={className ? `calendar ${className}` : 'calendar'} ref={ref} {...root}>      {grids.map((data, index) => {        const one = count === 1        const title = `${id}title${index}`        const header = (          <div className="calendar-header">            {index === 0 && previous}            <h3 className="calendar-title" id={title} aria-live="polite">              {one ? <button type="button" className="calendar-title-button" aria-description={jumpLabel}>{periods?.title ?? data.title}</button> : data.title}            </h3>            {index === count - 1 && next}          </div>        )        const grid = (          <div className="calendar-grid" role="grid" aria-labelledby={title} aria-multiselectable={several}>            {one && periods              ? periods.rows.map(row => (                  <div className="calendar-week" role="row" key={row[0]!.value}>                    {row.map(cell => <button type="button" className={cell.outside ? 'calendar-period calendar-period-outside' : 'calendar-period'} role="gridcell" tabIndex={-1} value={cell.value} aria-label={cell.label} key={cell.value}>{cell.text}</button>)}                  </div>                ))              : (                  <>                    <div className="calendar-week" role="row">                      {data.weekdays.map(weekday => <span className="calendar-weekday" role="columnheader" aria-label={weekday.name} key={weekday.name}>{weekday.short}</span>)}                    </div>                    {data.weeks.map(week => (                      <div className="calendar-week" role="row" key={week[0]!.date}>                        {week.map(day => <button type="button" className={['calendar-day', day.outside && 'calendar-day-outside', day.range].filter(Boolean).join(' ')} role="gridcell" tabIndex={day.tab ? 0 : -1} value={day.date} aria-selected={day.selected || undefined} aria-label={day.label} key={day.date}>{day.text}</button>)}                      </div>                    ))}                  </>                )}          </div>        )        // One month is a header and a grid. Each of several is a calendar-month, which keeps its place, so the        // button in its header keeps focus while the months turn.        return one ? <Fragment key={index}>{header}{grid}</Fragment> : <div className="calendar-month" key={index}>{header}{grid}</div>      })}    </div>  )}
ui/Calendar.svelte
<script lang="ts" module>  import type { HTMLAttributes } from 'svelte/elements'  import type { CalendarLabels } from '@master/ui/behaviors/calendar.js'  /** A day as `YYYY-MM-DD`; in a range, its two ends, the second null until it is chosen; with `multiple`, the days chosen, sorted. */  export type CalendarValue = string | [string, string | null] | string[] | null  export interface CalendarProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {    /** What is chosen. Bind it, or leave it out and the pattern keeps its own. */    value?: CalendarValue    onValueChange?: (value: CalendarValue) => void    /** Choose two days and every day between them. */    range?: boolean    /** Choose any number of separate days; the value is their list. `range` wins over it. */    multiple?: boolean    /** How many months to show side by side, 1 by default. A calendar of one month has a title that jumps to the months and the years. */    months?: number    /** The first and the last day that can be chosen, as `YYYY-MM-DD`. */    min?: string    max?: string    /** The month to show first, as `YYYY-MM`. The month of the value, or this month, by default. */    month?: string    /** The day in the first column, 0 for Sunday to 6 for Saturday. The locale's own by default. */    weekStart?: number    /** A BCP 47 tag for the names. Give it when the calendar is rendered on a server, so both sides agree. */    locale?: string    /** Says whether a day cannot be chosen. */    disabled?: (date: Date) => boolean    previousLabel?: string    nextLabel?: string    /** What the title button does, said to assistive technology. */    jumpLabel?: string    /** The names of the month buttons while the grid shows months or years. */    labels?: CalendarLabels  }</script><script lang="ts">  import { untrack } from 'svelte'  import { calendar, calendarMonth, calendarPeriods, type CalendarMonth, type CalendarView } from '@master/ui/behaviors/calendar.js'  import { behavior } from './behavior.svelte.js'  let { value = $bindable(), onValueChange, range, multiple, months = 1, min, max, month, weekStart, locale, disabled, previousLabel = 'Previous month', nextLabel = 'Next month', jumpLabel = 'Choose a month or a year', labels, class: className, ...root }: CalendarProps = $props()  const id = $props.id()  const first = untrack(() => value)  let shown = $state(untrack(() => calendarMonth(month, { value: first }).month))  let view = $state<CalendarView>('days')  const count = $derived(Math.max(1, Math.floor(months)))  // The first value's days are marked in the first render; after that the behavior marks what is chosen.  const grids = $derived(Array.from({ length: count }, (_, offset) => calendarMonth(shown, { weekStart, locale, value: first, range, multiple, offset })))  const periods = $derived(view === 'days' ? null : calendarPeriods(shown, { view, locale }))  const several = $derived(range || multiple || undefined)  const attach = behavior(calendar, () => ({    value: (first ?? undefined) as string | string[] | undefined,    range,    multiple,    min,    max,    month,    weekStart,    locale,    disabled,    labels,    draw: (next: string, nextView: CalendarView) => { shown = next; view = nextView },  }), {    value: () => value,    change: (next) => { value = next; onValueChange?.(next) },  })</script><!--  @component  A calendar. Svelte writes the months, from the same data the behavior uses, so they are in the first HTML;  the behavior marks today, the chosen days and the day in the tab order, and asks for other months, or for  the months of a year or the years of a decade when the title jumps.-->{#snippet previous()}  <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label={previousLabel}>    <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" /></svg>  </button>{/snippet}{#snippet next()}  <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label={nextLabel}>    <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" /></svg>  </button>{/snippet}{#snippet days(data: CalendarMonth)}  <div class="calendar-week" role="row">    {#each data.weekdays as weekday (weekday.name)}      <span class="calendar-weekday" role="columnheader" aria-label={weekday.name}>{weekday.short}</span>    {/each}  </div>  {#each data.weeks as week (week[0]!.date)}    <div class="calendar-week" role="row">      {#each week as day (day.date)}        <button type="button" class={['calendar-day', day.outside && 'calendar-day-outside', day.range]} role="gridcell" tabindex={day.tab ? 0 : -1} value={day.date} aria-selected={day.selected || undefined} aria-label={day.label}>{day.text}</button>      {/each}    </div>  {/each}{/snippet}<div class={['calendar', className]} {@attach attach} {...root}>  {#if count > 1}    <!-- A month keeps its place, so the button in its header keeps focus while the months turn. -->    {#each grids as data, index (index)}      <div class="calendar-month">        <div class="calendar-header">          {#if index === 0}{@render previous()}{/if}          <h3 class="calendar-title" id="{id}title{index}" aria-live="polite">{data.title}</h3>          {#if index === count - 1}{@render next()}{/if}        </div>        <div class="calendar-grid" role="grid" aria-labelledby="{id}title{index}" aria-multiselectable={several}>          {@render days(data)}        </div>      </div>    {/each}  {:else}    <div class="calendar-header">      {@render previous()}      <!-- aria-description is an ARIA 1.3 attribute of every role, which Svelte's element types do not know yet. -->      <h3 class="calendar-title" id="{id}title" aria-live="polite"><button type="button" class="calendar-title-button" {...{ 'aria-description': jumpLabel }}>{periods?.title ?? grids[0]!.title}</button></h3>      {@render next()}    </div>    <div class="calendar-grid" role="grid" aria-labelledby="{id}title" aria-multiselectable={several}>      {#if periods}        {#each periods.rows as row (row[0]!.value)}          <div class="calendar-week" role="row">            {#each row as cell (cell.value)}              <button type="button" class={cell.outside ? 'calendar-period calendar-period-outside' : 'calendar-period'} role="gridcell" tabindex={-1} value={cell.value} aria-label={cell.label}>{cell.text}</button>            {/each}          </div>        {/each}      {:else}        {@render days(grids[0]!)}      {/if}    </div>  {/if}</div>
ui/Calendar.vue
<script lang="ts">/** A day as `YYYY-MM-DD`; in a range, its two ends, the second null until it is chosen; with `multiple`, the days chosen, sorted. */export type CalendarValue = string | [string, string | null] | string[] | null</script><script setup lang="ts">import { computed, shallowRef, useId, useTemplateRef } from 'vue'import { calendar, calendarMonth, calendarPeriods, type CalendarLabels, type CalendarView } from '@master/ui/behaviors/calendar.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const { range, multiple, months = 1, min, max, month, weekStart, locale, disabled, previousLabel = 'Previous month', nextLabel = 'Next month', jumpLabel = 'Choose a month or a year', labels } = defineProps<{  /** Choose two days and every day between them. */  range?: boolean  /** Choose any number of separate days; the value is their list. `range` wins over it. */  multiple?: boolean  /** How many months to show side by side, 1 by default. A calendar of one month has a title that jumps to the months and the years. */  months?: number  /** The first and the last day that can be chosen, as `YYYY-MM-DD`. */  min?: string  max?: string  /** The month to show first, as `YYYY-MM`. The month of the value, or this month, by default. */  month?: string  /** The day in the first column, 0 for Sunday to 6 for Saturday. The locale's own by default. */  weekStart?: number  /** A BCP 47 tag for the names. Give it when the calendar is rendered on a server, so both sides agree. */  locale?: string  /** Says whether a day cannot be chosen. */  disabled?: (date: Date) => boolean  previousLabel?: string  nextLabel?: string  /** What the title button does, said to assistive technology. */  jumpLabel?: string  /** The names of the month buttons while the grid shows months or years. */  labels?: CalendarLabels}>()/** The chosen day, the two ends of a range, or the days chosen with `multiple`: `v-model`. */const model = defineModel<CalendarValue>()/* * A calendar. Vue writes the months, from the same data the behavior uses, so they are in the first HTML; * the behavior marks today, the chosen days and the day in the tab order, and asks for other months, or for * the months of a year or the years of a decade when the title jumps. */const id = useId()const first = model.valueconst shown = shallowRef(calendarMonth(month, { value: first }).month)const view = shallowRef<CalendarView>('days')const count = computed(() => Math.max(1, Math.floor(months)))// The first value's days are marked in the first render; after that the behavior marks what is chosen.const grids = computed(() => Array.from({ length: count.value }, (_, offset) => calendarMonth(shown.value, { weekStart, locale, value: first, range, multiple, offset })))const periods = computed(() => (view.value === 'days' ? null : calendarPeriods(shown.value, { view: view.value, locale })))const several = computed(() => range || multiple || undefined)const root = useTemplateRef<HTMLDivElement>('root')useBehavior(root, calendar, () => ({  value: (first ?? undefined) as string | string[] | undefined,  range,  multiple,  min,  max,  month,  weekStart,  locale,  disabled,  labels,  draw: (next: string, nextView: CalendarView) => {    shown.value = next    view.value = nextView  },}), model)</script><template>  <div ref="root" class="calendar" v-bind="$attrs">    <template v-if="count > 1">      <div v-for="(data, index) in grids" :key="index" class="calendar-month">        <div class="calendar-header">          <button v-if="index === 0" type="button" class="btn btn-quiet btn-square btn-sm" :aria-label="previousLabel">            <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" /></svg>          </button>          <h3 :id="`${id}-title-${index}`" class="calendar-title" aria-live="polite">{{ data.title }}</h3>          <button v-if="index === count - 1" type="button" class="btn btn-quiet btn-square btn-sm" :aria-label="nextLabel">            <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" /></svg>          </button>        </div>        <div class="calendar-grid" role="grid" :aria-labelledby="`${id}-title-${index}`" :aria-multiselectable="several">          <div class="calendar-week" role="row">            <span v-for="weekday in data.weekdays" :key="weekday.name" class="calendar-weekday" role="columnheader" :aria-label="weekday.name">{{ weekday.short }}</span>          </div>          <div v-for="week in data.weeks" :key="week[0]!.date" class="calendar-week" role="row">            <button v-for="day in week" :key="day.date" type="button" class="calendar-day" :class="[{ 'calendar-day-outside': day.outside }, day.range]" role="gridcell" :tabindex="day.tab ? 0 : -1" :value="day.date" :aria-selected="day.selected || undefined" :aria-label="day.label">{{ day.text }}</button>          </div>        </div>      </div>    </template>    <template v-else>      <div class="calendar-header">        <button type="button" class="btn btn-quiet btn-square btn-sm" :aria-label="previousLabel">          <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" /></svg>        </button>        <h3 :id="`${id}-title`" class="calendar-title" aria-live="polite"><button type="button" class="calendar-title-button" :aria-description="jumpLabel">{{ periods?.title ?? grids[0]!.title }}</button></h3>        <button type="button" class="btn btn-quiet btn-square btn-sm" :aria-label="nextLabel">          <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" /></svg>        </button>      </div>      <div class="calendar-grid" role="grid" :aria-labelledby="`${id}-title`" :aria-multiselectable="several">        <template v-if="periods">          <div v-for="row in periods.rows" :key="row[0]!.value" class="calendar-week" role="row">            <button v-for="cell in row" :key="cell.value" type="button" class="calendar-period" :class="{ 'calendar-period-outside': cell.outside }" role="gridcell" :tabindex="-1" :value="cell.value" :aria-label="cell.label">{{ cell.text }}</button>          </div>        </template>        <template v-else>          <div class="calendar-week" role="row">            <span v-for="weekday in grids[0]!.weekdays" :key="weekday.name" class="calendar-weekday" role="columnheader" :aria-label="weekday.name">{{ weekday.short }}</span>          </div>          <div v-for="week in grids[0]!.weeks" :key="week[0]!.date" class="calendar-week" role="row">            <button v-for="day in week" :key="day.date" type="button" class="calendar-day" :class="[{ 'calendar-day-outside': day.outside }, day.range]" role="gridcell" :tabindex="day.tab ? 0 : -1" :value="day.date" :aria-selected="day.selected || undefined" :aria-label="day.label">{{ day.text }}</button>          </div>        </template>      </div>    </template>  </div></template>

#類別

類別說明
calendar月曆本體:標題列下方放置日期格線;顯示多個月時,則並排放置多個 calendar-month,每個月一個
calendar-month並排的多個月份之一,有自己的 calendar-header 和 calendar-grid。不屬於該月的日期會留白,因為旁邊的月份會顯示這些日期。一列放不下時,月份會換行排成一欄
calendar-header格線上方依序放置上個月按鈕、標題和下個月按鈕。顯示多個月時,上個月按鈕放在第一個月的標題列,下個月按鈕放在最後一個月的標題列
calendar-title月份名稱置於兩個按鈕中央。請設定 aria-live="polite",讓輔助技術在月份變更時播報。其中可放置 calendar-title-button
calendar-title-button以按鈕呈現的標題,用於只顯示一個月的月曆。按下後格線會顯示一年的十二個月,再按則顯示十年內的年份,此時按鈕會停用。標題文字由行為寫入按鈕中
calendar-grid七欄的格線,設定 role="grid",並以標題作為標籤。可選取日期範圍或多個日期時,設定 aria-multiselectable="true"。在月份或年份檢視中改為三欄
calendar-week沿格線欄位排列的一列,設定 role="row",可顯示星期名稱、一週的日期,或三個月份或年份
calendar-weekday使用 role="columnheader" 的欄標題,並在 aria-label 填入完整的星期名稱
calendar-day每個日期使用帶有 role="gridcell" 的按鈕。只有一個日期可用 Tab 鍵移入,其餘日期設為 tabindex="-1"。日期值採 YYYY-MM-DD 格式。元件會寫入此值,也能讀取其他程式碼已寫入的日期值
calendar-day-outside以前一個月或下一個月的日期補齊一週,並用較淡的文字顏色顯示搭配 calendar-day 使用
calendar-day-range-start範圍的第一天以墨色顯示,色帶位於朝向範圍的半側。同一天也套用 calendar-day-range-end 時,範圍只有一天搭配 calendar-day 使用
calendar-day-range日期範圍中的中間日期,以膠囊標籤的底色連接各儲存格,並在每週末端收成圓角。搭配 calendar-day 使用
calendar-day-range-end日期範圍的最後一天以墨色標示,色帶只填滿朝向範圍內側的一半搭配 calendar-day 使用
calendar-period月份或年份,使用帶有 role="gridcell" 的按鈕,放在由標題切換出的格線中。外觀與日期相同,四列的總高度與六週相同。月份的值為 YYYY-MM,年份的值為 YYYY
calendar-period-outside十年範圍之前或之後的年份,以較淡的文字顏色顯示,用來補齊各列搭配 calendar-period 使用

#自訂屬性

屬性預設值說明
--calendar-cell2.25rem日期格的寬度與高度,本身已大於手指所需的尺寸
--calendar-day-radiusvar(--radius-control-sm)日期格的圓角

#原始碼

@master/ui/components/calendar.css
/* * Calendar: a month of days to pick from, as an ARIA grid of buttons. * The stylesheet draws every state and leaves the dates and the keys to the script that fills it: today is * aria-current="date" and carries a dot, a chosen day is aria-selected and fills with ink the way a checkbox * does, and a range is a chip-toned band between two ink days. Weeks are rows on a subgrid, so the seven * columns are declared once. It has no surface of its own: put it in a popover for a date picker, or a card. * * The title may hold a button that jumps to the months of the year and the years of a decade: they are cells of * the same grid, three to a row, in the day's material, and the grid keeps the height of a six-week month so the * calendar does not jump with it. Several months side by side are a calendar-month each, wrapping to a column * where the row has no room; there the days outside a month are left blank, since the month beside it shows them. */@layer components.ui {  .calendar {    --calendar-cell: 2.25rem;    --calendar-day-radius: var(--radius-control-sm);    /* The width of a month button, which a title with a button on one side only keeps free on the other. */    --calendar-turn: 2rem;    display: inline-grid;    gap: .5rem;    min-width: 0;    color: var(--color-text-strong);    font: 400 .8125rem/1 var(--font-family-sans);    font-feature-settings: inherit;    font-variant-numeric: tabular-nums;    user-select: none;    -webkit-user-select: none;  }  /* Several months side by side: a column of them where the row has no room. */  .calendar:has(.calendar-month) {    display: inline-flex;    flex-wrap: wrap;    align-items: flex-start;    gap: 1rem 1.5rem;  }  /* One month of several: its header and its grid. */  .calendar-month {    display: grid;    gap: .5rem;    min-width: 0;    /* A day of the month before or after is shown by that month, so here it only keeps its column. */    & .calendar-day-outside {      visibility: hidden;    }  }  /* Previous, the month, next. */  .calendar-header {    display: flex;    align-items: center;    justify-content: space-between;    gap: .5rem;  }  .calendar-title {    flex: 1 1 0;    margin: 0;    color: var(--color-text-strong);    font: var(--font-weight-control) .875rem/1.4 var(--font-family-sans);    font-feature-settings: inherit;    text-align: center;    /* In a month of several the title may have a month button on one side only; it stays over the middle. */    &:first-child {      margin-inline-start: calc(var(--calendar-turn) + .5rem);    }    &:last-child {      margin-inline-end: calc(var(--calendar-turn) + .5rem);    }  }  /* The title as a button: it shows the months of the year, then the years of the decade. */  .calendar-title-button {    display: inline-flex;    align-items: center;    max-width: 100%;    min-height: 2rem;    margin: 0;    padding: 0 .5rem;    border: 0;    border-radius: calc(var(--calendar-day-radius) * var(--corner-scale));    corner-shape: var(--corner-shape);    background: transparent;    color: inherit;    font: inherit;    font-feature-settings: inherit;    appearance: none;    -webkit-tap-highlight-color: transparent;    cursor: pointer;    touch-action: manipulation;    /* Like a day, it answers at once. */    @media (hover: hover) {      &:hover:not(:disabled) {        background: var(--color-surface-chip);      }    }    &:active:not(:disabled) {      background: var(--color-surface-inset-hover);    }    &:focus-visible {      @apply --focus-ring;    }    /* At the decade there is nowhere further to go: it reads as the title it is. */    &:disabled {      cursor: default;    }    /* On touch the target reaches 44px around the title, which keeps its height. */    @media (pointer: coarse) {      position: relative;      &::after {        @apply --touch-target;      }    }  }  /* Seven columns; rows keep 2px apart so a range reads as one band per week. */  .calendar-grid {    display: grid;    grid-template-columns: repeat(7, var(--calendar-cell));    row-gap: 2px;    /* The months or the years: three columns over the same width. */    &:has(.calendar-period) {      grid-template-columns: repeat(3, 1fr);      width: calc(var(--calendar-cell) * 7);      gap: 4px;    }  }  /* A row of the grid: the weekday names, or a week of days, on the grid's own columns. */  .calendar-week {    display: grid;    grid-column: 1 / -1;    grid-template-columns: subgrid;  }  .calendar-weekday {    display: grid;    place-items: center;    height: 1.75rem;    color: var(--color-text-muted);    font-size: .71875rem;    font-weight: 400;  }  /* A day, or a month or a year: a button in a grid cell. */  .calendar-day, .calendar-period {    position: relative;    isolation: isolate;    display: grid;    place-items: center;    width: 100%;    height: var(--calendar-cell);    margin: 0;    padding: 0;    border: 0;    border-radius: calc(var(--calendar-day-radius) * var(--corner-scale));    corner-shape: var(--corner-shape);    background: transparent;    color: inherit;    font: inherit;    font-feature-settings: inherit;    appearance: none;    -webkit-tap-highlight-color: transparent;    cursor: pointer;    touch-action: manipulation;    font-variant-numeric: tabular-nums;    /* A day answers at once, like a row in a menu. */    @media (hover: hover) {      &:hover:not(:disabled, [aria-disabled="true"], [aria-selected="true"], [aria-pressed="true"]) {        background: var(--color-surface-chip);      }    }    /* Pressed: a step deeper than the pointer's tone. */    &:active:not(:disabled, [aria-disabled="true"], [aria-selected="true"], [aria-pressed="true"]) {      background: var(--color-surface-inset-hover);    }    /*     * Today keeps its place in the month with a dot under the number. It keeps the weight of every other day, so     * the number is as wide as it is on any other date.     */    &[aria-current="date"] {      &::after {        content: '';        position: absolute;        inset-block-end: .3125rem;        inset-inline-start: calc(50% - 1.5px);        width: 3px;        height: 3px;        border-radius: 999px;        background: currentColor;      }    }    /* A day of the month before or after, shown to complete a week; a year of the decade before or after. */    &.calendar-day-outside, &.calendar-period-outside {      color: var(--color-text-muted);    }    /* Chosen: ink, with the line of light a checked checkbox has. */    &:is([aria-selected="true"], [aria-pressed="true"]) {      background: var(--color-surface-inverse);      color: var(--color-text-inverse);      box-shadow: var(--shadow-ink-mark);    }    /* Inside a range: a chip-toned band that runs from cell to cell, rounded where a week ends. */    &.calendar-day-range {      border-radius: 0;      background: var(--color-surface-chip);      color: var(--color-text-strong);      box-shadow: none;      &:first-child {        border-start-start-radius: calc(var(--calendar-day-radius) * var(--corner-scale));        border-end-start-radius: calc(var(--calendar-day-radius) * var(--corner-scale));      }      &:last-child {        border-start-end-radius: calc(var(--calendar-day-radius) * var(--corner-scale));        border-end-end-radius: calc(var(--calendar-day-radius) * var(--corner-scale));      }    }    /*     * The ends of a range: the band covers the half of the cell that faces the range, and the ink day sits     * on it as a layer of its own, so the band meets the day's middle and not its rounded edge.     */    &:is(.calendar-day-range-start, .calendar-day-range-end) {      --calendar-band: to right;      border-radius: 0;      background: linear-gradient(var(--calendar-band), transparent 50%, var(--color-surface-chip) 0);      color: var(--color-text-inverse);      box-shadow: none;      &::before {        content: '';        position: absolute;        inset: 0;        z-index: -1;        border-radius: calc(var(--calendar-day-radius) * var(--corner-scale));        corner-shape: var(--corner-shape);        background: var(--color-surface-inverse);        box-shadow: var(--shadow-ink-mark);      }      &:dir(rtl) {        --calendar-band: to left;      }    }    &.calendar-day-range-end {      --calendar-band: to left;      &:dir(rtl) {        --calendar-band: to right;      }    }    /* A range of one day has no band, and a range that ends a week does not run past it. */    &.calendar-day-range-start:is(.calendar-day-range-end, :last-child), &.calendar-day-range-end:first-child {      background: none;    }    &:focus-visible {      @apply --focus-ring;      z-index: 1;    }    &:is(:disabled, [aria-disabled="true"]) {      color: var(--color-text-disabled);      cursor: not-allowed;    }    @media (forced-colors: active) {      /*       * A button marked aria-disabled is not one the platform knows to grey: it is given the system's disabled ink.       * A chosen day keeps its highlighted text, which the rule after this one gives it.       */      &:is(:disabled, [aria-disabled="true"]) {        color: GrayText;      }      &:is([aria-selected="true"], [aria-pressed="true"], .calendar-day-range-start, .calendar-day-range-end) {        background: Highlight;        color: HighlightText;        forced-color-adjust: none;      }      &.calendar-day-range {        outline: 1px solid Highlight;        outline-offset: -1px;      }      /*       * Focus keeps its ring in the system's color. It follows the band's outline, which would otherwise take its       * place on a day inside a range, and it is given a color because the chosen days opt out of forced colors.       */      &:focus-visible {        outline: 2px solid Highlight;        outline-offset: 2px;      }      &::before {        display: none;      }      /* Today's dot is drawn in the current color, which forced colors would turn to the canvas: it keeps the text's. */      &[aria-current="date"]::after {        forced-color-adjust: none;      }    }  }  /*   * A month or a year: four rows as tall as the weekday names and six weeks, so the grid keeps the height of a   * six-week month.   */  .calendar-period {    height: calc((var(--calendar-cell) * 6 + 1.75rem) / 4);    /* The dot of today's month or year keeps the distance it has under a day's number. */    &[aria-current="date"]::after {      inset-block-end: calc(50% - .8125rem);    }  }}