Giter VIP home page Giter VIP logo

remark-react's Introduction

remark-react

Stability: Legacy. This package is no longer recommended for use. It’s still covered by semantic-versioning guarantees and not yet deprecated, but use of this package should be avoided. Please use remark-rehype to move from remark (markdown) to rehype (HTML) and then replace remark-react with rehype-react.

Legacy documentation for this package is still available in Git.

License

MIT © Titus Wormer, modified by Tom MacWright and Mapbox.

remark-react's People

Contributors

bebraw avatar ciaranw avatar craftzdog avatar davidtheclark avatar ek5000 avatar jstcki avatar makenowjust avatar medfreeman avatar mrh-is avatar rhysd avatar sapegin avatar stefanprobst avatar tmcw avatar wooorm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

remark-react's Issues

Using remark-react in a tab nature causes DOM related errors

I am using this remark-react to render markdown inside a tab like environment.
Based on the active tab, a content container is passed markdown as props which is inturn passed to remark-react...

const item = remark().use(reactRenderer).processSync(this.props.md).contents;
    return (<div>
      {item}
    </div>);

The errors I am seeing when changing tabs quickly:

image

Should I be caching the result call to remark?

Environment details
"react": "^15.5.4",
"react-dom": "^15.5.4",
"remark": "^7.0.0",
"remark-react": "^4.0.0",
"styled-components": "^1.4.5"

I can't use tasks list like github

I want to use tasks list like below:

  • first task
  • second task

I thought remark-react correspond to GFM. But, when I use tasks list, a normal list was output instead of a checkbox.

remarkReactComponents not working

remarkReactComponents not working

I have the following markdown and component. The image tag is discarded from the final result (htmlContent).

<img src="/foo.png" id="logo" />
Lorem ipsum
export const MarkdownContent = ({ content, ...props }) => {
	const opts = {
		createElement: React.createElement,
		schema: false,
		remarkReactComponents: {
			img: (props) => {
				console.log(props);
				return (<MarkdownImage {...props} />);
			},
		}
	};

	const htmlContent = unified()
		.use(parse)
		.use(remark2react, opts)
		.processSync(content).result;

	return (
		<div className="w-full p-8 bg-white sm:py-12 text-gray-800">
			<div className="container my-20 flex md:w-2/3 mx-auto flex-col">
				<div className={styles['markdown-content']}>
					{ htmlContent }
				</div>
			</div>
		</div>
	);
};

Your environment

  • OS: Ubuntu
  • Packages: 7.0.1

table rendering not working

Hello,
by using the code from the read.me:

const res = remark()
    .use(remark2react)
    .processSync(value)

and using this simple markdown -> value:P1|P2|P3| P4| P5| P6| P7| P8|↵---|---|---|---|---|---|---|---|↵XX1| XX2|XX3|XX4|XX5|XX6|XX7|XX8

leads to
image

which is wrong since the "new lines" are not sanitised and this leads in the end to:
image

Any idea how to fix this?
Thanks a lot Ognian

PS: children 0,2 and 4 should be omitted

Incorrect treatment of 'tel'-links

I realize that this is probably the wrong repository to report this issue in, but I'm a bit lost on where to go to actually solve it.

Basically the problem I have is that a link on the form [+15553485](tel:+15553485) generates the following html: <a>+15553485</a> instead of the expected <a href="tel:+15553485">+15553485</a>.

5.0.0

Heya! I’ve just pushed some polishing, updating, and cleaning stuff. Would be nice to cut a new release, but I don’t have permissions.

@davidtheclark Could you publish a major for me?

Also: maybe we can move this to @remarkjs for better maintainability.

Cheers 🎉

Improve documentation around linking to custom React Components

I'm trying to implement react-katex maths rendering in remark-react and I'm a little bit confused as to how to go about this. #23 seems to discuss the issue of custom components, but I think the discussion got a bit side tracked by sanitize before a solution was proposed. I've also looked at the related documentation in the Readme on configuration.

My basic approach is to use remark-math to process the inlineMath and math node types, then make remark use the react-katex components to render these.

I have the following configuration:

// ...other imports
import math from 'remark-math';
import { InlineMath } from 'react-katex';

const renderer = remark()
  .use(math)
  .use(mathRenamer)
  .use(reactRenderer, {
    createElement: React.createElement,
    sanitize: schema,
    remarkReactComponents: {
      inlineMath: InlineMath
    }
  });

The mathRenamer plugin looks like this:

const transformer = tree => {
  visit(tree, 'inlineMath', node => {
    node.data.hName = 'Component';  // I've also tried `inlineMath`
  });

  console.log('TREE', tree);
};

const attacher = () => transformer;

I'm doing a similar thing for BlockMath which I have omitted. Using this input:

Test $ax^2 + bx + c$ Test

$$
3^2*2+1=19
$$

Test

I can verify that the data.hName property is correctly set from the logging in the transformer. However after calling processSync, the generated DOM looks like this:

image

If I call console.log(JSON.stringify(renderer.parse(content)) I see something like this (some sections cut out). Note that it has span and div for the hNames

{
    "type": "root",
    "children": [
        {
            "type": "paragraph",
            "children": [
                // ...
                {
                    "type": "inlineMath",
                    "value": "ax^2 + bx + c",
                    "data": {
                        "hName": "span",
                        "hProperties": {
                            "className": "inlineMath"
                        },
                        "hChildren": [
                            {
                                "type": "text",
                                "value": "ax^2 + bx + c"
                            }
                        ]
                    }
                }
                //...
            ]
        },
        {
            "type": "math",
            "value": "3^2*2+1=19",
            "data": {
                "hName": "div",
                "hProperties": {
                    "className": "math"
                },
                "hChildren": [
                    {
                        "type": "text",
                        "value": "3^2*2+1=19"
                    }
                ]
            }
        }
        // ...
    ]
}

Am I doing something silly?

P.S. Sorry this is a bit of an essay... I'm happy to contribute an example for the documentation if we can get this sorted as I feel it could be a fairly common use case.

ReactElement key differs on server and client renders

I'm using mdast-react in an isomorphic react app. I'm getting warnings from React on the client about the server-generated markup differing from what the client generated. I've tracked this down to the fact that the key counter used in h.js resets on every client render, but persists on the server renders. This leads to the counter increasing with every subsequent server render, which causes React to generate non-matching data-reactid attributes on elements.

A potential solution to this might be to initialise a counter in the Compiler constructor, and then use that to source the key from. Quite happy to submit a pull request but thought I should check in case you have a cleaner/better solution?

TypeError: Cannot set property 'Compiler' of undefined

I am getting a really strange error.
Using webpack if that makes a difference....
Would really appreciate the help...

import React, { Component } from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import remark from 'remark';
import reactRenderer from 'remark-react';
class KComponent extends Component {
  render() {
    console.log("rendering K" );
    var item = remark().use(reactRenderer).processSync('# hello').contents

    return (<div>
        hello
    </div>)
  }
}

export default KComponent;

chorme output

Uncaught TypeError: Cannot set property 'Compiler' of undefined
    at Function.plugin (eval at ./node_modules/remark-react/index.js (0.chunk.js:2911), <anonymous>:95:24)
    at freeze (eval at ./node_modules/unified/index.js (0.chunk.js:3908), <anonymous>:122:28)
    at Function.processSync (eval at ./node_modules/unified/index.js (0.chunk.js:3908), <anonymous>:392:5)
    at KComponent.render (eval at ./app/containers/FeaturePage/TestComponent.js (0.chunk.js:47), <anonymous>:72:125)

allowDangerousHTML doesn't work

It looks like it's not possible to get remark-react to render raw html, even when passing the allowDangerousHTML flag through to mdast-util-to-hast.

For example, attempting to add this unit test fails:

diff --git a/test/index.js b/test/index.js
index d6cb228..22d347e 100644
--- a/test/index.js
+++ b/test/index.js
@@ -121,6 +121,19 @@ versions.forEach(function(reactVersion) {
       'passes toHast options to inner toHAST() function'
     )
 
+    t.equal(
+      React.renderToStaticMarkup(
+        remark()
+          .use(reactRenderer, {
+            createElement: React.createElement,
+            toHast: {allowDangerousHTML: true}
+          })
+          .processSync('<strong>raw</strong> html').contents
+      ),
+      '<p><strong>raw</strong> html</p>',
+      'renders raw html when specified'
+    )
+
     fixtures.forEach(function(name) {
       var base = path.join(root, name)
       var input = fs.readFileSync(path.join(base, 'input.md'))

with the error:

not ok 6 renders raw html when specified
  ---
    operator: equal
    expected: '<p><strong>raw</strong> html</p>'
    actual:   '<p>raw html</p>'

Is there a different expected configuration to be able to support raw HTML inputs?

Add Typescript types

A type definition file would be very helpful for those of us who us TS. Let me know if you're open to a PR for this.

Thanks for the project!

Custom components for mdast nodes

remarkReactComponents and createElement are nice but I would like to be able to customize rendering a few levels lower. By the time data gets to those extension points, all semantic information beyond the HTML element is lost.

For example, I would like to use my own React components for footnote references and footnote definitions. After some digging (phew 😅 ), I think the point to do that would be at the MDAST level, i.e. through my own plugin which I use() before this plugin.

Now, I didn't understand how to modify the footnoteDefinition node in a way (e.g. by adding a component prop) that gets preserved by mdast-util-to-hast because it turns unknown nodes into divs and somehow when I set properties on a node they don't show up in the createElement props.

Maybe this all sounds a bit confusing but currently I am confused 😁 (mainly by the multiple layers of abstraction). I'll try to summarize:

  • What I want is to associate a footnoteDefinition node with a React component which receives the information about footnote definitions as data.
  • What I don't want is to construct some intermediary dom-like representation with paragraphs and list items and reverse-engineer that in createElement.
  • What I'd prefer to avoid is to have to re-build everything above the MDAST level myself.

Maybe @wooorm can shed some light on this?

Pass `position` into props

Hello. I'm trying to implement two-panel view and to achieve good scrolling and navigation experience I'd like to use position information from MDAST. But it seems that react children have no access to an original Position structure.

Is it possible to add this functionality?

hast-util-sanitize dep failing

I wasn't sure if I should file this issue here or for hast-util-sanitize but I figured this was the place since it's an indirect dependency.

Trying to use the example out of the box in the readme and I get the following error:

ERROR in ./~/hast-util-sanitize/lib/index.js
Module not found: Error: Can't resolve './github' in '/home/s1n/project/node_modules/hast-util-sanitize/lib'
 @ ./~/hast-util-sanitize/lib/index.js 5:15-34
 @ ./~/hast-util-sanitize/index.js
 @ ./~/remark-react/index.js
 @ ./app/containers/MarkDoc/index.js
 @ ./app/routes.js
 @ ./app/app.js
 @ multi main
Child html-webpack-plugin for "index.html":

Any reason why the root element has to be a <div>?

I'm refactoring some of our code to use this module, instead of dangerouslySetInnerHtml using marked. Marked appears to have a root element of a <p> tag, this module has a <div> that everything gets wrapped in.

This is causing some issues in our tests because previously we were inserting markdown content inside of a <p> tag. A <p> inside of a <p> is a valid descendant. A <div> inside of a <p> results in this react error:

Warning: validateDOMNesting(...): <div> cannot appear as a descendant of <p>.

Would you be open to accepting a pr which makes the root tag customisable?

TypeError: No default value

When using an earlier version, I was having the issue where < symbols would show up as &lt;. I updated to 3.0.1 but got issues there.

MIDDLEWARE ERROR:
Error: mdast-util-definitions expected node — index.js:53
["loginPage/USER_FETCH", "loginPage/USER_FETCH_SUCCESS", "loginPage/USER_FETCH_FAILURE"] 

I took this to be because remark was version 4.2.0so I updated that to 5.0.1. Now I get errors like this:

MIDDLEWARE ERROR:
TypeError: No default value — traverseAllChildren.js:157
["loginPage/USER_FETCH", "loginPage/USER_FETCH_SUCCESS", "loginPage/USER_FETCH_FAILURE"]

remark-react does not render telephone links

remark-react does not render telephone links.

Input

[telephone link](tel:1234567890)

Expected output

<a href="tel:1234567890">telephone link</a>

Actual output

<a>telephone link</a>

Steps to reproduce

  1. git clone [email protected]:sebflipper/remark-test.git
  2. cd remark-test
  3. yarn - installs modules
  4. yarn remark-test - shows the correct output from a basic stand-alone remark setup.
  5. yarn start - starts a React server with the same Markdown text, with the incorrectly rendered telephone link.

remarkReactComponents target classes

Is it possible to target an element with a class i.e. div.custom-block in remarkReactComponents option?
I use remark-custom-blocks plugin that creates divs out of markdown, i.e. [[section]] --> div.custom-block.section. I would like to transform such divs into customised components.
Thanks!

Confusing readme

Hi
This is not a bug but a problem with the readme instructions:

The readme example is
unified() .use(parse) .use(remark2react) .processSync(this.state.text).result

But later it says the API is
remark().use(react[, options])

Can you please explain ?
Thanks!

Laguage type not being passed

Let's suppose that the original markdown was a code-block with ```js as opening syntax.

The remarkReactComponents property is not passing the language to the "code" component that y specified, the only property that the component received is an array of children.

        {remark().use(reactRenderer, {
          remarkReactComponents: {
            code: PrismCode
          }
        }).processSync(readme).contents}

My component PrismCode is only receiving the children prop, how can I know that language was this code block defined on?

HTML in markdown always getting escaped

Have a feeling I could be missing something very obvious here so apologies if this has already been addressed, but any markup in my markdown seems to be getting escaped with no way to override this behavior. I've tried modifying the sanitization options as well as the toHast options but to no avail. As far as I can tell this doesn't work in the remark-react demo either. Something like:

<h2>Testing</h2>

gets converted to:

\u003ch2\u003eTesting!\u003c/h2\u003e\

Could someone point me in the right direction here?

How to use remark-react with hightlight.js

I'm trying to use HightlightJS with remark-react but I don't quite understand how to use the syntax:

import remark from 'remark';
import reactRenderer from 'remark-react';
import hljs from 'remark-highlight.js';

...

this.markdownProcessor = remark().use([reactRenderer, hljs]);

Any hint on how to use it?

Is this compatible with remark 4?

I just tried to update a boilerplate of mine to use the newly released remark 4. For some reason it didn't process correctly there (output remained as markdown). Is remark-react compatible with it?

remark v5 API is async now

Hi,

Just thought to note that remark changed its API so that it's async. The signature is like this:

remark().use(lint).use(html).process('## Hello world!', function (err, file) {
    console.error(report(file));
    console.log(file.toString());
});

You might want to tweak the README example accordingly.

Update mdast to remark

Hey @tmcw / mapbox!

I’d like to update mdast to remark. You’ve probably noticed this, but mdast got a big new update including a rename to remark (see what’s new, learn how to upgrade plugins).

I have time to do the update myself if needed, but I’d first like to know whether you’d like to include GH-11, GH-12 first (as the update will probably make rebasing those more difficult).

Access the data property of hast code elements in my custom component

Subject of the feature

I want to customise the rendering of code elements based on metadata extracted from the markdown input.

Problem

The metadata that exists in the mdast code nodes is added to as data to the hast by the default mdast-util-to-hast handler. However, that property gets lost and does not reach the custom renderer provided in the remarkReactComponents.

Expected behavior

I want to access the metadata in the custom component:

remarkReactComponents: {
  code: () => {
    // access the data here
  }
}

Alternatives

Create alternative handlers for converting mdast to hast and pass them as options to toHast option. The handler will attach the matadata to the props using the same pattern as with className

toHast: {
  handlers: {
    code: (h, node) => {
      // my handler
    }
  }
}

Nested ordered lists need at least 3 spaces to work

Subject of the issue

Nested ordered lists need at least 3 spaces to work while unordered lists require 2 spaces - which seems inconsistent. I am not sure if this is expected behavior. Is there a way to configure a number of spaces to make nesting work?

Your environment

  • Packages: 6.0.0

Steps to reproduce

Pasting this code in the example site:

- list
  - sublist with 2 spaces

---

1. list
  1. sublist with 2 spaces

---

1. list
   1. sublist with 3 spaces

Yields:

Screenshot of Google Chrome (02-12-2019, 00-50-23)

Expected behavior

Indenting with 2 spaces should make an ordered list nested -- just like an unordered list

Actual behavior

Ignores indentation.

Is it a normal behavior to have all element properties stringified (through hast-to-hyperscript) ?

Hi, thanks for your work !!

here's a bit of context.

I'm developing a common mark generic extensions plugin, supporting this kind of syntax:
!Element[content](argument){ properties }

I'm using !Icon[My-tooltip](my-icon){ floating } for testing

My remark inline tokenizer returns this node:

{
  type: 'extension',
  data: {
    hName: 'Icon',
    hProperties: {
      tooltip: 'My-tooltip',
      icon: 'my-icon'
      floating: true
    },
  }
})

Notice the boolean property named floating.

I can properly have my corresponding react component TooltipIcon render with the following snippet (es6):

import remark from "remark"
import reactRenderer from "remark-react"
import merge from "deepmerge"
import sanitizeGhSchema from "hast-util-sanitize/lib/github.json"

import TooltipIcon from "../TooltipIcon"
import genericExtensions from "./remark-commonmark-generic-extensions.js"

remark()
    .use(genericExtensions, {
      elements: {
        Icon: {
          attributeMap: {
            content: "tooltip",
            argument: "icon",
          },
          attributeDefaultValues: {
            floating: true,
          }
        }
      }
    })
    .use(reactRenderer, {
      sanitize: merge(sanitizeGhSchema, {
        tagNames: [
          "Icon",
        ],
        attributes: {
          Icon: [
            "className",
            "tooltip",
            "icon",
            "floating",
          ],
        },
      }),
      remarkReactComponents: {
        Icon: TooltipIcon
      },
    })
    .processSync(body, {
      commonmark: true,
    })

Whereas my floating property is effectively boolean inside the HAST tree generated by remark, it is stringified by hast-to-hyperscript at this line, called here in remark-react.

In order to avoid a react PropTypes type warning, i'm actually forced to also allow String in addition to Boolean propTypes for the floating property inside my component. I then coerce the floating property back to boolean, in order for the subcomponent (which requires floating to be boolean) to be happy.

Here's my TooltipIcon component:

import React, { PropTypes } from "react"
import IconButton from "react-toolbox/lib/button"
import Tooltip from "react-toolbox/lib/tooltip"

const TooltipButton = Tooltip(IconButton)

const TooltipIcon = props => {

  const { floating, ...otherProps } = props
  if (floating === "true") {
    otherProps.floating = true
  }

  return (
    <TooltipButton
      { ...otherProps }
    />
  )
}

TooltipIcon.propTypes = {
  floating: PropTypes.oneOfType([
    PropTypes.bool,
    PropTypes.string,
  ]),
  tooltip: PropTypes.any,
  theme: PropTypes.object,
}

export default TooltipIcon

I hope you get the general idea, and if you can tell if it's a requirement to have every property stringified.
Because in this case only String properties can be passed to React if i'm not mistaken.

Test passing options to toHast() wrong?

I believe the test for passing options to toHast() actually does not test anything, since (i) the markdown sample does not contain any html for allowDangerousHTML to make a difference, and (ii) AFAICT if allowDangerousHTML is set, toHast will return raw nodes which will be ignored by hast-to-hyperscript anyway and thus not show up in the rendered markup.

Code Snippets are not getting their class names?

Code Snippets seem to be loosing their language class names.
Nor is it passed to the props?
Does not work with the https://github.com/bebraw/remark-react-lowlight
I am invoking the library as follows:

    const item = remark().use(reactRenderer).processSync(this.props.md).contents;

The input for this.props.md is the following text:

  1. Autoload the SDK Package. This will include all the files and classes to your autoloader. Please note, If your downloaded our SDK using composer, replace PayPal-PHP-SDK with vendor. This applies for all sample code in our SDK.
<?php
// 1. Autoload the SDK Package. This will include all the files and classes to your autoloader
// Used for composer based installation
require __DIR__  . '/vendor/autoload.php';
// Use below for direct download installation
// require __DIR__  . '/PayPal-PHP-SDK/autoload.php';

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.