Skip to content
This repository has been archived by the owner on Sep 26, 2024. It is now read-only.

[MOC-179] image alterations #141

Merged
merged 23 commits into from
Aug 16, 2024
Merged

[MOC-179] image alterations #141

merged 23 commits into from
Aug 16, 2024

Conversation

fitzk
Copy link
Contributor

@fitzk fitzk commented Aug 9, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced image upload functionality with a new callback parameter for improved integration.
    • Ability to undo image edits and restore original sources through new state management.
    • Direct image upload from the EditToast via double-click events.
    • Introduced a custom hook for managing image uploads efficiently, including modal interfaces and storage management.
    • Improved testing capabilities with new configuration and mock setups for Vitest.
  • Bug Fixes

    • Button interaction streamlined by conditionally disabling based on the presence of image edits.
    • Reduced console output by removing unnecessary log statements.

Copy link

coderabbitai bot commented Aug 9, 2024

Warning

Rate limit exceeded

@fitzk has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 23 minutes and 13 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between 1ea8eaa and 964963e.

Walkthrough

Walkthrough

The recent changes enhance the modularity and functionality of image upload and editing processes across multiple components. Key updates include making the openImageUploadModal function public with a new onChange callback, introducing a custom useImages hook for improved state management, and enhancing the EditToast component's image handling. These modifications streamline code structures, improve user interactions, and significantly elevate the overall usability of the application.

Changes

File Change Summary
apps/mocksi-lite/content/EditMode/... Made openImageUploadModal public with an onChange callback; removed closeImageUploadModal; reordered parameters in decorateTextTag and modified type declaration in applyEditor.
apps/mocksi-lite/content/Toast/... Enhanced EditToast with new state management for images using useImages and improved event handling; modified ApplyAlteration type.
apps/mocksi-lite/content/useImages... Introduced useImages hook for managing image uploads and edits, featuring state tracking, modal handling, and storage management.
apps/mocksi-lite/package.json Updated devDependencies for improved testing capabilities and modified test script for Vitest.
apps/mocksi-lite/tsconfig.json Expanded types array and modified exclude pattern for better type support and file exclusions.
apps/mocksi-lite/vitest.* Added configuration files for Vitest, including environment setup for DOM testing with mocks.

Poem

🐰 In the code where rabbits play,
Changes hop in bright array,
Images dance, buttons gleam,
A toast of joy, what a dream!
So leap and twirl, rejoice today,
For every line, a brighter way! 🥕✨


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>.
    • 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.

Copy link

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

Outside diff range, codebase verification and nitpick comments (1)
apps/mocksi-lite/content/EditMode/editMode.ts (1)

Line range hint 10-66:
Refactor suggestion: Consider separating modal creation and event handling.

The openImageUploadModal function handles both modal creation and event handling. Consider separating these concerns to improve readability and maintainability.

function createModalContent(): HTMLElement {
  const modalContent = document.createElement("div");
  modalContent.innerHTML = `
      <div id="image-upload-modal" style="display: block; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border: 1px solid #ccc;">
          <h2>Upload New Image</h2>
          <input type="file" id="image-input" accept="image/*">
          <button id="upload-button">Upload</button>
          <button id="cancel-button">Cancel</button>
      </div>
  `;
  return modalContent;
}

function openImageUploadModal(
  targetedElement: HTMLImageElement,
  onChange: (i: number | string, src: string) => void,
) {
  console.log("targetElement", targetedElement);

  const modalContainer = document.createElement("div");
  document.body.appendChild(modalContainer);

  const shadowRoot = modalContainer.attachShadow({ mode: "open" });
  shadowRoot.appendChild(createModalContent());

  const imageInput = shadowRoot.querySelector("#image-input") as HTMLInputElement;
  const uploadButton = shadowRoot.querySelector("#upload-button") as HTMLButtonElement;
  const cancelButton = shadowRoot.querySelector("#cancel-button") as HTMLButtonElement;

  targetedElement.focus();

  uploadButton.addEventListener("click", () => {
    const file = imageInput.files?.[0];
    if (file) {
      convertImageToDataUri(file)
        .then((newSrc) => {
          if (targetedElement.srcset) {
            targetedElement.removeAttribute("srcset");
          }
          targetedElement.src = newSrc;
          const i = targetedElement.getAttribute("data-mocksi-img");
          if (i) {
            onChange(i, newSrc);
            console.log("after: ", targetedElement);
          }
        })
        .catch((error) => {
          console.error("Error reading file:", error);
        });
      closeImageUploadModal();
    } else {
      console.error("No file selected.");
    }
  });

  cancelButton.addEventListener("click", closeImageUploadModal);

  function closeImageUploadModal() {
    document.body.removeChild(modalContainer);
  }
}
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 34ee92b and 09ae29d.

Files selected for processing (3)
  • apps/mocksi-lite/content/EditMode/editMode.ts (5 hunks)
  • apps/mocksi-lite/content/ListPopup/DemoItem.tsx (1 hunks)
  • apps/mocksi-lite/content/Toast/EditToast.tsx (10 hunks)
Additional comments not posted (9)
apps/mocksi-lite/content/ListPopup/DemoItem.tsx (1)

73-73: Verify the impact of always enabling the Play button.

The button is no longer conditionally disabled based on the alterations array. Ensure that this change does not negatively impact the user experience, especially in scenarios where the button should be disabled.

apps/mocksi-lite/content/EditMode/editMode.ts (3)

6-9: Verify the usage of the onChange parameter in openImageUploadModal.

The onChange parameter is a new addition that allows for better integration. Verify that this parameter is used correctly across the codebase and that it effectively handles changes as intended.

Verification successful

The onChange parameter in openImageUploadModal is used correctly.

The function setDemoSrc is defined with the appropriate signature and is used to update the image source mapping, ensuring that changes are handled as intended.

  • apps/mocksi-lite/content/Toast/EditToast.tsx: setDemoSrc is defined and used correctly with openImageUploadModal.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the `onChange` parameter in `openImageUploadModal`.

# Test: Search for all calls to `openImageUploadModal` to ensure `onChange` is used correctly.
rg --type ts $'openImageUploadModal($_, $_)'

Length of output: 45


Script:

#!/bin/bash
# Description: Search for all occurrences of `openImageUploadModal` to verify its usage.

# Test: Search for all calls to `openImageUploadModal` in the codebase.
rg --type ts 'openImageUploadModal'

Length of output: 411


Script:

#!/bin/bash
# Description: Search for the definition and usage of `setDemoSrc` in `EditToast.tsx`.

# Test: Find where `setDemoSrc` is defined and how it is used in `EditToast.tsx`.
rg --type ts 'setDemoSrc' apps/mocksi-lite/content/Toast/EditToast.tsx -A 5 -B 5

Length of output: 913


119-119: Parameter reordering in applyEditor function.

The reordering of selectedRange parameters does not affect functionality but improves readability. Ensure that all calls to this function are updated accordingly.

Verification successful

All calls to applyEditor are correctly updated with the new parameter order.

The call to applyEditor in EditToast.tsx matches the parameter order defined in editMode.ts. No further updates are needed.

  • EditToast.tsx:
    • applyEditor(targetedElement, selection, event.shiftKey, applyAlteration);
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all calls to `applyEditor` are updated with the new parameter order.

# Test: Search for all calls to `applyEditor`.
rg --type ts $'applyEditor($_, null | $_, $_, $_)'

Length of output: 51


Script:

#!/bin/bash
# Locate the definition of the `applyEditor` function to understand its parameters.
ast-grep --lang typescript --pattern 'function applyEditor($_, $_, $_, $_) { $$$ }'

# Search for all calls to `applyEditor` in the codebase to verify parameter order.
rg 'applyEditor(' -A 2 --type ts

Length of output: 1931


Script:

#!/bin/bash
# Correct the search pattern to find all calls to `applyEditor`.
rg 'applyEditor\(' -A 2 --type ts

Length of output: 460


Script:

#!/bin/bash
# Search for the full call to `applyEditor` in `EditToast.tsx` to verify all parameters.
rg 'applyEditor\(' -A 5 apps/mocksi-lite/content/Toast/EditToast.tsx

Length of output: 175


92-92: Parameter reordering in decorateTextTag function.

The reordering of endOffset and startOffset parameters improves readability without affecting functionality. Ensure that all calls to this function are updated accordingly.

apps/mocksi-lite/content/Toast/EditToast.tsx (5)

62-62: Use of useRef for modal tracking.

The useRef hook is used to track the currently open modal, which enhances handling of double-click events on images. Ensure that this approach effectively manages modal states across different scenarios.

Verification successful

Use of useRef for modal tracking is appropriate.

The modalOpenRef is used to track the index of the currently open modal, ensuring that modal state changes are handled correctly. The implementation checks and updates the current property effectively.

  • File: apps/mocksi-lite/content/Toast/EditToast.tsx
  • Lines: Initialization and conditional updates.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the effectiveness of using `useRef` for tracking open modals.

# Test: Search for all references to `modalOpenRef` to ensure it is used correctly.
rg --type tsx $'modalOpenRef'

Length of output: 56


Script:

#!/bin/bash
# Description: Search for all references to `modalOpenRef` in the codebase.

# Test: Search for all occurrences of `modalOpenRef` in any file.
rg 'modalOpenRef'

Length of output: 422


Line range hint 226-244:
Ensure proper cleanup with teardownEditor and resetEditor.

Both teardownEditor and resetEditor functions include calls to undoImgEdits. Verify that these functions are invoked correctly to ensure proper cleanup of the component state.

Verification successful

Cleanup Functions Verified: teardownEditor and resetEditor are Invoked Correctly

The functions teardownEditor and resetEditor are defined and invoked within the same file, ensuring proper cleanup of the component state. No issues were found with their usage.

  • teardownEditor is invoked at line 226 in apps/mocksi-lite/content/Toast/EditToast.tsx.
  • resetEditor is invoked at line 230 in the same file.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correct invocation of `teardownEditor` and `resetEditor` for cleanup.

# Test: Search for all references to `teardownEditor` and `resetEditor`.
rg --type tsx $'teardownEditor|resetEditor'

Length of output: 72


Script:

#!/bin/bash
# Description: Verify the correct invocation of `teardownEditor` and `resetEditor` for cleanup.

# Test: Search for all references to `teardownEditor` and `resetEditor` without specifying file type.
rg 'teardownEditor|resetEditor'

Length of output: 329


125-141: New function undoImgEdits for restoring image sources.

The undoImgEdits function restores original image sources based on stored mappings. Ensure that this function is called appropriately during the component's lifecycle.

Verification successful

Verified Usage of undoImgEdits Function

The undoImgEdits function is appropriately used within the component's lifecycle, specifically in functions that handle resetting or reverting editor states. This ensures that image sources are restored to their original state as intended.

  • Calls to undoImgEdits are found in functions handling modifications and editor resets.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the appropriate use of `undoImgEdits` during the component's lifecycle.

# Test: Search for all calls to `undoImgEdits` to ensure it is used correctly.
rg --type tsx $'undoImgEdits'

Length of output: 56


Script:

#!/bin/bash
# Description: Verify the appropriate use of `undoImgEdits` during the component's lifecycle.

# Test: Search for all calls to `undoImgEdits` to ensure it is used correctly.
rg 'undoImgEdits'

Length of output: 227


Script:

#!/bin/bash
# Description: Extract context around `undoImgEdits` calls to verify appropriate usage.

# Extract 5 lines before and after each call to `undoImgEdits` in `EditToast.tsx`.
rg 'undoImgEdits' -A 5 -B 5 apps/mocksi-lite/content/Toast/EditToast.tsx

Length of output: 754


162-209: Setup of image data and event listeners in setupEditor.

The setupEditor function now gathers image data and sets up event listeners for double-clicks on images. Ensure that this setup is robust and does not introduce performance issues.


112-123: New function setDemoSrc for image source management.

The setDemoSrc function updates the imgSrcMap with demo source information. Ensure that this function integrates well with other parts of the image handling logic.

Copy link
Contributor

@elg0nz elg0nz left a comment

Choose a reason for hiding this comment

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

Lovely!

const i = targetedElement.getAttribute("data-mocksi-img");
if (i) {
onChange(i, newSrc);
console.log("after: ", targetedElement);
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: console.debug 😉

}
for (let i = 0; i < images.length; i++) {
const image = images[i];
console.log(image);
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: console.log

});
}

function undoImgEdits() {
Copy link
Contributor

Choose a reason for hiding this comment

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

Just Couple edits:

  1. Early Resolve: Moved resolve() to execute immediately after checking the length of images, ensuring that the promise is resolved right away if there are no images.
  2. for...of Loop: Refactored the loop to use for...of with Array.from(images).entries(). This enhances clarity by directly iterating over the images collection with access to both the index and the image in each iteration.
  3. Type Annotation: Explicitly typed images as HTMLCollectionOf to ensure strong typing throughout the function.
  4. Optional Chaining (?.): Added optional chaining when accessing originalSrc to avoid potential runtime errors if imgSrcMap[i] is undefined.

Here's how the final code should look like:

function undoImgEdits(): Promise<void> {
    return new Promise<void>((resolve) => {
        const images: HTMLCollectionOf<HTMLImageElement> = document.images;

        if (images.length === 0) {
            resolve();
            return;
        }

        for (const [i, image] of Array.from(images).entries()) {
            console.debug(image);
            const src: string | undefined = imgSrcMap[i]?.originalSrc;

            if (src) {
                image.src = src;
            }
        }

        resolve();
    });
}

(hope you don't mind ChatGPT typing the explanation above 😅 )

@@ -125,18 +159,72 @@ const EditToast = ({ initialReadOnlyState }: EditToastProps) => {
applyReadOnlyMode();
}

document.body.addEventListener("dblclick", onDoubleClickText);
const images = document.images;
Copy link
Contributor

Choose a reason for hiding this comment

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

I’ve refactored the code snippet for improved readability and maintainability. The main changes include:

  1. for...of Loop: Replaced the for loop with a for...of loop using Array.from(images).entries(). This makes the iteration more expressive and eliminates the need to manually manage the index.
  2. DRY Principle: Combined the duplicated dblclick event listeners into a single function to avoid redundancy and make the code easier to maintain.
  3. Type Annotation: Maintained explicit typing for tempImageSrcMap to ensure the structure of the record is clear and strongly typed.

The final code should look like this:

const images: HTMLCollectionOf<HTMLImageElement> = document.images;
const tempImageSrcMap: Record<
    number,
    { demoSrc: string; index: string; originalSrc: string }
> = {};

// Function to handle the dblclick event
const handleDblClick = (image: HTMLImageElement, i: number) => (event: Event) => {
    event.stopPropagation();
    if (modalOpenRef.current !== i) {
        openImageUploadModal(image, setDemoSrc);
        modalOpenRef.current = i;
    }
};

for (const [i, image] of Array.from(images).entries()) {
    if (image.style.display === "none" && !image.checkVisibility()) {
        continue; // Early return to skip the current iteration
    }

    tempImageSrcMap[i] = {
        demoSrc: "",
        index: i.toString(),
        originalSrc: image.src,
    };

    image.setAttribute("data-mocksi-img", i.toString());
    image.setAttribute("listener", "true");

    const parent = image.parentNode;
    if (parent) {
        parent.addEventListener("dblclick", handleDblClick(image, i), false);
    }

    image.addEventListener("dblclick", handleDblClick(image, i), false);
}

Copy link
Contributor

Choose a reason for hiding this comment

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

(and yes another ChatGPT-assisted suggestion 😅 )

Copy link

@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, codebase verification and nitpick comments (1)
apps/mocksi-lite/content/EditMode/editMode.ts (1)

Line range hint 22-22:
Consider removing or replacing console.debug.

The use of console.debug might not be suitable for production code. Consider using a logging library or removing it before finalizing the PR.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 09ae29d and 50df99e.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (8)
  • apps/mocksi-lite/content/EditMode/editMode.ts (2 hunks)
  • apps/mocksi-lite/content/Toast/EditToast.tsx (9 hunks)
  • apps/mocksi-lite/content/useImages.test.tsx (1 hunks)
  • apps/mocksi-lite/content/useImages.tsx (1 hunks)
  • apps/mocksi-lite/package.json (2 hunks)
  • apps/mocksi-lite/tsconfig.json (1 hunks)
  • apps/mocksi-lite/vitest.config.ts (1 hunks)
  • apps/mocksi-lite/vitest.init.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • apps/mocksi-lite/vitest.config.ts
Files skipped from review as they are similar to previous changes (1)
  • apps/mocksi-lite/content/Toast/EditToast.tsx
Additional comments not posted (8)
apps/mocksi-lite/tsconfig.json (2)

20-20: Enhanced type support for testing libraries.

The addition of vitest/globals and @testing-library/jest-dom to the types field improves type support for testing, which is a positive change.


22-22: Ensure exclusion of test files is intentional.

The change to exclude both .ts and .tsx test files is appropriate if you intend to exclude all test files from compilation. Verify that this aligns with your project's testing strategy.

Verification successful

Exclusion of test files is intentional and appropriate.

The exclusion pattern in tsconfig.json correctly targets .test.ts and .test.tsx files, aligning with the project's strategy to exclude test files from compilation. Configuration and setup files with "test" in their names do not need to be excluded.

  • The exclusion pattern ./**/*.test.tsx? is correctly applied.
  • No additional test files require exclusion.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Ensure that the exclusion of `.ts` and `.tsx` test files is intentional.

# Test: List all test files to confirm exclusion is as intended.
fd --extension ts --extension tsx --exec echo

Length of output: 3265


Script:

#!/bin/bash
# Description: Check for any test files with extensions other than `.test.ts` or `.test.tsx`.

# Test: List files that contain 'test' in their name but do not end with `.test.ts` or `.test.tsx`.
fd --type f --exec echo | grep 'test' | grep -v '\.test\.ts$' | grep -v '\.test\.tsx$'

Length of output: 306

apps/mocksi-lite/vitest.init.ts (2)

1-6: Proper setup for testing with JSDOM and Vitest.

The imports and setup for using JSDOM and Vitest are correctly configured, which is essential for testing components that interact with the DOM.


8-19: Verify Chrome API mock implementations.

Ensure that the mock implementations for the Chrome API accurately reflect the expected behavior in your tests. This is crucial for reliable test results.

apps/mocksi-lite/package.json (2)

16-35: Improved testing capabilities with new dependencies.

The addition of testing libraries and updates to type definitions enhance the project's testing framework, which is a positive change.


46-46: Verify the test script configuration.

Ensure that the vitest.config.ts file is correctly set up and that the test script functions as expected with the new configuration.

Verification successful

Test script configuration appears to be correctly set up.

The vitest.config.ts file(s) contain valid configurations for vitest, specifying jsdom as the test environment. Ensure that the intended configuration is being used for your tests. If there are specific concerns about which configuration should be applied, further manual verification may be needed.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence and correctness of the `vitest.config.ts` file.

# Test: Check for the presence of the `vitest.config.ts` file.
fd --type f --name 'vitest.config.ts' --exec cat

Length of output: 299


Script:

#!/bin/bash
# Description: Verify the existence and correctness of the `vitest.config.ts` file.

# Test: Check for the presence of the `vitest.config.ts` file.
fd --type f 'vitest.config.ts' --exec cat

Length of output: 463

apps/mocksi-lite/content/useImages.test.tsx (1)

1-44: Basic test structure looks good.

The initial setup and basic tests for the useImages hook are well-structured. They provide a foundation for further expansion.

apps/mocksi-lite/content/EditMode/editMode.ts (1)

Line range hint 10-37:
Enhancements to modularity and usability are well-implemented.

The changes to decorateTextTag and applyEditor functions improve the modularity and usability of the code.

document.body.innerHTML = "";
});

// TODO: expand on or remove test
Copy link

Choose a reason for hiding this comment

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

Consider expanding the test coverage.

The TODO comment suggests that the test case is minimal. Consider expanding it to cover additional scenarios, such as error handling and edge cases.

Would you like assistance in expanding the test cases or opening a GitHub issue to track this task?

Comment on lines 1 to 212
reader.onerror = reject;
reader.readAsDataURL(file);
});
}

async function getStoredEdits() {
const storage = await chrome.storage.local.get("mocksi-images");
const storedImages = storage["mocksi-images"];
const url = new URL(document.location.href);
const editsForHostname = storedImages?.[url.hostname];
if (editsForHostname) {
console.debug(`no stored images found for ${url.hostname}`);
return;
}
return editsForHostname;
}

function undoImagesEdits() {
return new Promise<void>((resolve) => {
const images = document.images;
if (!images.length) {
resolve();
return;
}
for (let i = 0; i < images.length; i++) {
const image = images[i];
const edit = edits[i];
if (edit) {
const src = edits[i].originalSrc;
if (src) {
// image.replaceWith(image.cloneNode(true)) TODO: look into using this
image.src = edit.originalSrc;
}
}
}
resolve();
});
}

useEffect(() => {
const images = document.images;
if (images.length) {
console.error("No images found in document");
return;
}
// use to remove all event listeners on unmount
const { signal } = abortControllerRef.current;
if (!signal) {
console.debug("abort controller undefined");
}
// add data attribute and double click handlers
for (let i = 0; i < images.length; i++) {
const image = images[i];

// only edit visible image elements
if (image.checkVisibility()) {
image.setAttribute("data-mocksi-img", i.toString());
image.setAttribute("listener", "true");

const parent = image.parentNode;

const handleDoubleClick: EventListener = (event) => {
event.stopPropagation();
if (uploadModalOpenRef.current !== i) {
function setDemoSrc(i: number, demoSrc: string) {
setEdits((prevState) => {
return {
...prevState,
[i]: {
...prevState[i],
demoSrc,
},
};
});
}

openImageUploadModal(image, setDemoSrc);
uploadModalOpenRef.current = i;
}
};

parent?.addEventListener("dblclick", handleDoubleClick, { signal });
image.addEventListener("dblclick", handleDoubleClick, { signal });
}
}

return () => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
};
}, [openImageUploadModal]);

return {
edits,
getStoredEdits,
setEdits,
storeEdits,
};
}
Copy link

Choose a reason for hiding this comment

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

Consider enhancing error handling and performance.

While the useImages hook is well-structured, consider the following improvements:

  • Enhance error handling, especially in asynchronous operations like storeEdits and getStoredEdits.
  • Optimize performance by minimizing DOM manipulations, such as creating and removing elements in openImageUploadModal.

Overall, the hook provides essential functionalities for image management.

Copy link

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 50df99e and 93d314e.

Files selected for processing (2)
  • apps/mocksi-lite/content/ListPopup/DemoItem.tsx (1 hunks)
  • apps/mocksi-lite/content/useImages.tsx (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • apps/mocksi-lite/content/useImages.tsx
Additional comments not posted (1)
apps/mocksi-lite/content/ListPopup/DemoItem.tsx (1)

69-69: Verify the always-enabled handlePlay button behavior.

The Button for handlePlay is now always enabled. Ensure this change aligns with the intended user experience and does not lead to unexpected behavior, especially if alterations is expected to influence the button's state.

Copy link

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 93d314e and a3b712a.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (4)
  • apps/mocksi-lite/content/useImages.test.tsx (1 hunks)
  • apps/mocksi-lite/package.json (3 hunks)
  • apps/mocksi-lite/tsconfig.json (1 hunks)
  • apps/mocksi-lite/vitest.init.ts (1 hunks)
Files skipped from review as they are similar to previous changes (4)
  • apps/mocksi-lite/content/useImages.test.tsx
  • apps/mocksi-lite/package.json
  • apps/mocksi-lite/tsconfig.json
  • apps/mocksi-lite/vitest.init.ts

const jsdom = new JSDOM("<!doctype html><html><body></body></html>");
const { window } = jsdom;

global.document = window.document;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I wasn't sure if everything shares one Vite config or not so I just added one to the apps/mocksi-lite scope

Copy link
Contributor

Choose a reason for hiding this comment

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

Afaik this is correct, each app/package has its own vitest with its own Vite config. Duplication sometimes is a good thing 😅

Copy link

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a3b712a and 34409f0.

Files selected for processing (1)
  • apps/mocksi-lite/content/useImages.tsx (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • apps/mocksi-lite/content/useImages.tsx

@fitzk fitzk changed the title image alterations [MOC-179] image alterations Aug 13, 2024
Copy link

linear bot commented Aug 13, 2024

// const result = await chrome.storage.local.get([MOCKSI_RECORDING_ID]);
// const { recordingId } = result[MOCKSI_RECORDING_ID];

await chrome.storage.local.set({
Copy link
Contributor

Choose a reason for hiding this comment

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

Should we not store these as part of alterations rather than a separate entry? Alterations have a type field and I'm pretty sure Reactor will handle the images cc: @jonathankap

});
}

async function applyEdits() {
Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe add a comment here just we can keep track, but this would eventually be replaced by Reactor I believe

Copy link

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 34409f0 and 62d92df.

Files selected for processing (5)
  • apps/mocksi-lite/content/Toast/EditToast.tsx (8 hunks)
  • apps/mocksi-lite/content/Toast/PlayToast.tsx (6 hunks)
  • apps/mocksi-lite/content/useImages.test.tsx (1 hunks)
  • apps/mocksi-lite/content/useImages.tsx (1 hunks)
  • apps/mocksi-lite/utils.ts (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • apps/mocksi-lite/content/Toast/EditToast.tsx
  • apps/mocksi-lite/content/useImages.test.tsx
  • apps/mocksi-lite/content/useImages.tsx
Additional comments not posted (5)
apps/mocksi-lite/content/Toast/PlayToast.tsx (4)

16-16: Import of useImages is appropriate.

The import statement for useImages is correctly added and aligns with the component's functionality enhancements.


59-59: Application of image edits is well-placed.

The call to images.applyEdits() within the useEffect hook ensures that image edits are applied after loading previous modifications, enhancing functionality.


68-68: DOM setup for image editing is appropriate.

The inclusion of images.setupDom() in the handleEdit function is a logical enhancement for preparing the DOM for editing.


80-80: Reversion of image edits is correctly implemented.

The call to images.undoEdits() in the handleStop function ensures that any image edits made during playback are reverted, maintaining state integrity.

apps/mocksi-lite/utils.ts (1)

237-239: Early exit for empty alterations is a good addition.

The early exit condition in loadPreviousModifications prevents unnecessary processing and potential errors when alterations is empty or undefined.

Copy link

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 62d92df and 00cd11f.

Files selected for processing (7)
  • apps/mocksi-lite/content/ListPopup/DemoItem.tsx (3 hunks)
  • apps/mocksi-lite/content/ListPopup/index.tsx (1 hunks)
  • apps/mocksi-lite/content/Toast/EditToast.tsx (7 hunks)
  • apps/mocksi-lite/content/Toast/PlayToast.tsx (5 hunks)
  • apps/mocksi-lite/content/useImages.test.tsx (1 hunks)
  • apps/mocksi-lite/content/useImages.tsx (1 hunks)
  • apps/mocksi-lite/utils.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • apps/mocksi-lite/content/ListPopup/index.tsx
Files skipped from review as they are similar to previous changes (6)
  • apps/mocksi-lite/content/ListPopup/DemoItem.tsx
  • apps/mocksi-lite/content/Toast/EditToast.tsx
  • apps/mocksi-lite/content/Toast/PlayToast.tsx
  • apps/mocksi-lite/content/useImages.test.tsx
  • apps/mocksi-lite/content/useImages.tsx
  • apps/mocksi-lite/utils.ts

@fitzk fitzk marked this pull request as ready for review August 16, 2024 03:21
Copy link

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 00cd11f and 1ea8eaa.

Files selected for processing (5)
  • apps/mocksi-lite/content/ListPopup/DemoItem.tsx (3 hunks)
  • apps/mocksi-lite/content/ListPopup/index.tsx (5 hunks)
  • apps/mocksi-lite/content/Toast/PlayToast.tsx (5 hunks)
  • apps/mocksi-lite/content/useImages.test.tsx (1 hunks)
  • apps/mocksi-lite/content/useImages.tsx (1 hunks)
Files skipped from review as they are similar to previous changes (5)
  • apps/mocksi-lite/content/ListPopup/DemoItem.tsx
  • apps/mocksi-lite/content/ListPopup/index.tsx
  • apps/mocksi-lite/content/Toast/PlayToast.tsx
  • apps/mocksi-lite/content/useImages.test.tsx
  • apps/mocksi-lite/content/useImages.tsx

Copy link
Contributor

@elg0nz elg0nz left a comment

Choose a reason for hiding this comment

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

This looks great, left one question about one dev but it does not seem like a blocker

document.body.innerHTML = "";
});

// TODO: expand on or remove test
Copy link
Contributor

Choose a reason for hiding this comment

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

Good enough for now

@@ -1,5 +1,6 @@
{
"dependencies": {
"-": "^0.0.1",
Copy link
Contributor

Choose a reason for hiding this comment

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

What's this dependency?
Just curious

Copy link
Contributor Author

Choose a reason for hiding this comment

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

oops that's def not supposed to be there good catch!

"resolveJsonModule": true,
"strict": true,
"sourceMap": false,
"moduleResolution": "node",
Copy link
Contributor

Choose a reason for hiding this comment

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

sigh, these re-ordering diffs are super distracting. Can't wait to remove biome 😄

Copy link
Contributor Author

Choose a reason for hiding this comment

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

they are, I try to keep them at a minimum believe it or not haha

const jsdom = new JSDOM("<!doctype html><html><body></body></html>");
const { window } = jsdom;

global.document = window.document;
Copy link
Contributor

Choose a reason for hiding this comment

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

Afaik this is correct, each app/package has its own vitest with its own Vite config. Duplication sometimes is a good thing 😅

pnpm-lock.yaml Outdated
@@ -33,6 +33,9 @@ importers:

apps/mocksi-lite:
dependencies:
'-':
Copy link
Contributor

Choose a reason for hiding this comment

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

Again, just wondering about this dependency.

@fitzk fitzk merged commit e9194ca into main Aug 16, 2024
3 checks passed
@elg0nz elg0nz deleted the img-alterations branch September 12, 2024 21:00
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants