Compare commits

...

31 Commits

Author SHA1 Message Date
Samy Pessé 3388be9db6 Update app.js 2015-10-27 23:11:55 +01:00
Samy Pessé 9b89319820 Bump version to 2.5.1 2015-10-27 23:11:31 +01:00
Samy Pessé ad34089df5 Merge changelog for 2.5.0 2015-10-27 23:10:29 +01:00
Samy Pessé 7a4c6bc326 Fix calcul of root in gitbook.state when serving index.html as / 2015-10-27 18:44:04 +01:00
Samy Pessé 6ab386ae35 Bump version to 2.5.0 2015-10-27 13:25:52 +01:00
Samy Pessé 0abbfde912 Add chapterTitle to app build 2015-10-27 12:19:54 +01:00
Samy Pessé 0521defb63 Add 'chapterTitle' to gitbook.state api 2015-10-27 12:18:04 +01:00
Samy Pessé ea4d96610f Compatibility for require of plugins 2015-10-24 21:36:17 +02:00
Samy Pessé 4bc56564b4 Comment gitbook.state api 2015-10-22 16:12:21 +02:00
Samy Pessé 013f7f09da Add gitbook.state.filepath
Fix gitbook.state.root
2015-10-22 16:11:05 +02:00
Samy Pessé f082de1f92 Bump version to 2.5.0-beta.7 2015-10-22 13:52:19 +02:00
Samy Pessé ad39dc8c0c Update app.js 2015-10-22 13:50:05 +02:00
Samy Pessé 481a76319f Provide gitbook.state.root to plugins 2015-10-22 13:49:28 +02:00
Samy Pessé 27a43d5aea Merge pull request #986 from GitbookIO/fix/heading_ids
Normalize ID for headings
2015-10-21 18:05:40 +02:00
Samy Pessé df1d5a0680 Correctly generate id if none found 2015-10-21 17:58:06 +02:00
Samy Pessé 722109faf0 Update gitbook-parsers@0.8.7 2015-10-21 16:22:47 +02:00
Samy Pessé d4dca7736a Update gitbook-parsers@0.8.6 2015-10-21 16:15:56 +02:00
Samy Pessé 4e90becd52 Use Arial as default font 2015-10-21 15:54:45 +02:00
Samy Pessé 26890e94eb Bump version to 2.5.0-beta.6 2015-10-20 18:20:44 +02:00
Samy Pessé 55c83f9a59 Use helvetica by default for pdf 2015-10-20 18:09:51 +02:00
Samy Pessé b837d82878 Fix default style for pdf footer and header 2015-10-20 18:02:23 +02:00
Samy Pessé cbdcdb1e0f Fix #974: correctly handle query in image urls 2015-10-20 17:22:01 +02:00
Samy Pessé 4fea85289e Merge pull request #983 from GitbookIO/fix/982
Fix #982: correctly handle templating in imported content
2015-10-20 17:09:15 +02:00
Samy Pessé ba5f9132c9 Fix #982: fix shortcuts for included templates 2015-10-20 17:08:44 +02:00
Samy Pessé 991681daa2 Add failing test for #982 2015-10-20 16:38:48 +02:00
Samy Pessé 2faf53e16b Bump version to 2.5.0-beta.5 2015-10-16 13:48:27 +02:00
Samy Pessé 5430ed99de Update gitbook-parsers@0.8.5 2015-10-16 13:47:09 +02:00
Samy Pessé fef4dfd05e Fix position of sidebar toggle button 2015-10-14 13:35:03 +02:00
Samy Pessé 05943db3b5 Bump version to 2.5.0-beta.4 2015-10-14 13:16:49 +02:00
Samy Pessé 682fabd1ef Fix position of glossary icon relative to sidebar toggler 2015-10-14 13:15:36 +02:00
Samy Pessé ee8ccc6d7e Fix legacy properties book.options.input, ... 2015-10-14 12:31:37 +02:00
22 changed files with 725 additions and 189 deletions
+11 -6
View File
@@ -2,13 +2,10 @@
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## 2.5.0-beta.3
- Fix installation of plugins when using a pre-release
## 2.5.1
- Fix calcul of `gitbook.state.root` when serving HTML index as `/`
## 2.5.0-beta.2
- Fix support for pre-releases
## 2.5.0-beta.1
## 2.5.0
- Font settings, sharing and search are externalized as default plugins
- Plugins can define a configuration schema in the manifest, this schema will be used to validate configuration during build
- New Node.js API for plugin: `book.formatString(type, content)`
@@ -17,6 +14,14 @@ This project adheres to [Semantic Versioning](http://semver.org/).
- Cleaner table of contents for ebooks
- Support for RTL in ebook's table of contents
- Better colors for mobi (links and code blocks)
- Fix installation of plugins when using a pre-release
- Fix support for pre-releases
- Update asciidoc parser to remove git dependency
- Fix templating in imported content
- Fix querystring in image urls
- Normalize heading IDs like GitHub
- Use Arial as default font for PDFs
- Add `root`, `chapterTitle` and `filepath` to `gitbook.state` JS API
## 2.4.3
- Add ukrainian translation (`uk`)
+2 -1
View File
@@ -75,8 +75,9 @@ module.exports = {
// Add page numbers to the bottom of every page
'pageNumbers': false,
// Font size for the file content
// Font for the file content
'fontSize': 12,
'fontFamily': 'Arial',
// Paper size for the pdf
// Choices are [u’a0’, u’a1’, u’a2’, u’a3’, u’a4’, u’a5’, u’a6’, u’b0’, u’b1’, u’b2’, u’b3’, u’b4’, u’b5’, u’b6’, u’legal’, u’letter’]
+23 -23
View File
@@ -84,31 +84,8 @@ function normalizePluginsList(plugins, addDefaults) {
}
var Configuration = function(book, options) {
var that = this;
this.book = book;
this.replace(options);
// options.input == book.root
Object.defineProperty(this.options, 'input', {
get: function () {
return that.book.root;
}
});
// options.originalInput == book.parent.root
Object.defineProperty(this.options, 'originalInput', {
get: function () {
return that.book.parent? that.book.parent.root : undefined;
}
});
// options.originalOutput == book.parent.options.output
Object.defineProperty(this.options, 'originalOutput', {
get: function () {
return that.book.parent? that.book.parent.options.output : undefined;
}
});
};
// Read and parse the configuration
@@ -171,8 +148,31 @@ Configuration.prototype.extend = function(options) {
// Replace the whole configuration
Configuration.prototype.replace = function(options) {
var that = this;
this.options = _.cloneDeep(DEFAULT_CONFIG);
this.options = _.merge(this.options, options || {});
// options.input == book.root
Object.defineProperty(this.options, 'input', {
get: function () {
return that.book.root;
}
});
// options.originalInput == book.parent.root
Object.defineProperty(this.options, 'originalInput', {
get: function () {
return that.book.parent? that.book.parent.root : undefined;
}
});
// options.originalOutput == book.parent.options.output
Object.defineProperty(this.options, 'originalOutput', {
get: function () {
return that.book.parent? that.book.parent.options.output : undefined;
}
});
};
// Dump configuration as json object
+20 -10
View File
@@ -1,15 +1,19 @@
var path = require("path");
var nunjucks = require("nunjucks");
var _ = require('lodash');
var path = require('path');
var nunjucks = require('nunjucks');
var git = require("./utils/git");
var fs = require("./utils/fs");
var pathUtil = require("./utils/path");
var git = require('./utils/git');
var fs = require('./utils/fs');
var pathUtil = require('./utils/path');
// The loader should handle relative and git url
var BookLoader = nunjucks.Loader.extend({
async: true,
init: function(book) {
init: function(book, opts) {
this.opts = _.defaults(opts || {}, {
interpolate: _.identity
});
this.book = book;
},
@@ -20,14 +24,20 @@ var BookLoader = nunjucks.Loader.extend({
.then(function(filepath) {
// Is local file
if (!filepath) filepath = path.resolve(fileurl);
else that.book.log.debug.ln("resolve from git", fileurl, "to", filepath);
else that.book.log.debug.ln('resolve from git', fileurl, 'to', filepath);
// Read file from absolute path
return fs.readFile(filepath)
.then(function(source) {
return that.opts.interpolate(filepath, source.toString());
})
.then(function(source) {
return {
src: source.toString(),
path: filepath
src: source,
path: filepath,
// We disable cache sincde content is modified (shortcuts, ...)
noCache: true
};
});
})
@@ -53,7 +63,7 @@ var BookLoader = nunjucks.Loader.extend({
return path.resolve(path.dirname(from), to);
},
// Handle all files as relative, so that nunjucks pass responsability to "resolve"
// Handle all files as relative, so that nunjucks pass responsability to 'resolve'
// Only git urls are considered as absolute
isRelative: function(filename) {
return !git.checkUrl(filename);
+3 -2
View File
@@ -46,7 +46,7 @@ Generator.prototype.writeSummary = function() {
Generator.prototype.getPDFTemplate = function(id) {
var tpl = this.options.pdf[id+'Template'];
var defaultTpl = path.resolve(this.options.theme, 'templates/ebook/'+id+'.html');
var defaultCSS = path.resolve(this.options.theme, 'assets/pdf.css');
var defaultCSS = path.resolve(this.options.theme, 'assets/ebook/pdf.css');
// Default template from theme
if (!tpl && fs.existsSync(defaultTpl)) {
@@ -123,7 +123,8 @@ Generator.prototype.finish = function() {
'--paper-size': String(pdfOptions.paperSize),
'--pdf-page-numbers': Boolean(pdfOptions.pageNumbers),
'--pdf-header-template': that.getPDFTemplate('header'),
'--pdf-footer-template': that.getPDFTemplate('footer')
'--pdf-footer-template': that.getPDFTemplate('footer'),
'--pdf-sans-family': String(pdfOptions.fontFamily)
});
} else if (that.ebookFormat == 'epub') {
_.extend(_options, {
+60 -34
View File
@@ -1,12 +1,14 @@
var _ = require("lodash");
var Q = require("q");
var nunjucks = require("nunjucks");
var escapeStringRegexp = require("escape-string-regexp");
var _ = require('lodash');
var Q = require('q');
var path = require('path');
var nunjucks = require('nunjucks');
var parsers = require('gitbook-parsers');
var escapeStringRegexp = require('escape-string-regexp');
var batch = require("./utils/batch");
var pkg = require("../package.json");
var defaultBlocks = require("./blocks");
var BookLoader = require("./conrefs_loader");
var batch = require('./utils/batch');
var pkg = require('../package.json');
var defaultBlocks = require('./blocks');
var BookLoader = require('./conrefs_loader');
// Normalize result from a block
function normBlockResult(blk) {
@@ -16,24 +18,37 @@ function normBlockResult(blk) {
var TemplateEngine = function(book) {
var that = this;
this.book = book;
this.log = this.book.log;
// Template loader
this.loader = new BookLoader(book, {
// Replace shortcuts in imported files
interpolate: function(filepath, source) {
var parser = parsers.get(path.extname(filepath));
var type = parser? parser.name : null;
return that.applyShortcuts(type, source);
}
});
// Nunjucks env
this.env = new nunjucks.Environment(
new BookLoader(book),
this.loader,
{
// Escaping is done after by the markdown parser
autoescape: false,
// Tags
tags: {
blockStart: "{%",
blockEnd: "%}",
variableStart: "{{",
variableEnd: "}}",
commentStart: "{###",
commentEnd: "###}"
blockStart: '{%',
blockEnd: '%}',
variableStart: '{{',
variableEnd: '}}',
commentStart: '{###',
commentEnd: '###}'
}
}
);
@@ -60,20 +75,20 @@ TemplateEngine.prototype.processBlock = function(blk) {
parse: false,
post: undefined
});
blk.id = _.uniqueId("blk");
blk.id = _.uniqueId('blk');
var toAdd = (!blk.parse) || (blk.post !== undefined);
// Add to global map
if (toAdd) this.blockBodies[blk.id] = blk;
//Parsable block, just return it
// Parsable block, just return it
if (blk.parse) {
return blk.body;
}
// Return it as a position marker
return "@%@"+blk.id+"@%@";
return '@%@'+blk.id+'@%@';
};
// Replace position markers of blocks by body after processing
@@ -110,11 +125,13 @@ TemplateEngine.prototype.bindContext = function(func) {
TemplateEngine.prototype.addFilter = function(filterName, func) {
try {
this.env.getFilter(filterName);
this.log.warn.ln("conflict in filters, \""+filterName+"\" is already set");
this.log.warn.ln('conflict in filters, \''+filterName+'\' is already set');
return false;
} catch(e) {}
} catch(e) {
// Filter doesn't exist
}
this.log.debug.ln("add filter \""+filterName+"\"");
this.log.debug.ln('add filter \''+filterName+'\'');
this.env.addFilter(filterName, this.bindContext(function() {
var ctx = this;
var args = Array.prototype.slice.apply(arguments);
@@ -138,7 +155,7 @@ TemplateEngine.prototype.addFilters = function(filters) {
// Return nunjucks extension name of a block
TemplateEngine.prototype.blockExtName = function(name) {
return "Block"+name+"Extension";
return 'Block'+name+'Extension';
};
// Test if a block is defined
@@ -167,7 +184,7 @@ TemplateEngine.prototype.addBlock = function(name, block) {
block = _.defaults(block || {}, {
shortcuts: [],
end: "end"+name,
end: 'end'+name,
process: _.identity,
blocks: []
});
@@ -175,13 +192,13 @@ TemplateEngine.prototype.addBlock = function(name, block) {
extName = this.blockExtName(name);
if (this.hasBlock(name) && !defaultBlocks[name]) {
this.log.warn.ln("conflict in blocks, \""+name+"\" is already defined");
this.log.warn.ln('conflict in blocks, \''+name+'\' is already defined');
}
// Cleanup previous block
this.removeBlock(name);
this.log.debug.ln("add block \""+name+"\"");
this.log.debug.ln('add block \''+name+'\'');
this.blocks[name] = block;
Ext = function () {
@@ -238,7 +255,7 @@ TemplateEngine.prototype.addBlock = function(name, block) {
bodies.push(subbodies[blockName][0].body);
});
return new nodes.CallExtensionAsync(this, "run", args, bodies);
return new nodes.CallExtensionAsync(this, 'run', args, bodies);
};
this.run = function(context) {
@@ -287,7 +304,7 @@ TemplateEngine.prototype.addBlock = function(name, block) {
// Add shortcuts
if (!_.isArray(block.shortcuts)) block.shortcuts = [block.shortcuts];
_.each(block.shortcuts, function(shortcut) {
this.log.debug.ln("add template shortcut from \""+shortcut.start+"\" to block \""+name+"\" for parsers ", shortcut.parsers);
this.log.debug.ln('add template shortcut from \''+shortcut.start+'\' to block \''+name+'\' for parsers ', shortcut.parsers);
this.shortcuts.push({
block: name,
parsers: shortcut.parsers,
@@ -314,7 +331,7 @@ TemplateEngine.prototype.applyBlock = function(name, blk, ctx) {
var func, block, r;
block = this.blocks[name];
if (!block) throw new Error("Block not found \""+name+"\"");
if (!block) throw new Error('Block not found \''+name+'\'');
if (_.isString(blk)) {
blk = {
body: blk
@@ -339,14 +356,19 @@ TemplateEngine.prototype.applyBlock = function(name, blk, ctx) {
TemplateEngine.prototype._applyShortcut = function(parser, content, shortcut) {
if (!_.contains(shortcut.parsers, parser)) return content;
var regex = new RegExp(
escapeStringRegexp(shortcut.start) + "([\\s\\S]*?[^\\$])" + escapeStringRegexp(shortcut.end),
"g"
escapeStringRegexp(shortcut.start) + '([\\s\\S]*?[^\\$])' + escapeStringRegexp(shortcut.end),
'g'
);
return content.replace(regex, function(all, match) {
return "{% "+shortcut.tag.start+" %}"+ match + "{% "+shortcut.tag.end+" %}";
return '{% '+shortcut.tag.start+' %}'+ match + '{% '+shortcut.tag.end+' %}';
});
};
// Apply all shortcuts to some template string
TemplateEngine.prototype.applyShortcuts = function(type, content) {
return _.reduce(this.shortcuts, _.partial(this._applyShortcut.bind(this), type), content);
};
// Render a string from the book
TemplateEngine.prototype.renderString = function(content, context, options) {
context = _.extend({}, context, {
@@ -367,14 +389,18 @@ TemplateEngine.prototype.renderString = function(content, context, options) {
type: null
});
if (options.path) options.path = this.book.resolve(options.path);
if (!options.type && options.path) {
var parser = parsers.get(path.extname(options.path));
options.type = parser? parser.name : null;
}
// Replace shortcuts
content = _.reduce(this.shortcuts, _.partial(this._applyShortcut.bind(this), options.type), content);
content = this.applyShortcuts(options.type, content);
return Q.nfcall(this.env.renderString.bind(this.env), content, context, options)
.fail(function(err) {
if (_.isString(err)) err = new Error(err);
err.message = err.message.replace(/^Error: /, "");
err.message = err.message.replace(/^Error: /, '');
throw err;
});
@@ -398,7 +424,7 @@ TemplateEngine.prototype.renderPage = function(page) {
return that.book.statFile(page.path)
.then(function(stat) {
var context = {
var context = {
// infos about the file
file: {
path: page.path,
+14 -6
View File
@@ -6,6 +6,7 @@ var cheerio = require('cheerio');
var domSerializer = require('dom-serializer');
var request = require('request');
var crc = require('crc');
var slug = require('github-slugid');
var links = require('./links');
var imgUtils = require('./images');
@@ -14,18 +15,18 @@ var batch = require('./batch');
var parsableExtensions = require('gitbook-parsers').extensions;
// Map of images that have been converted
var imgConversionCache = {};
// Render a cheerio dom as html
var renderDom = function($, dom, options) {
function renderDom($, dom, options) {
if (!dom && $._root && $._root.children) {
dom = $._root.children;
}
options = options|| dom.options || $._options;
return domSerializer(dom, options);
};
// Map of images that have been converted
var imgConversionCache = {};
}
function replaceText($, el, search, replace, text_only ) {
return $(el).each(function(){
@@ -114,6 +115,13 @@ function normalizeHtml(src, options) {
});
}
// Generate ID for headings
$('h1,h2,h3,h4,h5,h6').each(function() {
if ($(this).attr('id')) return;
$(this).attr('id', slug($(this).text()));
});
// Find images to normalize
$('img').each(function() {
var origin;
@@ -132,7 +140,7 @@ function normalizeHtml(src, options) {
// If image is external and ebook, then downlaod the images
if (isExternal) {
origin = src;
src = '/'+crc.crc32(origin).toString(16)+path.extname(origin);
src = '/'+crc.crc32(origin).toString(16)+path.extname(url.parse(origin).pathname);
src = links.toAbsolute(src, options.base, options.output);
isExternal = false;
}
+4 -3
View File
@@ -1,6 +1,6 @@
{
"name": "gitbook",
"version": "2.5.0-beta.3",
"version": "2.5.1",
"homepage": "https://www.gitbook.com",
"description": "Library and cmd utility to generate GitBooks",
"main": "lib/index.js",
@@ -11,7 +11,7 @@
"resolve": "0.6.3",
"fs-extra": "0.16.5",
"fstream-ignore": "1.0.2",
"gitbook-parsers": "0.8.4",
"gitbook-parsers": "0.8.7",
"gitbook-plugin-highlight": "1.0.3",
"gitbook-plugin-sharing": "1.0.1",
"gitbook-plugin-search": "1.0.2",
@@ -39,7 +39,8 @@
"juice": "1.5.0",
"jsonschema": "1.0.2",
"json-schema-defaults": "0.1.1",
"merge-defaults": "0.2.1"
"merge-defaults": "0.2.1",
"github-slugid": "1.0.0"
},
"devDependencies": {
"eslint": "1.5.0",
+3
View File
@@ -1,5 +1,8 @@
# Readme
<p id="test-plugin-block-shortcuts-1">$$test_block1$$</p>
<p id="test-plugin-block-shortcuts-2">{% include "./block.md" %}</p>
### Relative
<p id="t1">{% include "./hello.md" %}</p>
+1
View File
@@ -0,0 +1 @@
$$test_block2$$
+3
View File
@@ -0,0 +1,3 @@
# Hello World
## Hello {#hello-custom}
View File
+22 -22
View File
@@ -1,63 +1,63 @@
var path = require("path");
var fs = require("fs");
var path = require('path');
var fs = require('fs');
var Plugin = require("../lib/plugin");
var PLUGINS_ROOT = path.resolve(__dirname, "plugins");
var Plugin = require('../lib/plugin');
var PLUGINS_ROOT = path.resolve(__dirname, 'plugins');
describe("Code Highlighting", function () {
describe('Code Highlighting', function () {
var book, PAGE;
before(function() {
return books.generate("highlight", "website", {
return books.generate('highlight', 'website', {
prepare: function(_book) {
book = _book;
var plugin = new Plugin(book, "replace_highlight");
plugin.load("./replace_highlight", PLUGINS_ROOT);
var plugin = new Plugin(book, 'replace_highlight');
plugin.load('./replace_highlight', PLUGINS_ROOT);
book.plugins.load(plugin);
}
})
.then(function() {
PAGE = fs.readFileSync(
path.join(book.options.output, "index.html"),
{ encoding: "utf-8" }
path.join(book.options.output, 'index.html'),
{ encoding: 'utf-8' }
);
});
});
it("should correctly replace highlighting", function() {
it('should correctly replace highlighting', function() {
PAGE.should.be.html({
"code": {
'code': {
index: 0,
text: "code_test 1\n_code"
text: 'code_test 1\n_code'
}
});
});
it("should correctly replace highlighting with language", function() {
it('should correctly replace highlighting with language', function() {
PAGE.should.be.html({
"code": {
'code': {
index: 1,
text: "lang_test 2\n_lang"
text: 'lang_test 2\n_lang'
}
});
});
it("should correctly replace highlighting for inline code", function() {
it('should correctly replace highlighting for inline code', function() {
PAGE.should.be.html({
"code": {
'code': {
index: 2,
text: "code_test 3_code"
text: 'code_test 3_code'
}
});
});
it("should correctly replace highlighting for inline code with html tags", function() {
it('should correctly replace highlighting for inline code with html tags', function() {
PAGE.should.be.html({
"code": {
'code': {
index: 3,
text: "code_<test>_code"
text: 'code_<test>_code'
}
});
});
+21 -21
View File
@@ -1,66 +1,66 @@
var fs = require("fs");
var path = require("path");
var fs = require('fs');
var path = require('path');
describe("ConRefs", function () {
describe('ConRefs', function () {
var book, readme;
before(function() {
return books.generate("conrefs", "website")
return books.generate('conrefs', 'website')
.then(function(_book) {
book = _book;
readme = fs.readFileSync(
path.join(book.options.output, "index.html"),
{ encoding: "utf-8" }
path.join(book.options.output, 'index.html'),
{ encoding: 'utf-8' }
);
});
});
it("should handle local references", function() {
it('should handle local references', function() {
readme.should.be.html({
".page-inner p#t1": {
'.page-inner p#t1': {
count: 1,
text: "Hello World",
text: 'Hello World',
trim: true
}
});
});
it("should handle local references with absolute paths", function() {
it('should handle local references with absolute paths', function() {
readme.should.be.html({
".page-inner p#t2": {
'.page-inner p#t2': {
count: 1,
text: "Hello World",
text: 'Hello World',
trim: true
}
});
});
it("should correctly include file from git reference", function() {
it('should correctly include file from git reference', function() {
readme.should.be.html({
".page-inner p#t3": {
'.page-inner p#t3': {
count: 1,
text: "Hello from git",
text: 'Hello from git',
trim: true
}
});
});
it("should correctly handle deep include in git reference", function() {
it('should correctly handle deep include in git reference', function() {
readme.should.be.html({
".page-inner p#t4": {
'.page-inner p#t4': {
count: 1,
text: "First Hello. Hello from git",
text: 'First Hello. Hello from git',
trim: true
}
});
});
it("should correctly handle absolute include in git reference", function() {
it('should correctly handle absolute include in git reference', function() {
readme.should.be.html({
".page-inner p#t5": {
'.page-inner p#t5': {
count: 1,
text: "First Hello. Hello from git",
text: 'First Hello. Hello from git',
trim: true
}
});
+37
View File
@@ -0,0 +1,37 @@
var path = require('path');
var fs = require('fs');
describe('Headings', function () {
var book, PAGE;
before(function() {
return books.generate('headings', 'website')
.then(function(_book) {
book = _book;
PAGE = fs.readFileSync(
path.join(book.options.output, 'index.html'),
{ encoding: 'utf-8' }
);
});
});
describe('IDs', function() {
it('should correctly generate an ID', function() {
PAGE.should.be.html({
'h1#hello-world': {
count: 1
}
});
});
it('should correctly accept custom ID', function() {
PAGE.should.be.html({
'h2#hello-custom': {
count: 1
}
});
});
});
});
+23 -17
View File
@@ -1,13 +1,13 @@
var os = require("os");
var path = require("path");
var Q = require("q");
var _ = require("lodash");
var os = require('os');
var path = require('path');
var Q = require('q');
var _ = require('lodash');
var fsUtil = require("../lib/utils/fs");
var Book = require("../").Book;
var LOG_LEVELS = require("../").LOG_LEVELS;
var fsUtil = require('../lib/utils/fs');
var Book = require('../').Book;
var LOG_LEVELS = require('../').LOG_LEVELS;
require("./assertions");
require('./assertions');
var BOOKS = {};
@@ -20,7 +20,7 @@ function generateBook(bookId, test, opts) {
prepare: function() {}
});
return parseBook(bookId, test)
return parseBook(bookId, test, opts)
.then(function(book) {
return Q(opts.prepare(book))
@@ -32,21 +32,27 @@ function generateBook(bookId, test, opts) {
}
// Generate and return a book
function parseBook(bookId, test) {
test = test || "website";
BOOKS[bookId] = BOOKS[bookId] || {};
if (BOOKS[bookId][test]) return Q(BOOKS[bookId][test]);
function parseBook(bookId, test, opts) {
opts = _.defaults(opts || {}, {
testId: ''
});
BOOKS[bookId][test] = new Book(path.resolve(__dirname, "books", bookId), {
test = test || 'website';
var testId = [test, opts.testId].join('-');
BOOKS[bookId] = BOOKS[bookId] || {};
if (BOOKS[bookId][testId]) return Q(BOOKS[bookId][testId]);
BOOKS[bookId][testId] = new Book(path.resolve(__dirname, 'books', bookId), {
logLevel: LOG_LEVELS.DISABLED,
config: {
output: path.resolve(TMPDIR, bookId+"-"+test)
output: path.resolve(TMPDIR, bookId+'-'+testId)
}
});
return BOOKS[bookId][test].parse()
return BOOKS[bookId][testId].parse()
.then(function() {
return BOOKS[bookId][test];
return BOOKS[bookId][testId];
});
}
+41 -6
View File
@@ -1,4 +1,5 @@
var _ = require('lodash');
var fs = require('fs');
var should = require('should');
var path = require('path');
@@ -193,15 +194,49 @@ describe('Plugins', function () {
});
});
it('should correctly accept shortcuts', function() {
return testTpl('$$hello$$', {}, {
type: 'markdown'
})
.then(function(content) {
content.should.equal('testhellotest');
describe('Shortcuts', function() {
it('should correctly accept shortcuts', function() {
return testTpl('$$hello$$', {}, {
type: 'markdown'
})
.then(function(content) {
content.should.equal('testhellotest');
});
});
it('should correctly apply shortcuts to included file', function() {
return books.generate('conrefs', 'website', {
testId: 'include-plugins',
prepare: function(bookConref) {
plugin = new Plugin(bookConref, 'blocks');
plugin.load('./blocks', PLUGINS_ROOT);
return bookConref.plugins.load(plugin);
}
})
.then(function(bookConref) {
var readme = fs.readFileSync(
path.join(bookConref.options.output, 'index.html'),
{ encoding: 'utf-8' }
);
readme.should.be.html({
'.page-inner p#test-plugin-block-shortcuts-1': {
count: 1,
text: 'testtest_block1test',
trim: true
},
'.page-inner p#test-plugin-block-shortcuts-2': {
count: 1,
text: 'testtest_block2test',
trim: true
}
});
});
});
});
it('should correctly extend template blocks with defined end', function() {
return testTpl('{% test2 %}hello{% endtest2end %}')
.then(function(content) {
+388 -28
View File
@@ -1,4 +1,325 @@
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function(p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function(path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function(path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function(path) {
return splitPath(path)[3];
};
function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
}).call(this,require('_process'))
},{"_process":2}],2:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],3:[function(require,module,exports){
(function (global){
/*! https://mths.be/punycode v1.3.2 by @mathias */
;(function(root) {
@@ -532,7 +853,7 @@
}(this));
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],2:[function(require,module,exports){
},{}],4:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
@@ -618,7 +939,7 @@ var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
},{}],3:[function(require,module,exports){
},{}],5:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
@@ -705,13 +1026,13 @@ var objectKeys = Object.keys || function (obj) {
return res;
};
},{}],4:[function(require,module,exports){
},{}],6:[function(require,module,exports){
'use strict';
exports.decode = exports.parse = require('./decode');
exports.encode = exports.stringify = require('./encode');
},{"./decode":2,"./encode":3}],5:[function(require,module,exports){
},{"./decode":4,"./encode":5}],7:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
@@ -1420,7 +1741,7 @@ function isNullOrUndefined(arg) {
return arg == null;
}
},{"punycode":1,"querystring":4}],6:[function(require,module,exports){
},{"punycode":3,"querystring":6}],8:[function(require,module,exports){
/*!
* jQuery JavaScript Library v2.1.4
* http://jquery.com/
@@ -10632,7 +10953,7 @@ return jQuery;
}));
},{}],7:[function(require,module,exports){
},{}],9:[function(require,module,exports){
(function (global){
/**
* @license
@@ -22987,7 +23308,7 @@ return jQuery;
}.call(this));
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],8:[function(require,module,exports){
},{}],10:[function(require,module,exports){
/*global define:false */
/**
* Copyright 2015 Craig Campbell
@@ -24010,7 +24331,7 @@ return jQuery;
}
}) (window, document);
},{}],9:[function(require,module,exports){
},{}],11:[function(require,module,exports){
var $ = require('jquery');
function toggleDropdown(e) {
@@ -24037,13 +24358,13 @@ module.exports = {
};
},{"jquery":6}],10:[function(require,module,exports){
},{"jquery":8}],12:[function(require,module,exports){
var $ = require('jquery');
module.exports = $({});
},{"jquery":6}],11:[function(require,module,exports){
},{"jquery":8}],13:[function(require,module,exports){
var $ = require('jquery');
var _ = require('lodash');
@@ -24073,6 +24394,7 @@ function start(config) {
// Add action to toggle sidebar
toolbar.createButton({
index: 0,
icon: 'fa fa-align-justify',
onClick: function(e) {
e.preventDefault();
@@ -24104,7 +24426,7 @@ var gitbook = {
// Modules mapping for plugins
var MODULES = {
'gitbook': gitbook,
'jQuery': $,
'jquery': $,
'lodash': _
};
@@ -24113,6 +24435,7 @@ window.$ = $;
window.jQuery = $;
window.require = function(mods, fn) {
mods = _.map(mods, function(mod) {
mod = mod.toLowerCase();
if (!MODULES[mod]) {
throw new Error('GitBook module '+mod+' doesn\'t exist');
}
@@ -24126,7 +24449,7 @@ window.require = function(mods, fn) {
module.exports = {};
},{"./dropdown":9,"./events":10,"./keyboard":12,"./navigation":14,"./sidebar":16,"./state":17,"./storage":18,"./toolbar":19,"jquery":6,"lodash":7}],12:[function(require,module,exports){
},{"./dropdown":11,"./events":12,"./keyboard":14,"./navigation":16,"./sidebar":18,"./state":19,"./storage":20,"./toolbar":21,"jquery":8,"lodash":9}],14:[function(require,module,exports){
var Mousetrap = require('mousetrap');
var navigation = require('./navigation');
@@ -24164,7 +24487,7 @@ module.exports = {
bind: bindShortcut
};
},{"./navigation":14,"./sidebar":16,"mousetrap":8}],13:[function(require,module,exports){
},{"./navigation":16,"./sidebar":18,"mousetrap":10}],15:[function(require,module,exports){
var state = require('./state');
function showLoading(p) {
@@ -24180,7 +24503,7 @@ module.exports = {
show: showLoading
};
},{"./state":17}],14:[function(require,module,exports){
},{"./state":19}],16:[function(require,module,exports){
var $ = require('jquery');
var url = require('url');
@@ -24342,12 +24665,12 @@ module.exports = {
goPrev: goPrev
};
},{"./events":10,"./loading":13,"./state":17,"jquery":6,"url":5}],15:[function(require,module,exports){
},{"./events":12,"./loading":15,"./state":19,"jquery":8,"url":7}],17:[function(require,module,exports){
module.exports = {
isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
};
},{}],16:[function(require,module,exports){
},{}],18:[function(require,module,exports){
var $ = require('jquery');
var _ = require('lodash');
@@ -24400,25 +24723,41 @@ module.exports = {
filter: filterSummary
};
},{"./platform":15,"./state":17,"./storage":18,"jquery":6,"lodash":7}],17:[function(require,module,exports){
},{"./platform":17,"./state":19,"./storage":20,"jquery":8,"lodash":9}],19:[function(require,module,exports){
var $ = require('jquery');
var url = require('url');
var path = require('path');
var state = {};
state.update = function(dom) {
var $book = $(dom.find(".book"));
var $book = $(dom.find('.book'));
state.$book = $book;
state.level = $book.data("level");
state.basePath = $book.data("basepath");
state.revision = $book.data("revision");
state.level = $book.data('level');
state.basePath = $book.data('basepath');
// Date of build
state.revision = $book.data('revision');
// Original path of the file
state.filepath = $book.data('filepath');
// Title of the chapter
state.chapterTitle = $book.data('chapter-title');
// Absolute url to the root of the book
state.root = url.resolve(
location.protocol+'//'+location.host,
path.dirname(path.resolve(location.pathname.replace(/\/$/, '/index.html'), state.basePath))
);
};
state.update($);
module.exports = state;
},{"jquery":6}],18:[function(require,module,exports){
},{"jquery":8,"path":1,"url":7}],20:[function(require,module,exports){
var baseKey = '';
/*
@@ -24457,7 +24796,7 @@ module.exports = {
}
};
},{}],19:[function(require,module,exports){
},{}],21:[function(require,module,exports){
var $ = require('jquery');
var _ = require('lodash');
@@ -24466,6 +24805,18 @@ var events = require('./events');
// List of created buttons
var buttons = [];
// Insert a jquery element at a specific position
function insertAt(parent, selector, index, element) {
var lastIndex = parent.children(selector).size();
if (index < 0) {
index = Math.max(0, lastIndex + 1 + index);
}
parent.append(element);
if (index < lastIndex) {
parent.children(selector).eq(index).before(parent.children(selector).last());
}
}
// Default click handler
function defaultOnClick(e) {
@@ -24543,7 +24894,10 @@ function createButton(opts) {
onClick: defaultOnClick,
// Button is a dropdown
dropdown: null
dropdown: null,
// Position in the toolbar
index: null
});
buttons.push(opts);
@@ -24552,6 +24906,7 @@ function createButton(opts) {
// Update a button
function updateButton(opts) {
var $result;
var $toolbar = $('.book-header');
var $title = $toolbar.find('h1');
@@ -24593,12 +24948,17 @@ function updateButton(opts) {
$menu.addClass('dropdown-'+(opts.position == 'right'? 'left' : 'right'));
$container.append($menu);
$container.insertBefore($title);
$result = $container;
} else {
$btn.addClass(positionClass);
$btn.addClass(opts.className);
$btn.insertBefore($title);
$result = $btn;
}
if (_.isNumber(opts.index) && opts.index >= 0) {
insertAt($toolbar, '.btn, .dropdown, h1', opts.index, $result);
} else {
$result.insertBefore($title);
}
}
@@ -24616,4 +24976,4 @@ module.exports = {
createButton: createButton
};
},{"./events":10,"jquery":6,"lodash":7}]},{},[11]);
},{"./events":12,"jquery":8,"lodash":9}]},{},[13]);
+3 -1
View File
@@ -27,6 +27,7 @@ function start(config) {
// Add action to toggle sidebar
toolbar.createButton({
index: 0,
icon: 'fa fa-align-justify',
onClick: function(e) {
e.preventDefault();
@@ -58,7 +59,7 @@ var gitbook = {
// Modules mapping for plugins
var MODULES = {
'gitbook': gitbook,
'jQuery': $,
'jquery': $,
'lodash': _
};
@@ -67,6 +68,7 @@ window.$ = $;
window.jQuery = $;
window.require = function(mods, fn) {
mods = _.map(mods, function(mod) {
mod = mod.toLowerCase();
if (!MODULES[mod]) {
throw new Error('GitBook module '+mod+' doesn\'t exist');
}
+20 -4
View File
@@ -1,14 +1,30 @@
var $ = require('jquery');
var url = require('url');
var path = require('path');
var state = {};
state.update = function(dom) {
var $book = $(dom.find(".book"));
var $book = $(dom.find('.book'));
state.$book = $book;
state.level = $book.data("level");
state.basePath = $book.data("basepath");
state.revision = $book.data("revision");
state.level = $book.data('level');
state.basePath = $book.data('basepath');
// Date of build
state.revision = $book.data('revision');
// Original path of the file
state.filepath = $book.data('filepath');
// Title of the chapter
state.chapterTitle = $book.data('chapter-title');
// Absolute url to the root of the book
state.root = url.resolve(
location.protocol+'//'+location.host,
path.dirname(path.resolve(location.pathname.replace(/\/$/, '/index.html'), state.basePath))
);
};
state.update($);
+25 -4
View File
@@ -6,6 +6,18 @@ var events = require('./events');
// List of created buttons
var buttons = [];
// Insert a jquery element at a specific position
function insertAt(parent, selector, index, element) {
var lastIndex = parent.children(selector).size();
if (index < 0) {
index = Math.max(0, lastIndex + 1 + index);
}
parent.append(element);
if (index < lastIndex) {
parent.children(selector).eq(index).before(parent.children(selector).last());
}
}
// Default click handler
function defaultOnClick(e) {
@@ -83,7 +95,10 @@ function createButton(opts) {
onClick: defaultOnClick,
// Button is a dropdown
dropdown: null
dropdown: null,
// Position in the toolbar
index: null
});
buttons.push(opts);
@@ -92,6 +107,7 @@ function createButton(opts) {
// Update a button
function updateButton(opts) {
var $result;
var $toolbar = $('.book-header');
var $title = $toolbar.find('h1');
@@ -133,12 +149,17 @@ function updateButton(opts) {
$menu.addClass('dropdown-'+(opts.position == 'right'? 'left' : 'right'));
$container.append($menu);
$container.insertBefore($title);
$result = $container;
} else {
$btn.addClass(positionClass);
$btn.addClass(opts.className);
$btn.insertBefore($title);
$result = $btn;
}
if (_.isNumber(opts.index) && opts.index >= 0) {
insertAt($toolbar, '.btn, .dropdown, h1', opts.index, $result);
} else {
$result.insertBefore($title);
}
}
+1 -1
View File
@@ -14,7 +14,7 @@
{% block description %}{% if progress.current.level == "0" %}{{ description }}{% endif %}{% endblock %}
{% block content %}
<div class="book" data-level="{{ progress.current.level }}" data-basepath="{{ basePath }}" data-revision="{{ revision }}">
<div class="book" data-level="{{ progress.current.level }}" data-chapter-title="{{ progress.current.title }}" data-filepath="{{ progress.current.path }}" data-basepath="{{ basePath }}" data-revision="{{ revision }}">
{% include "includes/summary.html" %}
<div class="book-body">
<div class="body-inner">