22
33require ( 'node-jsx' ) . install ( { extension : '.jsx' , harmony : true } ) ;
44var React = require ( 'react/addons' ) ;
5+ var JSXTransformer = require ( 'react/dist/JSXTransformer' ) ;
56var path = require ( 'path' ) ;
7+ var fs = require ( 'fs' ) ;
68var _ = require ( 'lodash' ) ;
79
810/*
@@ -22,7 +24,17 @@ exports.process = function (req, res, next) {
2224 var pathToFile = path . join ( global . app . get ( 'user' ) , req . url ) ;
2325 var html ;
2426 try {
25- var component = React . createFactory ( require ( pathToFile ) ) ;
27+ var matchingPattern = / < S o u r c e E x a m p l e ( (?: .| \n ) * ?) > \s * ( (?: .| \n ) + ?) \n \s * ?< \/ S o u r c e E x a m p l e > / g;
28+ //noinspection HtmlUnknownAttribute
29+ var replacementPattern = '<code className="src-html source_visible">{`$2`}</code>' +
30+ '<SourceExample$1>$2</SourceExample>' ;
31+ var specContents = fs . readFileSync ( pathToFile , {
32+ encoding : 'utf-8'
33+ } ) . replace ( matchingPattern , replacementPattern ) ;
34+ specContents = JSXTransformer . transform ( specContents , {
35+ harmony : true
36+ } ) . code ;
37+ var component = React . createFactory ( requireCode ( specContents , pathToFile ) ) ;
2638 html = getHtml ( component ) ;
2739 } catch ( ex ) {
2840 html = getErrorAsHtml ( ex ) ;
@@ -33,6 +45,30 @@ exports.process = function (req, res, next) {
3345 next ( ) ;
3446} ;
3547
48+ function requireCode ( code , pathToCode ) {
49+ var path = require ( 'path' ) ;
50+ var Module = require ( 'module' ) . Module ;
51+
52+ var filepath = path . resolve ( process . cwd ( ) , pathToCode ) ;
53+ var dirname = path . dirname ( filepath ) ;
54+
55+ var cachedModule = Module . _cache [ filepath ] ;
56+ if ( cachedModule ) {
57+ return cachedModule . exports ;
58+ }
59+
60+ var mod = new Module ( filepath , module ) ;
61+ Module . _cache [ filepath ] = mod ;
62+
63+ mod . filename = filepath ;
64+ mod . paths = Module . _nodeModulePaths ( dirname ) ;
65+
66+ mod . _compile ( code , filepath ) ;
67+ mod . loaded = true ;
68+
69+ return mod . exports ;
70+ }
71+
3672function getHtml ( component ) {
3773 try {
3874 return React . renderToString ( component ( { } ) ) ;
0 commit comments