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

Add utility for universal text replacement #53

Closed
wants to merge 1 commit into from

Conversation

jonathankap
Copy link
Contributor

@jonathankap jonathankap commented Jun 14, 2024

Adds a utility to do universal text replacement using a MutationObserver. It automatically adds and removes the observer as patterns are added. To use it:

import UniversalReplace from "../universalReplace";
...
UniversalReplace.addPattern('the', 'teh');

You can also add regular expressions as patterns, but note that the equivalent of 'the' is /\bthe\b/ig

Summary by CodeRabbit

  • New Features

    • Introduced dynamic text replacement functionality. Users can now specify patterns to replace text content on web pages dynamically. The feature reacts to changes in the DOM and applies replacement rules accordingly.
  • Improvements

    • Enhanced the mocksi-lite app to include .map files as web-accessible resources, improving debugging and development experience.

Copy link

coderabbitai bot commented Jun 14, 2024

Walkthrough

Walkthrough

The updates introduce significant dynamic content replacement capabilities to the mocksi-lite app. The new UniversalReplace class can now detect and replace text in the DOM based on dynamic patterns using MutationObserver. This enhancement enables sophisticated manipulation of web content without altering the HTML structure. Additionally, .map files are now accessible as web resources.

Changes

Files Change Summary
.../manifest.json Added "/*.map" to web_accessible_resources to make source maps accessible for debugging.
.../universalReplace.ts Enhanced UniversalReplace class with dynamic pattern replacement using MutationObserver. Added new methods for pattern management and a text case handling function.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant DOM
    participant UniversalReplace
    participant MutationObserver

    User->>DOM: Loads the Web Page
    DOM->>UniversalReplace: Initializes Replacement Engine
    UniversalReplace->>MutationObserver: Start Observing DOM Changes
    DOM->>MutationObserver: Detects DOM Mutation
    MutationObserver->>UniversalReplace: Reports Mutation
    UniversalReplace->>DOM: Applies Pattern Replacements
    DOM->>User: Displays Updated Content
Loading

Poem

In the code where changes bloom,

Patterns weave and text does groom.

The UniversalReplace on watchful tread,

Alters words with gentle spread.

Source maps now a debugger's boon,

Code and flow aligned; a new moon's tune. 🌜🐇


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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 934ac7b and 97faa92.

Files selected for processing (2)
  • apps/mocksi-lite/manifest.json (1 hunks)
  • apps/mocksi-lite/universalReplace.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • apps/mocksi-lite/manifest.json
Additional context used
Biome
apps/mocksi-lite/universalReplace.ts

[error] 6-7: This constructor is unnecessary. (lint/complexity/noUselessConstructor)

Unsafe fix: Remove the unnecessary constructor.


[error] 30-55: This function expression can be turned into an arrow function. (lint/complexity/useArrowFunction)

Function expressions that don't use this can be turned into arrow functions.
Safe fix: Use an arrow function instead.


[error] 76-78: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.

Additional comments not posted (5)
apps/mocksi-lite/universalReplace.ts (5)

9-15: Well-implemented method for adding patterns. Consider adding comments to explain the logic, especially how patterns are transformed and stored.


17-26: Good implementation of pattern removal and efficient management of the observer based on the patterns array length.


60-68: Efficient implementation of pattern matching. Ensure comprehensive unit tests cover various text inputs and pattern complexities.


82-88: Well-implemented utility function for converting patterns to regular expressions. Ensure edge cases and special characters in patterns are handled correctly.


90-90: Appropriate use of default export for a utility class that is likely intended to be used as a singleton.

Comment on lines +6 to +7
constructor() {
}
Copy link

Choose a reason for hiding this comment

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

Remove the unnecessary constructor to simplify the class definition.

-    constructor() {
-    }
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
constructor() {
}
Tools
Biome

[error] 6-7: This constructor is unnecessary. (lint/complexity/noUselessConstructor)

Unsafe fix: Remove the unnecessary constructor.

Comment on lines +30 to +55
this.observer = new MutationObserver(function (mutations) {
for (let mutation of mutations) {
if (mutation.addedNodes != null && mutation.addedNodes.length > 0) {
for (let node of mutation.addedNodes) {
if (node instanceof Text &&
node.parentElement &&
!(node.parentElement instanceof HTMLScriptElement) &&
!(node.parentElement instanceof HTMLStyleElement) &&
node.textContent !== null &&
!(/^\s*$/.test(node.textContent)))
{
const replace = this_.matchReplacePattern(node.textContent);
if (replace) {
const treeWalker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);
let textNode: Node
do {
textNode = treeWalker.currentNode;
if (textNode.nodeValue === null) continue;
textNode.nodeValue = textNode.nodeValue.replace(replace.pattern, replaceFirstLetterCase(replace.replace));
} while (treeWalker.nextNode());
}
}
}
}
}
});
Copy link

@coderabbitai coderabbitai bot Jun 14, 2024

Choose a reason for hiding this comment

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

Refactor the function expression to an arrow function to enhance readability and maintain consistency with modern JavaScript practices.

-        this.observer = new MutationObserver(function (mutations) {
+        this.observer = new MutationObserver((mutations) => {

Committable suggestion was skipped due to low confidence.

Tools
Biome

[error] 30-55: This function expression can be turned into an arrow function. (lint/complexity/useArrowFunction)

Function expressions that don't use this can be turned into arrow functions.
Safe fix: Use an arrow function instead.

Copy link
Contributor

Choose a reason for hiding this comment

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

Yeah, also changing that you won't need to declare const this_ = this;

Copy link

Choose a reason for hiding this comment

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

@NicoMorenoSirius You're absolutely right! By converting the function to an arrow function, this automatically refers to the enclosing context, eliminating the need for const this_ = this;. Here’s how the refactored code would look:

createObserver() {
    this.observer = new MutationObserver((mutations) => {
        for (let mutation of mutations) {
            if (mutation.addedNodes != null && mutation.addedNodes.length > 0) {
                for (let node of mutation.addedNodes) {
                    if (node instanceof Text && 
                        node.parentElement &&
                        !(node.parentElement instanceof HTMLScriptElement) &&
                        !(node.parentElement instanceof HTMLStyleElement) &&
                        node.textContent !== null &&
                        !(/^\s*$/.test(node.textContent)))
                    {
                        const replace = this.matchReplacePattern(node.textContent);
                        if (replace) {
                            const treeWalker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);
                            let textNode;
                            do {
                                textNode = treeWalker.currentNode;
                                if (textNode.nodeValue === null) continue;
                                textNode.nodeValue = textNode.nodeValue.replace(replace.pattern, replaceFirstLetterCase(replace.replace));
                            } while (treeWalker.nextNode());
                        }
                    }
                }
            }
        });
}

This change simplifies the code and enhances its readability. If there's anything else you'd like to adjust or discuss, feel free to let me know!


Learnings added
User: NicoMorenoSirius
PR: Mocksi/HARlighter#53
File: apps/mocksi-lite/universalReplace.ts:30-55
Timestamp: 2024-06-17T19:21:12.952Z
Learning: Arrow functions capture the `this` value of the enclosing context at the time they are created, making the use of `const this_ = this;` redundant when refactoring from a traditional function.

Note: Learnings are effective only in the context of specific code segments. To apply general coding guidelines, please configure review instructions.

Comment on lines +71 to +79
const replaceFirstLetterCase = (value: string) => {
return (match: string) => {
// Check if the first letter in the match is uppercase
if (match[0] === match[0].toUpperCase()) {
return value.charAt(0).toUpperCase() + value.slice(1);
} else {
return value;
}
}
Copy link

Choose a reason for hiding this comment

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

Simplify the function by removing the unnecessary else clause.

-        } else {
-            return value;
-        }
+        return value;
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 replaceFirstLetterCase = (value: string) => {
return (match: string) => {
// Check if the first letter in the match is uppercase
if (match[0] === match[0].toUpperCase()) {
return value.charAt(0).toUpperCase() + value.slice(1);
} else {
return value;
}
}
const replaceFirstLetterCase = (value: string) => {
return (match: string) => {
// Check if the first letter in the match is uppercase
if (match[0] === match[0].toUpperCase()) {
return value.charAt(0).toUpperCase() + value.slice(1);
}
return value;
}
}
Tools
Biome

[error] 76-78: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.

@NicoMorenoSirius
Copy link
Contributor

Closing because this branch is inside this PR:
#61

@elg0nz elg0nz deleted the universal_replace 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