cl-calendar.uvue 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. <template>
  2. <view class="cl-calendar" :class="[pt.className]">
  3. <!-- 年月选择器弹窗 -->
  4. <calendar-picker
  5. :year="currentYear"
  6. :month="currentMonth"
  7. :ref="refs.set('picker')"
  8. @change="onYearMonthChange"
  9. ></calendar-picker>
  10. <!-- 头部导航栏 -->
  11. <view class="cl-calendar__header" v-if="showHeader">
  12. <!-- 上一月按钮 -->
  13. <view
  14. class="cl-calendar__header-prev"
  15. :class="{ 'is-dark': isDark }"
  16. @tap.stop="gotoPrevMonth"
  17. >
  18. <cl-icon name="arrow-left-s-line" :size="16"></cl-icon>
  19. </view>
  20. <!-- 当前年月显示区域 -->
  21. <view class="cl-calendar__header-date" @tap="refs.open('picker')">
  22. <slot name="current-date">
  23. <cl-text :size="18">{{
  24. $t(`{year}年{month}月`, { year: currentYear, month: currentMonth })
  25. }}</cl-text>
  26. </slot>
  27. </view>
  28. <!-- 下一月按钮 -->
  29. <view
  30. class="cl-calendar__header-next"
  31. :class="{ 'is-dark': isDark }"
  32. @tap.stop="gotoNextMonth"
  33. >
  34. <cl-icon name="arrow-right-s-line" :size="16"></cl-icon>
  35. </view>
  36. </view>
  37. <!-- 星期标题行 -->
  38. <view class="cl-calendar__weeks" :style="{ gap: `${cellGap}px` }" v-if="showWeeks">
  39. <view class="cl-calendar__weeks-item" v-for="weekName in weekLabels" :key="weekName">
  40. <cl-text>{{ weekName }}</cl-text>
  41. </view>
  42. </view>
  43. <!-- 日期网格容器 -->
  44. <view
  45. class="cl-calendar__view"
  46. ref="viewRef"
  47. :style="{ height: `${viewHeight}px`, gap: `${cellGap}px` }"
  48. @tap="onTap"
  49. >
  50. <!-- #ifndef APP -->
  51. <view
  52. class="cl-calendar__view-row"
  53. :style="{ gap: `${cellGap}px` }"
  54. v-for="(weekRow, rowIndex) in dateMatrix"
  55. :key="rowIndex"
  56. >
  57. <view
  58. class="cl-calendar__view-cell"
  59. v-for="(dateCell, cellIndex) in weekRow"
  60. :key="cellIndex"
  61. :class="{
  62. 'is-selected': dateCell.isSelected,
  63. 'is-range': dateCell.isRange,
  64. 'is-hide': dateCell.isHide,
  65. 'is-disabled': dateCell.isDisabled,
  66. 'is-today': dateCell.isToday,
  67. 'is-other-month': !dateCell.isCurrentMonth
  68. }"
  69. :style="{
  70. height: cellHeight + 'px',
  71. backgroundColor: getCellBgColor(dateCell)
  72. }"
  73. @click.stop="selectDateCell(dateCell)"
  74. >
  75. <!-- 顶部文本 -->
  76. <cl-text
  77. :size="10"
  78. :color="getCellTextColor(dateCell)"
  79. :pt="{
  80. className: 'absolute top-[4px]'
  81. }"
  82. >{{ dateCell.topText }}</cl-text
  83. >
  84. <!-- 主日期数字 -->
  85. <cl-text
  86. :color="getCellTextColor(dateCell)"
  87. :size="fontSize"
  88. :pt="{
  89. className: 'font-bold'
  90. }"
  91. >{{ dateCell.date }}</cl-text
  92. >
  93. <!-- 底部文本 -->
  94. <cl-text
  95. :size="10"
  96. :color="getCellTextColor(dateCell)"
  97. :pt="{
  98. className: 'absolute bottom-[4px]'
  99. }"
  100. >{{ dateCell.bottomText }}</cl-text
  101. >
  102. </view>
  103. </view>
  104. <!-- #endif -->
  105. </view>
  106. </view>
  107. </template>
  108. <script lang="ts" setup>
  109. import { computed, nextTick, onMounted, ref, watch, type PropType } from "vue";
  110. import { ctx, dayUts, first, isDark, isHarmony, parsePt, useRefs, $t, t } from "@/.cool";
  111. import CalendarPicker from "./picker.uvue";
  112. import type { ClCalendarDateConfig, ClCalendarMode } from "../../types";
  113. import { useSize } from "../../hooks";
  114. defineOptions({
  115. name: "cl-calendar"
  116. });
  117. // 组件属性定义
  118. const props = defineProps({
  119. // 透传样式配置
  120. pt: {
  121. type: Object,
  122. default: () => ({})
  123. },
  124. // 当前选中的日期值(单选模式)
  125. modelValue: {
  126. type: String as PropType<string | null>,
  127. default: null
  128. },
  129. // 选中的日期数组(多选/范围模式)
  130. date: {
  131. type: Array as PropType<string[]>,
  132. default: () => []
  133. },
  134. // 日期选择模式:单选/多选/范围选择
  135. mode: {
  136. type: String as PropType<ClCalendarMode>,
  137. default: "single"
  138. },
  139. // 日期配置
  140. dateConfig: {
  141. type: Array as PropType<ClCalendarDateConfig[]>,
  142. default: () => []
  143. },
  144. // 开始日期,可选日期的开始
  145. start: {
  146. type: String
  147. },
  148. // 结束日期,可选日期的结束
  149. end: {
  150. type: String
  151. },
  152. // 设置年份
  153. year: {
  154. type: Number
  155. },
  156. // 设置月份
  157. month: {
  158. type: Number
  159. },
  160. // 是否显示其他月份的日期
  161. showOtherMonth: {
  162. type: Boolean,
  163. default: true
  164. },
  165. // 是否显示头部导航栏
  166. showHeader: {
  167. type: Boolean,
  168. default: true
  169. },
  170. // 是否显示星期
  171. showWeeks: {
  172. type: Boolean,
  173. default: true
  174. },
  175. // 单元格高度
  176. cellHeight: {
  177. type: Number,
  178. default: 66
  179. },
  180. // 单元格间距
  181. cellGap: {
  182. type: Number,
  183. default: 0
  184. },
  185. // 主色
  186. color: {
  187. type: String,
  188. default: ""
  189. },
  190. // 当前月份日期颜色
  191. textColor: {
  192. type: String,
  193. default: ""
  194. },
  195. // 其他月份日期颜色
  196. textOtherMonthColor: {
  197. type: String,
  198. default: ""
  199. },
  200. // 禁用日期颜色
  201. textDisabledColor: {
  202. type: String,
  203. default: ""
  204. },
  205. // 今天日期颜色
  206. textTodayColor: {
  207. type: String,
  208. default: "#ff6b6b"
  209. },
  210. // 选中日期颜色
  211. textSelectedColor: {
  212. type: String,
  213. default: "#ffffff"
  214. },
  215. // 选中日期背景颜色
  216. bgSelectedColor: {
  217. type: String,
  218. default: ""
  219. },
  220. // 范围选择背景颜色
  221. bgRangeColor: {
  222. type: String,
  223. default: ""
  224. }
  225. });
  226. // 事件发射器定义
  227. const emit = defineEmits(["update:modelValue", "update:date", "change"]);
  228. // 日期单元格数据结构
  229. type DateCell = {
  230. date: string; // 显示的日期数字
  231. isCurrentMonth: boolean; // 是否属于当前显示月份
  232. isToday: boolean; // 是否为今天
  233. isSelected: boolean; // 是否被选中
  234. isRange: boolean; // 是否在选择范围内
  235. fullDate: string; // 完整日期格式 YYYY-MM-DD
  236. isDisabled: boolean; // 是否被禁用
  237. isHide: boolean; // 是否隐藏显示
  238. topText: string; // 顶部文案
  239. bottomText: string; // 底部文案
  240. color: string; // 颜色
  241. };
  242. // 透传样式属性类型
  243. type PassThrough = {
  244. className?: string;
  245. };
  246. // 解析透传样式配置
  247. const pt = computed(() => parsePt<PassThrough>(props.pt));
  248. // 字体大小
  249. const { toScale } = useSize();
  250. // 主色
  251. const color = computed(() => {
  252. if (props.color != "") {
  253. return props.color;
  254. }
  255. return ctx.color["primary-500"] as string;
  256. });
  257. // 单元格高度
  258. const cellHeight = computed(() => props.cellHeight);
  259. // 单元格间距
  260. const cellGap = computed(() => props.cellGap);
  261. // 字体大小
  262. const fontSize = computed(() => {
  263. // #ifdef APP
  264. return toScale(14);
  265. // #endif
  266. // #ifndef APP
  267. return 14;
  268. // #endif
  269. });
  270. // 当前月份日期颜色
  271. const textColor = computed(() => {
  272. if (props.textColor != "") {
  273. return props.textColor;
  274. }
  275. return isDark.value ? "white" : (ctx.color["surface-700"] as string);
  276. });
  277. // 其他月份日期颜色
  278. const textOtherMonthColor = computed(() => {
  279. if (props.textOtherMonthColor != "") {
  280. return props.textOtherMonthColor;
  281. }
  282. return isDark.value
  283. ? (ctx.color["surface-500"] as string)
  284. : (ctx.color["surface-300"] as string);
  285. });
  286. // 禁用日期颜色
  287. const textDisabledColor = computed(() => {
  288. if (props.textDisabledColor != "") {
  289. return props.textDisabledColor;
  290. }
  291. return isDark.value
  292. ? (ctx.color["surface-500"] as string)
  293. : (ctx.color["surface-300"] as string);
  294. });
  295. // 今天日期颜色
  296. const textTodayColor = computed(() => props.textTodayColor);
  297. // 选中日期颜色
  298. const textSelectedColor = computed(() => props.textSelectedColor);
  299. // 选中日期背景颜色
  300. const bgSelectedColor = computed(() => {
  301. if (props.bgSelectedColor != "") {
  302. return props.bgSelectedColor;
  303. }
  304. return color.value;
  305. });
  306. // 范围选择背景颜色
  307. const bgRangeColor = computed(() => {
  308. if (props.bgRangeColor != "") {
  309. return props.bgRangeColor;
  310. }
  311. return isHarmony() ? (ctx.color["primary-50"] as string) : color.value + "11";
  312. });
  313. // 组件引用管理器
  314. const refs = useRefs();
  315. // 日历视图DOM元素引用
  316. const viewRef = ref<UniElement | null>(null);
  317. // 当前显示的年份
  318. const currentYear = ref(0);
  319. // 当前显示的月份
  320. const currentMonth = ref(0);
  321. // 视图高度
  322. const viewHeight = computed(() => {
  323. return cellHeight.value * 6;
  324. });
  325. // 单元格宽度
  326. const cellWidth = ref(0);
  327. // 星期标签数组
  328. const weekLabels = computed(() => {
  329. return [t("周日"), t("周一"), t("周二"), t("周三"), t("周四"), t("周五"), t("周六")];
  330. });
  331. // 日历日期矩阵数据(6行7列)
  332. const dateMatrix = ref<DateCell[][]>([]);
  333. // 当前选中的日期列表
  334. const selectedDates = ref<string[]>([]);
  335. /**
  336. * 获取日历视图元素的位置信息
  337. */
  338. async function getViewRect(): Promise<DOMRect | null> {
  339. return viewRef.value!.getBoundingClientRectAsync();
  340. }
  341. /**
  342. * 判断指定日期是否被选中
  343. * @param dateStr 日期字符串 YYYY-MM-DD
  344. */
  345. function isDateSelected(dateStr: string): boolean {
  346. if (props.mode == "single") {
  347. // 单选模式:检查是否为唯一选中日期
  348. return selectedDates.value[0] == dateStr;
  349. } else {
  350. // 多选/范围模式:检查是否在选中列表中
  351. return selectedDates.value.includes(dateStr);
  352. }
  353. }
  354. /**
  355. * 判断指定日期是否被禁用
  356. * @param dateStr 日期字符串 YYYY-MM-DD
  357. */
  358. function isDateDisabled(dateStr: string): boolean {
  359. // 大于开始日期
  360. if (props.start != null) {
  361. if (dayUts(dateStr).isBefore(dayUts(props.start))) {
  362. return true;
  363. }
  364. }
  365. // 小于结束日期
  366. if (props.end != null) {
  367. if (dayUts(dateStr).isAfter(dayUts(props.end))) {
  368. return true;
  369. }
  370. }
  371. return props.dateConfig.some((config) => config.date == dateStr && config.disabled == true);
  372. }
  373. /**
  374. * 判断指定日期是否在选择范围内(不包括端点)
  375. * @param dateStr 日期字符串 YYYY-MM-DD
  376. */
  377. function isDateInRange(dateStr: string): boolean {
  378. // 仅范围选择模式且已选择两个端点时才有范围
  379. if (props.mode != "range" || selectedDates.value.length != 2) {
  380. return false;
  381. }
  382. const [startDate, endDate] = selectedDates.value;
  383. const currentDate = dayUts(dateStr);
  384. return currentDate.isAfter(startDate) && currentDate.isBefore(endDate);
  385. }
  386. /**
  387. * 获取单元格字体颜色
  388. * @param dateCell 日期单元格数据
  389. * @returns 字体颜色
  390. */
  391. function getCellTextColor(dateCell: DateCell): string {
  392. // 选中的日期文字颜色
  393. if (dateCell.isSelected) {
  394. return textSelectedColor.value;
  395. }
  396. if (dateCell.color != "") {
  397. return dateCell.color;
  398. }
  399. // 范围选择日期颜色
  400. if (dateCell.isRange) {
  401. return color.value;
  402. }
  403. // 禁用的日期颜色
  404. if (dateCell.isDisabled) {
  405. return textDisabledColor.value;
  406. }
  407. // 今天日期颜色
  408. if (dateCell.isToday) {
  409. return textTodayColor.value;
  410. }
  411. // 当前月份日期颜色
  412. if (dateCell.isCurrentMonth) {
  413. return textColor.value;
  414. }
  415. // 其他月份日期颜色
  416. return textOtherMonthColor.value;
  417. }
  418. /**
  419. * 获取单元格背景颜色
  420. * @param dateCell 日期单元格数据
  421. * @returns 背景颜色
  422. */
  423. function getCellBgColor(dateCell: DateCell): string {
  424. if (dateCell.isSelected) {
  425. return bgSelectedColor.value;
  426. }
  427. if (dateCell.isRange) {
  428. return bgRangeColor.value;
  429. }
  430. return "transparent";
  431. }
  432. /**
  433. * 计算并生成日历矩阵数据
  434. * 生成6行7列共42个日期,包含上月末尾和下月开头的日期
  435. */
  436. function calculateDateMatrix() {
  437. const weekRows: DateCell[][] = [];
  438. const todayStr = dayUts().format("YYYY-MM-DD"); // 今天的日期字符串
  439. // 获取当前月第一天
  440. const monthFirstDay = dayUts(`${currentYear.value}-${currentMonth.value}-01`);
  441. const firstDayWeekIndex = monthFirstDay.getDay(); // 第一天是星期几 (0=周日, 6=周六)
  442. // 计算日历显示的起始日期(可能是上个月的日期)
  443. const calendarStartDate = monthFirstDay.subtract(firstDayWeekIndex, "day");
  444. // 生成6周的日期数据(6行 × 7列 = 42天)
  445. let iterateDate = calendarStartDate;
  446. for (let weekIndex = 0; weekIndex < 6; weekIndex++) {
  447. const weekDates: DateCell[] = [];
  448. for (let dayIndex = 0; dayIndex < 7; dayIndex++) {
  449. const fullDateStr = iterateDate.format("YYYY-MM-DD");
  450. const nativeDate = iterateDate.toDate();
  451. const dayNumber = nativeDate.getDate();
  452. // 判断是否属于当前显示月份
  453. const belongsToCurrentMonth =
  454. nativeDate.getMonth() + 1 == currentMonth.value &&
  455. nativeDate.getFullYear() == currentYear.value;
  456. // 日期配置
  457. const dateConfig = props.dateConfig.find((config) => config.date == fullDateStr);
  458. // 构建日期单元格数据
  459. const dateCell = {
  460. date: `${dayNumber}`,
  461. isCurrentMonth: belongsToCurrentMonth,
  462. isToday: fullDateStr == todayStr,
  463. isSelected: isDateSelected(fullDateStr),
  464. isRange: isDateInRange(fullDateStr),
  465. fullDate: fullDateStr,
  466. isDisabled: isDateDisabled(fullDateStr),
  467. isHide: false,
  468. topText: dateConfig?.topText ?? "",
  469. bottomText: dateConfig?.bottomText ?? "",
  470. color: dateConfig?.color ?? ""
  471. } as DateCell;
  472. // 根据配置决定是否隐藏相邻月份的日期
  473. if (!props.showOtherMonth && !belongsToCurrentMonth) {
  474. dateCell.isHide = true;
  475. }
  476. weekDates.push(dateCell);
  477. iterateDate = iterateDate.add(1, "day"); // 移动到下一天
  478. }
  479. weekRows.push(weekDates);
  480. }
  481. dateMatrix.value = weekRows;
  482. }
  483. /**
  484. * 使用Canvas绘制日历(仅APP端)
  485. * Web端使用DOM渲染,APP端使用Canvas提升性能
  486. */
  487. async function renderCalendar() {
  488. // #ifdef APP
  489. await nextTick(); // 等待DOM更新完成
  490. const ctx = viewRef.value!.getDrawableContext();
  491. if (ctx == null) return;
  492. ctx!.reset(); // 清空画布
  493. /**
  494. * 绘制单个日期单元格
  495. * @param dateCell 日期单元格数据
  496. * @param colIndex 列索引 (0-6)
  497. * @param rowIndex 行索引 (0-5)
  498. */
  499. function drawSingleCell(dateCell: DateCell, colIndex: number, rowIndex: number) {
  500. // 计算单元格位置
  501. const cellX = colIndex * cellWidth.value;
  502. const cellY = rowIndex * cellHeight.value;
  503. const centerX = cellX + cellWidth.value / 2;
  504. const centerY = cellY + cellHeight.value / 2;
  505. // 绘制背景(选中状态或范围状态)
  506. if (dateCell.isSelected || dateCell.isRange) {
  507. const padding = cellGap.value; // 使用间距作为内边距
  508. const bgX = cellX + padding;
  509. const bgY = cellY + padding;
  510. const bgWidth = cellWidth.value - padding * 2;
  511. const bgHeight = cellHeight.value - padding * 2;
  512. // 设置背景颜色
  513. if (dateCell.isSelected) {
  514. ctx!.fillStyle = bgSelectedColor.value;
  515. }
  516. if (dateCell.isRange) {
  517. ctx!.fillStyle = bgRangeColor.value;
  518. }
  519. ctx!.fillRect(bgX, bgY, bgWidth, bgHeight); // 绘制背景矩形
  520. }
  521. // 获取单元格文字颜色
  522. const cellTextColor = getCellTextColor(dateCell);
  523. ctx!.textAlign = "center";
  524. // 绘制顶部文本
  525. if (dateCell.topText != "") {
  526. ctx!.font = `${Math.floor(fontSize.value * 0.75)}px sans-serif`;
  527. ctx!.fillStyle = cellTextColor;
  528. const topY = cellY + 16; // 距离顶部
  529. ctx!.fillText(dateCell.topText, centerX, topY);
  530. }
  531. // 绘制主日期数字
  532. ctx!.font = `${fontSize.value}px sans-serif`;
  533. ctx!.fillStyle = cellTextColor;
  534. const textOffsetY = (fontSize.value / 2) * 0.7;
  535. ctx!.fillText(dateCell.date.toString(), centerX, centerY + textOffsetY);
  536. // 绘制底部文本
  537. if (dateCell.bottomText != "") {
  538. ctx!.font = `${Math.floor(fontSize.value * 0.75)}px sans-serif`;
  539. ctx!.fillStyle = cellTextColor;
  540. const bottomY = cellY + cellHeight.value - 8; // 距离底部
  541. ctx!.fillText(dateCell.bottomText, centerX, bottomY);
  542. }
  543. }
  544. // 获取容器尺寸信息
  545. const viewRect = await getViewRect();
  546. if (viewRect == null) {
  547. return;
  548. }
  549. // 计算单元格宽度(总宽度除以7列)
  550. const cellSize = viewRect.width / 7;
  551. // 更新渲染配置
  552. cellWidth.value = cellSize;
  553. // 遍历日期矩阵进行绘制
  554. for (let rowIndex = 0; rowIndex < dateMatrix.value.length; rowIndex++) {
  555. const weekRow = dateMatrix.value[rowIndex];
  556. for (let colIndex = 0; colIndex < weekRow.length; colIndex++) {
  557. const dateCell = weekRow[colIndex];
  558. if (!dateCell.isHide) {
  559. drawSingleCell(dateCell, colIndex, rowIndex);
  560. }
  561. }
  562. }
  563. ctx!.update(); // 更新画布显示
  564. // #endif
  565. }
  566. /**
  567. * 处理日期单元格选择逻辑
  568. * @param dateCell 被点击的日期单元格
  569. */
  570. function selectDateCell(dateCell: DateCell) {
  571. // 隐藏或禁用的日期不可选择
  572. if (dateCell.isHide || dateCell.isDisabled) {
  573. return;
  574. }
  575. if (props.mode == "single") {
  576. // 单选模式:直接替换选中日期
  577. selectedDates.value = [dateCell.fullDate];
  578. emit("update:modelValue", dateCell.fullDate);
  579. } else if (props.mode == "multiple") {
  580. // 多选模式:切换选中状态
  581. const existingIndex = selectedDates.value.indexOf(dateCell.fullDate);
  582. if (existingIndex >= 0) {
  583. // 已选中则移除
  584. selectedDates.value.splice(existingIndex, 1);
  585. } else {
  586. // 未选中则添加
  587. selectedDates.value.push(dateCell.fullDate);
  588. }
  589. } else {
  590. // 范围选择模式
  591. if (selectedDates.value.length == 0) {
  592. // 第一次点击:设置起始日期
  593. selectedDates.value = [dateCell.fullDate];
  594. } else if (selectedDates.value.length == 1) {
  595. // 第二次点击:设置结束日期
  596. const startDate = dayUts(selectedDates.value[0]);
  597. const endDate = dayUts(dateCell.fullDate);
  598. if (endDate.isBefore(startDate)) {
  599. // 结束日期早于开始日期时自动交换
  600. selectedDates.value = [dateCell.fullDate, selectedDates.value[0]];
  601. } else {
  602. selectedDates.value = [selectedDates.value[0], dateCell.fullDate];
  603. }
  604. } else {
  605. // 已有范围时重新开始选择
  606. selectedDates.value = [dateCell.fullDate];
  607. }
  608. }
  609. // 发射更新事件
  610. emit("update:date", [...selectedDates.value]);
  611. emit("change", selectedDates.value);
  612. // 重新计算日历数据并重绘
  613. calculateDateMatrix();
  614. renderCalendar();
  615. }
  616. /**
  617. * 处理年月选择器的变化事件
  618. * @param yearMonthArray [年份, 月份] 数组
  619. */
  620. function onYearMonthChange(yearMonthArray: number[]) {
  621. currentYear.value = yearMonthArray[0];
  622. currentMonth.value = yearMonthArray[1];
  623. // 重新计算日历数据并重绘
  624. calculateDateMatrix();
  625. renderCalendar();
  626. }
  627. /**
  628. * 处理点击事件(APP端点击检测)
  629. */
  630. async function onTap(e: UniPointerEvent) {
  631. // 获取容器位置信息
  632. const viewRect = await getViewRect();
  633. if (viewRect == null) {
  634. return;
  635. }
  636. // 计算触摸点相对于容器的坐标
  637. const relativeX = e.clientX - viewRect.left;
  638. const relativeY = e.clientY - viewRect.top;
  639. // 根据坐标计算对应的行列索引
  640. const columnIndex = Math.floor(relativeX / cellWidth.value);
  641. const rowIndex = Math.floor(relativeY / cellHeight.value);
  642. // 边界检查:确保索引在有效范围内
  643. if (
  644. rowIndex < 0 ||
  645. rowIndex >= dateMatrix.value.length ||
  646. columnIndex < 0 ||
  647. columnIndex >= 7
  648. ) {
  649. return;
  650. }
  651. const targetDateCell = dateMatrix.value[rowIndex][columnIndex];
  652. selectDateCell(targetDateCell);
  653. }
  654. /**
  655. * 切换到上一个月
  656. */
  657. function gotoPrevMonth() {
  658. const [newYear, newMonth] = dayUts(`${currentYear.value}-${currentMonth.value}-01`)
  659. .subtract(1, "month")
  660. .toArray();
  661. currentYear.value = newYear;
  662. currentMonth.value = newMonth;
  663. // 重新计算并渲染日历
  664. calculateDateMatrix();
  665. renderCalendar();
  666. }
  667. /**
  668. * 切换到下一个月
  669. */
  670. function gotoNextMonth() {
  671. const [newYear, newMonth] = dayUts(`${currentYear.value}-${currentMonth.value}-01`)
  672. .add(1, "month")
  673. .toArray();
  674. currentYear.value = newYear;
  675. currentMonth.value = newMonth;
  676. // 重新计算并渲染日历
  677. calculateDateMatrix();
  678. renderCalendar();
  679. }
  680. /**
  681. * 解析选中日期
  682. */
  683. function parseDate(flag: boolean | null = null) {
  684. // 根据选择模式初始化选中日期
  685. if (props.mode == "single") {
  686. selectedDates.value = props.modelValue != null ? [props.modelValue] : [];
  687. } else {
  688. selectedDates.value = [...props.date];
  689. }
  690. // 获取初始显示日期(优先使用选中日期,否则使用当前日期)
  691. let [year, month] = dayUts(first(selectedDates.value)).toArray();
  692. if (flag == true) {
  693. year = props.year ?? year;
  694. month = props.month ?? month;
  695. }
  696. currentYear.value = year;
  697. currentMonth.value = month;
  698. // 计算初始日历数据
  699. calculateDateMatrix();
  700. // 渲染日历视图
  701. renderCalendar();
  702. }
  703. // 组件挂载时的初始化逻辑
  704. onMounted(() => {
  705. // 解析日期
  706. parseDate(true);
  707. // 监听单选模式的值变化
  708. watch(
  709. computed(() => props.modelValue ?? ""),
  710. (newValue: string) => {
  711. selectedDates.value = [newValue];
  712. parseDate();
  713. }
  714. );
  715. // 监听多选/范围模式的值变化
  716. watch(
  717. computed(() => props.date),
  718. (newDateArray: string[]) => {
  719. selectedDates.value = [...newDateArray];
  720. parseDate();
  721. }
  722. );
  723. // 重新渲染
  724. watch(
  725. computed(() => [props.dateConfig, props.showOtherMonth]),
  726. () => {
  727. calculateDateMatrix();
  728. renderCalendar();
  729. },
  730. {
  731. deep: true
  732. }
  733. );
  734. });
  735. </script>
  736. <style lang="scss" scoped>
  737. /* 日历组件主容器 */
  738. .cl-calendar {
  739. @apply relative;
  740. /* 头部导航栏样式 */
  741. &__header {
  742. @apply flex flex-row items-center justify-between p-3 w-full;
  743. /* 上一月/下一月按钮样式 */
  744. &-prev,
  745. &-next {
  746. @apply flex flex-row items-center justify-center rounded-full bg-surface-100;
  747. width: 30px;
  748. height: 30px;
  749. /* 暗色模式适配 */
  750. &.is-dark {
  751. @apply bg-surface-700;
  752. }
  753. }
  754. /* 当前年月显示区域 */
  755. &-date {
  756. @apply flex flex-row items-center justify-center;
  757. }
  758. }
  759. /* 星期标题行样式 */
  760. &__weeks {
  761. @apply flex flex-row;
  762. /* 单个星期标题样式 */
  763. &-item {
  764. @apply flex flex-row items-center justify-center flex-1;
  765. height: 40px;
  766. }
  767. }
  768. /* 日期网格容器样式 */
  769. &__view {
  770. @apply w-full;
  771. // #ifndef APP
  772. /* 日期行样式 */
  773. &-row {
  774. @apply flex flex-row;
  775. }
  776. /* 日期单元格样式 */
  777. &-cell {
  778. @apply flex-1 flex flex-col items-center justify-center relative;
  779. height: 40px;
  780. /* 隐藏状态(相邻月份日期) */
  781. &.is-hide {
  782. opacity: 0;
  783. }
  784. /* 禁用状态 */
  785. &.is-disabled {
  786. @apply opacity-50;
  787. }
  788. }
  789. // #endif
  790. }
  791. }
  792. </style>