Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Fix rich text description round-tripping in product forms (#14322)

Damian Legawiec3b2a8625f100
diff --git a/packages/dashboard/CHANGELOG.md b/packages/dashboard/CHANGELOG.md
new file mode 100644
index 0000000000..ac2b8be666
--- /dev/null
+++ b/packages/dashboard/CHANGELOG.md
@@ -0,0 +1,7 @@
+# @spree/dashboard
+
+## 0.10.2
+
+### Patch Changes
+
+- Fix the product edit form collapsing multi-paragraph descriptions on reload. The description editor now hydrates from the API's `description_html` field instead of the tag-stripped plain-text `description`, so paragraphs, line breaks, and inline formatting survive save and reload cycles.
diff --git a/packages/dashboard/e2e/products-edit.spec.ts b/packages/dashboard/e2e/products-edit.spec.ts
index 1762c781ee..618b309cd0 100644
--- a/packages/dashboard/e2e/products-edit.spec.ts
+++ b/packages/dashboard/e2e/products-edit.spec.ts
@@ -1,6 +1,6 @@
import { expect, test } from '@playwright/test'
import { FIXTURE_BULK_CHANNEL_NAME, login } from './helpers'
-import { createProduct, publishingCard } from './products-helpers'
+import { createProduct, publishingCard, typeDescription } from './products-helpers'
test.describe('product edit', () => {
test('creates a product and lands on the edit page', async ({ page }) => {
@@ -13,6 +13,32 @@ test.describe('product edit', () => {
await expect(page.getByLabel(/^name$/i)).toHaveValue(name)
})
+ test('preserves multi-paragraph description formatting across reload', async ({ page }) => {
+ const creds = await login(page)
+ const name = `E2E Product Rich Text ${Date.now()}`
+
+ await createProduct(page, creds.store_id, name)
+
+ // Type two paragraphs on the edit page so the save goes through the
+ // update path (the reported bug scenario), not create.
+ await typeDescription(page, 'First paragraph\nSecond paragraph')
+
+ await page.getByRole('button', { name: /save product/i }).click()
+ await expect(page.getByRole('button', { name: /save product/i })).toBeDisabled({
+ timeout: 15_000,
+ })
+
+ await page.reload()
+
+ // The saved HTML must round-trip as two separate paragraphs. Before the
+ // fix the form hydrated from the tag-stripped, whitespace-squished
+ // plain-text `description`, collapsing both lines into a single block.
+ const description = page.locator('#product-description')
+ await expect(description.locator('p')).toHaveCount(2)
+ await expect(description.locator('p').first()).toHaveText('First paragraph')
+ await expect(description.locator('p').nth(1)).toHaveText('Second paragraph')
+ })
+
test('updates name on an existing product', async ({ page }) => {
const creds = await login(page)
const original = `E2E Product Update ${Date.now()}`
diff --git a/packages/dashboard/e2e/products-helpers.ts b/packages/dashboard/e2e/products-helpers.ts
index 3724d9cfc4..43e4c31e6e 100644
--- a/packages/dashboard/e2e/products-helpers.ts
+++ b/packages/dashboard/e2e/products-helpers.ts
@@ -5,12 +5,21 @@ import { gotoIndex } from './helpers'
export const PRODUCTS_PATH = (storeId: string) => `/${storeId}/products`
export const OPTIONS_PATH = (storeId: string) => `/${storeId}/products/options`
+/**
+ * Focus the product form's description field and type `text`. The field is a
+ * tiptap `RichTextEditor` (contenteditable), not a textarea, so `.fill()` is
+ * wrong; we click to focus and `keyboard.type` instead, which presses Enter
+ * for each `\n` — splitting the text into separate paragraphs.
+ */
+export async function typeDescription(page: Page, text: string): Promise<void> {
+ await page.getByLabel(/^description$/i).click()
+ await page.keyboard.type(text)
+}
+
/**
* Drive the New Product form and land on the edit page. The minimum input the
* form accepts is a name — pass a `description` when the spec specifically
- * verifies how rich-text data round-trips. The description field is a tiptap
- * `RichTextEditor` (contenteditable), not a textarea, so `.fill()` is wrong;
- * we click to focus and `keyboard.type` instead.
+ * verifies how rich-text data round-trips.
*/
export async function createProduct(
page: Page,
@@ -22,11 +31,7 @@ export async function createProduct(
await page.getByRole('button', { name: /add product/i }).click()
await expect(page.getByRole('heading', { name: /^new product$/i })).toBeVisible()
await page.getByLabel(/^name$/i).fill(name)
- if (description) {
- const editor = page.getByLabel(/^description$/i)
- await editor.click()
- await page.keyboard.type(description)
- }
+ if (description) await typeDescription(page, description)
await page.getByRole('button', { name: /^create product$/i }).click()
// Lands on `/$storeId/products/$productId` (not `/new`).
await expect(page).toHaveURL(new RegExp(`/${storeId}/products/prod_[^/]+$`), { timeout: 15_000 })
diff --git a/packages/dashboard/package.json b/packages/dashboard/package.json
index 78f5f990be..77a39a26eb 100644
--- a/packages/dashboard/package.json
+++ b/packages/dashboard/package.json
@@ -1,7 +1,7 @@
{
"name": "@spree/dashboard",
"license": "MIT",
- "version": "0.10.1",
+ "version": "0.10.2",
"description": "Spree Dashboard app shell \u2014 the next-gen React admin for Spree Commerce. Routes, resource hooks, schemas, locales, and the <Dashboard /> component. Source-only package; hosts compile it via @spree/dashboard/vite. Developer Preview.",
"author": "Vendo Connect Inc.",
"homepage": "https://spreecommerce.org",
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx
index ed1a8cee2b..cd7041213b 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx
@@ -132,7 +132,11 @@ function productToFormValues(
return {
name: product.name,
- description: product.description ?? '',
+ // Hydrate the Tiptap editor from the HTML field, not `description` — the
+ // serializer squishes that one to tag-stripped plain text, which would
+ // collapse paragraphs/line breaks on every reload. Write still goes back
+ // through the `description` param (the API accepts HTML there).
+ description: product.description_html ?? '',
status: (product.status as ProductFormValues['status']) ?? 'draft',
category_ids: product.categories?.map((t) => t.id) ?? [],
tags: product.tags ?? [],
diff --git a/spree/api/app/serializers/spree/api/v3/product_serializer.rb b/spree/api/app/serializers/spree/api/v3/product_serializer.rb
index 8494f1ffcd..624a0a6f12 100644
--- a/spree/api/app/serializers/spree/api/v3/product_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/product_serializer.rb
@@ -48,7 +48,7 @@ module Spree
attribute :description do |product|
next if product.description.blank?
- Nokogiri::HTML.fragment(product.description).text.squish
+ Spree::RichTextHelper.to_plain_text(product.description)
end
attribute :description_html do |product|
diff --git a/spree/core/app/helpers/spree/rich_text_helper.rb b/spree/core/app/helpers/spree/rich_text_helper.rb
new file mode 100644
index 0000000000..ea516b68e8
--- /dev/null
+++ b/spree/core/app/helpers/spree/rich_text_helper.rb
@@ -0,0 +1,37 @@
+module Spree
+ # Converts stored rich text HTML (Tiptap output persisted in plain text
+ # columns, e.g. +Spree::Product#description+) into a faithful plain-text
+ # rendering for API +description+/+body+ fields.
+ #
+ # Tiptap serializes blocks with no whitespace between them
+ # (+<p>a</p><p>b</p>+), so a naive tag strip glues adjacent blocks into a
+ # single run ("ab") and loses every paragraph and line break. This maps
+ # block boundaries and +<br>+ to newlines before stripping tags, keeping the
+ # text readable for storefronts, feeds, search indexing, and meta tags.
+ #
+ # Newlines already present in the markup (pretty-printed source from the
+ # legacy admin's TinyMCE code view, imports, seeds) render as a single space
+ # in a browser and are treated the same way here — only +<br>+ and block
+ # boundaries produce line breaks.
+ module RichTextHelper
+ # Closing block tags whose boundaries become line breaks.
+ BLOCK_BOUNDARY = %r{</(?:p|div|li|h[1-6]|blockquote|tr|ul|ol|table|section|article|header|footer|pre)>}i
+
+ # Hard line breaks.
+ LINE_BREAK = %r{<br\s*/?>}i
+
+ # @param html [String, nil] rich text HTML
+ # @return [String] plain text with paragraph and line breaks preserved
+ def self.to_plain_text(html)
+ return '' if html.blank?
+
+ with_breaks = html.gsub(/\s+/, ' ').gsub(LINE_BREAK, "\n").gsub(BLOCK_BOUNDARY, "\\0\n")
+
+ Nokogiri::HTML.fragment(with_breaks).text
+ .gsub(/[^\S\n]+/, ' ') # collapse runs of non-newline whitespace
+ .gsub(/ *\n */, "\n") # trim spaces hugging newlines
+ .gsub(/\n{3,}/, "\n\n") # cap consecutive blank lines
+ .strip
+ end
+ end
+end
diff --git a/spree/core/spec/helpers/spree/rich_text_helper_spec.rb b/spree/core/spec/helpers/spree/rich_text_helper_spec.rb
new file mode 100644
index 0000000000..f808f68162
--- /dev/null
+++ b/spree/core/spec/helpers/spree/rich_text_helper_spec.rb
@@ -0,0 +1,45 @@
+require 'spec_helper'
+
+RSpec.describe Spree::RichTextHelper do
+ describe '.to_plain_text' do
+ subject { described_class.to_plain_text(html) }
+
+ context 'when blank' do
+ let(:html) { nil }
+
+ it { is_expected.to eq('') }
+ end
+
+ context 'with a single paragraph' do
+ let(:html) { '<p>A <strong>comfortable</strong> cotton t-shirt.</p>' }
+
+ it 'strips tags without trailing whitespace' do
+ is_expected.to eq('A comfortable cotton t-shirt.')
+ end
+ end
+
+ context 'with multiple blocks' do
+ let(:html) { '<p>Need to install the following packages:</p><p>[email protected]</p>' }
+
+ it 'separates adjacent blocks with a newline instead of gluing them' do
+ is_expected.to eq("Need to install the following packages:\[email protected]")
+ end
+ end
+
+ context 'with hard line breaks and lists' do
+ let(:html) { '<p>First<br>Second</p><ul><li>One</li><li>Two</li></ul>' }
+
+ it 'preserves line breaks and list item boundaries' do
+ is_expected.to eq("First\nSecond\nOne\nTwo")
+ end
+ end
+
+ context 'with pretty-printed source HTML (legacy TinyMCE, imports)' do
+ let(:html) { "<p>Hello\n world</p>\n<p>Second</p>" }
+
+ it 'renders source newlines as spaces, like a browser' do
+ is_expected.to eq("Hello world\nSecond")
+ end
+ end
+ end
+end