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

Qr scanners and codes for passing around guardian links / verification codes. #435

Open
wants to merge 43 commits into
base: master
Choose a base branch
from

Conversation

Kodylow
Copy link
Member

@Kodylow Kodylow commented Jun 15, 2024

We had a workshop at BTC prague where a bunch of people tried running the guardian setup on their phones and passing around the codes was a total pain. This adds qr scanning and qr codes for all the inputs/fields that need to get passed around between the guardians.

Summary by CodeRabbit

  • New Features

    • Added QR code scanning functionality with new modal components (QrModal, QrScannerModal) for improved user interaction.
    • Introduced Scanner component for seamless QR code scanning.
    • Enhanced BasicSettingsForm with a QR code scanner for setting the host server URL.
    • Improved ConnectGuardians component with a QR code icon that triggers a modal display.
    • Added ConfirmFollowersConnected component for confirming the connection status of followers.
    • Streamlined the VerifyGuardians component to allow direct QR scanning and verification.
    • Provided comprehensive end-to-end testing instructions for the Fedimint Guardian and Gateway UI.
  • Bug Fixes

    • Updated dependencies to enhance QR code scanning capabilities.
  • Chores

    • Improved script robustness by updating the mprocs-nix.sh script for reliable directory handling.
  • Documentation

    • Updated language files to include new translations for QR code scanning features.

@Kodylow Kodylow changed the title WIP: Qr scanners and codes for passing around guardian links / verification codes. Qr scanners and codes for passing around guardian links / verification codes. Jul 1, 2024
@Kodylow Kodylow marked this pull request as ready for review July 9, 2024 21:30
@Kodylow Kodylow requested review from a team as code owners July 9, 2024 21:30
Copy link
Contributor

coderabbitai bot commented Jul 9, 2024

Walkthrough

Walkthrough

This update enhances the guardian-ui application by integrating advanced QR code functionalities, including new modal components for improved user interactions. Existing components have been refactored to enhance state management and usability, resulting in a more modular architecture that streamlines QR code generation and scanning processes.

Changes

File Path Change Summary
.../package.json Added qr-scanner package for QR functionalities.
.../InviteCode.tsx, .../GuardianAuthenticationCode.tsx Updated QR code size management to import from utilities for maintainability.
.../QrModal.tsx, .../QrScannerModal.tsx Introduced components for displaying QR codes and scanning, featuring error handling.
.../ConnectGuardians.tsx, .../BasicSettingsForm.tsx Integrated QR code functionalities into existing workflows with state management.
.../ConfirmFollowersConnected.tsx, .../PeerVerificationTable.tsx, .../VerificationButton.tsx, .../VerificationCodeInput.tsx Added components to manage verification processes and user interactions.
.../languages/en.json Added translation key for QR scanning and updated interface text for clarity.
.../scripts/mprocs-nix.sh Enhanced robustness of FM_TEST_DIR export.
.../flake.nix Updated URL for fedimint dependency to include a specific revision.
.../testing.md Introduced comprehensive end-to-end testing instructions for the Fedimint system.

Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 3537965 and 932049f.

Files selected for processing (2)
  • apps/guardian-ui/src/admin/FederationAdmin.tsx (4 hunks)
  • apps/guardian-ui/src/languages/en.json (4 hunks)
Files skipped from review as they are similar to previous changes (1)
  • apps/guardian-ui/src/languages/en.json
Additional comments not posted (3)
apps/guardian-ui/src/admin/FederationAdmin.tsx (3)

21-42: LGTM!

The checkAnnouncementNeeded function correctly handles the logic for checking announcements and opening the modal, including error handling.


44-49: LGTM!

The findOurPeerId function is straightforward and enhances code readability and maintainability.


Line range hint 1-192:
LGTM! But verify the function usage.

The enhancements to the FederationAdmin component, including new hooks, state management, and the integration of the SignApiAnnouncement component, are well-implemented.

However, ensure that the fetchData function and other hooks are correctly utilized throughout the codebase.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

@Kodylow
Copy link
Member Author

Kodylow commented Jul 9, 2024

Note: getting this annoying play() error being called during state change error that I can't pin down, it still works it just throws the runtime error when you open the QRScanner and you click out of it and it works.

@IroncladDev @alexlwn123 wizards plz help

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: 9

Comment on lines +39 to +49
onDecodeError: (error) => {
if (typeof error === 'string' && err.current !== error) {
err.current = error;
onError(error);
} else if (
typeof error !== 'string' &&
err.current !== error.message
) {
err.current = error.message;
onError(error.message);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Handle non-string error types more robustly.

Ensure that all possible error types are handled correctly by adding a default case.

+  else {
+    const errorMessage = error.message || 'Unknown error';
+    err.current = errorMessage;
+    onError(errorMessage);
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
onDecodeError: (error) => {
if (typeof error === 'string' && err.current !== error) {
err.current = error;
onError(error);
} else if (
typeof error !== 'string' &&
err.current !== error.message
) {
err.current = error.message;
onError(error.message);
}
onDecodeError: (error) => {
if (typeof error === 'string' && err.current !== error) {
err.current = error;
onError(error);
} else if (
typeof error !== 'string' &&
err.current !== error.message
) {
err.current = error.message;
onError(error.message);
} else {
const errorMessage = error.message || 'Unknown error';
err.current = errorMessage;
onError(errorMessage);
}

Comment on lines +7 to +8
onError: (error: string) => void;
} & React.VideoHTMLAttributes<HTMLVideoElement>;
Copy link
Contributor

Choose a reason for hiding this comment

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

Add a default value for onError in ScannerProps.

To prevent potential runtime errors, consider adding a default value for the onError function.

+  onError: (error: string) => void = () => {},

Committable suggestion was skipped due to low confidence.

@@ -39,6 +44,7 @@ export const BasicSettingsForm: React.FC<BasicSettingsFormProps> = ({
}) => {
const { t } = useTranslation();
const theme = useTheme();
const [isQrScannerOpen, setIsQrScannerOpen] = useState(false);
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure the QR scanner modal state is reset appropriately.

Add a cleanup function to reset the QR scanner modal state when the component unmounts.

+  React.useEffect(() => {
+    return () => setIsQrScannerOpen(false);
+  }, []);
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const [isQrScannerOpen, setIsQrScannerOpen] = useState(false);
const [isQrScannerOpen, setIsQrScannerOpen] = useState(false);
React.useEffect(() => {
return () => setIsQrScannerOpen(false);
}, []);

Comment on lines +117 to +121
<QrScannerModal
isOpen={isQrScannerOpen}
onClose={() => setIsQrScannerOpen(false)}
onScan={(data) => setHostServerUrl(data)}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for QR scanner modal.

Add error handling for the QR scanner modal to handle potential scanning errors.

+  onError={(error) => console.error('QR Scanner Error:', error)}
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<QrScannerModal
isOpen={isQrScannerOpen}
onClose={() => setIsQrScannerOpen(false)}
onScan={(data) => setHostServerUrl(data)}
/>
<QrScannerModal
isOpen={isQrScannerOpen}
onClose={() => setIsQrScannerOpen(false)}
onScan={(data) => setHostServerUrl(data)}
onError={(error) => console.error('QR Scanner Error:', error)}
/>

@@ -32,6 +34,7 @@ export const ConnectGuardians: React.FC<Props> = ({ next }) => {
const {
state: { role, peers, numPeers, configGenParams, ourCurrentId },
} = useSetupContext();
const [isOpen, setIsOpen] = useState(false);
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure the QR modal state is reset appropriately.

Add a cleanup function to reset the QR modal state when the component unmounts.

+  React.useEffect(() => {
+    return () => setIsOpen(false);
+  }, []);
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const [isOpen, setIsOpen] = useState(false);
const [isOpen, setIsOpen] = useState(false);
React.useEffect(() => {
return () => setIsOpen(false);
}, []);

Comment on lines +224 to +229
<QrModal
isOpen={isOpen}
onClose={() => setIsOpen(false)}
content={guardianLink}
header={t('connect-guardians.invite-guardians')}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for QR modal.

Add error handling for the QR modal to handle potential errors when generating the QR code.

+  onError={(error) => console.error('QR Modal Error:', error)}
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<QrModal
isOpen={isOpen}
onClose={() => setIsOpen(false)}
content={guardianLink}
header={t('connect-guardians.invite-guardians')}
/>
<QrModal
isOpen={isOpen}
onClose={() => setIsOpen(false)}
content={guardianLink}
header={t('connect-guardians.invite-guardians')}
onError={(error) => console.error('QR Modal Error:', error)}
/>

const [isQrModalOpen, setQrModalOpen] = useState(false);
const [scanningGuardian, setScanningGuardian] = useState<string>();
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure the QR scanner modal state is reset appropriately.

Add a cleanup function to reset the QR scanner modal state when the component unmounts.

+  React.useEffect(() => {
+    return () => setQrModalOpen(false);
+  }, []);
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const [isQrModalOpen, setQrModalOpen] = useState(false);
const [scanningGuardian, setScanningGuardian] = useState<string>();
const [isQrModalOpen, setQrModalOpen] = useState(false);
const [scanningGuardian, setScanningGuardian] = useState<string>();
React.useEffect(() => {
return () => setQrModalOpen(false);
}, []);

@IroncladDev
Copy link

I'll take a look in a bit. I have a bunch of high-priority tickets on my sprint board right now.

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: 1

scripts/mprocs-nix.sh Outdated Show resolved Hide resolved
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: 1

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: 1

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: 9

Comment on lines +28 to +33
const handleScan = (data: string) => {
onScan(data);
onClose();
};
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure valid data before calling onScan.

Add a check to ensure data is valid before calling onScan.

-    onScan(data);
+    if (data) {
+      onScan(data);
+    }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const handleScan = (data: string) => {
onScan(data);
onClose();
};
const handleScan = (data: string) => {
if (data) {
onScan(data);
}
onClose();
};

Comment on lines +33 to +62
const handleError = (error: string) => {
console.error(error);
if (error.includes('play() request was interrupted')) {
toast({
title: 'Scanner Error',
description: 'The camera stream was interrupted. Please try again.',
status: 'error',
duration: 5000,
isClosable: true,
});
onClose();
}
};
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve error handling for non-specific errors.

Handle non-specific errors by adding a default case.

-    if (error.includes('play() request was interrupted')) {
+    if (error.includes('play() request was interrupted')) {
       toast({
         title: 'Scanner Error',
         description: 'The camera stream was interrupted. Please try again.',
         status: 'error',
         duration: 5000,
         isClosable: true,
       });
       onClose();
+    } else {
+      toast({
+        title: 'Scanner Error',
+        description: 'An unknown error occurred. Please try again.',
+        status: 'error',
+        duration: 5000,
+        isClosable: true,
+      });
+      onClose();
     }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const handleError = (error: string) => {
console.error(error);
if (error.includes('play() request was interrupted')) {
toast({
title: 'Scanner Error',
description: 'The camera stream was interrupted. Please try again.',
status: 'error',
duration: 5000,
isClosable: true,
});
onClose();
}
};
const handleError = (error: string) => {
console.error(error);
if (error.includes('play() request was interrupted')) {
toast({
title: 'Scanner Error',
description: 'The camera stream was interrupted. Please try again.',
status: 'error',
duration: 5000,
isClosable: true,
});
onClose();
} else {
toast({
title: 'Scanner Error',
description: 'An unknown error occurred. Please try again.',
status: 'error',
duration: 5000,
isClosable: true,
});
onClose();
}
};

Comment on lines +94 to +121
<InputGroup>
<Input
value={hostServerUrl}
onChange={(ev) => setHostServerUrl(ev.currentTarget.value)}
placeholder='ws://...'
pr='4.5rem'
/>
<InputRightElement width='4.5rem'>
<Icon
as={ScanIcon}
cursor='pointer'
onClick={() => setIsQrScannerOpen(true)}
boxSize='1.5rem'
color='gray.500'
_hover={{ color: 'blue.500' }}
/>
</InputRightElement>
</InputGroup>
<FormHelperText>
{t('set-config.join-federation-help')}
</FormHelperText>
</FormControl>
)}
<QrScannerModal
isOpen={isQrScannerOpen}
onClose={() => setIsQrScannerOpen(false)}
onScan={(data) => setHostServerUrl(data)}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for QR scanner modal.

Add error handling for the QR scanner modal to handle potential scanning errors.

+  onError={(error) => console.error('QR Scanner Error:', error)}
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<InputGroup>
<Input
value={hostServerUrl}
onChange={(ev) => setHostServerUrl(ev.currentTarget.value)}
placeholder='ws://...'
pr='4.5rem'
/>
<InputRightElement width='4.5rem'>
<Icon
as={ScanIcon}
cursor='pointer'
onClick={() => setIsQrScannerOpen(true)}
boxSize='1.5rem'
color='gray.500'
_hover={{ color: 'blue.500' }}
/>
</InputRightElement>
</InputGroup>
<FormHelperText>
{t('set-config.join-federation-help')}
</FormHelperText>
</FormControl>
)}
<QrScannerModal
isOpen={isQrScannerOpen}
onClose={() => setIsQrScannerOpen(false)}
onScan={(data) => setHostServerUrl(data)}
/>
<InputGroup>
<Input
value={hostServerUrl}
onChange={(ev) => setHostServerUrl(ev.currentTarget.value)}
placeholder='ws://...'
pr='4.5rem'
/>
<InputRightElement width='4.5rem'>
<Icon
as={ScanIcon}
cursor='pointer'
onClick={() => setIsQrScannerOpen(true)}
boxSize='1.5rem'
color='gray.500'
_hover={{ color: 'blue.500' }}
/>
</InputRightElement>
</InputGroup>
<FormHelperText>
{t('set-config.join-federation-help')}
</FormHelperText>
</FormControl>
)}
<QrScannerModal
isOpen={isQrScannerOpen}
onClose={() => setIsQrScannerOpen(false)}
onScan={(data) => setHostServerUrl(data)}
onError={(error) => console.error('QR Scanner Error:', error)}
/>

Comment on lines +69 to +84
<Flex direction='row' alignItems='center' gap='6px'>
<CopyInput
value={guardianLink}
size='sm'
buttonLeftIcon={<Icon as={CopyIcon} />}
/>
<Icon
as={QrIcon}
cursor='pointer'
onClick={() => setIsOpen(true)}
bg='white'
boxSize='40px'
borderRadius='10%'
border='1px solid lightgray'
_hover={{ bg: 'gray.100' }}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for QR modal.

Add error handling for the QR modal to handle potential errors when generating the QR code.

+  onError={(error) => console.error('QR Modal Error:', error)}

Committable suggestion was skipped due to low confidence.

Comment on lines 234 to 254
<InputGroup size='md'>
<Input
variant='filled'
value={value}
placeholder={`${t('verify-guardians.verified-placeholder')}`}
onChange={(ev) => handleChangeHash(ev.currentTarget.value, idx)}
readOnly={isValid}
/>
<InputRightElement>
<Icon
as={ScanIcon}
cursor='pointer'
onClick={() => {
setQrModalOpen(true);
setScanningGuardian(peersWithHash[idx].peer.name);
}}
boxSize='1.5rem'
color='gray.500'
_hover={{ color: 'blue.500' }}
/>
</InputRightElement>
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for QR scanner modal.

Add error handling for the QR scanner modal to handle potential scanning errors.

+  onError={(error) => console.error('QR Scanner Error:', error)}

Committable suggestion was skipped due to low confidence.

Comment on lines 205 to 212
const handleScanHash = useCallback(
(data: string) => {
// parse out index:value from the data string
const [index, value] = data.split(':');
handleChangeHash(value, parseInt(index, 10));
},
[handleChangeHash]
);
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for QR scanner modal.

Add error handling for the QR scanner modal to handle potential scanning errors.

+  onError={(error) => console.error('QR Scanner Error:', error)}

Committable suggestion was skipped due to low confidence.

Comment on lines 403 to 410
<QrScannerModal
isOpen={isQrModalOpen}
onClose={() => setQrModalOpen(false)}
onScan={handleScanHash}
title={t('verify-guardians.scanning-guardian', {
guardian: scanningGuardian,
})}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for QR scanner modal.

Add error handling for the QR scanner modal to handle potential scanning errors.

+  onError={(error) => console.error('QR Scanner Error:', error)}
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<QrScannerModal
isOpen={isQrModalOpen}
onClose={() => setQrModalOpen(false)}
onScan={handleScanHash}
title={t('verify-guardians.scanning-guardian', {
guardian: scanningGuardian,
})}
/>
<QrScannerModal
isOpen={isQrModalOpen}
onClose={() => setQrModalOpen(false)}
onScan={handleScanHash}
title={t('verify-guardians.scanning-guardian', {
guardian: scanningGuardian,
})}
onError={(error) => console.error('QR Scanner Error:', error)}
/>

Comment on lines 397 to 402
<QrModal
isOpen={isOpen}
onClose={() => setIsOpen(false)}
content={`${ourCurrentId}:${myHash}`}
header={t('setup.verify-guardians.verification-code')}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for QR modal.

Add error handling for the QR modal to handle potential errors when generating the QR code.

+  onError={(error) => console.error('QR Modal Error:', error)}
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<QrModal
isOpen={isOpen}
onClose={() => setIsOpen(false)}
content={`${ourCurrentId}:${myHash}`}
header={t('setup.verify-guardians.verification-code')}
/>
<QrModal
isOpen={isOpen}
onClose={() => setIsOpen(false)}
content={`${ourCurrentId}:${myHash}`}
header={t('setup.verify-guardians.verification-code')}
onError={(error) => console.error('QR Modal Error:', error)}
/>

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: 1

@@ -8,7 +8,8 @@ fi
DEVIMINT_COMMAND=$1
MPROCS_PATH=$2

export FM_TEST_DIR="$TMP/fm-$(LC_ALL=C tr -dc A-Za-z0-9 </dev/urandom | head -c 4 || true)"
TMP="${TMP:-/tmp}"
export FM_TEST_DIR="${TMP}/fm-$(LC_ALL=C tr -dc A-Za-z0-9 </dev/urandom | head -c 4 || true)"
Copy link
Contributor

Choose a reason for hiding this comment

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

Declare and assign separately to avoid masking return values.

To follow best practices and avoid potential issues, declare and assign the variable separately.

+ TMP="${TMP:-/tmp}"
export FM_TEST_DIR="${TMP}/fm-$(LC_ALL=C tr -dc A-Za-z0-9 </dev/urandom | head -c 4 || true)"

Committable suggestion was skipped due to low confidence.

Tools
Shellcheck

[warning] 12-12: Declare and assign separately to avoid masking return values.

(SC2155)

Copy link
Collaborator

@alexlwn123 alexlwn123 left a comment

Choose a reason for hiding this comment

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

@Kodylow Few small things... otherwise looks great!

pb={8}
>
<QRCode value={content} size={256} />
</ModalBody>
Copy link
Collaborator

Choose a reason for hiding this comment

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

Add a "copy" button below the QR code... similar to the paste button on the scanner

onScan(data);
onClose();
};
const handlePaste = async () => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

wrap callback function in useCallback

}
};

const handleError = (error: string) => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

wrap callback function in useCallback

onError,
...props
}) => {
const [res, setRes] = React.useState<string | null>(null);
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: import {useState, useRef, useEffect} from 'react'

...props
}) => {
const [res, setRes] = React.useState<string | null>(null);
const err = React.useRef<string | null>(null);
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: useState over useRef for strings

@@ -37,6 +32,11 @@ import { ReactComponent as CopyIcon } from '../../../../assets/svgs/copy.svg';
import { formatApiErrorMessage } from '../../../../utils/api';
import { ReactComponent as CheckCircleIcon } from '../../../../assets/svgs/check-circle.svg';
import { ReactComponent as XCircleIcon } from '../../../../assets/svgs/x-circle.svg';
import { ReactComponent as QrIcon } from '../../../../assets/svgs/qr.svg';
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: I'm not a huge fan of this pattern. (importing ReactComponent then use as within the chakra Icon)

Perhaps we can consider doing this:

import QrIcon from '../../../../assets/svgs/qr.svg';


....

<>
  <Icon>
    <QrIcon />
  </Icon>
</>

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: 12

Outside diff range, codebase verification and nitpick comments (3)
JUSTFILE (1)

13-14: User lacks necessary sudo permissions.

The current user does not have the required sudo permissions to execute the rm -rf fm_* command. This will cause the reset dc command to fail.

  • Ensure the user has the necessary sudo permissions to remove directories.
Analysis chain

Ensure the backup file exists and permissions are correct.

Verify that original-docker-compose.yml exists and the script has the necessary permissions to copy and remove directories.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence of the backup Docker Compose file and check permissions.

# Test: Check if original-docker-compose.yml exists and is readable. Expect: File exists and is readable.
if [ ! -r "original-docker-compose.yml" ]; then
  echo "original-docker-compose.yml does not exist or is not readable."
  exit 1
fi
echo "original-docker-compose.yml exists and is readable."

Length of output: 157


Script:

#!/bin/bash
# Description: Verify sudo permissions and existence of fm_* directories.

# Test: Check if the user has sudo permissions. Expect: User has sudo permissions.
if ! sudo -n true 2>/dev/null; then
  echo "User does not have sudo permissions."
  exit 1
fi
echo "User has sudo permissions."

# Test: Check if any fm_* directories exist. Expect: Directories exist.
if ls fm_* 1> /dev/null 2>&1; then
  echo "fm_* directories exist."
else
  echo "No fm_* directories found."
fi

Length of output: 106

apps/guardian-ui/src/components/dashboard/tabs/ApiAnnouncements.tsx (2)

23-24: Translation key federation-dashboard.api-announcements.guardian is missing.

The translation key federation-dashboard.api-announcements.guardian does not exist in the translation files. Please ensure that this key is defined and translated appropriately.

Analysis chain

Ensure translation keys are correct.

Verify that the translation key federation-dashboard.api-announcements.guardian exists and is correctly translated.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence of the translation key for `guardian`.

# Test: Search for the translation key. Expect: Only occurrences of the correct key.
rg --type json 'federation-dashboard.api-announcements.guardian'

Length of output: 64


Script:

#!/bin/bash
# Description: Verify the existence of the translation key for `guardian` in all files.

# Test: Search for the translation key in all files. Expect: Only occurrences of the correct key.
rg 'federation-dashboard.api-announcements.guardian'

Length of output: 191


Script:

#!/bin/bash
# Description: Verify the existence of the translation key for `guardian` in translation files.

# Test: Search for the translation key in JSON and YAML translation files. Expect: Only occurrences of the correct key.
rg 'federation-dashboard.api-announcements.guardian' --type json --type yaml

Length of output: 76


28-29: The translation key federation-dashboard.api-announcements.revision is missing in the language files. Please add the necessary translations.

  • Missing key: federation-dashboard.api-announcements.revision in apps/guardian-ui/src/languages/ko.json, apps/guardian-ui/src/languages/en.json, and apps/guardian-ui/src/languages/es.json.
Analysis chain

Ensure translation keys are correct.

Verify that the translation key federation-dashboard.api-announcements.revision exists and is correctly translated.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence of the translation key for `revision`.

# Test: Search for the translation key. Expect: Only occurrences of the correct key.
rg --type json 'federation-dashboard.api-announcements.revision'

Length of output: 64


Script:

#!/bin/bash
# Description: Search for all translation keys under `federation-dashboard.api-announcements`.

# Test: Search for translation keys. Expect: List of all keys under `federation-dashboard.api-announcements`.
rg --type json 'federation-dashboard.api-announcements'

Length of output: 55


Script:

#!/bin/bash
# Description: Search for all translation keys under `federation-dashboard`.

# Test: Search for translation keys. Expect: List of all keys under `federation-dashboard`.
rg --type json 'federation-dashboard'

Length of output: 238


Script:

#!/bin/bash
# Description: Verify the existence of the specific translation key `federation-dashboard.api-announcements.revision` within the identified files.

# Test: Search for the specific translation key in the identified files. Expect: Occurrences of the specific key.
rg 'federation-dashboard.api-announcements.revision' apps/guardian-ui/src/languages/ko.json apps/guardian-ui/src/languages/en.json apps/guardian-ui/src/languages/es.json

Length of output: 169

Comment on lines 294 to 309
<Flex direction='row' alignItems='center' gap='6px'>
<CopyInput
value={myHash}
buttonLeftIcon={<Icon as={CopyIcon} />}
size='sm'
/>
<Icon
as={QrIcon}
cursor='pointer'
onClick={() => setIsOpen(true)}
bg='white'
boxSize='40px'
borderRadius='10%'
border='1px solid lightgray'
_hover={{ bg: 'gray.100' }}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for QR scanner and modal.

Add error handling to handle potential errors when generating or scanning QR codes.

+  onError={(error) => console.error('QR Scanner/Modal Error:', error)}

Also applies to: 399-404, 405-412

scripts/mprocs-restart-guardian.sh Show resolved Hide resolved
testing.md Outdated Show resolved Hide resolved
testing.md Outdated Show resolved Hide resolved
testing.md Outdated Show resolved Hide resolved
testing.md Outdated Show resolved Hide resolved
testing.md Outdated Show resolved Hide resolved
scripts/mprocs-restart-guardian.sh Show resolved Hide resolved
docker-compose.yml Show resolved Hide resolved
scripts/mprocs-rotate-guardian.sh Show resolved Hide resolved
Kodylow and others added 8 commits July 31, 2024 10:25
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 3

Comment on lines 267 to 297
<Flex direction='row' alignItems='center' gap='6px'>
<CopyInput
value={myHash}
buttonLeftIcon={<Icon as={CopyIcon} />}
size='sm'
/>
<Icon
as={QrIcon}
cursor='pointer'
onClick={() => setQrModalOpen(true)}
bg='white'
boxSize='40px'
borderRadius='10%'
border='1px solid lightgray'
_hover={{ bg: 'gray.100' }}
/>
<Button
onClick={() => setIsScannerActive(!isScannerActive)}
leftIcon={<Icon as={ScanIcon} />}
size='sm'
variant='outline'
bg='white'
borderColor='gray.200'
_hover={{ bg: 'gray.100' }}
color='black.700'
>
{isScannerActive
? t('verify-guardians.stop-scan')
: t('verify-guardians.start-scan')}
</Button>
</Flex>
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for QR code functionalities.

Add error handling for the QR code generation and scanning functionalities to handle potential errors.

+  onError={(error) => console.error('QR Code Error:', error)}

Committable suggestion was skipped due to low confidence.

Comment on lines 34 to 38
import { ReactComponent as QrIcon } from '../../../../assets/svgs/qr.svg';
import { ReactComponent as ScanIcon } from '../../../../assets/svgs/scan.svg';
import { QrModal } from '../../qr/QrModal';
import { ConfirmFollowersConnected } from './ConfirmFollowersConnected';
import { Scanner } from '../../qr/Scanner';
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure consistency in import patterns.

Consider following a consistent import pattern for SVG components to improve readability.

- import { ReactComponent as QrIcon } from '../../../../assets/svgs/qr.svg';
- import { ReactComponent as ScanIcon } from '../../../../assets/svgs/scan.svg';
+ import QrIcon from '../../../../assets/svgs/qr.svg';
+ import ScanIcon from '../../../../assets/svgs/scan.svg';
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { ReactComponent as QrIcon } from '../../../../assets/svgs/qr.svg';
import { ReactComponent as ScanIcon } from '../../../../assets/svgs/scan.svg';
import { QrModal } from '../../qr/QrModal';
import { ConfirmFollowersConnected } from './ConfirmFollowersConnected';
import { Scanner } from '../../qr/Scanner';
import QrIcon from '../../../../assets/svgs/qr.svg';
import ScanIcon from '../../../../assets/svgs/scan.svg';
import { QrModal } from '../../qr/QrModal';
import { ConfirmFollowersConnected } from './ConfirmFollowersConnected';
import { Scanner } from '../../qr/Scanner';

Comment on lines 393 to 403
<ConfirmFollowersConnected
isOpen={isConfirmOpen}
setIsOpen={setIsConfirmOpen}
handleNext={handleNext}
/>
<QrModal
isOpen={isQrModalOpen}
onClose={() => setQrModalOpen(false)}
content={`${ourCurrentId}:${myHash}`}
header={t('verify-guardians.verification-code')}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for QR modal.

Add error handling for the QR modal to handle potential errors when generating the QR code.

+  onError={(error) => console.error('QR Modal Error:', error)}

Committable suggestion was skipped due to low confidence.

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: 7

Comment on lines +188 to +197
{isScannerActive && (
<Scanner
scanning={true}
onResult={(data) => {
const [index, hash] = data.split(':');
handleChangeHash(hash, parseInt(index, 10));
}}
onError={(error) => console.error(error)}
/>
<FormHelperText>
{t('verify-guardians.verification-code-help')}
</FormHelperText>
</FormControl>
<Hide below='sm'>
<Table
title={t('verify-guardians.table-title')}
description={t('verify-guardians.table-description')}
columns={tableColumns}
rows={tableRows}
)}
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for Scanner.

The Scanner component is used correctly, but add error handling to manage potential scanning errors.

-  onError={(error) => console.error(error)}
+  onError={(error) => console.error('QR Scanner Error:', error)}
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{isScannerActive && (
<Scanner
scanning={true}
onResult={(data) => {
const [index, hash] = data.split(':');
handleChangeHash(hash, parseInt(index, 10));
}}
onError={(error) => console.error(error)}
/>
<FormHelperText>
{t('verify-guardians.verification-code-help')}
</FormHelperText>
</FormControl>
<Hide below='sm'>
<Table
title={t('verify-guardians.table-title')}
description={t('verify-guardians.table-description')}
columns={tableColumns}
rows={tableRows}
)}
{isScannerActive && (
<Scanner
scanning={true}
onResult={(data) => {
const [index, hash] = data.split(':');
handleChangeHash(hash, parseInt(index, 10));
}}
onError={(error) => console.error('QR Scanner Error:', error)}
/>
)}

Comment on lines +17 to +22
interface VerificationCodeInputProps {
myHash: string;
setQrModalOpen: (isOpen: boolean) => void;
isScannerActive: boolean;
setIsScannerActive: (isActive: boolean) => void;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding prop types validation.

Ensure that the props passed to the component are validated for type safety.

+ import PropTypes from 'prop-types';

VerificationCodeInput.propTypes = {
  myHash: PropTypes.string.isRequired,
  setQrModalOpen: PropTypes.func.isRequired,
  isScannerActive: PropTypes.bool.isRequired,
  setIsScannerActive: PropTypes.func.isRequired,
};
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
interface VerificationCodeInputProps {
myHash: string;
setQrModalOpen: (isOpen: boolean) => void;
isScannerActive: boolean;
setIsScannerActive: (isActive: boolean) => void;
}
import PropTypes from 'prop-types';
interface VerificationCodeInputProps {
myHash: string;
setQrModalOpen: (isOpen: boolean) => void;
isScannerActive: boolean;
setIsScannerActive: (isActive: boolean) => void;
}
VerificationCodeInput.propTypes = {
myHash: PropTypes.string.isRequired,
setQrModalOpen: PropTypes.func.isRequired,
isScannerActive: PropTypes.bool.isRequired,
setIsScannerActive: PropTypes.func.isRequired,
};

Comment on lines +33 to +70
return (
<FormControl bg={theme.colors.blue[50]} p={4} borderRadius='md' maxW='md'>
<FormLabel>{t('verify-guardians.verification-code')}</FormLabel>
<Flex direction='row' alignItems='center' gap='6px'>
<CopyInput
value={myHash}
buttonLeftIcon={<Icon as={CopyIcon} />}
size='sm'
/>
<Icon
as={QrIcon}
cursor='pointer'
onClick={() => setQrModalOpen(true)}
bg='white'
boxSize='40px'
borderRadius='10%'
border='1px solid lightgray'
_hover={{ bg: 'gray.100' }}
/>
<Button
onClick={() => setIsScannerActive(!isScannerActive)}
leftIcon={<Icon as={ScanIcon} />}
size='sm'
variant='outline'
bg='white'
borderColor='gray.200'
_hover={{ bg: 'gray.100' }}
color='black.700'
>
{isScannerActive
? t('verify-guardians.stop-scan')
: t('verify-guardians.start-scan')}
</Button>
</Flex>
<FormHelperText>
{t('verify-guardians.verification-code-help')}
</FormHelperText>
</FormControl>
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for QR modal and scanner.

Ensure that opening the QR modal and toggling the scanner handle errors gracefully.

-  onClick={() => setQrModalOpen(true)}
+  onClick={() => {
+    try {
+      setQrModalOpen(true);
+    } catch (error) {
+      console.error('Failed to open QR modal', error);
+    }
+  }}

-  onClick={() => setIsScannerActive(!isScannerActive)}
+  onClick={() => {
+    try {
+      setIsScannerActive(!isScannerActive);
+    } catch (error) {
+      console.error('Failed to toggle scanner', error);
+    }
+  }}
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return (
<FormControl bg={theme.colors.blue[50]} p={4} borderRadius='md' maxW='md'>
<FormLabel>{t('verify-guardians.verification-code')}</FormLabel>
<Flex direction='row' alignItems='center' gap='6px'>
<CopyInput
value={myHash}
buttonLeftIcon={<Icon as={CopyIcon} />}
size='sm'
/>
<Icon
as={QrIcon}
cursor='pointer'
onClick={() => setQrModalOpen(true)}
bg='white'
boxSize='40px'
borderRadius='10%'
border='1px solid lightgray'
_hover={{ bg: 'gray.100' }}
/>
<Button
onClick={() => setIsScannerActive(!isScannerActive)}
leftIcon={<Icon as={ScanIcon} />}
size='sm'
variant='outline'
bg='white'
borderColor='gray.200'
_hover={{ bg: 'gray.100' }}
color='black.700'
>
{isScannerActive
? t('verify-guardians.stop-scan')
: t('verify-guardians.start-scan')}
</Button>
</Flex>
<FormHelperText>
{t('verify-guardians.verification-code-help')}
</FormHelperText>
</FormControl>
return (
<FormControl bg={theme.colors.blue[50]} p={4} borderRadius='md' maxW='md'>
<FormLabel>{t('verify-guardians.verification-code')}</FormLabel>
<Flex direction='row' alignItems='center' gap='6px'>
<CopyInput
value={myHash}
buttonLeftIcon={<Icon as={CopyIcon} />}
size='sm'
/>
<Icon
as={QrIcon}
cursor='pointer'
onClick={() => {
try {
setQrModalOpen(true);
} catch (error) {
console.error('Failed to open QR modal', error);
}
}}
bg='white'
boxSize='40px'
borderRadius='10%'
border='1px solid lightgray'
_hover={{ bg: 'gray.100' }}
/>
<Button
onClick={() => {
try {
setIsScannerActive(!isScannerActive);
} catch (error) {
console.error('Failed to toggle scanner', error);
}
}}
leftIcon={<Icon as={ScanIcon} />}
size='sm'
variant='outline'
bg='white'
borderColor='gray.200'
_hover={{ bg: 'gray.100' }}
color='black.700'
>
{isScannerActive
? t('verify-guardians.stop-scan')
: t('verify-guardians.start-scan')}
</Button>
</Flex>
<FormHelperText>
{t('verify-guardians.verification-code-help')}
</FormHelperText>
</FormControl>

Comment on lines +35 to +41
const handleClick = () => {
if (role === GuardianRole.Host) {
setIsConfirmOpen(true);
} else {
handleNext();
}
};
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for button click.

Ensure that the button click handler handles errors gracefully.

-  if (role === GuardianRole.Host) {
-    setIsConfirmOpen(true);
-  } else {
-    handleNext();
-  }
+  try {
+    if (role === GuardianRole.Host) {
+      setIsConfirmOpen(true);
+    } else {
+      handleNext();
+    }
+  } catch (error) {
+    console.error('Failed to handle button click', error);
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const handleClick = () => {
if (role === GuardianRole.Host) {
setIsConfirmOpen(true);
} else {
handleNext();
}
};
const handleClick = () => {
try {
if (role === GuardianRole.Host) {
setIsConfirmOpen(true);
} else {
handleNext();
}
} catch (error) {
console.error('Failed to handle button click', error);
}
};

Comment on lines +19 to +24
interface VerificationButtonProps {
verifiedConfigs: boolean;
isStarting: boolean;
role: GuardianRole;
handleNext: () => void;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding prop types validation.

Ensure that the props passed to the component are validated for type safety.

+ import PropTypes from 'prop-types';

VerificationButton.propTypes = {
  verifiedConfigs: PropTypes.bool.isRequired,
  isStarting: PropTypes.bool.isRequired,
  role: PropTypes.string.isRequired,
  handleNext: PropTypes.func.isRequired,
};
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
interface VerificationButtonProps {
verifiedConfigs: boolean;
isStarting: boolean;
role: GuardianRole;
handleNext: () => void;
}
import PropTypes from 'prop-types';
interface VerificationButtonProps {
verifiedConfigs: boolean;
isStarting: boolean;
role: GuardianRole;
handleNext: () => void;
}
VerificationButton.propTypes = {
verifiedConfigs: PropTypes.bool.isRequired,
isStarting: PropTypes.bool.isRequired,
role: PropTypes.string.isRequired,
handleNext: PropTypes.func.isRequired,
};

Comment on lines +18 to +31
interface PeerWithHash {
id: string;
peer: {
name: string;
cert: string;
};
hash: string;
}

interface Props {
peersWithHash: PeerWithHash[];
enteredHashes: string[];
handleChangeHash: (value: string, index: number) => void;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding prop types validation.

Ensure that the props passed to the component are validated for type safety.

+ import PropTypes from 'prop-types';

PeerVerificationTable.propTypes = {
  peersWithHash: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.string.isRequired,
      peer: PropTypes.shape({
        name: PropTypes.string.isRequired,
        cert: PropTypes.string.isRequired,
      }).isRequired,
      hash: PropTypes.string.isRequired,
    })
  ).isRequired,
  enteredHashes: PropTypes.arrayOf(PropTypes.string).isRequired,
  handleChangeHash: PropTypes.func.isRequired,
};

Committable suggestion was skipped due to low confidence.

Comment on lines +57 to +85
const tableRows = peersWithHash.map(({ peer, hash }, idx) => {
const value = enteredHashes[idx] || '';
const isValid = Boolean(value && value === hash);
const isError = Boolean(value && !isValid);
return {
key: peer.cert,
name: (
<Text maxWidth={200} isTruncated>
{peer.name}
</Text>
),
status: isValid ? (
<Tag colorScheme='green'>{t('verify-guardians.verified')}</Tag>
) : (
''
),
hashInput: (
<FormControl isInvalid={isError}>
<Input
variant='filled'
value={value}
placeholder={`${t('verify-guardians.verified-placeholder')}`}
onChange={(ev) => handleChangeHash(ev.currentTarget.value, idx)}
readOnly={isValid}
/>
</FormControl>
),
};
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Optimize table row mapping.

Ensure that the table row mapping is optimized for performance.

-  const tableRows = peersWithHash.map(({ peer, hash }, idx) => {
-    const value = enteredHashes[idx] || '';
-    const isValid = Boolean(value && value === hash);
-    const isError = Boolean(value && !isValid);
-    return {
-      key: peer.cert,
-      name: (
-        <Text maxWidth={200} isTruncated>
-          {peer.name}
-        </Text>
-      ),
-      status: isValid ? (
-        <Tag colorScheme='green'>{t('verify-guardians.verified')}</Tag>
-      ) : (
-        ''
-      ),
-      hashInput: (
-        <FormControl isInvalid={isError}>
-          <Input
-            variant='filled'
-            value={value}
-            placeholder={`${t('verify-guardians.verified-placeholder')}`}
-            onChange={(ev) => handleChangeHash(ev.currentTarget.value, idx)}
-            readOnly={isValid}
-          />
-        </FormControl>
-      ),
-    };
-  });
+  const tableRows = peersWithHash.map(({ peer, hash }, idx) => {
+    const value = enteredHashes[idx] || '';
+    const isValid = value === hash;
+    const isError = value && !isValid;
+    return {
+      key: peer.cert,
+      name: <Text maxWidth={200} isTruncated>{peer.name}</Text>,
+      status: isValid ? <Tag colorScheme='green'>{t('verify-guardians.verified')}</Tag> : '',
+      hashInput: (
+        <FormControl isInvalid={isError}>
+          <Input
+            variant='filled'
+            value={value}
+            placeholder={t('verify-guardians.verified-placeholder')}
+            onChange={(ev) => handleChangeHash(ev.currentTarget.value, idx)}
+            readOnly={isValid}
+          />
+        </FormControl>
+      ),
+    };
+  });
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const tableRows = peersWithHash.map(({ peer, hash }, idx) => {
const value = enteredHashes[idx] || '';
const isValid = Boolean(value && value === hash);
const isError = Boolean(value && !isValid);
return {
key: peer.cert,
name: (
<Text maxWidth={200} isTruncated>
{peer.name}
</Text>
),
status: isValid ? (
<Tag colorScheme='green'>{t('verify-guardians.verified')}</Tag>
) : (
''
),
hashInput: (
<FormControl isInvalid={isError}>
<Input
variant='filled'
value={value}
placeholder={`${t('verify-guardians.verified-placeholder')}`}
onChange={(ev) => handleChangeHash(ev.currentTarget.value, idx)}
readOnly={isValid}
/>
</FormControl>
),
};
});
const tableRows = peersWithHash.map(({ peer, hash }, idx) => {
const value = enteredHashes[idx] || '';
const isValid = value === hash;
const isError = value && !isValid;
return {
key: peer.cert,
name: <Text maxWidth={200} isTruncated>{peer.name}</Text>,
status: isValid ? <Tag colorScheme='green'>{t('verify-guardians.verified')}</Tag> : '',
hashInput: (
<FormControl isInvalid={isError}>
<Input
variant='filled'
value={value}
placeholder={t('verify-guardians.verified-placeholder')}
onChange={(ev) => handleChangeHash(ev.currentTarget.value, idx)}
readOnly={isValid}
/>
</FormControl>
),
};
});

@elsirion
Copy link
Contributor

This PR is in rebase hell 😬

@Kodylow
Copy link
Member Author

Kodylow commented Aug 23, 2024

yeah gotta update it, but bigger issue is I still can't stop the fucking flickering. Will rebase but then could use some help or maybe just ask around on nostr for someone who might know what's up

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants