feat(lunar): 双端农历换算层(Go + TS,同作者同算法)

日历要支持「每农历月十五」「农历生日」这类规则。公历与农历的换算不能
自己算,两端各引一个库:Go 用 6tail/lunar-go v1.4.6,前端用同作者的
lunar-javascript 1.7.7 —— 同算法保证两端结果一致(前端要在格子上显示
农历日、在编辑器里预览接下来几次触发)。

为什么要包一层而不直接用库:

**1. 库在非法日期上 panic 而不是返回 error。**
`NewLunarFromYmd(2027, 9, 30)` 直接 panic("only 29 days in lunar year
2027 month 9")。农历月是 29 或 30 天不定,「每月农历三十」这条规则必然
撞上短月份。调度器里一次 panic 就让那条提醒永久卡住。
修法是夹到该月实际天数并返回 clamped 标记 —— 夹而不滚:「每月三十」的
语义是「月末那天」,滚到下月初一会让提醒与前一次只隔一天。

**2. 闰月用负数月份表示**(-6 = 闰六月),这个约定藏在库内部。
2025 有闰六月、2028 有闰五月,2026/2027 没有。AddYears 从闰月出发而
目标年没有同一闰月时退回正月份 —— 静默让重复事件消失更糟。

**3. 按农历推进不能加固定天数。**
农历月 29~30 天、农历年 353~385 天(闰年多一整月),AddDate 近似一年
能偏半个月。

前端另有一个 TS 陷阱:日名有五种前缀形态(初一/十一/二十/廿一/三十),
原来用正则从 toString() 截取时漏了「二十」,20 号会显示整串「七月二十」。
改成查表。

测试:Go 12 例 / TS 37 例。含「同一农历日在六年公历里落到至少 4 个不同
月日上」—— 那正是农历重复存在的理由(公历 yearly 会固定在同一天)。
This commit is contained in:
2026-09-04 06:27:15 +08:00
parent 473c46659a
commit 4d211c84d6
9 changed files with 1085 additions and 1 deletions

7
web/package-lock.json generated
View File

@ -8,6 +8,7 @@
"name": "agentmail-web",
"version": "0.1.0",
"dependencies": {
"lunar-javascript": "1.7.7",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-markdown": "^9.0.1",
@ -2957,6 +2958,12 @@
"yallist": "^3.0.2"
}
},
"node_modules/lunar-javascript": {
"version": "1.7.7",
"resolved": "https://registry.npmmirror.com/lunar-javascript/-/lunar-javascript-1.7.7.tgz",
"integrity": "sha512-u/KYiwPIBo/0bT+WWfU7qO1d+aqeB90Tuy4ErXenr2Gam0QcWeezUvtiOIyXR7HbVnW2I1DKfU0NBvzMZhbVQw==",
"license": "MIT"
},
"node_modules/lz-string": {
"version": "1.5.0",
"resolved": "https://registry.npmmirror.com/lz-string/-/lz-string-1.5.0.tgz",

View File

@ -8,13 +8,14 @@
"build": "vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit",
"test": "node test/markdown-xss.test.mjs && node test/narrow-layout.test.mjs && vitest run",
"test": "node test/markdown-xss.test.mjs && node test/narrow-layout.test.mjs && node test/theme.test.mjs && vitest run",
"test:narrow": "node test/manual/narrow-verify.mjs",
"test:wide": "node test/manual/wide-regression.mjs",
"test:components": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"lunar-javascript": "1.7.7",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-markdown": "^9.0.1",

327
web/src/lib/lunar.ts Normal file
View File

@ -0,0 +1,327 @@
import { Solar, Lunar, LunarYear } from 'lunar-javascript';
/**
* 农历换算与「按农历推进」的重复规则计算。
*
* 这一层是后端 `internal/lunar/lunar.go` 的镜像 —— 两边用的是同一作者
* 6tail的库lunar-javascript / lunar-go换算结果一致。
* 前端需要它是因为**日历格子上要显示农历日**,而且事件编辑器要在保存前
* 预览「这条规则接下来几次落在哪天」。让后端算再拉一次网络请求太慢,
* 而完全不显示农历会让人无法确认规则没被理解错。
*
* 与后端保持同步的两条硬约定:
*
* 1. **闰月用负数月份表示**-6 = 闰六月)。
* 2. **非法日期必须夹取而不是抛错**。库在 `Lunar.fromYmd(2027, 9, 30)`
* 上直接 throw农历月是 29 或 30 天不定),「每月农历三十」这条规则
* 必然撞上 29 天的月份。
*/
/** 一个农历日期。month 为负数表示闰月。 */
export interface LunarDate {
year: number;
month: number;
day: number;
}
/** 公历 Date → 农历日期(只取年月日)。 */
export function fromSolar(d: Date): LunarDate {
const l = Solar.fromYmd(d.getFullYear(), d.getMonth() + 1, d.getDate()).getLunar();
return { year: l.getYear(), month: l.getMonth(), day: l.getDay() };
}
/** 某农历年的闰月0 = 无闰月)。 */
export function leapMonth(year: number): number {
try {
return LunarYear.fromYear(year).getLeapMonth();
} catch {
return 0;
}
}
/**
* 某个农历月有多少天29 或 30
*
* 返回 0 表示该月不存在(例如问一个没有闰六月的年份要闰六月)——
* 这不是异常:「每年农历闰六月十五」在无闰六月的年份本来就无法落地,
* 调用方需要据此跳过而不是猜一个日子。
*/
export function daysInMonth(year: number, month: number): number {
try {
const ly = LunarYear.fromYear(year);
const months = ly.getMonths();
for (const lm of months) {
if (lm.getYear() === year && lm.getMonth() === month) {
return lm.getDayCount();
}
}
} catch {
return 0;
}
return 0;
}
/**
* 农历日期 → 公历 Date带上给定的时分秒。
*
* 日期会被**夹到该农历月的实际天数内**:请求农历三十而该月只有 29 天时
* 返回廿九,而不是抛错也不是滚到下个月初一。
*
* 夹而不滚:「每月农历三十」的语义是「月末那天」,滚到下月初一会让提醒
* 出现在完全错误的日子(且与前一次只隔一天)。
*
* 返回 null 表示该农历月根本不存在(无效的闰月)。
*/
export function toSolar(
d: LunarDate,
hour = 0,
minute = 0,
second = 0
): { date: Date; clamped: boolean } | null {
const days = daysInMonth(d.year, d.month);
if (days === 0) return null;
let day = d.day;
let clamped = false;
if (day > days) {
day = days;
clamped = true;
}
if (day < 1) return null;
try {
const s = Lunar.fromYmd(d.year, d.month, day).getSolar();
return {
date: new Date(s.getYear(), s.getMonth() - 1, s.getDay(), hour, minute, second, 0),
clamped
};
} catch {
return null;
}
}
/**
* 在农历上推进若干个月。
*
* 逐月走而不是「月份数 + n 取模」:中间可能夹着闰月,而闰月是否存在
* 取决于年份,没有闭式公式。
*
* **推进时跳过闰月**:从六月推一个月得七月,不是闰六月。「每月十五」
* 这类规则的用户期望是一年 12 次,把闰月算进去会让闰年多出一次提醒 ——
* 那是农历年的性质,不是提醒的性质。
*/
export function addLunarMonths(d: LunarDate, n: number): LunarDate {
let { year, month } = d;
// 从闰月出发时先归到对应的正月份:闰六月 +1 → 七月
if (month < 0) month = -month;
for (let i = 0; i < n; i++) {
month++;
if (month > 12) {
month = 1;
year++;
}
}
return { year, month, day: d.day };
}
/**
* 在农历上推进若干年,月份与日期保持不变。
*
* 从闰月出发而目标年没有同一个闰月时,退回对应的正月份 ——
* 「去年闰六月十五」在今年最接近的对应日就是六月十五。
* 直接放弃(不再提醒)更糟:那是静默地让重复事件消失。
*/
export function addLunarYears(d: LunarDate, n: number): LunarDate {
const year = d.year + n;
let month = d.month;
if (month < 0 && leapMonth(year) !== -month) {
month = -month;
}
return { year, month, day: d.day };
}
/** 「二〇二六年七月廿二」这样的完整中文农历表示。 */
export function formatLunarFull(d: LunarDate): string {
const days = daysInMonth(d.year, d.month);
if (days === 0) return `农历 ${d.year}-${d.month}-${d.day}(无效)`;
const day = Math.min(d.day, days);
try {
return Lunar.fromYmd(d.year, d.month, day).toString();
} catch {
return `农历 ${d.year}-${d.month}-${d.day}`;
}
}
/**
* 只要月日的简短农历,如「七月廿二」。
*
* 日历格子里用这个:年份已经在页头写了,每格重复一遍挤不下也没意义。
*/
export function formatLunarShort(d: LunarDate): string {
const full = formatLunarFull(d);
// 「二〇二六年」= 4 个数字字 + 「年」
const chars = Array.from(full);
if (chars.length > 5 && chars[4] === '年') {
return chars.slice(5).join('');
}
return full;
}
/**
* 农历日名,如 1 → 初一、20 → 二十、22 → 廿二、30 → 三十。
*
* 用查表而不是从 `Lunar.toString()` 里正则截取:实测日名有五种前缀形态
* (初一/十一/二十/廿一/三十),写一个覆盖全部的正则既难读又容易漏 ——
* 之前那版就漏了「二十」20 号会退化成显示整串「七月二十」。
*/
const LUNAR_DAY_NAMES = [
'', '初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十',
'十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十',
'廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十'
];
export function lunarDayName(day: number): string {
return LUNAR_DAY_NAMES[day] ?? String(day);
}
/**
* 日历格子里显示的农历标记:初一显示月名,其余显示日名。
*
* 每格都写完整「七月廿二」会让格子里全是重复的月份字样,而格子只有
* 几十像素宽。月初那天写月名(如「七月」)就够定位了 —— 纸质日历的惯例。
*/
export function cellLunarLabel(date: Date): string {
const d = fromSolar(date);
if (d.day === 1) {
// 初一:写月名。闰月要带「闰」字,否则闰六月与六月在格子里长得一样
const leap = d.month < 0 ? '闰' : '';
return `${leap}${LUNAR_MONTH_NAMES[Math.abs(d.month)] ?? Math.abs(d.month)}`;
}
return lunarDayName(d.day);
}
/** 农历月名。十一/十二月习惯写「冬月」「腊月」,与 lunar-javascript 一致。 */
const LUNAR_MONTH_NAMES = [
'', '正', '二', '三', '四', '五', '六', '七', '八', '九', '十', '冬', '腊'
];
/** 公历 Date → 「2026-09-03农历七月廿二」。给提醒预览与详情用。 */
export function formatSolarWithLunar(d: Date): string {
const pad = (n: number) => String(n).padStart(2, '0');
const ymd = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
return `${ymd}(农历${formatLunarShort(fromSolar(d))}`;
}
/** 是否是按农历推进的规则。 */
export function isLunarRecurrence(r: string): boolean {
return r === 'lunar_monthly' || r === 'lunar_yearly';
}
/**
* 算出下一次触发时刻。必须与后端 `repo.NextOccurrence` 行为一致 ——
* 前端用它预览「接下来几次在哪天」,与实际触发不符比不预览更糟。
*
* 返回 null 表示不重复或算不出来。
*/
export function nextOccurrence(recurrence: string, from: Date): Date | null {
switch (recurrence) {
case 'daily':
return shiftDays(from, 1);
case 'weekly':
return shiftDays(from, 7);
case 'monthly':
return addSolarMonthsClamped(from, 1);
case 'yearly':
return addSolarMonthsClamped(from, 12);
case 'lunar_monthly': {
const r = toSolar(
addLunarMonths(fromSolar(from), 1),
from.getHours(),
from.getMinutes(),
from.getSeconds()
);
return r ? r.date : null;
}
case 'lunar_yearly': {
const r = toSolar(
addLunarYears(fromSolar(from), 1),
from.getHours(),
from.getMinutes(),
from.getSeconds()
);
return r ? r.date : null;
}
default:
return null;
}
}
function shiftDays(d: Date, n: number): Date {
const x = new Date(d);
x.setDate(x.getDate() + n);
return x;
}
/**
* 公历加月份,日期夹到目标月的实际天数内。
*
* `setMonth` 的溢出行为3 月 31 日 +1 月 = 5 月 1 日)对「每月同一日」
* 是错的31 日的事件在 2 月会变成 3 月 3 日,然后从此每月 3 日提醒 ——
* 一次溢出永久改变了规则。
*/
export function addSolarMonthsClamped(d: Date, n: number): Date {
const y = d.getFullYear();
const m = d.getMonth() + n;
// 目标月第 0 天 = 上个月最后一天,用它拿月长
const last = new Date(y, m + 1, 0).getDate();
const day = Math.min(d.getDate(), last);
return new Date(y, m, day, d.getHours(), d.getMinutes(), d.getSeconds(), 0);
}
/**
* 预览接下来 n 次触发。事件编辑器里用它让人确认规则没被理解错 ——
* 农历规则的公历日期每次都在变,光看规则名分辨不出对不对。
*/
export function upcomingOccurrences(recurrence: string, from: Date, n = 3): Date[] {
const out: Date[] = [];
let cur = from;
for (let i = 0; i < n; i++) {
const next = nextOccurrence(recurrence, cur);
// 算不出来(例如目标年没有那个闰月)就停在这里,
// 而不是跳过继续试 —— 后端的 AdvanceRecurrence 也会在这一步放弃。
if (!next || next <= cur) break;
out.push(next);
cur = next;
}
return out;
}
/** 重复规则的人类可读标签。含农历时把农历日子写出来。 */
export function describeRecurrenceRule(recurrence: string, eventTime?: Date): string {
switch (recurrence) {
case 'none':
return '不重复';
case 'daily':
return '每天';
case 'weekly':
return '每周';
case 'monthly':
return '每月';
case 'yearly':
return '每年';
case 'lunar_monthly':
return eventTime
? `每农历月${dayNameOf(eventTime)}`
: '每农历月同一日';
case 'lunar_yearly':
return eventTime
? `每年农历${formatLunarShort(fromSolar(eventTime))}`
: '每农历年同月同日';
default:
return '不重复';
}
}
/** 取「廿二」这样的农历日名。 */
function dayNameOf(d: Date): string {
return lunarDayName(fromSolar(d).day);
}

57
web/src/types/lunar-javascript.d.ts vendored Normal file
View File

@ -0,0 +1,57 @@
/**
* lunar-javascript 的类型声明。
*
* 上游没有发布 .d.ts也没有 @types/lunar-javascript不声明的话
* `import` 直接 TS7016 编译失败。
*
* 只声明我们真正用到的成员而不是 `declare module 'lunar-javascript'`
* (那等于放弃整个模块的类型)—— 写错方法名时仍要能在编译期发现,
* 否则会变成运行时的「undefined is not a function」而日历页面
* 一旦抛错整片区域白屏。
*/
declare module 'lunar-javascript' {
export interface LunarMonthLike {
getYear(): number;
/** 负数表示闰月 */
getMonth(): number;
/** 29 或 30 */
getDayCount(): number;
}
export interface SolarLike {
getYear(): number;
/** 1-12 */
getMonth(): number;
getDay(): number;
toYmd(): string;
toString(): string;
}
export interface LunarLike {
getYear(): number;
/** 负数表示闰月 */
getMonth(): number;
getDay(): number;
getSolar(): SolarLike;
/** 「二〇二六年七月廿二」 */
toString(): string;
}
export const Solar: {
fromYmd(year: number, month: number, day: number): SolarLike & { getLunar(): LunarLike };
};
export const Lunar: {
/** month 传负数表示闰月。**非法日期会 throw** —— 农历月是 29 或 30 天不定。 */
fromYmd(year: number, month: number, day: number): LunarLike;
};
export const LunarYear: {
fromYear(year: number): {
/** 0 = 无闰月 */
getLeapMonth(): number;
/** 含跨年边界的月份,因此使用时必须同时比对 getYear() */
getMonths(): LunarMonthLike[];
};
};
}

View File

@ -0,0 +1,268 @@
import { describe, it, expect } from 'vitest';
import {
fromSolar, toSolar, leapMonth, daysInMonth,
addLunarMonths, addLunarYears,
formatLunarFull, formatLunarShort, cellLunarLabel, lunarDayName,
formatSolarWithLunar, isLunarRecurrence,
nextOccurrence, addSolarMonthsClamped, upcomingOccurrences,
describeRecurrenceRule
} from '../../src/lib/lunar';
describe('公历 ↔ 农历', () => {
it('已知锚点', () => {
const d = fromSolar(new Date(2026, 8, 3));
expect(d).toEqual({ year: 2026, month: 7, day: 22 });
});
it('闰月用负数月份表示', () => {
// 2025 有闰六月
expect(leapMonth(2025)).toBe(6);
const d = fromSolar(new Date(2025, 6, 25)); // 2025-07-25
expect(d.month).toBe(-6);
expect(d.day).toBe(1);
});
it('无闰月的年份返回 0', () => {
expect(leapMonth(2026)).toBe(0);
expect(leapMonth(2027)).toBe(0);
});
it('往返不丢日期', () => {
for (const [y, m, dd] of [[2026, 8, 3], [2027, 1, 14], [2025, 6, 25]] as const) {
const solar = new Date(y, m, dd);
const lunar = fromSolar(solar);
const back = toSolar(lunar, 9, 30);
expect(back).not.toBeNull();
expect(back!.clamped).toBe(false);
expect(back!.date.getFullYear()).toBe(y);
expect(back!.date.getMonth()).toBe(m);
expect(back!.date.getDate()).toBe(dd);
// 时钟原样带过去(农历只定义到「日」)
expect(back!.date.getHours()).toBe(9);
expect(back!.date.getMinutes()).toBe(30);
}
});
});
describe('短月份夹取', () => {
it('2027 农历九月只有 29 天', () => {
expect(daysInMonth(2027, 9)).toBe(29);
expect(daysInMonth(2026, 1)).toBe(30);
});
// 库在 Lunar.fromYmd(2027,9,30) 上直接 throw。
// 「每月农历三十」必然撞上 29 天的月份,不夹住就是整片白屏。
it('要三十而该月只有廿九时夹到廿九,不抛错', () => {
const r = toSolar({ year: 2027, month: 9, day: 30 }, 9, 0);
expect(r).not.toBeNull();
expect(r!.clamped).toBe(true);
// 夹取后必须仍在同一个农历月内(滚到下月初一是错的)
expect(fromSolar(r!.date).month).toBe(9);
expect(fromSolar(r!.date).day).toBe(29);
});
it('不存在的闰月返回 null 而不是猜一个日子', () => {
expect(daysInMonth(2026, -6)).toBe(0);
expect(toSolar({ year: 2026, month: -6, day: 1 })).toBeNull();
});
it('非法日返回 null', () => {
expect(toSolar({ year: 2026, month: 1, day: 0 })).toBeNull();
expect(toSolar({ year: 2026, month: 13, day: 1 })).toBeNull();
});
});
describe('农历推进', () => {
it('加月跨年', () => {
expect(addLunarMonths({ year: 2026, month: 12, day: 5 }, 1)).toEqual({ year: 2027, month: 1, day: 5 });
});
it('推 12 次回到次年同月', () => {
expect(addLunarMonths({ year: 2026, month: 7, day: 22 }, 12))
.toEqual({ year: 2027, month: 7, day: 22 });
});
// 「每月十五」的期望是一年 12 次,把闰月算进去会让闰年多一次
it('从闰月出发先归正月份', () => {
expect(addLunarMonths({ year: 2025, month: -6, day: 15 }, 1).month).toBe(7);
});
it('加年保持月日', () => {
expect(addLunarYears({ year: 2026, month: 7, day: 22 }, 1))
.toEqual({ year: 2027, month: 7, day: 22 });
});
// 静默让重复事件消失比退回正月份更糟
it('目标年无同一闰月时退回正月份', () => {
expect(addLunarYears({ year: 2025, month: -6, day: 15 }, 1))
.toEqual({ year: 2026, month: 6, day: 15 });
});
});
describe('中文表示', () => {
it('完整表示', () => {
expect(formatLunarFull({ year: 2026, month: 7, day: 22 })).toBe('二〇二六年七月廿二');
});
it('闰月带「闰」字', () => {
expect(formatLunarFull({ year: 2025, month: -6, day: 1 })).toBe('二〇二五年闰六月初一');
});
it('短表示去掉年份', () => {
expect(formatLunarShort({ year: 2026, month: 7, day: 22 })).toBe('七月廿二');
});
// 日名有五种前缀形态(初一/十一/二十/廿一/三十),
// 用正则截取时「二十」曾被漏掉
it('日名查表覆盖全部 30 天', () => {
const names = Array.from({ length: 30 }, (_, i) => lunarDayName(i + 1));
expect(names[0]).toBe('初一');
expect(names[9]).toBe('初十');
expect(names[10]).toBe('十一');
expect(names[19]).toBe('二十');
expect(names[20]).toBe('廿一');
expect(names[29]).toBe('三十');
expect(new Set(names).size).toBe(30); // 无重复
expect(names.every(n => n.length === 2)).toBe(true);
});
it('格子标记:初一显示月名,其余显示日名', () => {
// 2026-08-13 是农历七月初一
const firstDay = toSolar({ year: 2026, month: 7, day: 1 })!.date;
expect(cellLunarLabel(firstDay)).toBe('七月');
expect(cellLunarLabel(new Date(2026, 8, 3))).toBe('廿二');
});
it('闰月初一的格子标记带「闰」', () => {
const leapFirst = toSolar({ year: 2025, month: -6, day: 1 })!.date;
expect(cellLunarLabel(leapFirst)).toBe('闰六月');
});
it('公历+农历合并显示', () => {
expect(formatSolarWithLunar(new Date(2026, 8, 3))).toBe('2026-09-03农历七月廿二');
});
});
describe('nextOccurrence 与后端 repo.NextOccurrence 对齐', () => {
const base = new Date(2026, 8, 3, 9, 30);
it('公历三种', () => {
expect(nextOccurrence('daily', base)!.getDate()).toBe(4);
expect(nextOccurrence('weekly', base)!.getDate()).toBe(10);
expect(nextOccurrence('monthly', base)!.getMonth()).toBe(9);
});
it('公历每年', () => {
const n = nextOccurrence('yearly', base)!;
expect(n.getFullYear()).toBe(2027);
expect(n.getMonth()).toBe(8);
expect(n.getDate()).toBe(3);
});
it('none 与未知值给 null', () => {
expect(nextOccurrence('none', base)).toBeNull();
expect(nextOccurrence('每隔一个蓝月亮', base)).toBeNull();
});
it('时钟保留', () => {
for (const r of ['daily', 'weekly', 'monthly', 'yearly', 'lunar_monthly', 'lunar_yearly']) {
const n = nextOccurrence(r, base);
expect(n).not.toBeNull();
expect(n!.getHours()).toBe(9);
expect(n!.getMinutes()).toBe(30);
}
});
});
// setMonth 的溢出3月31日 +1月 = 5月1日会永久改变规则
// 31 日的事件在 2 月变成 3 月 3 日,然后从此每月 3 日提醒
describe('公历月末夹取', () => {
it.each([
['2026-01-31', 1, '2026-02-28'],
['2026-03-31', 1, '2026-04-30'],
['2028-01-31', 1, '2028-02-29'],
['2028-02-29', 12, '2029-02-28'],
['2026-01-15', 1, '2026-02-15']
])('%s + %i 月 → %s', (from, n, want) => {
const [y, m, d] = from.split('-').map(Number);
const got = addSolarMonthsClamped(new Date(y, m - 1, d), n);
const pad = (x: number) => String(x).padStart(2, '0');
expect(`${got.getFullYear()}-${pad(got.getMonth() + 1)}-${pad(got.getDate())}`).toBe(want);
});
});
describe('农历重复的公历漂移', () => {
it('农历月间隔在 29~30 天之间浮动,不是固定值', () => {
let cur = new Date(2026, 8, 3, 9, 0);
const gaps = new Set<number>();
for (let i = 0; i < 6; i++) {
const next = nextOccurrence('lunar_monthly', cur)!;
expect(next.getTime()).toBeGreaterThan(cur.getTime());
gaps.add(Math.round((next.getTime() - cur.getTime()) / 86400000));
// 农历「日」保持不变
expect(fromSolar(next).day).toBe(22);
cur = next;
}
expect(gaps.size).toBeGreaterThan(1);
for (const g of gaps) expect(g).toBeGreaterThanOrEqual(28);
for (const g of gaps) expect(g).toBeLessThanOrEqual(31);
});
// 这是农历规则存在的理由:用公历 yearly 日子会固定,
// 与「过农历生日/祭日」的期望不符
it('农历年推进时公历月日每年都变', () => {
let cur = new Date(2026, 8, 3, 9, 0);
const seen = new Set<string>();
for (let i = 0; i < 5; i++) {
const next = nextOccurrence('lunar_yearly', cur)!;
const d = fromSolar(next);
expect(d.month).toBe(7);
expect(d.day).toBe(22);
seen.add(`${next.getMonth() + 1}-${next.getDate()}`);
cur = next;
}
expect(seen.size).toBeGreaterThanOrEqual(3);
});
});
describe('upcomingOccurrences', () => {
it('给出连续递增的 n 次', () => {
const list = upcomingOccurrences('lunar_monthly', new Date(2026, 8, 3, 9, 0), 3);
expect(list).toHaveLength(3);
for (let i = 1; i < list.length; i++) {
expect(list[i].getTime()).toBeGreaterThan(list[i - 1].getTime());
}
});
it('不重复时给空数组', () => {
expect(upcomingOccurrences('none', new Date(), 3)).toEqual([]);
});
});
describe('describeRecurrenceRule', () => {
it('公历规则', () => {
expect(describeRecurrenceRule('none')).toBe('不重复');
expect(describeRecurrenceRule('daily')).toBe('每天');
expect(describeRecurrenceRule('weekly')).toBe('每周');
expect(describeRecurrenceRule('monthly')).toBe('每月');
expect(describeRecurrenceRule('yearly')).toBe('每年');
});
it('农历规则把农历日子写出来', () => {
const t = new Date(2026, 8, 3);
expect(describeRecurrenceRule('lunar_monthly', t)).toBe('每农历月廿二');
expect(describeRecurrenceRule('lunar_yearly', t)).toBe('每年农历七月廿二');
});
it('无事件时间时退回泛化描述', () => {
expect(describeRecurrenceRule('lunar_monthly')).toBe('每农历月同一日');
expect(describeRecurrenceRule('lunar_yearly')).toBe('每农历年同月同日');
});
it('isLunarRecurrence', () => {
expect(isLunarRecurrence('lunar_monthly')).toBe(true);
expect(isLunarRecurrence('lunar_yearly')).toBe(true);
expect(isLunarRecurrence('monthly')).toBe(false);
expect(isLunarRecurrence('yearly')).toBe(false);
});
});