Skip to content

Commit 0229290

Browse files
committed
Merge pull request #46 from Kreozot/constructors-and-prototypes
Parser and Writter has been rewritten with constructors and prototype functions
2 parents 5b72c4b + d5f4b2a commit 0229290

File tree

3 files changed

+91
-100
lines changed

3 files changed

+91
-100
lines changed

src/js/main.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@
33
* @author Miller Medeiros
44
*/
55

6-
var writter = require('./writter');
6+
var Writter = require('./writter');
77

88
exports.run = function (opts) {
9-
writter.processFiles(opts);
9+
var writter = new Writter(opts);
10+
writter.processFiles();
1011
};

src/js/parser.js

Lines changed: 35 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,37 @@
11

2-
var showdown = require('showdown'),
3-
converter = new showdown.Converter();
4-
5-
var _headingLevel;
2+
var showdown = require('showdown');
63

4+
var Parser = function(config) {
5+
this.config = config;
6+
this.headingLevel = config.headingLevel || 2;
7+
var converter = new showdown.Converter();
8+
this.parseMdown = converter.makeHtml;
9+
}
710

8-
exports.parseDoc = function(mdown, headingLevel){
9-
mdown = normalizeLineBreaks(mdown);
10-
mdown = convertCodeBlocks(mdown);
11-
_headingLevel = (headingLevel || 2);
11+
Parser.prototype.parseDoc = function(mdown){
12+
mdown = this.normalizeLineBreaks(mdown);
13+
mdown = this.convertCodeBlocks(mdown);
1214

13-
var toc = getTocData(mdown);
15+
var toc = this.getTocData(mdown);
1416

1517
return {
1618
toc : toc,
17-
html : parseContent(mdown, toc),
18-
title : getTitle(mdown)
19+
html : this.parseContent(mdown, toc),
20+
title : this.getTitle(mdown)
1921
};
2022
};
2123

22-
exports.parseMdown = function(mdown){
23-
return converter.makeHtml(mdown);
24-
};
25-
26-
27-
function wrapCode(str, p1, p2){
24+
Parser.prototype.wrapCode = function(str, p1, p2){
2825
return p1? '<pre class="brush:'+p1+'">'+p2+'</pre>' : '<pre>'+p2+'</pre>';
2926
}
3027

31-
function convertCodeBlocks(mdown){
28+
Parser.prototype.convertCodeBlocks = function(mdown){
3229
// showdown have issues with github style code blocks..
3330
var re = /^```\s*(\w+)\s*$([\s\S]*?)^```$/gm;
34-
return mdown.replace(re, wrapCode);
31+
return mdown.replace(re, this.wrapCode);
3532
}
3633

37-
function normalizeLineBreaks(str, lineEnd) {
34+
Parser.prototype.normalizeLineBreaks = function(str, lineEnd) {
3835
lineEnd = lineEnd || '\n';
3936
return str
4037
.replace(/\r\n/g, lineEnd) // DOS
@@ -43,11 +40,11 @@ function normalizeLineBreaks(str, lineEnd) {
4340
}
4441

4542

46-
function getTocData(mdown){
43+
Parser.prototype.getTocData = function(mdown){
4744

4845
var matchTitle,
4946
matchName,
50-
rH = getHeaderRegExp(),
47+
rH = this.getHeaderRegExp(),
5148
rName = /([^\(#:%\?!,]+)(\(?)[^\)]*(\)?):?.*/,
5249
toc = [];
5350

@@ -57,23 +54,23 @@ function getTocData(mdown){
5754
href : matchName[1],
5855
title : matchTitle[1].replace(/\\/g, ''),
5956
name : (matchName.slice(1,4).join('')),
60-
description : getDescription(mdown, rH.lastIndex)
57+
description : this.getDescription(mdown, rH.lastIndex)
6158
});
6259
}
6360

6461
return toc;
6562
}
6663

67-
function getHeaderRegExp(level){
68-
return new RegExp('^'+ getHeaderHashes(level) +'\\s*([^#\\n\\r]+)[# \t]*$', 'gm');
64+
Parser.prototype.getHeaderRegExp = function(level){
65+
return new RegExp('^'+ this.getHeaderHashes(level) +'\\s*([^#\\n\\r]+)[# \t]*$', 'gm');
6966
}
7067

71-
function getHeaderHashes(level){
72-
level = level != null? level : _headingLevel;
68+
Parser.prototype.getHeaderHashes = function(level){
69+
level = level != null? level : this.headingLevel;
7370
return (new Array(level + 1)).join('#');
7471
}
7572

76-
function getDescription(mdown, fromIndex) {
73+
Parser.prototype.getDescription = function(mdown, fromIndex) {
7774
var desc = mdown.substr(fromIndex);
7875
desc = desc.replace(/^\n+/g, '').split(/\n\n/)[0]; //first paragraph
7976

@@ -82,39 +79,41 @@ function getDescription(mdown, fromIndex) {
8279
return null;
8380
}
8481

85-
desc = exports.parseMdown(desc.replace(/\n+/, ' '))
82+
desc = this.parseMdown(desc.replace(/\n+/, ' '))
8683
.replace(/<\/?p>/g, '') //remove paragraphs
8784
.replace(/<\/?a[^>]*>/g, ''); //remove links since it breaks layout
8885
return desc;
8986
}
9087

91-
function parseContent(mdown, toc){
88+
Parser.prototype.parseContent = function(mdown, toc){
9289

9390
// add deep-links
9491

9592
var i = 0, cur;
9693

97-
mdown = mdown.replace(getHeaderRegExp(), function(str){
94+
mdown = mdown.replace(this.getHeaderRegExp(), function(str){
9895
cur = toc[i++];
9996
return str +' <a href="#'+ cur.href +'" id="'+ cur.href +'" class="deep-link">#</a>';
10097
});
10198

10299
// generate TOC
103100

104-
var tocIndex = mdown.search( new RegExp('^'+ getHeaderHashes() +'[^#]+', 'm') ), //first header
101+
var tocIndex = mdown.search( new RegExp('^'+ this.getHeaderHashes() +'[^#]+', 'm') ), //first header
105102
pre = mdown.substring(0, tocIndex),
106103
post = mdown.substring(tocIndex),
107-
tocContent = getHeaderHashes() +' Table of Contents <a href="#toc" name="toc" class="deep-link">#</a>\n\n';
104+
tocContent = this.getHeaderHashes() +' Table of Contents <a href="#toc" name="toc" class="deep-link">#</a>\n\n';
108105

109106
toc.forEach(function(val, i){
110107
tocContent += ' - ['+ val.name +'](#'+ val.href +')\n';
111108
});
112109

113-
return exports.parseMdown( pre + tocContent + post );
110+
return this.parseMdown( pre + tocContent + post );
114111
}
115112

116113

117-
function getTitle(mdown){
118-
var match = getHeaderRegExp(_headingLevel - 1).exec(mdown); //H1
114+
Parser.prototype.getTitle = function(mdown){
115+
var match = this.getHeaderRegExp(this.headingLevel - 1).exec(mdown); //H1
119116
return match? match[1].trim() : '';
120117
}
118+
119+
module.exports = Parser;

src/js/writter.js

Lines changed: 53 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ var handlebars = require('handlebars'),
33
fs = require('fs'),
44
path = require('path'),
55
wrench = require('wrench'),
6-
parser = require('./parser'),
6+
Parser = require('./parser'),
77
pathProcessor = require('./pathProcessor');
88

99

@@ -14,99 +14,91 @@ var DEFAULT_INCLUDE = '*.mdown,*.md,*.markdown',
1414
DEFAULT_PAGE_TITLE = 'Documentation';
1515

1616

17-
// ---
18-
19-
var _baseTemplatePath,
20-
_docTemplate,
21-
_sidebarTemplate,
22-
_indexTemplate;
17+
var Writter = function(config) {
18+
this.config = config;
19+
this.parser = new Parser(this.config);
20+
}
2321

24-
function compileTemplate(name){
25-
var tmp = path.normalize(_baseTemplatePath +'/'+ name +'.hbs');
22+
Writter.prototype.compileTemplate = function(name){
23+
var tmp = path.normalize(this.baseTemplatePath +'/'+ name +'.hbs');
2624
return handlebars.compile(fs.readFileSync(tmp, 'utf-8'));
2725
}
2826

27+
Writter.prototype.compileAllTemplates = function(){
28+
this.baseTemplatePath = this.config.templatePath || __dirname +'/../template';
2929

30-
function compileAllTemplates(config){
31-
_baseTemplatePath = config.templatePath || __dirname +'/../template';
32-
33-
var key, helpers = config.hbHelpers;
30+
var key, helpers = this.config.hbHelpers;
3431
for (key in helpers){
3532
if (helpers.hasOwnProperty(key)){
3633
handlebars.registerHelper(key, helpers[key]);
3734
}
3835
}
3936

40-
handlebars.registerPartial('header', compileTemplate('header'));
41-
handlebars.registerPartial('footer', compileTemplate('footer'));
37+
handlebars.registerPartial('header', this.compileTemplate('header'));
38+
handlebars.registerPartial('footer', this.compileTemplate('footer'));
4239

43-
_docTemplate = compileTemplate('doc');
44-
_sidebarTemplate = compileTemplate('sidebar');
45-
_indexTemplate = compileTemplate('index');
40+
this.docTemplate = this.compileTemplate('doc');
41+
this.sidebarTemplate = this.compileTemplate('sidebar');
42+
this.indexTemplate = this.compileTemplate('index');
4643
}
4744

48-
49-
// ---
50-
51-
52-
exports.processFiles = function(config){
45+
Writter.prototype.processFiles = function(){
5346
console.log(' Converting files...');
5447

55-
compileAllTemplates(config);
48+
this.compileAllTemplates(this.config);
5649

57-
var toc = processDoc(config),
58-
outputDir = config.outputDir;
50+
var toc = this.processDoc(this.config),
51+
outputDir = this.config.outputDir;
5952

6053
console.log(' Generating Sidebar...');
61-
fs.writeFileSync(path.join(outputDir, 'sidebar_.html'), _sidebarTemplate({
54+
fs.writeFileSync(path.join(outputDir, 'sidebar_.html'), this.sidebarTemplate({
6255
modules : toc,
63-
ctx: config.ctx || {}
56+
ctx: this.config.ctx || {}
6457
}), 'utf-8');
6558

6659
console.log(' Generating Index...');
67-
fs.writeFileSync(path.join(outputDir, 'index.html'), _indexTemplate({
60+
fs.writeFileSync(path.join(outputDir, 'index.html'), this.indexTemplate({
6861
modules : toc,
69-
page_title : config.baseTitle || DEFAULT_PAGE_TITLE,
70-
content : getIndexContent(config),
71-
ctx: config.ctx || {}
62+
page_title : this.config.baseTitle || DEFAULT_PAGE_TITLE,
63+
content : this.getIndexContent(this.config),
64+
ctx: this.config.ctx || {}
7265
}), 'utf-8');
7366

7467
console.log(' Copying Assets...');
75-
var assetsPath = config.assetsPath || path.normalize(_baseTemplatePath +'/assets_');
68+
var assetsPath = this.config.assetsPath || path.normalize(this.baseTemplatePath +'/assets_');
7669
wrench.copyDirSyncRecursive(assetsPath, path.join(outputDir, 'assets_/'));
7770

7871
console.log(' Finished.');
7972
};
8073

81-
82-
function processDoc(config){
83-
74+
Writter.prototype.processDoc = function(){
8475
var toc = [];
76+
var self = this;
8577

86-
getFilesInfos(config).forEach(function(fileInfo){
78+
this.getFilesInfos(this.config).forEach(function(fileInfo){
8779

88-
if (config.mapOutName) {
89-
fileInfo.output = config.mapOutName(fileInfo.output);
80+
if (self.config.mapOutName) {
81+
fileInfo.output = self.config.mapOutName(fileInfo.output);
9082
}
9183

9284
pathProcessor.processFile(fileInfo, function(content){
93-
var parseResult = parser.parseDoc(content, config.headingLevel),
94-
fileName = fileInfo.output.replace(config.outputDir, '').replace(/^[\/\\]/, ''),
95-
moduleName = config.mapTocName? config.mapTocName(fileName, parseResult.toc, parseResult.title) : fileName.replace('.html', '');
85+
var parseResult = self.parser.parseDoc(content, self.config.headingLevel),
86+
fileName = fileInfo.output.replace(self.config.outputDir, '').replace(/^[\/\\]/, ''),
87+
moduleName = self.config.mapTocName? self.config.mapTocName(fileName, parseResult.toc, parseResult.title) : fileName.replace('.html', '');
9688

9789
toc.push({
9890
'file' : fileName,
9991
'module' : moduleName,
10092
'toc' : parseResult.toc
10193
});
10294

103-
var relativeRoot = path.relative( fileInfo.output.replace(/[\/\\][^\/\\]+$/, '/'), config.outputDir );
95+
var relativeRoot = path.relative( fileInfo.output.replace(/[\/\\][^\/\\]+$/, '/'), self.config.outputDir );
10496

105-
return _docTemplate({
97+
return self.docTemplate({
10698
root_path : relativeRoot? relativeRoot +'/' : '',
107-
content : handlebars.compile(parseResult.html)({ctx: config.ctx}),
108-
page_title : parseResult.title +' : '+ (config.baseTitle || DEFAULT_PAGE_TITLE),
109-
ctx: config.ctx || {}
99+
content : handlebars.compile(parseResult.html)({ctx: self.config.ctx}),
100+
page_title : parseResult.title +' : '+ (self.config.baseTitle || DEFAULT_PAGE_TITLE),
101+
ctx: self.config.ctx || {}
110102
});
111103
});
112104
console.log(' processed: '+ fileInfo.input +' > '+ fileInfo.output);
@@ -115,36 +107,35 @@ function processDoc(config){
115107
return toc;
116108
}
117109

118-
119-
120-
function getFilesInfos(config){
110+
Writter.prototype.getFilesInfos = function(){
121111
var files = pathProcessor.getFilesPaths({
122-
inputDir : config.inputDir,
123-
outputDir : config.outputDir,
112+
inputDir : this.config.inputDir,
113+
outputDir : this.config.outputDir,
124114
outputExt : '.html',
125-
include : config.include || DEFAULT_INCLUDE,
126-
exclude : config.exclude
115+
include : this.config.include || DEFAULT_INCLUDE,
116+
exclude : this.config.exclude
127117
});
128118

129-
if (config.filterFiles) {
130-
files = files.filter(config.filterFiles);
119+
if (this.config.filterFiles) {
120+
files = files.filter(this.config.filterFiles);
131121
}
132122

133123
return files;
134124
}
135125

136-
137-
function generateFile(toc, template, outputFile, title){
126+
Writter.prototype.generateFile = function(toc, template, outputFile, title){
138127
var content = template({
139128
modules : toc,
140129
page_title : title || ''
141130
});
142131
fs.writeFileSync(outputFile, content, 'utf-8');
143132
}
144133

145-
function getIndexContent(config){
146-
if (config.indexContentPath && !config.indexContent) {
147-
config.indexContent = handlebars.compile(parser.parseMdown( fs.readFileSync(config.indexContentPath, 'utf-8') ))({ctx: config.ctx});
134+
Writter.prototype.getIndexContent = function(){
135+
if (this.config.indexContentPath && !this.config.indexContent) {
136+
this.config.indexContent = handlebars.compile(this.parser.parseMdown( fs.readFileSync(this.config.indexContentPath, 'utf-8') ))({ctx: this.config.ctx});
148137
}
149-
return config.indexContent || '';
138+
return this.config.indexContent || '';
150139
}
140+
141+
module.exports = Writter;

0 commit comments

Comments
 (0)