Skip to content

Instantly share code, notes, and snippets.

@pikilon
Last active November 22, 2020 14:21
Show Gist options
  • Save pikilon/ed8ccd58902792d009dd6cfe2b664fa2 to your computer and use it in GitHub Desktop.
Save pikilon/ed8ccd58902792d009dd6cfe2b664fa2 to your computer and use it in GitHub Desktop.
Frontity WP shortcodes processors
import React from "react";
import Gist from "react-gist";
import { testShortCode, getShortCodeProps } from "./shortcode-utils";
const gist = {
name: "gist",
priority: 10,
test: ({ node }) => testShortCode(node, "gist"), //👈 [gist ]
processor: ({ node }) => {
/*
this node will be like
[gist id="long-github-id" file="filename-or-undefined"]
*/
const firstTextChildren = node.children[0]
const shortcodeText = firstTextChildren.content
const shortcodeProps = getShortCodeProps(shortcodeText);
// we can check the required props are set
const { id, file } = shortcodeProps;
if (id) {
// https://www.npmjs.com/package/react-gist#gist-idstring-filestring-
node.props = { id, file };
node.component = Gist;
}
return node;
},
};
export default gist;
import Theme from "./components";
import image from "@frontity/html2react/processors/image";
import iframe from "@frontity/html2react/processors/iframe";
import link from "@frontity/html2react/processors/link";
// OUR NEW PROCESSOR 👇
import gist from "./processors/gist";
//...scroll to libraries
libraries: {
html2react: {
processors: [image, iframe, link, gist], // 👈 our component
},
},
};
// ...
export const testShortCode = ({ type, children, component }, name) => {
const isNodeWithOnlyText =
type === "element" && // is not a comment or plain text
children.length === 1 && // has only only a text child
children[0].type === "text";
if (!isNodeWithOnlyText) return false;
// format [name something] AND NOTHING ELSE in the tag
const pattern = new RegExp(`\\s*\\[${name}[^\\]]*\\]\s*$`);
return pattern.test(children[0].content);
};
export const getShortCodeProps = (shorcodeString) => {
const regex = /\s+([^=\[\]\s]+)(=["'”]?([^"'\s\]”]+)["'”]?)?/gi;
const props = [...shorcodeString.matchAll(regex)].reduce(
(result, [fullMatch, propName, hasEqual, value]) => {
let finalValue = value; // string without quotes
const lowerCaseValue = value ? value.toLowerCase() : ""
const isTrue = !hasEqual || lowerCaseValue === "true"
// [shortcode isBooleanProp] isBooleanProp = true
if (isTrue) finalValue = true;
// [shortcode isTrulyBoolean="false"] isTrulyBoolean = false
if (lowerCaseValue === "false") finalValue = booleanValue;
result[propName] = finalValue;
return result;
},
{}
);
return props;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment