regression: momentFormatToDateFns not handling literal date formats#40304
regression: momentFormatToDateFns not handling literal date formats#40304dougfabris wants to merge 2 commits intorelease-8.4.0from
momentFormatToDateFns not handling literal date formats#40304Conversation
|
Looks like this PR is not ready to merge, because of the following issues:
Please fix the issues and try again If you have any trouble, please check the PR guidelines |
|
WalkthroughThe changes fix handling of Moment-style bracket-escaped literals in date format strings when converting to date-fns format. The implementation now properly recognizes bracket-escaped segments ( Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Suggested labels
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Warning Review ran into problems🔥 ProblemsErrors were encountered while retrieving linked issues. Errors (1)
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 |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## release-8.4.0 #40304 +/- ##
=================================================
+ Coverage 69.74% 69.95% +0.20%
=================================================
Files 3298 3298
Lines 119292 120081 +789
Branches 21469 21521 +52
=================================================
+ Hits 83206 84004 +798
- Misses 32785 32791 +6
+ Partials 3301 3286 -15
Flags with carried forward coverage won't be shown. Click here to find out more. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
apps/meteor/client/lib/utils/dateFormat.ts (1)
43-61: Consider hoistingtokenMap,entries, andreplaceTokensto module scope.
momentFormatToDateFnsis invoked on every message/timestamp render. As written, each call rebuildstokenMap, re-sortsentries, and constructs ~22 freshRegExpobjects insidereplaceTokens. Since none of this depends on the input, moving them out of the function body would avoid the per-call allocation without changing behavior.♻️ Proposed refactor
+const TOKEN_MAP: Record<string, string> = { + L: 'P', + LT: 'p', + LTS: 'pp', + LL: 'PPP', + LLL: 'PPP p', + LLLL: 'EEEE, PPP p', + YYYY: 'yyyy', + YY: 'yy', + Y: 'yyyy', + MMMM: 'MMMM', + MMM: 'MMM', + MM: 'MM', + M: 'M', + Do: 'do', + DD: 'dd', + D: 'd', + dddd: 'EEEE', + ddd: 'EEE', + HH: 'HH', + H: 'H', + hh: 'hh', + h: 'h', + mm: 'mm', + m: 'm', + ss: 'ss', + s: 's', + A: 'a', + a: 'a', +}; + +const TOKEN_ENTRIES: Array<[RegExp, string]> = Object.entries(TOKEN_MAP) + .sort(([a], [b]) => b.length - a.length) + .map(([mom, df]) => [new RegExp(mom.replace(/([.*+?^${}()|[\]\\])/g, '\\$1'), 'g'), df]); + +const replaceTokens = (input: string): string => + TOKEN_ENTRIES.reduce((acc, [re, df]) => acc.replace(re, df), input); + export const momentFormatToDateFns = (momentFormat: string): string => { - const tokenMap: Record<string, string> = { /* ... */ }; - const entries = Object.entries(tokenMap).sort(([a], [b]) => b.length - a.length); - - const replaceTokens = (input: string): string => { - let out = input; - for (const [mom, df] of entries) { - out = out.replace(new RegExp(mom.replace(/([.*+?^${}()|[\]\\])/g, '\\$1'), 'g'), df); - } - return out; - }; - return momentFormat .split(/(\[[^\]]*\])/g) .map((part) => { if (part.startsWith('[') && part.endsWith(']')) { return `'${part.slice(1, -1).replace(/'/g, "''")}'`; } return replaceTokens(part); }) .join(''); };🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/meteor/client/lib/utils/dateFormat.ts` around lines 43 - 61, The code repeatedly rebuilds tokenMap, entries, and replaceTokens on every call to momentFormatToDateFns causing needless allocations; move tokenMap, the computed entries (sorted Object.entries(tokenMap)), and the replaceTokens function to module scope (outside momentFormatToDateFns) so they are created once. Ensure replaceTokens still uses the hoisted entries and escapes regex metacharacters the same way, and keep the existing per-call logic that splits momentFormat and wraps bracketed literals; update any references inside momentFormatToDateFns to use the hoisted symbols (tokenMap, entries, replaceTokens).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@apps/meteor/client/lib/utils/dateFormat.ts`:
- Around line 43-61: The code repeatedly rebuilds tokenMap, entries, and
replaceTokens on every call to momentFormatToDateFns causing needless
allocations; move tokenMap, the computed entries (sorted
Object.entries(tokenMap)), and the replaceTokens function to module scope
(outside momentFormatToDateFns) so they are created once. Ensure replaceTokens
still uses the hoisted entries and escapes regex metacharacters the same way,
and keep the existing per-call logic that splits momentFormat and wraps
bracketed literals; update any references inside momentFormatToDateFns to use
the hoisted symbols (tokenMap, entries, replaceTokens).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f80463b1-56ca-4c74-ab43-e42431e920a4
📒 Files selected for processing (2)
apps/meteor/client/lib/utils/dateFormat.spec.tsapps/meteor/client/lib/utils/dateFormat.ts
📜 Review details
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx,js}
📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)
**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation
Files:
apps/meteor/client/lib/utils/dateFormat.spec.tsapps/meteor/client/lib/utils/dateFormat.ts
**/*.spec.ts
📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)
**/*.spec.ts: Use descriptive test names that clearly communicate expected behavior in Playwright tests
Use.spec.tsextension for test files (e.g.,login.spec.ts)
Files:
apps/meteor/client/lib/utils/dateFormat.spec.ts
🧠 Learnings (17)
📓 Common learnings
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/elements/Timestamp/DateTimeFormats.spec.tsx:20-23
Timestamp: 2026-03-06T18:09:17.867Z
Learning: In the RocketChat/Rocket.Chat gazzodown package (`packages/gazzodown`), tests are intended to run under the UTC timezone, but as of PR `#39397` this is NOT yet explicitly enforced in `jest.config.ts` or the `package.json` test scripts (which just run `jest` without `TZ=UTC`). To make timezone-sensitive snapshot tests reliable across all environments, `TZ=UTC` should be added to the test scripts in `package.json` or to `jest.config.ts` via `testEnvironmentOptions.timezone`. Without explicit UTC enforcement, snapshot tests involving date-fns formatted output or `toLocaleString()` will fail for contributors in non-UTC timezones.
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 37419
File: packages/i18n/src/locales/en.i18n.json:918-921
Timestamp: 2025-11-19T18:20:07.720Z
Learning: Repo: RocketChat/Rocket.Chat — i18n/formatting
Learning: This repository uses a custom message formatting parser in UI blocks/messages; do not assume standard Markdown rules. For keys like Call_ended_bold, Call_not_answered_bold, Call_failed_bold, and Call_transferred_bold in packages/i18n/src/locales/en.i18n.json, retain the existing single-asterisk emphasis unless maintainers request otherwise.
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/elements/Timestamp/RelativeTime.spec.tsx:63-70
Timestamp: 2026-03-06T18:02:20.381Z
Learning: In RocketChat/Rocket.Chat, tests in the `packages/gazzodown` package (and likely the broader test suite) are always expected to run in the UTC timezone. This makes `toLocaleString()` output deterministic, so snapshot tests that include locale/timezone-sensitive content (such as `title` attributes from `toLocaleString()`) are stable and do not need to be replaced with targeted assertions.
📚 Learning: 2026-03-06T18:09:17.867Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/elements/Timestamp/DateTimeFormats.spec.tsx:20-23
Timestamp: 2026-03-06T18:09:17.867Z
Learning: In the RocketChat/Rocket.Chat gazzodown package (`packages/gazzodown`), tests are intended to run under the UTC timezone, but as of PR `#39397` this is NOT yet explicitly enforced in `jest.config.ts` or the `package.json` test scripts (which just run `jest` without `TZ=UTC`). To make timezone-sensitive snapshot tests reliable across all environments, `TZ=UTC` should be added to the test scripts in `package.json` or to `jest.config.ts` via `testEnvironmentOptions.timezone`. Without explicit UTC enforcement, snapshot tests involving date-fns formatted output or `toLocaleString()` will fail for contributors in non-UTC timezones.
Applied to files:
apps/meteor/client/lib/utils/dateFormat.spec.tsapps/meteor/client/lib/utils/dateFormat.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Utilize Playwright fixtures (`test`, `page`, `expect`) for consistency in test files
Applied to files:
apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2025-12-10T21:00:54.909Z
Learnt from: KevLehman
Repo: RocketChat/Rocket.Chat PR: 37091
File: ee/packages/abac/jest.config.ts:4-7
Timestamp: 2025-12-10T21:00:54.909Z
Learning: Rocket.Chat monorepo: Jest testMatch pattern '<rootDir>/src/**/*.spec.(ts|js|mjs)' is valid in this repo and used across multiple packages (e.g., packages/tools, ee/packages/omnichannel-services). Do not flag it as invalid in future reviews.
Applied to files:
apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : All test files must be created in `apps/meteor/tests/e2e/` directory
Applied to files:
apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Group related tests in the same file
Applied to files:
apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Ensure tests run reliably in parallel without shared state conflicts
Applied to files:
apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2026-03-06T18:02:20.381Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/elements/Timestamp/RelativeTime.spec.tsx:63-70
Timestamp: 2026-03-06T18:02:20.381Z
Learning: In RocketChat/Rocket.Chat, tests in the `packages/gazzodown` package (and likely the broader test suite) are always expected to run in the UTC timezone. This makes `toLocaleString()` output deterministic, so snapshot tests that include locale/timezone-sensitive content (such as `title` attributes from `toLocaleString()`) are stable and do not need to be replaced with targeted assertions.
Applied to files:
apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Use `expect` matchers for assertions (`toEqual`, `toContain`, `toBeTruthy`, `toHaveLength`, etc.) instead of `assert` statements in Playwright tests
Applied to files:
apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to **/*.spec.ts : Use descriptive test names that clearly communicate expected behavior in Playwright tests
Applied to files:
apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Prefer web-first assertions (`toBeVisible`, `toHaveText`, etc.) in Playwright tests
Applied to files:
apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2026-02-10T16:32:42.586Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38528
File: apps/meteor/client/startup/roles.ts:14-14
Timestamp: 2026-02-10T16:32:42.586Z
Learning: In Rocket.Chat's Meteor client code, DDP streams use EJSON and Date fields arrive as Date objects; do not manually construct new Date() in stream handlers (for example, in sdk.stream()). Only REST API responses return plain JSON where dates are strings, so implement explicit conversion there if needed. Apply this guidance to all TypeScript files under apps/meteor/client to ensure consistent date handling in DDP streams and REST responses.
Applied to files:
apps/meteor/client/lib/utils/dateFormat.spec.tsapps/meteor/client/lib/utils/dateFormat.ts
📚 Learning: 2026-02-24T19:22:48.358Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 38493
File: apps/meteor/tests/e2e/omnichannel/omnichannel-send-pdf-transcript.spec.ts:66-67
Timestamp: 2026-02-24T19:22:48.358Z
Learning: In Playwright end-to-end tests (e.g., under apps/meteor/tests/e2e/...), prefer locating elements by translated text (getByText) and ARIA roles (getByRole) over data-qa attributes. If translation values change, update the corresponding test locators accordingly. Never use data-qa locators. This guideline applies to all Playwright e2e test specs in the repository and helps keep tests robust to UI text changes and accessible semantics.
Applied to files:
apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.
Applied to files:
apps/meteor/client/lib/utils/dateFormat.spec.tsapps/meteor/client/lib/utils/dateFormat.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.
Applied to files:
apps/meteor/client/lib/utils/dateFormat.spec.tsapps/meteor/client/lib/utils/dateFormat.ts
📚 Learning: 2026-03-06T18:10:15.268Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/code/CodeBlock.spec.tsx:47-68
Timestamp: 2026-03-06T18:10:15.268Z
Learning: In tests (especially those using testing-library/dom/jsdom) for Rocket.Chat components, the HTML <code> element has an implicit ARIA role of 'code'. Therefore, screen.getByRole('code') or screen.findByRole('code') will locate <code> elements even without a role attribute. Do not flag findByRole('code') as invalid in reviews; prefer using the implicit role instead of adding role="code" unless necessary for accessibility.
Applied to files:
apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2026-04-17T23:32:07.223Z
Learnt from: d-gubert
Repo: RocketChat/Rocket.Chat PR: 38357
File: apps/meteor/app/apps/server/converters/messages.ts:348-352
Timestamp: 2026-04-17T23:32:07.223Z
Learning: In `apps/meteor/app/apps/server/converters/messages.ts`, the `timestamp` handler inside `_convertAttachmentsToApp` uses a non-null assertion (`attachment.ts!`) intentionally. The `ts` property on `MessageAttachment` is optional only to accommodate MessageAttachment creation-time scenarios; by the time `_convertAttachmentsToApp` is called, the message has already been stored and the attachment is guaranteed to have a `ts` value. Do not flag this non-null assertion as unsafe during code review.
Applied to files:
apps/meteor/client/lib/utils/dateFormat.ts
🔇 Additional comments (2)
apps/meteor/client/lib/utils/dateFormat.ts (1)
53-61: Bracket-literal handling looks correct.Verified the split + map pipeline against the relevant edge cases:
[Today at] LT→'Today at' p✓[it's]→'it''s'(single-quote doubled) ✓[]preserved as''✓[[](Moment escape for literal[) is correctly captured by[^\]]*and emitted as'['✓- Token replacement is correctly scoped to non-literal segments, avoiding regressions where bracket contents like
[on]were previously being token-replaced.apps/meteor/client/lib/utils/dateFormat.spec.ts (1)
1-43: Test coverage looks solid and TZ-stable.A few observations confirming this works across environments:
new Date('2026-04-24T20:30:45')parses as local time, andformatoutputs in local time, so theYYYY-MM-DDassertion at line 41 is stable regardless of the runner's timezone (the local date is always2026-04-24).- The
formatDate(sample, '[Today at] LT')test only matches the literal prefix, so locale/TZ-dependent time output won't make it flaky.- Coverage hits the regression scenarios well: literal segment, embedded
', and empty[].
Proposed changes (including videos or screenshots)
Introduced here: #40076
momentFormatToDateFnsdid not translate Moment's[literal]escape syntax, so admin-configured formats like[Today at] LT(valid in 8.3.2) crashed the room view on 8.4.0 withRangeError: Format string contains an unescaped latin alphabet character 'o'.[...]blocks, convert each literal to date-fns''...'form (escaping embedded'as''), and run token substitution only on the non-literal segments.Test plan
[Today at] LT, upgrade to this build, open a room — messages render and tooltips showToday at 8:30 PM.Issue(s)
Steps to test or reproduce
Further comments
CORE-2134
Summary by CodeRabbit
Tests
Bug Fixes