Skip to content

Commit

Permalink
Merge pull request #184 from preactjs/encode-perf
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinhagemeister authored Mar 10, 2021
2 parents ced65a7 + ab73d3f commit 16df0e4
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
8 changes: 5 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ const UNNAMED = [];

const VOID_ELEMENTS = /^(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/;

const UNSAFE_NAME = /[\s\n\\/='"\0<>]/;

const noop = () => {};

/** Render Preact JSX + Components to an HTML string.
Expand Down Expand Up @@ -291,12 +293,12 @@ function _renderToString(vnode, context, opts, inner, isSvgMode, selectValue) {
}

s = `<${nodeName}${s}>`;
if (String(nodeName).match(/[\s\n\\/='"\0<>]/))
if (UNSAFE_NAME.test(String(nodeName)))
throw new Error(`${nodeName} is not a valid HTML tag name in ${s}`);

let isVoid =
String(nodeName).match(VOID_ELEMENTS) ||
(opts.voidElements && String(nodeName).match(opts.voidElements));
VOID_ELEMENTS.test(String(nodeName)) ||
(opts.voidElements && opts.voidElements.test(String(nodeName)));
let pieces = [];

let children;
Expand Down
26 changes: 24 additions & 2 deletions src/util.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,20 @@
/**
* @template T
* @param {T} fn
* @returns {T}
*/
function memoize(fn) {
const cache = new Map();
return (arg) => {
let res = cache.get(arg);
if (!res) {
res = fn(arg);
cache.set(arg, res);
}
return res;
};
}

// DOM properties that should NOT have "px" added when numeric
export const IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|^--/i;

Expand All @@ -9,10 +26,15 @@ const tagsToReplace = {
'"': '&quot;'
};
const replaceTag = (tag) => tagsToReplace[tag] || tag;
export function encodeEntities(s) {

/**
* @param {any} s
* @returns {string}
*/
export const encodeEntities = memoize((s) => {
if (typeof s !== 'string') s = String(s);
return s.replace(HTML_ENTITY_REG, replaceTag);
}
});

export let indent = (s, char) =>
String(s).replace(/(\n+)/g, '$1' + (char || '\t'));
Expand Down

0 comments on commit 16df0e4

Please sign in to comment.