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

MOC-294 flag for recording styles #193

Merged
merged 4 commits into from
Sep 25, 2024

Conversation

jonathankap
Copy link
Contributor

@jonathankap jonathankap commented Sep 25, 2024

Summary by CodeRabbit

  • New Features

    • Introduced DomJsonExportOptions type to customize JSON export options, including style inclusion.
    • Enhanced htmlElementToJson function to support exporting computed styles in JSON output.
    • Updated exportDOM method to accept additional options for improved DOM export functionality.
  • Bug Fixes

    • Improved handling of attributes in DomJsonExportNode to ensure required attributes are enforced.
  • Tests

    • Added new test cases for htmlElementToJson to ensure accurate conversion of HTML elements to JSON, including style handling.

Copy link

coderabbitai bot commented Sep 25, 2024

📝 Walkthrough

Walkthrough

The changes introduce a new type, DomJsonExportOptions, which includes an optional styles property. The DomJsonExportNode type is updated to require the attributes property. The htmlElementToJson function is modified to accept these options, enabling the inclusion of computed styles in the JSON output. The exportDOM method in the Reactor class is also updated to pass these options. Additionally, new test cases are added to ensure the functionality works as intended, particularly focusing on the handling of styles.

Changes

Files Change Summary
packages/reactor/interfaces.ts Added DomJsonExportOptions type with optional styles property. Updated DomJsonExportNode to make attributes a required property.
packages/reactor/main.ts Updated htmlElementToJson function to accept options parameter. Added logic to handle exportStyles, including computed styles in JSON output.
packages/reactor/reactor.ts Modified exportDOM method to include options parameter, ensuring it can utilize new options when exporting the DOM.
packages/reactor/tests/main.test.ts Added test cases for htmlElementToJson, validating conversion and style handling. Included setup for isolated tests and new import statement.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Reactor
    participant Main

    User->>Reactor: exportDOM(element, options)
    Reactor->>Main: htmlElementToJson(root, options)
    Main->>Main: Process HTML element
    alt exportStyles is true
        Main->>Main: Retrieve computed styles
        Main->>Main: Map styles to unique class names
    end
    Main-->>Reactor: Return DomJsonExportNode[]
    Reactor-->>User: Return exported JSON
Loading

Poem

🐰 In the meadow where styles bloom,
A rabbit hops, dispelling gloom.
With JSON now dressed in flair,
Attributes bold, styles to share.
Hooray for changes, bright and new,
A world of color, just for you! 🌼


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

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

🧹 Outside diff range and nitpick comments (5)
packages/reactor/interfaces.ts (2)

40-42: LGTM! Consider adding JSDoc comments.

The new DomJsonExportOptions type is well-defined and follows TypeScript conventions. It provides a clear way to control style inclusion in DOM JSON exports.

Consider adding JSDoc comments to improve documentation:

/**
 * Options for DOM JSON export.
 */
export type DomJsonExportOptions = {
  /**
   * Whether to include computed styles in the export.
   */
  styles?: boolean;
}

40-49: Summary: New export options and modified DOM node representation

The changes introduce a new DomJsonExportOptions type for controlling style inclusion in exports and modify DomJsonExportNode to require the attributes property. These changes enhance the flexibility of DOM JSON exports and ensure consistency in node representation.

Key points:

  1. The new DomJsonExportOptions allows for optional inclusion of styles in exports.
  2. The attributes property in DomJsonExportNode is now required, which may impact existing code.

These changes appear to be part of a larger feature implementation related to MOC-294 for recording styles. Ensure that these changes are reflected in the implementation of the export functionality and that existing code is updated to accommodate the new required attributes property.

packages/reactor/reactor.ts (1)

Line range hint 126-137: LGTM: Method signature updated correctly.

The exportDOM method has been successfully updated to include the optional options parameter, and it's correctly passed to the htmlElementToJson function. This change enhances the method's flexibility while maintaining backward compatibility.

Consider updating the method's JSDoc comment to include information about the new options parameter. Here's a suggested addition:

   * @param {HTMLElement | null} element - The element to export. If not provided, the entire body of the attached document will be exported.
+  * @param {DomJsonExportOptions} [options] - Optional configuration for the DOM export process.
   * @throws {Error} If the reactor is not attached and no element is specified.
   * @return {DomJsonExportNode[]} An array of `DomJsonExportNode` objects representing the exported DOM.
   */
packages/reactor/main.ts (1)

Line range hint 43-140: Add unit tests for the new exportStyles option

The introduction of the exportStyles option adds significant functionality. To ensure reliability and prevent future regressions, please consider adding unit tests that cover scenarios with exportStyles set to true and false.

Would you like me to help draft unit tests for this feature or open a GitHub issue to track this task?

packages/reactor/tests/main.test.ts (1)

2-4: Organize import statements

Consider organizing import statements for better readability. Group imports logically, such as placing all test-related imports together.

Apply this diff:

 import { JSDOM } from "jsdom";
 import { describe, expect, it, beforeEach } from "vitest";
+import type { AppliedModificationsImpl } from "../modifications";
 import type { ModificationRequest } from "../interfaces";
-import { modifyDom, modifyHtml, htmlElementToJson } from "../main";
+import { modifyDom, modifyHtml, htmlElementToJson } from "../main";
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cb5f88f and 5895463.

📒 Files selected for processing (4)
  • packages/reactor/interfaces.ts (1 hunks)
  • packages/reactor/main.ts (5 hunks)
  • packages/reactor/reactor.ts (3 hunks)
  • packages/reactor/tests/main.test.ts (2 hunks)
🔇 Additional comments not posted (3)
packages/reactor/reactor.ts (2)

4-4: LGTM: New import added correctly.

The new import for DomJsonExportOptions is correctly added and aligns with the changes in the exportDOM method.


Line range hint 1-224: Summary: Changes successfully implement the new flag for recording styles.

The modifications to the Reactor class, specifically the exportDOM method, successfully implement the ability to include a flag for recording styles as described in the PR objectives (MOC-294). The changes are well-structured, maintain backward compatibility, and enhance the flexibility of the DOM export process.

Key points:

  1. The new DomJsonExportOptions type is correctly imported.
  2. The exportDOM method signature is updated to include an optional options parameter.
  3. The options parameter is correctly passed to the htmlElementToJson function.

These changes align with the PR objectives and the AI-generated summary, providing the desired functionality for including computed styles in the JSON output when exporting the DOM.

packages/reactor/tests/main.test.ts (1)

381-403: Verify if inline styles should be retained after consolidation

Please verify whether retaining the inline style attributes is intentional after consolidating styles into classes. This may lead to duplication and unnecessary data in the JSON output.

Run the following script to check for elements that have both a class and a style attribute:

Also applies to: 405-437

✅ Verification successful

Inline styles are correctly consolidated without duplication.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find elements with both 'class' and 'style' attributes in the JSON output.

# Test: Search for patterns in test cases. Expect: Elements should not have both attributes unless intentional.
grep -E '"attributes": \{[^}]*"class": "[^"]+",[^}]*"style": "[^"]+"' -r packages/reactor/tests/

Length of output: 98

Comment on lines +44 to 49
export type DomJsonExportNode = {
tag: string;
visible: boolean;
text?: string;
attributes?: Record<string, string>;
attributes: Record<string, string>;
children?: DomJsonExportNode[];
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Issues Found with DomJsonExportNode Type Changes

The recent change making the attributes property required in DomJsonExportNode introduces inconsistencies in the codebase. Specifically, the following instance is missing the attributes property:

  • File: packages/reactor/main.ts
    • Location: nodeToJson function
    • Issue: The DomJsonExportNode object is created without the attributes property.

Please update the affected code to include the attributes property to ensure consistency and prevent potential runtime errors.

🔗 Analysis chain

LGTM! Verify impact on existing code.

The change to make attributes a required property in DomJsonExportNode is logical and aligns with the typical structure of DOM nodes. This ensures consistency in the exported JSON representation of DOM nodes.

However, this change might affect existing code that uses this type. Please run the following script to verify the impact:

Ensure that all usage of DomJsonExportNode includes the attributes property, and update any code that might assume attributes is optional.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of DomJsonExportNode type and potential issues with the attributes property

# Test 1: Find all occurrences of DomJsonExportNode
echo "Occurrences of DomJsonExportNode:"
rg --type typescript "DomJsonExportNode"

# Test 2: Check for potential issues where attributes might be undefined
echo "\nPotential issues with attributes property:"
rg --type typescript "DomJsonExportNode.*\{(?!.*attributes)" -A 5

Length of output: 581


Script:

#!/bin/bash
# Description: Check for usage of DomJsonExportNode type and potential issues with the attributes property

# Test 1: Find all occurrences of DomJsonExportNode
echo "Occurrences of DomJsonExportNode:"
rg "DomJsonExportNode"

# Test 2: Check for potential issues where attributes might be undefined without using look-around
echo "\nPotential issues with attributes property:"
rg "DomJsonExportNode\s*{\s*(?!.*attributes)" -A 5 --pcre2

Length of output: 1669

Comment on lines +78 to +97
if (exportStyles) {
const styles = window.getComputedStyle(element);
if (styles.length > 0) {
const styleString = Array.from(styles)
.map((style) => `${style}: ${styles.getPropertyValue(style)}`)
.join('; ');
let styleClass = stylesMap[styleString];
if (!styleClass) {
styleClass = `mocksi-${styleIndex.idx}`;
stylesMap[styleString] = styleClass;
styleIndex.idx += 1;
}

if (obj.attributes['class']) {
obj.attributes['class'] += ' ' + styleClass;
} else {
obj.attributes['class'] = styleClass;
}
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize style extraction for performance

Using window.getComputedStyle for every element can be performance-intensive, especially for large DOM trees. Consider limiting the extracted styles to only those necessary for your application or implementing caching mechanisms.

Comment on lines +131 to +139
if (exportStyles) {
const stylesString = Object.entries(stylesMap).map(([styleString, clazz]) => `.${clazz} { ${styleString} }`).join('\n');
json.push({
tag: 'style',
visible: false,
text: stylesString,
attributes: {}
})
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid adding empty <style> nodes

If no styles are collected (i.e., stylesMap is empty), the code still adds an empty <style> node to the JSON. This can be unnecessary and may introduce empty nodes in your output.

Apply this diff to add a check before adding the <style> node:

if (exportStyles && Object.keys(stylesMap).length > 0) {
  const stylesString = Object.entries(stylesMap)
    .map(([styleString, clazz]) => `.${clazz} { ${styleString} }`)
    .join('\n');
  json.push({
    tag: 'style',
    visible: false,
    text: stylesString,
    attributes: {}
  });
}
📝 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
if (exportStyles) {
const stylesString = Object.entries(stylesMap).map(([styleString, clazz]) => `.${clazz} { ${styleString} }`).join('\n');
json.push({
tag: 'style',
visible: false,
text: stylesString,
attributes: {}
})
}
if (exportStyles && Object.keys(stylesMap).length > 0) {
const stylesString = Object.entries(stylesMap).map(([styleString, clazz]) => `.${clazz} { ${styleString} }`).join('\n');
json.push({
tag: 'style',
visible: false,
text: stylesString,
attributes: {}
});
}

Comment on lines +91 to +95
if (obj.attributes['class']) {
obj.attributes['class'] += ' ' + styleClass;
} else {
obj.attributes['class'] = styleClass;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle existing class attributes safely

When appending the new style class to the element's class attribute, ensure that you're correctly handling existing classes and avoiding potential duplicates.

Apply this diff to improve class attribute handling:

- if (obj.attributes['class']) {
-   obj.attributes['class'] += ' ' + styleClass;
- } else {
-   obj.attributes['class'] = styleClass;
- }
+ const existingClass = obj.attributes['class'] || '';
+ const classes = new Set(existingClass.split(/\s+/).filter(Boolean));
+ classes.add(styleClass);
+ obj.attributes['class'] = Array.from(classes).join(' ');
📝 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
if (obj.attributes['class']) {
obj.attributes['class'] += ' ' + styleClass;
} else {
obj.attributes['class'] = styleClass;
}
const existingClass = obj.attributes['class'] || '';
const classes = new Set(existingClass.split(/\s+/).filter(Boolean));
classes.add(styleClass);
obj.attributes['class'] = Array.from(classes).join(' ');

@@ -39,7 +40,11 @@
}
}

export const htmlElementToJson = (root: HTMLElement): DomJsonExportNode[] => {
export const htmlElementToJson = (root: HTMLElement, options?: DomJsonExportOptions): DomJsonExportNode[] => {
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

htmlElementToJson is used outside of browser contexts

Using htmlElementToJson without ensuring window is available can lead to runtime errors in non-browser environments.

Affected file:

  • packages/reactor/reactor.ts
🔗 Analysis chain

Ensure window is available in the execution environment

The use of window.getComputedStyle relies on the availability of the window object. Please verify that this function is always executed in a browser environment. If the code can run in non-browser environments (like Node.js), this will cause a runtime error.

You can run the following script to check for non-browser usages of htmlElementToJson:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find usages of 'htmlElementToJson' outside browser contexts.

# Search for files importing 'htmlElementToJson' that don't reference 'window'.
rg --type ts --files-with-matches 'htmlElementToJson' | xargs grep -L 'window'

Length of output: 104

Comment on lines +406 to +407
doc.body.innerHTML = '<div id="test" style="color: red; font-size: 24px;">Hello World!</div><div id="test" style="color: red; font-size: 24px;">Hello World!</div>';
const json = htmlElementToJson(doc.body, {styles: true});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Duplicate id attributes in HTML elements

Both div elements have the same id="test", which violates HTML standards as id attributes should be unique within a document. This could lead to unexpected behavior during DOM manipulation.

Apply this diff to assign unique id values:

-	doc.body.innerHTML = '<div id="test" style="color: red; font-size: 24px;">Hello World!</div><div id="test" style="color: red; font-size: 24px;">Hello World!</div>';
+	doc.body.innerHTML = '<div id="test1" style="color: red; font-size: 24px;">Hello World!</div><div id="test2" style="color: red; font-size: 24px;">Hello World!</div>';
📝 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
doc.body.innerHTML = '<div id="test" style="color: red; font-size: 24px;">Hello World!</div><div id="test" style="color: red; font-size: 24px;">Hello World!</div>';
const json = htmlElementToJson(doc.body, {styles: true});
doc.body.innerHTML = '<div id="test1" style="color: red; font-size: 24px;">Hello World!</div><div id="test2" style="color: red; font-size: 24px;">Hello World!</div>';
const json = htmlElementToJson(doc.body, {styles: true});

Comment on lines +335 to +350
it('should convert a simple HTML element to JSON', async () => {
doc.body.innerHTML = '<div id="test" class="example">Hello World!</div>';
const json = htmlElementToJson(doc.body);

expect(json).toEqual([
{
tag: 'div',
visible: false,
attributes: {
id: 'test',
class: 'example',
},
text: 'Hello World!',
},
]);
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Unnecessary 'async' keyword in test function declaration

The test function is declared as async, but it does not use the await keyword inside. Consider removing async for clarity.

Apply this diff to remove the async keyword:

-	it('should convert a simple HTML element to JSON', async () => {
+	it('should convert a simple HTML element to JSON', () => {
📝 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
it('should convert a simple HTML element to JSON', async () => {
doc.body.innerHTML = '<div id="test" class="example">Hello World!</div>';
const json = htmlElementToJson(doc.body);
expect(json).toEqual([
{
tag: 'div',
visible: false,
attributes: {
id: 'test',
class: 'example',
},
text: 'Hello World!',
},
]);
});
it('should convert a simple HTML element to JSON', () => {
doc.body.innerHTML = '<div id="test" class="example">Hello World!</div>';
const json = htmlElementToJson(doc.body);
expect(json).toEqual([
{
tag: 'div',
visible: false,
attributes: {
id: 'test',
class: 'example',
},
text: 'Hello World!',
},
]);
});

Comment on lines +352 to +379
it('should handle nested HTML elements', async () => {
doc.body.innerHTML = '<div id="test"><p>Hello</p><span>World!</span></div>';
const json = htmlElementToJson(doc.body);

expect(json).toEqual([
{
tag: 'div',
visible: false,
attributes: {
id: 'test',
},
children: [
{
attributes: {},
tag: 'p',
visible: false,
text: 'Hello',
},
{
attributes: {},
tag: 'span',
visible: false,
text: 'World!',
},
],
},
]);
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Unnecessary 'async' keyword in test function declaration

Similar to the previous test, this function does not use await. Removing async improves readability.

Apply this diff:

-	it('should handle nested HTML elements', async () => {
+	it('should handle nested HTML elements', () => {
📝 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
it('should handle nested HTML elements', async () => {
doc.body.innerHTML = '<div id="test"><p>Hello</p><span>World!</span></div>';
const json = htmlElementToJson(doc.body);
expect(json).toEqual([
{
tag: 'div',
visible: false,
attributes: {
id: 'test',
},
children: [
{
attributes: {},
tag: 'p',
visible: false,
text: 'Hello',
},
{
attributes: {},
tag: 'span',
visible: false,
text: 'World!',
},
],
},
]);
});
it('should handle nested HTML elements', () => {
doc.body.innerHTML = '<div id="test"><p>Hello</p><span>World!</span></div>';
const json = htmlElementToJson(doc.body);
expect(json).toEqual([
{
tag: 'div',
visible: false,
attributes: {
id: 'test',
},
children: [
{
attributes: {},
tag: 'p',
visible: false,
text: 'Hello',
},
{
attributes: {},
tag: 'span',
visible: false,
text: 'World!',
},
],
},
]);
});

Comment on lines +381 to +403
it('should export styles when the option is set', async () => {
doc.body.innerHTML = '<div id="test" style="color: red; font-size: 24px;">Hello World!</div>';
const json = htmlElementToJson(doc.body, {styles: true});

expect(json).toEqual([
{
tag: 'div',
visible: false,
attributes: {
class: 'mocksi-1',
id: 'test',
style: 'color: red; font-size: 24px;',
},
text: 'Hello World!',
},
{
attributes: {},
tag: "style",
text: ".mocksi-1 { display: block; color: rgb(255, 0, 0); font-size: 24px; visibility: visible; pointer-events: auto; background-color: rgba(0, 0, 0, 0); border-block-start-color: rgb(255, 0, 0); border-block-end-color: rgb(255, 0, 0); border-inline-start-color: rgb(255, 0, 0); border-inline-end-color: rgb(255, 0, 0); border-top-color: rgb(255, 0, 0); border-right-color: rgb(255, 0, 0); border-bottom-color: rgb(255, 0, 0); border-left-color: rgb(255, 0, 0); caret-color: auto }",
visible: false
}
]);
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Unnecessary 'async' keyword in test function declaration

The async keyword is unnecessary here as well.

Apply this diff:

-	it('should export styles when the option is set', async () => {
+	it('should export styles when the option is set', () => {
📝 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
it('should export styles when the option is set', async () => {
doc.body.innerHTML = '<div id="test" style="color: red; font-size: 24px;">Hello World!</div>';
const json = htmlElementToJson(doc.body, {styles: true});
expect(json).toEqual([
{
tag: 'div',
visible: false,
attributes: {
class: 'mocksi-1',
id: 'test',
style: 'color: red; font-size: 24px;',
},
text: 'Hello World!',
},
{
attributes: {},
tag: "style",
text: ".mocksi-1 { display: block; color: rgb(255, 0, 0); font-size: 24px; visibility: visible; pointer-events: auto; background-color: rgba(0, 0, 0, 0); border-block-start-color: rgb(255, 0, 0); border-block-end-color: rgb(255, 0, 0); border-inline-start-color: rgb(255, 0, 0); border-inline-end-color: rgb(255, 0, 0); border-top-color: rgb(255, 0, 0); border-right-color: rgb(255, 0, 0); border-bottom-color: rgb(255, 0, 0); border-left-color: rgb(255, 0, 0); caret-color: auto }",
visible: false
}
]);
});
it('should export styles when the option is set', () => {
doc.body.innerHTML = '<div id="test" style="color: red; font-size: 24px;">Hello World!</div>';
const json = htmlElementToJson(doc.body, {styles: true});
expect(json).toEqual([
{
tag: 'div',
visible: false,
attributes: {
class: 'mocksi-1',
id: 'test',
style: 'color: red; font-size: 24px;',
},
text: 'Hello World!',
},
{
attributes: {},
tag: "style",
text: ".mocksi-1 { display: block; color: rgb(255, 0, 0); font-size: 24px; visibility: visible; pointer-events: auto; background-color: rgba(0, 0, 0, 0); border-block-start-color: rgb(255, 0, 0); border-block-end-color: rgb(255, 0, 0); border-inline-start-color: rgb(255, 0, 0); border-inline-end-color: rgb(255, 0, 0); border-top-color: rgb(255, 0, 0); border-right-color: rgb(255, 0, 0); border-bottom-color: rgb(255, 0, 0); border-left-color: rgb(255, 0, 0); caret-color: auto }",
visible: false
}
]);
});

Comment on lines +405 to +437
it('should consolidate styles when they are the same', async () => {
doc.body.innerHTML = '<div id="test" style="color: red; font-size: 24px;">Hello World!</div><div id="test" style="color: red; font-size: 24px;">Hello World!</div>';
const json = htmlElementToJson(doc.body, {styles: true});

expect(json).toEqual([
{
tag: 'div',
visible: false,
attributes: {
class: 'mocksi-1',
id: 'test',
style: 'color: red; font-size: 24px;',
},
text: 'Hello World!',
},
{
tag: 'div',
visible: false,
attributes: {
class: 'mocksi-1',
id: 'test',
style: 'color: red; font-size: 24px;',
},
text: 'Hello World!',
},
{
attributes: {},
tag: "style",
text: ".mocksi-1 { display: block; color: rgb(255, 0, 0); font-size: 24px; visibility: visible; pointer-events: auto; background-color: rgba(0, 0, 0, 0); border-block-start-color: rgb(255, 0, 0); border-block-end-color: rgb(255, 0, 0); border-inline-start-color: rgb(255, 0, 0); border-inline-end-color: rgb(255, 0, 0); border-top-color: rgb(255, 0, 0); border-right-color: rgb(255, 0, 0); border-bottom-color: rgb(255, 0, 0); border-left-color: rgb(255, 0, 0); caret-color: auto }",
visible: false
}
]);
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Unnecessary 'async' keyword in test function declaration

Again, remove async since there's no await used in the function.

Apply this diff:

-	it('should consolidate styles when they are the same', async () => {
+	it('should consolidate styles when they are the same', () => {
📝 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
it('should consolidate styles when they are the same', async () => {
doc.body.innerHTML = '<div id="test" style="color: red; font-size: 24px;">Hello World!</div><div id="test" style="color: red; font-size: 24px;">Hello World!</div>';
const json = htmlElementToJson(doc.body, {styles: true});
expect(json).toEqual([
{
tag: 'div',
visible: false,
attributes: {
class: 'mocksi-1',
id: 'test',
style: 'color: red; font-size: 24px;',
},
text: 'Hello World!',
},
{
tag: 'div',
visible: false,
attributes: {
class: 'mocksi-1',
id: 'test',
style: 'color: red; font-size: 24px;',
},
text: 'Hello World!',
},
{
attributes: {},
tag: "style",
text: ".mocksi-1 { display: block; color: rgb(255, 0, 0); font-size: 24px; visibility: visible; pointer-events: auto; background-color: rgba(0, 0, 0, 0); border-block-start-color: rgb(255, 0, 0); border-block-end-color: rgb(255, 0, 0); border-inline-start-color: rgb(255, 0, 0); border-inline-end-color: rgb(255, 0, 0); border-top-color: rgb(255, 0, 0); border-right-color: rgb(255, 0, 0); border-bottom-color: rgb(255, 0, 0); border-left-color: rgb(255, 0, 0); caret-color: auto }",
visible: false
}
]);
});
it('should consolidate styles when they are the same', () => {
doc.body.innerHTML = '<div id="test" style="color: red; font-size: 24px;">Hello World!</div><div id="test" style="color: red; font-size: 24px;">Hello World!</div>';
const json = htmlElementToJson(doc.body, {styles: true});
expect(json).toEqual([
{
tag: 'div',
visible: false,
attributes: {
class: 'mocksi-1',
id: 'test',
style: 'color: red; font-size: 24px;',
},
text: 'Hello World!',
},
{
tag: 'div',
visible: false,
attributes: {
class: 'mocksi-1',
id: 'test',
style: 'color: red; font-size: 24px;',
},
text: 'Hello World!',
},
{
attributes: {},
tag: "style",
text: ".mocksi-1 { display: block; color: rgb(255, 0, 0); font-size: 24px; visibility: visible; pointer-events: auto; background-color: rgba(0, 0, 0, 0); border-block-start-color: rgb(255, 0, 0); border-block-end-color: rgb(255, 0, 0); border-inline-start-color: rgb(255, 0, 0); border-inline-end-color: rgb(255, 0, 0); border-top-color: rgb(255, 0, 0); border-right-color: rgb(255, 0, 0); border-bottom-color: rgb(255, 0, 0); border-left-color: rgb(255, 0, 0); caret-color: auto }",
visible: false
}
]);
});

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.

I'm not sure how relevant the Rabbit suggestions are this time, so I'm just going to ignore them for now. Feel free to merge!

@jonathankap jonathankap merged commit 7ad3812 into main Sep 25, 2024
2 checks passed
@jonathankap jonathankap deleted the MOC-294_flag_for_recording_styles branch September 25, 2024 17:40
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.

2 participants