77 lines
2.4 KiB
JavaScript
77 lines
2.4 KiB
JavaScript
|
'use strict';
|
||
|
|
||
|
Ox.SourceViewer = function(options, self) {
|
||
|
|
||
|
self = self || {};
|
||
|
var that = Ox.Container({}, self)
|
||
|
.defaults({
|
||
|
file: '',
|
||
|
replace: []
|
||
|
})
|
||
|
.options(options)
|
||
|
.addClass('OxSourceViewer');
|
||
|
|
||
|
self.replace = Ox.merge(
|
||
|
[[
|
||
|
// removes indentation inside <pre> tags
|
||
|
/<pre>([\s\S]+)<\/pre>/g,
|
||
|
function(pre, text) {
|
||
|
var lines = trim(text).split('\n'),
|
||
|
indent = Ox.min(lines.map(function(line) {
|
||
|
var match = line.match(/^\s+/);
|
||
|
return match ? match[0].length : 0;
|
||
|
}));
|
||
|
return '<pre>' + lines.map(function(line) {
|
||
|
return line.substr(indent);
|
||
|
}).join('\n') + '</pre>';
|
||
|
}
|
||
|
]],
|
||
|
self.options.replace
|
||
|
);
|
||
|
Ox.print('RE', self.replace)
|
||
|
|
||
|
self.$table = $('<table>').appendTo(that.$content);
|
||
|
|
||
|
Ox.get(self.options.file, function(source) {
|
||
|
var sections = [{comment: '', code: ''}];
|
||
|
Ox.tokenize(source).forEach(function(token, i) {
|
||
|
var text = source.substr(token.offset, token.length),
|
||
|
type = token.type == 'comment' ? 'comment' : 'code';
|
||
|
if (type == 'comment') {
|
||
|
i && sections.push({comment: '', code: ''});
|
||
|
text = /^\/\*/.test(text)
|
||
|
? Ox.sub(text, 2, -2)
|
||
|
: Ox.sub(text, 2);
|
||
|
self.replace.forEach(function(replace) {
|
||
|
text = text.replace(replace[0], replace[1]);
|
||
|
});
|
||
|
}
|
||
|
Ox.last(sections)[type] += text;
|
||
|
});
|
||
|
sections.forEach(function(section) {
|
||
|
var $section = $('<tr>'),
|
||
|
$comment = $('<td>')
|
||
|
.addClass('OxComment')
|
||
|
.html(trim(section.comment)),
|
||
|
$code = $('<td>')
|
||
|
.addClass('OxCode')
|
||
|
.append(
|
||
|
Ox.SyntaxHighlighter({
|
||
|
source: trim(section.code)
|
||
|
})
|
||
|
)
|
||
|
$section
|
||
|
.append($comment)
|
||
|
.append($code)
|
||
|
.appendTo(self.$table);
|
||
|
});
|
||
|
});
|
||
|
|
||
|
function trim(str) {
|
||
|
// removes leading or trailing empty line
|
||
|
return str.replace(/^\s*\n/, '').replace(/\n\s*$/, '');
|
||
|
}
|
||
|
|
||
|
return that;
|
||
|
|
||
|
};
|