feat: support Temporal generateConfig - #998
Conversation
|
Caution The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased. |
|
@ZQDesigned is attempting to deploy a commit to the afc163's projects Team on Vercel. A member of the Team first needs to authorize it. |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
Walkthrough新增基于 Temporal 的 ChangesTemporal 支持
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Picker
participant temporalGenerateConfig
participant Temporal
Picker->>temporalGenerateConfig: 解析输入值
temporalGenerateConfig->>Temporal: 创建并校验 PlainDateTime
Temporal-->>temporalGenerateConfig: 返回日期时间或失败
temporalGenerateConfig-->>Picker: 更新选择值与显示文本
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Pull request overview
Adds a new Temporal.PlainDateTime-based generateConfig adapter for @rc-component/picker, including locale formatting/parsing support and test coverage, and exposes the adapter via browser mappings while documenting the polyfill requirement via dependencies.
Changes:
- Introduces
src/generate/temporal.tsimplementing Temporal-based get/set/add/compare plus locale format/parse helpers (including week tokens). - Adds Jest coverage for the shared generate-config test suite and picker integration using Temporal values.
- Adds
@js-temporal/polyfillas a dev dependency and optional peer dependency, and exposes./generate/temporalin package browser mappings.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
src/generate/temporal.ts |
New Temporal adapter with token-based locale formatting/parsing and week-related helpers. |
tests/generate.spec.tsx |
Adds Temporal to the shared generate-config regression suite; tweaks week/format expectations. |
tests/picker.spec.tsx |
Adds an integration test proving Picker value/onChange works with Temporal PlainDateTime. |
package.json |
Adds polyfill dev + optional peer dependency and exposes generate/temporal in browser mappings. |
Comments suppressed due to low confidence (1)
tests/generate.spec.tsx:131
- This assertion is inside the
elsebranch that only runs fordate-fnsandluxon, so thename === 'temporal'conditional is unreachable and misleading. Simplify it to an unconditional expectation.
).toEqual(name === 'temporal' ? '2019-1st' : null);
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| getFixedDate: (value) => { | ||
| const matched = value.match(/^(\d{4})-(\d{1,2})-(\d{2})$/); | ||
|
|
||
| if (!matched) { | ||
| throw new Error(`Invalid fixed date value: ${value}`); | ||
| } | ||
|
|
||
| return createDateTime(Number(matched[1]), Number(matched[2]), Number(matched[3])); | ||
| }, |
|
|
||
| describe('Picker.Generate', () => { | ||
| beforeAll(() => { | ||
| globalThis.Temporal = TemporalPolyfill as typeof globalThis.Temporal; |
| beforeEach(() => { | ||
| globalThis.Temporal = TemporalPolyfill as typeof globalThis.Temporal; | ||
| jest.useFakeTimers().setSystemTime(fakeTime); | ||
| }); |
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (6)
src/generate/temporal.ts (4)
50-58: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value建议改名并补注释说明这些硬编码映射的用意。
fullWidthFormatLocaleMap存的是'narrow'宽度,名称与内容不符;shortWeekDayLengthMap的截断长度 2 也缺乏来源说明。建议改为weekDayFormatLocaleMap/weekDayTruncateLengthMap并加一行注释,说明这是为对齐 moment/dayjs 的短星期输出。🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/generate/temporal.ts` around lines 50 - 58, Rename fullWidthFormatLocaleMap to weekDayFormatLocaleMap and shortWeekDayLengthMap to weekDayTruncateLengthMap, updating all references. Add a concise comment explaining that these locale mappings and truncation lengths align short weekday output with moment/dayjs behavior.
272-301: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick wintoken 集合缺少
dddd/ddd/dd/Do,且未命中的 token 会被静默当作字面量输出。排序(长 token 在前)没问题,但星期名与序数日不在表中:
'dddd'会原样输出dddd,'Do'会被切成 tokenD+ 字面量o,得到28o。这类静默错误比抛错更难排查。建议至少补上
dddd/ddd/dd(可复用Intl.DateTimeFormat的weekday)和Do,或在模块顶部注释里显式声明受支持的 token 白名单。🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/generate/temporal.ts` around lines 272 - 301, Update the token handling around tokenList to include the supported weekday tokens dddd, ddd, and dd plus the ordinal-day token Do, keeping longer tokens ordered before their prefixes. Ensure these tokens are actually formatted using the existing date-formatting logic, and prevent unsupported tokens from being silently emitted as literal text by enforcing the module’s supported-token behavior.
105-119: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win鸭子类型判断建议追加方法检查。
当前只校验 7 个数值字段,任意普通字面量对象都会通过,
isValidate也会跟着返回true;但下游会调用date.add()/date.with(),那时才崩。用instanceof在原生/polyfill 混用时不可靠,所以再校验一下关键方法是最划算的加固:return ( typeof (value as TemporalDateTime).year === 'number' && typeof (value as TemporalDateTime).month === 'number' && typeof (value as TemporalDateTime).day === 'number' && typeof (value as TemporalDateTime).hour === 'number' && typeof (value as TemporalDateTime).minute === 'number' && typeof (value as TemporalDateTime).second === 'number' && - typeof (value as TemporalDateTime).millisecond === 'number' + typeof (value as TemporalDateTime).millisecond === 'number' && + typeof (value as TemporalDateTime).with === 'function' && + typeof (value as TemporalDateTime).add === 'function' );🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/generate/temporal.ts` around lines 105 - 119, Update isTemporalDateTime to also validate the callable TemporalDateTime methods used downstream, especially add and with, alongside the existing numeric-field checks. Keep the duck-typing approach and avoid instanceof so native and polyfill TemporalDateTime values remain supported.
121-138: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value
new Intl.Locale(normalized)对非法 locale 会抛RangeError,建议包一层 try/catch 落到已有的 fallback。函数下方已经准备好了
en-US与 ISO 默认值两条兜底路径,加个try就能让非法 locale 走到这些兜底而不是把异常抛进渲染流程。🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/generate/temporal.ts` around lines 121 - 138, 在 getWeekInfo 中将 new Intl.Locale(normalized) 及其周信息读取逻辑包裹在 try/catch 内;捕获非法 locale 导致的 RangeError 后不要继续抛出,让流程落到函数下方现有的 en-US 与 ISO fallback 路径,保持合法 locale 的现有处理不变。tests/picker.spec.tsx (1)
199-220: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win建议补充 week / time 面板的集成用例。
这条用例只覆盖了 date 面板的基础选择路径,而
src/generate/temporal.ts中占比最大、也最容易出错的是周计算(getWeekFirstDate/getWeek/Wo)和 12 小时制 +A/a的格式化与解析。建议至少再加picker="week"和带showTime+hh:mm A的两条用例,否则这部分逻辑在 Picker 层是零覆盖的。需要的话我可以直接把这两条用例补上,或开一个 issue 跟踪。
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/picker.spec.tsx` around lines 199 - 220, Expand the Temporal generateConfig integration coverage in the test around the existing “supports Temporal generateConfig” case by adding a picker="week" scenario that exercises week selection and a showTime scenario using the hh:mm A format that verifies 12-hour parsing and formatting. Assert the resulting Temporal values, displayed input values, and onChange payloads for both paths.tests/generate.spec.tsx (1)
184-188: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value改用
locale.format是必要的,但建议补一条 parse 结果非空的断言。第 184/187 行的
!会在parse返回null时把失败推迟到format内部,报错信息不指向真正的原因。加一行expect(enDate).toBeTruthy()能让回归更好定位。🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/generate.spec.tsx` around lines 184 - 188, 在测试中为 locale.parse 的结果增加显式非空断言:分别在使用 enDate 和 zhDate 调用 locale.format 前,断言对应值为 truthy;移除依赖非空断言操作符 `!`,保留现有格式化结果断言不变。
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/generate/temporal.ts`:
- Around line 523-527: 修复 src/generate/temporal.ts 的 parseDateByWeek:拒绝 week 小于
1 或大于 53,并确认计算结果的 weekYear 仍等于传入值,否则返回 null;同时让其调用方正确处理该 null。更新
tests/generate.spec.tsx 中对应断言,移除 temporal 专用的 '2019-1st' 特例,恢复所有 generateConfig
统一断言 null。
- Around line 153-180: 缓存按 locale 复用的 Intl.DateTimeFormat、月份名称和
getLocaleDayPeriods 结果,避免 getLocaleMonthNames 为每个月重复构造 formatter;同时在
locale.format 外层一次计算 getWeekInfoForDate 与 getLocaleDayPeriods,并让 formatToken
接收或复用这些结果,而不是为每个 token 重新计算。
- Around line 578-587: Update the MMM and MMMM parsing branches in the temporal
date-token logic to explicitly detect a failed findIndex result before adding
one, and route invalid month names through the existing validation/error path
instead of allowing month 0 to reach createDateTime. Also include year in the
NaN validation at the shared check around the referenced validation logic,
preserving normal parsing for valid month names.
- Around line 182-185: 统一使用 normalizeLocale(locale) 的结果进行区域设置查表和语言前缀判断:更新
getShortWeekDays 中 fullWidthFormatLocaleMap 与 shortWeekDayLengthMap 的访问,并调整
getWeekOrdinal 的 startsWith 判断。同步将相关映射键改为归一化的 BCP-47 形式(如
zh-CN、en-US),确保这些输入保持正确的短星期宽度和序数格式。
- Around line 722-730: Update the regular expression in getFixedDate so both
month and day components accept one or two digits, allowing values such as
“2020-1-5” while preserving the existing fixed-date validation and parsing
behavior.
- Around line 569-572: 更新 temporal.ts 中处理 YY 的分支,使两位年份按 moment/dayjs
约定推断世纪:数值小于等于 68 映射到 20xx,大于等于 69 映射到 19xx;保留 usedDateToken 标记和现有解析流程不变。
- Around line 772-782: Update the invalid-date guard in
GenerateConfig.locale.format to return an empty string instead of null,
preserving the existing validation and normal formatting path so the method
consistently satisfies its string return contract.
---
Nitpick comments:
In `@src/generate/temporal.ts`:
- Around line 50-58: Rename fullWidthFormatLocaleMap to weekDayFormatLocaleMap
and shortWeekDayLengthMap to weekDayTruncateLengthMap, updating all references.
Add a concise comment explaining that these locale mappings and truncation
lengths align short weekday output with moment/dayjs behavior.
- Around line 272-301: Update the token handling around tokenList to include the
supported weekday tokens dddd, ddd, and dd plus the ordinal-day token Do,
keeping longer tokens ordered before their prefixes. Ensure these tokens are
actually formatted using the existing date-formatting logic, and prevent
unsupported tokens from being silently emitted as literal text by enforcing the
module’s supported-token behavior.
- Around line 105-119: Update isTemporalDateTime to also validate the callable
TemporalDateTime methods used downstream, especially add and with, alongside the
existing numeric-field checks. Keep the duck-typing approach and avoid
instanceof so native and polyfill TemporalDateTime values remain supported.
- Around line 121-138: 在 getWeekInfo 中将 new Intl.Locale(normalized) 及其周信息读取逻辑包裹在
try/catch 内;捕获非法 locale 导致的 RangeError 后不要继续抛出,让流程落到函数下方现有的 en-US 与 ISO fallback
路径,保持合法 locale 的现有处理不变。
In `@tests/generate.spec.tsx`:
- Around line 184-188: 在测试中为 locale.parse 的结果增加显式非空断言:分别在使用 enDate 和 zhDate 调用
locale.format 前,断言对应值为 truthy;移除依赖非空断言操作符 `!`,保留现有格式化结果断言不变。
In `@tests/picker.spec.tsx`:
- Around line 199-220: Expand the Temporal generateConfig integration coverage
in the test around the existing “supports Temporal generateConfig” case by
adding a picker="week" scenario that exercises week selection and a showTime
scenario using the hh:mm A format that verifies 12-hour parsing and formatting.
Assert the resulting Temporal values, displayed input values, and onChange
payloads for both paths.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 880307a1-c555-4b28-b4e3-4900096bf9ed
📒 Files selected for processing (4)
package.jsonsrc/generate/temporal.tstests/generate.spec.tsxtests/picker.spec.tsx
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/generate/temporal.ts (1)
401-469: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift为 ISO 周 token 使用固定的 ISO 周规则,而非当前 locale 的周规则。
当前
GGGG/WW虽然被解析为 ISO 类型,但parseDateByWeek、formatToken与getWeekInfoForDate都只传locale,始终以firstDay=0, minimalDays=1/locale 配置计算周。对于en-US等非 ISO-like locale,WW/GGGG会产出与标准 ISO 8601 不同的格式化/解析结果,应让 ISO token 明确使用firstDay=1, minimalDays=4,保持与g/w大小写约定的区隔。🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/generate/temporal.ts` around lines 401 - 469, 为 ISO 周 token(GGGG、W、WW、Wo)引入固定的 ISO 周规则,在 formatToken 和 parseDateByWeek 中传递 firstDay=1、minimalDays=4 给 getWeekInfoForDate;小写 g/w token 继续使用 locale 周规则,保持大小写约定及现有非周 token 行为不变。
🧹 Nitpick comments (1)
tests/generate.spec.tsx (1)
15-27: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win回归测试与实现修复一一对应,覆盖到位。
新增的
Generate:temporal用例(357-411 行)分别验证了dddd/ddd/dd/Do格式化、A+两位年份解析、locale 归一化及 fixed date 规范化、非法月份名返回null,均能与src/generate/temporal.ts中对应修复相互印证。131-142 行、195-201 行也针对 temporal 的周序/周年解析行为做了合理调整。需要注意的是,目前测试中没有覆盖
WW/GGGG(ISO 周 token)与w/ww/gggg(locale 周 token)在非 ISO 默认 locale 下的往返(format→parse)一致性场景,建议在修复src/generate/temporal.ts中 ISO/locale 周规则混用问题后,补充对应回归用例。Also applies to: 131-142, 195-201, 342-412
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/generate.spec.tsx` around lines 15 - 27, 补充回归测试覆盖非 ISO 默认 locale 下 ISO 周 token(WW、GGGG)及 locale 周 token(w、ww、gggg)的 format→parse 往返一致性,分别验证周数与周年解析结果保持一致。将用例加入现有 Generate:temporal 测试范围,并确保覆盖 src/generate/temporal.ts 中 ISO 与 locale 周规则混用的修复行为。
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@src/generate/temporal.ts`:
- Around line 401-469: 为 ISO 周 token(GGGG、W、WW、Wo)引入固定的 ISO 周规则,在 formatToken 和
parseDateByWeek 中传递 firstDay=1、minimalDays=4 给 getWeekInfoForDate;小写 g/w token
继续使用 locale 周规则,保持大小写约定及现有非周 token 行为不变。
---
Nitpick comments:
In `@tests/generate.spec.tsx`:
- Around line 15-27: 补充回归测试覆盖非 ISO 默认 locale 下 ISO 周 token(WW、GGGG)及 locale 周
token(w、ww、gggg)的 format→parse 往返一致性,分别验证周数与周年解析结果保持一致。将用例加入现有 Generate:temporal
测试范围,并确保覆盖 src/generate/temporal.ts 中 ISO 与 locale 周规则混用的修复行为。
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 18d4c2f4-9b39-401c-83f7-641ee769dc64
📒 Files selected for processing (3)
src/generate/temporal.tstests/generate.spec.tsxtests/picker.spec.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
- tests/picker.spec.tsx
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #998 +/- ##
==========================================
- Coverage 98.87% 95.84% -3.04%
==========================================
Files 68 69 +1
Lines 2857 3390 +533
Branches 815 1020 +205
==========================================
+ Hits 2825 3249 +424
- Misses 29 138 +109
Partials 3 3 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/generate.spec.tsx`:
- Around line 534-540: Update the Temporal-missing test around the assertion in
the test case to restore globalThis.Temporal in a finally block or shared
afterEach cleanup, ensuring restoration occurs even when the assertion fails.
Export the TEMPORAL_MISSING_ERROR constant from temporal.ts and reuse it in the
test expectation instead of hardcoding the full error message.
- Around line 356-361: 将 Intl.Locale 的恢复逻辑从父套件的 afterAll 移到修改它的
Generate:temporal 测试用例内部,使用 try/finally 确保测试成功或失败后都恢复
originalIntlLocale;也可改用该套件的 afterEach,并移除原有 afterAll 恢复,避免 BrokenLocale 污染后续测试。
- Around line 484-488: 稳定 midnightDate 测试中的当前时间,避免解析与断言分别调用
temporalGenerateConfig.getNow() 跨越午夜;在 temporalGenerateConfig.locale.format
调用前固定一次 now,并让解析和期望日期都复用该值,或使用 Jest 假时钟固定系统时间。同时将该用例的格式串从 24 小时制 `H` 调整为与
meridiem 边界一致的 `h:mm A`。
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 4eed2e91-f4b9-408d-bdf8-b59ffcf849b1
📒 Files selected for processing (3)
src/generate/temporal.tstests/generate.spec.tsxtests/picker.spec.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
- src/generate/temporal.ts
这个 PR 在做什么该 PR 新增基于 结论不适合合并 主测试、TSC 及本地 196 条相关测试均通过,但仍存在多个会静默改变用户输入的正确性问题。Codecov 当前也未通过;Vercel 失败属于授权问题,不作为代码缺陷。 问题清单🔴 高优先级(阻塞合并)
🟡 中优先级(建议修复)
🟢 低优先级(可选改进)无。 |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/generate/temporal.ts`:
- Line 771: 将 temporal.ts 中的 parsedWeekDays 声明从 let 改为 const;其数组内容仍可通过 push
修改,无需改变后续逻辑。
- Around line 932-946: Update the quarter-to-month fallback in the date parsing
branch around parsedMonth so it checks whether quarter is provided by comparing
against undefined rather than using truthiness. This must make quarter === 0
calculate (quarter - 1) * 3 + 1 and reach createDateTime with reject, while
preserving the default month of 1 when quarter is actually absent.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: def2ae3e-db89-4f70-951d-12cb5df51503
📒 Files selected for processing (2)
src/generate/temporal.tstests/generate.spec.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
- tests/generate.spec.tsx
Summary
Add a
Temporal.PlainDateTimegenerateConfig for@rc-component/picker.Related: ant-design/ant-design#58295
What changed
src/generate/temporal.ts./generate/temporalthrough the package browser mappings@js-temporal/polyfillas:Notes
This adapter reads
globalThis.Temporalat runtime.Consumers need either:
@js-temporal/polyfillattached toglobalThis.TemporalTests
npm run lint:tsctests/generate.spec.tsxtests/picker.spec.tsxnpm run compilenpm run browser-fieldSummary by CodeRabbit
@js-temporal/polyfill(可选),并在浏览端补充分发映射;同时对运行时 Temporal 可用性进行检测,支持 locale/week 信息不可用时的回退策略。onChange参数校验。