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

fix(ojoi): Updated controllers and bugfixes #17146

Merged
merged 4 commits into from
Dec 5, 2024

Conversation

jonbjarnio
Copy link
Member

@jonbjarnio jonbjarnio commented Dec 5, 2024

What

  • Updated some of the OJOI controllers to use the input components directly instead of the built in application system controllers.
  • Fixed bug where submit button was disabled when it was not supposed to
  • Fixed bug where input fields / selects did not update when user selected an older advert
  • Improved and simplified the advert modal screen

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

    • Enhanced input components for better user experience with updated rendering logic.
    • Improved flexibility in select options handling, allowing for a wider range of input types.
    • Streamlined advert handling in the modal for more efficient user interactions.
  • Bug Fixes

    • Corrected data access paths for advert-related properties to ensure accurate rendering and functionality.
  • Refactor

    • Simplified state management and data handling across various components, improving overall readability and performance.
    • Introduced a reusable base entity schema for consistency in data validation.
  • Documentation

    • Updated schemas to enhance validation and consistency across the application.

…ted a previous advert the inputs fields were not updating. Switched out controller components since we have our own.
@jonbjarnio jonbjarnio requested a review from a team as a code owner December 5, 2024 14:26
Copy link
Contributor

coderabbitai bot commented Dec 5, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request includes significant updates across several components in the official journal application. Key changes involve the replacement of the InputController with the Input component, enhancements to type safety in the OJOISelectController, and modifications to the Advert, AdvertModal, and Publishing components for improved data handling and state management. Additionally, a new baseEntitySchema has been introduced for validation, and various utility functions have been updated to align with the new structure. These changes streamline the components and improve their integration with the overall application.

Changes

File Path Change Summary
libs/application/templates/official-journal-of-iceland/src/components/input/OJOIInputController.tsx Replaced InputController with Input component, updated props handling, and removed import for InputController.
libs/application/templates/official-journal-of-iceland/src/components/input/OJOISelectController.tsx Introduced generic type parameters for SelectOption and Props, updated onChange and onBeforeChange callbacks, and replaced SelectController with Select component.
libs/application/templates/official-journal-of-iceland/src/fields/Advert.tsx Simplified props by removing timeStamp, adjusted department and type handling, and updated onChange handlers.
libs/application/templates/official-journal-of-iceland/src/fields/AdvertModal.tsx Removed AlertMessage, changed selectedAdvertId to selectedAdvert, updated onSelectAdvert and onConfirm functions for direct advert object manipulation.
libs/application/templates/official-journal-of-iceland/src/fields/Preview.tsx Updated type variable access to reflect new data structure, adjusted hasMarkup condition, and maintained error handling logic.
libs/application/templates/official-journal-of-iceland/src/fields/Publishing.tsx Changed onCategoryChange to use stricter type validation with Zod, updated category handling logic, and modified rendering structure.
libs/application/templates/official-journal-of-iceland/src/fields/Summary.tsx Removed multiple data fetching hooks, simplified state management, and updated property access to reflect new application state structure.
libs/application/templates/official-journal-of-iceland/src/hooks/useTypes.ts Added useLazyQuery for lazy data fetching, updated return structure of useTypes hook.
libs/application/templates/official-journal-of-iceland/src/lib/OJOIApplication.ts Modified getApplicationName function to access application type using a new path.
libs/application/templates/official-journal-of-iceland/src/lib/dataSchema.ts Introduced baseEntitySchema and updated existing schemas to reference it, ensuring consistency across validation logic.
libs/application/templates/official-journal-of-iceland/src/lib/types.ts Updated keys in InputFields and RequiredInputFieldsNames to reflect new naming conventions for department and type.
libs/application/templates/official-journal-of-iceland/src/lib/utils.ts Added isBaseEntity function for type checking against baseEntitySchema.
libs/application/templates/official-journal-of-iceland/src/screens/AdvertScreen.tsx Removed generateTimestamp function and associated state, updated onConfirmChange implementation in AdvertModal.

Possibly related PRs

  • fix(ojoi): Updated controllers and bugfixes #17146: The changes in the main PR involve updates to the OJOIInputController and OJOISelectController, which are directly related to the modifications made in the same components in the retrieved PR. Both PRs focus on enhancing the functionality and usability of input components within the OJOI system.

Suggested reviewers

  • Valur
  • Toti91

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 081223e and 2f5cf44.

📒 Files selected for processing (1)
  • libs/application/templates/official-journal-of-iceland/src/components/input/OJOISelectController.tsx (3 hunks)

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 Dec 5, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 35.75%. Comparing base (5a1b1a6) to head (2f5cf44).
Report is 2 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main   #17146   +/-   ##
=======================================
  Coverage   35.75%   35.75%           
=======================================
  Files        6925     6925           
  Lines      147603   147603           
  Branches    42022    42022           
=======================================
  Hits        52772    52772           
  Misses      94831    94831           
Flag Coverage Δ
api 3.33% <ø> (ø)
application-system-api 38.77% <ø> (-0.01%) ⬇️
application-template-api-modules 27.83% <ø> (+0.01%) ⬆️
application-ui-shell 22.48% <ø> (ø)

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


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 4704971...2f5cf44. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Dec 5, 2024

Datadog Report

All test runs e3c0c2f 🔗

4 Total Test Services: 0 Failed, 4 Passed
➡️ Test Sessions change in coverage: 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 2.4s 1 no change Link
application-system-api 0 0 0 46 0 2m 22.42s 1 no change Link
application-template-api-modules 0 0 0 118 0 2m 4.37s 1 no change Link
application-ui-shell 0 0 0 74 0 31.64s 1 no change Link

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 (15)
libs/application/templates/official-journal-of-iceland/src/fields/Preview.tsx (2)

Line range hint 58-74: LGTM! Consider extracting download name generation logic.

The type-safe access pattern and URL cleanup in the finally block are well implemented. However, the download name generation logic could be extracted into a separate function for better readability and reusability.

Consider refactoring like this:

+ const getDownloadName = (type?: string, title?: string, fallbackId?: string) => {
+   let downloadName = type ? type.replace('.', '') : '';
+   if (title) {
+     downloadName += ` ${title}`;
+   }
+   return downloadName || `Innsending ${fallbackId}`;
+ };

- let downloadName
- const type = currentApplication.answers.advert?.type?.title
- if (type) {
-   downloadName = type.replace('.', '')
- }
-
- const title = currentApplication.answers.advert?.title
- if (title) {
-   downloadName += ` ${title}`
- }
-
- if (!downloadName) {
-   downloadName = `Innsending ${application.id}`
- }
-
- downloadName += '.pdf'
+ const downloadName = `${getDownloadName(
+   currentApplication.answers.advert?.type?.title,
+   currentApplication.answers.advert?.title,
+   application.id
+ )}.pdf`;

Line range hint 1-224: Consider enhancing error handling and testing coverage.

As this is a library component, consider the following architectural improvements:

  1. Add error boundaries to handle PDF generation failures gracefully
  2. Extract PDF download logic into a custom hook for reusability
  3. Add unit tests for the new type structure handling

Would you like me to help create:

  1. An error boundary implementation
  2. A reusable PDF download hook
  3. Unit test templates for the component?
libs/application/templates/official-journal-of-iceland/src/lib/OJOIApplication.ts (1)

Line range hint 1-44: Enhance type exports for reusability

Following the coding guidelines for libs/**/*, consider exporting the type structure for InputFields.advert.type to improve reusability across different NextJS apps.

Consider adding type exports like this:

export interface AdvertType {
  title: string;
  // other type properties
}

export interface AdvertFields {
  type: AdvertType;
  title: string;
  // other advert fields
}
libs/application/templates/official-journal-of-iceland/src/fields/Summary.tsx (4)

72-74: Improve optional chaining consistency

The cleanup function uses && operator while the rest of the code uses optional chaining. Consider using optional chaining for consistency.

-      setSubmitButtonDisabled && setSubmitButtonDisabled(false)
+      setSubmitButtonDisabled?.setSubmitButtonDisabled(false)
🧰 Tools
🪛 Biome (1.9.4)

[error] 73-73: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


Line range hint 61-70: Consider optimizing the effect dependencies

The effect's logic could be simplified by combining the validation checks into a single derived value. This would reduce the number of effect dependencies and make the code more maintainable.

+ const isValid = advertValidationCheck.success && 
+   signatureValidationCheck.success && 
+   publishingCheck.success;

  useEffect(() => {
-    if (
-      advertValidationCheck.success &&
-      signatureValidationCheck.success &&
-      publishingCheck.success
-    ) {
-      setSubmitButtonDisabled && setSubmitButtonDisabled(false)
-    } else {
-      setSubmitButtonDisabled && setSubmitButtonDisabled(true)
-    }
+    setSubmitButtonDisabled?.(!isValid)

    return () => {
-      setSubmitButtonDisabled && setSubmitButtonDisabled(false)
+      setSubmitButtonDisabled?.(false)
    }
-  }, [
-    advertValidationCheck,
-    signatureValidationCheck,
-    publishingCheck,
-    setSubmitButtonDisabled,
-  ])
+  }, [isValid, setSubmitButtonDisabled])
🧰 Tools
🪛 Biome (1.9.4)

[error] 69-69: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 73-73: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


Line range hint 89-185: Reduce validation message duplication

The validation message rendering logic is repeated three times with similar patterns. Consider extracting this into a reusable component to improve maintainability.

Example implementation:

type ValidationMessageProps = {
  validationResult: SafeParseReturnType<any, any>;
  title: string;
  route: Routes;
  sectionName: string;
  goToScreen?: (route: Routes) => void;
  setSubmitButtonDisabled?: (disabled: boolean) => void;
};

const ValidationMessage = ({
  validationResult,
  title,
  route,
  sectionName,
  goToScreen,
  setSubmitButtonDisabled,
}: ValidationMessageProps) => {
  if (validationResult.success) return null;
  
  return (
    <AlertMessage
      type="warning"
      title={title}
      message={
        <Stack space={2}>
          <BulletList color="black">
            {validationResult.error.issues.map((issue) => {
              const parsedIssue = parseZodIssue(issue as ZodCustomIssue)
              return (
                <Bullet key={issue.path.join('.')}>
                  {f(parsedIssue.message)}
                </Bullet>
              )
            })}
          </BulletList>
          <Button
            onClick={() => {
              setSubmitButtonDisabled?.(false)
              goToScreen?.(route)
            }}
            size="small"
            variant="text"
            preTextIcon="arrowBack"
          >
            {`Opna kafla ${sectionName}`}
          </Button>
        </Stack>
      }
    />
  );
};

Line range hint 30-40: Consider improving component reusability

As this component is part of a library, consider:

  1. Extracting validation logic into a custom hook
  2. Making the component more configurable through props
  3. Documenting the component's API and usage patterns

Would you like assistance in implementing these architectural improvements?

libs/application/templates/official-journal-of-iceland/src/hooks/useTypes.ts (2)

70-70: Typo: Correct 'initalTypes' to 'initialTypes'

There is a typographical error in the return object. The key initalTypes should be corrected to initialTypes to ensure consistency and avoid confusion.

Apply this diff to fix the typo:

-        initalTypes: data?.officialJournalOfIcelandTypes.types,
+        initialTypes: data?.officialJournalOfIcelandTypes.types,

71-73: Improve error handling by combining 'error' and 'lazyTypesError'

Currently, only the error from the initial useQuery is returned, while lazyTypesError is returned separately. For consistent error handling, consider combining both errors or handling them appropriately to ensure errors from both queries are accounted for.

Apply this diff to adjust the error handling:

-        loading: loading || lazyTypesLoading,
-        error,
+        loading: loading || lazyTypesLoading,
+        error: error || lazyTypesError,
libs/application/templates/official-journal-of-iceland/src/components/input/OJOISelectController.tsx (2)

57-57: Simplify function call with optional chaining

You can simplify the conditional function call by using optional chaining for better readability.

Apply this diff:

-        onBeforeChange && onBeforeChange(newAnswers, value)
+        onBeforeChange?.(newAnswers, value)
🧰 Tools
🪛 Biome (1.9.4)

[error] 57-57: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


62-62: Simplify function call with optional chaining

You can simplify the conditional function call by using optional chaining for better readability.

Apply this diff:

-        onChange && onChange(value)
+        onChange?.(value)
🧰 Tools
🪛 Biome (1.9.4)

[error] 62-62: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

libs/application/templates/official-journal-of-iceland/src/screens/AdvertScreen.tsx (1)

38-38: Simplify function call with optional chaining

You can use optional chaining to simplify the conditional function call to props.refetch.

Apply this diff:

-              props.refetch && props.refetch()
+              props.refetch?.()
🧰 Tools
🪛 Biome (1.9.4)

[error] 38-38: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

libs/application/templates/official-journal-of-iceland/src/fields/Publishing.tsx (2)

Line range hint 58-69: Consider performance optimization for category updates

While the type safety improvements with Zod are excellent, using structuredClone for the entire answers object might be inefficient for large state trees.

Consider using a more targeted update approach:

-const currentAnswers = structuredClone(currentApplication.answers)
-const selectedCategories = currentAnswers.advert?.categories || []
+const selectedCategories = [...(currentApplication.answers.advert?.categories || [])]

127-142: UI improvement with better accessibility

Good improvement using Inline component for consistent spacing and Tag components for better interaction. However, consider adding aria-label for better accessibility.

 <Tag
   disabled={isUpdatingCategory}
   onClick={() => onCategoryChange(c)}
   outlined
   key={c.id}
+  aria-label={`Remove category ${c.title}`}
 >
libs/application/templates/official-journal-of-iceland/src/lib/dataSchema.ts (1)

145-155: Consider extracting shared validation logic.

The validation logic is duplicated between advertValidationSchema and previewValidationSchema. Consider extracting the common validation rules into a shared function or schema.

// Create a shared validation schema
const sharedEntityValidation = (errorMessage: MessageDescriptor) =>
  baseEntitySchema
    .optional()
    .nullable()
    .refine((value) => value !== null && value !== undefined, {
      params: errorMessage,
    });

// Use in both schemas
const advertValidationSchema = z.object({
  advert: z.object({
    department: sharedEntityValidation(error.missingDepartment),
    type: sharedEntityValidation(error.missingType),
    // ... rest of the schema
  }),
});
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d5d4383 and 081223e.

📒 Files selected for processing (13)
  • libs/application/templates/official-journal-of-iceland/src/components/input/OJOIInputController.tsx (2 hunks)
  • libs/application/templates/official-journal-of-iceland/src/components/input/OJOISelectController.tsx (3 hunks)
  • libs/application/templates/official-journal-of-iceland/src/fields/Advert.tsx (1 hunks)
  • libs/application/templates/official-journal-of-iceland/src/fields/AdvertModal.tsx (4 hunks)
  • libs/application/templates/official-journal-of-iceland/src/fields/Preview.tsx (2 hunks)
  • libs/application/templates/official-journal-of-iceland/src/fields/Publishing.tsx (6 hunks)
  • libs/application/templates/official-journal-of-iceland/src/fields/Summary.tsx (5 hunks)
  • libs/application/templates/official-journal-of-iceland/src/hooks/useTypes.ts (2 hunks)
  • libs/application/templates/official-journal-of-iceland/src/lib/OJOIApplication.ts (1 hunks)
  • libs/application/templates/official-journal-of-iceland/src/lib/dataSchema.ts (5 hunks)
  • libs/application/templates/official-journal-of-iceland/src/lib/types.ts (2 hunks)
  • libs/application/templates/official-journal-of-iceland/src/lib/utils.ts (2 hunks)
  • libs/application/templates/official-journal-of-iceland/src/screens/AdvertScreen.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
libs/application/templates/official-journal-of-iceland/src/lib/utils.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/official-journal-of-iceland/src/lib/OJOIApplication.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/official-journal-of-iceland/src/fields/Summary.tsx (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/official-journal-of-iceland/src/fields/Preview.tsx (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/official-journal-of-iceland/src/lib/types.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/official-journal-of-iceland/src/screens/AdvertScreen.tsx (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/official-journal-of-iceland/src/hooks/useTypes.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/official-journal-of-iceland/src/fields/Publishing.tsx (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/official-journal-of-iceland/src/fields/AdvertModal.tsx (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/official-journal-of-iceland/src/components/input/OJOIInputController.tsx (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/official-journal-of-iceland/src/fields/Advert.tsx (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/official-journal-of-iceland/src/components/input/OJOISelectController.tsx (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/official-journal-of-iceland/src/lib/dataSchema.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🪛 Biome (1.9.4)
libs/application/templates/official-journal-of-iceland/src/fields/Summary.tsx

[error] 73-73: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

libs/application/templates/official-journal-of-iceland/src/screens/AdvertScreen.tsx

[error] 38-38: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

libs/application/templates/official-journal-of-iceland/src/components/input/OJOISelectController.tsx

[error] 57-57: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 62-62: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (15)
libs/application/templates/official-journal-of-iceland/src/fields/Preview.tsx (1)

101-108: LGTM! Verify markup generation with the new type structure.

The type-safe access pattern is consistently applied. Let's verify that the markup generation works correctly with the new nested type structure.

✅ Verification successful

Type-safe access pattern is consistently implemented across markup generation

The verification shows that the new type structure (advert?.type?.title) is consistently used across all relevant files:

  • Preview.tsx: Used in markup generation, hasMarkup condition, and download name logic
  • Advert.tsx: Used in title preview markup generation
  • Summary.tsx: Used in property display
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any other instances of markup generation to ensure consistency

# Search for other markup generation patterns
ast-grep --pattern 'getAdvertMarkup({
  $$$
})'

# Search for type access patterns to ensure consistency
rg -A 2 'advert\?\.type\?\.title'

Length of output: 2961

libs/application/templates/official-journal-of-iceland/src/lib/OJOIApplication.ts (1)

44-44: Verify type safety and data structure changes

The path change from InputFields.advert.typeName to ${InputFields.advert.type}.title suggests a structural change in how advert types are stored. This change needs verification to ensure type safety and proper data handling.

✅ Verification successful

Change from typeName to type.title is valid and consistent

The verification shows that:

  1. In types.ts, InputFields.advert.type is correctly defined as 'advert.type'
  2. The usage of type.title is consistent with the API schema, as seen in OJOIAdvert.tsx where advert.type.title is used
  3. No remaining usages of the old typeName pattern were found in the OJOI application context

The change aligns with the codebase structure and appears to be a valid refactoring to match the API schema's structure.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the type structure and usage across the codebase

# Check the InputFields type definition
ast-grep --pattern 'interface InputFields {
  advert: {
    $$$
    type: $_
    $$$
  }
}'

# Check for any remaining uses of the old path
rg "advert\.typeName" -t ts -t tsx

# Check for consistent usage of the new path structure
rg "advert\.type\.title" -t ts -t tsx

Length of output: 226


Script:

#!/bin/bash
# Let's try a different approach to verify the type structure and usage

# Search for InputFields interface definition
ast-grep --pattern 'interface InputFields {
  $$$
}'

# Check for type-related imports and definitions
rg "InputFields" --type ts

# Look for advert type-related patterns
rg "advert\.type" --type ts

# Check for any remaining uses of typeName
rg "typeName" --type ts

Length of output: 19642


Script:

#!/bin/bash
# Let's check the specific type definition and structure

# Check the types.ts file content
cat libs/application/templates/official-journal-of-iceland/src/lib/types.ts

# Look for any references to advert.type.title
rg "advert\.type\.title" --type ts -A 2 -B 2

Length of output: 2999

libs/application/templates/official-journal-of-iceland/src/fields/Summary.tsx (1)

41-45: Verify if price loading state is still necessary

While other loading states have been removed, loadingPrice is still being used. Consider if this loading state is necessary or if it can be simplified similar to other data fetching in this component.

✅ Verification successful

Let me search for more context about the usePrice hook and its usage pattern.


Loading state for price is correctly implemented and necessary

The price loading state is required as it's actively used in the Property component to show loading state while fetching price data via GraphQL. The implementation is consistent with GraphQL data fetching patterns where:

  • The usePrice hook performs a GraphQL query that may take time to complete
  • The loading state is properly propagated to the UI through the Property component
  • The price calculation requires a server round-trip, making it different from other removed loading states that might have been client-side only
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other usages of usePrice hook to understand the loading pattern
ast-grep --pattern 'const { price, loading: $_ } = usePrice($$$)'

Length of output: 404


Script:

#!/bin/bash
# Search for usePrice hook definition and implementation
ast-grep --pattern 'export const usePrice = ($$$) => {
  $$$
}'

# Search for other price loading usages in the component
rg "loadingPrice" libs/application/templates/official-journal-of-iceland/src/fields/Summary.tsx -A 2 -B 2

Length of output: 2162

libs/application/templates/official-journal-of-iceland/src/fields/AdvertModal.tsx (1)

Line range hint 28-198: Code changes effectively simplify state management

The modifications improve state handling by directly storing the selected advert object. The logic is clear, and the implementation enhances the component's efficiency.

🧰 Tools
🪛 Biome (1.9.4)

[error] 108-108: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

libs/application/templates/official-journal-of-iceland/src/components/input/OJOIInputController.tsx (1)

Line range hint 1-82: Refactor to use 'Input' component improves code simplicity

The replacement of InputController with the Input component simplifies the code and aligns with updated UI component usage. The changes are appropriate and well-implemented.

libs/application/templates/official-journal-of-iceland/src/lib/types.ts (2)

41-42: LGTM! Field labels updated consistently

The human-readable labels have been updated to match the new field names while maintaining the same meaning.


14-15: Verify the impact of field name changes across the codebase

The renaming from departmentId/typeId to department/type suggests a shift in data structure. While the changes look good, we should verify the impact.

libs/application/templates/official-journal-of-iceland/src/fields/Advert.tsx (3)

17-21: Props simplified and application state management improved

Good improvement in component props by removing unused timeStamp. The useApplication hook usage is now more focused.


36-43: Type-safe department options mapping

Good implementation of type-safe options with complete department entity information.


66-79: Verify proper cleanup of dependent fields

The cleanup of the type field when department changes is good, but we should verify the handling of other dependent fields.

libs/application/templates/official-journal-of-iceland/src/lib/dataSchema.ts (4)

46-50: LGTM! Well-structured base entity schema.

The schema provides a solid foundation for entity validation with required id, title, and slug fields.


70-71: LGTM! Enhanced type safety with baseEntitySchema.

The changes improve type safety by replacing string IDs with structured entities, while maintaining flexibility with optional and nullable fields where appropriate.

Also applies to: 75-75


116-127: LGTM! Robust validation with proper null checks.

The validation logic properly handles null and undefined cases while maintaining consistent error messaging.


181-184: LGTM! Consistent schema usage.

The categories validation properly uses the baseEntitySchema while maintaining the existing refinement logic.

libs/application/templates/official-journal-of-iceland/src/lib/utils.ts (1)

134-137: LGTM! Well-implemented type guard.

The type guard follows TypeScript best practices and maintains consistency with other type guards in the file.

Copy link
Member

@thorkellmani thorkellmani left a comment

Choose a reason for hiding this comment

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

LGTM

@jonbjarnio jonbjarnio added the automerge Merge this PR as soon as all checks pass label Dec 5, 2024
@kodiakhq kodiakhq bot merged commit 2804be7 into main Dec 5, 2024
39 checks passed
@kodiakhq kodiakhq bot deleted the fix/ojoi-fix-default-values-not-showing branch December 5, 2024 15:24
thorhildurt pushed a commit that referenced this pull request Dec 11, 2024
* Updated data schema to make less api calls, fixed bug when user selected a previous advert the inputs fields were not updating. Switched out controller components since we have our own.

* Returning false instead of undefined.

---------

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
automerge Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants