Compare commits

...

162 Commits

Author SHA1 Message Date
Aaron O'Mullan 2cc23b7e34 Bump version to 0.1.3 2014-04-08 17:03:13 -07:00
Aaron O'Mullan 61b6848a95 Uglify output JS theme/assets/app.js 2014-04-08 17:01:43 -07:00
Aaron O'Mullan 9265b0185a Add context code support to exercises (optional)
Partial #52, fixes #49, fixes #46
2014-04-08 16:58:04 -07:00
Aaron O'Mullan 392573a990 Add lexing support for content code in exercises
#52, #49, #46
2014-04-08 15:01:12 -07:00
Aaron O'Mullan 554d6a6170 Fix URL rewriting error on empty URLs
Fixes #54, fixes #59
2014-04-08 14:47:36 -07:00
Samy Pessé 2182baa2e9 Merge pull request #51 from calmdev/fix/gh-enterprise
Fixes --githubHost option for use with Github Enterprise.
2014-04-07 10:42:55 -07:00
Levi Lewis 7fe189907e Fixes --githubHost option for use with Github Enterprise. 2014-04-07 13:11:44 -04:00
Samy Pessé 9d541a0a4d Bump version to 0.1.2 2014-04-07 01:22:58 -07:00
Samy Pessé 8f3df085d8 Center images in markdown body 2014-04-07 01:11:08 -07:00
Samy Pessé b7e04b5475 Don't use caching for search index 2014-04-07 01:08:11 -07:00
Samy Pessé ee8bf6dc4c Fix display of table in page body 2014-04-07 01:06:44 -07:00
Samy Pessé 9670f564d9 Improve new navigation on mobile 2014-04-07 01:03:35 -07:00
Samy Pessé b541df2b93 Add new lateral navigations 2014-04-07 00:44:30 -07:00
Samy Pessé cf3a641350 Fix progress link to README 2014-04-07 00:02:00 -07:00
Samy Pessé ec719891a1 Remove need for README.md for multi-languages 2014-04-06 23:53:39 -07:00
Samy Pessé 1bfa8c186c Fix overflow on languages page 2014-04-06 23:51:16 -07:00
Samy Pessé 5887f1de28 Merge pull request #42 from GitbookIO/feature/ebook
Fix #10: Add generation to ebook
2014-04-06 22:28:17 -07:00
Samy Pessé a9a66bc240 Add format ebook to README.md 2014-04-06 22:09:52 -07:00
Samy Pessé 742229a989 Add command "ebook" to generate an ebook 2014-04-06 22:03:44 -07:00
Samy Pessé 9fe80b878e Add option cover for ebook generation 2014-04-06 21:46:11 -07:00
Samy Pessé 4b64c87011 Add base ebook generator using ebook-convert 2014-04-06 19:10:22 -07:00
Samy Pessé 4c36c592c1 Merge pull request #40 from GitbookIO/feature/searchclient
Feature/searchclient
2014-04-06 17:13:32 -07:00
Samy Pessé 9ffb1a062f Use cache in localstorage to store search index 2014-04-06 17:13:10 -07:00
Samy Pessé 536c480969 Fix loading of search index in sub directories 2014-04-06 17:06:01 -07:00
Samy Pessé d14bd7245f Open sidebar when opening search 2014-04-06 16:51:14 -07:00
Samy Pessé 6fc8255b7f Reset search results when hidding search bar 2014-04-06 16:47:28 -07:00
Samy Pessé a42f287a92 Filter summary using search bar 2014-04-06 16:46:29 -07:00
Samy Pessé d2f62fd109 Move search bar as global 2014-04-06 16:20:31 -07:00
Samy Pessé f24b66f2c4 Blur search input when hidding search bar 2014-04-06 16:17:54 -07:00
Samy Pessé 607b45f172 Change norm of core/state 2014-04-06 16:10:25 -07:00
Aaron O'Mullan c166a9863e Resolve image URLs, fixes #38
Using outidr & dir options
2014-04-06 16:05:12 -07:00
Aaron O'Mullan 1a4b196851 Add outdir option to generators' generateFile 2014-04-06 16:04:28 -07:00
Samy Pessé ff52a2317b Hide the search bar when pressing ESC key 2014-04-06 16:02:43 -07:00
Samy Pessé b598c9a272 Add keyboard shortcut "f" for opening search bar 2014-04-06 15:58:00 -07:00
Samy Pessé 9cd7c9ad0e Focus search input when opening 2014-04-06 15:56:28 -07:00
Aaron O'Mullan 75a8d3069d Fix dir option in site generator
Use relative folder not absolute
2014-04-06 15:55:24 -07:00
Samy Pessé ed41429d58 Add base search bar in sidebar 2014-04-06 15:53:53 -07:00
Aaron O'Mullan eecb33baa8 Fix relative link detection in renderer 2014-04-06 15:46:20 -07:00
Aaron O'Mullan b8f2da734e Fix minor repetion in README
.gitignore was repeated twice
2014-04-06 15:25:39 -07:00
Aaron O'Mullan 3687a1701b Fix a few typos in README 2014-04-06 15:23:07 -07:00
Aaron O'Mullan c8f83e2684 Document ignores in README, fixes #37 2014-04-06 15:21:57 -07:00
Aaron O'Mullan aa7835e913 Add .bookignore to ignoreFiles #37 2014-04-06 15:19:31 -07:00
Samy Pessé 74edc4f279 Merge pull request #39 from GitbookIO/feature/search
Feature/search
2014-04-06 15:03:27 -07:00
Aaron O'Mullan 696cbdc3b1 Generate section.id in lexer
This allows generating correct URLs for our search index
2014-04-06 14:53:33 -07:00
Aaron O'Mullan 2f8543d710 Generate search_index.json when generating site
Fixes #24
2014-04-06 14:50:11 -07:00
Aaron O'Mullan aee33d67b6 Add lunr@0.5.2 dependency 2014-04-06 14:49:44 -07:00
Samy Pessé 52ccc2b46d Fix #33: copy files when generating pdf or single page 2014-04-06 14:37:33 -07:00
Aaron O'Mullan 9270d7949a In page parser, lex only if not already lexed 2014-04-06 14:13:48 -07:00
Samy Pessé 855c9b9aef Add documentation about multi-languages books 2014-04-06 14:08:11 -07:00
Aaron O'Mullan c98ba22b08 Move page lexer to separate module
Allow lexer to be used independently of page parser/renderer
2014-04-06 14:02:49 -07:00
Samy Pessé d1e55aef8e Add support of multi-languages book in command pdf 2014-04-06 13:59:58 -07:00
Aaron O'Mullan ef059c8737 Add marked-text-renderer@0.0.1 dependency 2014-04-06 13:50:44 -07:00
Samy Pessé fde66ed849 bin/build after generation return all the options 2014-04-06 13:49:51 -07:00
Samy Pessé abce29866e Return options after generate 2014-04-06 13:47:29 -07:00
Samy Pessé 014b2f9c69 Merge pull request #35 from GitbookIO/feature/multilangs
Fix #34: Feature/multilangs
2014-04-06 13:44:14 -07:00
Samy Pessé 65cb23feab Fix generation for page format 2014-04-06 13:43:20 -07:00
Samy Pessé 2b3c67a26b Fix commands options 2014-04-06 13:16:06 -07:00
Samy Pessé 174ce965d9 Fix command build 2014-04-06 13:09:42 -07:00
Samy Pessé adf20e6a16 Add base style for languages index page 2014-04-06 13:07:57 -07:00
Samy Pessé 53f714b7f3 Add base for generating languages index 2014-04-06 12:52:35 -07:00
Samy Pessé d19906d5b2 Add base for multi-languages book 2014-04-06 12:11:43 -07:00
Samy Pessé fb26b634ce Fix page format when chapters are not yet written 2014-04-06 01:59:53 -07:00
Samy Pessé a34dc458c9 Fix footer link when no chapters is ready yet 2014-04-06 00:36:44 -07:00
Aaron O'Mullan eeb715d5d6 Prevent renderer from mutating sections 2014-04-06 00:21:55 -07:00
Samy Pessé a8e026a642 Add information about output format 2014-04-05 23:30:48 -07:00
Samy Pessé cc096d2253 Rename Index.js to index.js 2014-04-06 05:25:22 +02:00
Samy Pessé a4c1cf9334 Refactor bin/gitbook.js 2014-04-05 20:22:27 -07:00
Samy Pessé 9ffec175a5 Add command gitbook pdf to generate PDF 2014-04-05 20:22:27 -07:00
Aaron O'Mullan 465188cae6 Remove useless console.log in test/summary.js 2014-04-05 20:09:50 -07:00
Aaron O'Mullan 4547ec73fd Merge pull request #31 from GitbookIO/feature/lang
Feature/lang
2014-04-05 20:06:38 -07:00
Aaron O'Mullan cae6267665 Adapt test to new code language normalization 2014-04-05 20:04:54 -07:00
Aaron O'Mullan 58bee15f37 Add basic code language normalization 2014-04-05 20:04:24 -07:00
Samy Pessé 761cfb4a2c Add pdf generator using gitbook-pdf 2014-04-05 19:52:51 -07:00
Samy Pessé 8e3339ead2 Fix link to introduction 2014-04-05 18:45:56 -07:00
Aaron O'Mullan b330277ed7 Normalize paths on Windows to Unix convention
Convert “\” to “/“ in relative paths in fs.list
2014-04-05 18:44:53 -07:00
Samy Pessé 12b5baf433 Start exercise index at 1 on pdf format 2014-04-05 18:44:17 -07:00
Samy Pessé f38d68c355 Improve style of exercises in pdf format 2014-04-05 18:42:21 -07:00
Samy Pessé 865bf40e1a Add exercise solutions at the end of the pdf book 2014-04-05 18:08:25 -07:00
Samy Pessé 562ee2b77f Add README introduction to page/pdf generation 2014-04-05 17:33:09 -07:00
Samy Pessé 8b0f2f6329 Fix rendering of code in exercises 2014-04-05 17:28:46 -07:00
Samy Pessé 44717a3e3e Generate an index.html instead of a README.html 2014-04-05 17:15:22 -07:00
Samy Pessé 6f7e3fda02 Fix conflict in app.js 2014-04-05 13:54:13 -07:00
Samy Pessé 511fc7bd46 Merge branch 'master' of https://github.com/GitbookIO/gitbook
Conflicts:
	theme/assets/app.js
2014-04-05 13:54:00 -07:00
Aaron O'Mullan 4987beec2b Add test for exercise language detection 2014-04-05 13:53:44 -07:00
Aaron O'Mullan e414cbd6d1 Detect exercise language
And ensure that all code blocks use the same language
2014-04-05 13:53:31 -07:00
Samy Pessé 694afeccc5 Add base for exercise for others languages 2014-04-05 13:53:22 -07:00
Aaron O'Mullan 959a2d830a Improve robustness of analytics.isAvailable
Fixes GitbookIO/javascript#18

Safari has issues with loading mixpanel, this adds and extra check so
Safari doesn’t fail on event tracking
2014-04-05 12:47:49 -07:00
Aaron O'Mullan 4850c0f302 Bump version to 0.1.1 2014-04-05 01:10:51 -07:00
Aaron O'Mullan ac258329ff Copy README.html to index.html instead of symlimk
Fixes #28
2014-04-05 01:05:31 -07:00
Samy Pessé d5bd08dcd2 Show exercise in page format 2014-04-04 20:12:22 -07:00
Samy Pessé 6c414ec400 Fix link for chapters in page format 2014-04-04 20:01:50 -07:00
Samy Pessé 881a0c6f6d Add info about --theme option 2014-04-04 18:21:40 -07:00
Samy Pessé 0071594300 Fix error with mixpanel loading 2014-04-04 18:18:50 -07:00
Samy Pessé 460799828f Merge pull request #27 from qrohlf/fix-sidebar-mobile
don't show the sidebar by default on mobile
2014-04-05 02:56:57 +02:00
Samy Pessé 02b75288d2 No need to include highlight twice (style.css and print.css) 2014-04-04 17:50:35 -07:00
Samy Pessé b108be0c3b Add separation line between pages 2014-04-04 17:46:59 -07:00
Samy Pessé 7ab285832b Improve style for page printing 2014-04-04 17:40:37 -07:00
Quinn Rohlf 0bc288fe96 don't show the sidebar by default on mobile 2014-04-04 16:44:25 -07:00
Samy Pessé 9fbe240843 Add summary to page generator 2014-04-04 16:40:21 -07:00
Samy Pessé 0c7e2b3557 Add base style for printing 2014-04-04 16:02:57 -07:00
Samy Pessé e34e65813c Fix pages order in page generator 2014-04-04 15:53:30 -07:00
Samy Pessé 63f946ced9 In page generator, add break for printing between pages 2014-04-04 15:47:45 -07:00
Samy Pessé af9f3cf89f Don't generate folder when using generator "page" 2014-04-04 15:41:22 -07:00
Samy Pessé 355094bbb3 Change option for changing generator to format 2014-04-04 15:38:01 -07:00
Samy Pessé b3adedb468 Add base for generating single page html 2014-04-04 14:40:27 -07:00
Samy Pessé 026e4362d8 Move mixpanel to app.js 2014-04-04 14:27:32 -07:00
Samy Pessé 9cf5384fbe Change template name for site generation to site 2014-04-04 14:22:48 -07:00
Samy Pessé 9bc0bf19da Add command line options for changing theme 2014-04-04 14:15:06 -07:00
Samy Pessé f49a1a484e Remove lex command 2014-04-04 14:11:43 -07:00
Samy Pessé 446d486a0f Add base for theming 2014-04-04 14:10:56 -07:00
Samy Pessé 07101deaef Move generator to specific folder 2014-04-04 13:57:07 -07:00
Samy Pessé 76b3fcb41c Add base for page generator 2014-04-04 13:55:43 -07:00
Samy Pessé febda9aba1 Add Travis CI badge 2014-04-04 20:07:05 +02:00
Aaron O'Mullan f952fa47b9 Use relative symlink between index & README
Fixes #19, fixes #21
2014-04-04 11:04:58 -07:00
Samy Pessé 1984660930 Rename PAGE.MD to PAGE.md 2014-04-04 20:04:49 +02:00
Aaron O'Mullan d475affd3b Merge pull request #25 from GitbookIO/feature/generators
Feature/generators
2014-04-04 10:59:13 -07:00
Samy Pessé fe3de93e06 Create .travis.yml 2014-04-04 19:57:51 +02:00
Samy Pessé 5cae311edf Log error in command line tool 2014-04-04 10:55:48 -07:00
Samy Pessé 26701a2a73 Remove logs from generation 2014-04-04 10:50:59 -07:00
Samy Pessé 5125e04814 Update tests 2014-04-04 10:47:44 -07:00
Samy Pessé 0a6194340f Remove file template.js 2014-04-04 10:46:11 -07:00
Samy Pessé e0d96b3163 Fix links in templates 2014-04-04 10:45:36 -07:00
Samy Pessé f656390783 Base for new site generator 2014-04-04 10:39:27 -07:00
Samy Pessé 88c480ba4f Complete json generator 2014-04-04 10:27:45 -07:00
Samy Pessé 3da53d56a2 Add option -g to choice generator
Add base json generator
2014-04-04 09:53:05 -07:00
Samy Pessé 91359fab1e _path is not used anymore 2014-04-04 09:47:34 -07:00
Samy Pessé a52a4bed1a Change normalization of parser to give link in .md 2014-04-04 09:47:06 -07:00
Samy Pessé 9dce855113 Add class BaseGenerator 2014-04-04 09:45:04 -07:00
Samy Pessé 57e2595a3e Merge pull request #20 from mintbridge/github-host-url
Adding config option for github host
2014-04-04 16:51:28 +02:00
Paul Dixon b1314273bb Adding config option for github host
- this config option allows the github host url to be set to
something other than github.com, mainly so that github enterprise
users can change the url to their private host but will also
work with bitbucket
2014-04-04 14:55:08 +01:00
Samy Pessé cb9a0b82ba Fix some typos in lib 2014-04-04 00:00:12 -07:00
Samy Pessé 57ecfe4a54 Make templates more modular 2014-04-03 23:54:03 -07:00
Samy Pessé 405792fd8f Fix #17: Remember state of book summary panel 2014-04-03 23:17:45 -07:00
Samy Pessé fc6d911340 Merge pull request #16 from wh0/patch-1
GiBook -> GitBook
2014-04-04 05:00:29 +02:00
wh0 1e6307b69b GiBook -> GitBook 2014-04-03 19:59:56 -07:00
Aaron O'Mullan af87dc8d7c Bump version to 0.1.0 2014-04-03 16:19:49 -07:00
Aaron O'Mullan 1699028688 Handle empty repoID and print error, fixes #11 2014-04-03 16:10:47 -07:00
Samy Pessé 55d9bfbf18 Enable use of spacebar for scrolling into book body 2014-04-03 15:53:50 -07:00
Samy Pessé c964b53137 Add keyboard shortcut 's' to toggle sidebar 2014-04-03 15:39:05 -07:00
Samy Pessé 510f7bacb4 Show sidebar by default 2014-04-03 15:29:34 -07:00
Samy Pessé c934238f3d Fix #9: add keyboard navigation using right/left 2014-04-03 15:24:57 -07:00
Samy Pessé ab48959968 Update screenshot preview 2014-04-02 21:25:33 -07:00
Samy Pessé eb6204aa42 Bump version to 0.0.4 2014-04-02 20:26:08 -07:00
Samy Pessé a70439f375 Update app.js build 2014-04-02 20:25:52 -07:00
Samy Pessé a3b562b4e8 Prevent default click action on sharing 2014-04-02 20:24:07 -07:00
Samy Pessé aa4e3abc33 Add sharing links in header 2014-04-02 20:17:46 -07:00
Samy Pessé f24a7fbb6e Fix selection of all buffer when clicking on "Solution" 2014-04-02 19:00:50 -07:00
Samy Pessé f3a49306b1 Use prefix for storage key 2014-04-02 18:57:36 -07:00
Samy Pessé f312472abd Add button to edit current chapter in sidebar 2014-04-02 18:53:58 -07:00
Aaron O'Mullan ecb07468f6 Resolve relative links to GitHub repo, fixes #6
Useful for linking to blobs and other files …
2014-04-02 18:40:53 -07:00
Aaron O'Mullan 8fc09e2e05 Add github link resolution test 2014-04-02 18:40:53 -07:00
Aaron O'Mullan ed7798237a Add GITHUB_LINKS.md fixture
For testing github link resolution
2014-04-02 18:40:52 -07:00
Samy Pessé faf63566df Hide articles in progress bar on mobile 2014-04-02 17:48:35 -07:00
Samy Pessé c88382aea0 Update favicon 2014-04-02 17:01:30 -07:00
Samy Pessé 9ee5f48aef Add meta tag generator 2014-04-02 16:53:28 -07:00
Samy Pessé e1dfe5c0f6 Improve meta tags 2014-04-02 16:48:12 -07:00
Aaron O'Mullan 3adcd77ae4 Merge sections together, fixes #7 2014-04-02 16:40:51 -07:00
Aaron O'Mullan 4bdcfd07a9 Add tests for section merging 2014-04-02 16:40:51 -07:00
Aaron O'Mullan a9967df6eb Add HR_PAGE.md fixture
This is for testing that non exercise sections are merged correctly
together and united with HRs
2014-04-02 16:40:51 -07:00
Samy Pessé 62a2e8f81c Fix #8: Improve page title 2014-04-02 16:38:24 -07:00
Aaron O'Mullan 6bcc2d8cf2 Expose titles in navigation of current nodes 2014-04-02 16:33:31 -07:00
Samy Pessé ad1867e4d8 Add preview on readme 2014-04-02 10:40:47 +02:00
160 changed files with 3082 additions and 604 deletions
+5
View File
@@ -0,0 +1,5 @@
language: node_js
node_js:
- "0.11"
- "0.10"
- "0.8"
+17 -4
View File
@@ -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,15 +25,18 @@ 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",
optimize: "uglify", //"uglify",
include: ["requireLib"],
paths: {
"jQuery": 'vendors/jquery',
"lodash": 'vendors/lodash',
"requireLib": 'vendors/require',
"Mousetrap": 'vendors/mousetrap',
"mixpanel": 'vendors/mixpanel',
"lunr": path.join(__dirname, "node_modules/lunr/lunr")
},
shim: {
'jQuery': {
@@ -40,6 +44,15 @@ module.exports = function (grunt) {
},
'lodash': {
exports: '_'
},
'Mousetrap': {
exports: 'Mousetrap'
},
'mixpanel': {
exports: 'mixpanel'
},
'lunr': {
exports: 'lunr'
}
}
}
+51 -8
View File
@@ -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/).
[![Build Status](https://travis-ci.org/GitbookIO/gitbook.png?branch=master)](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/).
![Image](https://raw.github.com/GitbookIO/gitbook/master/preview.png)
## How to use it:
@@ -29,8 +33,23 @@ Options for commands `build` and `serve` are:
-t, --title <name> Name of the book to generate, defaults to repo name
-i, --intro <intro> Description of the book to generate
-g, --github <repo_path> ID of github repo like : username/repo
-o, --output <directory> Path to output directory, defaults to ./_book
-f, --format <name> Change generation format, defaults to site, availables are: site, page, pdf, json
-i, --intro <intro> Description of the book to generate
--githubHost <url> The url of the github host (defaults to https://github.com/)
--theme <path> Path to theme directory
```
## Output Formats
GitBook can generate your book in the following formats:
* **Static Website**: This is the default format, it generates a complete interactive static website that can be for example hosted on GitHub Pages.
* **PDF**: A complete PDF book with exercise solutions at the end of the book. Generate to this format using: ```gitbook pdf ./myrepo```, you need to have [gitbook-pdf](https://github.com/GitbookIO/gitbook-pdf) installed.
* **eBook**: A complete eBook with exercise solutions at the end of the book. Generate to this format using: ```gitbook ebook ./myrepo```, you need to have [ebook-convert](http://manual.calibre-ebook.com/cli/ebook-convert.html) installed.
* **Single Page**: The book will be stored in a single printable HTML page, this format is used for conversion to PDF or eBook. Generate to this format using: ```gitbook build ./myrepo -f page```.
* **JSON**: This format is used for debugging or extracting metadata from a book. Generate to this format using: ```gitbook build ./myrepo -f json```.
## Book Format
A book is a GitHub repository containing at least 2 files: `README.md` and `SUMMARY.md`.
@@ -70,22 +89,46 @@ An exercise is defined by 4 simple parts:
* **Solution** code, being a correct solution to the exercise
* **Validation** code that tests the correctness of the user's input
Exercises need to start and finish with a separation bar (```---``` or ```***```). It should contain 3 code elements (**base**, **solution** and **validation**).
Exercises need to start and finish with a separation bar (```---``` or ```***```). It should contain 3 code elements (**base**, **solution** and **validation**). It can contain a 4th element that provides **context** code (functions, imports of libraries etc ... that shouldn't be displayed to the user).
---
Define a variable `x` equal to 10.
```js
var x =
var x =
```
```js
var x = 10;
```
```js
assert(x == 10);
```
```js
// This is context code available everywhere
// The user will be able to call magicFunc in his code
function magicFunc() {
return 3;
}
```
---
#### Multi-Languages
GitBook supports building books written in multiple languages. Each language should be a sub-directory following the normal GitBook format, and a file named `LANGS.md` should be present at the root of the repository with the following format:
```
* [English](en/)
* [French](fr/)
* [Español](es/)
```
You can see a complete example with the [Learn Git](https://github.com/GitbookIO/git) book.
#### Ignoring files & folders
GitBook will read the `.gitignore`, `.bookignore` and `.ignore` files to get a list of files and folders to skip. (The format inside those files, follows the same convention as `.gitignore`)
-41
View File
@@ -1,41 +0,0 @@
define([
"utils/storage",
"utils/platform",
"core/state"
], function(storage, platform, state) {
// Toggle sidebar with or withour animation
var toggleSidebar = function(_state, animation) {
if (animation == null) animation = true;
var $book = state().$book;
$book.toggleClass("without-animation", !animation);
$book.toggleClass("with-summary", _state);
storage.set("sidebar", isOpen());
};
// Return true if sidebar is open
var isOpen = function() {
return state().$book.hasClass("with-summary");
};
// Prepare sidebar: state and toggle button
var init = function() {
var $book = state().$book;
// Toggle summary
$book.find(".book-header .toggle-summary").click(function(e) {
e.preventDefault();
toggleSidebar();
});
// Init last state if not mobile and not homepage
if (!isOpen()) toggleSidebar(platform.isMobile ? false : storage.get("sidebar", false), false);
};
return {
init: init,
toggle: toggleSidebar
}
});
-14
View File
@@ -1,14 +0,0 @@
define([
"jQuery"
], function() {
return function() {
var $book = $(".book");
return {
'$book': $book,
'githubId': $book.data("github"),
'level': $book.data("level")
};
};
});
-18
View File
@@ -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
};
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

File diff suppressed because one or more lines are too long
-42
View File
@@ -1,42 +0,0 @@
.book {
.page-footer {
position: absolute;
bottom: 0px;
width: 100%;
height: 80px;
padding: 10px;
overflow: hidden;
color: #fff;
.navigation-link {
display: inline-block;
text-align: center;
width: 100%;
height: 100%;
font-size: 24px;
line-height: 60px;
border-radius: 2px;
background: @brand-success;
color: inherit;
text-transform: uppercase;
&:hover {
background: darken(@btn-success-bg, 5%);
text-decoration: none;
}
&.coming-soon, &.coming-soon:hover {
background: #f0ad4e;
}
&.finished, &.finished:hover {
background: darken(@btn-success-bg, 5%);
}
}
}
}
+114
View File
@@ -0,0 +1,114 @@
var path = require('path');
var Q = require('q');
var _ = require('lodash');
var tmp = require('tmp');
var utils = require('./utils');
var generate = require("../lib/generate");
var parse = require("../lib/parse");
var fs = require('../lib/generate/fs');
var generators = require("../lib/generate").generators;
var 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 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(
_.extend(options.options || {}, {
input: dir,
output: outputDir,
title: title,
description: options.intro,
github: githubID,
githubHost: options.githubHost,
generator: options.format,
theme: options.theme
})
);
})
.then(function(output) {
console.log("Successfuly built !");
return output;
}, utils.logError);
};
var buildFiles = function(dir, outputFile, options, masterOptions) {
var ext = masterOptions.extension;
outputFile = outputFile || path.resolve(dir, "book."+ext);
Q.nfcall(tmp.dir)
.then(function(tmpDir) {
return buildFunc(
dir,
_.extend(options, {
output: tmpDir,
format: masterOptions.format,
options: masterOptions.options
})
)
.then(function(_options) {
var copyPDF = function(lang) {
var _outputFile = outputFile;
var _tmpDir = tmpDir;
if (lang) {
_outputFile = _outputFile.slice(0, -path.extname(_outputFile).length)+"_"+lang+path.extname(_outputFile);
_tmpDir = path.join(_tmpDir, lang);
}
console.log("Generating in", _outputFile);
return fs.copy(
path.join(_tmpDir, "index."+ext),
_outputFile
);
};
// Multi-langs book
return Q()
.then(function() {
if (_options.langsSummary) {
console.log("Generating for all the languages");
return Q.all(
_.map(_options.langsSummary.list, function(lang) {
return copyPDF(lang.lang);
})
);
} else {
return copyPDF();
}
})
.then(function() {
return fs.remove(tmpDir);
})
.fail(utils.logError);
});
})
};
module.exports = {
folder: buildFunc,
files: buildFiles
};
+53 -68
View File
@@ -1,101 +1,86 @@
#! /usr/bin/env node
// Requires
var Q = require('q');
var _ = require('lodash');
var path = require('path');
var prog = require('commander');
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 fs = require('../lib/generate/fs');
var utils = require('./utils');
var build = require('./build');
// General options
prog
.version(pkg.version)
.option('-d, --dir <source_directory>', 'Source directory of book, containing Markdown files');
.version(pkg.version);
var buildCommand = function(command, action) {
return command
.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('--githubHost <url>', 'The url of the github host (defaults to https://github.com/')
.option('--theme <path>', 'Path to theme directory')
.action(action);
}
var buildFunc;
prog
buildCommand(prog
.command('build [source_dir]')
.description('Build a gitbook from a directory')
.option('-o, --output <directory>', 'Path to output directory, defaults to ./_book')
.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')
.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);
})
.then(function(repoID) {
var parts = repoID.split('/', 2);
var user = parts[0], repo = parts[1];
.description('Build a gitbook from a directory'), build.folder);
return generate.folder(
dir,
outputDir,
{
title: options.title || utils.titleCase(repo),
description: options.intro,
github: options.github || repoID
}
);
})
.then(function(output) {
console.log("Successfuly built !");
}, function(err) {
console.log(err.stack || err);
throw err;
})
.then(_.constant(outputDir));
});
prog
buildCommand(prog
.command('serve [source_dir]')
.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('-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')
.action(function(dir, options) {
buildFunc(dir, options)
.then(function(outputDir) {
.option('-p, --port <port>', 'Port for server to listen on', 4000),
function(dir, options) {
build.folder(dir, options)
.then(function(_options) {
console.log();
console.log('Starting server ...');
return utils.serveDir(outputDir, options.port);
return utils.serveDir(_options.output, options.port)
.fail(utils.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));
buildCommand(prog
.command('pdf [source_dir] [output_file]')
.description('Build a gitbook as a PDF')
.option('-pf, --paperformat <format>', 'PDF paper format (default is A4): "5in*7.5in", "10cm*20cm", "A4", "Letter"'),
function(dir, output, options) {
build.files(dir, output, options, {
extension: "pdf",
format: "pdf",
options: {
paperformat: options.paperformat
}
});
});
buildCommand(prog
.command('ebook [source_dir] [output_file]')
.description('Build a gitbook as a eBook')
.option('-c, --cover <path>', 'Cover image, default is cover.png if exists'),
function(dir, output, options) {
var ext = output ? path.extname(output) : "epub";
build.files(dir, output, options, {
extension: ext,
format: "ebook",
options: {
extension: ext,
cover: options.cover
}
});
});
// Parse and fallback to help if no args
if(_.isEmpty(prog.parse(process.argv).args) && process.argv.length === 2) {
+6
View File
@@ -82,6 +82,11 @@ function serveDir(dir, port) {
return d.promise;
}
function logError(err) {
console.log(err.stack || err.message || err);
return Q.reject(err);
};
// Exports
module.exports = {
@@ -89,4 +94,5 @@ module.exports = {
githubID: githubID,
titleCase: titleCase,
serveDir: serveDir,
logError: logError
};
+70
View File
@@ -0,0 +1,70 @@
var util = require("util");
var path = require("path");
var Q = require("q");
var _ = require("lodash");
var exec = require('child_process').exec;
var fs = require("fs");
var parse = require("../../parse");
var BaseGenerator = require("../page");
/*
* This generator inherits from the single page generator
* and convert the page output to ebook
*/
var Generator = function() {
BaseGenerator.apply(this, arguments);
// Options for eBook generation
this.options = _.defaults(this.options, {
extension: "epub"
});
if (!this.options.cover && fs.existsSync(path.join(this.options.input, "cover.png"))) {
this.options.cover = path.join(this.options.input, "cover.png")
}
};
util.inherits(Generator, BaseGenerator);
Generator.prototype.finish = function() {
var that = this;
return BaseGenerator.prototype.finish.apply(this)
.then(function() {
var d = Q.defer();
var _options = {
"--cover": that.options.cover
};
var command = [
"ebook-convert",
path.join(that.options.output, "index.html"),
path.join(that.options.output, "index."+that.options.extension),
_.chain(_options)
.map(function(value, key) {
if (value == null) return null;
return key+"="+value;
})
.compact()
.value()
.join(" ")
].join(" ");
exec(command, function (error, stdout, stderr) {
if (error) {
if (error.code == 127) {
error.message = "Need to install ebook-convert from Calibre";
} else {
error.message = error.message + " "+stdout;
}
return d.reject(error);
}
d.resolve();
});
return d.promise;
});
};
module.exports = Generator;
+11 -3
View File
@@ -11,7 +11,7 @@ var getFiles = function(path) {
var ig = Ignore({
path: path,
ignoreFiles: ['.ignore', '.gitignore']
ignoreFiles: ['.ignore', '.gitignore', '.bookignore']
});
// Add extra rules to ignore common folders
@@ -27,13 +27,21 @@ var getFiles = function(path) {
});
ig.on('end', function() {
d.resolve(files);
// Normalize paths on Windows
if(process.platform === 'win32') {
return d.resolve(files.map(function(file) {
return file.replace(/\\/g, '/');
}));
}
// Simply return paths otherwise
return d.resolve(files);
});
ig.on('error', d.reject);
return d.promise;
}
};
module.exports = {
list: getFiles,
+36
View File
@@ -0,0 +1,36 @@
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.langsIndex = function(langs) {
return Q.reject(new Error("Langs index is not supported in this generator"));
};
BaseGenerator.prototype.finish = function() {
return Q.reject(new Error("Could not finish generation"));
};
module.exports = BaseGenerator;
+108 -86
View File
@@ -2,125 +2,147 @@ var Q = require("q");
var _ = require("lodash");
var path = require("path");
var swig = require('swig');
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"),
"pdf": require("./pdf"),
"ebook": require("./ebook"),
"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)
.then(function(_files) {
files = _files;
})
})
// Check repository is valid
.then(function(_files) {
files = _files;
// Create the generator
.then(function() {
generator = new generators[options.generator](options);
})
if (!_.contains(files, "SUMMARY.md") || !_.contains(files, "README.md")) {
// Detect multi-languages book
.then(function() {
if (_.contains(files, "LANGS.md")) {
// Multi-languages book
return fs.readFile(path.join(options.input, "LANGS.md"), "utf-8")
// Generate sub-books
.then(function(_langsSummary) {
options.langsSummary = parse.langs(_langsSummary);
// Generated a book for each valid entry
return Q.all(
_.map(options.langsSummary.list, function(entry) {
return generate(_.extend({}, options, {
input: path.join(options.input, entry.path),
output: path.join(options.output, entry.path)
}));
})
);
})
// Generate languages index
.then(function() {
return generator.langsIndex(options.langsSummary);
});
} else if (!_.contains(files, "SUMMARY.md") || !_.contains(files, "README.md")) {
// Invalid book
return Q.reject(new Error("Invalid gitbook repository, need SUMMARY.md and README.md"));
} else {
// Generate the book
return fs.readFile(path.join(options.input, "SUMMARY.md"), "utf-8")
// Get summary
.then(function(_summary) {
options.summary = parse.summary(_summary);
// Parse navigation
options.navigation = parse.navigation(options.summary);
})
// Copy file and replace markdown file
.then(function() {
return Q.all(
_.chain(files)
.map(function(file) {
if (!file) return;
if (file[file.length -1] == "/") {
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()
);
})
// Finish gneration
.then(function() {
return generator.finish();
});
}
})
// Get summary
// Return all options
.then(function() {
return fs.readFile(path.join(root, "SUMMARY.md"), "utf-8")
.then(function(_summary) {
summary = parse.summary(_summary);
// Parse navigation
navigation = parse.navigation(summary);
});
})
// Create template
.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
}
});
})
// Copy file and replace markdown file
.then(function() {
return Q.all(
_.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)
);
}
})
.value()
);
})
// Symlink index.html to README.html
.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 options;
});
};
module.exports = {
generators: generators,
folder: generate
};
+47
View File
@@ -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;
+84
View File
@@ -0,0 +1,84 @@
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("../site");
// 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.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) || '/',
outdir: './',
});
})
.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._writeTemplate(that.template, {
pages: that.pages,
basePath: basePath,
staticBase: path.join(basePath, "gitbook"),
}, output);
})
// Copy assets
.then(function() {
return fs.copy(
path.join(that.options.theme, "assets"),
path.join(that.options.output, "gitbook")
);
});
};
module.exports = Generator;
+56
View File
@@ -0,0 +1,56 @@
var util = require("util");
var path = require("path");
var Q = require("q");
var _ = require("lodash");
var exec = require('child_process').exec;
var fs = require("../fs");
var parse = require("../../parse");
var BaseGenerator = require("../page");
/*
* This generator inherits from the single page generator
* and convert the page output to pdf using gitbook-pdf
*/
var Generator = function() {
BaseGenerator.apply(this, arguments);
// Options for PDF generation
this.options = _.defaults(this.options, {
paperformat: "A4"
});
};
util.inherits(Generator, BaseGenerator);
Generator.prototype.finish = function() {
var that = this;
return BaseGenerator.prototype.finish.apply(this)
.then(function() {
var d = Q.defer();
var command = [
"gitbook-pdf",
"generate",
path.join(that.options.output, "index.html"),
path.join(that.options.output, "index.pdf"),
"--format="+that.options.paperformat
].join(" ");
exec(command, function (error, stdout, stderr) {
if (error) {
if (error.code == 127) {
error.message = "Need to install gitbook-pdf using: npm install gitbook-pdf -g";
} else {
error.message = error.message + " "+stdout;
}
return d.reject(error);
}
d.resolve();
});
return d.promise;
});
};
module.exports = Generator;
+156
View File
@@ -0,0 +1,156 @@
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");
var indexer = require('./search_indexer');
// 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) {
var link = link.replace(".md", ".html");
if (link == "README.html") link = "index.html";
return link;
});
var Generator = function() {
BaseGenerator.apply(this, arguments);
// Attach methods to instance
_.bindAll(this);
this.revision = Date.now();
this.indexer = indexer();
// Load base template
this.template = swig.compileFile(path.resolve(this.options.theme, 'templates/site.html'));
this.langsTemplate = swig.compileFile(path.resolve(this.options.theme, 'templates/langs.html'));
};
util.inherits(Generator, BaseGenerator);
// Generate a template
Generator.prototype._writeTemplate = function(tpl, options, output) {
var that = this;
return Q()
.then(function(sections) {
return tpl(_.extend({
revision: that.revision,
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
}, options));
})
.then(function(html) {
return fs.writeFile(
output,
html
);
});
};
Generator.prototype.indexPage = function(lexed, pagePath) {
this.indexer.add(lexed, pagePath);
return Q();
};
// 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");
if (_output == "README.html") _output = "index.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() {
// Lex page
return parse.lex(content);
})
.then(function(lexed) {
// Index page in search
return that.indexPage(lexed, _output)
.then(_.constant(lexed));
})
.then(function(lexed) {
// Get HTML generated sections
return parse.page(lexed, {
repo: that.options.githubId,
dir: path.dirname(_input) || '/',
outdir: path.dirname(_input) || '/',
});
})
.then(function(sections) {
return that._writeTemplate(that.template, {
progress: progress,
_input: _input,
content: sections,
basePath: basePath,
staticBase: path.join(basePath, "gitbook"),
}, output);
});
};
// Generate languages index
Generator.prototype.langsIndex = function(langs) {
var that = this;
var basePath = ".";
return this._writeTemplate(this.langsTemplate, {
langs: langs.list,
basePath: basePath,
staticBase: path.join(basePath, "gitbook"),
}, path.join(this.options.output, "index.html"))
.then(function() {
// Copy assets
return that.copyAssets();
});
};
// Copy assets
Generator.prototype.copyAssets = function() {
var that = this;
return fs.copy(
path.join(that.options.theme, "assets"),
path.join(that.options.output, "gitbook")
);
};
// Dump search index to disk
Generator.prototype.writeSearchIndex = function() {
return fs.writeFile(
path.join(this.options.output, 'search_index.json'),
this.indexer.dump()
);
};
Generator.prototype.finish = function() {
return this.copyAssets()
.then(this.writeSearchIndex);
};
module.exports = Generator;
+71
View File
@@ -0,0 +1,71 @@
var Q = require("q");
var _ = require("lodash");
var lunr = require('lunr');
var marked = require('marked');
var textRenderer = require('marked-text-renderer');
function Indexer() {
if(!(this instanceof Indexer)) {
return new Indexer();
}
_.bindAll(this);
// Setup lunr index
this.idx = lunr(function () {
this.ref('url');
this.field('title', { boost: 10 });
this.field('body');
});
this.renderer = textRenderer();
}
Indexer.prototype.text = function(nodes) {
// Copy section
var section = _.toArray(nodes);
// marked's Render expects this, we don't use it yet
section.links = {};
var options = _.extend({}, marked.defaults, {
renderer: this.renderer
});
return marked.parser(section, options);
};
Indexer.prototype.addSection = function(path, section) {
var url = [path, section.id].join('#');
var title = this.text(
_.filter(section, {'type': 'heading'})
);
var body = this.text(
_.omit(section, {'type': 'heading'})
);
// Add to lunr index
this.idx.add({
url: url,
title: title,
body: body,
});
};
Indexer.prototype.add = function(lexedPage, url) {
var sections = lexedPage;
_.map(sections, _.partial(this.addSection, url));
};
Indexer.prototype.dump = function() {
return JSON.stringify(this.idx);
};
// Exports
module.exports = Indexer;
-65
View File
@@ -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;
+2
View File
@@ -1,6 +1,8 @@
module.exports = {
summary: require('./summary'),
langs: require('./langs'),
page: require('./page'),
lex: require('./lex'),
progress: require('./progress'),
navigation: require('./navigation'),
};
+23
View File
@@ -0,0 +1,23 @@
var _ = require("lodash")
var parseSummary = require("./summary");
var parseLangs = function(content) {
var summary = parseSummary(content);
return {
list: _.chain(summary.chapters)
.filter(function(entry) {
return entry.path != null;
})
.map(function(entry) {
return {
title: entry.title,
path: entry.path,
lang: entry.path.replace("/", "")
};
})
.value()
}
};
module.exports = parseLangs;
+77
View File
@@ -0,0 +1,77 @@
var _ = require('lodash');
var marked = require('marked');
// Split a page up into sections (lesson, exercises, ...)
function splitSections(nodes) {
var section = [];
return _.reduce(nodes, function(sections, el) {
if(el.type === 'hr') {
sections.push(section);
section = [];
} else {
section.push(el);
}
return sections;
}, []).concat([section]); // Add remaining nodes
}
// What is the type of this section
function sectionType(nodes, idx) {
var codeNodes = _.filter(nodes, {
type: 'code'
}).length;
if(
(codeNodes === 3 || codeNodes === 4) &&
(idx % 2) === 1)
{
return 'exercise';
}
return 'normal';
}
// Generate a uniqueId to identify this section in our code
function sectionId(section, idx) {
return _.uniqueId('gitbook_');
}
function lexPage(src) {
// Lex file
var nodes = marked.lexer(src);
return _.chain(splitSections(nodes))
.map(function(section, idx) {
// Detect section type
section.type = sectionType(section, idx);
return section;
})
.map(function(section, idx) {
// Give each section an ID
section.id = sectionId(section, idx);
return section;
})
.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;
}, [])
.value();
}
// Exports
module.exports = lexPage;
+9 -6
View File
@@ -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',
+31 -50
View File
@@ -2,8 +2,12 @@ var _ = require('lodash');
var marked = require('marked');
var hljs = require('highlight.js');
var lex = require('./lex');
var renderer = require('./renderer');
var lnormalize = require('../utils/lang').normalize;
// Synchronous highlighting with highlight.js
marked.setOptions({
highlight: function (code, lang) {
@@ -16,64 +20,28 @@ marked.setOptions({
});
// Split a page up into sections (lesson, exercises, ...)
function splitSections(nodes) {
var section = [];
return _.reduce(nodes, function(sections, el) {
if(el.type === 'hr') {
sections.push(section);
section = [];
} else {
section.push(el);
}
return sections;
}, []).concat([section]); // Add remaining nodes
}
// What is the type of this section
function sectionType(nodes, idx) {
var codeNodes = _.filter(nodes, {
type: 'code'
}).length;
if(codeNodes === 3 && (idx % 2) == 1) {
return 'exercise';
}
return 'normal';
}
// Render a section using our custom renderer
function render(section) {
function render(section, _options) {
// Copy section
section = _.toArray(section);
// 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) {
var nodes = marked.lexer(src);
function parsePage(src, options) {
options = options || {};
return _.chain(splitSections(nodes))
.map(function(section, idx) {
// Detect section type
section.type = sectionType(section, idx);
return section;
})
.filter(function(section) {
return !_.isEmpty(section);
})
// Lex if not already lexed
return (_.isArray(src) ? src : lex(src))
.map(function(section) {
// Generate a uniqueId to identify this section in our code
var id = _.uniqueId('gitbook_');
// Transform given type
if(section.type === 'exercise') {
var nonCodeNodes = _.reject(section, {
@@ -84,26 +52,39 @@ function parsePage(src) {
'type': 'code'
});
// Languages in code blocks
var langs = _.pluck(codeNodes, 'lang').map(lnormalize);
// Check that they are all the same
var validLangs = _.all(_.map(langs, function(lang) {
return lang && lang === langs[0];
}));
// Main language
var lang = validLangs ? langs[0] : null;
return {
id: id,
id: section.id,
type: section.type,
content: render(nonCodeNodes),
lang: lang,
code: {
base: codeNodes[0].text,
solution: codeNodes[1].text,
validation: codeNodes[2].text,
// Context is optional
context: codeNodes[3] ? codeNodes[3].text : null,
}
};
}
// Render normal pages
return {
id: id,
id: section.id,
type: section.type,
content: render(section)
content: render(section, options)
};
})
.value();
});
}
// Exports
+12 -3
View File
@@ -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
};
}
+38 -2
View File
@@ -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.protocol && parsed.path && 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 + '"';
@@ -54,5 +68,27 @@ GitBookRenderer.prototype.link = function(href, title, text) {
return out;
};
GitBookRenderer.prototype.image = function(href, title, text) {
// Our "fixed" href
var _href = href;
// Parsed version of the url
var parsed = url.parse(href);
// Options
var o = this._extra_options;
// Relative image, rewrite it depending output
if(!parsed.protocol && parsed.path && parsed.path[0] != '/' && o && o.dir && o.outdir) {
_href = path.relative(o.outdir, path.normalize(path.join(
o.dir,
href
)));
}
return GitBookRenderer.super_.prototype.image.call(this, _href, title, text);
};
// Exports
module.exports = GitBookRenderer;
+1 -4
View File
@@ -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],
};
}
+3
View File
@@ -0,0 +1,3 @@
module.exports = {
lang: require('./lang'),
};
+16
View File
@@ -0,0 +1,16 @@
var MAP = {
'py': 'python',
'js': 'javascript',
'rb': 'ruby',
};
function normalize(lang) {
var lower = lang.toLowerCase();
return MAP[lower] || lower;
}
// Exports
module.exports = {
normalize: normalize,
MAP: MAP
};
+5 -2
View File
@@ -1,18 +1,21 @@
{
"name": "gitbook",
"version": "0.0.3",
"version": "0.1.3",
"description": "Library and cmd utility to generate GitBooks",
"main": "lib/index.js",
"dependencies": {
"q": "1.0.1",
"lodash": "2.4.1",
"marked": "0.3.2",
"marked-text-renderer": "0.0.1",
"lunr": "0.5.2",
"swig": "1.3.2",
"send": "0.2.0",
"fstream-ignore": "0.0.7",
"commander": "2.2.0",
"fs-extra": "0.8.1",
"highlight.js": "8.0.0"
"highlight.js": "8.0.0",
"tmp": "0.0.23"
},
"devDependencies": {
"mocha": "1.18.2",
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 157 KiB

After

Width:  |  Height:  |  Size: 110 KiB

-13
View File
@@ -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>
-30
View File
@@ -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>
-53
View File
@@ -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 %}
+3
View File
@@ -0,0 +1,3 @@
# Nice course
Check out this source file [in C++](../src/something.cpp)
+11
View File
@@ -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 ...
+33
View File
@@ -30,3 +30,36 @@ Some more nice content ....
[Cool stuff](http://gitbook.io)
[Link to another Markdown file](./xyz/file.md)
Lets go for another exercise but this time with some context :
---
Exercise with some context code :
Using the `double` function provided, build a `quadruple` function
```py
```
```py
def quadruple(x):
return double(double(x))
```
```py
assert(quadruple(8), 32)
```
```py
def double(x):
return x * 2
```
---
+32 -32
View File
@@ -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() {
+42 -1
View File
@@ -8,9 +8,15 @@ 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);
assert.equal(LEXED.length, 4);
});
it('should detection section types', function() {
@@ -30,5 +36,40 @@ describe('Page parsing', function() {
assert(LEXED[1].code.base);
assert(LEXED[1].code.solution);
assert(LEXED[1].code.validation);
assert(LEXED[1].code.context === null);
assert(LEXED[3].content);
assert(LEXED[3].code);
assert(LEXED[3].code.base);
assert(LEXED[3].code.solution);
assert(LEXED[3].code.validation);
assert(LEXED[3].code.context);
});
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);
});
it('should detect an exercise\'s language', function() {
assert.equal(LEXED[1].lang, 'python');
});
});
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);
});
});
+3 -7
View File
@@ -10,7 +10,6 @@ var LEXED = summary(CONTENT);
describe('Summary parsing', function () {
console.log(LEXED);
it('should detect chapters', function() {
assert.equal(LEXED.chapters.length, 5);
@@ -37,12 +36,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() {
+5
View File
@@ -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>```
File diff suppressed because one or more lines are too long

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

+1
View File
@@ -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{margin:1cm 0;padding:.4cm;page-break-inside:avoid;border:3px solid #ddd}section article .exercise .exercise-header{margin-bottom:.4cm;padding-bottom:.2cm;border-bottom:1px solid #ddd}
File diff suppressed because one or more lines are too long
@@ -1,21 +1,31 @@
require([
"jQuery",
"utils/storage",
"utils/analytic",
"utils/sharing",
"core/state",
"core/keyboard",
"core/exercise",
"core/progress",
"core/sidebar"
], function($, analytic, _state, exercise, progress, sidebar){
"core/sidebar",
"core/search"
], function($, storage, analytic, sharing, state, keyboard, exercise, progress, sidebar, search){
$(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();
// Load search
search.init();
// Init keyboard
keyboard.init();
// Star and watch count
$.getJSON("https://api.github.com/repos/"+state.githubId)
.done(function(repo) {
@@ -26,7 +36,13 @@ require([
// Bind exercise
exercise.init();
// Bind sharing button
sharing.init();
// Show progress
progress.show();
// Focus on content
$(".book-body").focus();
});
});
@@ -8,6 +8,7 @@ define([
var prepareExercise = function($exercise) {
var codeSolution = $exercise.find(".code-solution").text();
var codeValidation = $exercise.find(".code-validation").text();
var codeContext = $exercise.find(".code-context").text();
var editor = ace.edit($exercise.find(".editor").get(0));
editor.setTheme("ace/theme/tomorrow");
@@ -20,7 +21,7 @@ define([
analytic.track("exercise.submit");
execute(editor.getValue(), codeValidation, function(err, result) {
execute("javascript", editor.getValue(), codeValidation, codeContext, function(err, result) {
$exercise.toggleClass("return-error", err != null);
$exercise.toggleClass("return-success", err == null);
if (err) $exercise.find(".alert-danger").text(err.message || err);
@@ -32,12 +33,13 @@ define([
e.preventDefault();
editor.setValue(codeSolution);
editor.gotoLine(0);
});
};
// Prepare all exercise
var init = function() {
state().$book.find("section.exercise").each(function() {
state.$book.find("section.exercise").each(function() {
prepareExercise($(this));
});
};
+39
View File
@@ -0,0 +1,39 @@
define([
"jQuery",
"Mousetrap",
"core/navigation",
"core/sidebar",
"core/search"
], function($, Mousetrap, navigation, sidebar, search){
// 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;
});
// Toggle Search
Mousetrap.bind(['f'], function(e) {
search.toggle();
return false;
});
};
return {
init: init,
search: search
};
});
+17
View File
@@ -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,7 +6,7 @@ define([
], function(_, $, storage, state) {
// Get current level
var getCurrentLevel = function() {
return state().level;
return state.level;
};
// Return all levels
+97
View File
@@ -0,0 +1,97 @@
define([
"jQuery",
"lodash",
"lunr",
"utils/storage",
"core/state",
"core/sidebar"
], function($, _, lunr, storage, state, sidebar) {
var index = null;
var $searchBar = state.$book.find(".book-search");
var $searchInput = $searchBar.find("input");
// Use a specific idnex
var useIndex = function(data) {
index = lunr.Index.load(data);
};
// Load complete index
var loadIndex = function() {
$.getJSON(state.basePath+"/search_index.json")
.then(useIndex);
};
// Search for a term
var search = function(q) {
if (!index) return;
var results = _.chain(index.search(q))
.map(function(result) {
var parts = result.ref.split("#")
return {
path: parts[0],
hash: parts[1]
}
})
.value();
return results;
};
// Toggle search bar
var toggleSearch = function(_state) {
if (state != null && isSearchOpen() == _state) return;
state.$book.toggleClass("with-search", _state);
// If search bar is open: focus input
if (isSearchOpen()) {
sidebar.toggle(true);
$searchInput.focus();
} else {
$searchInput.blur();
$searchInput.val("");
sidebar.filter(null);
}
};
// Return true if search bar is open
var isSearchOpen = function() {
return state.$book.hasClass("with-search");
};
var init = function() {
loadIndex();
// Toggle search
state.$book.find(".book-header .toggle-search").click(function(e) {
e.preventDefault();
toggleSearch();
});
$searchInput.keyup(function(e) {
var key = (e.keyCode ? e.keyCode : e.which);
var q = $(this).val();
if (key == 27) {
e.preventDefault();
toggleSearch(false);
return;
}
if (q.length == 0) {
sidebar.filter(null);
} else {
var results = search(q);
sidebar.filter(
_.pluck(results, "path")
);
}
});
};
return {
init: init,
search: search,
toggle: toggleSearch
};
});
+56
View File
@@ -0,0 +1,56 @@
define([
"lodash",
"utils/storage",
"utils/platform",
"core/state"
], function(_, storage, platform, state) {
var $summary = state.$book.find(".book-summary");
// Toggle sidebar with or withour animation
var toggleSidebar = function(_state, animation) {
if (state != null && isOpen() == _state) return;
if (animation == null) animation = true;
state.$book.toggleClass("without-animation", !animation);
state.$book.toggleClass("with-summary", _state);
storage.set("sidebar", isOpen());
};
// Return true if sidebar is open
var isOpen = function() {
return state.$book.hasClass("with-summary");
};
// Prepare sidebar: state and toggle button
var init = function() {
// Toggle summary
state.$book.find(".book-header .toggle-summary").click(function(e) {
e.preventDefault();
toggleSidebar();
});
// Init last state if not mobile
if (!platform.isMobile) {
toggleSidebar(storage.get("sidebar", true), false);
}
};
// Filter summary with a list of path
var filterSummary = function(paths) {
$summary.find("li").each(function() {
var path = $(this).data("path");
var st = paths == null || _.contains(paths, path);
$(this).toggle(st);
if (st) $(this).parents("li").show();
});
};
return {
$el: $summary,
init: init,
toggle: toggleSidebar,
filter: filterSummary
}
});
+14
View File
@@ -0,0 +1,14 @@
define([
"jQuery"
], function() {
var $book = $(".book");
return {
'$book': $book,
'githubId': $book.data("github"),
'level': $book.data("level"),
'basePath': $book.data("basepath"),
'revision': $book.data("revision")
};
});
+8
View File
@@ -0,0 +1,8 @@
define(function() {
return {
id: "javascript",
assertCode: "function assert(condition, message) { \nif (!condition) { \n throw message || \"Assertion failed\"; \n } \n }\n",
REPL: JSREPL,
sep: ";\n",
};
});
+33
View File
@@ -0,0 +1,33 @@
define([
"lodash",
"mixpanel"
], function(_, mixpanel) {
mixpanel.init("01eb2b950ae09a5fdb15a98dcc5ff20e", {
loaded: function() {
track("View");
}
});
var isAvailable = function() {
return (
typeof mixpanel !== "undefined" &&
typeof mixpanel.track === "function"
);
};
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
};
});
@@ -1,5 +1,12 @@
define(function(){
var evalJS = function(code, callback) {
define([
"execute/javascript"
], function(javascript) {
var LANGUAGES = {
"javascript": javascript
};
var evalJS = function(lang, code, callback) {
var ready = false;
var finished = false;
@@ -11,7 +18,7 @@ define(function(){
return callback.apply(null, arguments);
};
var jsrepl;
var repl;
// Handles all our events
var eventHandler = function(data, eventType) {
@@ -42,14 +49,14 @@ define(function(){
// We're good to get results and stuff back now
ready = true;
// Eval our code now that the runtime is ready
jsrepl.eval(code);
repl.eval(code);
break;
default:
console.log('Unhandled event =', eventType, 'data =', data);
}
};
jsrepl = new JSREPL({
repl = new lang.REPL({
input: eventHandler,
output: eventHandler,
result: eventHandler,
@@ -61,16 +68,24 @@ define(function(){
}
});
jsrepl.loadLanguage('javascript', eventHandler);
repl.loadLanguage(lang.id, eventHandler);
};
var execute = function(lang, solution, validation, context, callback) {
// Language data
var langd = LANGUAGES[lang];
var ass = "function assert(condition, message) { \nif (!condition) { \n throw message || \"Assertion failed\"; \n } \n }\n";
// Check language is supported
if (!langd) return callback(new Error("Language '"+lang+"' not available for execution"));
var execute = function(solution, validation, callback) {
// Validate with validation code
var code = [solution, ass, validation].join(";\n");
evalJS(code, function(err, res) {
var code = [
context,
solution,
langd.assertCode,
validation,
].join(langd.sep);
evalJS(langd, code, function(err, res) {
if(err) return callback(err);
if (res.type == "error") callback(new Error(res.value));
@@ -79,4 +94,4 @@ define(function(){
};
return execute;
});
});
+33
View File
@@ -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);
}
};
+2
View File
@@ -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||[]);
+953
View File
@@ -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);
@@ -5,7 +5,15 @@
right: 0px;
left: 0px;
bottom: 0px;
overflow-y: auto;
.body-inner {
position: absolute;
top: 0px;
right: 0px;
left: 0px;
bottom: 0px;
overflow-y: auto;
}
.transition(left 0.5s ease);
@@ -14,7 +22,6 @@
.page-wrapper {
position: relative;
min-height: 100%;
padding-bottom: 100px;
.page-inner {
max-width: 800px;
@@ -39,6 +46,16 @@
}
}
}
@media (max-width: @mobileMaxWidth) {
overflow-y: auto;
.body-inner {
position: static;
padding-bottom: 20px;
min-height: calc(~"100% - 57px")
}
}
}
&.with-summary {
+46
View File
@@ -0,0 +1,46 @@
.book-langs-index {
width: 100%;
height: 100%;
background: #edece4;
padding: 40px 0px;
margin: 0px;
overflow: auto;
.inner {
max-width: 350px;
width: 100%;
margin: 0px auto;
padding: 15px;
background: #fff;
border-radius: 3px;
h1 {
margin: 0px;
text-align: center;
}
.languages {
list-style: none;
padding: 0px;
margin: 0px;
margin-top: 20px;
border-top: 1px solid #eee;
li {
text-align: center;
padding: 10px 5px;
font-size: 16px;
border-bottom: 1px solid #eee;
a {
}
}
}
}
}
@@ -156,7 +156,10 @@
margin-bottom: 0; }
table {
padding: 0; }
width: 100%;
padding: 0;
}
table tr {
border-top: 1px solid #cccccc;
background-color: white;
@@ -181,7 +184,10 @@
margin-bottom: 0; }
img {
max-width: 100%; }
max-width: 100%;
display: block;
margin: 0px auto;
}
span.frame {
display: block;
+45
View File
@@ -0,0 +1,45 @@
.book .book-body {
.navigation {
position: absolute;
top: 0px;
bottom: 0px;
margin: 0;
max-width: 150px;
min-width: 90px;
display: flex;
justify-content:center;
align-content:center;
flex-direction:column;
font-size: 40px;
color: rgba(0,0,0, 0.5);
text-align: center;
.transition(all 350ms ease);
&:hover {
background-color: rgba(0,0,0, 0.06);
text-decoration: none;
}
&.navigation-next {
right: 0px;
}
&.navigation-prev {
left: 0px;
}
}
@media (max-width: @mobileMaxWidth) {
.navigation {
position: static;
top: auto;
max-width: 50%;
width: 50%;
display: inline-block;
float: left;
}
}
}
@@ -23,6 +23,7 @@
position: relative;
background: #fff;
margin-bottom: 20px;
z-index: 10;
.bar {
height: 8px;
@@ -74,6 +75,14 @@
background: @brand-success;
box-shadow: none;
}
@media (max-width: 800px) {
display: none;
&.new-chapter {
display: block;
}
}
}
}
}
@@ -1,4 +1,6 @@
.book {
@searchHeight: 41px;
.book-summary {
@width: 250px;
@@ -8,19 +10,49 @@
bottom: 0px;
z-index: 1;
overflow-y: auto;
width: @width;
background: #2e3133;
color: #e2edf2;
.transition(all 0.5s ease);
.book-search {
padding: 6px;
padding-top: 0px;
background: #242628;
border-bottom: 1px solid #333;
position: absolute;
top: -@searchHeight;
left: 0px;
right: 0px;
.transition(top 0.5s ease);
input, input:focus {
width: 100%;
border: none;
.box-shadow(none);
}
}
ul.summary {
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
overflow-y: auto;
list-style: none;
margin: 0px;
padding: 0px;
.transition(top 0.5s ease);
li {
list-style: none;
@@ -96,4 +128,16 @@
.transition(none) !important;
}
}
&.with-search {
.book-summary {
.book-search {
top: 0px;
}
ul.summary {
top: @searchHeight;
}
}
}
}
@@ -7,13 +7,14 @@
@import "highlight.less";
@import "book/languages.less";
@import "book/header.less";
@import "book/summary.less";
@import "book/body.less";
@import "book/footer.less";
@import "book/exercise.less";
@import "book/markdown.less";
@import "book/progress.less";
@import "book/navigation.less";
* {
-webkit-overflow-scrolling: touch;
+81
View File
@@ -0,0 +1,81 @@
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 {
margin: 1cm 0cm;
padding: 0.4cm;
page-break-inside: avoid;
border: 3px solid #ddd;
.exercise-header {
margin-bottom: 0.4cm;
padding-bottom: 0.2cm;
border-bottom: 1px solid #ddd;
}
}
}
}
@@ -1,11 +1,9 @@
/* Base static */
@staticPath: "./";
/* Colors */
@codeboxMainColor: #F16956; /* red */
@codeboxMainColorDarker: darken(@codeboxMainColor, 15%);
// Sizes
@mobileMaxWidth: 1240px;
@codeboxMainColor2: #353D48;
// Basics of a navbar
@navbar-height: 50px;
@@ -22,13 +20,6 @@
@navbar-default-brand-hover-color: @navbar-default-link-color;
@navbar-default-brand-hover-bg: transparent;
// Navbar toggle
@navbar-default-toggle-hover-bg: #fff;
@navbar-default-toggle-icon-bar-bg: @codeboxMainColorDarker;
@navbar-default-toggle-border-color: @codeboxMainColorDarker;
@navbar-default-link-active-color: @codeboxMainColor;
@navbar-default-link-active-bg: #fff;
@border-radius-base: 1px;
@border-radius-large: 3px;
@border-radius-small: 1px;

Some files were not shown because too many files have changed in this diff Show More