payload icon indicating copy to clipboard operation
payload copied to clipboard

Lexical to Markdown converter strips out uploaded Image elements

Open pranavks opened this issue 1 year ago • 9 comments

Describe the Bug

Converting Lexical to Markdown using the instructions strips out uploaded Image elements.

Block elements also get stripped out but they get a replacement text 'Block Field' in the markdown which was helpful in injecting them back based on our needs.

But for uploaded images, there is nothing in the markdown. Not even a replacement text.

Desired solution: Output the markdown images in markdown image syntax.

Link to the code that reproduces this issue

https://github.com/pranavks/payload-lexical-markdown-converter-bug-reproduction/tree/main/app/(payload)/api/convert-lexical-to-markdown

Reproduction Steps

Reproduction link includes a simple route handler that does the Lexical to Markdown conversion.

  1. Send the stringified Lexical data as request body to the POST request.
  2. Observe the returned converted markdown. There is no trace of images.

Which area(s) are affected? (Select all that apply)

plugin: richtext-lexical

Environment Info

Binaries:
  Node: 22.13.0
  npm: 10.9.2
  Yarn: 1.22.19
  pnpm: 9.15.1
Relevant Packages:
  payload: 3.33.0
  next: 15.1.4
  @payloadcms/db-postgres: 3.33.0
  @payloadcms/graphql: 3.33.0
  @payloadcms/live-preview: 3.33.0
  @payloadcms/live-preview-react: 3.33.0
  @payloadcms/next/utilities: 3.33.0
  @payloadcms/plugin-cloud-storage: 3.33.0
  @payloadcms/plugin-redirects: 3.33.0
  @payloadcms/plugin-search: 3.33.0
  @payloadcms/plugin-seo: 3.33.0
  @payloadcms/richtext-lexical: 3.33.0
  @payloadcms/storage-s3: 3.33.0
  @payloadcms/translations: 3.33.0
  @payloadcms/ui/shared: 3.33.0
  react: 19.1.0
  react-dom: 19.1.0
Operating System:
  Platform: darwin
  Arch: x64
  Version: Darwin Kernel Version 24.3.0: Thu Jan  2 20:24:24 PST 2025; root:xnu-11215.81.4~3/RELEASE_ARM64_T6030
  Available memory (MB): 18432
  Available CPU cores: 11

pranavks avatar Jul 08 '25 10:07 pranavks

Same. Since there is no ready-made Vue component for displaying Lexical content (similar to the React component included in the plugin), I have to use a Markdown converter for my Nuxt 4 project. However, the convertLexicalToMarkdown function either doesn't support or incorrectly converts the standard "upload" field for richText components. The output is empty.

Image

lollipoh avatar Aug 03 '25 20:08 lollipoh

Same here! My version is 3.49.1

@vladpro3 I'm using the same API to render in my Nuxt 3 project! Do you find some way to fix this? I need to render my blog posts!

Tks

patrickalima98 avatar Aug 06 '25 18:08 patrickalima98

Edit: This issue is the same #12425

patrickalima98 avatar Aug 06 '25 18:08 patrickalima98

Same here! My version is 3.49.1

@vladpro3 I'm using the same API to render in my Nuxt 3 project! Do you find some way to fix this? I need to render my blog posts!

Tks

I’ve found two temporary solutions. The first is to use not recommended method with the HTML field (https://payloadcms.com/docs/rich-text/converting-html#html-field). The second is to manually convert to HTML using convertLexicalToHTML (https://payloadcms.com/docs/rich-text/converting-html#on-demand).

I don’t like either option, since they involve directly injecting HTML via v-html in Nuxt, but at least they work, unlike converting to Markdown.

lollipoh avatar Aug 09 '25 20:08 lollipoh

Hey @vladpro3 After some days I've found the Markdown Tranformers that can be used for what We need, it's working great for me and my Nuxt 3 project.

https://payloadcms.com/docs/rich-text/custom-features#server-feature-markdown-transformers

You can find the details in my markdown field.

import type { CollectionConfig, RichTextField } from 'payload';
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical';
import {
  convertLexicalToMarkdown,
  editorConfigFactory,
  createServerFeature,
} from '@payloadcms/richtext-lexical'
import type { ElementTransformer } from '@payloadcms/richtext-lexical/lexical/markdown'
import { v4 as uuidv4 } from 'uuid';
import { slug } from '@/fields/slug';
import { UploadServerNode } from '@payloadcms/richtext-lexical';
import { $isUploadServerNode } from 'node_modules/@payloadcms/richtext-lexical/dist/features/upload/server/nodes/UploadNode';
import { Media } from '@/payload-types';


const MarkdownTransformerWithUpload: ElementTransformer = {
  type: 'element',
  dependencies: [UploadServerNode],
  export: (node, _exportChildren) => {
    if (!$isUploadServerNode(node)) {
      return null
    }
    const { value, fields } = node.__data
    if (typeof value !== 'string') {
      return null
    }

    return `![${fields.alt}](${process.env.PAYLOAD_PUBLIC_BACKEND_URL}${fields.url} "${fields.alt}")`
  },
  regExp: /^media upload id:[0-9a-f]{24}\s/,
  replace: (_parentNode, _children, _match, _isImport) => {
    // TODO: Implement replace if deemed necessary
  },
}


export const MarkdownUploadFieldFeature = createServerFeature({
  feature: {
    markdownTransformers: [MarkdownTransformerWithUpload],

  },
  key: 'markdownUploadFieldFeature',
})


export const supportArticles: CollectionConfig = {
  slug: 'supportArticles',
  versions: true,
  access: {
    read: () => true,
  },
  labels: {
    plural: {
      en: 'Articles',
      pt: 'Artigos',
    }
  },
  admin: {
    group: "helpAndSupport",
    useAsTitle: 'title',
  },
  fields: [
    {
      name: 'id', 
      required: false,
      type: 'text',
      defaultValue: () => uuidv4(),
    },
    {
      name: 'title',
      type: 'text',
      required: true,
      localized: true
    },
    {
      name: 'tags',
      type: 'array',
      fields: [
        {
          name: 'value',
          type: 'text',
        }
      ],
      required: true,
      localized: true
    },
    slug({ trackingField: 'title' }, { localized: true }),
    {
      name: 'description',
      type: 'textarea',
      required: true,
      localized: true
    },
    {
      name: 'product', 
      required: true,
      relationTo: 'products',
      type: 'relationship',
    },
    {
      name: 'section',
      type: 'relationship',
      relationTo: 'supportSections',
      required: true,
    },
    {
      name: 'content',
      type: 'richText',
      localized: true,
    },
    {
      name: 'markdown',
      type: 'textarea',
      admin: {
        hidden: true,
      },
      hooks: {
        afterRead: [
          async ({ siblingData, siblingFields, req }) => {
            const data: SerializedEditorState =
              siblingData['content']

            if (!data) {
              return ''
            }

            const updatedData = data?.root?.children as Array<any> || [];
            
            // Get all upload fields to find in database
            const findIndex = updatedData.findIndex((item) => {
              return item.type === "upload";
            });

            // Get all upload ids to use in a unique query
            const uploadNodesIds = updatedData
              .filter((item) => item.type === "upload")
              .map((item) => item.value);

            const mediaFields = await req.payload.find({
              collection: "media",
              depth: 3,
              where: {
                or: [
                  {
                    id: {
                      in: uploadNodesIds
                    }
                  }
                ]
              },
              locale: req.locale
            });

            const mappedMediaFieldsKv = mediaFields.docs.reduce((acc, mediaField) => {
              acc[mediaField.id] = mediaField;
              return acc;
            }, {} as Record<string, Media>);

            data.root.children = updatedData.map((i) => {
              if (i.value in mappedMediaFieldsKv && i.type === "upload") {
                return {
                  ...i,
                  fields: mappedMediaFieldsKv[i.value]
                }
              }

              return i;
            });
            
            const markdown = convertLexicalToMarkdown({
              data,
              editorConfig: (() => {
                const a = editorConfigFactory.fromField({
                  field: siblingFields.find(
                    (field) =>
                      'name' in field && field.name === 'content',
                  ) as RichTextField,
                });

                a.features.markdownTransformers.push(MarkdownTransformerWithUpload);

                return a;
              })(),
            })

            return markdown
          },
        ],
        beforeChange: [
          ({ siblingData }) => {
            // Ensure that the markdown field is not saved in the database
            delete siblingData['markdown']
            return null
          },
        ],
      },
    },
  ],
}

patrickalima98 avatar Aug 11 '25 16:08 patrickalima98

Just ran into the same issue.

Following the pattern of the other Lexical editor components, it looks like the Upload component does not have a markdown transformer.

Heading example: https://github.com/payloadcms/payload/blob/main/packages/richtext-lexical/src/features/heading/markdownTransformer.ts

MichielDeMey avatar Sep 29 '25 21:09 MichielDeMey

I've investigated this issue and found the root cause.

Root Cause

The UploadFeature in @payloadcms/richtext-lexical doesn't have a markdown transformer registered. Looking at the code:

packages/richtext-lexical/src/features/upload/server/index.ts:

  • Has HTML converters (lines 136-236) for converting to <img>, <a>, and <picture> tags ✅
  • Has JSX converters ✅
  • No markdown transformer ❌

When convertLexicalToMarkdown is called, it uses $convertToMarkdownString(editorConfig?.features?.markdownTransformers). Since the Upload feature doesn't register any markdown transformer, upload nodes are silently skipped during conversion.

Comparison with Other Features

Other features like LinkFeature have proper markdown transformers:

// packages/richtext-lexical/src/features/link/markdownTransformer.ts
export const LinkMarkdownTransformer: TextMatchTransformer = {
  type: 'text-match',
  dependencies: [LinkNode],
  export: (_node, exportChildren) => {
    if (!$isLinkNode(_node)) {
      return null
    }
    const { url } = node.getFields()
    const textContent = exportChildren(node)
    return `[${textContent}](${url})`
  },
  // ... import logic
}

Solution

Add a markdown transformer for the Upload feature that:

  1. Exports images as ![alt](url) format
  2. Exports non-image uploads as [filename](url) links

I have a fix ready and will open a PR shortly.

RajeshKumar11 avatar Jan 19 '26 17:01 RajeshKumar11

This issue has been automatically locked. Please open a new issue if this issue persists with any additional detail.

github-actions[bot] avatar Feb 27 '26 05:02 github-actions[bot]

🚀 This is included in version v3.78.0

github-actions[bot] avatar Feb 27 '26 20:02 github-actions[bot]