From 37a79a801a57f055e578251818faf7fa9abdbab5 Mon Sep 17 00:00:00 2001 From: Nikolay Kost Date: Sun, 21 Aug 2022 23:43:03 +0200 Subject: [PATCH] chore(readme): add plugin example --- README.md | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/README.md b/README.md index ecccdd7..55fead9 100644 --- a/README.md +++ b/README.md @@ -270,6 +270,51 @@ render() // Super +For example lets parse all strings that similar to links like "https://some-site.com" + +```js +import { createRoot } from "react-dom/client"; + +import BBCode from "@bbob/react/es/Component"; +import TagNode from "@bbob/plugin-helper/es/TagNode"; +import { isStringNode } from "@bbob/plugin-helper/es"; + +const URL_RE = new RegExp( + `([--:\\w?@%&+~#=]+\\/*\\.[a-z]{2,4}\\/{0,2})((?:[?&](?:\\w+)=(?:\\w+))+|[^^).|,][--:\\w?@%&+~#=()_]+)?`, + "g" +); + +const isValidUrl = (url) => URL_RE.test(url); + +const linkParsePlugin = (tree) => { + return tree.walk((node) => { + if (isStringNode(node) && isValidUrl(node)) { + return TagNode.create( + "a", + { + href: node + }, + `Url to: ${node}` + ); + } + + return node; + }); +}; + +const rootElement = document.getElementById("root"); +const root = createRoot(rootElement); + +root.render( + + https://github.com/JiLiZART/BBob Other text without link + +); +``` + +[![Edit x7w52lqmzz](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/bbob-plugin-example-dmq1bh) + + ### Benchmarks To test on your machine run