Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(web): WHODAS calculator #16947

Merged
merged 8 commits into from
Nov 21, 2024
Merged

feat(web): WHODAS calculator #16947

merged 8 commits into from
Nov 21, 2024

Conversation

RunarVestmann
Copy link
Member

@RunarVestmann RunarVestmann commented Nov 19, 2024

WHODAS calculator

Screenshots / Gifs

Screen.Recording.2024-11-20.at.16.10.02.mov

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced the WHODAS calculator component, allowing users to assess disability levels through a series of questions.
    • Added internationalized messages for user navigation and results display within the calculator.
  • Style

    • Implemented a new grid layout for the calculator interface, enhancing visual organization.
    • Added new global styles for links in the markdown text component, improving visual consistency.
  • Chores

    • Updated rendering logic to support the new WHODAS calculator component in the application.

Copy link
Contributor

coderabbitai bot commented Nov 19, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request introduces a new WHODAS calculator component to the web application. It includes a CSS module for styling, a TypeScript file for internationalized strings, and the main React component that manages user input and displays results. The changes enhance the user interface and functionality of the WHODAS calculator, allowing for better user interaction and localization.

Changes

File Path Change Summary
Calculator.css.ts Added a new CSS module with a grid layout style constant breakdownRowContainer.
Calculator.strings.ts Introduced a new TypeScript file defining internationalized messages for the WHODAS calculator component.
Calculator.tsx Added a new React component for the WHODAS calculator, including interfaces and subcomponents for form handling.
.../utils/richText.tsx Updated webRenderConnectedComponent to handle the new WHODASCalculator component type.
MarkdownText.css.ts Added global styles for anchor elements, including color and hover effects.

Possibly related PRs

Suggested labels

deploy-feature

Suggested reviewers

  • mannipje
  • Tryggvig
  • Valur

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Nov 19, 2024

Codecov Report

Attention: Patch coverage is 0% with 75 lines in your changes missing coverage. Please review.

Project coverage is 36.39%. Comparing base (22200fa) to head (b618a1a).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...pps/web/components/connected/WHODAS/Calculator.tsx 0.00% 71 Missing ⚠️
apps/web/utils/richText.tsx 0.00% 3 Missing ⚠️
.../components/connected/WHODAS/Calculator.strings.ts 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16947      +/-   ##
==========================================
- Coverage   36.41%   36.39%   -0.02%     
==========================================
  Files        6899     6901       +2     
  Lines      144866   144941      +75     
  Branches    41402    41422      +20     
==========================================
  Hits        52756    52756              
- Misses      92110    92185      +75     
Flag Coverage Δ
api 3.34% <ø> (ø)
application-system-api 41.02% <ø> (ø)
application-template-api-modules 27.73% <ø> (+0.02%) ⬆️
application-templates-inheritance-report 6.55% <ø> (ø)
application-ui-shell 20.57% <ø> (ø)
web 1.76% <0.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
.../components/connected/WHODAS/Calculator.strings.ts 0.00% <0.00%> (ø)
apps/web/utils/richText.tsx 0.00% <0.00%> (ø)
...pps/web/components/connected/WHODAS/Calculator.tsx 0.00% <0.00%> (ø)

Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 22200fa...b618a1a. Read the comment docs.

---- 🚨 Try these New Features:

@datadog-island-is
Copy link

datadog-island-is bot commented Nov 19, 2024

Datadog Report

All test runs 7fa58be 🔗

5 Total Test Services: 0 Failed, 5 Passed
🔻 Test Sessions change in coverage: 1 decreased (-0.02%), 8 no change

Test Services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 3.2s 1 no change Link
application-system-api 0 0 0 112 2 3m 21.41s 1 no change Link
application-template-api-modules 0 0 0 116 0 2m 18.55s 1 no change Link
application-ui-shell 0 0 0 74 0 31.63s 1 no change Link
web 0 0 0 84 0 24.35s 1 decreased (-0.02%) Link

🔻 Code Coverage Decreases vs Default Branch (1)

  • web - jest 2.43% (-0.02%) - Details

@RunarVestmann RunarVestmann added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Nov 20, 2024
@RunarVestmann RunarVestmann marked this pull request as ready for review November 20, 2024 16:06
@RunarVestmann RunarVestmann requested review from a team as code owners November 20, 2024 16:06
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (7)
apps/web/components/connected/WHODAS/Calculator.strings.ts (2)

4-25: Enhance type safety and translator context.

Two suggestions for improvement:

  1. Add type information for the progress message placeholders
  2. Provide more descriptive context in the description fields for translators

Apply this diff to improve the code:

   progress: {
     id: 'web.whodas.calculator:form.progress',
     defaultMessage: 'Skref {stepIndex} af {stepCount}',
-    description: 'Skref {stepIndex} af {stepCount}',
+    description: 'Progress indicator showing current step number out of total steps',
+    values: {
+      stepIndex: {
+        type: 'number',
+        minimum: 1,
+      },
+      stepCount: {
+        type: 'number',
+        minimum: 1,
+      },
+    },
   },

26-52: Consider using an enum for answer labels.

The current implementation uses string keys for numeric values. Consider using an enum to improve type safety and maintainability.

Create a new type definition:

enum DifficultyLevel {
  None = '0',
  Slight = '1',
  Moderate = '2',
  Severe = '3',
  Extreme = '4',
}

// Then use it in the messages:
export const m = {
  answerLabel: defineMessages<Record<DifficultyLevel, MessageDescriptor>>({
    [DifficultyLevel.None]: {
      // ... existing message
    },
    // ... other messages
  }),
}
apps/web/utils/richText.tsx (1)

203-205: Consider improving type safety for component mapping

While the implementation is correct, consider enhancing type safety by:

  1. Defining a union type for all component types
  2. Ensuring the slice prop type is properly constrained

Example implementation:

type ComponentType =
  | 'Fiskistofa/ShipSearch'
  | 'WHODAS/Calculator'
  // ... other types

interface WHODASSlice extends ConnectedComponent {
  // Add specific WHODAS calculator props here
}

// In the switch statement
case 'WHODAS/Calculator':
  connectedComponent = <WHODASCalculator slice={slice as WHODASSlice} />
  break;
apps/web/components/connected/WHODAS/Calculator.tsx (4)

41-49: Enhance type safety by reusing existing interfaces

The CheckboxState interface defines structures similar to the existing Step and Question interfaces. Reusing these interfaces can improve type consistency and reduce code duplication.

Consider modifying the CheckboxState interface as follows:

-interface CheckboxState {
-  steps: {
-    title: string
-    questions: {
-      selectedAnswerIndex: number
-      answerScore: number
-    }[]
-  }[]
-}
+interface QuestionState extends Omit<Question, 'answerOptions'> {
+  selectedAnswerIndex: number
+  answerScore: number
+}
+
+interface StepState extends Omit<Step, 'questions'> {
+  questions: QuestionState[]
+}
+
+interface CheckboxState {
+  steps: StepState[]
+}

This approach reuses the properties from Question and Step, adding only the necessary state-related fields.


263-266: Avoid using hardcoded values for better maintainability

Using hardcoded values like 16.9 can make future updates error-prone. Consider extracting this value into a constant or retrieving it from configuration to enhance flexibility and readability.

Apply this diff to define a constant for the breakpoint:

+const FIRST_BRACKET_BREAKPOINT = slice.configJson?.firstBracketBreakpoint ?? 16.9

return (
  <WHODASResults
    results={results}
    bracket={
-     totalScore <= (slice.configJson?.firstBracketBreakpoint ?? 16.9)
+     totalScore <= FIRST_BRACKET_BREAKPOINT
        ? 1
        : 2
    }
  />
)

81-83: Clarify the purpose of limiting answer options to four choices

The condition if (answerIndex > 3) filters out answer options beyond the first four. Ensure this aligns with the intended design and consider adding a comment to explain this limitation for future maintainability.

Add a comment explaining why only the first four answer options are considered:

if (answerIndex > 3) {
+  // Only display the first four answer options as per the survey design
   return null
}

272-317: Enhance accessibility by adding ARIA labels to navigation buttons

To improve accessibility, consider adding ARIA labels to the "Next" and "Previous" buttons to provide better context for screen readers.

Apply this diff to include aria-label attributes:

<Button
  size="small"
  variant="ghost"
  preTextIcon="arrowBack"
+ aria-label="Previous Step"
  onClick={() => {
    setStepIndex((s) => s - 1)
  }}
>
  {formatMessage(m.form.previousStep)}
</Button>

<Button
  size="small"
+ aria-label="Next Step"
  onClick={() => {
    setStepIndex((s) => s + 1)
  }}
>
  {formatMessage(
    stepIndex >= steps.length - 1 ? m.form.seeResults : m.form.nextStep,
  )}
</Button>
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b90bbfa and 6ff3ac8.

📒 Files selected for processing (4)
  • apps/web/components/connected/WHODAS/Calculator.css.ts (1 hunks)
  • apps/web/components/connected/WHODAS/Calculator.strings.ts (1 hunks)
  • apps/web/components/connected/WHODAS/Calculator.tsx (1 hunks)
  • apps/web/utils/richText.tsx (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/web/components/connected/WHODAS/Calculator.css.ts
🧰 Additional context used
📓 Path-based instructions (3)
apps/web/components/connected/WHODAS/Calculator.strings.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/web/components/connected/WHODAS/Calculator.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/web/utils/richText.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (6)
apps/web/components/connected/WHODAS/Calculator.strings.ts (2)

1-3: LGTM! Clean and well-structured initialization.

The file follows react-intl best practices with proper typing through defineMessages.


89-98: Verify markdown processing for advice messages.

The advice messages are marked with #markdown suffix in their IDs, but there's no visible markdown processing setup.

apps/web/utils/richText.tsx (1)

91-91: LGTM! Import follows established patterns

The WHODASCalculator import follows the project's component organization and import conventions.

apps/web/components/connected/WHODAS/Calculator.tsx (3)

215-244: Verify that scrolling behavior works as intended on all devices

The useEffect hook scrolls to the top of the form on step changes, except during the initial render. Ensure this behavior provides a good user experience across different devices and does not interfere with browser accessibility features.

Test the scrolling functionality on various devices and screen sizes to confirm that it enhances, rather than hinders, the user experience.


136-145: Confirm print functionality works correctly across browsers

The window.print() method is used to print the results. Verify that this feature works seamlessly across different browsers and devices, and that the printed output is formatted appropriately.

Test the print functionality in various browsers to ensure consistent behavior and acceptable print layout.


85-89: Ensure safe access to localization messages to prevent runtime errors

Accessing dynamic keys in localization objects could result in undefined if the key does not exist. Confirm that all possible answerIndex values have corresponding entries in m.answerLabel.

Run the following script to verify that all indices up to 3 have corresponding localization entries:

✅ Verification successful

Let me search for the message definitions to understand how these labels are actually defined.


The localization messages are properly defined and safe to use

The code is actually safe as all required keys (0 to 4) are properly defined in Calculator.strings.ts. The type assertion as keyof typeof m.answerLabel ensures type safety, and the actual implementation shows that all possible answer indices (0 to 4) have corresponding localization messages defined.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check that m.answerLabel has entries for keys '0' to '3'

# Expected: All keys from '0' to '3' exist in m.answerLabel
for i in {0..3}; do
  rg "m\.answerLabel\['$i'\]" ./ -l || echo "Key '$i' is missing in m.answerLabel"
done

Length of output: 583


Script:

#!/bin/bash
# Search for the message definitions related to answerLabel
rg "answerLabel" -B 2 -A 2

Length of output: 2932

@RunarVestmann RunarVestmann force-pushed the feature/web-whodas-calculator branch from ff9eec4 to 1a20933 Compare November 21, 2024 10:31
@kodiakhq kodiakhq bot merged commit 869bce3 into main Nov 21, 2024
39 of 40 checks passed
@kodiakhq kodiakhq bot deleted the feature/web-whodas-calculator branch November 21, 2024 10:47
jonnigs pushed a commit that referenced this pull request Nov 26, 2024
* WIP

* Use dynamic text

* Add translation

* Add progress meter

* Only scroll when not initially rendering

* Update id

* Style links

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
deprecated:automerge (Disabled) Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants