Skip to content

Commit

Permalink
Merge pull request #81 from dimaMachina/ignore-script-style
Browse files Browse the repository at this point in the history
ignore content of `<script>` and `<style>` html elements
  • Loading branch information
silvenon authored Jan 11, 2024
2 parents e2b1492 + ab6bcd1 commit b665025
Show file tree
Hide file tree
Showing 4 changed files with 1,965 additions and 936 deletions.
14 changes: 13 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@ import { retext } from "retext";
import { visit } from "unist-util-visit";
import smartypants from "retext-smartypants";

const VISITED_NODES = new Set(["text", "inlineCode"]);

const IGNORED_HTML_ELEMENTS = new Set(["style", "script"]);

function check(node, index, parent) {
return (
VISITED_NODES.has(node.type) &&
(parent.type !== "mdxJsxTextElement" ||
!IGNORED_HTML_ELEMENTS.has(parent.name))
);
}

/**
* remark plugin to implement SmartyPants.
*
Expand Down Expand Up @@ -35,7 +47,7 @@ export default function remarkSmartypants(options) {
let startIndex = 0;
const nodes = [];

visit(tree, ["text", "inlineCode"], (node) => {
visit(tree, check, (node) => {
allText +=
node.type === "text" ? node.value : "A".repeat(node.value.length);
nodes.push(node);
Expand Down
22 changes: 20 additions & 2 deletions index.test.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { it, expect, describe } from "vitest";
import { remark } from "remark";
import smartypants from "./";
import remarkMdx from "remark-mdx";
import remarkSmartypants from "./";

const { process } = remark().use(smartypants);
const compiler = remark().use(remarkSmartypants);
const process = compiler.process.bind(compiler);

it("implements SmartyPants", async () => {
const file = await process('# "Hello World!"');
Expand Down Expand Up @@ -57,3 +59,19 @@ describe("handles quotes around inline code", async () => {
"`);
});
});

describe("should ignore parent nodes", () => {
const mdxCompiler = remark().use(remarkMdx).use(remarkSmartypants);
const process = mdxCompiler.process.bind(mdxCompiler);

it("<style>", async () => {
const mdxContent = `<style>html:after \\{ content: '""' }</style>`;
const file = await process(mdxContent);
expect(file.value.trimEnd()).toBe(mdxContent);
});
it("<script>", async () => {
const mdxContent = '<script>console.log("foo")</script>';
const file = await process(mdxContent);
expect(file.value.trimEnd()).toBe(mdxContent);
});
});
Loading

0 comments on commit b665025

Please sign in to comment.