yhatt / jsx-slack

Build JSON object for Slack Block Kit surfaces from JSX
https://jsx-slack.netlify.app/
MIT License
467 stars 16 forks source link

converting jsx to slack #310

Closed SeungyeopShin closed 10 months ago

SeungyeopShin commented 10 months ago

Hello, I tested jsx-slack to convert standard markdown to slack markdown. But I can't get the result I want.

import Markdown from 'markdown-to-jsx'
import { jsxslack } from 'jsx-slack'
const mdText = `
**Our Project**

Hello, **Markdown**!
`
const md = <Markdown>{mdText}</Markdown>
const result = jsxslack`
                <Blocks>
                  <Section>
                    ${md}
                  </Section>
                </Blocks>`
console.log(JSON.stringify(result))

// output : jsx is converted to "[object Object]"
// [{"type":"section","text":{"type":"mrkdwn","text":"[object Object]","verbatim":true}}]
const htmlText = unified()
                  .use(markdown)
                  .use(remark2rehype)
                  .use(html)
                  .processSync(mdText)

const result = jsxslack`
                <Blocks>
                  <Section>
                    ${htmlText.toString()}
                  </Section>
                </Blocks>`

console.log(JSON.stringify(result))
// output : markup is encoded
// [{"type":"section","text":{"type":"mrkdwn","text":"&lt;p&gt;&lt;strong&gt;Our Project&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Hello, &lt;strong&gt;Markdown&lt;/strong&gt;!&lt;/p&gt;","verbatim":true}}]

How could I get correct json object with slack markdown.

yhatt commented 10 months ago

Expressions in jsxslack template literal tag are always escaped, and cannot mix non jsx-slack components. markdown-to-jsx is designed for React, not jsx-slack.

To convert the string representation of HTML into Slack Mrkdwn, you can use jsxslack as a function just like this:

import { jsxslack } from 'jsx-slack';

// HTML should be jsx-slack compatible
const html = '<p><b>Our Project</b></p><p>Hello, <b>Markdown</b>!</p>';

const result = jsxslack([`<Mrkdwn>${html}</Mrkdwn>`]);
console.log(result.text); // *Our Project*\n\nHello, *Markdown*!

You can pass the string representation of HTML that is converted from Markdown.

See also:

This is exactly how our REPL demo converts the string to actual JSX.

https://github.com/yhatt/jsx-slack/blob/b9b6e1236e03321539996dd217f0664d600c5516/demo/js/convert.js#L10

Note that the string is wrapped in an array. Once you understand how the template literal tag works, you may understand why this works like magic :)

https://github.com/yhatt/jsx-slack/issues/307#issuecomment-1842183952

SeungyeopShin commented 10 months ago

Thanks for you reply. I successed with marked.