Skip to content

feat: render images in RichText via a custom Lexical image node - #3448

Merged
lemagnetic merged 6 commits into
devfrom
feat/rich-text-embed-images
Oct 8, 2026
Merged

lemagnetic merged 6 commits into
devfrom
feat/rich-text-embed-images

Conversation

@carolvalenca

@carolvalenca carolvalenca commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

What's the purpose of this pull request?

This pull request introduces support for custom image nodes in the rich text editor, allowing images with alignment and width options to be rendered and styled consistently. The main changes include the implementation of a new RichTextImageNode for image handling, its integration into the editor pipeline, and corresponding styling updates.

Rich Text Image Node Implementation and Integration:

  • Added the new RichTextImageNode class to RichTextImageNode.ts, supporting image source, alt text, alignment (left, center, right), and width percentage, with logic for exporting to and importing from JSON and DOM, and automatic image resizing for VTEX assets.
  • Registered RichTextImageNode in the lexicalToHtml function, enabling the rich text editor to recognize and handle image nodes.
  • Imported RichTextImageNode into RichText.tsx to ensure it is available for use in the editor.

Styling Enhancements:

  • Updated styles.scss to add styles for [data-fs-rich-text-image-wrapper], ensuring images are displayed with correct alignment and responsive sizing according to their alignment and width settings.

How it works?

An image inserted via Content Platform's RichTextWidget gets serialized as a Lexical image node (src, altText, alignment, widthPercent) inside the rich text field's content. RichText's headless Lexical editor didn't recognize that node type, so images were dropped or broke parsing.

Added RichTextImageNode, registered in lexicalToHtml(), to close that gap: it parses the node (sanitizing alignment/widthPercent, capping width at 100%) and renders it to <div data-fs-rich-text-image-wrapper> + <img data-fs-rich-text-image loading="lazy">. VTEX file-manager URLs get resized via query params (same convention as faststoreLoader). A missing/invalid src makes the node skip itself instead of breaking the block. Styling was added to @faststore/ui's RichText/styles.scss.

(Check this PR to get more context)

How to test it?

This should be tested using Content Platform as content source. It can be tested using the Newsletter component. Simply set up a store that uses the code from this PR on CP and create a new entry with the Newsletter component. The preview feature can then be used to test the rendering of the Newsletter rich text.

Checklist

PR Title and Commit Messages

  • PR title and commit messages follow the Conventional Commits specification
    • Available prefixes: feat, fix, chore, docs, style, refactor, ci and test

PR Description

  • Added a label according to the PR goal - breaking change, bug, contributing, performance, documentation..

Dependencies

  • Committed the pnpm-lock.yaml file when there were changes to the packages

Documentation

  • PR description
  • For documentation changes, ping @Mariana-Caetano to review and update (Or submit a doc request)

Summary by CodeRabbit

  • New Features
    • Rich-text content can display images alongside text, with left, center, or right alignment and responsive widths.
    • Images support alternative text, optimized loading, and external image URLs.
    • The Rich Text component is available through the core package.
    • Newsletter privacy policy fields use the updated rich-text editor.
  • Bug Fixes
    • Missing or malformed image data no longer disrupts rich-text rendering.

@carolvalenca
carolvalenca requested a review from a team as a code owner August 12, 2026 17:59
@carolvalenca
carolvalenca requested review from eduardoformiga and renatomaurovtex and removed request for a team August 12, 2026 17:59
@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: vtex/faststore/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 73ebe6e0-8cd3-4a9a-859e-67c5933fce68
📥 Commits

Reviewing files that changed from the base of the PR and between 0d700bb and cc9b304.

📒 Files selected for processing (3)
  • packages/core/cms/faststore/components/cms_component__bannernewsletter.jsonc
  • packages/core/cms/faststore/components/cms_component__newsletter.jsonc
  • packages/core/index.ts

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review.


Walkthrough

RichText now processes Lexical image nodes. The node validates and serializes image metadata, transforms supported VTEX URLs, and exports responsive HTML with alignment metadata. The change also updates rich-text styles, public exports, newsletter privacy-policy widget settings, and browser tests.

Changes

Rich-text image support

Layer / File(s) Summary
Image node contract and serialization
packages/core/src/components/ui/RichText/RichTextImageNode.ts
Adds image alignment and serialized-node types. The node validates image metadata, preserves state when cloned, and implements JSON serialization and Lexical lifecycle methods.
Lexical registration and image rendering
packages/core/src/components/ui/RichText/RichText.tsx, packages/core/src/components/ui/RichText/RichTextImageNode.ts, packages/ui/src/components/atoms/RichText/styles.scss, packages/core/index.ts, packages/core/cms/faststore/components/cms_component__*.jsonc
Registers the image node, exports responsive image HTML, applies supported VTEX URL parameters, and adds alignment styles. The core package re-exports RichText and RichTextProps. Newsletter privacy-policy fields use the draftjs-rich-text-v2 widget.
Browser rendering validation
packages/core/test/components/ui/RichText/RichText.browser.test.tsx
Tests image rendering and ordering, invalid image handling, alignment and width defaults, width clamping, URL passthrough, and existing content formats.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant RichText
  participant HeadlessLexicalEditor
  participant RichTextImageNode
  participant BrowserDOM
  RichText->>HeadlessLexicalEditor: register RichTextImageNode
  HeadlessLexicalEditor->>RichTextImageNode: process serialized image data
  RichTextImageNode->>RichTextImageNode: validate metadata and transform supported VTEX URL
  RichTextImageNode-->>RichText: export responsive image HTML
  RichText->>BrowserDOM: render HTML with alignment wrapper
Loading

Merge Risk: ⚪ Minimal · up to cc9b3

The previously reported test-loading issue has been corrected, and no actionable merge-blocking risk remains after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to cc9b3

The image implementation uses DOM properties rather than interpolated markup, and the existing HTML-rendering behavior is preserved. No introduced exploitable path is established. However, content-author permissions, validation by external callers, and editor-to-renderer compatibility are not fully confirmed.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — Image content can cause visitor browsers to load the supplied URL on pages using this renderer. The reviewed converter emits an image element rather than fetching its source server-side. Maximum affected storefront scope depends on publishing authority and caller reuse, neither of which is established by the available evidence.

Trust Boundaries and Controls

  • observed — Raw HTML acceptance and direct HTML rendering predate this PR. The public core export exposes that existing contract through a new package entrypoint, but no production caller with attacker-controlled input is established. DOM construction limits image attribute-markup injection; it does not establish the trustworthiness of authored URLs or arbitrary raw HTML.

Hardening Proposals

  • proposed — Document the public component's trusted-content requirement. If lower-trust authors or arbitrary external content are supported, define where raw HTML sanitization and image-origin policy are enforced, and validate that policy at the publishing or rendering boundary. This is conditional hardening, not an observed missing production control.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 3 files. (2 skipped: 2… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the primary change: rendering RichText images through a custom Lexical image node.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 3 files. (2 skipped: 2 unsupported.)

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

Comment @coderabbitai help to get the list of available commands.

@codesandbox-ci

codesandbox-ci Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/components/ui/RichText/RichTextImageNode.ts`:
- Around line 37-40: Update resolveWidthPercent so it accepts only finite,
positive numeric width values; reject Infinity, -Infinity, and NaN before
returning the value, while preserving DEFAULT_WIDTH_PERCENT for invalid inputs.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 1db129b2-2d82-4b71-a422-0b302abe1cb1

📥 Commits

Reviewing files that changed from the base of the PR and between 17d1209 and 2c8459e.

📒 Files selected for processing (3)
  • packages/core/src/components/ui/RichText/RichText.tsx
  • packages/core/src/components/ui/RichText/RichTextImageNode.ts
  • packages/ui/src/components/atoms/RichText/styles.scss

@pkg-pr-new

pkg-pr-new Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

npm i https://pkg.pr.new/vtex/faststore/@faststore/api@dca80dd

@faststore/cli

npm i https://pkg.pr.new/vtex/faststore/@faststore/cli@dca80dd

@faststore/components

npm i https://pkg.pr.new/vtex/faststore/@faststore/components@dca80dd

@faststore/core

npm i https://pkg.pr.new/vtex/faststore/@faststore/core@dca80dd

@faststore/diagnostics

npm i https://pkg.pr.new/vtex/faststore/@faststore/diagnostics@dca80dd

@faststore/lighthouse

npm i https://pkg.pr.new/vtex/faststore/@faststore/lighthouse@dca80dd

@faststore/sdk

npm i https://pkg.pr.new/vtex/faststore/@faststore/sdk@dca80dd

@faststore/ui

npm i https://pkg.pr.new/vtex/faststore/@faststore/ui@dca80dd

commit: dca80dd

@carolvalenca carolvalenca added the enhancement New feature or request label Aug 12, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/test/components/ui/RichText/RichText.test.tsx`:
- Around line 8-12: Hoist isContentPlatformSourceMock with vi.hoisted before the
vi.mock factory uses it, preserving the existing mock behavior. Rename the test
file from RichText.test.tsx to RichText.browser.test.tsx so it is collected by
the browser project instead of the node project.

Apply the same fix in
`@packages/core/test/components/ui/RichText/RichText.test.tsx` around lines 1 - 3.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: acf386cc-3ea9-4d43-86b5-e06088ccdc2f

📥 Commits

Reviewing files that changed from the base of the PR and between d49fd8a and a561416.

📒 Files selected for processing (2)
  • packages/core/src/components/ui/RichText/RichTextImageNode.ts
  • packages/core/test/components/ui/RichText/RichText.test.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/components/ui/RichText/RichTextImageNode.ts

const VALID_ALIGNMENTS = new Set<ImageAlignment>(['left', 'center', 'right'])
const DEFAULT_ALIGNMENT: ImageAlignment = 'left'
const DEFAULT_WIDTH_PERCENT = 100
const RICH_TEXT_CONTENT_MAX_WIDTH = 720

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

deu pra testar no Newsletter em desktop? queria saber de onde vem esse 720 e se a imagem ficou nítida

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

o RICH_TEXT_CONTENT_MAX_WIDTH serve para melhorar a performance do componente, é um valor base que garante que arquivos pesados nao sejam baixados por inteiro
a imagem ficou nitida sim, mas podemos excluir essa constante se fizer mais sentido

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

não precisamos remover, o teto faz sentido, eu só queria entender esse valor base, não dá para saber se o teto está baixo demais para tela retina ou alto demais para o Newsletter

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

eu concordo! o que tu acha que deveria ser feito nesse caso?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

eu tentei validar o RichText no componente de Newsletter na conta brandless pra ver como ficava a imagem, mas não consegui por causa do problema que comentei no slack, o schema desse componente nativo não usa o draftjs-rich-text-v2. O teste iria validar se o 720 estava ok como base.

@lemagnetic lemagnetic left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@lemagnetic
lemagnetic self-requested a review September 29, 2026 23:12
@sonar-workflows

Copy link
Copy Markdown

const DEFAULT_WIDTH_PERCENT = 100
const RICH_TEXT_CONTENT_MAX_WIDTH = 720
const DEFAULT_IMAGE_QUALITY = 8

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[Functional.Logic] 🟡 RESTRICT

DEFAULT_IMAGE_QUALITY is set to 8, which on a 0-100 quality scale produces heavily compressed, visibly degraded images for every rich-text image rendered through the VTEX resize pipeline. The included test merely asserts this value rather than a sane one, so it would not be caught by CI.

Action: Verify the intended quality value with design/content stakeholders — likely should be 80 — and update DEFAULT_IMAGE_QUALITY plus the corresponding test assertion.

To dismiss: reply /dk-review dismiss [reason] under this comment


function withVtexResizeParams(src: string, widthPercent: number): string {
if (!src.includes('vtexassets') || !src.includes('/assets')) {
return src

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[Functional.Check] 🟡 RESTRICT

withVtexResizeParams decides whether to treat a URL as a VTEX asset by checking if the full URL string contains the substrings 'vtexassets' and '/assets' anywhere, instead of validating the actual hostname. A URL such as https://evil.example.com/path?ref=vtexassets/assets/x.png would pass both checks even though the host isn't a VTEX asset CDN.

Action: Parse the URL and validate url.hostname (e.g. ends with .vtexassets.com) rather than doing substring checks on the raw string.

To dismiss: reply /dk-review dismiss [reason] under this comment

@dk-pr-review

dk-pr-review Bot commented Oct 8, 2026

Copy link
Copy Markdown

DK Review — Audit Summary

Verdict: ⚠️ RESTRICTED

Severity Count
BLOCK 0
RESTRICT 2
SUGGEST 2

Only BLOCK and RESTRICT findings anchored to a changed line are commented inline on the diff. The other 2 findings below open no review thread.

Scenarios evaluated: feature-flags, general-review
Scenarios skipped: dependency-governance (no matching files), pipeline-config (no matching files), agent-skills-review (no matching files), quality-ratchet (no matching files)

⚠️ Governance warnings: Large PR detected (7 files) — review coverage may be incomplete


📋 Findings (4)

RESTRICT

  1. [Functional.Logic] packages/core/src/components/ui/RichText/RichTextImageNode.ts:29 — DEFAULT_IMAGE_QUALITY is set to 8, which on a 0-100 quality scale produces heavily compressed, visibly degraded images for every rich-text image rendered through the VTEX resize pipeline. The included test merely asserts this value rather than a sane one, so it would not be caught by CI.
    → Verify the intended quality value with design/content stakeholders — likely should be 80 — and update DEFAULT_IMAGE_QUALITY plus the corresponding test assertion.
  2. [Functional.Check] packages/core/src/components/ui/RichText/RichTextImageNode.ts:46 — withVtexResizeParams decides whether to treat a URL as a VTEX asset by checking if the full URL string contains the substrings 'vtexassets' and '/assets' anywhere, instead of validating the actual hostname. A URL such as https://evil.example.com/path?ref=vtexassets/assets/x.png would pass both checks even though the host isn't a VTEX asset CDN.
    → Parse the URL and validate url.hostname (e.g. ends with .vtexassets.com) rather than doing substring checks on the raw string.

SUGGEST

  1. [Functional.Check] packages/core/src/components/ui/RichText/RichTextImageNode.ts:38 — resolveWidthPercent only rejects non-number and <=0 values, but typeof NaN === 'number' and NaN <= 0 is false, so a NaN widthPercent falls through to Math.min(NaN, 100), which is itself NaN — producing an invalid style="width: NaN%;" on export.
    → Use Number.isFinite(widthPercent) instead of typeof widthPercent !== 'number' before clamping.
  2. [Evolvability.SolutionApproach] packages/core/src/components/ui/RichText/RichTextImageNode.ts:28 — RICH_TEXT_CONTENT_MAX_WIDTH = 720 bakes a specific container pixel width into the Lexical node's resize-URL logic, coupling a presentation/layout concern to the content-model layer. If the container's max width changes in CSS/theme, resized image URLs will request the wrong pixel width with no obvious link back to this constant.
    → Source this value from a shared layout/token constant (or make it configurable) instead of duplicating it as a local magic number in the node class.

DK Review v1.0.0 | To dismiss a finding: reply /dk-review dismiss [reason] under its comment

@lemagnetic
lemagnetic merged commit a7c85b8 into dev Oct 8, 2026
15 of 16 checks passed
@eduardoformiga
eduardoformiga deleted the feat/rich-text-embed-images branch October 9, 2026 17:12
@eduardoformiga eduardoformiga mentioned this pull request Oct 15, 2026
2 of 7 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants