Skip to content

Instantly share code, notes, and snippets.

@zachwolf
Last active June 19, 2018 19:26
Show Gist options
  • Save zachwolf/333f4174ecdb4dcc32a5eca160cfe457 to your computer and use it in GitHub Desktop.
Save zachwolf/333f4174ecdb4dcc32a5eca160cfe457 to your computer and use it in GitHub Desktop.
const MARKER = '__jss-snapshot-serializer-marker__';
const jssClassNameRegexp = /(^(?:[^-]+)-\w+)(?:(?:-\d+){1,2})/i;
const collectElements = (element, elements = []) => {
if (typeof element !== 'object') {
return elements;
}
elements.push(element);
if (element.children) {
element.children.forEach(child => collectElements(child, elements));
}
return elements;
};
const markElements = nodes => nodes.forEach((element) => {
element[MARKER] = true;
});
const replaceJssClassNames = (elements) => {
elements.forEach((element) => {
if (!element.props || !element.props.class) return;
const classNameProp = element.props.class;
const deterministicClassNames = classNameProp
.trim()
.split(/\s+/)
.map((className) => {
console.log('className', className, jssClassNameRegexp.test(className))
console.log('jssClassNameRegexp.exec(className)', jssClassNameRegexp.exec(className))
// do not modify the className if it is not generated by JSS
if (!jssClassNameRegexp.test(className)) return className;
return jssClassNameRegexp.exec(className)[1]
});
element.props.class = deterministicClassNames.join(' ');
});
};
module.exports = {
test(value) {
// apply the serializer only to react elements that we haven't marked(processed) before
return value && !value[MARKER] && value.$$typeof === Symbol.for('react.test.json');
},
print(value, serialize) {
// collect all react element nodes in the tree of the value
const elements = collectElements(value);
// mark the collected element nodes to avoid processing them several times
markElements(elements);
// remove the non-deterministic part from the JSS class names
// to keep the snapshots repeatable
replaceJssClassNames(elements);
return serialize(value);
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment