@clipboard-health/ai-rules 1.1.1 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4342 +1 @@
1
- <!-- Source: .ruler/backend/nestJsApis.md -->
2
-
3
- # NestJS APIs
4
-
5
- - Use a three-tier architecture:
6
- - Controllers in the entrypoints tier translate from data transfer objects (DTOs) to domain objects (DOs) and call the logic tier.
7
- - Logic tier services call other services in the logic tier and repos and gateways at the data tier. The logic tier operates only on DOs.
8
- - Data tier repos translate from DOs to data access objects (DAOs), call the database using either Prisma for Postgres or Mongoose for MongoDB, and then translate from DAOs to DOs before returning to the logic tier.
9
- - Use ts-rest to define contracts using Zod schemas, one contract per resource.
10
- - A controller implements each ts-rest contract.
11
- - Requests and responses follow the JSON:API specification, including pagination for listings.
12
- - Use TypeDoc to document public functions, classes, methods, and complex code blocks.
13
-
14
- <!-- Source: .ruler/backend/notifications.md -->
15
-
16
- # Notifications
17
-
18
- Send notifications through [Knock](https://docs.knock.app) using the `@clipboard-health/notifications` NPM library.
19
-
20
- ## Usage
21
-
22
- <embedex source="packages/notifications/examples/usage.md">
23
-
24
- 1. Search your service for a `NotificationJobEnqueuer` instance. If there isn't one, create and export it:
25
-
26
- ```ts
27
- import { NotificationJobEnqueuer } from "@clipboard-health/notifications";
28
-
29
- import { BackgroundJobsService } from "./setup";
30
-
31
- // Create and export one instance of this in your microservice.
32
- export const notificationJobEnqueuer = new NotificationJobEnqueuer({
33
- // Use your instance of `@clipboard-health/mongo-jobs` or `@clipboard-health/background-jobs-postgres` here.
34
- adapter: new BackgroundJobsService(),
35
- });
36
- ```
37
-
38
- 1. Implement a minimal job, calling off to a NestJS service for any business logic and to send the notification.
39
-
40
- ```ts
41
- import { type BaseHandler } from "@clipboard-health/background-jobs-adapter";
42
- import { type NotificationData } from "@clipboard-health/notifications";
43
- import { isFailure, toError } from "@clipboard-health/util-ts";
44
-
45
- import { type ExampleNotificationService } from "./exampleNotification.service";
46
-
47
- export type ExampleNotificationData = NotificationData<{
48
- workplaceId: string;
49
- }>;
50
-
51
- export const EXAMPLE_NOTIFICATION_JOB_NAME = "ExampleNotificationJob";
52
-
53
- // For mongo-jobs, you'll implement HandlerInterface<ExampleNotificationData["Job"]>
54
- // For background-jobs-postgres, you'll implement Handler<ExampleNotificationData["Job"]>
55
- export class ExampleNotificationJob implements BaseHandler<ExampleNotificationData["Job"]> {
56
- public name = EXAMPLE_NOTIFICATION_JOB_NAME;
57
-
58
- constructor(private readonly service: ExampleNotificationService) {}
59
-
60
- async perform(data: ExampleNotificationData["Job"], job: { attemptsCount: number }) {
61
- const result = await this.service.sendNotification({
62
- ...data,
63
- // Include the job's attempts count for debugging, this is called `retryAttempts` in `background-jobs-postgres`.
64
- attempt: job.attemptsCount + 1,
65
- });
66
-
67
- if (isFailure(result)) {
68
- throw toError(result.error);
69
- }
70
- }
71
- }
72
- ```
73
-
74
- 1. Search your service for a constant that stores workflow keys. If there isn't one, create and export it:
75
-
76
- ```ts
77
- export const WORKFLOW_KEYS = {
78
- eventStartingReminder: "event-starting-reminder",
79
- } as const;
80
- ```
81
-
82
- 1. Enqueue your job:
83
-
84
- ```ts
85
- import {
86
- EXAMPLE_NOTIFICATION_JOB_NAME,
87
- type ExampleNotificationData,
88
- } from "./exampleNotification.job";
89
- import { notificationJobEnqueuer } from "./notificationJobEnqueuer";
90
- import { WORKFLOW_KEYS } from "./workflowKeys";
91
-
92
- async function enqueueNotificationJob() {
93
- await notificationJobEnqueuer.enqueueOneOrMore<ExampleNotificationData["Enqueue"]>(
94
- EXAMPLE_NOTIFICATION_JOB_NAME,
95
- // Important: Read the TypeDoc documentation for additional context.
96
- {
97
- /**
98
- * Set expiresAt at enqueue-time so it remains stable across job retries. Use date-fns in your
99
- * service instead of this manual calculation.
100
- */
101
- expiresAt: new Date(Date.now() + 60 * 60_000).toISOString(),
102
- // Set idempotencyKey at enqueue-time so it remains stable across job retries.
103
- idempotencyKey: {
104
- resourceId: "event-123",
105
- },
106
- // Set recipients at enqueue-time so they respect our notification provider's limits.
107
- recipients: ["userId-1"],
108
-
109
- workflowKey: WORKFLOW_KEYS.eventStartingReminder,
110
-
111
- // Any additional enqueue-time data passed to the job:
112
- workplaceId: "workplaceId-123",
113
- },
114
- );
115
- }
116
-
117
- // eslint-disable-next-line unicorn/prefer-top-level-await
118
- void enqueueNotificationJob();
119
- ```
120
-
121
- 1. Trigger the job in your NestJS service:
122
-
123
- ```ts
124
- import { type NotificationClient } from "@clipboard-health/notifications";
125
-
126
- import { type ExampleNotificationData } from "./exampleNotification.job";
127
-
128
- type ExampleNotificationDo = ExampleNotificationData["Job"] & { attempt: number };
129
-
130
- export class ExampleNotificationService {
131
- constructor(private readonly client: NotificationClient) {}
132
-
133
- async sendNotification(params: ExampleNotificationDo) {
134
- const { attempt, expiresAt, idempotencyKey, recipients, workflowKey, workplaceId } = params;
135
-
136
- // Assume this comes from a database and are used as template variables...
137
- // Use @clipboard-health/date-time's formatShortDateTime in your service for consistency.
138
- const data = { favoriteColor: "blue", favoriteAt: new Date().toISOString(), secret: "2" };
139
-
140
- // Important: Read the TypeDoc documentation for additional context.
141
- return await this.client.trigger({
142
- attempt,
143
- body: {
144
- data,
145
- recipients,
146
- workplaceId,
147
- },
148
- expiresAt: new Date(expiresAt),
149
- idempotencyKey,
150
- keysToRedact: ["secret"],
151
- workflowKey,
152
- });
153
- }
154
- }
155
- ```
156
-
157
- </embedex>
158
-
159
- <!-- Source: .ruler/common/codeStyleAndStructure.md -->
160
-
161
- # Code style and structure
162
-
163
- - Write concise, technical TypeScript code with accurate examples.
164
- - Use functional and declarative programming patterns.
165
- - Prefer iteration and modularization over code duplication.
166
- - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
167
- - Structure files: constants, types, exported functions, non-exported functions.
168
- - Avoid magic strings and numbers; define constants.
169
- - Use camelCase for files and directories (e.g., modules/shiftOffers.ts).
170
- - When declaring functions, use the `function` keyword, not `const`.
171
- - Files should read from top to bottom: `export`ed items live on top and the internal functions and methods they call go below them.
172
- - Prefer data immutability.
173
-
174
- # Commit messages
175
-
176
- - Follow the Conventional Commits 1.0 spec for commit messages and in pull request titles.
177
-
178
- <!-- Source: .ruler/common/errorHandlingAndValidation.md -->
179
-
180
- # Error handling and validation
181
-
182
- - Sanitize user input.
183
- - Handle errors and edge cases at the beginning of functions.
184
- - Use early returns for error conditions to avoid deeply nested if statements.
185
- - Place the happy path last in the function for improved readability.
186
- - Avoid unnecessary else statements; use the if-return pattern instead.
187
- - Use guard clauses to handle preconditions and invalid states early.
188
- - Implement proper error logging and user-friendly error messages.
189
- - Favor `@clipboard-health/util-ts`'s `Either` type for expected errors instead of `try`/`catch`.
190
-
191
- <!-- Source: .ruler/common/testing.md -->
192
-
193
- # Testing
194
-
195
- - Follow the Arrange-Act-Assert convention for tests with newlines between each section.
196
- - Name test variables using the `mockX`, `input`, `expected`, `actual` convention.
197
- - Aim for high test coverage, writing both positive and negative test cases.
198
- - Prefer `it.each` for multiple test cases.
199
- - Avoid conditional logic in tests.
200
-
201
- <!-- Source: .ruler/common/typeScript.md -->
202
-
203
- # TypeScript usage
204
-
205
- - Use strict-mode TypeScript for all code; prefer interfaces over types.
206
- - Avoid enums; use const maps instead.
207
- - Strive for precise types. Look for type definitions in the codebase and create your own if none exist.
208
- - Avoid using type assertions like `as` or `!` unless absolutely necessary.
209
- - Use the `unknown` type instead of `any` when the type is truly unknown.
210
- - Use an object to pass multiple function params and to return results.
211
- - Leverage union types, intersection types, and conditional types for complex type definitions.
212
- - Use mapped types and utility types (e.g., `Partial<T>`, `Pick<T>`, `Omit<T>`) to transform existing types.
213
- - Implement generic types to create reusable, flexible type definitions.
214
- - Utilize the `keyof` operator and index access types for dynamic property access.
215
- - Implement discriminated unions for type-safe handling of different object shapes where appropriate.
216
- - Use the `infer` keyword in conditional types for type inference.
217
- - Leverage `readonly` properties for function parameter immutability.
218
- - Prefer narrow types whenever possible with `as const` assertions, `typeof`, `instanceof`, `satisfies`, and custom type guards.
219
- - Implement exhaustiveness checking using `never`.
220
-
221
- <!-- Source: .ruler/frontend/custom-hooks.md -->
222
-
223
- # Custom Hook Standards
224
-
225
- ## Hook Structure
226
-
227
- ```typescript
228
- interface UseFeatureOptions {
229
- enabled?: boolean;
230
- refetchInterval?: number;
231
- }
232
-
233
- export function useFeature(params: Params, options: UseFeatureOptions = {}) {
234
- const { enabled = true } = options;
235
-
236
- // Multiple queries/hooks
237
- const query1 = useQuery(...);
238
- const query2 = useQuery(...);
239
-
240
- // Derived state
241
- const computed = useMemo(() => {
242
- // Combine data
243
- return transformData(query1.data, query2.data);
244
- }, [query1.data, query2.data]);
245
-
246
- // Callbacks
247
- const handleAction = useCallback(async () => {
248
- // Perform action
249
- }, [dependencies]);
250
-
251
- // Return structured object
252
- return {
253
- // Data
254
- data: computed,
255
-
256
- // Loading states
257
- isLoading: query1.isLoading || query2.isLoading,
258
- isError: query1.isError || query2.isError,
259
-
260
- // Actions
261
- refetch: async () => {
262
- await Promise.all([query1.refetch(), query2.refetch()]);
263
- },
264
- handleAction,
265
- };
266
- }
267
- ```
268
-
269
- ## Naming Rules
270
-
271
- - **Always** prefix with `use`
272
- - Boolean hooks: `useIsFeatureEnabled`, `useShouldShowModal`, `useHasPermission`
273
- - Data hooks: `useGetData`, `useFeatureData`
274
- - Action hooks: `useBookShift`, `useSubmitForm`
275
-
276
- ## Return Values
277
-
278
- - Return objects (not arrays) for complex hooks
279
- - Name properties clearly: `isLoading` not `loading`, `refetch` not `refresh`
280
- - Group related properties together
281
-
282
- ```typescript
283
- // Good - clear property names
284
- return {
285
- data,
286
- isLoading,
287
- isError,
288
- refetch,
289
- };
290
-
291
- // Avoid - array destructuring for complex returns
292
- return [data, isLoading, refetch]; // Only for very simple hooks
293
- ```
294
-
295
- ## State Management with Constate
296
-
297
- For local/shared state management, use **`constate`** to create context with minimal boilerplate:
298
-
299
- ```typescript
300
- import constate from "constate";
301
- import { useState, useCallback } from "react";
302
-
303
- // Define your hook with state logic
304
- function useShiftFilters() {
305
- const [filters, setFilters] = useState<Filters>({});
306
- const [isLoading, setIsLoading] = useState(false);
307
-
308
- const applyFilters = useCallback((newFilters: Filters) => {
309
- setFilters(newFilters);
310
- }, []);
311
-
312
- const clearFilters = useCallback(() => {
313
- setFilters({});
314
- }, []);
315
-
316
- return {
317
- filters,
318
- isLoading,
319
- applyFilters,
320
- clearFilters,
321
- };
322
- }
323
-
324
- // Create provider and hook with constate
325
- export const [ShiftFiltersProvider, useShiftFiltersContext] = constate(useShiftFilters);
326
- ```
327
-
328
- **Usage:**
329
-
330
- ```typescript
331
- // Wrap components that need access
332
- function ShiftsPage() {
333
- return (
334
- <ShiftFiltersProvider>
335
- <ShiftList />
336
- <FilterPanel />
337
- </ShiftFiltersProvider>
338
- );
339
- }
340
-
341
- // Use in child components
342
- function ShiftList() {
343
- const { filters, applyFilters } = useShiftFiltersContext();
344
-
345
- // Use shared state
346
- return <div>{/* ... */}</div>;
347
- }
348
- ```
349
-
350
- **Benefits:**
351
-
352
- - Minimal boilerplate compared to raw Context API
353
- - TypeScript support out of the box
354
- - Avoids prop drilling
355
- - Clean separation of state logic
356
-
357
- **When to use Constate:**
358
-
359
- - Sharing state between multiple sibling components
360
- - Complex feature-level state (filters, UI state, form state)
361
- - Alternative to prop drilling
362
-
363
- **When NOT to use Constate:**
364
-
365
- - Server state (use React Query instead)
366
- - Global app state (consider if it's truly needed)
367
- - Simple parent-child communication (use props)
368
-
369
- ## Boolean Hooks
370
-
371
- ```typescript
372
- // Pattern: useIs*, useHas*, useShould*
373
- export function useIsFeatureEnabled(): boolean {
374
- const flags = useFeatureFlags();
375
- return flags.includes("new-feature");
376
- }
377
-
378
- export function useHasPermission(permission: string): boolean {
379
- const user = useUser();
380
- return user.permissions.includes(permission);
381
- }
382
-
383
- export function useShouldShowModal(): boolean {
384
- const hasSeenModal = usePreference("hasSeenModal");
385
- return !hasSeenModal;
386
- }
387
- ```
388
-
389
- ## Data Transformation Hooks
390
-
391
- ```typescript
392
- export function useTransformedData() {
393
- const { data: rawData, isLoading, isError } = useGetRawData();
394
-
395
- const transformedData = useMemo(() => {
396
- if (!rawData) return undefined;
397
-
398
- return rawData.map((item) => ({
399
- ...item,
400
- displayName: formatName(item),
401
- }));
402
- }, [rawData]);
403
-
404
- return {
405
- data: transformedData,
406
- isLoading,
407
- isError,
408
- };
409
- }
410
- ```
411
-
412
- ## Side Effect Hooks
413
-
414
- ```typescript
415
- // Hooks that perform side effects (logging, tracking, etc.)
416
- export function useTrackPageView(pageName: string) {
417
- useEffect(() => {
418
- logEvent("PAGE_VIEWED", { pageName });
419
- }, [pageName]);
420
- }
421
-
422
- // Usage
423
- export function MyPage() {
424
- useTrackPageView("MyPage");
425
- // ... rest of component
426
- }
427
- ```
428
-
429
- ## Composite Hooks
430
-
431
- ```typescript
432
- // Combines multiple hooks and data sources
433
- export function useWorkerBookingsData() {
434
- const worker = useDefinedWorker();
435
- const isFeatureEnabled = useIsFeatureEnabled("new-bookings");
436
-
437
- const {
438
- data: shifts,
439
- isLoading: isLoadingShifts,
440
- refetch: refetchShifts,
441
- } = useGetShifts(worker.id);
442
-
443
- const {
444
- data: invites,
445
- isLoading: isLoadingInvites,
446
- refetch: refetchInvites,
447
- } = useGetInvites(worker.id, { enabled: isFeatureEnabled });
448
-
449
- // Combine data
450
- const bookings = useMemo(() => {
451
- return [...(shifts ?? []), ...(invites ?? [])].sort(sortByDate);
452
- }, [shifts, invites]);
453
-
454
- // Combined loading state
455
- const isLoading = isLoadingShifts || isLoadingInvites;
456
-
457
- // Combined refetch
458
- async function refreshAllData() {
459
- await Promise.all([refetchShifts(), refetchInvites()]);
460
- }
461
-
462
- return {
463
- // Data
464
- bookings,
465
-
466
- // States
467
- isLoading,
468
- isFeatureEnabled,
469
-
470
- // Actions
471
- refreshAllData,
472
- };
473
- }
474
- ```
475
-
476
- ## Co-location
477
-
478
- - Place hooks in `hooks/` folder within feature directory
479
- - Place API hooks in `api/` folder
480
- - Keep generic/shared hooks in `lib/` or `utils/`
481
-
482
- ```text
483
- FeatureName/
484
- ├── api/
485
- │ ├── useGetFeature.ts # API data fetching
486
- │ └── useUpdateFeature.ts
487
- ├── hooks/
488
- │ ├── useFeatureLogic.ts # Business logic hooks
489
- │ ├── useFeatureState.ts # Constate state hooks
490
- │ └── useFeatureFilters.ts
491
- └── components/
492
- └── FeatureComponent.tsx
493
- ```
494
-
495
- ## Options Pattern
496
-
497
- ```typescript
498
- // Always use options object for flexibility
499
- interface UseFeatureOptions {
500
- enabled?: boolean;
501
- refetchInterval?: number;
502
- onSuccess?: (data: Data) => void;
503
- }
504
-
505
- export function useFeature(params: Params, options: UseFeatureOptions = {}) {
506
- const { enabled = true, refetchInterval, onSuccess } = options;
507
-
508
- // Use options in queries
509
- return useQuery({
510
- enabled,
511
- refetchInterval,
512
- onSuccess,
513
- // ...
514
- });
515
- }
516
- ```
517
-
518
- ## Hook Dependencies
519
-
520
- ```typescript
521
- // Be explicit about dependencies
522
- export function useFormattedData(rawData: Data[]) {
523
- return useMemo(() => {
524
- return rawData.map(format);
525
- }, [rawData]); // Clear dependency
526
- }
527
-
528
- // Avoid creating functions in dependency arrays
529
- export function useHandler() {
530
- const [value, setValue] = useState();
531
-
532
- // Good - stable reference
533
- const handleChange = useCallback((newValue: string) => {
534
- setValue(newValue);
535
- }, []); // No dependencies on value
536
-
537
- return handleChange;
538
- }
539
- ```
540
-
541
- ## Best Practices
542
-
543
- - **Prefix with `use`** - Always
544
- - **Return objects, not arrays** - For hooks with multiple values
545
- - **Use constate for shared state** - Avoid prop drilling
546
- - **API hooks in `api/`** - Logic hooks in `hooks/`
547
- - **Clear property names** - `isLoading`, not `loading`
548
- - **Options pattern** - For flexible configuration
549
- - **Explicit dependencies** - In useMemo/useCallback
550
-
551
- <!-- Source: .ruler/frontend/data-fetching.md -->
552
-
553
- # Data Fetching Standards
554
-
555
- ## Technology Stack
556
-
557
- - **React Query** (@tanstack/react-query) for all API calls
558
- - **Axios** for HTTP requests
559
- - **Zod** for response validation
560
-
561
- ## Core Principles
562
-
563
- 1. **Use URL and query parameters in query keys** - Makes cache invalidation predictable
564
- 2. **Always use `useGetQuery` hook** - Provides consistent structure, logging, and validation
565
- 3. **Define Zod schemas** for all API requests and responses
566
- 4. **Log errors with centralized constants** - From `APP_V2_APP_EVENTS`, never inline strings
567
- 5. **Rely on React Query state** - Use `isLoading`, `isError`, `isSuccess` - don't reinvent state management
568
- 6. **Use `enabled` for conditional fetching** - With `isDefined()` helper
569
- 7. **Use `invalidateQueries` for disabled queries** - Not `refetch()` which ignores enabled state
570
-
571
- ## Hook Patterns
572
-
573
- ### Simple Query
574
-
575
- ```typescript
576
- export function useGetUser(userId: string) {
577
- return useGetQuery({
578
- url: `/api/users/${userId}`,
579
- responseSchema: userSchema,
580
- enabled: isDefined(userId),
581
- staleTime: minutesToMilliseconds(5),
582
- meta: {
583
- logErrorMessage: APP_V2_APP_EVENTS.GET_USER_FAILURE,
584
- },
585
- });
586
- }
587
- ```
588
-
589
- ### Infinite/Paginated Query
590
-
591
- ```typescript
592
- export function usePaginatedShifts(params: Params) {
593
- return useInfiniteQuery({
594
- queryKey: ["shifts", params],
595
- queryFn: async ({ pageParam }) => {
596
- const response = await get({
597
- url: "/api/shifts",
598
- queryParams: { cursor: pageParam, ...params },
599
- responseSchema: shiftsResponseSchema,
600
- });
601
- return response.data;
602
- },
603
- getNextPageParam: (lastPage) => lastPage.links.nextCursor,
604
- });
605
- }
606
- ```
607
-
608
- ### Composite Data Fetching
609
-
610
- ```typescript
611
- // Hook that combines multiple queries
612
- export function useWorkerBookingsData() {
613
- const { data: shifts, isLoading: isLoadingShifts, refetch: refetchShifts } = useGetShifts();
614
- const { data: invites, isLoading: isLoadingInvites, refetch: refetchInvites } = useGetInvites();
615
-
616
- // Combine data
617
- const bookings = useMemo(() => {
618
- return [...(shifts ?? []), ...(invites ?? [])];
619
- }, [shifts, invites]);
620
-
621
- // Combine loading states
622
- const isLoading = isLoadingShifts || isLoadingInvites;
623
-
624
- // Combine refetch functions
625
- async function refreshAllData() {
626
- await Promise.all([refetchShifts(), refetchInvites()]);
627
- }
628
-
629
- return {
630
- bookings,
631
- isLoading,
632
- refreshAllData,
633
- };
634
- }
635
- ```
636
-
637
- ## Error Handling
638
-
639
- Always use centralized error constants and handle expected errors gracefully:
640
-
641
- ```typescript
642
- useGetQuery({
643
- url: "/api/resource",
644
- responseSchema: schema,
645
- meta: {
646
- logErrorMessage: APP_V2_APP_EVENTS.GET_RESOURCE_FAILURE, // ✅ Centralized
647
- userErrorMessage: "Failed to load data", // Shows alert to user
648
- },
649
- useErrorBoundary: (error) => {
650
- // Don't show error boundary for 404s (expected errors)
651
- return !(axios.isAxiosError(error) && error.response?.status === 404);
652
- },
653
- retry: (failureCount, error) => {
654
- // Don't retry 404s or 401s
655
- if (axios.isAxiosError(error)) {
656
- const status = error.response?.status;
657
- return ![404, 401].includes(status ?? 0);
658
- }
659
- return failureCount < 3;
660
- },
661
- });
662
- ```
663
-
664
- ## State Management - Don't Reinvent the Wheel
665
-
666
- ❌ **Don't** create your own loading/error state:
667
-
668
- ```typescript
669
- const [data, setData] = useState();
670
- const [isLoading, setIsLoading] = useState(false);
671
- const [error, setError] = useState();
672
-
673
- useEffect(() => {
674
- async function fetchData() {
675
- try {
676
- setIsLoading(true);
677
- const result = await api.get("/data");
678
- setData(result);
679
- } catch (err) {
680
- setError(err);
681
- } finally {
682
- setIsLoading(false);
683
- }
684
- }
685
- fetchData();
686
- }, []);
687
- ```
688
-
689
- ✅ **Do** use React Query states:
690
-
691
- ```typescript
692
- const { data, isLoading, isError, isSuccess } = useGetQuery({...});
693
-
694
- if (isLoading) return <Loading />;
695
- if (isError) return <Error />;
696
- if (isSuccess) return <div>{data.property}</div>;
697
- ```
698
-
699
- ## Mutations
700
-
701
- ```typescript
702
- export function useCreateDocument() {
703
- const queryClient = useQueryClient();
704
-
705
- return useMutation({
706
- mutationFn: async (data: CreateDocumentRequest) => {
707
- return await post({
708
- url: "/api/documents",
709
- data,
710
- responseSchema: documentSchema,
711
- });
712
- },
713
- onSuccess: () => {
714
- // Invalidate queries to refetch
715
- queryClient.invalidateQueries(["documents"]);
716
- },
717
- onError: (error) => {
718
- logEvent(APP_V2_APP_EVENTS.CREATE_DOCUMENT_FAILURE, { error });
719
- },
720
- });
721
- }
722
- ```
723
-
724
- ## Query Keys
725
-
726
- Always include URL and parameters in query keys:
727
-
728
- ```typescript
729
- // ❌ Don't use static strings
730
- useQuery({ queryKey: "users", ... });
731
-
732
- // ✅ Do include URL and params
733
- useQuery({ queryKey: [`/api/users?${status}`, { status }], ... });
734
-
735
- // Consistent query key structure
736
- export const queryKeys = {
737
- users: ["users"] as const,
738
- user: (id: string) => ["users", id] as const,
739
- userShifts: (id: string) => ["users", id, "shifts"] as const,
740
- };
741
-
742
- // Usage
743
- useQuery({
744
- queryKey: queryKeys.user(userId),
745
- // ...
746
- });
747
- ```
748
-
749
- ## Refetch Intervals
750
-
751
- ```typescript
752
- useGetQuery({
753
- url: "/api/resource",
754
- responseSchema: schema,
755
- refetchInterval: (data) => {
756
- // Dynamic refetch based on data state
757
- if (!data?.isComplete) {
758
- return 1000; // Poll every second until complete
759
- }
760
- return 0; // Stop refetching
761
- },
762
- });
763
- ```
764
-
765
- ## Conditional Fetching
766
-
767
- Use `enabled` option with `isDefined()` helper:
768
-
769
- ```typescript
770
- import { isDefined } from "@/lib/utils";
771
-
772
- const { data } = useGetQuery({
773
- url: "/api/resource",
774
- responseSchema: schema,
775
- // Only fetch when conditions are met
776
- enabled: isDefined(userId) && isFeatureEnabled,
777
- });
778
- ```
779
-
780
- ## Refetch vs InvalidateQueries
781
-
782
- **Important:** For disabled queries, use `invalidateQueries` instead of `refetch`:
783
-
784
- ❌ **Don't** use `refetch()` on disabled queries:
785
-
786
- ```typescript
787
- const { refetch, data } = useGetQuery({
788
- enabled: isDefined(shift.agentId),
789
- ...
790
- });
791
-
792
- // Will fetch even if agentId is undefined!
793
- refetch();
794
- ```
795
-
796
- ✅ **Do** use `invalidateQueries`:
797
-
798
- ```typescript
799
- const queryClient = useQueryClient();
800
-
801
- const { data } = useGetQuery({
802
- enabled: isDefined(shift.agentId),
803
- ...
804
- });
805
-
806
- // Respects the enabled state
807
- queryClient.invalidateQueries({ queryKey: [myQueryKey] });
808
- ```
809
-
810
- ## Query Cancellation
811
-
812
- ```typescript
813
- export function usePaginatedData() {
814
- const queryClient = useQueryClient();
815
-
816
- return useInfiniteQuery({
817
- queryKey: ["data"],
818
- queryFn: async ({ pageParam }) => {
819
- // Cancel previous in-flight requests
820
- await queryClient.cancelQueries({ queryKey: ["data"] });
821
-
822
- const response = await get({
823
- url: "/api/data",
824
- queryParams: { cursor: pageParam },
825
- });
826
- return response.data;
827
- },
828
- // ...
829
- });
830
- }
831
- ```
832
-
833
- ## Naming Conventions
834
-
835
- - **useGet\*** - Simple queries: `useGetUser`, `useGetShift`
836
- - **usePaginated\*** - Infinite queries: `usePaginatedPlacements`
837
- - **useFetch\*** - Complex fetching logic: `useFetchPaginatedInterviews`
838
- - **Mutations**: `useCreateDocument`, `useUpdateShift`, `useDeletePlacement`
839
-
840
- ## Response Transformation
841
-
842
- ```typescript
843
- export function useGetUser(userId: string) {
844
- return useGetQuery({
845
- url: `/api/users/${userId}`,
846
- responseSchema: userResponseSchema,
847
- select: (data) => {
848
- // Transform response data
849
- return {
850
- ...data,
851
- fullName: `${data.firstName} ${data.lastName}`,
852
- };
853
- },
854
- });
855
- }
856
- ```
857
-
858
- ## Hook Location
859
-
860
- - **API hooks** → Place in `api/` folder within feature directory
861
- - **One endpoint = one hook** principle
862
- - Export types inferred from Zod: `export type User = z.infer<typeof userSchema>`
863
-
864
- Example:
865
-
866
- ```text
867
- Feature/
868
- ├── api/
869
- │ ├── useGetResource.ts
870
- │ ├── useCreateResource.ts
871
- │ └── schemas.ts (optional)
872
- ```
873
-
874
- <!-- Source: .ruler/frontend/error-handling.md -->
875
-
876
- # Error Handling Standards
877
-
878
- ## React Query Error Handling
879
-
880
- ### Basic Error Configuration
881
-
882
- ```typescript
883
- useGetQuery({
884
- url: "/api/resource",
885
- responseSchema: schema,
886
- meta: {
887
- logErrorMessage: APP_V2_APP_EVENTS.GET_RESOURCE_FAILURE,
888
- },
889
- useErrorBoundary: (error) => {
890
- // Show error boundary for 500s, not for 404s
891
- return !(axios.isAxiosError(error) && error.response?.status === 404);
892
- },
893
- retry: (failureCount, error) => {
894
- // Don't retry 404s or 401s
895
- if (axios.isAxiosError(error)) {
896
- const status = error.response?.status;
897
- return ![404, 401].includes(status ?? 0);
898
- }
899
- return failureCount < 3;
900
- },
901
- });
902
- ```
903
-
904
- ### Error Boundary Strategy
905
-
906
- - **Show error boundary** for unexpected errors (500s, network failures)
907
- - **Don't show error boundary** for expected errors (404s, validation errors)
908
- - Use `useErrorBoundary` to control this behavior
909
-
910
- ```typescript
911
- useErrorBoundary: (error) => {
912
- // Only show error boundary for server errors
913
- if (axios.isAxiosError(error)) {
914
- const status = error.response?.status;
915
- return status !== undefined && status >= 500;
916
- }
917
- return true; // Show for non-Axios errors
918
- };
919
- ```
920
-
921
- ### Retry Configuration
922
-
923
- ```typescript
924
- // Don't retry client errors
925
- retry: (failureCount, error) => {
926
- if (axios.isAxiosError(error)) {
927
- const status = error.response?.status;
928
- // Don't retry 4xx errors
929
- if (status !== undefined && status >= 400 && status < 500) {
930
- return false;
931
- }
932
- }
933
- // Retry server errors up to 3 times
934
- return failureCount < 3;
935
- };
936
- ```
937
-
938
- ### Exponential Backoff
939
-
940
- ```typescript
941
- import { type QueryClient } from "@tanstack/react-query";
942
-
943
- const queryClient = new QueryClient({
944
- defaultOptions: {
945
- queries: {
946
- retry: 3,
947
- retryDelay: (attemptIndex) => {
948
- // Exponential backoff: 1s, 2s, 4s
949
- return Math.min(1000 * 2 ** attemptIndex, 30000);
950
- },
951
- },
952
- },
953
- });
954
- ```
955
-
956
- ## Component Error States
957
-
958
- ### Pattern: Loading → Error → Success
959
-
960
- ```typescript
961
- export function DataComponent() {
962
- const { data, isLoading, isError, error, refetch } = useGetData();
963
-
964
- if (isLoading) {
965
- return <LoadingState />;
966
- }
967
-
968
- if (isError) {
969
- return <ErrorState message="Failed to load data" onRetry={refetch} error={error} />;
970
- }
971
-
972
- // Happy path
973
- return <DataDisplay data={data} />;
974
- }
975
- ```
976
-
977
- ### Inline Error Messages
978
-
979
- ```typescript
980
- export function FormComponent() {
981
- const mutation = useCreateResource();
982
-
983
- return (
984
- <form onSubmit={handleSubmit}>
985
- {mutation.isError && <Alert severity="error">Failed to save. Please try again.</Alert>}
986
-
987
- <Button type="submit" loading={mutation.isLoading} disabled={mutation.isLoading}>
988
- Save
989
- </Button>
990
- </form>
991
- );
992
- }
993
- ```
994
-
995
- ### Graceful Degradation
996
-
997
- ```typescript
998
- export function OptionalDataComponent() {
999
- const { data, isError } = useGetOptionalData();
1000
-
1001
- // Don't block UI for optional data
1002
- if (isError) {
1003
- logError("Failed to load optional data");
1004
- return null; // or show simplified version
1005
- }
1006
-
1007
- if (!data) {
1008
- return null;
1009
- }
1010
-
1011
- return <EnhancedView data={data} />;
1012
- }
1013
- ```
1014
-
1015
- ## Mutation Error Handling
1016
-
1017
- ### onError Callback
1018
-
1019
- ```typescript
1020
- export function useCreateDocument() {
1021
- const queryClient = useQueryClient();
1022
-
1023
- return useMutation({
1024
- mutationFn: createDocumentApi,
1025
- onSuccess: (data) => {
1026
- queryClient.invalidateQueries(["documents"]);
1027
- showSuccessToast("Document created");
1028
- },
1029
- onError: (error) => {
1030
- logEvent(APP_V2_APP_EVENTS.CREATE_DOCUMENT_FAILURE, {
1031
- error: error.message,
1032
- });
1033
- showErrorToast("Failed to create document");
1034
- },
1035
- });
1036
- }
1037
- ```
1038
-
1039
- ### Handling Specific Errors
1040
-
1041
- ```typescript
1042
- export function useUpdateProfile() {
1043
- return useMutation({
1044
- mutationFn: updateProfileApi,
1045
- onError: (error: AxiosError) => {
1046
- if (error.response?.status === 409) {
1047
- showErrorToast("Email already exists");
1048
- } else if (error.response?.status === 422) {
1049
- showErrorToast("Invalid data provided");
1050
- } else {
1051
- showErrorToast("Failed to update profile");
1052
- }
1053
- },
1054
- });
1055
- }
1056
- ```
1057
-
1058
- ## Logging and Monitoring
1059
-
1060
- ### Event Logging
1061
-
1062
- ```typescript
1063
- import { logEvent } from '@/lib/analytics';
1064
- import { APP_EVENTS } from '@/constants/events';
1065
-
1066
- // In query configuration
1067
- meta: {
1068
- logErrorMessage: APP_V2_APP_EVENTS.GET_SHIFTS_FAILURE,
1069
- }
1070
-
1071
- // In error handlers
1072
- onError: (error) => {
1073
- logEvent(APP_V2_APP_EVENTS.BOOKING_FAILED, {
1074
- shiftId,
1075
- error: error.message,
1076
- userId: worker.id,
1077
- });
1078
- }
1079
- ```
1080
-
1081
- ### Error Context
1082
-
1083
- Always include relevant context when logging errors:
1084
-
1085
- ```typescript
1086
- logEvent(APP_V2_APP_EVENTS.API_ERROR, {
1087
- endpoint: "/api/shifts",
1088
- method: "GET",
1089
- statusCode: error.response?.status,
1090
- errorMessage: error.message,
1091
- userId: worker.id,
1092
- timestamp: new Date().toISOString(),
1093
- });
1094
- ```
1095
-
1096
- ## Validation Errors
1097
-
1098
- ### Zod Validation
1099
-
1100
- ```typescript
1101
- import { z } from "zod";
1102
-
1103
- const formSchema = z.object({
1104
- email: z.string().email("Invalid email address"),
1105
- age: z.number().min(18, "Must be 18 or older"),
1106
- });
1107
-
1108
- try {
1109
- const validated = formSchema.parse(formData);
1110
- // Use validated data
1111
- } catch (error) {
1112
- if (error instanceof z.ZodError) {
1113
- // Handle validation errors
1114
- error.errors.forEach((err) => {
1115
- showFieldError(err.path.join("."), err.message);
1116
- });
1117
- }
1118
- }
1119
- ```
1120
-
1121
- ### API Validation Errors
1122
-
1123
- ```typescript
1124
- interface ApiValidationError {
1125
- field: string;
1126
- message: string;
1127
- }
1128
-
1129
- function handleApiValidationError(error: AxiosError) {
1130
- const validationErrors = error.response?.data?.errors as ApiValidationError[];
1131
-
1132
- if (validationErrors) {
1133
- validationErrors.forEach(({ field, message }) => {
1134
- setFieldError(field, message);
1135
- });
1136
- }
1137
- }
1138
- ```
1139
-
1140
- ## Network Errors
1141
-
1142
- ### Offline Detection
1143
-
1144
- ```typescript
1145
- export function useNetworkStatus() {
1146
- const [isOnline, setIsOnline] = useState(navigator.onLine);
1147
-
1148
- useEffect(() => {
1149
- function handleOnline() {
1150
- setIsOnline(true);
1151
- }
1152
-
1153
- function handleOffline() {
1154
- setIsOnline(false);
1155
- }
1156
-
1157
- window.addEventListener("online", handleOnline);
1158
- window.addEventListener("offline", handleOffline);
1159
-
1160
- return () => {
1161
- window.removeEventListener("online", handleOnline);
1162
- window.removeEventListener("offline", handleOffline);
1163
- };
1164
- }, []);
1165
-
1166
- return isOnline;
1167
- }
1168
- ```
1169
-
1170
- ### Offline UI
1171
-
1172
- ```typescript
1173
- export function AppContainer() {
1174
- const isOnline = useNetworkStatus();
1175
-
1176
- return (
1177
- <>
1178
- {!isOnline && (
1179
- <Banner severity="warning">You are offline. Some features may not be available.</Banner>
1180
- )}
1181
- <App />
1182
- </>
1183
- );
1184
- }
1185
- ```
1186
-
1187
- ## Timeout Handling
1188
-
1189
- ### Request Timeouts
1190
-
1191
- ```typescript
1192
- import axios from "axios";
1193
-
1194
- const api = axios.create({
1195
- timeout: 30000, // 30 seconds
1196
- });
1197
-
1198
- api.interceptors.response.use(
1199
- (response) => response,
1200
- (error) => {
1201
- if (error.code === "ECONNABORTED") {
1202
- showErrorToast("Request timed out. Please try again.");
1203
- }
1204
- return Promise.reject(error);
1205
- },
1206
- );
1207
- ```
1208
-
1209
- ## Error Boundaries
1210
-
1211
- ### React Error Boundary
1212
-
1213
- ```typescript
1214
- import { Component, type ReactNode } from "react";
1215
-
1216
- interface Props {
1217
- children: ReactNode;
1218
- fallback?: ReactNode;
1219
- }
1220
-
1221
- interface State {
1222
- hasError: boolean;
1223
- error?: Error;
1224
- }
1225
-
1226
- export class ErrorBoundary extends Component<Props, State> {
1227
- constructor(props: Props) {
1228
- super(props);
1229
- this.state = { hasError: false };
1230
- }
1231
-
1232
- static getDerivedStateFromError(error: Error): State {
1233
- return { hasError: true, error };
1234
- }
1235
-
1236
- componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
1237
- logEvent("ERROR_BOUNDARY_TRIGGERED", {
1238
- error: error.message,
1239
- componentStack: errorInfo.componentStack,
1240
- });
1241
- }
1242
-
1243
- render() {
1244
- if (this.state.hasError) {
1245
- return this.props.fallback || <ErrorFallback />;
1246
- }
1247
-
1248
- return this.props.children;
1249
- }
1250
- }
1251
- ```
1252
-
1253
- ## Best Practices
1254
-
1255
- ### 1. Always Handle Errors
1256
-
1257
- ```typescript
1258
- // ❌ Don't ignore errors
1259
- const { data } = useGetData();
1260
-
1261
- // ✅ Handle error states
1262
- const { data, isError, error } = useGetData();
1263
- if (isError) {
1264
- return <ErrorState error={error} />;
1265
- }
1266
- ```
1267
-
1268
- ### 2. Provide User-Friendly Messages
1269
-
1270
- ```typescript
1271
- // ❌ Show technical errors to users
1272
- <Alert>{error.message}</Alert>
1273
-
1274
- // ✅ Show helpful messages
1275
- <Alert>
1276
- We couldn't load your shifts. Please check your connection and try again.
1277
- </Alert>
1278
- ```
1279
-
1280
- ### 3. Log Errors for Debugging
1281
-
1282
- ```typescript
1283
- // Always log errors for monitoring
1284
- onError: (error) => {
1285
- logEvent(APP_V2_APP_EVENTS.ERROR, {
1286
- context: "shift-booking",
1287
- error: error.message,
1288
- });
1289
- showErrorToast("Booking failed");
1290
- };
1291
- ```
1292
-
1293
- ### 4. Provide Recovery Actions
1294
-
1295
- ```typescript
1296
- // ✅ Give users a way to recover
1297
- <ErrorState message="Failed to load data" onRetry={refetch} onDismiss={() => navigate("/home")} />
1298
- ```
1299
-
1300
- ### 5. Different Strategies for Different Errors
1301
-
1302
- ```typescript
1303
- // Critical errors: Show error boundary
1304
- useErrorBoundary: (error) => isCriticalError(error);
1305
-
1306
- // Expected errors: Show inline message
1307
- if (isError && error.response?.status === 404) {
1308
- return <NotFoundMessage />;
1309
- }
1310
-
1311
- // Transient errors: Auto-retry with backoff
1312
- retry: (failureCount) => failureCount < 3;
1313
- ```
1314
-
1315
- <!-- Source: .ruler/frontend/file-organization.md -->
1316
-
1317
- # File Organization Standards
1318
-
1319
- ## Feature-Based Structure
1320
-
1321
- ```text
1322
- FeatureName/
1323
- ├── api/ # Data fetching hooks
1324
- │ ├── useGetFeature.ts
1325
- │ ├── useUpdateFeature.ts
1326
- │ └── useDeleteFeature.ts
1327
- ├── components/ # Feature-specific components
1328
- │ ├── FeatureCard.tsx
1329
- │ ├── FeatureList.tsx
1330
- │ └── FeatureHeader.tsx
1331
- ├── hooks/ # Feature-specific hooks (non-API)
1332
- │ ├── useFeatureLogic.ts
1333
- │ └── useFeatureState.ts
1334
- ├── utils/ # Feature utilities
1335
- │ ├── formatFeature.ts
1336
- │ ├── formatFeature.test.ts
1337
- │ └── validateFeature.ts
1338
- ├── __tests__/ # Integration tests (optional)
1339
- │ └── FeatureFlow.test.tsx
1340
- ├── Page.tsx # Main page component
1341
- ├── Router.tsx # Feature routes
1342
- ├── paths.ts # Route paths
1343
- ├── types.ts # Shared types
1344
- ├── constants.ts # Constants
1345
- └── README.md # Feature documentation (optional)
1346
- ```
1347
-
1348
- ## File Naming Conventions
1349
-
1350
- ### React Components
1351
-
1352
- - **PascalCase** for all React components
1353
- - Examples: `Button.tsx`, `UserProfile.tsx`, `ShiftCard.tsx`
1354
-
1355
- ### Avoid Path Stuttering
1356
-
1357
- Don't repeat directory names in file names - the full path provides enough context:
1358
-
1359
- ❌ **Bad** - Path stuttering:
1360
-
1361
- ```text
1362
- Shift/
1363
- ShiftInvites/
1364
- ShiftInviteCard.tsx // ❌ "Shift" repeated 3 times in path
1365
- ShiftInviteList.tsx // ❌ Import: Shift/ShiftInvites/ShiftInviteCard
1366
- ```
1367
-
1368
- ✅ **Good** - Clean, concise:
1369
-
1370
- ```text
1371
- Shift/
1372
- Invites/
1373
- Card.tsx // ✅ Path: Shift/Invites/Card
1374
- List.tsx // ✅ Import: Shift/Invites/List
1375
- ```
1376
-
1377
- **Reasoning:**
1378
-
1379
- - The full path already provides context (`Shift/Invites/Card` is clear)
1380
- - Repeating names makes imports verbose: `import { ShiftInviteCard } from 'Shift/ShiftInvites/ShiftInviteCard'`
1381
- - Shorter names are easier to work with in the editor
1382
-
1383
- ### Utilities and Hooks
1384
-
1385
- - **camelCase** for utilities, hooks, and non-component files
1386
- - Examples: `formatDate.ts`, `useAuth.ts`, `calculateTotal.ts`
1387
-
1388
- ### Multi-word Non-Components
1389
-
1390
- - **camelCase** for multi-word utility and configuration files
1391
- - Examples: `userProfileUtils.ts`, `apiHelpers.ts`
1392
-
1393
- ### Test Files
1394
-
1395
- - Co-locate with source: `Button.test.tsx` next to `Button.tsx`
1396
- - Test folder: `__tests__/` for integration tests
1397
- - Pattern: `*.test.ts` or `*.test.tsx`
1398
-
1399
- ### Constants and Types
1400
-
1401
- - `types.ts` - Shared types for the feature
1402
- - `constants.ts` - Feature constants
1403
- - `paths.ts` - Route path constants
1404
-
1405
- ## Import Organization
1406
-
1407
- ### Import Order
1408
-
1409
- ```typescript
1410
- // 1. External dependencies (React, third-party)
1411
- import { useState, useEffect } from "react";
1412
- import { useQuery } from "@tanstack/react-query";
1413
- import { parseISO, format } from "date-fns";
1414
-
1415
- // 2. Internal packages (@clipboard-health, @src)
1416
- import { Button } from "@clipboard-health/ui-components";
1417
- import { CbhIcon } from "@clipboard-health/ui-components";
1418
- import { formatDate } from "@src/appV2/lib/dates";
1419
- import { useDefinedWorker } from "@src/appV2/Worker/useDefinedWorker";
1420
-
1421
- // 3. Relative imports (same feature)
1422
- import { useFeatureData } from "./hooks/useFeatureData";
1423
- import { FeatureCard } from "./components/FeatureCard";
1424
- import { FEATURE_PATHS } from "./paths";
1425
- import { type FeatureData } from "./types";
1426
- ```
1427
-
1428
- ### Import Grouping Rules
1429
-
1430
- - Add blank lines between groups
1431
- - Sort alphabetically within each group (optional but recommended)
1432
- - Group type imports with their module: `import { type User } from './types'`
1433
-
1434
- ## Path Management
1435
-
1436
- ### Defining Paths
1437
-
1438
- ```typescript
1439
- // paths.ts
1440
- import { APP_PATHS } from "@/constants/paths";
1441
-
1442
- export const FEATURE_BASE_PATH = "feature";
1443
- export const FEATURE_FULL_PATH = `${APP_PATHS.APP_V2_HOME}/${FEATURE_BASE_PATH}`;
1444
- export const FEATURE_PATHS = {
1445
- ROOT: FEATURE_FULL_PATH,
1446
- DETAILS: `${FEATURE_FULL_PATH}/:id`,
1447
- EDIT: `${FEATURE_FULL_PATH}/:id/edit`,
1448
- CREATE: `${FEATURE_FULL_PATH}/create`,
1449
- } as const;
1450
- ```
1451
-
1452
- ### Using Paths
1453
-
1454
- ```typescript
1455
- import { useHistory } from "react-router-dom";
1456
- import { FEATURE_PATHS } from "./paths";
1457
-
1458
- // Navigation
1459
- history.push(FEATURE_PATHS.DETAILS.replace(":id", featureId));
1460
-
1461
- // Route definition
1462
- <Route path={FEATURE_PATHS.DETAILS} component={FeatureDetailsPage} />;
1463
- ```
1464
-
1465
- ## Types and Interfaces
1466
-
1467
- ### Separate vs Co-located Types
1468
-
1469
- ```typescript
1470
- // Option 1: Separate types.ts for shared types
1471
- // types.ts
1472
- export interface Feature {
1473
- id: string;
1474
- name: string;
1475
- }
1476
-
1477
- export type FeatureStatus = "active" | "inactive";
1478
-
1479
- // Option 2: Co-located with component for component-specific types
1480
- // FeatureCard.tsx
1481
- interface FeatureCardProps {
1482
- feature: Feature;
1483
- onSelect: (id: string) => void;
1484
- }
1485
-
1486
- export function FeatureCard(props: FeatureCardProps) {
1487
- // ...
1488
- }
1489
- ```
1490
-
1491
- ## Constants
1492
-
1493
- ### Defining Constants
1494
-
1495
- ```typescript
1496
- // constants.ts
1497
- export const FEATURE_STATUS = {
1498
- ACTIVE: "active",
1499
- INACTIVE: "inactive",
1500
- PENDING: "pending",
1501
- } as const;
1502
-
1503
- export type FeatureStatus = (typeof FEATURE_STATUS)[keyof typeof FEATURE_STATUS];
1504
-
1505
- export const MAX_ITEMS = 100;
1506
- export const DEFAULT_PAGE_SIZE = 20;
1507
-
1508
- export const FEATURE_EVENTS = {
1509
- VIEWED: "FEATURE_VIEWED",
1510
- CREATED: "FEATURE_CREATED",
1511
- UPDATED: "FEATURE_UPDATED",
1512
- } as const;
1513
- ```
1514
-
1515
- ## Folder Depth Guidelines
1516
-
1517
- - **Maximum 3 levels deep** for feature folders
1518
- - For deeper nesting, consider splitting into separate features
1519
- - Use meaningful folder names that describe the content
1520
-
1521
- ```text
1522
- Good:
1523
- ├── Shift/
1524
- │ ├── Calendar/
1525
- │ │ └── ShiftCalendarCore.tsx
1526
- │ └── Card/
1527
- │ └── ShiftCard.tsx
1528
-
1529
- Avoid:
1530
- ├── Shift/
1531
- │ ├── Components/
1532
- │ │ ├── Display/
1533
- │ │ │ ├── Calendar/
1534
- │ │ │ │ └── Core/
1535
- │ │ │ │ └── ShiftCalendarCore.tsx # Too deep!
1536
- ```
1537
-
1538
- ## Module Exports
1539
-
1540
- ### Index Files
1541
-
1542
- Avoid using `index.ts` files in the redesign folder. Prefer explicit imports.
1543
-
1544
- ```typescript
1545
- // Avoid
1546
- // index.ts
1547
- export * from "./Button";
1548
- export * from "./Card";
1549
-
1550
- // Prefer explicit imports
1551
- import { Button } from "@/components/Button";
1552
- import { Card } from "@/components/Card";
1553
- ```
1554
-
1555
- ### Named Exports
1556
-
1557
- Always use named exports (not default exports) in redesign code.
1558
-
1559
- ```typescript
1560
- // Good
1561
- export function Button(props: ButtonProps) {}
1562
-
1563
- // Avoid
1564
- export default function Button(props: ButtonProps) {}
1565
- ```
1566
-
1567
- ## API Folder Structure
1568
-
1569
- ```text
1570
- api/
1571
- ├── useGetFeatures.ts # GET requests
1572
- ├── useCreateFeature.ts # POST requests
1573
- ├── useUpdateFeature.ts # PUT/PATCH requests
1574
- ├── useDeleteFeature.ts # DELETE requests
1575
- └── schemas.ts # Zod schemas (optional)
1576
- ```
1577
-
1578
- ## Utils Folder Guidelines
1579
-
1580
- - Keep utilities pure functions when possible
1581
- - Co-locate tests with utilities
1582
- - Export individual functions (not as objects)
1583
-
1584
- ```typescript
1585
- // Good
1586
- // utils/formatFeatureName.ts
1587
- export function formatFeatureName(name: string): string {
1588
- return name.trim().toUpperCase();
1589
- }
1590
-
1591
- // utils/formatFeatureName.test.ts
1592
- import { formatFeatureName } from "./formatFeatureName";
1593
-
1594
- describe("formatFeatureName", () => {
1595
- it("should format name correctly", () => {
1596
- expect(formatFeatureName(" test ")).toBe("TEST");
1597
- });
1598
- });
1599
- ```
1600
-
1601
- <!-- Source: .ruler/frontend/imports.md -->
1602
-
1603
- # Import Standards
1604
-
1605
- ## Component Wrapper Pattern
1606
-
1607
- Many projects wrap third-party UI library components to add app-specific functionality. This can be enforced via ESLint rules.
1608
-
1609
- ## Restricted MUI Imports
1610
-
1611
- ### ❌ Component Restrictions (Example)
1612
-
1613
- Some projects restrict direct imports of certain components from `@mui/material`:
1614
-
1615
- ```typescript
1616
- // ❌ Forbidden
1617
- import {
1618
- Avatar,
1619
- Accordion,
1620
- AccordionDetails,
1621
- AccordionSummary,
1622
- Badge,
1623
- Button,
1624
- Card,
1625
- Chip,
1626
- Dialog,
1627
- DialogTitle,
1628
- Divider,
1629
- Drawer,
1630
- FilledInput,
1631
- Icon,
1632
- IconButton,
1633
- InputBase,
1634
- List,
1635
- ListItem,
1636
- ListItemButton,
1637
- ListItemIcon,
1638
- ListItemText,
1639
- Modal,
1640
- OutlinedInput,
1641
- Rating,
1642
- Slider,
1643
- TextField,
1644
- Typography,
1645
- Tab,
1646
- Tabs,
1647
- SvgIcon,
1648
- } from "@mui/material";
1649
- ```
1650
-
1651
- ### ✅ Use Internal Wrappers
1652
-
1653
- ```typescript
1654
- // ✅ Correct - Use project wrappers
1655
- import { Button } from "@clipboard-health/ui-components/Button";
1656
- import { IconButton } from "@clipboard-health/ui-components/IconButton";
1657
- import { LoadingButton } from "@clipboard-health/ui-components/LoadingButton";
1658
- ```
1659
-
1660
- ### Rationale
1661
-
1662
- 1. Wrappers provide app-specific functionality and consistent behavior
1663
- 2. Use `sx` prop for custom styles with theme access
1664
- 3. Prefer app-specific dialog components over generic Modal components
1665
-
1666
- ## Icon Restrictions
1667
-
1668
- ### ❌ Third-Party Icons (Example)
1669
-
1670
- ```typescript
1671
- // ❌ Avoid direct imports from icon libraries
1672
- import SearchIcon from "@mui/icons-material/Search";
1673
- import CloseIcon from "@mui/icons-material/Close";
1674
- import AddIcon from "@mui/icons-material/Add";
1675
- ```
1676
-
1677
- ### ✅ Use Project Icon Component
1678
-
1679
- ```typescript
1680
- // ✅ Correct - Use project's icon system
1681
- import { Icon } from '@clipboard-health/ui-components';
1682
-
1683
- <Icon type="search" size="large" />
1684
- <Icon type="close" size="medium" />
1685
- <Icon type="plus" size="small" />
1686
- ```
1687
-
1688
- Many projects maintain their own icon system for consistency and customization.
1689
-
1690
- ## Allowed MUI Imports
1691
-
1692
- ### ✅ Safe to Import from MUI
1693
-
1694
- These components can be imported directly:
1695
-
1696
- ```typescript
1697
- import {
1698
- Box,
1699
- Stack,
1700
- Container,
1701
- Grid,
1702
- Paper,
1703
- Skeleton,
1704
- CircularProgress,
1705
- LinearProgress,
1706
- BottomNavigation,
1707
- BottomNavigationAction,
1708
- ThemeProvider,
1709
- useTheme,
1710
- useMediaQuery,
1711
- } from "@mui/material";
1712
- ```
1713
-
1714
- Layout and utility components are generally safe.
1715
-
1716
- ## Path Aliases
1717
-
1718
- ### Use @ Prefix for Absolute Imports
1719
-
1720
- ```typescript
1721
- // ✅ Use path aliases configured in tsconfig
1722
- import { formatDate } from "@/lib/dates";
1723
- import { useUser } from "@/features/user/hooks/useUser";
1724
- import { Button } from "@clipboard-health/ui-components/Button";
1725
- import { theme } from "@/theme";
1726
-
1727
- // ❌ Avoid relative paths to distant folders
1728
- import { formatDate } from "../../../lib/dates";
1729
- ```
1730
-
1731
- ### Relative Imports for Same Feature
1732
-
1733
- ```typescript
1734
- // ✅ Relative imports within the same feature
1735
- import { FeatureCard } from "./components/FeatureCard";
1736
- import { useFeatureData } from "./hooks/useFeatureData";
1737
- import { FEATURE_PATHS } from "./paths";
1738
- import { type FeatureData } from "./types";
1739
- ```
1740
-
1741
- ## Import Grouping
1742
-
1743
- ### Standard Order
1744
-
1745
- ```typescript
1746
- // 1. External dependencies (React, third-party libraries)
1747
- import { useState, useEffect, useMemo } from "react";
1748
- import { useQuery } from "@tanstack/react-query";
1749
- import { parseISO, format } from "date-fns";
1750
- import { z } from "zod";
1751
-
1752
- // 2. Internal absolute imports (via path aliases)
1753
- import { Button, Icon } from "@clipboard-health/ui-components";
1754
- import { theme } from "@/theme";
1755
- import { formatDate } from "@/lib/dates";
1756
- import { useUser } from "@/features/user/hooks/useUser";
1757
- import { APP_PATHS } from "@/constants/paths";
1758
-
1759
- // 3. Relative imports (same feature/module)
1760
- import { useFeatureData } from "./hooks/useFeatureData";
1761
- import { FeatureCard } from "./components/FeatureCard";
1762
- import { FEATURE_PATHS } from "./paths";
1763
- import { type FeatureData, type FeatureOptions } from "./types";
1764
- ```
1765
-
1766
- ### Blank Lines Between Groups
1767
-
1768
- - Add blank line between each group
1769
- - Helps with readability and organization
1770
- - ESLint/Prettier can auto-format this
1771
-
1772
- ## Type Imports
1773
-
1774
- ### Inline Type Imports
1775
-
1776
- ```typescript
1777
- // ✅ Preferred: Inline type imports
1778
- import { type User, type UserOptions } from "./types";
1779
- import { formatUser } from "./utils";
1780
- ```
1781
-
1782
- ### Separate Type Imports
1783
-
1784
- ```typescript
1785
- // ✅ Also acceptable
1786
- import type { User, UserOptions } from "./types";
1787
- import { formatUser } from "./utils";
1788
- ```
1789
-
1790
- ## Barrel Exports (index.ts)
1791
-
1792
- ### Consider Avoiding Barrel Exports
1793
-
1794
- ```typescript
1795
- // ❌ Barrel exports can slow build times
1796
- // index.ts
1797
- export * from "./Button";
1798
- export * from "./Card";
1799
- ```
1800
-
1801
- ### ✅ Use Explicit Imports
1802
-
1803
- ```typescript
1804
- // ✅ Import directly from files for better tree-shaking
1805
- import { Button } from "@clipboard-health/ui-components/Button";
1806
- import { Card } from "@clipboard-health/ui-components/Card";
1807
- ```
1808
-
1809
- Note: Barrel exports can cause issues with circular dependencies and slow down builds, especially in large projects.
1810
-
1811
- ## Dynamic Imports
1812
-
1813
- ### Code Splitting
1814
-
1815
- ```typescript
1816
- // For large components or routes
1817
- const HeavyComponent = lazy(() => import("./HeavyComponent"));
1818
-
1819
- // In component
1820
- <Suspense fallback={<Loading />}>
1821
- <HeavyComponent />
1822
- </Suspense>;
1823
- ```
1824
-
1825
- ## Common Import Patterns
1826
-
1827
- ### API Utilities
1828
-
1829
- ```typescript
1830
- import { useQuery } from "@/lib/api/hooks";
1831
- import { api } from "@/lib/api/client";
1832
- ```
1833
-
1834
- ### React Query
1835
-
1836
- ```typescript
1837
- import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
1838
- import { type UseQueryOptions, type UseQueryResult } from "@tanstack/react-query";
1839
- ```
1840
-
1841
- ### Routing
1842
-
1843
- ```typescript
1844
- import { useHistory, useLocation, useParams } from "react-router-dom";
1845
- import { type LocationState } from "history";
1846
- ```
1847
-
1848
- ### Date Utilities
1849
-
1850
- ```typescript
1851
- import { parseISO, format, addDays, isBefore } from "date-fns";
1852
- ```
1853
-
1854
- ### Validation
1855
-
1856
- ```typescript
1857
- import { z } from "zod";
1858
- import { zodResolver } from "@hookform/resolvers/zod";
1859
- ```
1860
-
1861
- ## ESLint Configuration
1862
-
1863
- Import restrictions can be enforced with ESLint's `no-restricted-imports` rule:
1864
-
1865
- ```javascript
1866
- module.exports = {
1867
- rules: {
1868
- "no-restricted-imports": [
1869
- "error",
1870
- {
1871
- paths: [
1872
- {
1873
- name: "@mui/material",
1874
- importNames: ["Button", "TextField", "Dialog"],
1875
- message: "Use wrapper components from @/components",
1876
- },
1877
- ],
1878
- patterns: [
1879
- {
1880
- group: ["@mui/icons-material/*"],
1881
- message: "Use project icon component instead",
1882
- },
1883
- ],
1884
- },
1885
- ],
1886
- },
1887
- };
1888
- ```
1889
-
1890
- ## Checking for Violations
1891
-
1892
- ```bash
1893
- # Lint your code
1894
- npm run lint
1895
-
1896
- # Auto-fix import issues
1897
- npm run lint:fix
1898
- ```
1899
-
1900
- ## Migration Guide
1901
-
1902
- ### When You See Import Errors
1903
-
1904
- 1. **Wrapper Component Error**
1905
- - Check if wrapper exists in `@/components/`
1906
- - If yes, import from there
1907
- - If no, discuss with team about creating wrapper
1908
-
1909
- 2. **Icon Error**
1910
- - Find equivalent in project icon system
1911
- - Use project's icon component
1912
- - Check available icon names in documentation
1913
-
1914
- 3. **Deprecated Pattern Error**
1915
- - Follow the suggested replacement pattern
1916
- - Move to modern alternatives (e.g., `sx` prop instead of `styled`)
1917
-
1918
- ## Summary
1919
-
1920
- ✅ **DO**:
1921
-
1922
- - Use project wrapper components instead of third-party components directly
1923
- - Use project icon system for consistency
1924
- - Use path aliases (e.g., `@/`) for absolute imports
1925
- - Group imports by external, internal, relative
1926
- - Consider avoiding barrel exports for better build performance
1927
-
1928
- ❌ **DON'T**:
1929
-
1930
- - Import third-party UI components directly if wrappers exist
1931
- - Import icon libraries directly if project has custom icon system
1932
- - Use deprecated styling patterns (check project guidelines)
1933
- - Use relative imports for distant files
1934
- - Create excessive barrel exports that hurt tree-shaking
1935
-
1936
- <!-- Source: .ruler/frontend/performance.md -->
1937
-
1938
- # Performance Standards
1939
-
1940
- ## React Query Optimization
1941
-
1942
- ### Stale Time Configuration
1943
-
1944
- ```typescript
1945
- // Set appropriate staleTime to avoid unnecessary refetch
1946
- useGetQuery({
1947
- url: "/api/resource",
1948
- responseSchema: schema,
1949
- staleTime: minutesToMilliseconds(5), // Don't refetch for 5 minutes
1950
- cacheTime: minutesToMilliseconds(30), // Keep in cache for 30 minutes
1951
- });
1952
- ```
1953
-
1954
- ### Conditional Fetching
1955
-
1956
- ```typescript
1957
- // Only fetch when conditions are met
1958
- const { data } = useGetQuery({
1959
- url: `/api/users/${userId}`,
1960
- responseSchema: userSchema,
1961
- enabled: isDefined(userId) && isFeatureEnabled, // Don't fetch until ready
1962
- });
1963
- ```
1964
-
1965
- ### Query Cancellation
1966
-
1967
- ```typescript
1968
- export function usePaginatedData(params: Params) {
1969
- const queryClient = useQueryClient();
1970
-
1971
- return useInfiniteQuery({
1972
- queryKey: ["data", params],
1973
- queryFn: async ({ pageParam }) => {
1974
- // Cancel previous in-flight requests
1975
- await queryClient.cancelQueries({ queryKey: ["data"] });
1976
-
1977
- const response = await get({
1978
- url: "/api/data",
1979
- queryParams: { cursor: pageParam, ...params },
1980
- });
1981
- return response.data;
1982
- },
1983
- getNextPageParam: (lastPage) => lastPage.nextCursor,
1984
- });
1985
- }
1986
- ```
1987
-
1988
- ### Prefetching
1989
-
1990
- ```typescript
1991
- export function usePreloadNextPage(nextUserId: string) {
1992
- const queryClient = useQueryClient();
1993
-
1994
- useEffect(() => {
1995
- if (nextUserId) {
1996
- // Prefetch next page in background
1997
- queryClient.prefetchQuery({
1998
- queryKey: ["user", nextUserId],
1999
- queryFn: () => fetchUser(nextUserId),
2000
- staleTime: minutesToMilliseconds(5),
2001
- });
2002
- }
2003
- }, [nextUserId, queryClient]);
2004
- }
2005
- ```
2006
-
2007
- ## React Optimization
2008
-
2009
- ### useMemo for Expensive Computations
2010
-
2011
- ```typescript
2012
- export function DataList({ items }: { items: Item[] }) {
2013
- // Memoize expensive sorting/filtering
2014
- const sortedItems = useMemo(() => {
2015
- return items.filter((item) => item.isActive).sort((a, b) => a.priority - b.priority);
2016
- }, [items]);
2017
-
2018
- return <List items={sortedItems} />;
2019
- }
2020
- ```
2021
-
2022
- ### useCallback for Event Handlers
2023
-
2024
- ```typescript
2025
- export function ParentComponent() {
2026
- const [selected, setSelected] = useState<string>();
2027
-
2028
- // Memoize callback to prevent child re-renders
2029
- const handleSelect = useCallback((id: string) => {
2030
- setSelected(id);
2031
- logEvent("ITEM_SELECTED", { id });
2032
- }, []); // Stable reference
2033
-
2034
- return <ChildComponent onSelect={handleSelect} />;
2035
- }
2036
- ```
2037
-
2038
- ### React.memo for Pure Components
2039
-
2040
- ```typescript
2041
- import { memo } from "react";
2042
-
2043
- interface ItemCardProps {
2044
- item: Item;
2045
- onSelect: (id: string) => void;
2046
- }
2047
-
2048
- // Memoize component to prevent unnecessary re-renders
2049
- export const ItemCard = memo(function ItemCard({ item, onSelect }: ItemCardProps) {
2050
- return (
2051
- <Card onClick={() => onSelect(item.id)}>
2052
- <h3>{item.name}</h3>
2053
- </Card>
2054
- );
2055
- });
2056
- ```
2057
-
2058
- ### Avoid Inline Object/Array Creation
2059
-
2060
- ```typescript
2061
- // ❌ Creates new object on every render
2062
- <Component style={{ padding: 8 }} />
2063
- <Component items={[1, 2, 3]} />
2064
-
2065
- // ✅ Define outside or use useMemo
2066
- const style = { padding: 8 };
2067
- const items = [1, 2, 3];
2068
- <Component style={style} items={items} />
2069
-
2070
- // ✅ Or use useMemo for dynamic values
2071
- const style = useMemo(() => ({ padding: spacing }), [spacing]);
2072
- ```
2073
-
2074
- ## List Rendering
2075
-
2076
- ### Key Prop for Lists
2077
-
2078
- ```typescript
2079
- // ✅ Use stable, unique keys
2080
- items.map((item) => <ItemCard key={item.id} item={item} />);
2081
-
2082
- // ❌ Don't use index as key (unless list never changes)
2083
- items.map((item, index) => <ItemCard key={index} item={item} />);
2084
- ```
2085
-
2086
- ### Virtualization for Long Lists
2087
-
2088
- ```typescript
2089
- import { FixedSizeList } from "react-window";
2090
-
2091
- export function VirtualizedList({ items }: { items: Item[] }) {
2092
- return (
2093
- <FixedSizeList height={600} itemCount={items.length} itemSize={80} width="100%">
2094
- {({ index, style }) => (
2095
- <div style={style}>
2096
- <ItemCard item={items[index]} />
2097
- </div>
2098
- )}
2099
- </FixedSizeList>
2100
- );
2101
- }
2102
- ```
2103
-
2104
- ### Pagination Instead of Infinite Data
2105
-
2106
- ```typescript
2107
- // For large datasets, use pagination
2108
- export function PaginatedList() {
2109
- const [page, setPage] = useState(1);
2110
- const pageSize = 20;
2111
-
2112
- const { data, isLoading } = useGetPaginatedData({
2113
- page,
2114
- pageSize,
2115
- });
2116
-
2117
- return (
2118
- <>
2119
- <List items={data?.items} />
2120
- <Pagination page={page} total={data?.total} pageSize={pageSize} onChange={setPage} />
2121
- </>
2122
- );
2123
- }
2124
- ```
2125
-
2126
- ## Data Fetching Patterns
2127
-
2128
- ### Parallel Queries
2129
-
2130
- ```typescript
2131
- export function useParallelData() {
2132
- // Fetch in parallel
2133
- const users = useGetUsers();
2134
- const shifts = useGetShifts();
2135
- const workplaces = useGetWorkplaces();
2136
-
2137
- // All queries run simultaneously
2138
- const isLoading = users.isLoading || shifts.isLoading || workplaces.isLoading;
2139
-
2140
- return {
2141
- users: users.data,
2142
- shifts: shifts.data,
2143
- workplaces: workplaces.data,
2144
- isLoading,
2145
- };
2146
- }
2147
- ```
2148
-
2149
- ### Dependent Queries
2150
-
2151
- ```typescript
2152
- export function useDependentData(userId?: string) {
2153
- // First query
2154
- const { data: user } = useGetUser(userId, {
2155
- enabled: isDefined(userId),
2156
- });
2157
-
2158
- // Second query depends on first
2159
- const { data: shifts } = useGetUserShifts(user?.id, {
2160
- enabled: isDefined(user?.id), // Only fetch when user is loaded
2161
- });
2162
-
2163
- return { user, shifts };
2164
- }
2165
- ```
2166
-
2167
- ### Debouncing Search Queries
2168
-
2169
- ```typescript
2170
- import { useDebouncedValue } from "@/lib/hooks";
2171
-
2172
- export function SearchComponent() {
2173
- const [searchTerm, setSearchTerm] = useState("");
2174
- const debouncedSearch = useDebouncedValue(searchTerm, 300);
2175
-
2176
- const { data } = useSearchQuery(debouncedSearch, {
2177
- enabled: debouncedSearch.length > 2,
2178
- });
2179
-
2180
- return (
2181
- <>
2182
- <input value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
2183
- <Results data={data} />
2184
- </>
2185
- );
2186
- }
2187
- ```
2188
-
2189
- ## Code Splitting
2190
-
2191
- ### Route-Based Splitting
2192
-
2193
- ```typescript
2194
- import { lazy, Suspense } from "react";
2195
-
2196
- // Lazy load route components
2197
- const ShiftDetailsPage = lazy(() => import("./Shift/DetailsPage"));
2198
- const ProfilePage = lazy(() => import("./Profile/Page"));
2199
-
2200
- export function Router() {
2201
- return (
2202
- <Suspense fallback={<LoadingScreen />}>
2203
- <Routes>
2204
- <Route path="/shifts/:id" element={<ShiftDetailsPage />} />
2205
- <Route path="/profile" element={<ProfilePage />} />
2206
- </Routes>
2207
- </Suspense>
2208
- );
2209
- }
2210
- ```
2211
-
2212
- ### Component-Based Splitting
2213
-
2214
- ```typescript
2215
- // Split large components that aren't immediately needed
2216
- const HeavyChart = lazy(() => import("./HeavyChart"));
2217
-
2218
- export function Dashboard() {
2219
- const [showChart, setShowChart] = useState(false);
2220
-
2221
- return (
2222
- <div>
2223
- <Summary />
2224
- {showChart && (
2225
- <Suspense fallback={<ChartSkeleton />}>
2226
- <HeavyChart />
2227
- </Suspense>
2228
- )}
2229
- </div>
2230
- );
2231
- }
2232
- ```
2233
-
2234
- ## Image Optimization
2235
-
2236
- ### Lazy Loading Images
2237
-
2238
- ```typescript
2239
- <img
2240
- src={imageUrl}
2241
- alt={alt}
2242
- loading="lazy" // Native lazy loading
2243
- />
2244
- ```
2245
-
2246
- ### Responsive Images
2247
-
2248
- ```typescript
2249
- <img
2250
- srcSet={`
2251
- ${image_small} 480w,
2252
- ${image_medium} 800w,
2253
- ${image_large} 1200w
2254
- `}
2255
- sizes="(max-width: 480px) 480px, (max-width: 800px) 800px, 1200px"
2256
- src={image_medium}
2257
- alt={alt}
2258
- />
2259
- ```
2260
-
2261
- ## State Management
2262
-
2263
- ### Avoid Prop Drilling
2264
-
2265
- ```typescript
2266
- // ❌ Prop drilling
2267
- <Parent>
2268
- <Child data={data}>
2269
- <GrandChild data={data}>
2270
- <GreatGrandChild data={data} />
2271
- </GrandChild>
2272
- </Child>
2273
- </Parent>;
2274
-
2275
- // ✅ Use context for deeply nested data
2276
- const DataContext = createContext<Data | undefined>(undefined);
2277
-
2278
- <DataContext.Provider value={data}>
2279
- <Parent>
2280
- <Child>
2281
- <GrandChild>
2282
- <GreatGrandChild />
2283
- </GrandChild>
2284
- </Child>
2285
- </Parent>
2286
- </DataContext.Provider>;
2287
- ```
2288
-
2289
- ### Local State Over Global State
2290
-
2291
- ```typescript
2292
- // ✅ Keep state as local as possible
2293
- export function FormComponent() {
2294
- const [formData, setFormData] = useState({}); // Local state
2295
- // Only lift state up when needed by multiple components
2296
- }
2297
- ```
2298
-
2299
- ## Bundle Size Optimization
2300
-
2301
- ### Tree Shaking
2302
-
2303
- ```typescript
2304
- // ✅ Import only what you need
2305
- import { format } from "date-fns";
2306
-
2307
- // ❌ Imports entire library
2308
- import * as dateFns from "date-fns";
2309
- ```
2310
-
2311
- ### Avoid Large Dependencies
2312
-
2313
- ```typescript
2314
- // Check bundle size before adding dependencies
2315
- // Use lighter alternatives when possible
2316
-
2317
- // ❌ Heavy library for simple task
2318
- import moment from "moment";
2319
-
2320
- // ✅ Lighter alternative
2321
- import { format } from "date-fns";
2322
- ```
2323
-
2324
- ## Monitoring Performance
2325
-
2326
- ### React DevTools Profiler
2327
-
2328
- ```typescript
2329
- // Wrap components to profile
2330
- <Profiler id="ShiftList" onRender={onRenderCallback}>
2331
- <ShiftList />
2332
- </Profiler>
2333
- ```
2334
-
2335
- ### Web Vitals
2336
-
2337
- ```typescript
2338
- import { getCLS, getFID, getFCP, getLCP, getTTFB } from "web-vitals";
2339
-
2340
- // Track Core Web Vitals
2341
- getCLS(console.log);
2342
- getFID(console.log);
2343
- getFCP(console.log);
2344
- getLCP(console.log);
2345
- getTTFB(console.log);
2346
- ```
2347
-
2348
- ## Best Practices Summary
2349
-
2350
- ### ✅ DO
2351
-
2352
- - Set appropriate `staleTime` and `cacheTime` for queries
2353
- - Use `useMemo` for expensive computations
2354
- - Use `useCallback` for callbacks passed to children
2355
- - Use React.memo for pure components
2356
- - Virtualize long lists
2357
- - Lazy load routes and heavy components
2358
- - Use pagination for large datasets
2359
- - Debounce search inputs
2360
- - Cancel queries when component unmounts
2361
- - Prefetch data when predictable
2362
-
2363
- ### ❌ DON'T
2364
-
2365
- - Fetch data unnecessarily
2366
- - Create objects/arrays inline in props
2367
- - Use index as key for dynamic lists
2368
- - Render all items in very long lists
2369
- - Import entire libraries when only need parts
2370
- - Keep all state global
2371
- - Ignore performance warnings in console
2372
- - Skip memoization for expensive operations
2373
-
2374
- <!-- Source: .ruler/frontend/react-patterns.md -->
2375
-
2376
- # React Component Patterns
2377
-
2378
- ## Core Principles
2379
-
2380
- - **Storybook is the single source of truth** for UI components, not Figma
2381
- - **Named exports only** (prefer named exports over default exports)
2382
- - **Explicit types** for all props and return values
2383
- - **Handle all states**: loading, error, empty, success
2384
- - **Composition over configuration** - prefer children over complex props
2385
-
2386
- ## Component Structure
2387
-
2388
- Follow this consistent structure for all components:
2389
-
2390
- ```typescript
2391
- // 1. Imports (grouped with blank lines between groups)
2392
- import { useState, useMemo, useCallback } from "react";
2393
- import { Box, Typography } from "@mui/material";
2394
-
2395
- import { useGetUser } from "@/api/hooks/useGetUser";
2396
- import { formatDate } from "@/utils/date";
2397
-
2398
- import { ChildComponent } from "./ChildComponent";
2399
-
2400
- // 2. Types (interfaces for props, types for unions)
2401
- interface UserCardProps {
2402
- userId: string;
2403
- onAction: (action: string) => void;
2404
- isHighlighted?: boolean;
2405
- }
2406
-
2407
- // 3. Component definition
2408
- export function UserCard({ userId, onAction, isHighlighted = false }: UserCardProps) {
2409
- // A. React Query hooks first
2410
- const { data: user, isLoading, isError } = useGetUser(userId);
2411
-
2412
- // B. Local state
2413
- const [isExpanded, setIsExpanded] = useState(false);
2414
-
2415
- // C. Derived values (with useMemo for expensive computations)
2416
- const displayName = useMemo(
2417
- () => (user ? `${user.firstName} ${user.lastName}` : "Unknown"),
2418
- [user]
2419
- );
2420
-
2421
- // D. Event handlers (with useCallback when passed to children)
2422
- const handleToggle = useCallback(() => {
2423
- setIsExpanded((prev) => !prev);
2424
- onAction("toggle");
2425
- }, [onAction]);
2426
-
2427
- // E. Early returns for loading/error states
2428
- if (isLoading) return <LoadingState />;
2429
- if (isError) return <ErrorState message="Failed to load user" />;
2430
- if (!user) return <EmptyState message="User not found" />;
2431
-
2432
- // F. Render
2433
- return (
2434
- <Box sx={{ padding: 2, backgroundColor: isHighlighted ? "primary.light" : "background.paper" }}>
2435
- <Typography variant="h6">{displayName}</Typography>
2436
- <ChildComponent onClick={handleToggle} />
2437
- </Box>
2438
- );
2439
- }
2440
- ```
2441
-
2442
- ## Why This Structure?
2443
-
2444
- 1. **Imports grouped** - Easy to see dependencies
2445
- 2. **Types first** - Documents component API
2446
- 3. **Hooks at top** - React rules of hooks
2447
- 4. **Derived values next** - Shows data flow
2448
- 5. **Handlers together** - Easy to find event logic
2449
- 6. **Early returns** - Fail fast, reduce nesting
2450
- 7. **Render last** - Main component logic
2451
-
2452
- ## Component Naming
2453
-
2454
- - **PascalCase** for components: `UserProfile`, `DataCard`
2455
- - **camelCase** for hooks and utilities: `useUserData`, `formatDate`
2456
- - Prefer named exports over default exports for better refactoring support
2457
-
2458
- ## Props
2459
-
2460
- - Always define explicit prop types
2461
- - Use destructuring with types
2462
- - Avoid prop spreading unless wrapping a component
2463
-
2464
- ```typescript
2465
- // Good
2466
- interface ButtonProps {
2467
- onClick: () => void;
2468
- label: string;
2469
- disabled?: boolean;
2470
- }
2471
-
2472
- export function Button({ onClick, label, disabled = false }: ButtonProps) {
2473
- return (
2474
- <button onClick={onClick} disabled={disabled}>
2475
- {label}
2476
- </button>
2477
- );
2478
- }
2479
-
2480
- // Acceptable for wrappers
2481
- export function CustomButton(props: ButtonProps) {
2482
- return <ButtonBase {...props} LinkComponent={InternalLink} />;
2483
- }
2484
- ```
2485
-
2486
- ## Wrappers
2487
-
2488
- - Wrap third-party components to add app-specific functionality
2489
- - Example: Wrapping a third-party Button with custom link handling
2490
-
2491
- ```typescript
2492
- import {
2493
- Button as ButtonBase,
2494
- type ButtonProps as ButtonPropsBase,
2495
- } from "@some-ui-library/components";
2496
- import { type LocationState } from "history";
2497
-
2498
- import { InternalLink } from "./InternalLink";
2499
-
2500
- interface ButtonProps extends Omit<ButtonPropsBase, "LinkComponent"> {
2501
- locationState?: LocationState;
2502
- }
2503
-
2504
- export function Button(props: ButtonProps) {
2505
- return <ButtonBase {...props} LinkComponent={InternalLink} />;
2506
- }
2507
- ```
2508
-
2509
- ## State Management
2510
-
2511
- - Use `useState` for local component state
2512
- - Use `useMemo` for expensive computations
2513
- - Use `useCallback` for functions passed to children
2514
- - Lift state up when needed by multiple components
2515
-
2516
- ## Conditional Rendering
2517
-
2518
- ```typescript
2519
- // Early returns for loading/error states
2520
- if (isLoading) return <LoadingState />;
2521
- if (isError) return <ErrorState />;
2522
-
2523
- // Ternary for simple conditions
2524
- return isActive ? <ActiveView /> : <InactiveView />;
2525
-
2526
- // && for conditional rendering
2527
- return <div>{hasData && <DataDisplay data={data} />}</div>;
2528
- ```
2529
-
2530
- ## Component Composition
2531
-
2532
- Prefer composition over complex props. Build small, focused components that compose together.
2533
-
2534
- ```typescript
2535
- // ✅ Good - Composition pattern
2536
- interface CardProps {
2537
- children: ReactNode;
2538
- }
2539
-
2540
- export function Card({ children }: CardProps) {
2541
- return <Box sx={{ padding: 3, borderRadius: 2, boxShadow: 1 }}>{children}</Box>;
2542
- }
2543
-
2544
- export function CardHeader({ children }: { children: ReactNode }) {
2545
- return (
2546
- <Box sx={{ marginBottom: 2 }}>
2547
- <Typography variant="h6">{children}</Typography>
2548
- </Box>
2549
- );
2550
- }
2551
-
2552
- export function CardContent({ children }: { children: ReactNode }) {
2553
- return <Box>{children}</Box>;
2554
- }
2555
-
2556
- // Usage - Flexible and composable
2557
- <Card>
2558
- <CardHeader>User Profile</CardHeader>
2559
- <CardContent>
2560
- <UserDetails user={user} />
2561
- <UserActions onEdit={handleEdit} />
2562
- </CardContent>
2563
- </Card>;
2564
-
2565
- // ❌ Bad - Complex props that limit flexibility
2566
- interface ComplexCardProps {
2567
- title: string;
2568
- subtitle?: string;
2569
- actions?: ReactNode;
2570
- content: ReactNode;
2571
- variant?: "default" | "highlighted" | "error";
2572
- showBorder?: boolean;
2573
- elevation?: number;
2574
- }
2575
-
2576
- export function ComplexCard(props: ComplexCardProps) {
2577
- // Too many props, hard to extend
2578
- // ...
2579
- }
2580
- ```
2581
-
2582
- ## Children Patterns
2583
-
2584
- ### Render Props Pattern
2585
-
2586
- Use when child components need access to parent state:
2587
-
2588
- ```typescript
2589
- interface DataProviderProps {
2590
- children: (data: Data, isLoading: boolean) => ReactNode;
2591
- }
2592
-
2593
- export function DataProvider({ children }: DataProviderProps) {
2594
- const { data, isLoading } = useGetData();
2595
-
2596
- return <>{children(data, isLoading)}</>;
2597
- }
2598
-
2599
- // Usage
2600
- <DataProvider>
2601
- {(data, isLoading) => (isLoading ? <Loading /> : <DataDisplay data={data} />)}
2602
- </DataProvider>;
2603
- ```
2604
-
2605
- ### Compound Components Pattern
2606
-
2607
- For components that work together:
2608
-
2609
- ```typescript
2610
- interface TabsContextValue {
2611
- activeTab: string;
2612
- setActiveTab: (tab: string) => void;
2613
- }
2614
-
2615
- const TabsContext = createContext<TabsContextValue | undefined>(undefined);
2616
-
2617
- export function Tabs({ children, defaultTab }: { children: ReactNode; defaultTab: string }) {
2618
- const [activeTab, setActiveTab] = useState(defaultTab);
2619
-
2620
- return (
2621
- <TabsContext.Provider value={{ activeTab, setActiveTab }}>
2622
- <Box>{children}</Box>
2623
- </TabsContext.Provider>
2624
- );
2625
- }
2626
-
2627
- export function TabList({ children }: { children: ReactNode }) {
2628
- return <Box sx={{ display: "flex", gap: 1 }}>{children}</Box>;
2629
- }
2630
-
2631
- export function Tab({ value, children }: { value: string; children: ReactNode }) {
2632
- const context = useContext(TabsContext);
2633
- if (!context) throw new Error("Tab must be used within Tabs");
2634
-
2635
- const { activeTab, setActiveTab } = context;
2636
- const isActive = activeTab === value;
2637
-
2638
- return (
2639
- <Button onClick={() => setActiveTab(value)} variant={isActive ? "contained" : "text"}>
2640
- {children}
2641
- </Button>
2642
- );
2643
- }
2644
-
2645
- export function TabPanel({ value, children }: { value: string; children: ReactNode }) {
2646
- const context = useContext(TabsContext);
2647
- if (!context) throw new Error("TabPanel must be used within Tabs");
2648
-
2649
- if (context.activeTab !== value) return null;
2650
- return <Box sx={{ padding: 2 }}>{children}</Box>;
2651
- }
2652
-
2653
- // Usage - Intuitive API
2654
- <Tabs defaultTab="profile">
2655
- <TabList>
2656
- <Tab value="profile">Profile</Tab>
2657
- <Tab value="settings">Settings</Tab>
2658
- </TabList>
2659
- <TabPanel value="profile">
2660
- <ProfileContent />
2661
- </TabPanel>
2662
- <TabPanel value="settings">
2663
- <SettingsContent />
2664
- </TabPanel>
2665
- </Tabs>;
2666
- ```
2667
-
2668
- ## Error Boundaries
2669
-
2670
- Use error boundaries for graceful error handling:
2671
-
2672
- ```typescript
2673
- interface ErrorBoundaryProps {
2674
- children: ReactNode;
2675
- fallback?: ReactNode;
2676
- }
2677
-
2678
- interface ErrorBoundaryState {
2679
- hasError: boolean;
2680
- error?: Error;
2681
- }
2682
-
2683
- export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
2684
- constructor(props: ErrorBoundaryProps) {
2685
- super(props);
2686
- this.state = { hasError: false };
2687
- }
2688
-
2689
- static getDerivedStateFromError(error: Error): ErrorBoundaryState {
2690
- return { hasError: true, error };
2691
- }
2692
-
2693
- componentDidCatch(error: Error, errorInfo: ErrorInfo) {
2694
- console.error("Error caught by boundary:", error, errorInfo);
2695
- // Log to error tracking service
2696
- }
2697
-
2698
- render() {
2699
- if (this.state.hasError) {
2700
- return this.props.fallback || <ErrorFallback error={this.state.error} />;
2701
- }
2702
-
2703
- return this.props.children;
2704
- }
2705
- }
2706
-
2707
- // Usage
2708
- <ErrorBoundary fallback={<ErrorPage />}>
2709
- <App />
2710
- </ErrorBoundary>;
2711
- ```
2712
-
2713
- ## Handling Lists
2714
-
2715
- ### Key Props
2716
-
2717
- Always use stable, unique keys (never index):
2718
-
2719
- ```typescript
2720
- // ✅ Good - Unique, stable ID
2721
- {
2722
- users.map((user) => <UserCard key={user.id} user={user} />);
2723
- }
2724
-
2725
- // ❌ Bad - Index as key (causes bugs when list changes)
2726
- {
2727
- users.map((user, index) => <UserCard key={index} user={user} />);
2728
- }
2729
-
2730
- // ✅ Acceptable - Composite key when no ID available
2731
- {
2732
- items.map((item) => <ItemCard key={`${item.type}-${item.name}`} item={item} />);
2733
- }
2734
- ```
2735
-
2736
- ### Empty States
2737
-
2738
- Always handle empty lists:
2739
-
2740
- ```typescript
2741
- export function UserList({ users }: { users: User[] }) {
2742
- if (users.length === 0) {
2743
- return (
2744
- <EmptyState
2745
- icon={<PersonIcon />}
2746
- title="No users found"
2747
- description="Try adjusting your search criteria"
2748
- />
2749
- );
2750
- }
2751
-
2752
- return (
2753
- <Box>
2754
- {users.map((user) => (
2755
- <UserCard key={user.id} user={user} />
2756
- ))}
2757
- </Box>
2758
- );
2759
- }
2760
- ```
2761
-
2762
- ## Conditional Rendering Best Practices
2763
-
2764
- ```typescript
2765
- export function ItemCard({ item }: { item: Item }) {
2766
- // ✅ Good - Early returns for invalid states
2767
- if (!item) return null;
2768
- if (item.isDeleted) return null;
2769
-
2770
- // ✅ Good - Ternary for simple either/or
2771
- const statusColor = item.isUrgent ? "error" : "default";
2772
-
2773
- return (
2774
- <Box>
2775
- <Typography color={statusColor}>{item.title}</Typography>
2776
-
2777
- {/* ✅ Good - && for optional elements */}
2778
- {item.isFeatured && <FeaturedBadge />}
2779
-
2780
- {/* ✅ Good - Ternary for alternate content */}
2781
- {item.isAvailable ? <AvailableStatus /> : <UnavailableStatus />}
2782
-
2783
- {/* ❌ Bad - Nested ternaries (hard to read) */}
2784
- {item.status === "urgent" ? (
2785
- <UrgentBadge />
2786
- ) : item.status === "normal" ? (
2787
- <NormalBadge />
2788
- ) : (
2789
- <DefaultBadge />
2790
- )}
2791
-
2792
- {/* ✅ Good - Extract to variable or switch */}
2793
- <StatusBadge status={item.status} />
2794
- </Box>
2795
- );
2796
- }
2797
- ```
2798
-
2799
- ## Performance Optimization
2800
-
2801
- ### When to Use `useMemo`
2802
-
2803
- ```typescript
2804
- // ✅ Do - Expensive computation
2805
- const sortedUsers = useMemo(() => [...users].sort((a, b) => a.name.localeCompare(b.name)), [users]);
2806
-
2807
- // ❌ Don't - Simple operations (premature optimization)
2808
- const fullName = useMemo(() => `${firstName} ${lastName}`, [firstName, lastName]);
2809
- ```
2810
-
2811
- ### When to Use `useCallback`
2812
-
2813
- ```typescript
2814
- // ✅ Do - Function passed to memoized child
2815
- const MemoizedChild = React.memo(ChildComponent);
2816
-
2817
- function Parent() {
2818
- const handleClick = useCallback(() => {
2819
- console.log("clicked");
2820
- }, []);
2821
-
2822
- return <MemoizedChild onClick={handleClick} />;
2823
- }
2824
-
2825
- // ❌ Don't - Function not passed to children
2826
- const handleSubmit = useCallback(() => {
2827
- // No child components use this
2828
- }, []);
2829
- ```
2830
-
2831
- <!-- Source: .ruler/frontend/react.md -->
2832
-
2833
- # React
2834
-
2835
- - Destructure props in function body rather than in function signature
2836
- - Prefer inline JSX rather than extracting variables and functions as variables outside of JSX
2837
- - Use useModalState for any showing/hiding functionality like dialogs
2838
- - Utilize custom hooks to encapsulate and reuse stateful logic
2839
- - When performing data-fetching in a custom hook, always use Zod to define any request and response schemas
2840
- - Use react-hook-form for all form UIs and use zod resolver for form schema validation
2841
- - Use date-fns for any Date based operations like formatting
2842
-
2843
- <!-- Source: .ruler/frontend/styling.md -->
2844
-
2845
- # Styling Standards
2846
-
2847
- ## Technology Stack
2848
-
2849
- - **Material UI (MUI)** with custom theme
2850
- - **sx prop** for custom styles (NOT `styled()`)
2851
- - Custom component wrappers for consistent UI
2852
- - **Storybook** as single source of truth for UI components
2853
-
2854
- ## Core Principles
2855
-
2856
- 1. **Always use `sx` prop** - Never CSS/SCSS/SASS files
2857
- 2. **Use theme tokens** - Never hardcode colors, spacing, or sizes
2858
- 3. **Leverage meaningful tokens** - Use semantic names like `theme.palette.text.primary`, not `common.white`
2859
- 4. **Type-safe theme access** - Use `sx={(theme) => ({...})}`, not string paths like `"text.secondary"`
2860
- 5. **Follow spacing system** - Use indices 1-12 (4px-64px)
2861
- 6. **Storybook is source of truth** - Check Storybook before Figma
2862
-
2863
- ## Restricted Patterns
2864
-
2865
- ### ❌ DO NOT USE
2866
-
2867
- - `styled()` from MUI (deprecated in our codebase)
2868
- - `makeStyles()` from MUI (deprecated)
2869
- - CSS/SCSS/SASS files
2870
- - Direct MUI icons from `@mui/icons-material`
2871
- - Direct MUI components without wrappers (except layout primitives; see list below)
2872
- - Inline styles via `style` prop (use `sx` instead)
2873
- - String paths for theme tokens (not type-safe)
2874
-
2875
- ### Rationale
2876
-
2877
- 1. Component wrappers provide consistent behavior and app-specific functionality
2878
- 2. `sx` prop provides type-safe access to theme tokens
2879
- 3. Project-specific dialog components ensure consistent UX patterns
2880
-
2881
- ## Storybook as Source of Truth
2882
-
2883
- **Important:** Storybook reflects what's actually implemented, not Figma designs.
2884
-
2885
- ### When Storybook Differs from Figma
2886
-
2887
- 1. **Check Storybook first** - It shows real, implemented components
2888
- 2. **Use closest existing variant** - Don't create one-off font sizes/colors
2889
- 3. **Confirm changes are intentional** - Consult with team before updating components
2890
- 4. **Create follow-up ticket** - If component needs updating but you're short on time
2891
- 5. **Make changes system-wide** - Component updates should benefit entire app
2892
-
2893
- ### Process
2894
-
2895
- - **Minor differences** (font sizes, colors) → Stick to Storybook
2896
- - **Component looks different** → Confirm with team, update component intentionally
2897
- - **Missing component** → Check with team - it may exist with a different name
2898
-
2899
- ## Use Internal Components
2900
-
2901
- ### ✅ ALWAYS USE Project Wrappers
2902
-
2903
- Instead of importing directly from `@mui/material`, use project wrappers:
2904
-
2905
- ```typescript
2906
- // ❌ Don't
2907
- import { Button, IconButton } from "@mui/material";
2908
-
2909
- // ✅ Do
2910
- import { Button } from "@/components/Button";
2911
- import { IconButton } from "@clipboard-health/ui-components";
2912
- ```
2913
-
2914
- ### Component Wrapper List (Example)
2915
-
2916
- Common components that may have wrappers:
2917
-
2918
- - `Button`, `LoadingButton`, `IconButton`
2919
- - `Avatar`, `Accordion`, `Badge`
2920
- - `Card`, `Chip`, `Dialog`
2921
- - `Drawer`, `List`, `ListItem`
2922
- - `Rating`, `Slider`, `Switch`
2923
- - `TextField`, `Typography`, `Tab`, `Tabs`
2924
-
2925
- Check your project's ESLint configuration for the full list.
2926
-
2927
- ## Icons
2928
-
2929
- ### Use Project Icon Component
2930
-
2931
- ```typescript
2932
- // ❌ Don't use third-party icons directly
2933
- import SearchIcon from '@mui/icons-material/Search';
2934
-
2935
- // ✅ Use project's icon system
2936
- import { CbhIcon } from '@clipboard-health/ui-components';
2937
-
2938
- <CbhIcon type="search" size="large" />
2939
- <CbhIcon type="search-colored" size="medium" />
2940
- ```
2941
-
2942
- ### Icon Variants
2943
-
2944
- - Many icon systems have variants for different states (e.g., `-colored` for active states)
2945
- - Check your project's icon documentation for available variants
2946
-
2947
- ## Styling with sx Prop
2948
-
2949
- ### Basic Usage - Type-Safe Theme Access
2950
-
2951
- ❌ **Never** hardcode values or use string paths:
2952
-
2953
- ```typescript
2954
- <Box
2955
- sx={{
2956
- backgroundColor: "red", // ❌ Raw color
2957
- color: "#ADFF11", // ❌ Hex code
2958
- padding: "16px", // ❌ Raw size
2959
- color: "text.secondary", // ❌ String path (no TypeScript support)
2960
- }}
2961
- />
2962
- ```
2963
-
2964
- ✅ **Always** use theme with type safety:
2965
-
2966
- ```typescript
2967
- <Box
2968
- sx={(theme) => ({
2969
- backgroundColor: theme.palette.background.primary, // ✅ Semantic token
2970
- color: theme.palette.text.secondary, // ✅ Type-safe
2971
- padding: theme.spacing(4), // or just: padding: 4 // ✅ Spacing system
2972
- })}
2973
- />
2974
- ```
2975
-
2976
- ### Use Meaningful Tokens
2977
-
2978
- ❌ **Avoid** non-descriptive tokens:
2979
-
2980
- ```typescript
2981
- theme.palette.common.white; // ❌ No context about usage
2982
- theme.palette.green300; // ❌ Which green? When to use?
2983
- ```
2984
-
2985
- ✅ **Use** semantic tokens:
2986
-
2987
- ```typescript
2988
- theme.palette.background.tertiary; // ✅ Clear purpose
2989
- theme.palette.instantPay.background; // ✅ Intent is obvious
2990
- theme.palette.text.primary; // ✅ Meaningful
2991
- ```
2992
-
2993
- ## Spacing System
2994
-
2995
- We use a strict index-based spacing system:
2996
-
2997
- | Index | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
2998
- | ----- | --- | --- | --- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
2999
- | Size | 4px | 6px | 8px | 12px | 16px | 20px | 24px | 32px | 40px | 48px | 56px | 64px |
3000
-
3001
- **Usage:**
3002
-
3003
- ```typescript
3004
- <Box sx={{ padding: 5 }} /> // → 16px
3005
- <Box sx={{ marginX: 4 }} /> // → 12px left and right
3006
- <Box sx={{ gap: 3 }} /> // → 8px
3007
- ```
3008
-
3009
- **Use `rem` for fonts and heights:**
3010
-
3011
- ```typescript
3012
- <Box
3013
- sx={(theme) => ({
3014
- height: "3rem", // ✅ Scales with user zoom
3015
- fontSize: theme.typography.body1.fontSize, // ✅ From theme
3016
- padding: 5, // ✅ px prevents overflow when zoomed
3017
- })}
3018
- />
3019
- ```
3020
-
3021
- **Reasoning:** Users who adjust device-wide zoom need `rem` for fonts/heights to scale properly, but `px` spacing prevents layout overflow.
3022
-
3023
- ## Theme Integration
3024
-
3025
- ### Responsive Styles
3026
-
3027
- ```typescript
3028
- <Box
3029
- sx={{
3030
- width: {
3031
- xs: "100%", // Mobile
3032
- sm: "75%", // Tablet
3033
- md: "50%", // Desktop
3034
- },
3035
- padding: {
3036
- xs: 1,
3037
- md: 3,
3038
- },
3039
- }}
3040
- />
3041
- ```
3042
-
3043
- ### Pseudo-classes and Hover States
3044
-
3045
- ```typescript
3046
- <Box
3047
- sx={(theme) => ({
3048
- "&:hover": {
3049
- backgroundColor: theme.palette.primary.dark,
3050
- cursor: "pointer",
3051
- },
3052
- "&:disabled": {
3053
- opacity: 0.5,
3054
- },
3055
- "&.active": {
3056
- borderColor: theme.palette.primary.main,
3057
- },
3058
- })}
3059
- />
3060
- ```
3061
-
3062
- ### Nested Selectors
3063
-
3064
- ```typescript
3065
- <Box
3066
- sx={(theme) => ({
3067
- "& .child-element": {
3068
- color: theme.palette.text.secondary,
3069
- },
3070
- "& > div": {
3071
- marginBottom: 1,
3072
- },
3073
- // Target nested MUI components
3074
- "& .MuiTypography-root": {
3075
- color: theme.palette.intent?.disabled.text,
3076
- },
3077
- })}
3078
- />
3079
- ```
3080
-
3081
- ## Shorthand Properties
3082
-
3083
- MUI provides shorthand properties - use full names, not abbreviations:
3084
-
3085
- ✅ **Use full names:**
3086
-
3087
- ```typescript
3088
- <Box
3089
- sx={{
3090
- padding: 2, // ✅ Clear
3091
- paddingX: 4, // ✅ Readable
3092
- marginY: 2, // ✅ Explicit
3093
- }}
3094
- />
3095
- ```
3096
-
3097
- ❌ **Avoid abbreviations** (per naming conventions best practice):
3098
-
3099
- ```typescript
3100
- <Box
3101
- sx={{
3102
- p: 2, // ❌ Too terse
3103
- px: 4, // ❌ Not clear
3104
- my: 2, // ❌ What does this mean?
3105
- }}
3106
- />
3107
- ```
3108
-
3109
- [Full list of shorthand properties](https://mui.com/system/properties/)
3110
-
3111
- ## Merging sx Props
3112
-
3113
- For generic components accepting an `sx` prop, merge default styles with custom styles:
3114
-
3115
- ```typescript
3116
- // Option 1: Array syntax (MUI native)
3117
- <Box
3118
- sx={[
3119
- (theme) => ({
3120
- backgroundColor: theme.palette.background.tertiary,
3121
- padding: 2,
3122
- }),
3123
- sx, // User's custom sx prop
3124
- ]}
3125
- {...restProps}
3126
- />
3127
-
3128
- // Option 2: Use a utility function if your project provides one
3129
- import { mergeSxProps } from "@clipboard-health/ui-components";
3130
-
3131
- <Box
3132
- sx={mergeSxProps(defaultStyles, sx)}
3133
- {...restProps}
3134
- />;
3135
- ```
3136
-
3137
- ## Theme Access
3138
-
3139
- ### Using useTheme Hook
3140
-
3141
- ```typescript
3142
- import { useTheme } from "@mui/material";
3143
-
3144
- export function Component() {
3145
- const theme = useTheme();
3146
-
3147
- return (
3148
- <Box sx={{ color: theme.palette.primary.main }}>
3149
- {/* Your components */}
3150
- </Box>
3151
- );
3152
- }
3153
- ```
3154
-
3155
- ### Theme Properties
3156
-
3157
- ```typescript
3158
- const theme = useTheme();
3159
-
3160
- // Colors
3161
- theme.palette.primary.main;
3162
- theme.palette.secondary.main;
3163
- theme.palette.error.main;
3164
- theme.palette.text.primary;
3165
- theme.palette.background.default;
3166
-
3167
- // Spacing
3168
- theme.spacing(1); // Project-defined (see spacing system above)
3169
- theme.spacing(2); // Project-defined (see spacing system above)
3170
-
3171
- // Typography
3172
- theme.typography.h1;
3173
- theme.typography.body1;
3174
-
3175
- // Breakpoints
3176
- theme.breakpoints.up("md");
3177
- theme.breakpoints.down("sm");
3178
- ```
3179
-
3180
- ## Modal Patterns
3181
-
3182
- ### ❌ Avoid Generic Modal
3183
-
3184
- ```typescript
3185
- // Avoid generic Modal when project has specific dialog components
3186
- import { Modal } from "@mui/material";
3187
- ```
3188
-
3189
- ### ✅ Use Project-Specific Dialog Components
3190
-
3191
- ```typescript
3192
- // For mobile-friendly modals
3193
- import { BottomSheet } from "@/components/BottomSheet";
3194
-
3195
- // For full-screen views
3196
- import { FullScreenDialog } from "@/components/FullScreenDialog";
3197
-
3198
- // For standard dialogs
3199
- import { Dialog } from "@/components/Dialog";
3200
- ```
3201
-
3202
- Check your project's component library for available dialog/modal components.
3203
-
3204
- ## Layout Components
3205
-
3206
- ### Use MUI Layout Components
3207
-
3208
- These are safe to import directly from MUI:
3209
-
3210
- ```typescript
3211
- import { Box, Stack, Container, Grid } from '@mui/material';
3212
-
3213
- // Stack for vertical/horizontal layouts
3214
- <Stack spacing={2} direction="row">
3215
- <Item />
3216
- <Item />
3217
- </Stack>
3218
-
3219
- // Box for flexible containers
3220
- <Box sx={{ display: 'flex', gap: 2 }}>
3221
- <Child />
3222
- </Box>
3223
-
3224
- // Grid for responsive layouts
3225
- <Grid container spacing={2}>
3226
- <Grid item xs={12} md={6}>
3227
- <Content />
3228
- </Grid>
3229
- </Grid>
3230
- ```
3231
-
3232
- ## MUI Theme Augmentation
3233
-
3234
- ### Type Safety
3235
-
3236
- Projects often augment MUI's theme with custom properties:
3237
-
3238
- ```typescript
3239
- // Example: Custom theme augmentation
3240
- declare module "@mui/material/styles" {
3241
- interface Theme {
3242
- customSpacing: {
3243
- small: string;
3244
- large: string;
3245
- };
3246
- }
3247
- interface ThemeOptions {
3248
- customSpacing?: {
3249
- small?: string;
3250
- large?: string;
3251
- };
3252
- }
3253
- }
3254
- ```
3255
-
3256
- Check your project's type definitions for available theme augmentations.
3257
-
3258
- ## Common Patterns
3259
-
3260
- ### Card with Custom Styling
3261
-
3262
- ```typescript
3263
- import { Card, CardContent } from "@mui/material";
3264
-
3265
- <Card
3266
- sx={{
3267
- borderRadius: 2,
3268
- boxShadow: 2,
3269
- "&:hover": {
3270
- boxShadow: 4,
3271
- },
3272
- }}
3273
- >
3274
- <CardContent>Content here</CardContent>
3275
- </Card>;
3276
- ```
3277
-
3278
- ### Buttons with Theme Colors
3279
-
3280
- ```typescript
3281
- import { Button } from "@/components/Button";
3282
-
3283
- <Button
3284
- variant="contained"
3285
- color="primary"
3286
- sx={{
3287
- textTransform: "none", // Override uppercase
3288
- fontWeight: "bold",
3289
- }}
3290
- >
3291
- Submit
3292
- </Button>;
3293
- ```
3294
-
3295
- ### Conditional Styles
3296
-
3297
- ```typescript
3298
- <Box
3299
- sx={(theme) => ({
3300
- backgroundColor: isActive
3301
- ? theme.palette.primary.main
3302
- : theme.palette.grey[200],
3303
- padding: 2,
3304
- })}
3305
- >
3306
- {content}
3307
- </Box>
3308
- ```
3309
-
3310
- ## Best Practices
3311
-
3312
- - **Check Storybook first** - It's the single source of truth
3313
- - **Use theme tokens** - Never hardcode colors/spacing
3314
- - **Type-safe access** - Function form: `sx={(theme) => ({...})}`
3315
- - **Meaningful tokens** - Semantic names over raw colors
3316
- - **Spacing system** - Indices 1-12 (or `theme.spacing(n)`)
3317
- - **Use shorthand props** - `paddingX`, `marginY` (full names, not `px`, `my`)
3318
- - **Leverage pseudo-classes** - For hover, focus, disabled states
3319
- - **Prefer `sx` over direct props** - `sx` takes priority and is more flexible
3320
-
3321
- <!-- Source: .ruler/frontend/testing.md -->
3322
-
3323
- # Testing Standards
3324
-
3325
- ## The Testing Trophy Philosophy
3326
-
3327
- Our testing strategy follows the **Testing Trophy** model:
3328
-
3329
- ```text
3330
- /\_
3331
- /E2E\ ← End-to-End (smallest layer)
3332
- /-----\
3333
- / Integ \ ← Integration (largest layer - FOCUS HERE!)
3334
- /---------\
3335
- / Unit \ ← Unit Tests (helpers/utilities only)
3336
- /-------------\
3337
- / Static \ ← TypeScript + ESLint (foundation)
3338
- ```
3339
-
3340
- **Investment Priority:**
3341
-
3342
- 1. **Static** (TypeScript/ESLint) - Free confidence, catches typos and type errors
3343
- 2. **Integration** - Most valuable, test how components work together as users experience them
3344
- 3. **Unit** - For pure helpers/utilities, NOT UI components
3345
- 4. **E2E** - Critical user flows only, slow and expensive
3346
-
3347
- **Key Principle:** Test as close to how users interact with your app as possible. Users don't shallow-render components or call functions in isolation - they interact with features.
3348
-
3349
- ## Technology Stack
3350
-
3351
- - **Vitest** for test runner
3352
- - **@testing-library/react** for component testing
3353
- - **@testing-library/user-event** for user interactions
3354
- - **Mock Service Worker (MSW)** for API mocking
3355
-
3356
- ## Test File Structure
3357
-
3358
- ```typescript
3359
- import { render, screen, waitFor } from "@testing-library/react";
3360
- import { renderHook } from "@testing-library/react";
3361
- import userEvent from "@testing-library/user-event";
3362
- import { describe, expect, it, vi, beforeEach } from "vitest";
3363
-
3364
- describe("ComponentName", () => {
3365
- beforeEach(() => {
3366
- vi.clearAllMocks();
3367
- });
3368
-
3369
- it("should render correctly", () => {
3370
- render(<Component />);
3371
- expect(screen.getByText("Expected")).toBeInTheDocument();
3372
- });
3373
-
3374
- it("should handle user interaction", async () => {
3375
- const user = userEvent.setup();
3376
- render(<Component />);
3377
-
3378
- await user.click(screen.getByRole("button", { name: "Submit" }));
3379
-
3380
- await waitFor(() => {
3381
- expect(screen.getByText("Success")).toBeInTheDocument();
3382
- });
3383
- });
3384
- });
3385
- ```
3386
-
3387
- ## Test Naming Conventions
3388
-
3389
- ### Describe Blocks
3390
-
3391
- - Use the component/function name: `describe('ComponentName', ...)`
3392
- - Nest describe blocks for complex scenarios
3393
-
3394
- ```typescript
3395
- describe("ShiftCard", () => {
3396
- describe("when shift is urgent", () => {
3397
- it("should display urgent badge", () => {
3398
- // ...
3399
- });
3400
- });
3401
-
3402
- describe("when shift is booked", () => {
3403
- it("should show booked status", () => {
3404
- // ...
3405
- });
3406
- });
3407
- });
3408
- ```
3409
-
3410
- ### Test Names
3411
-
3412
- - Pattern: `'should [expected behavior] when [condition]'`
3413
- - Be descriptive and specific
3414
-
3415
- ```typescript
3416
- // Good
3417
- it("should show loading spinner when data is fetching", () => {});
3418
- it("should display error message when API call fails", () => {});
3419
- it("should enable submit button when form is valid", () => {});
3420
-
3421
- // Avoid
3422
- it("works", () => {});
3423
- it("loading state", () => {});
3424
- ```
3425
-
3426
- ## Parameterized Tests
3427
-
3428
- ### Using it.each
3429
-
3430
- ```typescript
3431
- it.each([
3432
- { input: { isUrgent: true }, expected: "URGENT" },
3433
- { input: { isUrgent: false }, expected: "REGULAR" },
3434
- ])("should return $expected when isUrgent is $input.isUrgent", ({ input, expected }) => {
3435
- expect(getShiftType(input)).toBe(expected);
3436
- });
3437
- ```
3438
-
3439
- ### Table-Driven Tests
3440
-
3441
- ```typescript
3442
- describe("calculateShiftPay", () => {
3443
- it.each([
3444
- { hours: 8, rate: 30, expected: 240 },
3445
- { hours: 10, rate: 25, expected: 250 },
3446
- { hours: 12, rate: 35, expected: 420 },
3447
- ])("should calculate $expected for $hours hours at $rate/hr", ({ hours, rate, expected }) => {
3448
- expect(calculateShiftPay(hours, rate)).toBe(expected);
3449
- });
3450
- });
3451
- ```
3452
-
3453
- ## Component Testing (Integration Tests)
3454
-
3455
- Integration tests form the largest part of the Testing Trophy. Test features, not isolated components.
3456
-
3457
- ### Rendering Components
3458
-
3459
- ```typescript
3460
- import { render, screen } from "@testing-library/react";
3461
- import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
3462
-
3463
- function renderWithProviders(component: ReactElement) {
3464
- const queryClient = new QueryClient({
3465
- defaultOptions: {
3466
- queries: { retry: false },
3467
- },
3468
- });
3469
-
3470
- return render(<QueryClientProvider client={queryClient}>{component}</QueryClientProvider>);
3471
- }
3472
-
3473
- it("should render user name", () => {
3474
- renderWithProviders(<UserProfile userId="123" />);
3475
- expect(screen.getByText("John Doe")).toBeInTheDocument();
3476
- });
3477
- ```
3478
-
3479
- ### Querying Elements - Priority Order
3480
-
3481
- Follow [Testing Library's query priority](https://testing-library.com/docs/queries/about#priority):
3482
-
3483
- 1. **`getByRole`** - Best for accessibility (buttons, links, inputs)
3484
- 2. **`getByLabelText`** - For form fields with labels
3485
- 3. **`getByPlaceholderText`** - For inputs without labels
3486
- 4. **`getByText`** - For non-interactive content
3487
- 5. **`getByDisplayValue`** - For current input values
3488
- 6. **`getByAltText`** - For images
3489
- 7. **`getByTitle`** - Less common
3490
- 8. **`getByTestId`** - ⚠️ **LAST RESORT** - Use only when no other option exists
3491
-
3492
- ```typescript
3493
- // ✅ Prefer accessible queries
3494
- screen.getByRole("button", { name: /submit/i });
3495
- screen.getByLabelText("Email address");
3496
- screen.getByText("Welcome back");
3497
-
3498
- // ❌ Avoid CSS selectors and implementation details
3499
- screen.getByClassName("user-card"); // Users don't see classes
3500
- wrapper.find("UserCard").prop("user"); // Testing implementation
3501
- screen.getByTestId("custom-element"); // Last resort only
3502
- ```
3503
-
3504
- ### User Interactions
3505
-
3506
- ```typescript
3507
- import userEvent from "@testing-library/user-event";
3508
-
3509
- it("should handle form submission", async () => {
3510
- const user = userEvent.setup();
3511
- const onSubmit = vi.fn();
3512
-
3513
- render(<Form onSubmit={onSubmit} />);
3514
-
3515
- // Type in input
3516
- await user.type(screen.getByLabelText("Name"), "John Doe");
3517
-
3518
- // Click button
3519
- await user.click(screen.getByRole("button", { name: "Submit" }));
3520
-
3521
- // Assert
3522
- expect(onSubmit).toHaveBeenCalledWith({ name: "John Doe" });
3523
- });
3524
- ```
3525
-
3526
- ## Hook Testing (Unit Tests)
3527
-
3528
- Only write unit tests for hooks that contain business logic, not for UI components.
3529
-
3530
- ### Using renderHook
3531
-
3532
- ```typescript
3533
- import { renderHook, waitFor } from "@testing-library/react";
3534
-
3535
- describe("useCustomHook", () => {
3536
- it("should return loading state initially", () => {
3537
- const { result } = renderHook(() => useCustomHook());
3538
-
3539
- expect(result.current.isLoading).toBe(true);
3540
- });
3541
-
3542
- it("should return data after loading", async () => {
3543
- const { result } = renderHook(() => useCustomHook());
3544
-
3545
- await waitFor(() => {
3546
- expect(result.current.isLoading).toBe(false);
3547
- });
3548
-
3549
- expect(result.current.data).toEqual(expectedData);
3550
- });
3551
- });
3552
- ```
3553
-
3554
- ### Testing Hook Updates
3555
-
3556
- ```typescript
3557
- it("should update when dependencies change", async () => {
3558
- const { result, rerender } = renderHook(({ userId }) => useGetUser(userId), {
3559
- initialProps: { userId: "1" },
3560
- });
3561
-
3562
- await waitFor(() => {
3563
- expect(result.current.data?.id).toBe("1");
3564
- });
3565
-
3566
- // Update props
3567
- rerender({ userId: "2" });
3568
-
3569
- await waitFor(() => {
3570
- expect(result.current.data?.id).toBe("2");
3571
- });
3572
- });
3573
- ```
3574
-
3575
- ## MSW (Mock Service Worker)
3576
-
3577
- ### Factory Functions Pattern - IMPORTANT
3578
-
3579
- **Always export factory functions, not static handlers**. This allows tests to customize mock responses.
3580
-
3581
- ❌ **Don't** export static handlers (ties tests to single response):
3582
-
3583
- ```typescript
3584
- // Bad - can only return this one mock
3585
- export const facilityNotesSuccessScenario = rest.get(
3586
- `${TEST_API_URL}/facilityNotes`,
3587
- async (_, res, ctx) => res(ctx.status(200), ctx.json(mockFacilityNotes)),
3588
- );
3589
- ```
3590
-
3591
- ✅ **Do** export factory functions (flexible per test):
3592
-
3593
- ```typescript
3594
- // Good - each test can provide custom data
3595
- export const createFacilityNotesTestHandler = (facilityNotes: FacilityNote[]) => {
3596
- return rest.get<string, Record<string, string>, FacilityNotesResponse>(
3597
- `${TEST_API_URL}/facilityNotes/:facilityId`,
3598
- async (_req, res, ctx) => {
3599
- return res(ctx.status(200), ctx.json(facilityNotes));
3600
- },
3601
- );
3602
- };
3603
-
3604
- // Export default success scenario for convenience
3605
- export const facilityNotesTestHandlers = [createFacilityNotesTestHandler(mockFacilityNotes)];
3606
- ```
3607
-
3608
- **Usage in tests:**
3609
-
3610
- ```typescript
3611
- // In test setup
3612
- mockApiServer.use(
3613
- createFacilityNotesTestHandler(myCustomFacilityNotes),
3614
- createExtraTimePaySettingsTestHandler({ payload: customSettings }),
3615
- );
3616
- ```
3617
-
3618
- **Rationale:** When endpoints need different responses for different test scenarios, factory functions avoid duplication and inline mocks that become hard to maintain.
3619
-
3620
- ## Mocking
3621
-
3622
- ### Mocking Modules
3623
-
3624
- ```typescript
3625
- import { vi } from "vitest";
3626
- import * as useUserModule from "@/features/user/hooks/useUser";
3627
-
3628
- // Mock entire module
3629
- vi.mock("@/features/user/hooks/useUser");
3630
-
3631
- // Spy on specific function
3632
- const useDefinedWorkerSpy = vi.spyOn(useDefinedWorkerModule, "useDefinedWorker");
3633
- useDefinedWorkerSpy.mockReturnValue(getMockWorker({ id: "123" }));
3634
- ```
3635
-
3636
- ### Mocking Functions
3637
-
3638
- ```typescript
3639
- it("should call callback on success", async () => {
3640
- const onSuccess = vi.fn();
3641
-
3642
- render(<Component onSuccess={onSuccess} />);
3643
-
3644
- await user.click(screen.getByRole("button"));
3645
-
3646
- await waitFor(() => {
3647
- expect(onSuccess).toHaveBeenCalledWith(expectedData);
3648
- });
3649
- });
3650
- ```
3651
-
3652
- ### Mocking API Calls
3653
-
3654
- ```typescript
3655
- import { vi } from "vitest";
3656
-
3657
- vi.mock("@/lib/api", () => ({
3658
- get: vi.fn().mockResolvedValue({
3659
- data: { id: "1", name: "Test" },
3660
- }),
3661
- }));
3662
- ```
3663
-
3664
- ## Async Testing
3665
-
3666
- ### Using waitFor
3667
-
3668
- ```typescript
3669
- it("should display data after loading", async () => {
3670
- render(<AsyncComponent />);
3671
-
3672
- expect(screen.getByText("Loading...")).toBeInTheDocument();
3673
-
3674
- await waitFor(() => {
3675
- expect(screen.getByText("Data loaded")).toBeInTheDocument();
3676
- });
3677
- });
3678
- ```
3679
-
3680
- ### Using findBy Queries
3681
-
3682
- ```typescript
3683
- it("should display user name", async () => {
3684
- render(<UserProfile />);
3685
-
3686
- // findBy automatically waits
3687
- const name = await screen.findByText("John Doe");
3688
- expect(name).toBeInTheDocument();
3689
- });
3690
- ```
3691
-
3692
- ## Test Organization
3693
-
3694
- ### Co-location
3695
-
3696
- - Place test files next to source files
3697
- - Use same name with `.test.ts` or `.test.tsx` extension
3698
-
3699
- ```text
3700
- Feature/
3701
- ├── Component.tsx
3702
- ├── Component.test.tsx
3703
- ├── utils.ts
3704
- └── utils.test.ts
3705
- ```
3706
-
3707
- ### Test Helpers
3708
-
3709
- - Create test utilities in `testUtils.ts` or `test-utils.ts`
3710
- - Reusable mocks in `mocks/` folder
3711
-
3712
- ```typescript
3713
- // testUtils.ts
3714
- export function getMockShift(overrides = {}): Shift {
3715
- return {
3716
- id: "1",
3717
- title: "Test Shift",
3718
- ...overrides,
3719
- };
3720
- }
3721
- ```
3722
-
3723
- ## What to Test
3724
-
3725
- ### ✅ Do Test
3726
-
3727
- - **Integration tests for features** - Multiple components working together
3728
- - **Unit tests for helpers/utilities** - Pure business logic
3729
- - **All states** - Loading, success, error
3730
- - **User interactions** - Clicks, typing, form submissions
3731
- - **Conditional rendering** - Different states/permissions
3732
-
3733
- ### ❌ Don't Test
3734
-
3735
- - **UI components in isolation** - Users never shallow-render
3736
- - **Implementation details** - Internal state, function calls
3737
- - **Third-party libraries** - Trust they're tested
3738
- - **Styles/CSS** - Visual regression tests are separate
3739
-
3740
- ## Coverage Guidelines
3741
-
3742
- - Aim for high coverage on business logic and utilities
3743
- - Don't obsess over 100% coverage on UI components
3744
- - **Focus on testing behavior**, not implementation
3745
- - If you can't query it the way a user would, you're testing wrong
3746
-
3747
- ## Common Patterns
3748
-
3749
- ### Testing Loading States
3750
-
3751
- ```typescript
3752
- it("should show loading state", () => {
3753
- render(<Component />);
3754
- expect(screen.getByRole("progressbar")).toBeInTheDocument();
3755
- });
3756
- ```
3757
-
3758
- ### Testing Error States
3759
-
3760
- ```typescript
3761
- it("should display error message on failure", async () => {
3762
- // Mock API error
3763
- vi.mocked(get).mockRejectedValue(new Error("API Error"));
3764
-
3765
- render(<Component />);
3766
-
3767
- expect(await screen.findByText("Error loading data")).toBeInTheDocument();
3768
- });
3769
- ```
3770
-
3771
- ### Testing Conditional Rendering
3772
-
3773
- ```typescript
3774
- it("should show premium badge when user is premium", () => {
3775
- render(<UserCard user={{ ...mockUser, isPremium: true }} />);
3776
- expect(screen.getByText("Premium")).toBeInTheDocument();
3777
- });
3778
-
3779
- it("should not show premium badge when user is not premium", () => {
3780
- render(<UserCard user={{ ...mockUser, isPremium: false }} />);
3781
- expect(screen.queryByText("Premium")).not.toBeInTheDocument();
3782
- });
3783
- ```
3784
-
3785
- <!-- Source: .ruler/frontend/typeScript.md -->
3786
-
3787
- # TypeScript Standards
3788
-
3789
- ## Core Principles
3790
-
3791
- - **Strict mode enabled** - no `any` unless absolutely necessary (document why)
3792
- - **Prefer type inference** - let TypeScript infer when possible
3793
- - **Explicit return types** for exported functions
3794
- - **Zod for runtime validation** - single source of truth for types and validation
3795
- - **No type assertions** unless unavoidable (prefer type guards)
3796
-
3797
- ## Type vs Interface
3798
-
3799
- Use the right tool for the job:
3800
-
3801
- ### Use `interface` for:
3802
-
3803
- - **Component props**
3804
- - **Object shapes**
3805
- - **Class definitions**
3806
- - **Anything that might be extended**
3807
-
3808
- ```typescript
3809
- // ✅ Good - Interface for props
3810
- interface UserCardProps {
3811
- user: User;
3812
- onSelect: (id: string) => void;
3813
- isHighlighted?: boolean;
3814
- }
3815
-
3816
- // ✅ Good - Interface can be extended
3817
- interface BaseEntity {
3818
- id: string;
3819
- createdAt: string;
3820
- }
3821
-
3822
- interface User extends BaseEntity {
3823
- name: string;
3824
- email: string;
3825
- }
3826
- ```
3827
-
3828
- ### Use `type` for:
3829
-
3830
- - **Unions**
3831
- - **Intersections**
3832
- - **Tuples**
3833
- - **Derived/conditional types**
3834
- - **Type aliases**
3835
-
3836
- ```typescript
3837
- // ✅ Good - Type for unions
3838
- type Status = "pending" | "active" | "completed" | "failed";
3839
-
3840
- // ✅ Good - Type for intersections
3841
- type UserWithPermissions = User & { permissions: string[] };
3842
-
3843
- // ✅ Good - Type for tuples
3844
- type Coordinate = [number, number];
3845
-
3846
- // ✅ Good - Derived types
3847
- type UserKeys = keyof User;
3848
- type PartialUser = Partial<User>;
3849
- ```
3850
-
3851
- ## Naming Conventions
3852
-
3853
- ### Types and Interfaces
3854
-
3855
- - **Suffix with purpose**: `Props`, `Response`, `Request`, `Options`, `Params`, `State`
3856
- - **No `I` or `T` prefix** (we're not in C# or Java)
3857
- - **PascalCase** for type names
3858
-
3859
- ```typescript
3860
- // ✅ Good
3861
- interface ButtonProps { ... }
3862
- type ApiResponse = { ... };
3863
- type UserOptions = { ... };
3864
-
3865
- // ❌ Bad
3866
- interface IButton { ... } // No I prefix
3867
- type TResponse = { ... }; // No T prefix
3868
- interface buttonProps { ... } // Wrong case
3869
- ```
3870
-
3871
- ### Boolean Properties
3872
-
3873
- Always prefix with `is`, `has`, `should`, `can`, `will`:
3874
-
3875
- ```typescript
3876
- // ✅ Good
3877
- interface User {
3878
- isActive: boolean;
3879
- hasPermission: boolean;
3880
- shouldNotify: boolean;
3881
- canEdit: boolean;
3882
- willExpire: boolean;
3883
- }
3884
-
3885
- // ❌ Bad
3886
- interface User {
3887
- active: boolean; // Unclear
3888
- permission: boolean; // Unclear
3889
- notify: boolean; // Unclear
3890
- }
3891
- ```
3892
-
3893
- ## Zod Integration
3894
-
3895
- ```typescript
3896
- // Define schema first
3897
- const userSchema = z.object({
3898
- id: z.string(),
3899
- name: z.string(),
3900
- });
3901
-
3902
- // Infer type from schema
3903
- export type User = z.infer<typeof userSchema>;
3904
-
3905
- // Use for API validation
3906
- const response = await get({
3907
- url: "/api/users",
3908
- responseSchema: userSchema,
3909
- });
3910
- ```
3911
-
3912
- ## Type Guards
3913
-
3914
- ```typescript
3915
- export function isEventKey(key: string): key is EventKey {
3916
- return VALID_EVENT_KEYS.includes(key as EventKey);
3917
- }
3918
- ```
3919
-
3920
- ## Constants
3921
-
3922
- ```typescript
3923
- // Use const assertions for readonly values
3924
- export const STAGES = {
3925
- DRAFT: "draft",
3926
- PUBLISHED: "published",
3927
- } as const;
3928
-
3929
- export type Stage = (typeof STAGES)[keyof typeof STAGES];
3930
- ```
3931
-
3932
- ## Function Types
3933
-
3934
- ```typescript
3935
- // Explicit return types for exported functions
3936
- export function calculateTotal(items: Item[]): number {
3937
- return items.reduce((sum, item) => sum + item.price, 0);
3938
- }
3939
-
3940
- // Prefer interfaces for function props
3941
- interface HandleSubmitProps {
3942
- userId: string;
3943
- data: FormData;
3944
- }
3945
-
3946
- export function handleSubmit(props: HandleSubmitProps): Promise<void> {
3947
- // ...
3948
- }
3949
- ```
3950
-
3951
- ## Utility Types
3952
-
3953
- TypeScript provides powerful built-in utility types. Use them:
3954
-
3955
- ```typescript
3956
- // Partial - Make all properties optional
3957
- type PartialUser = Partial<User>;
3958
-
3959
- // Required - Make all properties required
3960
- type RequiredUser = Required<User>;
3961
-
3962
- // Readonly - Make all properties readonly
3963
- type ReadonlyUser = Readonly<User>;
3964
-
3965
- // Pick - Select specific properties
3966
- type UserIdOnly = Pick<User, "id" | "name">;
3967
-
3968
- // Omit - Remove specific properties
3969
- type UserWithoutPassword = Omit<User, "password">;
3970
-
3971
- // Record - Create object type with specific key/value types
3972
- type UserMap = Record<string, User>;
3973
-
3974
- // NonNullable - Remove null and undefined
3975
- type DefinedString = NonNullable<string | null | undefined>; // string
3976
-
3977
- // ReturnType - Extract return type from function
3978
- function getUser() { return { id: '1', name: 'John' }; }
3979
- type GetUserResult = ReturnType<typeof getUser>;
3980
-
3981
- // Parameters - Extract parameter types from function
3982
- function updateUser(id: string, data: UserData) { ... }
3983
- type UpdateUserParams = Parameters<typeof updateUser>; // [string, UserData]
3984
- ```
3985
-
3986
- ## Avoiding `any`
3987
-
3988
- The `any` type defeats the purpose of TypeScript. Use alternatives:
3989
-
3990
- ```typescript
3991
- // ❌ Bad - Loses all type safety
3992
- function process(data: any) {
3993
- return data.value; // No error if value doesn't exist!
3994
- }
3995
-
3996
- // ✅ Good - Use unknown for truly unknown types
3997
- function process(data: unknown) {
3998
- if (typeof data === "object" && data !== null && "value" in data) {
3999
- return (data as { value: string }).value;
4000
- }
4001
- throw new Error("Invalid data");
4002
- }
4003
-
4004
- // ✅ Better - Use generics
4005
- function process<T extends { value: string }>(data: T) {
4006
- return data.value; // Type safe!
4007
- }
4008
-
4009
- // ✅ Best - Use Zod for runtime validation
4010
- const dataSchema = z.object({ value: z.string() });
4011
- function process(data: unknown) {
4012
- const parsed = dataSchema.parse(data); // Throws if invalid
4013
- return parsed.value; // Type safe!
4014
- }
4015
- ```
4016
-
4017
- ## Generics
4018
-
4019
- Use generics for reusable, type-safe code:
4020
-
4021
- ```typescript
4022
- // ✅ Good - Generic function
4023
- function getFirst<T>(array: T[]): T | undefined {
4024
- return array[0];
4025
- }
4026
-
4027
- const firstNumber = getFirst([1, 2, 3]); // number | undefined
4028
- const firstName = getFirst(["a", "b"]); // string | undefined
4029
-
4030
- // ✅ Good - Generic component
4031
- interface ListProps<T> {
4032
- items: T[];
4033
- renderItem: (item: T) => ReactNode;
4034
- keyExtractor: (item: T) => string;
4035
- }
4036
-
4037
- export function List<T>({ items, renderItem, keyExtractor }: ListProps<T>) {
4038
- return (
4039
- <Box>
4040
- {items.map((item) => (
4041
- <Box key={keyExtractor(item)}>{renderItem(item)}</Box>
4042
- ))}
4043
- </Box>
4044
- );
4045
- }
4046
-
4047
- // Usage - Type inferred!
4048
- <List
4049
- items={users}
4050
- renderItem={(user) => <UserCard user={user} />} // user is User
4051
- keyExtractor={(user) => user.id}
4052
- />;
4053
-
4054
- // ✅ Good - Constrained generics
4055
- interface HasId {
4056
- id: string;
4057
- }
4058
-
4059
- function findById<T extends HasId>(items: T[], id: string): T | undefined {
4060
- return items.find((item) => item.id === id);
4061
- }
4062
- ```
4063
-
4064
- ## Runtime Type Checking
4065
-
4066
- Use type guards for runtime type checking:
4067
-
4068
- ```typescript
4069
- // ✅ Good - Type predicate
4070
- export function isUser(value: unknown): value is User {
4071
- return (
4072
- typeof value === "object" &&
4073
- value !== null &&
4074
- "id" in value &&
4075
- "name" in value &&
4076
- typeof value.id === "string" &&
4077
- typeof value.name === "string"
4078
- );
4079
- }
4080
-
4081
- // Usage
4082
- function processData(data: unknown) {
4083
- if (isUser(data)) {
4084
- console.log(data.name); // TypeScript knows data is User
4085
- }
4086
- }
4087
-
4088
- // ✅ Better - Use Zod (runtime validation + type guard)
4089
- const userSchema = z.object({
4090
- id: z.string(),
4091
- name: z.string(),
4092
- });
4093
-
4094
- export function isUser(value: unknown): value is User {
4095
- return userSchema.safeParse(value).success;
4096
- }
4097
-
4098
- // ✅ Good - Discriminated unions
4099
- type ApiResponse =
4100
- | { status: "success"; data: User }
4101
- | { status: "error"; error: string }
4102
- | { status: "loading" };
4103
-
4104
- function handleResponse(response: ApiResponse) {
4105
- switch (response.status) {
4106
- case "success":
4107
- console.log(response.data); // TypeScript knows data exists
4108
- break;
4109
- case "error":
4110
- console.log(response.error); // TypeScript knows error exists
4111
- break;
4112
- case "loading":
4113
- // TypeScript knows no data or error exists
4114
- break;
4115
- }
4116
- }
4117
- ```
4118
-
4119
- ## Const Assertions
4120
-
4121
- Use `as const` for readonly literal types:
4122
-
4123
- ```typescript
4124
- // ✅ Good - Const assertion for object
4125
- export const STATUSES = {
4126
- PENDING: "pending",
4127
- ACTIVE: "active",
4128
- COMPLETED: "completed",
4129
- } as const;
4130
-
4131
- // Type: 'pending' | 'active' | 'completed'
4132
- export type Status = (typeof STATUSES)[keyof typeof STATUSES];
4133
-
4134
- // ✅ Good - Const assertion for array
4135
- export const COLORS = ["red", "blue", "green"] as const;
4136
- export type Color = (typeof COLORS)[number]; // 'red' | 'blue' | 'green'
4137
-
4138
- // ❌ Bad - Without const assertion
4139
- export const STATUSES = {
4140
- PENDING: "pending", // Type: string (too loose!)
4141
- ACTIVE: "active",
4142
- };
4143
- ```
4144
-
4145
- ## Discriminated Unions
4146
-
4147
- Use for state machines and API responses:
4148
-
4149
- ```typescript
4150
- // ✅ Good - Discriminated union for query state
4151
- type QueryState<T> =
4152
- | { status: "idle" }
4153
- | { status: "loading" }
4154
- | { status: "success"; data: T }
4155
- | { status: "error"; error: Error };
4156
-
4157
- function useQueryState<T>(): QueryState<T> {
4158
- // ...
4159
- }
4160
-
4161
- // Usage - Type narrowing works automatically
4162
- const state = useQueryState<User>();
4163
-
4164
- if (state.status === "success") {
4165
- console.log(state.data); // TypeScript knows data exists
4166
- }
4167
-
4168
- // ✅ Good - Discriminated union for actions
4169
- type Action =
4170
- | { type: "SET_USER"; payload: User }
4171
- | { type: "CLEAR_USER" }
4172
- | { type: "UPDATE_USER"; payload: Partial<User> };
4173
-
4174
- function reducer(state: State, action: Action) {
4175
- switch (action.type) {
4176
- case "SET_USER":
4177
- return { ...state, user: action.payload }; // payload is User
4178
- case "CLEAR_USER":
4179
- return { ...state, user: null }; // no payload
4180
- case "UPDATE_USER":
4181
- return { ...state, user: { ...state.user, ...action.payload } };
4182
- }
4183
- }
4184
- ```
4185
-
4186
- ## Function Overloads
4187
-
4188
- Use for functions with different parameter/return combinations:
4189
-
4190
- ```typescript
4191
- // ✅ Good - Function overloads
4192
- function formatValue(value: string): string;
4193
- function formatValue(value: number): string;
4194
- function formatValue(value: Date): string;
4195
- function formatValue(value: string | number | Date): string {
4196
- if (typeof value === "string") return value;
4197
- if (typeof value === "number") return value.toString();
4198
- return value.toISOString();
4199
- }
4200
-
4201
- // TypeScript knows the return type based on input
4202
- const str1 = formatValue("hello"); // string
4203
- const str2 = formatValue(123); // string
4204
- const str3 = formatValue(new Date()); // string
4205
- ```
4206
-
4207
- ## Template Literal Types
4208
-
4209
- Use for type-safe string patterns:
4210
-
4211
- ```typescript
4212
- // ✅ Good - Event handler props with enforced naming
4213
- type EventHandlers<T extends string> = {
4214
- [K in T as `on${Capitalize<K>}`]: () => void;
4215
- };
4216
-
4217
- type Props = EventHandlers<"click" | "hover" | "submit">;
4218
- // Results in: { onClick: () => void; onHover: () => void; onSubmit: () => void; }
4219
-
4220
- // ✅ Good - Validate event handler keys
4221
- type ValidateEventKey<K extends string> = K extends `on${Capitalize<string>}` ? K : never;
4222
-
4223
- interface ComponentProps {
4224
- onClick: () => void; // ✅ Valid
4225
- onHover: () => void; // ✅ Valid
4226
- // click: () => void; // ❌ Does not satisfy ValidateEventKey
4227
- }
4228
-
4229
- // ✅ Good - Route paths
4230
- type Route = `/users/${string}` | `/posts/${string}` | "/";
4231
-
4232
- const validRoute: Route = "/users/123"; // ✅
4233
- const invalidRoute: Route = "users/123"; // ❌ Error
4234
-
4235
- // ✅ Good - CSS properties
4236
- type CSSProperty = `${"margin" | "padding"}${"Top" | "Bottom" | "Left" | "Right"}`;
4237
- // 'marginTop' | 'marginBottom' | 'marginLeft' | 'marginRight' | 'paddingTop' | ...
4238
- ```
4239
-
4240
- ## Mapped Types
4241
-
4242
- Create new types by transforming existing ones:
4243
-
4244
- ```typescript
4245
- // ✅ Good - Make all properties optional
4246
- type Optional<T> = {
4247
- [K in keyof T]?: T[K];
4248
- };
4249
-
4250
- // ✅ Good - Make all properties readonly
4251
- type Immutable<T> = {
4252
- readonly [K in keyof T]: T[K];
4253
- };
4254
-
4255
- // ✅ Good - Add suffix to all keys
4256
- type Prefixed<T, P extends string> = {
4257
- [K in keyof T as `${P}${Capitalize<string & K>}`]: T[K];
4258
- };
4259
-
4260
- type User = { name: string; age: number };
4261
- type PrefixedUser = Prefixed<User, "user">;
4262
- // { userName: string; userAge: number }
4263
- ```
4264
-
4265
- ## Type Narrowing
4266
-
4267
- Let TypeScript narrow types automatically:
4268
-
4269
- ```typescript
4270
- // ✅ Good - Typeof narrowing
4271
- function format(value: string | number) {
4272
- if (typeof value === "string") {
4273
- return value.toUpperCase(); // TypeScript knows value is string
4274
- }
4275
- return value.toFixed(2); // TypeScript knows value is number
4276
- }
4277
-
4278
- // ✅ Good - Truthiness narrowing
4279
- function getLength(value: string | null) {
4280
- if (value) {
4281
- return value.length; // TypeScript knows value is string
4282
- }
4283
- return 0;
4284
- }
4285
-
4286
- // ✅ Good - In narrowing
4287
- interface Fish {
4288
- swim: () => void;
4289
- }
4290
- interface Bird {
4291
- fly: () => void;
4292
- }
4293
-
4294
- function move(animal: Fish | Bird) {
4295
- if ("swim" in animal) {
4296
- animal.swim(); // TypeScript knows animal is Fish
4297
- } else {
4298
- animal.fly(); // TypeScript knows animal is Bird
4299
- }
4300
- }
4301
-
4302
- // ✅ Good - Instanceof narrowing
4303
- function handleError(error: unknown) {
4304
- if (error instanceof Error) {
4305
- console.log(error.message); // TypeScript knows error is Error
4306
- }
4307
- }
4308
- ```
4309
-
4310
- ## Common Patterns
4311
-
4312
- ### Optional Chaining & Nullish Coalescing
4313
-
4314
- ```typescript
4315
- // ✅ Good - Optional chaining
4316
- const userName = user?.profile?.name;
4317
-
4318
- // ✅ Good - Nullish coalescing (only null/undefined, not '')
4319
- const displayName = userName ?? "Anonymous";
4320
-
4321
- // ❌ Bad - Logical OR (treats '' and 0 as falsy)
4322
- const displayName = userName || "Anonymous";
4323
- ```
4324
-
4325
- ### Non-null Assertion (Use Sparingly)
4326
-
4327
- ```typescript
4328
- // ⚠️ Use sparingly - Only when you're 100% sure
4329
- const user = getUser()!; // Tells TS: trust me, it's not null
4330
-
4331
- // ✅ Better - Handle null case
4332
- const user = getUser();
4333
- if (!user) throw new Error("User not found");
4334
- // Now TypeScript knows user exists
4335
- ```
4336
-
4337
- <!-- Source: .ruler/frontend/uiAndStyling.md -->
4338
-
4339
- # UI and Styling
4340
-
4341
- - Use Material UI for components and styling and a mobile-first approach.
4342
- - Favor TanStack Query over "useEffect".
1
+ @AGENTS.md