fix: Parse Saleor JSON description format to plain text
- Add parseDescription() helper to extract text from EditorJS JSON - Update getLocalizedProduct to use parsed description - Fix product descriptions showing raw JSON on frontend
This commit is contained in:
@@ -32,4 +32,5 @@ export {
|
||||
isProductAvailable,
|
||||
formatPrice,
|
||||
getLocalizedProduct,
|
||||
parseDescription,
|
||||
} from "./products";
|
||||
|
||||
@@ -81,6 +81,39 @@ export function formatPrice(amount: number, currency: string = "RSD"): string {
|
||||
}).format(amount);
|
||||
}
|
||||
|
||||
// Parse Saleor's JSON description format (EditorJS) to plain text/HTML
|
||||
export function parseDescription(description: string | null | undefined): string {
|
||||
if (!description) return "";
|
||||
|
||||
// If it's already plain text (not JSON), return as-is
|
||||
if (!description.startsWith("{")) {
|
||||
return description;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(description);
|
||||
|
||||
// Handle EditorJS format: { blocks: [{ data: { text: "..." } }] }
|
||||
if (parsed.blocks && Array.isArray(parsed.blocks)) {
|
||||
return parsed.blocks
|
||||
.map((block: any) => {
|
||||
if (block.data?.text) {
|
||||
return block.data.text;
|
||||
}
|
||||
return "";
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
}
|
||||
|
||||
// Fallback: return stringified if unknown format
|
||||
return description;
|
||||
} catch (e) {
|
||||
// If JSON parse fails, return original
|
||||
return description;
|
||||
}
|
||||
}
|
||||
|
||||
// Get localized product data
|
||||
export function getLocalizedProduct(
|
||||
product: Product,
|
||||
@@ -94,11 +127,13 @@ export function getLocalizedProduct(
|
||||
} {
|
||||
const isEnglish = locale.toLowerCase() === "en";
|
||||
const translation = isEnglish ? product.translation : null;
|
||||
|
||||
const rawDescription = translation?.description || product.description;
|
||||
|
||||
return {
|
||||
name: translation?.name || product.name,
|
||||
slug: translation?.slug || product.slug,
|
||||
description: translation?.description || product.description,
|
||||
description: parseDescription(rawDescription),
|
||||
seoTitle: translation?.seoTitle || product.seoTitle,
|
||||
seoDescription: translation?.seoDescription || product.seoDescription,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user