Compare commits
75 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4850c0f302 | |||
| ac258329ff | |||
| d5bd08dcd2 | |||
| 6c414ec400 | |||
| 881a0c6f6d | |||
| 0071594300 | |||
| 460799828f | |||
| 02b75288d2 | |||
| b108be0c3b | |||
| 7ab285832b | |||
| 0bc288fe96 | |||
| 9fbe240843 | |||
| 0c7e2b3557 | |||
| e34e65813c | |||
| 63f946ced9 | |||
| af9f3cf89f | |||
| 355094bbb3 | |||
| b3adedb468 | |||
| 026e4362d8 | |||
| 9cf5384fbe | |||
| 9bc0bf19da | |||
| f49a1a484e | |||
| 446d486a0f | |||
| 07101deaef | |||
| 76b3fcb41c | |||
| febda9aba1 | |||
| f952fa47b9 | |||
| 1984660930 | |||
| d475affd3b | |||
| fe3de93e06 | |||
| 5cae311edf | |||
| 26701a2a73 | |||
| 5125e04814 | |||
| 0a6194340f | |||
| e0d96b3163 | |||
| f656390783 | |||
| 88c480ba4f | |||
| 3da53d56a2 | |||
| 91359fab1e | |||
| a52a4bed1a | |||
| 9dce855113 | |||
| 57e2595a3e | |||
| b1314273bb | |||
| cb9a0b82ba | |||
| 57ecfe4a54 | |||
| 405792fd8f | |||
| fc6d911340 | |||
| 1e6307b69b | |||
| af87dc8d7c | |||
| 1699028688 | |||
| 55d9bfbf18 | |||
| c964b53137 | |||
| 510f7bacb4 | |||
| c934238f3d | |||
| ab48959968 | |||
| eb6204aa42 | |||
| a70439f375 | |||
| a3b562b4e8 | |||
| aa4e3abc33 | |||
| f24a7fbb6e | |||
| f3a49306b1 | |||
| f312472abd | |||
| ecb07468f6 | |||
| 8fc09e2e05 | |||
| ed7798237a | |||
| faf63566df | |||
| c88382aea0 | |||
| 9ee5f48aef | |||
| e1dfe5c0f6 | |||
| 3adcd77ae4 | |||
| 4bdcfd07a9 | |||
| a9967df6eb | |||
| 62a2e8f81c | |||
| 6bcc2d8cf2 | |||
| ad1867e4d8 |
@@ -0,0 +1,5 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- "0.11"
|
||||
- "0.10"
|
||||
- "0.8"
|
||||
@@ -16,7 +16,8 @@ module.exports = function (grunt) {
|
||||
optimization: 2
|
||||
},
|
||||
files: {
|
||||
"assets/static/style.css": "assets/stylesheets/main.less"
|
||||
"theme/assets/style.css": "theme/stylesheets/main.less",
|
||||
"theme/assets/print.css": "theme/stylesheets/print.less"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -24,8 +25,8 @@ module.exports = function (grunt) {
|
||||
compile: {
|
||||
options: {
|
||||
name: "app",
|
||||
baseUrl: "assets/javascript/",
|
||||
out: "assets/static/app.js",
|
||||
baseUrl: "theme/javascript/",
|
||||
out: "theme/assets/app.js",
|
||||
preserveLicenseComments: false,
|
||||
optimize: "uglify",
|
||||
include: ["requireLib"],
|
||||
@@ -33,6 +34,8 @@ module.exports = function (grunt) {
|
||||
"jQuery": 'vendors/jquery',
|
||||
"lodash": 'vendors/lodash',
|
||||
"requireLib": 'vendors/require',
|
||||
"Mousetrap": 'vendors/mousetrap',
|
||||
"mixpanel": 'vendors/mixpanel'
|
||||
},
|
||||
shim: {
|
||||
'jQuery': {
|
||||
@@ -40,6 +43,12 @@ module.exports = function (grunt) {
|
||||
},
|
||||
'lodash': {
|
||||
exports: '_'
|
||||
},
|
||||
'Mousetrap': {
|
||||
exports: 'Mousetrap'
|
||||
},
|
||||
'mixpanel': {
|
||||
exports: 'mixpanel'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
GitBook
|
||||
=======
|
||||
|
||||
GiBook is a command line tool (and Node.js library) for building beautiful programming books and exercises using GitHub/Git and Markdown. You can see an example: [Learn Javascript](http://gitbookio.github.io/javascript/).
|
||||
[](https://travis-ci.org/GitbookIO/gitbook)
|
||||
|
||||
GitBook is a command line tool (and Node.js library) for building beautiful programming books and exercises using GitHub/Git and Markdown. You can see an example: [Learn Javascript](http://gitbookio.github.io/javascript/).
|
||||
|
||||

|
||||
|
||||
## How to use it:
|
||||
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
define([], function() {
|
||||
var isAvailable = function() {
|
||||
return (typeof mixpanel !== "undefined");
|
||||
};
|
||||
|
||||
var track = function(event, data) {
|
||||
if (!isAvailable()) {
|
||||
console.log("tracking not available!");
|
||||
return;
|
||||
}
|
||||
mixpanel.track(event, data);
|
||||
};
|
||||
|
||||
return {
|
||||
isAvailable: isAvailable,
|
||||
track: track
|
||||
};
|
||||
});
|
||||
|
Before Width: | Height: | Size: 1.1 KiB |
@@ -1,6 +1,7 @@
|
||||
#! /usr/bin/env node
|
||||
|
||||
// Requires
|
||||
var Q = require('q');
|
||||
var _ = require('lodash');
|
||||
var path = require('path');
|
||||
var prog = require('commander');
|
||||
@@ -10,9 +11,14 @@ var fs = require('fs');
|
||||
var pkg = require('../package.json');
|
||||
var generate = require("../lib/generate");
|
||||
var parse = require("../lib/parse");
|
||||
var generators = require("../lib/generate").generators;
|
||||
|
||||
var utils = require('./utils');
|
||||
|
||||
var logError = function(err) {
|
||||
console.log(err.message || err);
|
||||
return Q.reject(err);
|
||||
};
|
||||
|
||||
// General options
|
||||
prog
|
||||
@@ -25,40 +31,52 @@ prog
|
||||
.command('build [source_dir]')
|
||||
.description('Build a gitbook from a directory')
|
||||
.option('-o, --output <directory>', 'Path to output directory, defaults to ./_book')
|
||||
.option('-f, --format <name>', 'Change generation format, defaults to site, availables are: '+_.keys(generators).join(", "))
|
||||
.option('-t, --title <name>', 'Name of the book to generate, defaults to repo name')
|
||||
.option('-i, --intro <intro>', 'Description of the book to generate')
|
||||
.option('-g, --github <repo_path>', 'ID of github repo like : username/repo')
|
||||
.option('-gh, --githubHost <url>', 'The url of the github host (defaults to https://github.com/')
|
||||
.option('--theme <path>', 'Path to theme directory')
|
||||
.action(buildFunc = function(dir, options) {
|
||||
dir = dir || process.cwd();
|
||||
outputDir = options.output || path.join(dir, '_book');
|
||||
|
||||
|
||||
console.log('Starting build ...');
|
||||
// Get repo's URL
|
||||
return utils.gitURL(dir)
|
||||
.then(function(url) {
|
||||
// Get ID of repo
|
||||
return utils.githubID(url);
|
||||
}, function(err) {
|
||||
return null;
|
||||
})
|
||||
.then(function(repoID) {
|
||||
var parts = repoID.split('/', 2);
|
||||
var githubID = options.github || repoID;
|
||||
|
||||
if(!githubID) {
|
||||
throw new Error('Needs a githubID (username/repo). Either set repo origin to a github repo or use the -g flag');
|
||||
}
|
||||
|
||||
var parts = githubID.split('/', 2);
|
||||
var user = parts[0], repo = parts[1];
|
||||
|
||||
var title = options.title || utils.titleCase(repo);
|
||||
|
||||
return generate.folder(
|
||||
dir,
|
||||
outputDir,
|
||||
{
|
||||
title: options.title || utils.titleCase(repo),
|
||||
input: dir,
|
||||
output: outputDir,
|
||||
title: title,
|
||||
description: options.intro,
|
||||
github: options.github || repoID
|
||||
github: githubID,
|
||||
generator: options.format,
|
||||
theme: options.theme
|
||||
}
|
||||
);
|
||||
})
|
||||
.then(function(output) {
|
||||
console.log("Successfuly built !");
|
||||
}, function(err) {
|
||||
console.log(err.stack || err);
|
||||
throw err;
|
||||
})
|
||||
}, logError)
|
||||
.then(_.constant(outputDir));
|
||||
});
|
||||
|
||||
@@ -67,34 +85,26 @@ prog
|
||||
.description('Build then serve a gitbook from a directory')
|
||||
.option('-p, --port <port>', 'Port for server to listen on', 4000)
|
||||
.option('-o, --output <directory>', 'Path to output directory, defaults to ./_book')
|
||||
.option('-f, --format <name>', 'Change generation format, defaults to site, availables are: '+_.keys(generators).join(", "))
|
||||
.option('-t, --title <name>', 'Name of the book to generate, defaults to repo name')
|
||||
.option('-g, --github <repo_path>', 'ID of github repo like : username/repo')
|
||||
.option('-gh, --githubHost <url>', 'The url of the github host (defaults to https://github.com/')
|
||||
.option('--theme <path>', 'Path to theme directory')
|
||||
.action(function(dir, options) {
|
||||
buildFunc(dir, options)
|
||||
.then(function(outputDir) {
|
||||
console.log();
|
||||
console.log('Starting server ...');
|
||||
return utils.serveDir(outputDir, options.port);
|
||||
return utils.serveDir(outputDir, options.port)
|
||||
.fail(logError);
|
||||
})
|
||||
.then(function() {
|
||||
console.log('Serving book on http://localhost:'+options.port);
|
||||
console.log();
|
||||
console.log('Press CTRL+C to quit ...');
|
||||
})
|
||||
.fail(function(err) {
|
||||
console.error(err);
|
||||
});
|
||||
});
|
||||
|
||||
prog
|
||||
.command('lex <page_file>')
|
||||
.description('Parse a page file into sections, display JSON dump')
|
||||
.action(function(page_file) {
|
||||
var parsed = parse.page(fs.readFileSync(page_file, 'utf-8'));
|
||||
|
||||
console.log(JSON.stringify(parsed, null, 4));
|
||||
});
|
||||
|
||||
|
||||
|
||||
// Parse and fallback to help if no args
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
var path = require("path");
|
||||
var Q = require("q");
|
||||
var fs = require("./fs");
|
||||
|
||||
var BaseGenerator = function(options) {
|
||||
this.options = options;
|
||||
};
|
||||
|
||||
BaseGenerator.prototype.convertFile = function(content, input) {
|
||||
return Q.reject(new Error("Could not convert "+input));
|
||||
};
|
||||
|
||||
BaseGenerator.prototype.transferFile = function(input) {
|
||||
return fs.copy(
|
||||
path.join(this.options.input, input),
|
||||
path.join(this.options.output, input)
|
||||
);
|
||||
};
|
||||
|
||||
BaseGenerator.prototype.transferFolder = function(input) {
|
||||
return fs.mkdirp(
|
||||
path.join(this.options.output, input)
|
||||
);
|
||||
};
|
||||
|
||||
BaseGenerator.prototype.finish = function() {
|
||||
return Q.reject(new Error("Could not finish generation"));
|
||||
};
|
||||
|
||||
|
||||
|
||||
module.exports = BaseGenerator;
|
||||
@@ -5,33 +5,55 @@ var path = require("path");
|
||||
|
||||
var fs = require("./fs");
|
||||
var parse = require("../parse");
|
||||
var template = require("./template");
|
||||
|
||||
var generate = function(root, output, options) {
|
||||
var files, summary, navigation, tpl;
|
||||
var generators = {
|
||||
"site": require("./site"),
|
||||
"page": require("./page"),
|
||||
"json": require("./json")
|
||||
};
|
||||
|
||||
var generate = function(options) {
|
||||
var generator = null;
|
||||
var files;
|
||||
|
||||
options = _.defaults(options || {}, {
|
||||
// Folders to use
|
||||
input: null,
|
||||
output: null,
|
||||
|
||||
// Output generator
|
||||
generator: "site",
|
||||
|
||||
// Book title, keyword, description
|
||||
title: null,
|
||||
description: "Book generated using GitBook",
|
||||
|
||||
// Origin github repository id
|
||||
github: null
|
||||
github: null,
|
||||
githubHost: 'https://github.com/',
|
||||
|
||||
// Theming
|
||||
theme: path.resolve(__dirname, '../../theme')
|
||||
});
|
||||
|
||||
if (!options.github || !options.title) return Q.reject(new Error("Need options.github and optiosn.title"));
|
||||
if (!options.github || !options.title || !options.input || !options.output) {
|
||||
return Q.reject(new Error("Need options: github, title, input, output"));
|
||||
}
|
||||
|
||||
if (!generators[options.generator]) {
|
||||
return Q.reject(new Error("Invalid generator (availables are: "+_.keys(generators).join(", ")));
|
||||
}
|
||||
|
||||
// Clean output folder
|
||||
return fs.remove(output)
|
||||
return fs.remove(options.output)
|
||||
|
||||
.then(function() {
|
||||
return fs.mkdirp(output);
|
||||
return fs.mkdirp(options.output);
|
||||
})
|
||||
|
||||
// List all files in the repository
|
||||
.then(function() {
|
||||
return fs.list(root);
|
||||
return fs.list(options.input);
|
||||
})
|
||||
|
||||
// Check repository is valid
|
||||
@@ -45,31 +67,18 @@ var generate = function(root, output, options) {
|
||||
|
||||
// Get summary
|
||||
.then(function() {
|
||||
return fs.readFile(path.join(root, "SUMMARY.md"), "utf-8")
|
||||
return fs.readFile(path.join(options.input, "SUMMARY.md"), "utf-8")
|
||||
.then(function(_summary) {
|
||||
summary = parse.summary(_summary);
|
||||
options.summary = parse.summary(_summary);
|
||||
|
||||
// Parse navigation
|
||||
navigation = parse.navigation(summary);
|
||||
options.navigation = parse.navigation(options.summary);
|
||||
});
|
||||
})
|
||||
|
||||
// Create template
|
||||
// Create the generator
|
||||
.then(function() {
|
||||
tpl = template({
|
||||
root: root,
|
||||
output: output,
|
||||
locals: {
|
||||
title: options.title,
|
||||
description: options.description,
|
||||
|
||||
githubAuthor: options.github.split("/")[0],
|
||||
githubId: options.github,
|
||||
|
||||
summary: summary,
|
||||
allNavigation: navigation
|
||||
}
|
||||
});
|
||||
generator = new generators[options.generator](options);
|
||||
})
|
||||
|
||||
// Copy file and replace markdown file
|
||||
@@ -78,49 +87,29 @@ var generate = function(root, output, options) {
|
||||
_.chain(files)
|
||||
.map(function(file) {
|
||||
if (!file) return;
|
||||
var _html = file.replace(".md", ".html");
|
||||
|
||||
// Folder
|
||||
if (file[file.length -1] == "/") {
|
||||
return fs.mkdirp(
|
||||
path.join(output, file)
|
||||
);
|
||||
}
|
||||
|
||||
// Markdown file (only from the summary)
|
||||
else if (path.extname(file) == ".md" && navigation[_html] != null) {
|
||||
return tpl(file, file.replace(".md", ".html"));
|
||||
}
|
||||
|
||||
// Copy file
|
||||
else {
|
||||
return fs.copy(
|
||||
path.join(root, file),
|
||||
path.join(output, file)
|
||||
);
|
||||
return Q(generator.transferFolder(file));
|
||||
} else if (path.extname(file) == ".md" && options.navigation[file] != null) {
|
||||
return fs.readFile(path.join(options.input, file), "utf-8")
|
||||
.then(function(content) {
|
||||
return Q(generator.convertFile(content, file));
|
||||
});
|
||||
} else {
|
||||
return Q(generator.transferFile(file));
|
||||
}
|
||||
})
|
||||
.value()
|
||||
);
|
||||
})
|
||||
|
||||
// Symlink index.html to README.html
|
||||
// Finish gneration
|
||||
.then(function() {
|
||||
return fs.symlink(
|
||||
path.join(output, 'README.html'),
|
||||
path.join(output, 'index.html')
|
||||
);
|
||||
})
|
||||
|
||||
// Copy assets
|
||||
.then(function() {
|
||||
return fs.copy(
|
||||
path.join(__dirname, "../../assets/static"),
|
||||
path.join(output, "gitbook")
|
||||
);
|
||||
return generator.finish();
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
generators: generators,
|
||||
folder: generate
|
||||
};
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
var util = require("util");
|
||||
var path = require("path");
|
||||
var Q = require("q");
|
||||
|
||||
var fs = require("../fs");
|
||||
var parse = require("../../parse");
|
||||
var BaseGenerator = require("../generator");
|
||||
|
||||
|
||||
var Generator = function() {
|
||||
BaseGenerator.apply(this, arguments);
|
||||
};
|
||||
util.inherits(Generator, BaseGenerator);
|
||||
|
||||
Generator.prototype.transferFile = function(input) {
|
||||
// ignore
|
||||
};
|
||||
|
||||
Generator.prototype.convertFile = function(content, input) {
|
||||
var that = this;
|
||||
var json = {
|
||||
progress: parse.progress(this.options.navigation, input)
|
||||
};
|
||||
|
||||
return Q()
|
||||
.then(function() {
|
||||
return parse.page(content, {
|
||||
repo: that.options.githubId,
|
||||
dir: path.dirname(input) || '/'
|
||||
});
|
||||
})
|
||||
.then(function(sections) {
|
||||
json.sections = sections;
|
||||
})
|
||||
.then(function() {
|
||||
return fs.writeFile(
|
||||
path.join(that.options.output, input.replace(".md", ".json")),
|
||||
JSON.stringify(json, null, 4)
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
Generator.prototype.finish = function() {
|
||||
// ignore
|
||||
};
|
||||
|
||||
module.exports = Generator;
|
||||
@@ -0,0 +1,109 @@
|
||||
var _ = require("lodash");
|
||||
var util = require("util");
|
||||
var path = require("path");
|
||||
var Q = require("q");
|
||||
var swig = require('swig');
|
||||
var hljs = require('highlight.js');
|
||||
|
||||
var fs = require("../fs");
|
||||
var parse = require("../../parse");
|
||||
var BaseGenerator = require("../generator");
|
||||
|
||||
// Swig filter: highlight coloration
|
||||
swig.setFilter('code', function(code, lang) {
|
||||
try {
|
||||
return hljs.highlight(lang, code).value;
|
||||
} catch(e) {
|
||||
return hljs.highlightAuto(code).value;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
/*
|
||||
* This generator will generate a simple index.html which can be converted as a PDF
|
||||
*/
|
||||
var Generator = function() {
|
||||
BaseGenerator.apply(this, arguments);
|
||||
|
||||
// Load base template
|
||||
this.template = swig.compileFile(path.resolve(this.options.theme, 'templates/page.html'));
|
||||
|
||||
// List of pages content
|
||||
this.pages = {};
|
||||
};
|
||||
util.inherits(Generator, BaseGenerator);
|
||||
|
||||
Generator.prototype.transferFile = function(input) {
|
||||
// ignore
|
||||
};
|
||||
|
||||
Generator.prototype.transferFolder = function(input) {
|
||||
// ignore
|
||||
};
|
||||
|
||||
Generator.prototype.convertFile = function(content, input) {
|
||||
var that = this;
|
||||
var json = {
|
||||
path: input,
|
||||
progress: parse.progress(this.options.navigation, input)
|
||||
};
|
||||
|
||||
return Q()
|
||||
.then(function() {
|
||||
return parse.page(content, {
|
||||
repo: that.options.githubId,
|
||||
dir: path.dirname(input) || '/'
|
||||
});
|
||||
})
|
||||
.then(function(sections) {
|
||||
json.content = sections;
|
||||
})
|
||||
.then(function() {
|
||||
that.pages[input] = json;
|
||||
});
|
||||
};
|
||||
|
||||
Generator.prototype.finish = function() {
|
||||
var that = this;
|
||||
var basePath = ".";
|
||||
var output = path.join(this.options.output, "index.html");
|
||||
|
||||
return Q()
|
||||
// Generate html
|
||||
.then(function(pages) {
|
||||
return that.template({
|
||||
title: that.options.title,
|
||||
description: that.options.description,
|
||||
|
||||
githubAuthor: that.options.github.split("/")[0],
|
||||
githubId: that.options.github,
|
||||
githubHost: that.options.githubHost,
|
||||
|
||||
summary: that.options.summary,
|
||||
allNavigation: that.options.navigation,
|
||||
|
||||
pages: that.pages,
|
||||
|
||||
basePath: basePath,
|
||||
staticBase: path.join(basePath, "gitbook"),
|
||||
});
|
||||
})
|
||||
|
||||
// Write html to index.html
|
||||
.then(function(html) {
|
||||
return fs.writeFile(
|
||||
output,
|
||||
html
|
||||
);
|
||||
})
|
||||
|
||||
// Copy assets
|
||||
.then(function() {
|
||||
return fs.copy(
|
||||
path.join(that.options.theme, "assets"),
|
||||
path.join(that.options.output, "gitbook")
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = Generator;
|
||||
@@ -0,0 +1,92 @@
|
||||
var util = require("util");
|
||||
var path = require("path");
|
||||
var Q = require("q");
|
||||
var _ = require("lodash");
|
||||
var swig = require('swig');
|
||||
|
||||
var fs = require("../fs");
|
||||
var parse = require("../../parse");
|
||||
var BaseGenerator = require("../generator");
|
||||
|
||||
// Swig filter for returning the count of lines in a code section
|
||||
swig.setFilter('lines', function(content) {
|
||||
return content.split('\n').length;
|
||||
});
|
||||
|
||||
// Swig filter for returning a link to the associated html file of a markdown file
|
||||
swig.setFilter('mdLink', function(link) {
|
||||
return link.replace(".md", ".html");
|
||||
});
|
||||
|
||||
var Generator = function() {
|
||||
BaseGenerator.apply(this, arguments);
|
||||
|
||||
// Load base template
|
||||
this.template = swig.compileFile(path.resolve(this.options.theme, 'templates/site.html'));
|
||||
};
|
||||
util.inherits(Generator, BaseGenerator);
|
||||
|
||||
|
||||
// Convert a markdown file to html
|
||||
Generator.prototype.convertFile = function(content, _input) {
|
||||
var that = this;
|
||||
var progress = parse.progress(this.options.navigation, _input);
|
||||
|
||||
_output = _input.replace(".md", ".html");
|
||||
|
||||
var input = path.join(this.options.input, _input);
|
||||
var output = path.join(this.options.output, _output);
|
||||
var basePath = path.relative(path.dirname(output), this.options.output) || ".";
|
||||
|
||||
return Q()
|
||||
.then(function() {
|
||||
return parse.page(content, {
|
||||
repo: that.options.githubId,
|
||||
dir: path.dirname(input) || '/'
|
||||
});
|
||||
})
|
||||
.then(function(sections) {
|
||||
return that.template({
|
||||
title: that.options.title,
|
||||
description: that.options.description,
|
||||
|
||||
githubAuthor: that.options.github.split("/")[0],
|
||||
githubId: that.options.github,
|
||||
githubHost: that.options.githubHost,
|
||||
|
||||
summary: that.options.summary,
|
||||
allNavigation: that.options.navigation,
|
||||
progress: progress,
|
||||
|
||||
_input: _input,
|
||||
content: sections,
|
||||
|
||||
basePath: basePath,
|
||||
staticBase: path.join(basePath, "gitbook"),
|
||||
});
|
||||
})
|
||||
.then(function(html) {
|
||||
return fs.writeFile(
|
||||
output,
|
||||
html
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
// Symlink index.html and copy assets
|
||||
Generator.prototype.finish = function() {
|
||||
var that = this;
|
||||
|
||||
return fs.copy(
|
||||
path.join(that.options.output, 'README.html'),
|
||||
path.join(that.options.output, 'index.html')
|
||||
)
|
||||
.then(function() {
|
||||
return fs.copy(
|
||||
path.join(that.options.theme, "assets"),
|
||||
path.join(that.options.output, "gitbook")
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = Generator;
|
||||
@@ -1,65 +0,0 @@
|
||||
var swig = require('swig');
|
||||
var path = require('path');
|
||||
var _ = require("lodash");
|
||||
|
||||
var parse = require("../parse");
|
||||
|
||||
var fs = require('./fs');
|
||||
|
||||
swig.setFilter('lines', function(content) {
|
||||
return content.split('\n').length;
|
||||
});
|
||||
|
||||
// return a templeter for page
|
||||
var initTemplate = function(options) {
|
||||
var tpl = swig.compileFile(path.resolve(__dirname, '../../templates/page.html'));
|
||||
var nExercise = 1;
|
||||
|
||||
options = _.defaults(options || {}, {
|
||||
// Base folder for input
|
||||
root: "./",
|
||||
|
||||
// Base folder for output
|
||||
output: "./",
|
||||
|
||||
// Locals for templates
|
||||
locals: {}
|
||||
});
|
||||
|
||||
return function(input, output, local) {
|
||||
var _input = input, _output = output;
|
||||
input = path.join(options.root, input);
|
||||
output = path.join(options.output, output);
|
||||
|
||||
var basePath = path.relative(path.dirname(output), options.output) || ".";
|
||||
|
||||
// Read markdown file
|
||||
return fs.readFile(input, "utf-8")
|
||||
|
||||
// Parse sections
|
||||
.then(function(markdown) {
|
||||
return parse.page(markdown);
|
||||
})
|
||||
|
||||
//Calcul template
|
||||
.then(function(sections) {
|
||||
return tpl(
|
||||
_.extend(local || {}, options.locals, {
|
||||
_input: _input,
|
||||
content: sections,
|
||||
basePath: basePath,
|
||||
staticBase: path.join(basePath, "gitbook"),
|
||||
navigation: options.locals.allNavigation[_output],
|
||||
progress: parse.progress(options.locals.allNavigation, _output)
|
||||
})
|
||||
);
|
||||
})
|
||||
|
||||
// Write html
|
||||
.then(function(html) {
|
||||
return fs.writeFile(output, html);
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = initTemplate;
|
||||
@@ -1,15 +1,15 @@
|
||||
var _ = require('lodash');
|
||||
|
||||
// Cleans up an article/chapter object
|
||||
// remove 'articles' and '_path' attributes
|
||||
// remove 'articles' attributes
|
||||
function clean(obj) {
|
||||
return obj && _.omit(obj, ['articles', '_path']);
|
||||
return obj && _.omit(obj, ['articles']);
|
||||
}
|
||||
|
||||
// Returns a map of
|
||||
// Returns from a summary a map of
|
||||
/*
|
||||
{
|
||||
"file/path.html": {
|
||||
"file/path.md": {
|
||||
prev: ...,
|
||||
next: ...,
|
||||
},
|
||||
@@ -25,7 +25,7 @@ function navigation(summary, files) {
|
||||
|
||||
// Special README nav
|
||||
var README_NAV = {
|
||||
path: 'README.html',
|
||||
path: 'README.md',
|
||||
title: 'Introduction',
|
||||
};
|
||||
|
||||
@@ -45,6 +45,7 @@ function navigation(summary, files) {
|
||||
|
||||
// Add chapter mapping
|
||||
mapping[chapter.path] = {
|
||||
title: chapter.title,
|
||||
prev: clean(prev),
|
||||
next: clean(next),
|
||||
level: (idx+1).toString(),
|
||||
@@ -59,6 +60,7 @@ function navigation(summary, files) {
|
||||
var next = (_idx+1 >= articles.length) ? nextChapter : clean(articles[_idx+1]);
|
||||
|
||||
mapping[article.path] = {
|
||||
title: article.title,
|
||||
prev: clean(prev),
|
||||
next: clean(next),
|
||||
level: [idx+1, _idx+1].join('.'),
|
||||
@@ -67,7 +69,8 @@ function navigation(summary, files) {
|
||||
});
|
||||
|
||||
// Hack for README.html
|
||||
mapping['README.html'] = {
|
||||
mapping['README.md'] = {
|
||||
title: README_NAV.title,
|
||||
prev: null,
|
||||
next: clean(summary.chapters[0]),
|
||||
level: '0',
|
||||
|
||||
@@ -46,19 +46,22 @@ function sectionType(nodes, idx) {
|
||||
}
|
||||
|
||||
// Render a section using our custom renderer
|
||||
function render(section) {
|
||||
function render(section, _options) {
|
||||
// marked's Render expects this, we don't use it yet
|
||||
section.links = {};
|
||||
|
||||
// Build options using defaults and our custom renderer
|
||||
var options = _.extend({}, marked.defaults, {
|
||||
renderer: renderer()
|
||||
renderer: renderer(null, _options)
|
||||
});
|
||||
|
||||
return marked.parser(section, options);
|
||||
}
|
||||
|
||||
function parsePage(src) {
|
||||
function parsePage(src, options) {
|
||||
options = options || {};
|
||||
|
||||
// Lex file
|
||||
var nodes = marked.lexer(src);
|
||||
|
||||
return _.chain(splitSections(nodes))
|
||||
@@ -70,6 +73,19 @@ function parsePage(src) {
|
||||
.filter(function(section) {
|
||||
return !_.isEmpty(section);
|
||||
})
|
||||
.reduce(function(sections, section) {
|
||||
var last = _.last(sections);
|
||||
|
||||
// Merge normal sections together
|
||||
if(last && last.type === section.type && last.type === 'normal') {
|
||||
last.push.apply(last, [{'type': 'hr'}].concat(section));
|
||||
} else {
|
||||
// Add to list of sections
|
||||
sections.push(section);
|
||||
}
|
||||
|
||||
return sections;
|
||||
}, [])
|
||||
.map(function(section) {
|
||||
// Generate a uniqueId to identify this section in our code
|
||||
var id = _.uniqueId('gitbook_');
|
||||
@@ -100,7 +116,7 @@ function parsePage(src) {
|
||||
return {
|
||||
id: id,
|
||||
type: section.type,
|
||||
content: render(section)
|
||||
content: render(section, options)
|
||||
};
|
||||
})
|
||||
.value();
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
var _ = require("lodash");
|
||||
|
||||
// Returns from a navigation and a current file, a snapshot of current detailed state
|
||||
var calculProgress = function(navigation, current) {
|
||||
var n = _.size(navigation);
|
||||
var percent = 0, prevPercent = 0;
|
||||
var percent = 0, prevPercent = 0, currentChapter = null;
|
||||
var done = true;
|
||||
|
||||
var chapters = _.chain(navigation)
|
||||
@@ -20,6 +21,7 @@ var calculProgress = function(navigation, current) {
|
||||
// Is it done
|
||||
nav.done = done;
|
||||
if (nav.path == current) {
|
||||
currentChapter = nav;
|
||||
percent = nav.percent;
|
||||
done = false;
|
||||
} else if (done) {
|
||||
@@ -30,11 +32,18 @@ var calculProgress = function(navigation, current) {
|
||||
})
|
||||
.value();
|
||||
|
||||
|
||||
return {
|
||||
// Previous percent
|
||||
prevPercent: prevPercent,
|
||||
|
||||
// Current percent
|
||||
percent: percent,
|
||||
chapters: chapters
|
||||
|
||||
// List of chapter with progress
|
||||
chapters: chapters,
|
||||
|
||||
// Current chapter
|
||||
current: currentChapter
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
var url = require('url');
|
||||
var inherits = require('util').inherits;
|
||||
|
||||
var path = require('path');
|
||||
|
||||
var marked = require('marked');
|
||||
|
||||
|
||||
function GitBookRenderer(options) {
|
||||
function GitBookRenderer(options, extra_options) {
|
||||
if(!(this instanceof GitBookRenderer)) {
|
||||
return new GitBookRenderer(options);
|
||||
return new GitBookRenderer(options, extra_options);
|
||||
}
|
||||
GitBookRenderer.super_.call(this, options);
|
||||
|
||||
this._extra_options = extra_options;
|
||||
}
|
||||
inherits(GitBookRenderer, marked.Renderer);
|
||||
|
||||
@@ -39,6 +43,16 @@ GitBookRenderer.prototype.link = function(href, title, text) {
|
||||
// Parsed version of the url
|
||||
var parsed = url.parse(href);
|
||||
|
||||
var o = this._extra_options;
|
||||
// Relative link, rewrite it to point to github repo
|
||||
if(parsed.path[0] != '/' && o && o.repo && o.dir) {
|
||||
href = 'https://github.com/' + o.repo + '/blob' + path.normalize(path.join(
|
||||
'/',
|
||||
o.dir,
|
||||
href
|
||||
));
|
||||
parsed = url.parse(href);
|
||||
}
|
||||
|
||||
// Generate HTML for link
|
||||
var out = '<a href="' + href + '"';
|
||||
|
||||
@@ -82,10 +82,7 @@ function parseTitle(src, nums) {
|
||||
level: level,
|
||||
|
||||
// Replace .md references with .html
|
||||
path: matches[2].replace(/\.md$/, '.html'),
|
||||
|
||||
// Original, non normalized path
|
||||
_path: matches[2],
|
||||
path: matches[2],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "gitbook",
|
||||
"version": "0.0.3",
|
||||
"version": "0.1.1",
|
||||
"description": "Library and cmd utility to generate GitBooks",
|
||||
"main": "lib/index.js",
|
||||
"dependencies": {
|
||||
|
||||
|
Before Width: | Height: | Size: 157 KiB After Width: | Height: | Size: 110 KiB |
@@ -1,13 +0,0 @@
|
||||
<div class="book-header">
|
||||
<!-- Actions Left -->
|
||||
<a href="https://github.com/{{ githubId }}" target="_blank" class="btn pull-left"><i class="fa fa-github-alt"></i></a>
|
||||
<a href="#" class="btn pull-left toggle-summary"><i class="fa fa-align-justify"></i> Summary</a>
|
||||
|
||||
<!-- Actions Right -->
|
||||
<a href="https://github.com/{{ githubId }}/stargazers" target="_blank" class="btn pull-right count-star"><i class="fa fa-star-o"></i> Star (<span>-</span>)</a>
|
||||
<a href="https://github.com/{{ githubId }}/watchers" target="_blank" class="btn pull-right count-watch"><i class="fa fa-eye"></i> Watch (<span>-</span>)</a>
|
||||
|
||||
|
||||
<!-- Title -->
|
||||
<h1><a href="{{ basePath }}/README.html" >{{ title }}</a></h1>
|
||||
</div>
|
||||
@@ -1,30 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html lang="en-US">
|
||||
<head>
|
||||
{% block head %}
|
||||
<meta charset="UTF-8">
|
||||
<title>{% block title %} | GitBook{% endblock %}</title>
|
||||
<meta name="robots" content="{% block robots %}noindex, nofollow{% endblock %}">
|
||||
<link rel="shortcut icon" href="{{ staticBase }}/images/favicon.ico" type="image/x-icon">
|
||||
<link rel="stylesheet" href="{{ staticBase }}/style.css">
|
||||
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
||||
<meta name="description" content="{{ description }}">
|
||||
<meta name="keywords" content="gitbook,github" >
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black">
|
||||
<script type="text/javascript">
|
||||
(function(e,b){if(!b.__SV){var a,f,i,g;window.mixpanel=b;b._i=[];b.init=function(a,e,d){function f(b,h){var a=h.split(".");2==a.length&&(b=b[a[0]],h=a[1]);b[h]=function(){b.push([h].concat(Array.prototype.slice.call(arguments,0)))}}var c=b;"undefined"!==typeof d?c=b[d]=[]:d="mixpanel";c.people=c.people||[];c.toString=function(b){var a="mixpanel";"mixpanel"!==d&&(a+="."+d);b||(a+=" (stub)");return a};c.people.toString=function(){return c.toString(1)+".people (stub)"};i="disable track track_pageview track_links track_forms register register_once alias unregister identify name_tag set_config people.set people.set_once people.increment people.append people.track_charge people.clear_charges people.delete_user".split(" ");
|
||||
for(g=0;g<i.length;g++)f(c,i[g]);b._i.push([a,e,d])};b.__SV=1.2;a=e.createElement("script");a.type="text/javascript";a.src=("https:"===e.location.protocol?"https:":"http:")+'//cdn.mxpnl.com/libs/mixpanel-2.2.min.js';f=e.getElementsByTagName("script")[0];f.parentNode.insertBefore(a,f)}})(document,window.mixpanel||[]);
|
||||
mixpanel.init("01eb2b950ae09a5fdb15a98dcc5ff20e");
|
||||
</script>
|
||||
{% endblock %}
|
||||
</head>
|
||||
<body>
|
||||
{% block content %}{% endblock %}
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.1.3/ace.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.1.3/mode-javascript.js"></script>
|
||||
<script src="{{ staticBase }}/jsrepl/jsrepl.js" id="jsrepl-script"></script>
|
||||
<script src="{{ staticBase }}/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,53 +0,0 @@
|
||||
{% extends "layout.html" %}
|
||||
|
||||
{% block title %}{{ _input }} {{ title }}{% parent %}{% endblock %}
|
||||
{% block description %}{% endblock %}
|
||||
{% block robots %}index, follow{% endblock %}
|
||||
{% block content %}
|
||||
<div class="book {% if _input == "README.md" %}with-summary{% endif %}" data-github="{{ githubId }}" data-level="{{ navigation.level }}">
|
||||
{% include "includes/book/header.html" %}
|
||||
{% include "includes/book/summary.html" %}
|
||||
<div class="book-body">
|
||||
<div class="page-wrapper">
|
||||
<div class="book-progress">
|
||||
<div class="bar">
|
||||
<div class="inner" style="width: {{ progress.percent }}%;min-width: {{ progress.prevPercent }}%;"></div>
|
||||
</div>
|
||||
<div class="chapters">
|
||||
{% for p in progress.chapters %}
|
||||
<a href="{{ basePath }}/{{ p.path }}" title="{{ p.title }}" class="chapter {% if p.done %}done{% endif %} {% if p.level.length == 1 %}new-chapter{% endif %}" data-progress="{{ p.level }}" style="left: {{ p.percent }}%;"></a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="page-inner">
|
||||
{% for section in content %}
|
||||
<section class="{{ section.type }}" id="section-{{ section.id }}">
|
||||
{% if section.type == "normal" %}
|
||||
{% autoescape false %}{{ section.content }}{% endautoescape %}
|
||||
{% elif section.type == "exercise" %}
|
||||
{% include "./includes/book/exercise.html" with {section: section} %}
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<div class="page-footer">
|
||||
{% if _input == "README.md" %}
|
||||
<a href="{{ basePath }}/{{ navigation.next.path }}" class="navigation-link">Start</a>
|
||||
{% else %}
|
||||
{% if navigation.next %}
|
||||
{% if navigation.next.path %}
|
||||
<a href="{{ basePath }}/{{ navigation.next.path }}" class="navigation-link next">Next</a>
|
||||
{% else %}
|
||||
<div class="navigation-link coming-soon">Coming soon</div>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<div class="navigation-link finished">Finished!</div>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,3 @@
|
||||
# Nice course
|
||||
|
||||
Check out this source file [in C++](../src/something.cpp)
|
||||
@@ -0,0 +1,11 @@
|
||||
## Wow such book
|
||||
|
||||
Some nice content here
|
||||
|
||||
---
|
||||
|
||||
A beautiful separator, but non an exercise !
|
||||
|
||||
---
|
||||
|
||||
Some more beautiful text, because `this` book is awesome ...
|
||||
@@ -13,57 +13,57 @@ var LEXED = summary(CONTENT);
|
||||
describe('Summary navigation', function() {
|
||||
it('should provide next & prev entries for a file', function() {
|
||||
var nav = navigation(LEXED, [
|
||||
'README.html',
|
||||
'chapter-1/README.html',
|
||||
'chapter-1/ARTICLE1.html',
|
||||
'chapter-1/ARTICLE2.html',
|
||||
'chapter-2/README.html',
|
||||
'README.md',
|
||||
'chapter-1/README.md',
|
||||
'chapter-1/ARTICLE1.md',
|
||||
'chapter-1/ARTICLE2.md',
|
||||
'chapter-2/README.md',
|
||||
]);
|
||||
|
||||
// Make sure it found the files we gave it
|
||||
assert(nav['README.html']);
|
||||
assert(nav['chapter-1/README.html']);
|
||||
assert(nav['chapter-1/ARTICLE1.html']);
|
||||
assert(nav['chapter-1/ARTICLE2.html']);
|
||||
assert(nav['chapter-2/README.html']);
|
||||
assert(nav['README.md']);
|
||||
assert(nav['chapter-1/README.md']);
|
||||
assert(nav['chapter-1/ARTICLE1.md']);
|
||||
assert(nav['chapter-1/ARTICLE2.md']);
|
||||
assert(nav['chapter-2/README.md']);
|
||||
|
||||
|
||||
assert.equal(nav['README.html'].prev, null);
|
||||
assert.equal(nav['README.html'].next.path, 'chapter-1/README.html');
|
||||
assert.equal(nav['README.md'].prev, null);
|
||||
assert.equal(nav['README.md'].next.path, 'chapter-1/README.md');
|
||||
|
||||
assert.equal(nav['chapter-1/README.html'].prev.path, 'README.html');
|
||||
assert.equal(nav['chapter-1/README.html'].next.path, 'chapter-1/ARTICLE1.html');
|
||||
assert.equal(nav['chapter-1/README.md'].prev.path, 'README.md');
|
||||
assert.equal(nav['chapter-1/README.md'].next.path, 'chapter-1/ARTICLE1.md');
|
||||
|
||||
assert.equal(nav['chapter-1/ARTICLE1.html'].prev.path, 'chapter-1/README.html');
|
||||
assert.equal(nav['chapter-1/ARTICLE1.html'].next.path, 'chapter-1/ARTICLE2.html');
|
||||
assert.equal(nav['chapter-1/ARTICLE1.md'].prev.path, 'chapter-1/README.md');
|
||||
assert.equal(nav['chapter-1/ARTICLE1.md'].next.path, 'chapter-1/ARTICLE2.md');
|
||||
|
||||
assert.equal(nav['chapter-1/ARTICLE2.html'].prev.path, 'chapter-1/ARTICLE1.html');
|
||||
assert.equal(nav['chapter-1/ARTICLE2.html'].next.path, 'chapter-2/README.html');
|
||||
assert.equal(nav['chapter-1/ARTICLE2.md'].prev.path, 'chapter-1/ARTICLE1.md');
|
||||
assert.equal(nav['chapter-1/ARTICLE2.md'].next.path, 'chapter-2/README.md');
|
||||
|
||||
assert.equal(nav['chapter-2/README.html'].prev.path, 'chapter-1/ARTICLE2.html');
|
||||
assert.equal(nav['chapter-2/README.html'].next.path, 'chapter-3/README.html');
|
||||
assert.equal(nav['chapter-2/README.md'].prev.path, 'chapter-1/ARTICLE2.md');
|
||||
assert.equal(nav['chapter-2/README.md'].next.path, 'chapter-3/README.md');
|
||||
});
|
||||
|
||||
it('should give full tree, when not limited', function() {
|
||||
var nav = navigation(LEXED);
|
||||
|
||||
assert(nav['README.html']);
|
||||
assert(nav['chapter-1/README.html']);
|
||||
assert(nav['chapter-1/ARTICLE1.html']);
|
||||
assert(nav['chapter-1/ARTICLE2.html']);
|
||||
assert(nav['chapter-2/README.html']);
|
||||
assert(nav['chapter-3/README.html']);
|
||||
assert(nav['README.md']);
|
||||
assert(nav['chapter-1/README.md']);
|
||||
assert(nav['chapter-1/ARTICLE1.md']);
|
||||
assert(nav['chapter-1/ARTICLE2.md']);
|
||||
assert(nav['chapter-2/README.md']);
|
||||
assert(nav['chapter-3/README.md']);
|
||||
});
|
||||
|
||||
it('should detect levels correctly', function() {
|
||||
var nav = navigation(LEXED);
|
||||
|
||||
assert.equal(nav['README.html'].level, '0');
|
||||
assert.equal(nav['chapter-1/README.html'].level, '1');
|
||||
assert.equal(nav['chapter-1/ARTICLE1.html'].level, '1.1');
|
||||
assert.equal(nav['chapter-1/ARTICLE2.html'].level, '1.2');
|
||||
assert.equal(nav['chapter-2/README.html'].level, '2');
|
||||
assert.equal(nav['chapter-3/README.html'].level, '3');
|
||||
assert.equal(nav['README.md'].level, '0');
|
||||
assert.equal(nav['chapter-1/README.md'].level, '1');
|
||||
assert.equal(nav['chapter-1/ARTICLE1.md'].level, '1.1');
|
||||
assert.equal(nav['chapter-1/ARTICLE2.md'].level, '1.2');
|
||||
assert.equal(nav['chapter-2/README.md'].level, '2');
|
||||
assert.equal(nav['chapter-3/README.md'].level, '3');
|
||||
});
|
||||
|
||||
it('should not accept null paths', function() {
|
||||
|
||||
@@ -8,6 +8,12 @@ var page = require('../').parse.page;
|
||||
var CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/PAGE.md'), 'utf8');
|
||||
var LEXED = page(CONTENT);
|
||||
|
||||
var HR_CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/HR_PAGE.md'), 'utf8');
|
||||
var HR_LEXED = page(HR_CONTENT);
|
||||
|
||||
var LINKS_CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/GITHUB_LINKS.md'), 'utf8');
|
||||
|
||||
|
||||
describe('Page parsing', function() {
|
||||
it('should detection sections', function() {
|
||||
assert.equal(LEXED.length, 3);
|
||||
@@ -31,4 +37,27 @@ describe('Page parsing', function() {
|
||||
assert(LEXED[1].code.solution);
|
||||
assert(LEXED[1].code.validation);
|
||||
});
|
||||
|
||||
it('should merge sections correctly', function() {
|
||||
// One big section
|
||||
assert.equal(HR_LEXED.length, 1);
|
||||
|
||||
// HRs inserted correctly
|
||||
assert.equal(HR_LEXED[0].content.match(/<hr>/g).length, 2);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('Relative links', function() {
|
||||
it('should be resolved to their GitHub counterparts', function() {
|
||||
var LEXED = page(LINKS_CONTENT, {
|
||||
// GitHub repo ID
|
||||
repo: 'GitBookIO/javascript',
|
||||
|
||||
// Imaginary folder of markdown file
|
||||
dir: 'course',
|
||||
});
|
||||
|
||||
assert(LEXED[0].content.indexOf('https://github.com/GitBookIO/javascript/blob/src/something.cpp') !== -1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -37,12 +37,9 @@ describe('Summary parsing', function () {
|
||||
});
|
||||
|
||||
it('should normalize paths from .md to .html', function() {
|
||||
assert.equal(LEXED.chapters[0].path,'chapter-1/README.html');
|
||||
assert.equal(LEXED.chapters[0]._path,'chapter-1/README.md');
|
||||
assert.equal(LEXED.chapters[1].path,'chapter-2/README.html');
|
||||
assert.equal(LEXED.chapters[1]._path,'chapter-2/README.md');
|
||||
assert.equal(LEXED.chapters[2].path,'chapter-3/README.html');
|
||||
assert.equal(LEXED.chapters[2]._path,'chapter-3/README.md');
|
||||
assert.equal(LEXED.chapters[0].path,'chapter-1/README.md');
|
||||
assert.equal(LEXED.chapters[1].path,'chapter-2/README.md');
|
||||
assert.equal(LEXED.chapters[2].path,'chapter-3/README.md');
|
||||
});
|
||||
|
||||
it('should detect levels correctly', function() {
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# GitBook Theme
|
||||
|
||||
For creating a theme for GitBook, just copy this folder. The theme folder should at least contains two folders: `assets` and `templates`.
|
||||
|
||||
The theme can be changed using the option ```--theme=<path>```
|
||||
|
Before Width: | Height: | Size: 198 KiB After Width: | Height: | Size: 198 KiB |
|
Before Width: | Height: | Size: 59 KiB After Width: | Height: | Size: 59 KiB |
|
Before Width: | Height: | Size: 60 KiB After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1 @@
|
||||
h1,h2{page-break-after:avoid;page-break-before:auto}pre,blockquote{border:1px solid #999;page-break-inside:avoid}img{max-width:100%!important;page-break-inside:avoid}section{page-break-after:always}section#cover{padding:3cm 0;text-align:center}section#cover h1{font-size:1.5cm}section#summary{text-align:center}section#summary ul{font-size:.5cm;line-height:1.8em;padding:0;margin:0;list-style:none}section#summary>ul>li{margin-bottom:1cm}section#summary>ul>li>a{font-size:.6cm}section article{margin:1.5cm}section article.new-chapter{page-break-after:always;font-size:.6cm;text-align:center;padding:3cm 0;border-top:1px solid #ccc}@media print{section article.new-chapter{border:0}}section article .exercise{border:3px solid #ddd}
|
||||
@@ -1,21 +1,28 @@
|
||||
require([
|
||||
"jQuery",
|
||||
"utils/storage",
|
||||
"utils/analytic",
|
||||
"utils/sharing",
|
||||
|
||||
"core/state",
|
||||
"core/keyboard",
|
||||
"core/exercise",
|
||||
"core/progress",
|
||||
"core/sidebar"
|
||||
], function($, analytic, _state, exercise, progress, sidebar){
|
||||
], function($, storage, analytic, sharing, _state, keyboard, exercise, progress, sidebar){
|
||||
$(document).ready(function() {
|
||||
var state = _state();
|
||||
var $book = state.$book;
|
||||
|
||||
// Tract page view
|
||||
analytic.track("View");
|
||||
// Initialize storage
|
||||
storage.setBaseKey(state.githubId);
|
||||
|
||||
// Init sidebar
|
||||
sidebar.init();
|
||||
|
||||
// Init keyboard
|
||||
keyboard.init();
|
||||
|
||||
// Star and watch count
|
||||
$.getJSON("https://api.github.com/repos/"+state.githubId)
|
||||
.done(function(repo) {
|
||||
@@ -26,7 +33,13 @@ require([
|
||||
// Bind exercise
|
||||
exercise.init();
|
||||
|
||||
// Bind sharing button
|
||||
sharing.init();
|
||||
|
||||
// Show progress
|
||||
progress.show();
|
||||
|
||||
// Focus on content
|
||||
$(".book-body").focus();
|
||||
});
|
||||
});
|
||||
@@ -32,6 +32,7 @@ define([
|
||||
e.preventDefault();
|
||||
|
||||
editor.setValue(codeSolution);
|
||||
editor.gotoLine(0);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
define([
|
||||
"jQuery",
|
||||
"Mousetrap",
|
||||
"core/navigation",
|
||||
"core/sidebar"
|
||||
], function($, Mousetrap, navigation, sidebar){
|
||||
// Bind keyboard shortcuts
|
||||
var init = function() {
|
||||
// Next
|
||||
Mousetrap.bind(['right'], function(e) {
|
||||
navigation.goNext();
|
||||
return false;
|
||||
});
|
||||
|
||||
// Prev
|
||||
Mousetrap.bind(['left'], function(e) {
|
||||
navigation.goPrev();
|
||||
return false;
|
||||
});
|
||||
|
||||
// Toggle Summary
|
||||
Mousetrap.bind(['s'], function(e) {
|
||||
sidebar.toggle();
|
||||
return false;
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
init: init
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
define([
|
||||
"jQuery"
|
||||
], function($) {
|
||||
var goNext = function() {
|
||||
var url = $("link[rel='next']").attr("href");
|
||||
if (url) location.href = url;
|
||||
};
|
||||
var goPrev = function() {
|
||||
var url = $("link[rel='prev']").attr("href");
|
||||
if (url) location.href = url;
|
||||
};
|
||||
|
||||
return {
|
||||
goNext: goNext,
|
||||
goPrev: goPrev
|
||||
};
|
||||
});
|
||||
@@ -6,6 +6,7 @@ define([
|
||||
|
||||
// Toggle sidebar with or withour animation
|
||||
var toggleSidebar = function(_state, animation) {
|
||||
if (-state != null && isOpen() == _state) return;
|
||||
if (animation == null) animation = true;
|
||||
|
||||
var $book = state().$book;
|
||||
@@ -30,8 +31,10 @@ define([
|
||||
toggleSidebar();
|
||||
});
|
||||
|
||||
// Init last state if not mobile and not homepage
|
||||
if (!isOpen()) toggleSidebar(platform.isMobile ? false : storage.get("sidebar", false), false);
|
||||
// Init last state if not mobile
|
||||
if (!platform.isMobile) {
|
||||
toggleSidebar(storage.get("sidebar", true), false);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -0,0 +1,30 @@
|
||||
define([
|
||||
"lodash",
|
||||
"mixpanel"
|
||||
], function(_, mixpanel) {
|
||||
mixpanel.init("01eb2b950ae09a5fdb15a98dcc5ff20e", {
|
||||
loaded: function() {
|
||||
track("View");
|
||||
}
|
||||
});
|
||||
|
||||
var isAvailable = function() {
|
||||
return (typeof mixpanel !== "undefined");
|
||||
};
|
||||
|
||||
var track = function(e, data) {
|
||||
if (!isAvailable()) {
|
||||
console.warn("tracking not available!");
|
||||
return;
|
||||
}
|
||||
console.log("track", e);
|
||||
mixpanel.track(e, _.extend(data || {}, {
|
||||
'domain': window.location.host
|
||||
}));
|
||||
};
|
||||
|
||||
return {
|
||||
isAvailable: isAvailable,
|
||||
track: track
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
define([
|
||||
"jQuery"
|
||||
], function($) {
|
||||
var url = location.href;
|
||||
var title = $("title").text();
|
||||
|
||||
var types = {
|
||||
"twitter": function($el) {
|
||||
window.open("http://twitter.com/home?status="+encodeURIComponent(title+" "+url))
|
||||
},
|
||||
"facebook": function($el) {
|
||||
window.open("http://www.facebook.com/sharer/sharer.php?s=100&p[url]="+encodeURIComponent(url))
|
||||
},
|
||||
"google-plus": function($el) {
|
||||
window.open("https://plus.google.com/share?url="+encodeURIComponent(url))
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// Bind all sharing button
|
||||
var init = function() {
|
||||
$("a[data-sharing]").click(function(e) {
|
||||
if (e) e.preventDefault();
|
||||
var type = $(this).data("sharing");
|
||||
|
||||
types[type]($(this));
|
||||
})
|
||||
};
|
||||
|
||||
return {
|
||||
init: init
|
||||
};
|
||||
});
|
||||
@@ -1,19 +1,30 @@
|
||||
define(function(){
|
||||
var baseKey = "";
|
||||
|
||||
/*
|
||||
* Simple module for storing data in the browser's local storage
|
||||
*/
|
||||
return {
|
||||
setBaseKey: function(key) {
|
||||
baseKey = key;
|
||||
},
|
||||
set: function(key, value) {
|
||||
key = baseKey+":"+key;
|
||||
localStorage[key] = JSON.stringify(value);
|
||||
},
|
||||
get: function(key, def) {
|
||||
key = baseKey+":"+key;
|
||||
if (localStorage[key] === undefined) return def;
|
||||
try {
|
||||
return JSON.parse(localStorage[key]) || def;
|
||||
var v = JSON.parse(localStorage[key]);
|
||||
return v == null ? def : v;;
|
||||
} catch(err) {
|
||||
console.error(err);
|
||||
return localStorage[key] || def;
|
||||
}
|
||||
},
|
||||
remove: function(key) {
|
||||
key = baseKey+":"+key;
|
||||
localStorage.removeItem(key);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,2 @@
|
||||
(function(e,b){if(!b.__SV){var a,f,i,g;window.mixpanel=b;b._i=[];b.init=function(a,e,d){function f(b,h){var a=h.split(".");2==a.length&&(b=b[a[0]],h=a[1]);b[h]=function(){b.push([h].concat(Array.prototype.slice.call(arguments,0)))}}var c=b;"undefined"!==typeof d?c=b[d]=[]:d="mixpanel";c.people=c.people||[];c.toString=function(b){var a="mixpanel";"mixpanel"!==d&&(a+="."+d);b||(a+=" (stub)");return a};c.people.toString=function(){return c.toString(1)+".people (stub)"};i="disable track track_pageview track_links track_forms register register_once alias unregister identify name_tag set_config people.set people.set_once people.increment people.append people.track_charge people.clear_charges people.delete_user".split(" ");
|
||||
for(g=0;g<i.length;g++)f(c,i[g]);b._i.push([a,e,d])};b.__SV=1.2;a=e.createElement("script");a.type="text/javascript";a.async=!0;a.src=("https:"===e.location.protocol?"https:":"http:")+'//cdn.mxpnl.com/libs/mixpanel-2.2.min.js';f=e.getElementsByTagName("script")[0];f.parentNode.insertBefore(a,f)}})(document,window.mixpanel||[]);
|
||||
@@ -0,0 +1,953 @@
|
||||
/*global define:false */
|
||||
/**
|
||||
* Copyright 2013 Craig Campbell
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
* Mousetrap is a simple keyboard shortcut library for Javascript with
|
||||
* no external dependencies
|
||||
*
|
||||
* @version 1.4.6
|
||||
* @url craig.is/killing/mice
|
||||
*/
|
||||
(function(window, document, undefined) {
|
||||
|
||||
/**
|
||||
* mapping of special keycodes to their corresponding keys
|
||||
*
|
||||
* everything in this dictionary cannot use keypress events
|
||||
* so it has to be here to map to the correct keycodes for
|
||||
* keyup/keydown events
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
var _MAP = {
|
||||
8: 'backspace',
|
||||
9: 'tab',
|
||||
13: 'enter',
|
||||
16: 'shift',
|
||||
17: 'ctrl',
|
||||
18: 'alt',
|
||||
20: 'capslock',
|
||||
27: 'esc',
|
||||
32: 'space',
|
||||
33: 'pageup',
|
||||
34: 'pagedown',
|
||||
35: 'end',
|
||||
36: 'home',
|
||||
37: 'left',
|
||||
38: 'up',
|
||||
39: 'right',
|
||||
40: 'down',
|
||||
45: 'ins',
|
||||
46: 'del',
|
||||
91: 'meta',
|
||||
93: 'meta',
|
||||
224: 'meta'
|
||||
},
|
||||
|
||||
/**
|
||||
* mapping for special characters so they can support
|
||||
*
|
||||
* this dictionary is only used incase you want to bind a
|
||||
* keyup or keydown event to one of these keys
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
_KEYCODE_MAP = {
|
||||
106: '*',
|
||||
107: '+',
|
||||
109: '-',
|
||||
110: '.',
|
||||
111 : '/',
|
||||
186: ';',
|
||||
187: '=',
|
||||
188: ',',
|
||||
189: '-',
|
||||
190: '.',
|
||||
191: '/',
|
||||
192: '`',
|
||||
219: '[',
|
||||
220: '\\',
|
||||
221: ']',
|
||||
222: '\''
|
||||
},
|
||||
|
||||
/**
|
||||
* this is a mapping of keys that require shift on a US keypad
|
||||
* back to the non shift equivelents
|
||||
*
|
||||
* this is so you can use keyup events with these keys
|
||||
*
|
||||
* note that this will only work reliably on US keyboards
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
_SHIFT_MAP = {
|
||||
'~': '`',
|
||||
'!': '1',
|
||||
'@': '2',
|
||||
'#': '3',
|
||||
'$': '4',
|
||||
'%': '5',
|
||||
'^': '6',
|
||||
'&': '7',
|
||||
'*': '8',
|
||||
'(': '9',
|
||||
')': '0',
|
||||
'_': '-',
|
||||
'+': '=',
|
||||
':': ';',
|
||||
'\"': '\'',
|
||||
'<': ',',
|
||||
'>': '.',
|
||||
'?': '/',
|
||||
'|': '\\'
|
||||
},
|
||||
|
||||
/**
|
||||
* this is a list of special strings you can use to map
|
||||
* to modifier keys when you specify your keyboard shortcuts
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
_SPECIAL_ALIASES = {
|
||||
'option': 'alt',
|
||||
'command': 'meta',
|
||||
'return': 'enter',
|
||||
'escape': 'esc',
|
||||
'mod': /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl'
|
||||
},
|
||||
|
||||
/**
|
||||
* variable to store the flipped version of _MAP from above
|
||||
* needed to check if we should use keypress or not when no action
|
||||
* is specified
|
||||
*
|
||||
* @type {Object|undefined}
|
||||
*/
|
||||
_REVERSE_MAP,
|
||||
|
||||
/**
|
||||
* a list of all the callbacks setup via Mousetrap.bind()
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
_callbacks = {},
|
||||
|
||||
/**
|
||||
* direct map of string combinations to callbacks used for trigger()
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
_directMap = {},
|
||||
|
||||
/**
|
||||
* keeps track of what level each sequence is at since multiple
|
||||
* sequences can start out with the same sequence
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
_sequenceLevels = {},
|
||||
|
||||
/**
|
||||
* variable to store the setTimeout call
|
||||
*
|
||||
* @type {null|number}
|
||||
*/
|
||||
_resetTimer,
|
||||
|
||||
/**
|
||||
* temporary state where we will ignore the next keyup
|
||||
*
|
||||
* @type {boolean|string}
|
||||
*/
|
||||
_ignoreNextKeyup = false,
|
||||
|
||||
/**
|
||||
* temporary state where we will ignore the next keypress
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
_ignoreNextKeypress = false,
|
||||
|
||||
/**
|
||||
* are we currently inside of a sequence?
|
||||
* type of action ("keyup" or "keydown" or "keypress") or false
|
||||
*
|
||||
* @type {boolean|string}
|
||||
*/
|
||||
_nextExpectedAction = false;
|
||||
|
||||
/**
|
||||
* loop through the f keys, f1 to f19 and add them to the map
|
||||
* programatically
|
||||
*/
|
||||
for (var i = 1; i < 20; ++i) {
|
||||
_MAP[111 + i] = 'f' + i;
|
||||
}
|
||||
|
||||
/**
|
||||
* loop through to map numbers on the numeric keypad
|
||||
*/
|
||||
for (i = 0; i <= 9; ++i) {
|
||||
_MAP[i + 96] = i;
|
||||
}
|
||||
|
||||
/**
|
||||
* cross browser add event method
|
||||
*
|
||||
* @param {Element|HTMLDocument} object
|
||||
* @param {string} type
|
||||
* @param {Function} callback
|
||||
* @returns void
|
||||
*/
|
||||
function _addEvent(object, type, callback) {
|
||||
if (object.addEventListener) {
|
||||
object.addEventListener(type, callback, false);
|
||||
return;
|
||||
}
|
||||
|
||||
object.attachEvent('on' + type, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* takes the event and returns the key character
|
||||
*
|
||||
* @param {Event} e
|
||||
* @return {string}
|
||||
*/
|
||||
function _characterFromEvent(e) {
|
||||
|
||||
// for keypress events we should return the character as is
|
||||
if (e.type == 'keypress') {
|
||||
var character = String.fromCharCode(e.which);
|
||||
|
||||
// if the shift key is not pressed then it is safe to assume
|
||||
// that we want the character to be lowercase. this means if
|
||||
// you accidentally have caps lock on then your key bindings
|
||||
// will continue to work
|
||||
//
|
||||
// the only side effect that might not be desired is if you
|
||||
// bind something like 'A' cause you want to trigger an
|
||||
// event when capital A is pressed caps lock will no longer
|
||||
// trigger the event. shift+a will though.
|
||||
if (!e.shiftKey) {
|
||||
character = character.toLowerCase();
|
||||
}
|
||||
|
||||
return character;
|
||||
}
|
||||
|
||||
// for non keypress events the special maps are needed
|
||||
if (_MAP[e.which]) {
|
||||
return _MAP[e.which];
|
||||
}
|
||||
|
||||
if (_KEYCODE_MAP[e.which]) {
|
||||
return _KEYCODE_MAP[e.which];
|
||||
}
|
||||
|
||||
// if it is not in the special map
|
||||
|
||||
// with keydown and keyup events the character seems to always
|
||||
// come in as an uppercase character whether you are pressing shift
|
||||
// or not. we should make sure it is always lowercase for comparisons
|
||||
return String.fromCharCode(e.which).toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* checks if two arrays are equal
|
||||
*
|
||||
* @param {Array} modifiers1
|
||||
* @param {Array} modifiers2
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function _modifiersMatch(modifiers1, modifiers2) {
|
||||
return modifiers1.sort().join(',') === modifiers2.sort().join(',');
|
||||
}
|
||||
|
||||
/**
|
||||
* resets all sequence counters except for the ones passed in
|
||||
*
|
||||
* @param {Object} doNotReset
|
||||
* @returns void
|
||||
*/
|
||||
function _resetSequences(doNotReset) {
|
||||
doNotReset = doNotReset || {};
|
||||
|
||||
var activeSequences = false,
|
||||
key;
|
||||
|
||||
for (key in _sequenceLevels) {
|
||||
if (doNotReset[key]) {
|
||||
activeSequences = true;
|
||||
continue;
|
||||
}
|
||||
_sequenceLevels[key] = 0;
|
||||
}
|
||||
|
||||
if (!activeSequences) {
|
||||
_nextExpectedAction = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* finds all callbacks that match based on the keycode, modifiers,
|
||||
* and action
|
||||
*
|
||||
* @param {string} character
|
||||
* @param {Array} modifiers
|
||||
* @param {Event|Object} e
|
||||
* @param {string=} sequenceName - name of the sequence we are looking for
|
||||
* @param {string=} combination
|
||||
* @param {number=} level
|
||||
* @returns {Array}
|
||||
*/
|
||||
function _getMatches(character, modifiers, e, sequenceName, combination, level) {
|
||||
var i,
|
||||
callback,
|
||||
matches = [],
|
||||
action = e.type;
|
||||
|
||||
// if there are no events related to this keycode
|
||||
if (!_callbacks[character]) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// if a modifier key is coming up on its own we should allow it
|
||||
if (action == 'keyup' && _isModifier(character)) {
|
||||
modifiers = [character];
|
||||
}
|
||||
|
||||
// loop through all callbacks for the key that was pressed
|
||||
// and see if any of them match
|
||||
for (i = 0; i < _callbacks[character].length; ++i) {
|
||||
callback = _callbacks[character][i];
|
||||
|
||||
// if a sequence name is not specified, but this is a sequence at
|
||||
// the wrong level then move onto the next match
|
||||
if (!sequenceName && callback.seq && _sequenceLevels[callback.seq] != callback.level) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// if the action we are looking for doesn't match the action we got
|
||||
// then we should keep going
|
||||
if (action != callback.action) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// if this is a keypress event and the meta key and control key
|
||||
// are not pressed that means that we need to only look at the
|
||||
// character, otherwise check the modifiers as well
|
||||
//
|
||||
// chrome will not fire a keypress if meta or control is down
|
||||
// safari will fire a keypress if meta or meta+shift is down
|
||||
// firefox will fire a keypress if meta or control is down
|
||||
if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) {
|
||||
|
||||
// when you bind a combination or sequence a second time it
|
||||
// should overwrite the first one. if a sequenceName or
|
||||
// combination is specified in this call it does just that
|
||||
//
|
||||
// @todo make deleting its own method?
|
||||
var deleteCombo = !sequenceName && callback.combo == combination;
|
||||
var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level;
|
||||
if (deleteCombo || deleteSequence) {
|
||||
_callbacks[character].splice(i, 1);
|
||||
}
|
||||
|
||||
matches.push(callback);
|
||||
}
|
||||
}
|
||||
|
||||
return matches;
|
||||
}
|
||||
|
||||
/**
|
||||
* takes a key event and figures out what the modifiers are
|
||||
*
|
||||
* @param {Event} e
|
||||
* @returns {Array}
|
||||
*/
|
||||
function _eventModifiers(e) {
|
||||
var modifiers = [];
|
||||
|
||||
if (e.shiftKey) {
|
||||
modifiers.push('shift');
|
||||
}
|
||||
|
||||
if (e.altKey) {
|
||||
modifiers.push('alt');
|
||||
}
|
||||
|
||||
if (e.ctrlKey) {
|
||||
modifiers.push('ctrl');
|
||||
}
|
||||
|
||||
if (e.metaKey) {
|
||||
modifiers.push('meta');
|
||||
}
|
||||
|
||||
return modifiers;
|
||||
}
|
||||
|
||||
/**
|
||||
* prevents default for this event
|
||||
*
|
||||
* @param {Event} e
|
||||
* @returns void
|
||||
*/
|
||||
function _preventDefault(e) {
|
||||
if (e.preventDefault) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
|
||||
e.returnValue = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* stops propogation for this event
|
||||
*
|
||||
* @param {Event} e
|
||||
* @returns void
|
||||
*/
|
||||
function _stopPropagation(e) {
|
||||
if (e.stopPropagation) {
|
||||
e.stopPropagation();
|
||||
return;
|
||||
}
|
||||
|
||||
e.cancelBubble = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* actually calls the callback function
|
||||
*
|
||||
* if your callback function returns false this will use the jquery
|
||||
* convention - prevent default and stop propogation on the event
|
||||
*
|
||||
* @param {Function} callback
|
||||
* @param {Event} e
|
||||
* @returns void
|
||||
*/
|
||||
function _fireCallback(callback, e, combo, sequence) {
|
||||
|
||||
// if this event should not happen stop here
|
||||
if (Mousetrap.stopCallback(e, e.target || e.srcElement, combo, sequence)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (callback(e, combo) === false) {
|
||||
_preventDefault(e);
|
||||
_stopPropagation(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* handles a character key event
|
||||
*
|
||||
* @param {string} character
|
||||
* @param {Array} modifiers
|
||||
* @param {Event} e
|
||||
* @returns void
|
||||
*/
|
||||
function _handleKey(character, modifiers, e) {
|
||||
var callbacks = _getMatches(character, modifiers, e),
|
||||
i,
|
||||
doNotReset = {},
|
||||
maxLevel = 0,
|
||||
processedSequenceCallback = false;
|
||||
|
||||
// Calculate the maxLevel for sequences so we can only execute the longest callback sequence
|
||||
for (i = 0; i < callbacks.length; ++i) {
|
||||
if (callbacks[i].seq) {
|
||||
maxLevel = Math.max(maxLevel, callbacks[i].level);
|
||||
}
|
||||
}
|
||||
|
||||
// loop through matching callbacks for this key event
|
||||
for (i = 0; i < callbacks.length; ++i) {
|
||||
|
||||
// fire for all sequence callbacks
|
||||
// this is because if for example you have multiple sequences
|
||||
// bound such as "g i" and "g t" they both need to fire the
|
||||
// callback for matching g cause otherwise you can only ever
|
||||
// match the first one
|
||||
if (callbacks[i].seq) {
|
||||
|
||||
// only fire callbacks for the maxLevel to prevent
|
||||
// subsequences from also firing
|
||||
//
|
||||
// for example 'a option b' should not cause 'option b' to fire
|
||||
// even though 'option b' is part of the other sequence
|
||||
//
|
||||
// any sequences that do not match here will be discarded
|
||||
// below by the _resetSequences call
|
||||
if (callbacks[i].level != maxLevel) {
|
||||
continue;
|
||||
}
|
||||
|
||||
processedSequenceCallback = true;
|
||||
|
||||
// keep a list of which sequences were matches for later
|
||||
doNotReset[callbacks[i].seq] = 1;
|
||||
_fireCallback(callbacks[i].callback, e, callbacks[i].combo, callbacks[i].seq);
|
||||
continue;
|
||||
}
|
||||
|
||||
// if there were no sequence matches but we are still here
|
||||
// that means this is a regular match so we should fire that
|
||||
if (!processedSequenceCallback) {
|
||||
_fireCallback(callbacks[i].callback, e, callbacks[i].combo);
|
||||
}
|
||||
}
|
||||
|
||||
// if the key you pressed matches the type of sequence without
|
||||
// being a modifier (ie "keyup" or "keypress") then we should
|
||||
// reset all sequences that were not matched by this event
|
||||
//
|
||||
// this is so, for example, if you have the sequence "h a t" and you
|
||||
// type "h e a r t" it does not match. in this case the "e" will
|
||||
// cause the sequence to reset
|
||||
//
|
||||
// modifier keys are ignored because you can have a sequence
|
||||
// that contains modifiers such as "enter ctrl+space" and in most
|
||||
// cases the modifier key will be pressed before the next key
|
||||
//
|
||||
// also if you have a sequence such as "ctrl+b a" then pressing the
|
||||
// "b" key will trigger a "keypress" and a "keydown"
|
||||
//
|
||||
// the "keydown" is expected when there is a modifier, but the
|
||||
// "keypress" ends up matching the _nextExpectedAction since it occurs
|
||||
// after and that causes the sequence to reset
|
||||
//
|
||||
// we ignore keypresses in a sequence that directly follow a keydown
|
||||
// for the same character
|
||||
var ignoreThisKeypress = e.type == 'keypress' && _ignoreNextKeypress;
|
||||
if (e.type == _nextExpectedAction && !_isModifier(character) && !ignoreThisKeypress) {
|
||||
_resetSequences(doNotReset);
|
||||
}
|
||||
|
||||
_ignoreNextKeypress = processedSequenceCallback && e.type == 'keydown';
|
||||
}
|
||||
|
||||
/**
|
||||
* handles a keydown event
|
||||
*
|
||||
* @param {Event} e
|
||||
* @returns void
|
||||
*/
|
||||
function _handleKeyEvent(e) {
|
||||
|
||||
// normalize e.which for key events
|
||||
// @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
|
||||
if (typeof e.which !== 'number') {
|
||||
e.which = e.keyCode;
|
||||
}
|
||||
|
||||
var character = _characterFromEvent(e);
|
||||
|
||||
// no character found then stop
|
||||
if (!character) {
|
||||
return;
|
||||
}
|
||||
|
||||
// need to use === for the character check because the character can be 0
|
||||
if (e.type == 'keyup' && _ignoreNextKeyup === character) {
|
||||
_ignoreNextKeyup = false;
|
||||
return;
|
||||
}
|
||||
|
||||
Mousetrap.handleKey(character, _eventModifiers(e), e);
|
||||
}
|
||||
|
||||
/**
|
||||
* determines if the keycode specified is a modifier key or not
|
||||
*
|
||||
* @param {string} key
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function _isModifier(key) {
|
||||
return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
|
||||
}
|
||||
|
||||
/**
|
||||
* called to set a 1 second timeout on the specified sequence
|
||||
*
|
||||
* this is so after each key press in the sequence you have 1 second
|
||||
* to press the next key before you have to start over
|
||||
*
|
||||
* @returns void
|
||||
*/
|
||||
function _resetSequenceTimer() {
|
||||
clearTimeout(_resetTimer);
|
||||
_resetTimer = setTimeout(_resetSequences, 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* reverses the map lookup so that we can look for specific keys
|
||||
* to see what can and can't use keypress
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function _getReverseMap() {
|
||||
if (!_REVERSE_MAP) {
|
||||
_REVERSE_MAP = {};
|
||||
for (var key in _MAP) {
|
||||
|
||||
// pull out the numeric keypad from here cause keypress should
|
||||
// be able to detect the keys from the character
|
||||
if (key > 95 && key < 112) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (_MAP.hasOwnProperty(key)) {
|
||||
_REVERSE_MAP[_MAP[key]] = key;
|
||||
}
|
||||
}
|
||||
}
|
||||
return _REVERSE_MAP;
|
||||
}
|
||||
|
||||
/**
|
||||
* picks the best action based on the key combination
|
||||
*
|
||||
* @param {string} key - character for key
|
||||
* @param {Array} modifiers
|
||||
* @param {string=} action passed in
|
||||
*/
|
||||
function _pickBestAction(key, modifiers, action) {
|
||||
|
||||
// if no action was picked in we should try to pick the one
|
||||
// that we think would work best for this key
|
||||
if (!action) {
|
||||
action = _getReverseMap()[key] ? 'keydown' : 'keypress';
|
||||
}
|
||||
|
||||
// modifier keys don't work as expected with keypress,
|
||||
// switch to keydown
|
||||
if (action == 'keypress' && modifiers.length) {
|
||||
action = 'keydown';
|
||||
}
|
||||
|
||||
return action;
|
||||
}
|
||||
|
||||
/**
|
||||
* binds a key sequence to an event
|
||||
*
|
||||
* @param {string} combo - combo specified in bind call
|
||||
* @param {Array} keys
|
||||
* @param {Function} callback
|
||||
* @param {string=} action
|
||||
* @returns void
|
||||
*/
|
||||
function _bindSequence(combo, keys, callback, action) {
|
||||
|
||||
// start off by adding a sequence level record for this combination
|
||||
// and setting the level to 0
|
||||
_sequenceLevels[combo] = 0;
|
||||
|
||||
/**
|
||||
* callback to increase the sequence level for this sequence and reset
|
||||
* all other sequences that were active
|
||||
*
|
||||
* @param {string} nextAction
|
||||
* @returns {Function}
|
||||
*/
|
||||
function _increaseSequence(nextAction) {
|
||||
return function() {
|
||||
_nextExpectedAction = nextAction;
|
||||
++_sequenceLevels[combo];
|
||||
_resetSequenceTimer();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* wraps the specified callback inside of another function in order
|
||||
* to reset all sequence counters as soon as this sequence is done
|
||||
*
|
||||
* @param {Event} e
|
||||
* @returns void
|
||||
*/
|
||||
function _callbackAndReset(e) {
|
||||
_fireCallback(callback, e, combo);
|
||||
|
||||
// we should ignore the next key up if the action is key down
|
||||
// or keypress. this is so if you finish a sequence and
|
||||
// release the key the final key will not trigger a keyup
|
||||
if (action !== 'keyup') {
|
||||
_ignoreNextKeyup = _characterFromEvent(e);
|
||||
}
|
||||
|
||||
// weird race condition if a sequence ends with the key
|
||||
// another sequence begins with
|
||||
setTimeout(_resetSequences, 10);
|
||||
}
|
||||
|
||||
// loop through keys one at a time and bind the appropriate callback
|
||||
// function. for any key leading up to the final one it should
|
||||
// increase the sequence. after the final, it should reset all sequences
|
||||
//
|
||||
// if an action is specified in the original bind call then that will
|
||||
// be used throughout. otherwise we will pass the action that the
|
||||
// next key in the sequence should match. this allows a sequence
|
||||
// to mix and match keypress and keydown events depending on which
|
||||
// ones are better suited to the key provided
|
||||
for (var i = 0; i < keys.length; ++i) {
|
||||
var isFinal = i + 1 === keys.length;
|
||||
var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence(action || _getKeyInfo(keys[i + 1]).action);
|
||||
_bindSingle(keys[i], wrappedCallback, action, combo, i);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts from a string key combination to an array
|
||||
*
|
||||
* @param {string} combination like "command+shift+l"
|
||||
* @return {Array}
|
||||
*/
|
||||
function _keysFromString(combination) {
|
||||
if (combination === '+') {
|
||||
return ['+'];
|
||||
}
|
||||
|
||||
return combination.split('+');
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets info for a specific key combination
|
||||
*
|
||||
* @param {string} combination key combination ("command+s" or "a" or "*")
|
||||
* @param {string=} action
|
||||
* @returns {Object}
|
||||
*/
|
||||
function _getKeyInfo(combination, action) {
|
||||
var keys,
|
||||
key,
|
||||
i,
|
||||
modifiers = [];
|
||||
|
||||
// take the keys from this pattern and figure out what the actual
|
||||
// pattern is all about
|
||||
keys = _keysFromString(combination);
|
||||
|
||||
for (i = 0; i < keys.length; ++i) {
|
||||
key = keys[i];
|
||||
|
||||
// normalize key names
|
||||
if (_SPECIAL_ALIASES[key]) {
|
||||
key = _SPECIAL_ALIASES[key];
|
||||
}
|
||||
|
||||
// if this is not a keypress event then we should
|
||||
// be smart about using shift keys
|
||||
// this will only work for US keyboards however
|
||||
if (action && action != 'keypress' && _SHIFT_MAP[key]) {
|
||||
key = _SHIFT_MAP[key];
|
||||
modifiers.push('shift');
|
||||
}
|
||||
|
||||
// if this key is a modifier then add it to the list of modifiers
|
||||
if (_isModifier(key)) {
|
||||
modifiers.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
// depending on what the key combination is
|
||||
// we will try to pick the best event for it
|
||||
action = _pickBestAction(key, modifiers, action);
|
||||
|
||||
return {
|
||||
key: key,
|
||||
modifiers: modifiers,
|
||||
action: action
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* binds a single keyboard combination
|
||||
*
|
||||
* @param {string} combination
|
||||
* @param {Function} callback
|
||||
* @param {string=} action
|
||||
* @param {string=} sequenceName - name of sequence if part of sequence
|
||||
* @param {number=} level - what part of the sequence the command is
|
||||
* @returns void
|
||||
*/
|
||||
function _bindSingle(combination, callback, action, sequenceName, level) {
|
||||
|
||||
// store a direct mapped reference for use with Mousetrap.trigger
|
||||
_directMap[combination + ':' + action] = callback;
|
||||
|
||||
// make sure multiple spaces in a row become a single space
|
||||
combination = combination.replace(/\s+/g, ' ');
|
||||
|
||||
var sequence = combination.split(' '),
|
||||
info;
|
||||
|
||||
// if this pattern is a sequence of keys then run through this method
|
||||
// to reprocess each pattern one key at a time
|
||||
if (sequence.length > 1) {
|
||||
_bindSequence(combination, sequence, callback, action);
|
||||
return;
|
||||
}
|
||||
|
||||
info = _getKeyInfo(combination, action);
|
||||
|
||||
// make sure to initialize array if this is the first time
|
||||
// a callback is added for this key
|
||||
_callbacks[info.key] = _callbacks[info.key] || [];
|
||||
|
||||
// remove an existing match if there is one
|
||||
_getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level);
|
||||
|
||||
// add this call back to the array
|
||||
// if it is a sequence put it at the beginning
|
||||
// if not put it at the end
|
||||
//
|
||||
// this is important because the way these are processed expects
|
||||
// the sequence ones to come first
|
||||
_callbacks[info.key][sequenceName ? 'unshift' : 'push']({
|
||||
callback: callback,
|
||||
modifiers: info.modifiers,
|
||||
action: info.action,
|
||||
seq: sequenceName,
|
||||
level: level,
|
||||
combo: combination
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* binds multiple combinations to the same callback
|
||||
*
|
||||
* @param {Array} combinations
|
||||
* @param {Function} callback
|
||||
* @param {string|undefined} action
|
||||
* @returns void
|
||||
*/
|
||||
function _bindMultiple(combinations, callback, action) {
|
||||
for (var i = 0; i < combinations.length; ++i) {
|
||||
_bindSingle(combinations[i], callback, action);
|
||||
}
|
||||
}
|
||||
|
||||
// start!
|
||||
_addEvent(document, 'keypress', _handleKeyEvent);
|
||||
_addEvent(document, 'keydown', _handleKeyEvent);
|
||||
_addEvent(document, 'keyup', _handleKeyEvent);
|
||||
|
||||
var Mousetrap = {
|
||||
|
||||
/**
|
||||
* binds an event to mousetrap
|
||||
*
|
||||
* can be a single key, a combination of keys separated with +,
|
||||
* an array of keys, or a sequence of keys separated by spaces
|
||||
*
|
||||
* be sure to list the modifier keys first to make sure that the
|
||||
* correct key ends up getting bound (the last key in the pattern)
|
||||
*
|
||||
* @param {string|Array} keys
|
||||
* @param {Function} callback
|
||||
* @param {string=} action - 'keypress', 'keydown', or 'keyup'
|
||||
* @returns void
|
||||
*/
|
||||
bind: function(keys, callback, action) {
|
||||
keys = keys instanceof Array ? keys : [keys];
|
||||
_bindMultiple(keys, callback, action);
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
* unbinds an event to mousetrap
|
||||
*
|
||||
* the unbinding sets the callback function of the specified key combo
|
||||
* to an empty function and deletes the corresponding key in the
|
||||
* _directMap dict.
|
||||
*
|
||||
* TODO: actually remove this from the _callbacks dictionary instead
|
||||
* of binding an empty function
|
||||
*
|
||||
* the keycombo+action has to be exactly the same as
|
||||
* it was defined in the bind method
|
||||
*
|
||||
* @param {string|Array} keys
|
||||
* @param {string} action
|
||||
* @returns void
|
||||
*/
|
||||
unbind: function(keys, action) {
|
||||
return Mousetrap.bind(keys, function() {}, action);
|
||||
},
|
||||
|
||||
/**
|
||||
* triggers an event that has already been bound
|
||||
*
|
||||
* @param {string} keys
|
||||
* @param {string=} action
|
||||
* @returns void
|
||||
*/
|
||||
trigger: function(keys, action) {
|
||||
if (_directMap[keys + ':' + action]) {
|
||||
_directMap[keys + ':' + action]({}, keys);
|
||||
}
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
* resets the library back to its initial state. this is useful
|
||||
* if you want to clear out the current keyboard shortcuts and bind
|
||||
* new ones - for example if you switch to another page
|
||||
*
|
||||
* @returns void
|
||||
*/
|
||||
reset: function() {
|
||||
_callbacks = {};
|
||||
_directMap = {};
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
* should we stop this event before firing off callbacks
|
||||
*
|
||||
* @param {Event} e
|
||||
* @param {Element} element
|
||||
* @return {boolean}
|
||||
*/
|
||||
stopCallback: function(e, element) {
|
||||
|
||||
// if the element has the class "mousetrap" then no need to stop
|
||||
if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// stop for input, select, and textarea
|
||||
return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || element.isContentEditable;
|
||||
},
|
||||
|
||||
/**
|
||||
* exposes _handleKey publicly so it can be overwritten by extensions
|
||||
*/
|
||||
handleKey: _handleKey
|
||||
};
|
||||
|
||||
// expose mousetrap to the global object
|
||||
window.Mousetrap = Mousetrap;
|
||||
|
||||
// expose mousetrap as an AMD module
|
||||
if (typeof define === 'function' && define.amd) {
|
||||
define(Mousetrap);
|
||||
}
|
||||
}) (window, document);
|
||||
@@ -74,6 +74,14 @@
|
||||
background: @brand-success;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
display: none;
|
||||
|
||||
&.new-chapter {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
h1, h2 {
|
||||
page-break-after: avoid;
|
||||
page-break-before: auto;
|
||||
}
|
||||
|
||||
pre, blockquote {
|
||||
border: 1px solid #999;
|
||||
page-break-inside: avoid;
|
||||
}
|
||||
|
||||
img {
|
||||
max-width: 100% !important;
|
||||
page-break-inside: avoid;
|
||||
}
|
||||
|
||||
section {
|
||||
page-break-after: always;
|
||||
|
||||
&#cover {
|
||||
padding: 3cm 0cm;
|
||||
text-align: center;
|
||||
|
||||
h1 {
|
||||
font-size: 1.5cm;
|
||||
}
|
||||
}
|
||||
|
||||
&#summary {
|
||||
text-align: center;
|
||||
|
||||
ul {
|
||||
font-size: 0.5cm;
|
||||
line-height: 1.8em;
|
||||
padding: 0px;
|
||||
margin: 0px;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
> ul {
|
||||
> li {
|
||||
margin-bottom: 1cm;
|
||||
|
||||
> a {
|
||||
font-size: 0.6cm;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
article {
|
||||
margin: 1.5cm;
|
||||
|
||||
/* Big centered title */
|
||||
&.new-chapter {
|
||||
page-break-after: always;
|
||||
font-size: 0.6cm;
|
||||
text-align: center;
|
||||
padding: 3cm 0cm;
|
||||
|
||||
border-top: 1px solid #ccc;
|
||||
|
||||
@media print {
|
||||
border: none;
|
||||
}
|
||||
}
|
||||
|
||||
.exercise {
|
||||
border: 3px solid #ddd;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
// Reset
|
||||
@import "normalize.less";
|
||||
@import "print.less";
|
||||
//@import "print.less";
|
||||
|
||||
// Core CSS
|
||||
@import "scaffolding.less";
|
||||