From ca431984cb69ea3644393efd4b8ed8032db152ce Mon Sep 17 00:00:00 2001 From: Matthew Beale Date: Wed, 24 Jun 2015 16:36:15 -0400 Subject: [PATCH 01/77] Introduce cards --- demo/index.html | 8 ++++- src/js/commands/card.js | 38 ++++++++++++++++++++++++ src/js/commands/oembed.js | 2 +- src/js/editor/editor.js | 26 ++++++++-------- src/js/renderers/editor-html-renderer.js | 9 ++++-- 5 files changed, 66 insertions(+), 17 deletions(-) create mode 100644 src/js/commands/card.js diff --git a/demo/index.html b/demo/index.html index 61c69c336..e2e463763 100644 --- a/demo/index.html +++ b/demo/index.html @@ -72,7 +72,13 @@

Keyboard shortcuts:

diff --git a/src/js/commands/card.js b/src/js/commands/card.js new file mode 100644 index 000000000..1a94b9f9c --- /dev/null +++ b/src/js/commands/card.js @@ -0,0 +1,38 @@ +import Command from './base'; +import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; +import BlockModel from 'node_modules/content-kit-compiler/src/models/block'; +import Type from 'node_modules/content-kit-compiler/src/types/type'; + +function injectCardBlock(cardName, cardPayload, editor, index) { + // FIXME: Do we change the block model internal representation here? + var cardBlock = BlockModel.createWithType(Type.CARD, { + attributes: { + name: cardName, + payload: cardPayload + } + }); + editor.replaceBlock(cardBlock, index); +} + +function CardCommand() { + Command.call(this, { + name: 'card', + button: 'CA' + }); +} +inherit(CardCommand, Command); + +CardCommand.prototype = { + exec: function() { + CardCommand._super.prototype.exec.call(this); + var editor = this.editorContext; + var currentEditingIndex = editor.getCurrentBlockIndex(); + + var cardName = 'pick-color'; + var cardPayload = { options: ['red', 'blue'] }; + injectCardBlock(cardName, cardPayload, editor, currentEditingIndex); + editor.renderBlockAt(currentEditingIndex, true); + } +}; + +export default CardCommand; diff --git a/src/js/commands/oembed.js b/src/js/commands/oembed.js index 89bf081eb..7e2cd978d 100644 --- a/src/js/commands/oembed.js +++ b/src/js/commands/oembed.js @@ -35,7 +35,7 @@ OEmbedCommand.prototype.exec = function(url) { var editorContext = command.editorContext; var embedIntent = command.embedIntent; var index = editorContext.getCurrentBlockIndex(); - + embedIntent.showLoading(); this.embedService.fetch({ url: url, diff --git a/src/js/editor/editor.js b/src/js/editor/editor.js index 1e43bfb28..2bf004d58 100644 --- a/src/js/editor/editor.js +++ b/src/js/editor/editor.js @@ -12,6 +12,7 @@ import UnorderedListCommand from '../commands/unordered-list'; import OrderedListCommand from '../commands/ordered-list'; import ImageCommand from '../commands/image'; import OEmbedCommand from '../commands/oembed'; +import CardCommand from '../commands/card'; import Keycodes from '../utils/keycodes'; import { getSelectionBlockElement, getCursorOffsetInElement } from '../utils/selection-utils'; import EventEmitter from '../utils/event-emitter'; @@ -36,17 +37,16 @@ var defaults = { new SubheadingCommand() ], embedCommands: [ - new ImageCommand({ serviceUrl: '/upload' }), - new OEmbedCommand({ serviceUrl: '/embed' }) + new ImageCommand({ serviceUrl: '/upload' }), + new OEmbedCommand({ serviceUrl: '/embed' }), + new CardCommand() ], autoTypingCommands: [ new UnorderedListCommand(), new OrderedListCommand() ], - compiler: new Compiler({ - includeTypeNames: true, // outputs models with type names, i.e. 'BOLD', for easier debugging - renderer: new EditorHTMLRenderer() // subclassed HTML renderer that adds dom structure for additional editor interactivity - }) + compiler: null, + cards: {} }; function bindContentEditableTypingListeners(editor) { @@ -169,12 +169,14 @@ function getNonTextBlocks(blockTypeSet, model) { function Editor(element, options) { var editor = this; mergeWithOptions(editor, defaults, options); - - // Update embed commands by prepending the serverHost - editor.embedCommands = [ - new ImageCommand({ serviceUrl: editor.serverHost + '/upload' }), - new OEmbedCommand({ serviceUrl: editor.serverHost + '/embed' }) - ]; + if (!editor.compiler) { + editor.compiler = new Compiler({ + includeTypeNames: true, // outputs models with type names, i.e. 'BOLD', for easier debugging + renderer: new EditorHTMLRenderer({ + cards: editor.cards + }) // subclassed HTML renderer that adds dom structure for additional editor interactivity + }); + } if (element) { applyClassName(element); diff --git a/src/js/renderers/editor-html-renderer.js b/src/js/renderers/editor-html-renderer.js index 25bd8f4db..beeaf4cdb 100644 --- a/src/js/renderers/editor-html-renderer.js +++ b/src/js/renderers/editor-html-renderer.js @@ -5,6 +5,7 @@ import YouTubeRenderer from './youtube'; import TwitterRenderer from './twitter'; import InstagramRenderer from './instagram'; import LinkImageRenderer from './link-image-renderer'; +import { merge } from 'node_modules/content-kit-utils/src/object-utils'; /** * A dictionary of supported embeds types that we'll custom render @@ -55,10 +56,12 @@ typeRenderers[Type.IMAGE.id] = imageRenderer; * Subclass of HTMLRenderer specifically for the Editor * Wraps interactive elements to add functionality */ -function EditorHTMLRenderer() { - HTMLRenderer.call(this, { +function EditorHTMLRenderer(options) { + var rendererOptions = { typeRenderers: typeRenderers - }); + }; + merge(rendererOptions, options); + HTMLRenderer.call(this, rendererOptions); } inherit(EditorHTMLRenderer, HTMLRenderer); From 6dd5a691a43835927e6dee208b3622f0377a5bd2 Mon Sep 17 00:00:00 2001 From: Matthew Beale Date: Wed, 24 Jun 2015 17:52:31 -0400 Subject: [PATCH 02/77] Re-use card blocks from a previous render --- src/js/editor/editor.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/js/editor/editor.js b/src/js/editor/editor.js index 2bf004d58..a3c03f2ca 100644 --- a/src/js/editor/editor.js +++ b/src/js/editor/editor.js @@ -262,6 +262,7 @@ Editor.prototype.renderBlockAt = function(index, replace) { var dom = document.createElement('div'); dom.innerHTML = html; var newEl = dom.firstChild; + newEl.dataset.modelIndex = index; var sibling = this.element.children[index]; if (replace) { this.element.replaceChild(newEl, sibling); @@ -275,13 +276,18 @@ Editor.prototype.syncContentEditableBlocks = function() { var blockElements = toArray(this.element.children); var len = blockElements.length; var updatedModel = []; - var i, blockEl; + var i, block, blockEl; for (i = 0; i < len; i++) { blockEl = blockElements[i]; if(blockEl.isContentEditable) { updatedModel.push(this.compiler.parser.serializeBlockNode(blockEl)); } else { - updatedModel.push(nonTextBlocks.shift()); + if (blockEl.dataset.modelIndex) { + block = this.model[blockEl.dataset.modelIndex]; + updatedModel.push(block); + } else { + updatedModel.push(nonTextBlocks.shift()); + } } } this.model = updatedModel; From 0589f3caf0e67c10002316be47bde86fe4e71310 Mon Sep 17 00:00:00 2001 From: Matthew Beale Date: Thu, 25 Jun 2015 10:17:16 -0400 Subject: [PATCH 03/77] Small formatting cleanup --- src/js/utils/element-utils.js | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/js/utils/element-utils.js b/src/js/utils/element-utils.js index 1cba840dd..15ce55dff 100644 --- a/src/js/utils/element-utils.js +++ b/src/js/utils/element-utils.js @@ -114,7 +114,21 @@ function positionElementToRightOf(element, rightOfElement) { return positionElementToRect(element, rightOfElementRect, -verticalCenter, -rightOfElement.offsetWidth - elementMargin); } -export { createDiv, hideElement, showElement, swapElements, getEventTargetMatchingTag, nodeIsDescendantOfElement, -elementContentIsEmpty, getElementRelativeOffset, getElementComputedStyleNumericProp, positionElementToRect, -positionElementHorizontallyCenteredToRect, positionElementCenteredAbove, positionElementCenteredBelow, -positionElementCenteredIn, positionElementToLeftOf, positionElementToRightOf }; +export { + createDiv, + hideElement, + showElement, + swapElements, + getEventTargetMatchingTag, + nodeIsDescendantOfElement, + elementContentIsEmpty, + getElementRelativeOffset, + getElementComputedStyleNumericProp, + positionElementToRect, + positionElementHorizontallyCenteredToRect, + positionElementCenteredAbove, + positionElementCenteredBelow, + positionElementCenteredIn, + positionElementToLeftOf, + positionElementToRightOf +}; From 3e57efc1061584733c81113ae07929f298150b82 Mon Sep 17 00:00:00 2001 From: Matthew Beale Date: Thu, 25 Jun 2015 14:32:48 -0400 Subject: [PATCH 04/77] README updates --- README.md | 116 +++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 97 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index a94a42d1b..c053fd950 100644 --- a/README.md +++ b/README.md @@ -1,30 +1,108 @@ -# ContentKit-Editor [![Build Status](https://travis-ci.org/bustlelabs/content-kit-editor.svg?branch=master)](https://travis-ci.org/bustlelabs/content-kit-editor) -### A modern, minimalist WYSIWYG editor. +## ContentKit-Editor [![Build Status](https://travis-ci.org/bustlelabs/content-kit-editor.svg?branch=master)](https://travis-ci.org/bustlelabs/content-kit-editor) -*Currently under heavy active development. API subject to change.* +ContentKit is a modern WYSIWYG editor supporting interactive cards. Try a +demo at [http://content-kit.herokuapp.com/](http://content-kit.herokuapp.com/). -## Live Demo -[http://content-kit.herokuapp.com/](http://content-kit.herokuapp.com/) +ContentKit articles (we will use the term article, but any kind of content could +be authored) are built from models. Models represent rows of content, and can +be static or dynamic. + +For example, the teardown of an article might look like: + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ┌──────────┐ │ +│ │ Article │ │ +│ └──────────┘ │ +│┌────────────────────────────────────────────────────────────────────────────┐│ +││ ┌──────────────┐ ││ +││ │ MarkupModel │ ││ +││ └──────────────┘ ││ +││

One Weird Trick

││ +│└────────────────────────────────────────────────────────────────────────────┘│ +│┌────────────────────────────────────────────────────────────────────────────┐│ +││ ┌──────────────┐ ││ +││ │ BlockModel │ ││ +││ └──────────────┘ ││ +││

││ +││ You will never guess what happens ││ +││ when these cats take a bath ││ +││

││ +│└────────────────────────────────────────────────────────────────────────────┘│ +│┌────────────────────────────────────────────────────────────────────────────┐│ +││ ┌──────────────┐ ││ +││ │ EmbedModel │ ││ +││ └──────────────┘ ││ +││ ││ +││ ││ +│└────────────────────────────────────────────────────────────────────────────┘│ +│┌────────────────────────────────────────────────────────────────────────────┐│ +││ ┌────────────────────────┐ ││ +││ │ BlockModel (type CARD) │ ││ +││ └────────────────────────┘ ││ +││ node.innerHTML = 'Cards can change content at render time. For example, ││ +││ use an Ember component'; ││ +│└────────────────────────────────────────────────────────────────────────────┘│ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +### Usage + +ContentKit is attached to a DOM node when the `Editor` factory is instantiated. + +```js +var editor = new ContentKit.Editor(this.element, options); +``` + +`options` is an object which may include the following properties: + +* `stickyToolbar` - a boolean option enabling a persistent header with + formatting tools. Default is true for touch devices. +* `placeholder` - default text to show before a user starts typing. +* `spellcheck` - a boolean option enabling spellcheck. Default is true. +* `autofocus` - a boolean option for grabbing input focus when an editor is + rendered. +* `serverHost` - a URL prefix for embed and image API request. **[FIXME Remove]** +* `cards` - an object describing available cards. + +### Public Editor API + +* `editor.loadPost(post)` - render the editor with a post. **[FIXME Implement]** +* `editor.serializePost()` - serialize the current post for persistence. **[FIXME Implement]** + +### Contributing + +Running ContentKit tests and demo server locally requires the following dependencies: -## Prerequisites * [node.js](http://nodejs.org/) ([install package](http://nodejs.org/download/)) or `brew install node` +* `gulp`, via `npm install -g gulp` + +To run tests: + +``` +gulp test +``` + +To run the demo server: + +``` +npm start && open http://localhost:5000 +``` + +To ensure ContentKit rebuilds while you work with it: + +``` +gulp watch +``` + +For uploads and embeds to work, you will have to configure AWS and +Embedly keys as environment variables: -## Server Configuration (optional) -For uploads and embeds to work, you will have to configure AWS and Embedly keys as environment variables: ```bash export AWS_ACCESS_KEY_ID=XXXXXX export AWS_SECRET_ACCESS_KEY=XXXXXX export EMBEDLY_KEY=XXXXXX ``` -Also, set the `bucketName` in `server/config.json` with the name of your AWS S3 bucket for uploading files. - -## Playing -1. Install dependencies: `npm install` -2. Build: `gulp build` -3. Start server: `npm start` then visit [http://localhost:5000](http://localhost:5000) || To play without the server, simply open [demo/index.html](demo/index.html) - -## Testing -`gulp test` -## Dev tips -`gulp watch` to auto build/test as you save files +Also, set the `bucketName` in `server/config.json` with the name of your AWS +S3 bucket for uploading files. From 4d6e05f1778c9b780c57ba7338ddaad92d17b2e6 Mon Sep 17 00:00:00 2001 From: Matthew Beale Date: Thu, 25 Jun 2015 15:34:48 -0400 Subject: [PATCH 05/77] Build dist --- dist/content-kit-editor.js | 111 ++++++++++++++++++++++++++++++------- 1 file changed, 90 insertions(+), 21 deletions(-) diff --git a/dist/content-kit-editor.js b/dist/content-kit-editor.js index 4c74bbb78..451dadb96 100644 --- a/dist/content-kit-editor.js +++ b/dist/content-kit-editor.js @@ -308,7 +308,8 @@ new types_type({ tag: 'blockquote', name: 'quote' }), new types_type({ tag: 'ul', name: 'list' }), new types_type({ tag: 'ol', name: 'ordered list' }), - new types_type({ name: 'embed', isTextType: false }) + new types_type({ name: 'embed', isTextType: false }), + new types_type({ name: 'card' }) ]); /** @@ -666,11 +667,32 @@ var html_embed_renderer = HTMLEmbedRenderer; + /** + * @class CardRenderer + * @constructor + */ + function CardRenderer(cards) { + this.cards = cards; + } + + /** + * @method render + * @param model a card model + * @return String html + */ + CardRenderer.prototype.render = function(model) { + var render = this.cards[model.attributes.name]; + return '
'+render(model.attributes.payload)+'
'; + }; + + var card_renderer = CardRenderer; + function HTMLRenderer(options) { var defaults = { blockTypes : DefaultBlockTypeSet, markupTypes : DefaultMarkupTypeSet, - typeRenderers : {} + typeRenderers : {}, + cards : {} }; mergeWithOptions(this, defaults, options); } @@ -686,6 +708,9 @@ if (type === types_type.EMBED) { return new html_embed_renderer(); } + if (type === types_type.CARD) { + return new card_renderer(this.cards); + } return new html_element_renderer({ type: type, markupTypes: this.markupTypes }); }; @@ -700,8 +725,9 @@ var i, blockHtml; for (i = 0; i < len; i++) { + // this is renderModel, not only blocks!! blockHtml = this.renderBlock(model[i]); - if (blockHtml) { + if (blockHtml) { html += blockHtml; } } @@ -879,10 +905,12 @@ * Subclass of HTMLRenderer specifically for the Editor * Wraps interactive elements to add functionality */ - function EditorHTMLRenderer() { - html_renderer.call(this, { + function EditorHTMLRenderer(options) { + var rendererOptions = { typeRenderers: typeRenderers - }); + }; + merge(rendererOptions, options); + html_renderer.call(this, rendererOptions); } inherit(EditorHTMLRenderer, html_renderer); @@ -2135,7 +2163,7 @@ var editorContext = command.editorContext; var embedIntent = command.embedIntent; var index = editorContext.getCurrentBlockIndex(); - + embedIntent.showLoading(); this.embedService.fetch({ url: url, @@ -2167,6 +2195,40 @@ var oembed = OEmbedCommand; + function injectCardBlock(cardName, cardPayload, editor, index) { + // FIXME: Do we change the block model internal representation here? + var cardBlock = models_block.createWithType(types_type.CARD, { + attributes: { + name: cardName, + payload: cardPayload + } + }); + editor.replaceBlock(cardBlock, index); + } + + function CardCommand() { + base.call(this, { + name: 'card', + button: 'CA' + }); + } + inherit(CardCommand, base); + + CardCommand.prototype = { + exec: function() { + CardCommand._super.prototype.exec.call(this); + var editor = this.editorContext; + var currentEditingIndex = editor.getCurrentBlockIndex(); + + var cardName = 'pick-color'; + var cardPayload = { options: ['red', 'blue'] }; + injectCardBlock(cardName, cardPayload, editor, currentEditingIndex); + editor.renderBlockAt(currentEditingIndex, true); + } + }; + + var card = CardCommand; + // Based on https://github.com/jeromeetienne/microevent.js/blob/master/microevent.js // See also: https://github.com/allouis/minivents/blob/master/minivents.js @@ -2212,17 +2274,16 @@ new subheading() ], embedCommands: [ - new image({ serviceUrl: '/upload' }), - new oembed({ serviceUrl: '/embed' }) + new image({ serviceUrl: '/upload' }), + new oembed({ serviceUrl: '/embed' }), + new card() ], autoTypingCommands: [ new unordered_list(), new ordered_list() ], - compiler: new compiler({ - includeTypeNames: true, // outputs models with type names, i.e. 'BOLD', for easier debugging - renderer: new editor_html_renderer() // subclassed HTML renderer that adds dom structure for additional editor interactivity - }) + compiler: null, + cards: {} }; function bindContentEditableTypingListeners(editor) { @@ -2345,12 +2406,14 @@ function Editor(element, options) { var editor = this; mergeWithOptions(editor, defaults, options); - - // Update embed commands by prepending the serverHost - editor.embedCommands = [ - new image({ serviceUrl: editor.serverHost + '/upload' }), - new oembed({ serviceUrl: editor.serverHost + '/embed' }) - ]; + if (!editor.compiler) { + editor.compiler = new compiler({ + includeTypeNames: true, // outputs models with type names, i.e. 'BOLD', for easier debugging + renderer: new editor_html_renderer({ + cards: editor.cards + }) // subclassed HTML renderer that adds dom structure for additional editor interactivity + }); + } if (element) { applyClassName(element); @@ -2436,6 +2499,7 @@ var dom = document.createElement('div'); dom.innerHTML = html; var newEl = dom.firstChild; + newEl.dataset.modelIndex = index; var sibling = this.element.children[index]; if (replace) { this.element.replaceChild(newEl, sibling); @@ -2449,13 +2513,18 @@ var blockElements = toArray(this.element.children); var len = blockElements.length; var updatedModel = []; - var i, blockEl; + var i, block, blockEl; for (i = 0; i < len; i++) { blockEl = blockElements[i]; if(blockEl.isContentEditable) { updatedModel.push(this.compiler.parser.serializeBlockNode(blockEl)); } else { - updatedModel.push(nonTextBlocks.shift()); + if (blockEl.dataset.modelIndex) { + block = this.model[blockEl.dataset.modelIndex]; + updatedModel.push(block); + } else { + updatedModel.push(nonTextBlocks.shift()); + } } } this.model = updatedModel; From 35f34c847afe7932a2b86510e1b2b841cba22f2e Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Thu, 25 Jun 2015 14:48:30 -0400 Subject: [PATCH 06/77] use broccoli-multi-builder to output amd, globals, cjs * remove all explicit reference of node_modules * add `src` option to broccoli build trees * fix usage of doc and win for node, fix import paths * fix issue with exported window, remove js-test * change imports to not use node_modules or descendent paths --- .gitignore | 3 +- Brocfile.js | 30 + bower.json | 21 + dist/content-kit-editor.css | 606 ----- dist/content-kit-editor.js | 2577 ---------------------- package.json | 7 +- src/js/commands/bold.js | 4 +- src/js/commands/card.js | 8 +- src/js/commands/format-block.js | 7 +- src/js/commands/heading.js | 4 +- src/js/commands/image.js | 16 +- src/js/commands/italic.js | 4 +- src/js/commands/link.js | 4 +- src/js/commands/list.js | 7 +- src/js/commands/oembed.js | 16 +- src/js/commands/ordered-list.js | 4 +- src/js/commands/quote.js | 4 +- src/js/commands/subheading.js | 4 +- src/js/commands/text-format.js | 7 +- src/js/commands/unordered-list.js | 4 +- src/js/editor/editor-factory.js | 3 +- src/js/editor/editor.js | 25 +- src/js/index.js | 21 +- src/js/renderers/editor-html-renderer.js | 10 +- src/js/utils/element-utils.js | 11 +- src/js/utils/http-utils.js | 3 +- src/js/utils/selection-utils.js | 21 +- src/js/utils/win.js | 11 + src/js/views/embed-intent.js | 12 +- src/js/views/message.js | 2 +- src/js/views/prompt.js | 10 +- src/js/views/text-format-toolbar.js | 14 +- src/js/views/toolbar-button.js | 3 +- src/js/views/toolbar.js | 9 +- src/js/views/tooltip.js | 2 +- src/js/views/view.js | 6 +- 36 files changed, 214 insertions(+), 3286 deletions(-) create mode 100644 Brocfile.js create mode 100644 bower.json delete mode 100644 dist/content-kit-editor.css delete mode 100644 dist/content-kit-editor.js create mode 100644 src/js/utils/win.js diff --git a/.gitignore b/.gitignore index 633f344df..96b4c8706 100644 --- a/.gitignore +++ b/.gitignore @@ -33,4 +33,5 @@ bower_components # Builds keys.txt -export.sh \ No newline at end of file +export.sh +dist/ diff --git a/Brocfile.js b/Brocfile.js new file mode 100644 index 000000000..4aaeaa955 --- /dev/null +++ b/Brocfile.js @@ -0,0 +1,30 @@ +/* jshint node:true */ + +var multiBuilder = require('broccoli-multi-builder'); +var mergeTrees = require('broccoli-merge-trees'); + +var jsSrc = './src/js'; +var vendoredModules = ['content-kit-compiler', 'content-kit-utils']; +var packageName = require('./package.json').name; + +var amdTree = multiBuilder.buildAMD({ + isGlobal: false, + src: jsSrc, + vendoredModules: vendoredModules, + packageName: packageName +}); + +var globalTree = multiBuilder.buildAMD({ + isGlobal: true, + src: jsSrc, + vendoredModules: vendoredModules, + packageName: packageName +}); + +var cjsTree = multiBuilder.buildCJS({ + src: jsSrc, + vendoredModules: vendoredModules, + packageName: packageName +}); + +module.exports = mergeTrees([ amdTree, globalTree, cjsTree ]); diff --git a/bower.json b/bower.json new file mode 100644 index 000000000..26e506cf4 --- /dev/null +++ b/bower.json @@ -0,0 +1,21 @@ +{ + "name": "content-kit-editor", + "version": "0.0.0", + "homepage": "https://github.com/bustlelabs/content-kit-editor", + "moduleType": [ + "amd", + "es6", + "globals" + ], + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ], + "dependencies": { + "loader.js": "~3.2.1" + } +} diff --git a/dist/content-kit-editor.css b/dist/content-kit-editor.css deleted file mode 100644 index 2168230fe..000000000 --- a/dist/content-kit-editor.css +++ /dev/null @@ -1,606 +0,0 @@ -/** - * Editor - */ -.ck-editor { - font-family: 'Lora', Georgia, serif; - margin: 1em 0; - color: #454545; - /* - Chrome bug adds inline styles when backspacing to join 2 blocks. - Fix: Apply font styles to parent element, or use % for font-size, line-height. - http://stackoverflow.com/questions/15015019/prevent-chrome-from-wrapping-contents-of-joined-p-with-a-span - */ - font-size: 120%; - line-height: 160%; -} -.ck-editor:focus { - outline: none; -} -.ck-editor:empty:before { - content: attr(data-placeholder); - color: #bbb; -} -.ck-editor > * { - position: relative; -} -.ck-editor a { - color: #0b8bff; -} -.ck-editor h1, -.ck-editor h2, -.ck-editor h3, -.ck-editor h4, -.ck-editor h5, -.ck-editor h6 { - font-family: 'Merriweather Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif; - font-weight: 800; - letter-spacing: -0.02em; -} -.ck-editor blockquote { - border-left: 4px solid #0b8bff; - margin: 1em 0 1em -1.2em; - padding-left: 1.05em; - color: #a0a0a0; -} -.ck-editor img { - display: block; - max-width: 100%; - margin: 0 auto; -} -.ck-editor div, -.ck-editor iframe { - max-width: 100%; -} -/** - * Toolbar - */ -.ck-toolbar { - text-align: center; - position: absolute; - z-index: 1; - transition: left 0.1s, top 0.1s; - margin-bottom: 0.45em; -} -.ck-toolbar:after { - content: ''; - position: absolute; - left: 50%; - width: 0; - height: 0; - border-left: 0.45em solid transparent; - border-right: 0.45em solid transparent; - border-top: 0.45em solid #2b2b2b; - bottom: -0.4em; - margin: 0 0 0 -0.45em; -} -.ck-toolbar.right { - margin: 0 0 0 0.5em; -} -.ck-toolbar.right:after { - left: -0.4em; - top: 50%; - bottom: auto; - margin: -0.45em 0 0 0; - border-top: 0.45em solid transparent; - border-bottom: 0.45em solid transparent; - border-right: 0.45em solid #3d3d3d; - border-left: none; -} -.ck-toolbar, -.ck-toolbar-prompt { - -webkit-animation: pop-up 0.25s; - animation: pop-up 0.25s; -} -.ck-toolbar.right { - -webkit-animation: pop-right 0.25s; - animation: pop-right 0.25s; -} -.ck-toolbar.sticky { - position: fixed; - top: 0; - left: 0; - right: 0; - transition: none; - border-radius: 0; - margin: 0; - border-bottom: 1px solid #e0e0e0; - box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03); - background: linear-gradient(to bottom, rgba(252, 252, 252, 0.92) 0%, rgba(252, 252, 252, 0.97) 100%); - box-shadow: none; - -webkit-animation: slide-down 0.25s; - animation: slide-down 0.25s; -} -.ck-toolbar.sticky:after { - content: none; -} -.sticky .ck-toolbar-btn { - color: #454545; - text-shadow: none; -} -.sticky .ck-toolbar-btn:hover, -.sticky .ck-toolbar-btn:active { - background-color: #eee; -} -.ck-toolbar-content { - border-radius: 3px; - background: linear-gradient(to bottom, rgba(74, 74, 74, 0.97) 0%, #2b2b2b 100%); - box-shadow: 0 1px 3px -1px rgba(0, 0, 0, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.12), inset 1px 1px 0 #282828, inset -1px -1px 0 #282828; -} -.ck-toolbar-buttons { - border-radius: 5px; - overflow: hidden; - white-space: nowrap; -} -.ck-toolbar-btn { - display: inline-block; - background-color: transparent; - border: none; - outline: none; - color: #FFF; - font-size: 18px; - padding: 0; - margin: 0; - width: 48px; - height: 44px; - line-height: 42px; - cursor: pointer; - transition: background-color 0.1s linear; - text-shadow: 0 1px 1px rgba(0, 0, 0, 0.65); - -moz-user-select: none; - -webkit-user-select: none; - -ms-user-select: none; -} -.ck-toolbar-btn:hover { - background-color: rgba(43, 43, 43, 0.4); -} -.ck-toolbar-btn:active { - background-color: rgba(43, 43, 43, 0.65); -} -.ck-toolbar-btn:active, -.ck-toolbar-btn.active { - color: #3ea3ff; -} -.ck-toolbar-prompt { - display: none; -} -.ck-toolbar-prompt input { - background: none; - border: none; - color: #f5f5f5; - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 14px; - padding: 0 16px; - width: 288px; - height: 44px; - line-height: 1em; -} -.ck-toolbar-prompt input:focus { - outline: none; -} -.ck-toolbar-prompt input::-ms-clear { - display: none; -} -.ck-toolbar-prompt ::-webkit-input-placeholder { - background-color: #a2a2a2; - background-image: -webkit-gradient(linear, left top, right top, color-stop(0, #a2a2a2), color-stop(0.4, #a2a2a2), color-stop(0.5, #ffffff), color-stop(0.6, #a2a2a2), color-stop(1, #a2a2a2)); - background-repeat: no-repeat; - -webkit-background-clip: text; - -webkit-text-fill-color: transparent; - -webkit-animation: textGlimmer 4s infinite; -} -.ck-editor-hilite { - position: absolute; - z-index: -1; - background-color: rgba(62, 163, 255, 0.05); - border-bottom: 2px dotted #3ea3ff; -} -/** - * Tooltip - */ -.ck-tooltip { - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 0.7em; - white-space: nowrap; - position: absolute; - background-color: rgba(43, 43, 43, 0.9); - border-radius: 3px; - line-height: 1em; - padding: 0.7em 0.9em; - color: #FFF; - -webkit-animation: fade-in 0.2s; - animation: fade-in 0.2s; -} -.ck-tooltip:before { - content: ''; - position: absolute; - left: 50%; - width: 0; - height: 0; - border-left: 0.4em solid transparent; - border-right: 0.4em solid transparent; - border-bottom: 0.4em solid rgba(43, 43, 43, 0.9); - top: -0.4em; - margin-left: -0.4em; -} -.ck-tooltip:after { - /* help keeps mouseover state when moving from link to tooltip */ - content: ''; - position: absolute; - left: 0; - right: 0; - top: -0.4em; - height: 0.4em; -} -.ck-tooltip a { - color: #FFF; - text-decoration: none; -} -.ck-tooltip a:hover { - text-decoration: underline; -} -/** - * Embeds - */ -.ck-embed-intent { - position: absolute; -} -.ck-embed-intent .ck-toolbar { - min-width: 100px; - left: 40px; - top: 50%; - -webkit-transform: translateY(-50%); - transform: translateY(-50%); -} -.ck-embed-intent-btn { - position: relative; - display: block; - background: none; - border: none; - outline: none; - margin: 0 0.4em 0 0; - padding: 0; - width: 1em; - height: 1em; - border: 2px solid #ccc; - border-radius: 100%; - color: #ccc; - text-align: center; - font-size: 2em; - line-height: 0.7em; - cursor: pointer; - transition: color 0.1s, border-color 0.1s, transform 0.35s; - -webkit-animation: pop-out 0.25s; - animation: pop-out 0.25s; -} -.ck-embed-intent-btn:hover { - color: #999; - border-color: #999; -} -.ck-embed-intent-btn:active { - color: #666; - border-color: #666; - transition: none; -} -.ck-embed-intent-btn:before { - content: '+'; - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; -} -.activated .ck-embed-intent-btn { - -webkit-transform: rotate(-135deg); - transform: rotate(-135deg); -} -.ck-embed-loading { - position: absolute; - top: 0; - left: 50%; - margin-left: -0.75em; - width: 1.5em; - height: 1.5em; - border-radius: 50%; - border: 2px solid #ddd; - border-top-color: #3ea3ff; - animation: spin .5s linear infinite; - -webkit-animation: spin .5s linear infinite; -} -.ck-file-input { - display: none; -} -.ck-embed { - text-align: center; - margin: 1em 0; - -moz-user-select: none; - -webkit-user-select: none; - -ms-user-select: none; - user-select: none; -} -.ck-embed.selected figure { - border: 4px solid #3ea3ff; - margin: -4px; -} -.ck-embed iframe { - margin: 0 auto !important; - width: 100% !important; -} -.ck-embed figure { - position: relative; - margin: 0; -} -.ck-embed figcaption { - color: #999; - font-size: 0.7em; - line-height: 1.35em; - font-style: italic; - margin: 10px 0; -} -.ck-embed figcaption a { - color: #999; - text-decoration: none; -} -.ck-embed figcaption a:hover { - color: #666; - text-decoration: underline; -} -@media screen and (min-width: 1080px) { - .ck-embed figcaption { - position: absolute; - top: 0; - right: -130px; - width: 130px; - text-align: left; - margin: 0; - padding-left: 2em; - } -} -.ck-video-container { - position: relative; - overflow: hidden; - padding-top: 56.25%; -} -.ck-video-container iframe, -.ck-video-container object, -.ck-video-container embed { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; -} -.ck-image-embed { - -webkit-animation: fade-in 1s; - animation: fade-in 1s; -} -.ck-message { - position: fixed; - left: 0; - right: 0; - height: 3em; - line-height: 3em; - top: -3em; - z-index: 2; - padding: 0 1em; - font-weight: 500; - text-align: center; - background-color: rgba(103, 182, 255, 0.98); - border-bottom: 1px solid #4daaff; - -webkit-animation: messageShowHide 3.2s; - animation: messageShowHide 3.2s; -} -.ck-message-error { - color: #a33a3a; - background-color: rgba(233, 106, 106, 0.98); - border-bottom: 1px solid #e75d5d; -} -@-webkit-keyframes messageShowHide { - 8% { - top: 0; - } - 92% { - top: 0; - } - 100% { - top: -3em; - } -} -@keyframes messageShowHide { - 8% { - top: 0; - } - 92% { - top: 0; - } - 100% { - top: -3em; - } -} -/** - * Icons - */ -@font-face { - font-family: 'ck-icons'; - src: url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAALAIAAAwAwT1MvMggi/LwAAAC8AAAAYGNtYXAaVcxdAAABHAAAAExnYXNwAAAAEAAAAWgAAAAIZ2x5Zl5vXY0AAAFwAAAIgGhlYWQBGRzWAAAJ8AAAADZoaGVhBAgCEAAACigAAAAkaG10eA3eACQAAApMAAAALGxvY2EH2AnkAAAKeAAAABhtYXhwABAAtgAACpAAAAAgbmFtZdoByAQAAAqwAAABWnBvc3QAAwAAAAAMDAAAACAAAwIAAZAABQAAAUwBZgAAAEcBTAFmAAAA9QAZAIQAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAABAAADmBgHg/+D/4AHgACAAAAABAAAAAAAAAAAAAAAgAAAAAAACAAAAAwAAABQAAwABAAAAFAAEADgAAAAKAAgAAgACAAEAIOYG//3//wAAAAAAIOYA//3//wAB/+MaBAADAAEAAAAAAAAAAAAAAAEAAf//AA8AAQAAAAAAAAAAAAIAADc5AQAAAAABAAAAAAAAAAAAAgAANzkBAAAAAAEAAAAAAAAAAAACAAA3OQEAAAAAAwAAAAABkgG3AE8AbgCNAAA/ATY3Njc2NzY3Njc0NzQ9ARAnJicmJyYnJiMmIycyNzYzMjMyMzIXFhcWFxYXFhUUBwYHBgcGBwYHFhcWFRQHBgcGBwYHBiMiJyYjIgcGIxMUFxYVFAcUFRQXFjMyNzY3Njc2NTQnJicmJyYjIgcTFBcWFxYzMjU0JyYnJicmJyYjJiMiBxQHFBUUFRQVAAEEFBQKAgIBAQEBAQcBBQUIBwcGCAcBARxFRSUHDQ0GFBMTEhINDQgIBQUGBgwMCQkPLB0dCgoQERcXGBgaDBoZDB85OQmYAQIBAQwTFxIRDg4HCAkIDg8QERMOFwIBAQMVE2sMBwoKCgkODQsKERQIAQAbAQMEBAQEBAUGBAQGBwMTARgNAgICAQEBAQEYAwMEBAgIDAwSEhYODQwICQgIBQQHChwdKh0XFg8OCgoEBAEBBAMBlg8cHQ8IDw8HDQcCBAMJCRERGBQPDwgIBAQD/r4LDQ0GCV8hEwwJCQQFAgMBAw8eHw4DEREKAAAAAAEAAAAAASUBtwBOAAA/ATI3Njc2NzQ3Njc2PQEmJyYnJiM3FhcWFxYzMjc2NzY3BgcGBwYHBgcGFQYHBhUGBwYHFAcGBwYHBhcVFhcGByIHIiMiJyYjIiMiBwYjAAUCFRYKCAQREg8PBwkIDAsFBQoZGBISEQ0PDhQVCAIECBUUCwICAgECAQgREgUDAwMDAgIBBTABBAMGBgMJEBEIJxQOGhsIARgGBgUKEwJQUUpLCgcEAgEBAR4BAQEBAQEBAQEBCw8CBgUEBgYHBQUICAQqTk0YAw4ODAsMDQQFAQgMEAEDAwIDAAAEAAAAAAIlAbcAFAApADEAQgAANxE0NzYzITIXFhURFAcGIyEiJyY1MxQXFjMhMjc2NRE0JyYjISIHBhURNzU3FzcXFSE1NDc2MzIXFhUUBwYjIicmNQANDhMByRMNDg4NE/43Ew4NJQIDBAHJBAIDAwIE/jcEAwIkXC2Tdv5uEBAXFxAQEBAXFxAQLgFbEw0ODg0T/qUTDg0NDhMEAwICAwQBWwQDAgIDBP6lGzdbLZJ3gO4XEBAQEBcXEBAQEBcAAAAAAwAFAAUB1wHXACgAVACAAAATND8BNhc2HwEWFRQHFzYXNh8BFhUUDwEGByYvASY1NDcnBgcmLwEmNRcUHwEWNxY3IicmJyYnJicmNTQ3NjcWMxYXFhcWFxY3NjU0LwEmByYPAQYVFxQfARY3Fj8BNjU0LwEmJwYHFBcWFxYXFhcWFRQHBicGJyInJicmJyYnBhUFGCoYIiIYOxgZGRgjIhg8GBgqGCIjGDsXGRkZIyIYOxg2CDwICwwJAQUEAgEDAwEBCAgMBAQDBAQBAgQFAQkIOwgLCwkqCMkIOwgMCwgqCAg7CAwMCAUFAQICAwEBCAgLBQMEAwQCAgQEAQoBWyIYKRkBARk7GCIkFxoaAQEZOxkhIxcrFgEBFzwXIyIaGBgBARc8FyMBCgk6CQEBCgUDAwEFAgUCBgoJBwEBAgIDAQIEBgEHDQsJOgkBAQkoCQvKCgk7CAEBCCkJCgwHPQcBAQgCBAUBAgMFAgUDDQcJAQECBAICAQUEAgoLAAAAAwANAAUCGAGNABoALwBKAAA3ND8BNjMyHwEWFRQPARcWFRQPAQYjIi8BJjUXEzY3Nh8BFhcWBwMGBwYvASYnJjc3ND8BJyY1ND8BNjMyHwEWFRQPAQYjIi8BJjUNA4UDAwQDDgMDcHADAw4DBAMDhQO+awEDBAMSBAECAWoCAwMEEQQCAgGmA3FxAwMPAgQEA4UDA4UDBAQCDwPJBAOFAwMOAwQEA3BwAwQDAw8CAoYCBLMBcQMCAgEFAQMEA/6PBAICAQUBBAMEPAQDcHADBAQDDgMDhQMEBAKGAgIPAwMAAAAAAQASAAAB7gG3ALMAABM0NzYzMhcWMzI3NjMyFxYVFAcGByIHBgcGHQEUFRY7ATI3NDU3NCcmIyInJjU0NzYzMhcWMzI3NjMyFxYVFAcGIyIHIgcGFREUFxYXFjMyFxYVFAcGIyInJiMiBwYjIicmNTQ3NjcyNzY3NjUnNDUmKwEiBxQdARQXFhcWMzIXFhUUBwYjIicmIyIHBiMiJyY1NDc2NzI3Njc2NSc1MDc0NSY1NCcmJyYnJicmIyYjIicmNRIDBAYOGhoODBgYDAcEAwUFBgYICAQKBAjHBwQBCgUMDAcHAwQHDRkZDQwYGQwHBAQFBQcGCQgECgoECQkGBwUFAwQGDRkaDA0ZGQ0HAwQFBQYGCAkECgEECsELBAoFCQkHCAUGBAMHDRsaDQ0YGAwHAwQEBQYGBwgECgEBAQEBAQECAgIFCAkGBwUFAaMHBwYBAQEBBgcHCQQDAQEBAwYnXAYDAQEDBlwnBgQEAwsHBwYBAQEBBgcHCQQEAQMHJ/7yIgYDAQEEBAkHBwYBAQEBBgYHCQQEAQIBAwYicAYDAQEDBmopBgMBAQQECQcHBgEBAQEGBgcIBQQBAgEDByIQ6QcHAwQHCAQFBgUEAwIDAQQECQAAAAIAAAAbAgEBewAlAEsAADcyHgIVFA4CIyIuAjUnND4CMxUiDgIHDgMHMjY6ATMhMh4CFRQOAiMiLgI1JzQ+AjMVIg4CBw4DBzI2OgEzcBcoHxESHygXGCgfEQEjPVIuEB8dGgsCBAQEAgIEBQQCASAXKB8REh8oFxgoHxEBIz1SLhAfHRoLAgQEBAICBAUEAvsRHygYFykeEhIeKRcQL1E9I0AGDBELAwQFBQIBER8oGBcpHhISHikXEC9RPSNABgwRCwMEBQUCAQAAAAEAAAABAABSja6rXw889QALAgAAAAAAz+ruAQAAAADP6u4BAAAAAAIlAdcAAAAIAAIAAAAAAAAAAQAAAeD/4AAAAiUAAP//AiUAAQAAAAAAAAAAAAAAAAAAAAsAAAAAAAAAAAAAAAABAAAAAZMAAAElAAACJQAAAdwABQIlAA0CAAASAgAAAAAAAAAACgAUAB4A5gFaAbwCfALuA9oEQAABAAAACwC0AAQAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAADgCuAAEAAAAAAAEAEAAAAAEAAAAAAAIADgBaAAEAAAAAAAMAHAAmAAEAAAAAAAQAEABoAAEAAAAAAAUAFgAQAAEAAAAAAAYACABCAAEAAAAAAAoANAB4AAMAAQQJAAEAEAAAAAMAAQQJAAIADgBaAAMAAQQJAAMAHAAmAAMAAQQJAAQAEABoAAMAAQQJAAUAFgAQAAMAAQQJAAYAEABKAAMAAQQJAAoANAB4AGMAawAtAGkAYwBvAG4AcwBWAGUAcgBzAGkAbwBuACAAMQAuADAAYwBrAC0AaQBjAG8AbgBzADoAIAAyADAAMQA0Y2staWNvbnMAYwBrAC0AaQBjAG8AbgBzAFIAZQBnAHUAbABhAHIAYwBrAC0AaQBjAG8AbgBzAEYAbwBuAHQAIABnAGUAbgBlAHIAYQB0AGUAZAAgAGIAeQAgAEkAYwBvAE0AbwBvAG4ALgAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=) format('truetype'), url(data:application/font-woff;charset=utf-8;base64,d09GRk9UVE8AAA1gAAoAAAAADRgAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABDRkYgAAAA9AAACaoAAAmqfszNZk9TLzIAAAqgAAAAYAAAAGAIIvy8Y21hcAAACwAAAABMAAAATBpVzF1nYXNwAAALTAAAAAgAAAAIAAAAEGhlYWQAAAtUAAAANgAAADYBGRzWaGhlYQAAC4wAAAAkAAAAJAQIAhBobXR4AAALsAAAACwAAAAsDd4AJG1heHAAAAvcAAAABgAAAAYAC1AAbmFtZQAAC+QAAAFaAAABWtoByARwb3N0AAANQAAAACAAAAAgAAMAAAEABAQAAQEBCWNrLWljb25zAAECAAEAOvgcAvgbA/gYBB4KABlT/4uLHgoAGVP/i4sMB4tr+Ln4dAUdAAAAnQ8dAAAAohEdAAAACR0AAAmhEgAMAQEJERMVGB0iJywxNjtjay1pY29uc2NrLWljb25zdTB1MXUyMHVFNjAwdUU2MDF1RTYwMnVFNjAzdUU2MDR1RTYwNXVFNjA2AAACAYkACQALAgABAAQABwAKAA0ByAK/A5wFNwY+CHEI5fyUDvyUDvyUDvuUDvsBi4sVjKYFjYyUjJiNmI6VjZKOjI2NjoyOjI6MjouOjI+LjoyOi42Lj4yPi5CLjouNCIueBYv3T4nthpOLjImNh4yIjIaMhoyGjIeMhouHi4aMhouHjIiLiosIiqMFnYusjLmNuY2ujKSLkIuRi5SLlIuRi4+LmIuYiZiJmIiXh5eGl4WVhZSDk4OTgZB/CJB/jn6LfIuCiYGIg4iDh4SHhoeFhYaDhYOGhIaFiIWIg4eBh6iEo36feZ94lHOLbwiLeIh6hHuFfIJ/gIF/gX6DfIV8hHuHe4h7iHuKeYuDi36Leox7i36Mg4t3i22KZYgIZYl1ioWLCPcs+CoVi4GMfYt4jHeMfYuBi4aLg4qBi4GLhIuGi4KLhIyHk4qVipiLmouZjJeOlo2Wj5SRCJSRkpSQlpCWjpmLm4uYiJeFlYaVg5KCkYGRgY+AjYCOf4x+i4KLf4p7iQiN+9YVi4SLg4yCjIKMhY2HmYWYiJiL0ouvq4vKi6GHnIOYhpOFkoWRhJGFj4SOhY6DjoKMCIKNg4yEi4SMgouAi36LgYqGiYuBi3yKd4t3i3uLgouJi4WLf4uAi4KLhAgO+2+LjBWQowWMi5ONmY+aj5WOko+QkY+VjpiLjJGmlsGXwZa/lbyVvZCni5IIi5IFho6GjYWMhYyFi4OMhIuFjIiLCJCpBZKKloucipuKmYqXi5eLl4qWi5SLlIyVi5SLl4yYjJmMlIuRjIqDiYOIgYWKgoh9hwh+iICIhIiKh4mHioeKhoqHi4iKiIqHioWLhoqHi4iFb4NjgFd/WIRph3uLiYqFiYIIiYKJgomDiYSKg4mDioKLhouICIuGBY6KnYirhoqDioGIgYmLiIuHioeLiIuJi4WLg4yAjYCNg4yFi3GLd4t+i4KLfYp6igh5iYCKhYsIDrCLuRWL9+8Fi5iPlZSUlJSWkJiLCPhdiwWXi5aGlIKUgpCBi34Ii/vvBYt+hoCCgoKCgId/iwj8XYsFfouAj4KUgpSHlouYCLCLFYuIi4mNiY2JjYuOiwj4XYsFjYuNi42NjY2MjYuOCIv37wWLjoqNiY2JjImMiYsI/F2LBYiLiYqJiomJi4mLiAiL++8Fr6YVi8Ln5rhe9yf3JvcK+wuL+xT8JosFi/eCFYuakJiWlpaVmJGai5qLmIWWgZaAkH6LfIt8hn6AgICAfoZ8i3yLfpCAloCWhpiLmggOZ5D37xWLopOfm5oItbUFm5uek6KLooueg5t7CMZPBZt8k3eLdIt0gnd7ewikcgWbm5+Uoouii56Dm3sIx08Fm3uTeIt0i3SDeHt7CGFhBXt7d4R1i3SLd5N7mwhQxgV8m4Oei6KLopOfnJwIcqQFenp4g3OLdIt4k3ubCFDGBXubg5+LoQjBixWLhI6EkIYIx1AFkIWRiZOLk4uSjpGRiouJjYiOiI6JjYqMioyKjYmOiY2KjYqOi42KjouOi5KOkpCQCJGQkY6Ti46LjYuOio2KjYqOiY2KjYmMioyKjYmOiI6IjYmMi5GQjpKLk4uTiJKGkAhQxgWGkISOhIuDi4WIhYYIYWIFhoWIhYuDCPdd+10Vi4OOhZCGCMZPBZCGkomTi5KLko2QkAi1tQWQkI6Si5KLk4iRhpAIUMcFhZCFjoOLg4uEiIaFi4qNiY6IjoiNiYyKjIqNiYyJjYiMiYyJjIiLiYuIi4OIhYaFCIaGhIiEi4iLiIyJi4iMiYyJjYiNiYyKjIqMiY2IjoiOiY2LjISFiISLgwgOsJj3XRWLjoyNjY0I9xn3GQWNjY2MjYuOi42KjYkImX0FjYmMiIuJi4mKiImJCPsE+wT3BPsEBY2JjImLiIuJiomJiQh9fAWJiomKiIuJi4mMiYwI+xn3GgWJjIqOi40I91L7RxX2+AUFjI2MjY2MjoyNjI2KCJ2GBY2KjYqMiY2Ii4mKiQgh/AUFioiJiYmKiYqJi4iLCHqQBYiMiY2KjYqNi42Ljgj3OscVi46MjY2NCPcF9wT7BfcEBYmNio6LjYuNjI6NjQiamQWMjY6MjYuOi42KjYkI9xn7GQWNiYyJi4iLiYqIiYoI+xn7GgWJiomKiIuJi4iMiowIfJoFiY2KjYuNCA6d+DcVi5CMj42QjY+PjY+LlIuYi52KnYqYi5SLk4uXi5uMm4yXi5OLkIuOiY6HjYaMh4uGCIuFioeHiIiJh4mHi4eLhouGioaLh4mIiYSHiHyLcQiLLwWLh4uIi4mOi4+KkIsI91uLBZCLj4yNi4uNi46LjwiM5wWLpYeahY+HjoaMg4uDi4WNho2GjYmQi5KLkIyPjZCOj46NkIuUi5eLnIqcipeLlIsIk4uXi5uMnIyXi5OLkIuPiY2HjYaNh4uGi4WJh4iIh4mHiYeLh4uGi4WKhouHioiJCISGiHyLcQiL+6IFi3WOfZKHjomPipGKkYuQio+LkIuPiY6Jj4iMh4uFi4aKhomHiYeHiYeLgot/i3qMCHqMfouDi4KLf4t6inqKf4uCi4eLh42Jj4iPio+LkIuRjI+Pjo6Oj4yPjI+LkIyQjAiRjI+Mjo2Sj46Yi6IIivcEBYuPi46LjYmLhoyEiwj7VYsFhIuGioiLi4mLiIuHCIshBYtwjnuSh46JkIqRipGLkYqPi5CLj4qPiI+IjYeLhYuGioaIh4mHiImGi4KLfot5jAh6jH2Lg4uCi3+Le4p7in+Lg4uGi4iNiY+Ij4qPi5CLkYyPjo6Ojo+Mj4yPi4+MkIwIkIyPjI6NkpCOmIuiCIqbi/d9BYuLi46Mj4uPi4+LjYqOi4+Lj4uQi4+KjouPio6Kj4uPiY6KjYqNiY2KjIiNhoyGiwiFjIaLh4uGi4eMiI6HjoqPi5EIDvcF948VyIu+WYtNi05YWE6LTYtZvovICIqbBYv3EO/v9xCLCItLBWCLY3ttbYWFhoWGhJGMkYuRiwj3tIsVyIu+WYtNi05YWE6LTYtZvovICIqbBYv3EO/v9xCLCItLBWCLY3ttbYWFhoWGhJGMkYuRiwgO+JQU+JQViwwKAAAAAwIAAZAABQAAAUwBZgAAAEcBTAFmAAAA9QAZAIQAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAABAAADmBgHg/+D/4AHgACAAAAABAAAAAAAAAAAAAAAgAAAAAAACAAAAAwAAABQAAwABAAAAFAAEADgAAAAKAAgAAgACAAEAIOYG//3//wAAAAAAIOYA//3//wAB/+MaBAADAAEAAAAAAAAAAAAAAAEAAf//AA8AAQAAAAEAAGLPbdVfDzz1AAsCAAAAAADP6u4BAAAAAM/q7gEAAAAAAiUB1wAAAAgAAgAAAAAAAAABAAAB4P/gAAACJQAA//8CJQABAAAAAAAAAAAAAAAAAAAACwAAAAAAAAAAAAAAAAEAAAABkwAAASUAAAIlAAAB3AAFAiUADQIAABICAAAAAABQAAALAAAAAAAOAK4AAQAAAAAAAQAQAAAAAQAAAAAAAgAOAFoAAQAAAAAAAwAcACYAAQAAAAAABAAQAGgAAQAAAAAABQAWABAAAQAAAAAABgAIAEIAAQAAAAAACgA0AHgAAwABBAkAAQAQAAAAAwABBAkAAgAOAFoAAwABBAkAAwAcACYAAwABBAkABAAQAGgAAwABBAkABQAWABAAAwABBAkABgAQAEoAAwABBAkACgA0AHgAYwBrAC0AaQBjAG8AbgBzAFYAZQByAHMAaQBvAG4AIAAxAC4AMABjAGsALQBpAGMAbwBuAHMAOgAgADIAMAAxADRjay1pY29ucwBjAGsALQBpAGMAbwBuAHMAUgBlAGcAdQBsAGEAcgBjAGsALQBpAGMAbwBuAHMARgBvAG4AdAAgAGcAZQBuAGUAcgBhAHQAZQBkACAAYgB5ACAASQBjAG8ATQBvAG8AbgAuAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==) format('woff'); - font-weight: normal; - font-style: normal; -} -.ck-icon-bold, -.ck-icon-italic, -.ck-icon-image, -.ck-icon-link, -.ck-icon-embed, -.ck-icon-heading, -.ck-icon-quote { - font-family: 'ck-icons'; - speak: none; - font-style: normal; - font-weight: normal; - font-variant: normal; - text-transform: none; - line-height: 1; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} -.ck-icon-bold:before { - content: "\e600"; -} -.ck-icon-italic:before { - content: "\e601"; -} -.ck-icon-image:before { - content: "\e602"; -} -.ck-icon-link:before { - content: "\e603"; -} -.ck-icon-embed:before { - content: "\e604"; -} -.ck-icon-heading:before { - content: "\e605"; -} -.ck-icon-quote:before { - content: "\e606"; -} -/** - * Animations - */ -@-webkit-keyframes fade-in { - 0% { - opacity: 0; - } - 100% { - opacity: 1; - } -} -@keyframes fade-in { - 0% { - opacity: 0; - } - 100% { - opacity: 1; - } -} -@-webkit-keyframes spin { - to { - -webkit-transform: rotate(360deg); - } -} -@keyframes spin { - to { - transform: rotate(360deg); - } -} -@-webkit-keyframes shake { - 0%, - 100% { - -webkit-transform: translateX(0); - } - 20%, - 60% { - -webkit-transform: translateX(-10px); - } - 40%, - 80% { - -webkit-transform: translateX(10px); - } -} -@keyframes shake { - 0%, - 100% { - transform: translateX(0); - } - 20%, - 60% { - transform: translateX(-10px); - } - 40%, - 80% { - transform: translateX(10px); - } -} -@-webkit-keyframes textGlimmer { - 0% { - background-position: -288px 0; - } - 100% { - background-position: 288px 0; - } -} -@-webkit-keyframes pop-out { - 0% { - opacity: 0.8; - -webkit-transform: scale(0.8); - } - 50% { - opacity: 1; - -webkit-transform: scale(1.1); - } -} -@keyframes pop-out { - 0% { - opacity: 0.8; - transform: scale(0.8); - } - 50% { - opacity: 1; - transform: scale(1.1); - } -} -@-webkit-keyframes pop-up { - 0% { - opacity: 0.8; - -webkit-transform: scale(0.9) translateY(14px); - } - 50% { - opacity: 1; - -webkit-transform: scale(1.05) translateY(-4px); - } -} -@keyframes pop-up { - 0% { - opacity: 0.8; - transform: scale(0.9) translateY(14px); - } - 50% { - opacity: 1; - transform: scale(1.05) translateY(-4px); - } -} -@-webkit-keyframes pop-right { - 0% { - opacity: 0.8; - -webkit-transform: scale(0.9) translateX(-14px) translateY(-50%); - } - 50% { - opacity: 1; - -webkit-transform: scale(1.05) translateX(4px) translateY(-50%); - } -} -@keyframes pop-right { - 0% { - opacity: 0.8; - transform: scale(0.9) translateX(-14px); - } - 50% { - opacity: 1; - transform: scale(1.05) translateX(4px); - } -} -@-webkit-keyframes slide-down { - 0% { - -webkit-transform: translateY(-100%); - } - 100% { - -webkit-transform: none; - } -} -@keyframes slide-down { - 0% { - transform: translateY(-100%); - } - 100% { - transform: none; - } -} diff --git a/dist/content-kit-editor.js b/dist/content-kit-editor.js deleted file mode 100644 index 451dadb96..000000000 --- a/dist/content-kit-editor.js +++ /dev/null @@ -1,2577 +0,0 @@ -/** - * @overview content-kit-editor: A modern, minimalist WYSIWYG editor. - * @version 0.1.3 - * @author Garth Poitras (http://garthpoitras.com/) - * @license MIT - */ - -(function(window, document, undefined) { - - var RegExpTrim = /^\s+|\s+$/g; - var RegExpTrimLeft = /^\s+/; - var RegExpWSChars = /(\r\n|\n|\r|\t)/gm; - var RegExpMultiWS = /\s+/g; - var RegExpNonAlphaNum = /[^a-zA-Z\d]/g; - - /** - * String.prototype.trim polyfill - * Removes whitespace at beginning and end of string - */ - function trim(string) { - return string ? (string + '').replace(RegExpTrim, '') : ''; - } - - /** - * String.prototype.trimLeft polyfill - * Removes whitespace at beginning of string - */ - function trimLeft(string) { - return string ? (string + '').replace(RegExpTrimLeft, '') : ''; - } - - /** - * Replaces non-alphanumeric chars with underscores - */ - function underscore(string) { - return string ? trim(string + '').replace(RegExpNonAlphaNum, '_') : ''; - } - - /** - * Cleans line breaks, tabs, then multiple occuring whitespaces. - */ - function sanitizeWhitespace(string) { - return string ? (string + '').replace(RegExpWSChars, '').replace(RegExpMultiWS, ' ') : ''; - } - - /** - * Injects a string into another string at the index specified - */ - function injectIntoString(string, injection, index) { - return string.substr(0, index) + injection + string.substr(index); - } - - function Type(options) { - if (options) { - this.name = underscore(options.name || options.tag).toUpperCase(); - this.isTextType = options.isTextType !== undefined ? options.isTextType : true; - - if (options.id !== undefined) { - this.id = options.id; - } - if (options.tag) { - this.tag = options.tag.toLowerCase(); - this.selfClosing = /^(br|img|hr|meta|link|embed)$/i.test(this.tag); - if (options.mappedTags) { - this.mappedTags = options.mappedTags; - } - } - - // Register the type as constant - Type[this.name] = this; - } - } - - var types_type = Type; - - /** - * @class Model - * @constructor - * @private - */ - function Model(options) { - options = options || {}; - var type_name = options.type_name; - var attributes = options.attributes; - - this.type = options.type || null; - if (type_name) { - this.type_name = type_name; - } - if (attributes) { - this.attributes = attributes; - } - } - - /** - * @method createWithType - * @static - * @param type Type - * @param options Object - */ - Model.createWithType = function(type, options) { - options = options || {}; - options.type = type.id; - options.type_name = type.name; - return new this(options); - }; - - var models_model = Model; - - /** - * Merges defaults/options into an Object - * Useful for constructors - */ - function mergeWithOptions(original, updates, options) { - options = options || {}; - for(var prop in updates) { - if (options.hasOwnProperty(prop)) { - original[prop] = options[prop]; - } else if (updates.hasOwnProperty(prop)) { - original[prop] = updates[prop]; - } - } - return original; - } - - /** - * Merges properties of one object into another - */ - function merge(original, updates) { - return mergeWithOptions(original, updates); - } - - /** - * Prototype inheritance helper - */ - function inherit(Subclass, Superclass) { - for (var key in Superclass) { - if (Superclass.hasOwnProperty(key)) { - Subclass[key] = Superclass[key]; - } - } - Subclass.prototype = new Superclass(); - Subclass.constructor = Subclass; - Subclass._super = Superclass; - } - - function sortBlockMarkups(markups) { - return markups.sort(function(a, b) { - if (a.start === b.start && a.end === b.end) { - return b.type - a.type; - } - return 0; - }); - } - - /** - * @class BlockModel - * @constructor - * @extends Model - */ - function BlockModel(options) { - options = options || {}; - models_model.call(this, options); - this.value = options.value || ''; - this.markup = sortBlockMarkups(options.markup || []); - } - - inherit(BlockModel, models_model); - - var models_block = BlockModel; - - function EmbedModel(options) { - if (!options) { return null; } - - models_model.call(this, { - type: types_type.EMBED.id, - type_name: types_type.EMBED.name, - attributes: {} - }); - - // Massage the oEmbed data - var attributes = this.attributes; - var embedType = options.type; - var providerName = options.provider_name; - var embedUrl = options.url; - var embedTitle = options.title; - var embedThumbnail = options.thumbnail_url; - var embedHtml = options.html; - - if (embedType) { attributes.embed_type = embedType; } - if (providerName) { attributes.provider_name = providerName; } - if (embedUrl) { attributes.url = embedUrl; } - if (embedTitle) { attributes.title = embedTitle; } - - if (embedType === 'photo') { - attributes.thumbnail = options.media_url || embedUrl; - } else if (embedThumbnail) { - attributes.thumbnail = embedThumbnail; - } - - if (embedHtml && (embedType === 'rich' || embedType === 'video')) { - attributes.html = embedHtml; - } - } - - var embed = EmbedModel; - - /** - * Abstracted `document` between node.js and browser - */ - - var doc; - - if (typeof exports === 'object') { - var jsdom = require('jsdom').jsdom; - doc = jsdom(); - } else { - // A document instance separate from the html page document. (if browser supports it) - // Prevents images, scripts, and styles from executing while parsing - var implementation = document.implementation; - var createHTMLDocument = implementation.createHTMLDocument; - if (createHTMLDocument) { - doc = createHTMLDocument.call(implementation, ''); - } else { - doc = document; - } - } - - var parserDocument = doc; - - function MarkupModel(options) { - options = options || {}; - models_model.call(this, options); - this.start = options.start || 0; - this.end = options.end || 0; - } - - inherit(MarkupModel, models_model); - - var models_markup = MarkupModel; - - function TypeSet(types) { - var len = types && types.length, i; - - this._autoId = 1; // Auto-increment id counter - this.idLookup = {}; // Hash cache for finding by id - this.tagLookup = {}; // Hash cache for finding by tag - - for (i = 0; i < len; i++) { - this.addType(types[i]); - } - } - - TypeSet.prototype = { - /** - * Adds a type to the set - */ - addType: function(type) { - if (type instanceof types_type) { - this[type.name] = type; - if (type.id === undefined) { - type.id = this._autoId++; - } - this.idLookup[type.id] = type; - if (type.tag) { - this.tagLookup[type.tag] = type; - if (type.mappedTags) { - for (var i = 0, len = type.mappedTags.length; i < len; i++) { - this.tagLookup[type.mappedTags[i]] = type; - } - } - } - return type; - } - }, - - /** - * Returns type info for a given Node - */ - findByNode: function(node) { - if (node) { - return this.findByTag(node.tagName); - } - }, - /** - * Returns type info for a given tag - */ - findByTag: function(tag) { - if (tag) { - return this.tagLookup[tag.toLowerCase()]; - } - }, - /** - * Returns type info for a given id - */ - findById: function(id) { - return this.idLookup[id]; - } - }; - - var type_set = TypeSet; - - var DefaultBlockTypeSet = new type_set([ - new types_type({ tag: 'p', name: 'paragraph' }), - new types_type({ tag: 'h2', name: 'heading' }), - new types_type({ tag: 'h3', name: 'subheading' }), - new types_type({ tag: 'img', name: 'image', isTextType: false }), - new types_type({ tag: 'blockquote', name: 'quote' }), - new types_type({ tag: 'ul', name: 'list' }), - new types_type({ tag: 'ol', name: 'ordered list' }), - new types_type({ name: 'embed', isTextType: false }), - new types_type({ name: 'card' }) - ]); - - /** - * Default supported markup types - */ - var DefaultMarkupTypeSet = new type_set([ - new types_type({ tag: 'strong', name: 'bold', mappedTags: ['b'] }), - new types_type({ tag: 'em', name: 'italic', mappedTags: ['i'] }), - new types_type({ tag: 'u', name: 'underline' }), - new types_type({ tag: 'a', name: 'link' }), - new types_type({ tag: 'br', name: 'break' }), - new types_type({ tag: 'li', name: 'list item' }), - new types_type({ tag: 'sub', name: 'subscript' }), - new types_type({ tag: 'sup', name: 'superscript' }) - ]); - - /** - * Converts an array-like object (i.e. NodeList) to Array - * Note: could just use Array.prototype.slice but does not work in IE <= 8 - */ - function toArray(obj) { - var array = []; - var i = obj && obj.length >>> 0; // cast to Uint32 - while (i--) { - array[i] = obj[i]; - } - return array; - } - - /** - * Computes the sum of values in a (sparse) array - */ - function sumSparseArray(array) { - var sum = 0, i; - for (i in array) { // 'for in' is better for sparse arrays - if (array.hasOwnProperty(i)) { - sum += array[i]; - } - } - return sum; - } - - function textOfNode(node) { - var text = node.textContent || node.innerText; - return text ? sanitizeWhitespace(text) : ''; - } - - /** - * Replaces a `Node` with its children - */ - function unwrapNode(node) { - if (node.hasChildNodes()) { - var children = toArray(node.childNodes); - var len = children.length; - var parent = node.parentNode, i; - for (i = 0; i < len; i++) { - parent.insertBefore(children[i], node); - } - } - } - - /** - * Extracts attributes of a `Node` to a hash of key/value pairs - */ - function attributesForNode(node, blacklist) { - var attrs = node.attributes; - var len = attrs && attrs.length; - var i, attr, name, hash; - - for (i = 0; i < len; i++) { - attr = attrs[i]; - name = attr.name; - if (attr.specified && attr.value) { - if (blacklist && (name in blacklist)) { continue; } - hash = hash || {}; - hash[name] = attr.value; - } - } - return hash; - } - - var ELEMENT_NODE = 1; - var TEXT_NODE = 3; - var defaultAttributeBlacklist = { 'style' : 1, 'class' : 1 }; - - /** - * Returns the last block in the set or creates a default block if none exist yet. - */ - function getLastBlockOrCreate(blocks) { - var blockCount = blocks.length, block; - if (blockCount) { - block = blocks[blockCount - 1]; - } else { - block = models_block.createWithType(types_type.PARAGRAPH); - blocks.push(block); - } - return block; - } - - /** - * Helper to parse elements at the root that aren't blocks - */ - function handleNonBlockAtRoot(parser, elementNode, blocks) { - var block = getLastBlockOrCreate(blocks); - var markup = parser.parseMarkupForElement(elementNode, block.value.length); - if (markup) { - block.markup = block.markup.concat(markup); - } - block.value += textOfNode(elementNode); - } - - /** - * @class HTMLParser - * @constructor - */ - function HTMLParser(options) { - var defaults = { - blockTypes : DefaultBlockTypeSet, - markupTypes : DefaultMarkupTypeSet, - attributeBlacklist : defaultAttributeBlacklist, - includeTypeNames : false - }; - mergeWithOptions(this, defaults, options); - } - - /** - * @method parse - * @param html String of HTML content - * @return Array Parsed JSON content array - */ - HTMLParser.prototype.parse = function(html) { - var parsingNode = parserDocument.createElement('div'); - parsingNode.innerHTML = sanitizeWhitespace(html); - - var nodes = toArray(parsingNode.childNodes); - var nodeCount = nodes.length; - var blocks = []; - var i, node, nodeType, block, text; - - for (i = 0; i < nodeCount; i++) { - node = nodes[i]; - nodeType = node.nodeType; - - if (nodeType === ELEMENT_NODE) { - block = this.serializeBlockNode(node); - if (block) { - blocks.push(block); - } else { - handleNonBlockAtRoot(this, node, blocks); - } - } else if (nodeType === TEXT_NODE) { - text = node.nodeValue; - if (trim(text)) { - block = getLastBlockOrCreate(blocks); - block.value += text; - } - } - } - - return blocks; - }; - - /** - * @method parseMarkupForElement - * @param node element node to parse - * @return {Array} parsed markups - */ - HTMLParser.prototype.parseMarkupForElement = function(node, startOffset) { - var index = 0; - var markups = []; - var currentNode, nodeType, markup; - - startOffset = startOffset || 0; - node = node.cloneNode(true); - markup = this.serializeMarkupNode(node, startOffset); - if (markup) { markups.push(markup); } - - while (node.hasChildNodes()) { - currentNode = node.firstChild; - nodeType = currentNode.nodeType; - - if (nodeType === ELEMENT_NODE) { - markup = this.serializeMarkupNode(currentNode, startOffset); - if (markup) { markups.push(markup); } - unwrapNode(currentNode); - } else if (nodeType === TEXT_NODE) { - var text = sanitizeWhitespace(currentNode.nodeValue); - if (index === 0) { text = trimLeft(text); } - if (text) { startOffset += text.length; } - } - - currentNode.parentNode.removeChild(currentNode); - index++; - } - - return markups; - }; - - /** - * @method serializeBlockNode - * @param node element node to parse - * @return {BlockModel} parsed block model - * Serializes a single block type node into a model - */ - HTMLParser.prototype.serializeBlockNode = function(node) { - var type = this.blockTypes.findByNode(node); - if (type) { - return new models_block({ - type : type.id, - type_name : this.includeTypeNames && type.name, - value : trim(textOfNode(node)), - attributes : attributesForNode(node, this.attributeBlacklist), - markup : this.parseMarkupForElement(node) - }); - } - }; - - /** - * @method serializeMarkupNode - * @param node element node to parse - * @param startIndex - * @return {MarkupModel} markup model - * Serializes markup of a single html element node (no child elements) - */ - HTMLParser.prototype.serializeMarkupNode = function(node, startIndex) { - var type = this.markupTypes.findByNode(node); - var selfClosing, endIndex; - - if (type) { - selfClosing = type.selfClosing; - if (!selfClosing && !node.hasChildNodes()) { return; } // check for empty nodes - - endIndex = startIndex + (selfClosing ? 0 : textOfNode(node).length); - if (endIndex > startIndex || (selfClosing && endIndex === startIndex)) { // check for empty nodes - return new models_markup({ - type : type.id, - type_name : this.includeTypeNames && type.name, - start : startIndex, - end : endIndex, - attributes : attributesForNode(node, this.attributeBlacklist) - }); - } - } - }; - - var html_parser = HTMLParser; - - function createOpeningTag(tagName, attributes, selfClosing) { - var tag = '<' + tagName; - for (var attr in attributes) { - if (attributes.hasOwnProperty(attr)) { - tag += ' ' + attr + '="' + attributes[attr] + '"'; - } - } - if (selfClosing) { tag += '/'; } - tag += '>'; - return tag; - } - - /** - * Builds a closing html tag. i.e. '

' - */ - function createCloseTag(tagName) { - return ''; - } - - /** - * @class HTMLElementRenderer - * @constructor - */ - function HTMLElementRenderer(options) { - options = options || {}; - this.type = options.type; - this.markupTypes = options.markupTypes; - } - - /** - * @method render - * @param model a block model - * @return String html - * Renders a block model into a HTML string. - */ - HTMLElementRenderer.prototype.render = function(model) { - var html = ''; - var type = this.type; - var tagName = type.tag; - var selfClosing = type.selfClosing; - - if (tagName) { - html += createOpeningTag(tagName, model.attributes, selfClosing); - } - if (!selfClosing) { - html += this.renderMarkup(model.value, model.markup); - if (tagName) { - html += createCloseTag(tagName); - } - } - return html; - }; - - /** - * @method renderMarkup - * @param text plain text to apply markup to - * @param markup an array of markup models - * @return String html - * Renders a markup model into a HTML string. - */ - HTMLElementRenderer.prototype.renderMarkup = function(text, markups) { - var parsedTagsIndexes = []; - var len = markups && markups.length, i; - - for (i = 0; i < len; i++) { - var markup = markups[i], - markupMeta = this.markupTypes.findById(markup.type), - tagName = markupMeta.tag, - selfClosing = markupMeta.selfClosing, - start = markup.start, - end = markup.end, - openTag = createOpeningTag(tagName, markup.attributes, selfClosing), - parsedTagLengthAtIndex = parsedTagsIndexes[start] || 0, - parsedTagLengthBeforeIndex = sumSparseArray(parsedTagsIndexes.slice(0, start + 1)); - - text = injectIntoString(text, openTag, start + parsedTagLengthBeforeIndex); - parsedTagsIndexes[start] = parsedTagLengthAtIndex + openTag.length; - - if (!selfClosing) { - var closeTag = createCloseTag(tagName); - parsedTagLengthAtIndex = parsedTagsIndexes[end] || 0; - parsedTagLengthBeforeIndex = sumSparseArray(parsedTagsIndexes.slice(0, end)); - text = injectIntoString(text, closeTag, end + parsedTagLengthBeforeIndex); - parsedTagsIndexes[end] = parsedTagLengthAtIndex + closeTag.length; - } - } - - return text; - }; - - var html_element_renderer = HTMLElementRenderer; - - /** - * @class HTMLEmbedRenderer - * @constructor - */ - function HTMLEmbedRenderer() {} - - /** - * @method render - * @param model a block model - * @return String html - */ - HTMLEmbedRenderer.prototype.render = function(model) { - var attrs = model.attributes; - return attrs && attrs.html || ''; - }; - - var html_embed_renderer = HTMLEmbedRenderer; - - /** - * @class CardRenderer - * @constructor - */ - function CardRenderer(cards) { - this.cards = cards; - } - - /** - * @method render - * @param model a card model - * @return String html - */ - CardRenderer.prototype.render = function(model) { - var render = this.cards[model.attributes.name]; - return '
'+render(model.attributes.payload)+'
'; - }; - - var card_renderer = CardRenderer; - - function HTMLRenderer(options) { - var defaults = { - blockTypes : DefaultBlockTypeSet, - markupTypes : DefaultMarkupTypeSet, - typeRenderers : {}, - cards : {} - }; - mergeWithOptions(this, defaults, options); - } - - /** - * @method rendererFor - * @param block - * @returns renderer - * Returns an instance of a renderer for supplied block model - */ - HTMLRenderer.prototype.rendererFor = function(block) { - var type = this.blockTypes.findById(block.type); - if (type === types_type.EMBED) { - return new html_embed_renderer(); - } - if (type === types_type.CARD) { - return new card_renderer(this.cards); - } - return new html_element_renderer({ type: type, markupTypes: this.markupTypes }); - }; - - /** - * @method render - * @param model - * @return String html - */ - HTMLRenderer.prototype.render = function(model) { - var html = ''; - var len = model && model.length; - var i, blockHtml; - - for (i = 0; i < len; i++) { - // this is renderModel, not only blocks!! - blockHtml = this.renderBlock(model[i]); - if (blockHtml) { - html += blockHtml; - } - } - - return html; - }; - - /** - * @method renderBlock - * @param block - * @return String html - */ - HTMLRenderer.prototype.renderBlock = function(block) { - var renderer = this.rendererFor(block); - var renderHook = this.typeRenderers[block.type]; - return renderHook ? renderHook.call(renderer, block) : renderer.render(block); - }; - - var html_renderer = HTMLRenderer; - - function Compiler(options) { - var parser = new html_parser(); - var renderer = new html_renderer(); - var defaults = { - parser : parser, - renderer : renderer, - blockTypes : DefaultBlockTypeSet, - markupTypes : DefaultMarkupTypeSet, - includeTypeNames : false // Outputs `type_name:'HEADING'` etc. when parsing. Good for debugging. - }; - mergeWithOptions(this, defaults, options); - - // Reference the compiler settings - this.parser.blockTypes = this.renderer.blockTypes = this.blockTypes; - this.parser.markupTypes = this.renderer.markupTypes = this.markupTypes; - this.parser.includeTypeNames = this.includeTypeNames; - } - - /** - * @method parse - * @param input - * @return Array - */ - Compiler.prototype.parse = function(input) { - return this.parser.parse(input); - }; - - /** - * @method render - * @param model - * @return String - */ - Compiler.prototype.render = function(model) { - return this.renderer.render(model); - }; - - /** - * @method rerender - * @param input - * @return String - */ - Compiler.prototype.rerender = function(input) { - return this.render(this.parse(input)); - }; - - /** - * @method reparse - * @param model - * @return String - */ - Compiler.prototype.reparse = function(model) { - return this.parse(this.render(model)); - }; - - /** - * @method registerBlockType - * @param {Type} type - */ - Compiler.prototype.registerBlockType = function(type) { - return this.blockTypes.addType(type); - }; - - /** - * @method registerMarkupType - * @param {Type} type - */ - Compiler.prototype.registerMarkupType = function(type) { - return this.markupTypes.addType(type); - }; - - var compiler = Compiler; - - var RegExVideoId = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/; - - function getVideoIdFromUrl(url) { - var match = url && url.match(RegExVideoId); - if (match && match[1].length === 11){ - return match[1]; - } - return null; - } - - function YouTubeRenderer() {} - YouTubeRenderer.prototype.render = function(model) { - var videoId = getVideoIdFromUrl(model.attributes.url); - var embedUrl = 'http://www.youtube.com/embed/' + videoId + '?controls=2&showinfo=0&color=white&theme=light'; - return ''; - }; - - var youtube = YouTubeRenderer; - - function TwitterRenderer() {} - TwitterRenderer.prototype.render = function(model) { - return ''; - }; - - var twitter = TwitterRenderer; - - function InstagramRenderer() {} - InstagramRenderer.prototype.render = function(model) { - return ''; - }; - - var instagram = InstagramRenderer; - - function LinkImageRenderer() {} - LinkImageRenderer.prototype.render = function(model) { - return ''; - }; - - var link_image_renderer = LinkImageRenderer; - - var embedRenderers = { - YOUTUBE : new youtube(), - TWITTER : new twitter(), - INSTAGRAM : new instagram(), - LINK_IMAGE : new link_image_renderer() - }; - - function embedRenderer(model) { - var embedAttrs = model.attributes; - var embedType = embedAttrs.embed_type; - var isVideo = embedType === 'video'; - var providerName = embedAttrs.provider_name; - var customRendererId = providerName && providerName.toUpperCase(); - var customRenderer = embedRenderers[customRendererId]; - if (!customRenderer && embedType === 'link' && embedAttrs.thumbnail) { - customRenderer = embedRenderers.LINK_IMAGE; - } - var renderer = customRenderer ? customRenderer : this; - - return '
' + - '
' + - (isVideo ? '
' : '') + renderer.render(model) + (isVideo ? '
' : '') + - '
' + - '' + embedAttrs.title + '' + - '
' + - '
' + - '
'; - } - - function imageRenderer(model) { - return '
' + - '
' + this.render(model) + '
' + - '
'; - } - - var typeRenderers = {}; - typeRenderers[types_type.EMBED.id] = embedRenderer; - typeRenderers[types_type.IMAGE.id] = imageRenderer; - - /** - * @class EditorHTMLRenderer - * @constructor - * Subclass of HTMLRenderer specifically for the Editor - * Wraps interactive elements to add functionality - */ - function EditorHTMLRenderer(options) { - var rendererOptions = { - typeRenderers: typeRenderers - }; - merge(rendererOptions, options); - html_renderer.call(this, rendererOptions); - } - inherit(EditorHTMLRenderer, html_renderer); - - var editor_html_renderer = EditorHTMLRenderer; - - function renderClasses(view) { - var classNames = view.classNames; - if (classNames && classNames.length) { - view.element.className = classNames.join(' '); - } else if(view.element.className) { - view.element.removeAttribute('className'); - } - } - - function View(options) { - options = options || {}; - this.tagName = options.tagName || 'div'; - this.classNames = options.classNames || []; - this.element = document.createElement(this.tagName); - this.container = options.container || document.body; - this.isShowing = false; - renderClasses(this); - } - - View.prototype = { - show: function() { - var view = this; - if(!view.isShowing) { - view.container.appendChild(view.element); - view.isShowing = true; - return true; - } - }, - hide: function() { - var view = this; - if(view.isShowing) { - view.container.removeChild(view.element); - view.isShowing = false; - return true; - } - }, - addClass: function(className) { - var index = this.classNames && this.classNames.indexOf(className); - if (index === -1) { - this.classNames.push(className); - renderClasses(this); - } - }, - removeClass: function(className) { - var index = this.classNames && this.classNames.indexOf(className); - if (index > -1) { - this.classNames.splice(index, 1); - renderClasses(this); - } - }, - setClasses: function(classNameArr) { - this.classNames = classNameArr; - renderClasses(this); - } - }; - - var views_view = View; - - var buttonClassName = 'ck-toolbar-btn'; - - function ToolbarButton(options) { - var button = this; - var toolbar = options.toolbar; - var command = options.command; - var prompt = command.prompt; - var element = document.createElement('button'); - - button.element = element; - button.command = command; - button.isActive = false; - - element.title = command.name; - element.className = buttonClassName; - element.innerHTML = command.button; - element.addEventListener('mouseup', function(e) { - if (!button.isActive && prompt) { - toolbar.displayPrompt(prompt); - } else { - command.exec(); - toolbar.updateForSelection(); - } - e.stopPropagation(); - }); - } - - ToolbarButton.prototype = { - setActive: function() { - var button = this; - if (!button.isActive) { - button.element.className = buttonClassName + ' active'; - button.isActive = true; - } - }, - setInactive: function() { - var button = this; - if (button.isActive) { - button.element.className = buttonClassName; - button.isActive = false; - } - } - }; - - var toolbar_button = ToolbarButton; - - function createDiv(className) { - var div = document.createElement('div'); - if (className) { - div.className = className; - } - return div; - } - - function hideElement(element) { - element.style.display = 'none'; - } - - function showElement(element) { - element.style.display = 'block'; - } - - function swapElements(elementToShow, elementToHide) { - hideElement(elementToHide); - showElement(elementToShow); - } - - function getEventTargetMatchingTag(tag, target, container) { - // Traverses up DOM from an event target to find the node matching specifed tag - while (target && target !== container) { - if (target.tagName.toLowerCase() === tag) { - return target; - } - target = target.parentNode; - } - } - - function nodeIsDescendantOfElement(node, element) { - var parentNode = node.parentNode; - while(parentNode) { - if (parentNode === element) { - return true; - } - parentNode = parentNode.parentNode; - } - return false; - } - - function elementContentIsEmpty(element) { - var content = element && element.innerHTML; - if (content) { - return content === '' || content === '
'; - } - return false; - } - - function getElementRelativeOffset(element) { - var offset = { left: 0, top: -window.pageYOffset }; - var offsetParent = element.offsetParent; - var offsetParentPosition = window.getComputedStyle(offsetParent).position; - var offsetParentRect; - - if (offsetParentPosition === 'relative') { - offsetParentRect = offsetParent.getBoundingClientRect(); - offset.left = offsetParentRect.left; - offset.top = offsetParentRect.top; - } - return offset; - } - - function getElementComputedStyleNumericProp(element, prop) { - return parseFloat(window.getComputedStyle(element)[prop]); - } - - function positionElementToRect(element, rect, topOffset, leftOffset) { - var relativeOffset = getElementRelativeOffset(element); - var style = element.style; - var round = Math.round; - var left, top; - - topOffset = topOffset || 0; - leftOffset = leftOffset || 0; - left = round(rect.left - relativeOffset.left - leftOffset); - top = round(rect.top - relativeOffset.top - topOffset); - style.left = left + 'px'; - style.top = top + 'px'; - return { left: left, top: top }; - } - - function positionElementHorizontallyCenteredToRect(element, rect, topOffset) { - var horizontalCenter = (element.offsetWidth / 2) - (rect.width / 2); - return positionElementToRect(element, rect, topOffset, horizontalCenter); - } - - function positionElementCenteredAbove(element, aboveElement) { - var elementMargin = getElementComputedStyleNumericProp(element, 'marginBottom'); - return positionElementHorizontallyCenteredToRect(element, aboveElement.getBoundingClientRect(), element.offsetHeight + elementMargin); - } - - function positionElementCenteredBelow(element, belowElement) { - var elementMargin = getElementComputedStyleNumericProp(element, 'marginTop'); - return positionElementHorizontallyCenteredToRect(element, belowElement.getBoundingClientRect(), -element.offsetHeight - elementMargin); - } - - function positionElementCenteredIn(element, inElement) { - var verticalCenter = (inElement.offsetHeight / 2) - (element.offsetHeight / 2); - return positionElementHorizontallyCenteredToRect(element, inElement.getBoundingClientRect(), -verticalCenter); - } - - function positionElementToLeftOf(element, leftOfElement) { - var verticalCenter = (leftOfElement.offsetHeight / 2) - (element.offsetHeight / 2); - var elementMargin = getElementComputedStyleNumericProp(element, 'marginRight'); - return positionElementToRect(element, leftOfElement.getBoundingClientRect(), -verticalCenter, element.offsetWidth + elementMargin); - } - - function positionElementToRightOf(element, rightOfElement) { - var verticalCenter = (rightOfElement.offsetHeight / 2) - (element.offsetHeight / 2); - var elementMargin = getElementComputedStyleNumericProp(element, 'marginLeft'); - var rightOfElementRect = rightOfElement.getBoundingClientRect(); - return positionElementToRect(element, rightOfElementRect, -verticalCenter, -rightOfElement.offsetWidth - elementMargin); - } - - var RootTags = [ - types_type.PARAGRAPH.tag, - types_type.HEADING.tag, - types_type.SUBHEADING.tag, - types_type.QUOTE.tag, - types_type.LIST.tag, - types_type.ORDERED_LIST.tag - ]; - - var SelectionDirection = { - LEFT_TO_RIGHT : 1, - RIGHT_TO_LEFT : 2, - SAME_NODE : 3 - }; - - function getDirectionOfSelection(selection) { - var node = selection.anchorNode; - var position = node && node.compareDocumentPosition(selection.focusNode); - if (position & Node.DOCUMENT_POSITION_FOLLOWING) { - return SelectionDirection.LEFT_TO_RIGHT; - } else if (position & Node.DOCUMENT_POSITION_PRECEDING) { - return SelectionDirection.RIGHT_TO_LEFT; - } - return SelectionDirection.SAME_NODE; - } - - function getSelectionElement(selection) { - selection = selection || window.getSelection(); - var node = getDirectionOfSelection(selection) === SelectionDirection.LEFT_TO_RIGHT ? selection.anchorNode : selection.focusNode; - return node && (node.nodeType === 3 ? node.parentNode : node); - } - - function getSelectionBlockElement(selection) { - selection = selection || window.getSelection(); - var element = getSelectionElement(); - var tag = element && element.tagName.toLowerCase(); - while (tag && RootTags.indexOf(tag) === -1) { - if (element.contentEditable === 'true') { - return null; // Stop traversing up dom when hitting an editor element - } - element = element.parentNode; - tag = element.tagName && element.tagName.toLowerCase(); - } - return element; - } - - function getSelectionTagName() { - var element = getSelectionElement(); - return element ? element.tagName.toLowerCase() : null; - } - - function getSelectionBlockTagName() { - var element = getSelectionBlockElement(); - return element ? element.tagName && element.tagName.toLowerCase() : null; - } - - function tagsInSelection(selection) { - var element = getSelectionElement(selection); - var tags = []; - while(element) { - if (element.contentEditable === 'true') { break; } // Stop traversing up dom when hitting an editor element - if (element.tagName) { - tags.push(element.tagName.toLowerCase()); - } - element = element.parentNode; - } - return tags; - } - - function selectionIsInElement(selection, element) { - var node = selection.anchorNode; - return node && nodeIsDescendantOfElement(node, element); - } - - function selectionIsEditable(selection) { - var el = getSelectionBlockElement(selection); - return el && el.isContentEditable; - } - - function restoreRange(range) { - var selection = window.getSelection(); - selection.removeAllRanges(); - selection.addRange(range); - } - - function selectNode(node) { - var range = document.createRange(); - var selection = window.getSelection(); - range.setStart(node, 0); - range.setEnd(node, node.length); - selection.removeAllRanges(); - selection.addRange(range); - } - - function setCursorIndexInElement(element, index) { - var range = document.createRange(); - var selection = window.getSelection(); - range.setStart(element, index); - range.collapse(true); - selection.removeAllRanges(); - selection.addRange(range); - } - - function setCursorToStartOfElement(element) { - setCursorIndexInElement(element, 0); - } - - function getCursorOffsetInElement(element) { - // http://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container/4812022#4812022 - var caretOffset = 0; - var selection = window.getSelection(); - if (selection.rangeCount > 0) { - var range = selection.getRangeAt(0); - var preCaretRange = range.cloneRange(); - preCaretRange.selectNodeContents(element); - preCaretRange.setEnd(range.endContainer, range.endOffset); - caretOffset = preCaretRange.toString().length; - } - return caretOffset; - } - - var ToolbarDirection = { - TOP : 1, - RIGHT : 2 - }; - - function selectionContainsButtonsTag(selectedTags, buttonsTags) { - return selectedTags.filter(function(tag) { - return buttonsTags.indexOf(tag) > -1; - }).length; - } - - function updateButtonsForSelection(buttons, selection) { - var selectedTags = tagsInSelection(selection); - var len = buttons.length; - var i, button; - - for (i = 0; i < len; i++) { - button = buttons[i]; - if (selectionContainsButtonsTag(selectedTags, button.command.mappedTags)) { - button.setActive(); - } else { - button.setInactive(); - } - } - } - - function Toolbar(options) { - options = options || {}; - var toolbar = this; - var commands = options.commands; - var commandCount = commands && commands.length, i; - options.classNames = ['ck-toolbar']; - views_view.call(toolbar, options); - - toolbar.setSticky(options.sticky || false); - toolbar.setDirection(options.direction || ToolbarDirection.TOP); - toolbar.editor = options.editor || null; - toolbar.embedIntent = options.embedIntent || null; - toolbar.activePrompt = null; - toolbar.buttons = []; - - toolbar.contentElement = createDiv('ck-toolbar-content'); - toolbar.promptContainerElement = createDiv('ck-toolbar-prompt'); - toolbar.buttonContainerElement = createDiv('ck-toolbar-buttons'); - toolbar.contentElement.appendChild(toolbar.promptContainerElement); - toolbar.contentElement.appendChild(toolbar.buttonContainerElement); - toolbar.element.appendChild(toolbar.contentElement); - - for(i = 0; i < commandCount; i++) { - this.addCommand(commands[i]); - } - - // Closes prompt if displayed when changing selection - document.addEventListener('mouseup', function() { - toolbar.dismissPrompt(); - }); - } - inherit(Toolbar, views_view); - - Toolbar.prototype.hide = function() { - if (Toolbar._super.prototype.hide.call(this)) { - var style = this.element.style; - style.left = ''; - style.top = ''; - this.dismissPrompt(); - } - }; - - Toolbar.prototype.addCommand = function(command) { - command.editorContext = this.editor; - command.embedIntent = this.embedIntent; - var button = new toolbar_button({ command: command, toolbar: this }); - this.buttons.push(button); - this.buttonContainerElement.appendChild(button.element); - }; - - Toolbar.prototype.displayPrompt = function(prompt) { - var toolbar = this; - swapElements(toolbar.promptContainerElement, toolbar.buttonContainerElement); - toolbar.promptContainerElement.appendChild(prompt.element); - prompt.show(function() { - toolbar.dismissPrompt(); - toolbar.updateForSelection(); - }); - toolbar.activePrompt = prompt; - }; - - Toolbar.prototype.dismissPrompt = function() { - var toolbar = this; - var activePrompt = toolbar.activePrompt; - if (activePrompt) { - activePrompt.hide(); - swapElements(toolbar.buttonContainerElement, toolbar.promptContainerElement); - toolbar.activePrompt = null; - } - }; - - Toolbar.prototype.updateForSelection = function(selection) { - var toolbar = this; - selection = selection || window.getSelection(); - if (toolbar.sticky) { - updateButtonsForSelection(toolbar.buttons, selection); - } else if (!selection.isCollapsed) { - toolbar.positionToContent(selection.getRangeAt(0)); - updateButtonsForSelection(toolbar.buttons, selection); - } - }; - - Toolbar.prototype.positionToContent = function(content) { - var directions = ToolbarDirection; - var positioningMethod, position, sideEdgeOffset; - switch(this.direction) { - case directions.RIGHT: - positioningMethod = positionElementToRightOf; - break; - default: - positioningMethod = positionElementCenteredAbove; - } - position = positioningMethod(this.element, content); - sideEdgeOffset = Math.min(Math.max(10, position.left), document.body.clientWidth - this.element.offsetWidth - 10); - this.contentElement.style.transform = 'translateX(' + (sideEdgeOffset - position.left) + 'px)'; - }; - - Toolbar.prototype.setDirection = function(direction) { - this.direction = direction; - if (direction === ToolbarDirection.RIGHT) { - this.addClass('right'); - } else { - this.removeClass('right'); - } - }; - - Toolbar.prototype.setSticky = function(sticky) { - this.sticky = sticky; - if (sticky) { - this.addClass('sticky'); - this.element.removeAttribute('style'); // clears any prior positioning - this.show(); - } else { - this.removeClass('sticky'); - this.hide(); - } - }; - - Toolbar.prototype.toggleSticky = function() { - this.setSticky(!this.sticky); - }; - - Toolbar.Direction = ToolbarDirection; - - var views_toolbar = Toolbar; - - var Keycodes = { - BKSP : 8, - ENTER : 13, - ESC : 27, - DEL : 46, - M : 77 - }; - - function selectionIsEditableByToolbar(selection, toolbar) { - return selectionIsEditable(selection) && selectionIsInElement(selection, toolbar.rootElement); - } - - function handleTextSelection(toolbar) { - var selection = window.getSelection(); - if (toolbar.sticky) { - toolbar.updateForSelection(selectionIsEditableByToolbar(selection, toolbar) ? selection : null); - } else { - if (selection.isCollapsed || selection.toString().trim() === '' || !selectionIsEditableByToolbar(selection, toolbar)) { - toolbar.hide(); - } else { - toolbar.show(); - toolbar.updateForSelection(selection); - } - } - } - - function TextFormatToolbar(options) { - var toolbar = this; - views_toolbar.call(this, options); - toolbar.rootElement = options.rootElement; - toolbar.rootElement.addEventListener('keyup', function() { handleTextSelection(toolbar); }); - - document.addEventListener('mouseup', function() { - setTimeout(function() { - handleTextSelection(toolbar); - }); - }); - - document.addEventListener('keyup', function(e) { - var key = e.keyCode; - if (key === 116) { //F5 - toolbar.toggleSticky(); - handleTextSelection(toolbar); - } else if (!toolbar.sticky && key === Keycodes.ESC) { - toolbar.hide(); - } - }); - - window.addEventListener('resize', function() { - if(!toolbar.sticky && toolbar.isShowing) { - var activePromptRange = toolbar.activePrompt && toolbar.activePrompt.range; - toolbar.positionToContent(activePromptRange ? activePromptRange : window.getSelection().getRangeAt(0)); - } - }); - } - inherit(TextFormatToolbar, views_toolbar); - - var text_format_toolbar = TextFormatToolbar; - - function Tooltip(options) { - var tooltip = this; - var rootElement = options.rootElement; - var delay = options.delay || 200; - var timeout; - options.classNames = ['ck-tooltip']; - views_view.call(tooltip, options); - - rootElement.addEventListener('mouseover', function(e) { - var target = getEventTargetMatchingTag(options.showForTag, e.target, rootElement); - if (target && target.isContentEditable) { - timeout = setTimeout(function() { - tooltip.showLink(target.href, target); - }, delay); - } - }); - - rootElement.addEventListener('mouseout', function(e) { - clearTimeout(timeout); - var toElement = e.toElement || e.relatedTarget; - if (toElement && toElement.className !== tooltip.element.className) { - tooltip.hide(); - } - }); - } - inherit(Tooltip, views_view); - - Tooltip.prototype.showMessage = function(message, element) { - var tooltip = this; - var tooltipElement = tooltip.element; - tooltipElement.innerHTML = message; - tooltip.show(); - positionElementCenteredBelow(tooltipElement, element); - }; - - Tooltip.prototype.showLink = function(link, element) { - var message = '' + link + ''; - this.showMessage(message, element); - }; - - var views_tooltip = Tooltip; - - var LayoutStyle = { - GUTTER : 1, - CENTERED : 2 - }; - - function computeLayoutStyle(rootElement) { - if (rootElement.getBoundingClientRect().left > 100) { - return LayoutStyle.GUTTER; - } - return LayoutStyle.CENTERED; - } - - function EmbedIntent(options) { - var embedIntent = this; - var rootElement = embedIntent.rootElement = options.rootElement; - options.classNames = ['ck-embed-intent']; - views_view.call(embedIntent, options); - - embedIntent.isActive = false; - embedIntent.editorContext = options.editorContext; - embedIntent.loadingIndicator = createDiv('ck-embed-loading'); - embedIntent.button = document.createElement('button'); - embedIntent.button.className = 'ck-embed-intent-btn'; - embedIntent.button.title = 'Insert image or embed...'; - embedIntent.element.appendChild(embedIntent.button); - embedIntent.button.addEventListener('mouseup', function(e) { - if (embedIntent.isActive) { - embedIntent.deactivate(); - } else { - embedIntent.activate(); - } - e.stopPropagation(); - }); - - embedIntent.toolbar = new views_toolbar({ - container: embedIntent.element, - embedIntent: embedIntent, - editor: embedIntent.editorContext, - commands: options.commands, - direction: views_toolbar.Direction.RIGHT - }); - - function embedIntentHandler() { - var blockElement = getSelectionBlockElement(); - if (blockElement && elementContentIsEmpty(blockElement)) { - embedIntent.showAt(blockElement); - } else { - embedIntent.hide(); - } - } - - rootElement.addEventListener('keyup', embedIntentHandler); - document.addEventListener('mouseup', function() { - setTimeout(function() { embedIntentHandler(); }); - }); - - document.addEventListener('keyup', function(e) { - if (e.keyCode === Keycodes.ESC) { - embedIntent.hide(); - } - }); - - window.addEventListener('resize', function() { - if(embedIntent.isShowing) { - embedIntent.reposition(); - } - }); - } - inherit(EmbedIntent, views_view); - - EmbedIntent.prototype.hide = function() { - if (EmbedIntent._super.prototype.hide.call(this)) { - this.deactivate(); - } - }; - - EmbedIntent.prototype.showAt = function(node) { - this.atNode = node; - this.show(); - this.deactivate(); - this.reposition(); - }; - - EmbedIntent.prototype.reposition = function() { - if (computeLayoutStyle(this.rootElement) === LayoutStyle.GUTTER) { - positionElementToLeftOf(this.element, this.atNode); - } else { - positionElementCenteredIn(this.element, this.atNode); - } - }; - - EmbedIntent.prototype.activate = function() { - if (!this.isActive) { - this.addClass('activated'); - this.toolbar.show(); - this.isActive = true; - } - }; - - EmbedIntent.prototype.deactivate = function() { - if (this.isActive) { - this.removeClass('activated'); - this.toolbar.hide(); - this.isActive = false; - } - }; - - EmbedIntent.prototype.showLoading = function() { - var embedIntent = this; - var loadingIndicator = embedIntent.loadingIndicator; - embedIntent.hide(); - embedIntent.atNode.appendChild(loadingIndicator); - }; - - EmbedIntent.prototype.hideLoading = function() { - this.atNode.removeChild(this.loadingIndicator); - }; - - var embed_intent = EmbedIntent; - - function Command(options) { - options = options || {}; - var command = this; - var name = options.name; - var prompt = options.prompt; - command.name = name; - command.button = options.button || name; - if (prompt) { command.prompt = prompt; } - } - - Command.prototype.exec = function() {}; - - var base = Command; - - function TextFormatCommand(options) { - options = options || {}; - base.call(this, options); - this.tag = options.tag; - this.mappedTags = options.mappedTags || []; - this.mappedTags.push(this.tag); - this.action = options.action || this.name; - this.removeAction = options.removeAction || this.action; - } - inherit(TextFormatCommand, base); - - TextFormatCommand.prototype = { - exec: function(value) { - document.execCommand(this.action, false, value || null); - }, - unexec: function(value) { - document.execCommand(this.removeAction, false, value || null); - } - }; - - var text_format = TextFormatCommand; - - var RegExpHeadingTag = /^(h1|h2|h3|h4|h5|h6)$/i; - - function BoldCommand() { - text_format.call(this, { - name: 'bold', - tag: types_type.BOLD.tag, - mappedTags: types_type.BOLD.mappedTags, - button: '' - }); - } - inherit(BoldCommand, text_format); - - BoldCommand.prototype.exec = function() { - // Don't allow executing bold command on heading tags - if (!RegExpHeadingTag.test(getSelectionBlockTagName())) { - BoldCommand._super.prototype.exec.call(this); - } - }; - - var bold = BoldCommand; - - function ItalicCommand() { - text_format.call(this, { - name: 'italic', - tag: types_type.ITALIC.tag, - mappedTags: types_type.ITALIC.mappedTags, - button: '' - }); - } - inherit(ItalicCommand, text_format); - - var italic = ItalicCommand; - - var container = document.body; - var hiliter = createDiv('ck-editor-hilite'); - - function positionHiliteRange(range) { - var rect = range.getBoundingClientRect(); - var style = hiliter.style; - style.width = rect.width + 'px'; - style.height = rect.height + 'px'; - positionElementToRect(hiliter, rect); - } - - function Prompt(options) { - var prompt = this; - options.tagName = 'input'; - views_view.call(prompt, options); - - prompt.command = options.command; - prompt.element.placeholder = options.placeholder || ''; - prompt.element.addEventListener('mouseup', function(e) { e.stopPropagation(); }); // prevents closing prompt when clicking input - prompt.element.addEventListener('keyup', function(e) { - var entry = this.value; - if(entry && prompt.range && !e.shiftKey && e.which === Keycodes.ENTER) { - restoreRange(prompt.range); - prompt.command.exec(entry); - if (prompt.onComplete) { prompt.onComplete(); } - } - }); - - window.addEventListener('resize', function() { - var activeHilite = hiliter.parentNode; - var range = prompt.range; - if(activeHilite && range) { - positionHiliteRange(range); - } - }); - } - inherit(Prompt, views_view); - - Prompt.prototype.show = function(callback) { - var prompt = this; - var element = prompt.element; - var selection = window.getSelection(); - var range = selection && selection.rangeCount && selection.getRangeAt(0); - element.value = null; - prompt.range = range || null; - if (range) { - container.appendChild(hiliter); - positionHiliteRange(prompt.range); - setTimeout(function(){ element.focus(); }); // defer focus (disrupts mouseup events) - if (callback) { prompt.onComplete = callback; } - } - }; - - Prompt.prototype.hide = function() { - if (hiliter.parentNode) { - container.removeChild(hiliter); - } - }; - - var views_prompt = Prompt; - - var RegExpHttp = /^https?:\/\//i; - - function LinkCommand() { - text_format.call(this, { - name: 'link', - tag: types_type.LINK.tag, - action: 'createLink', - removeAction: 'unlink', - button: '', - prompt: new views_prompt({ - command: this, - placeholder: 'Enter a url, press return...' - }) - }); - } - inherit(LinkCommand, text_format); - - LinkCommand.prototype.exec = function(url) { - if (!url) { - return LinkCommand._super.prototype.unexec.call(this); - } - - if(this.tag === getSelectionTagName()) { - this.unexec(); - } else { - if (!RegExpHttp.test(url)) { - url = 'http://' + url; - } - LinkCommand._super.prototype.exec.call(this, url); - } - }; - - var commands_link = LinkCommand; - - function FormatBlockCommand(options) { - options = options || {}; - options.action = 'formatBlock'; - text_format.call(this, options); - } - inherit(FormatBlockCommand, text_format); - - FormatBlockCommand.prototype.exec = function() { - var tag = this.tag; - // Brackets neccessary for certain browsers - var value = '<' + tag + '>'; - var blockElement = getSelectionBlockElement(); - // Allow block commands to be toggled back to a text block - if(tag === blockElement.tagName.toLowerCase()) { - value = types_type.PARAGRAPH.tag; - } else { - // Flattens the selection before applying the block format. - // Otherwise, undesirable nested blocks can occur. - // TODO: would love to be able to remove this - var flatNode = document.createTextNode(blockElement.textContent); - blockElement.parentNode.insertBefore(flatNode, blockElement); - blockElement.parentNode.removeChild(blockElement); - selectNode(flatNode); - } - - FormatBlockCommand._super.prototype.exec.call(this, value); - }; - - var format_block = FormatBlockCommand; - - function QuoteCommand() { - format_block.call(this, { - name: 'quote', - tag: types_type.QUOTE.tag, - button: '' - }); - } - inherit(QuoteCommand, format_block); - - var quote = QuoteCommand; - - function HeadingCommand() { - format_block.call(this, { - name: 'heading', - tag: types_type.HEADING.tag, - button: '1' - }); - } - inherit(HeadingCommand, format_block); - - var heading = HeadingCommand; - - function SubheadingCommand() { - format_block.call(this, { - name: 'subheading', - tag: types_type.SUBHEADING.tag, - button: '2' - }); - } - inherit(SubheadingCommand, format_block); - - var subheading = SubheadingCommand; - - function ListCommand(options) { - text_format.call(this, options); - } - inherit(ListCommand, text_format); - - ListCommand.prototype.exec = function() { - ListCommand._super.prototype.exec.call(this); - - // After creation, lists need to be unwrapped - // TODO: eventually can remove this when direct model manipulation is ready - var listElement = getSelectionBlockElement(); - var wrapperNode = listElement.parentNode; - if (wrapperNode.firstChild === listElement) { - var editorNode = wrapperNode.parentNode; - editorNode.insertBefore(listElement, wrapperNode); - editorNode.removeChild(wrapperNode); - selectNode(listElement); - } - }; - - ListCommand.prototype.checkAutoFormat = function(node) { - // Creates unordered lists when node starts with '- ' - // or ordered list if node starts with '1. ' - var regex = this.autoFormatRegex, text; - if (node && regex) { - text = node.textContent; - if (types_type.LIST_ITEM.tag !== getSelectionTagName() && regex.test(text)) { - this.exec(); - window.getSelection().anchorNode.textContent = text.replace(regex, ''); - return true; - } - } - return false; - }; - - var list = ListCommand; - - function UnorderedListCommand() { - list.call(this, { - name: 'list', - tag: types_type.LIST.tag, - action: 'insertUnorderedList' - }); - } - inherit(UnorderedListCommand, list); - - UnorderedListCommand.prototype.autoFormatRegex = /^[-*]\s/; - - var unordered_list = UnorderedListCommand; - - function OrderedListCommand() { - list.call(this, { - name: 'ordered list', - tag: types_type.ORDERED_LIST.tag, - action: 'insertOrderedList' - }); - } - inherit(OrderedListCommand, list); - - OrderedListCommand.prototype.autoFormatRegex = /^1\.\s/; - - var ordered_list = OrderedListCommand; - - var defaultClassNames = ['ck-message']; - - function Message(options) { - options = options || {}; - options.classNames = defaultClassNames; - views_view.call(this, options); - } - inherit(Message, views_view); - - function show(view, message) { - view.element.innerHTML = message; - Message._super.prototype.show.call(view); - setTimeout(function() { - view.hide(); - }, 3200); - } - - Message.prototype.showInfo = function(message) { - this.setClasses(defaultClassNames); - show(this, message); - }; - - Message.prototype.showError = function(message) { - this.addClass('ck-message-error'); - show(this, message); - }; - - var views_message = Message; - - function createXHR(options) { - var xhr = new XMLHttpRequest(); - xhr.open(options.method, options.url); - xhr.onload = function () { - var response = xhr.responseText; - if (xhr.status === 200) { - return options.success.call(this, response); - } - options.error.call(this, response); - }; - xhr.onerror = function (error) { - options.error.call(this, error); - }; - return xhr; - } - - function xhrGet(options) { - options.method = 'GET'; - var xhr = createXHR(options); - try { - xhr.send(); - } catch(error) {} - } - - function xhrPost(options) { - options.method = 'POST'; - var xhr = createXHR(options); - var formData = new FormData(); - formData.append('file', options.data); - try { - xhr.send(formData); - } catch(error) {} - } - - function responseJSON(jsonString) { - if (!jsonString) { return null; } - try { - return JSON.parse(jsonString); - } catch(e) { - return jsonString; - } - } - - // -------------------------------------------- - - function FileUploader(options) { - options = options || {}; - var url = options.url; - var maxFileSize = options.maxFileSize; - if (url) { - this.url = url; - } else { - throw new Error('FileUploader: setting the `url` to an upload service is required'); - } - if (maxFileSize) { - this.maxFileSize = maxFileSize; - } - } - - FileUploader.prototype.upload = function(options) { - if (!options) { return; } - - var fileInput = options.fileInput; - var file = options.file || (fileInput && fileInput.files && fileInput.files[0]); - var callback = options.complete; - var maxFileSize = this.maxFileSize; - if (!file || !(file instanceof window.File)) { return; } - - if (maxFileSize && file.size > maxFileSize) { - if (callback) { callback.call(this, null, { message: 'max file size is ' + maxFileSize + ' bytes' }); } - return; - } - - xhrPost({ - url: this.url, - data: file, - success: function(response) { - if (callback) { callback.call(this, responseJSON(response)); } - }, - error: function(error) { - if (callback) { callback.call(this, null, responseJSON(error)); } - } - }); - }; - - function OEmbedder(options) { - options = options || {}; - var url = options.url; - if (url) { - this.url = url; - } else { - throw new Error('OEmbedder: setting the `url` to an embed service is required'); - } - } - - OEmbedder.prototype.fetch = function(options) { - var callback = options.complete; - xhrGet({ - url: this.url + "?url=" + encodeURI(options.url), - success: function(response) { - if (callback) { callback.call(this, responseJSON(response)); } - }, - error: function(error) { - if (callback) { callback.call(this, null, responseJSON(error)); } - } - }); - }; - - function createFileInput(command) { - var fileInput = document.createElement('input'); - fileInput.type = 'file'; - fileInput.accept = 'image/*'; - fileInput.className = 'ck-file-input'; - fileInput.addEventListener('change', function(e) { - command.handleFile(e); - }); - return fileInput; - } - - function injectImageBlock(src, editor, index) { - var imageModel = models_block.createWithType(types_type.IMAGE, { attributes: { src: src } }); - editor.replaceBlock(imageModel, index); - } - - function renderFromFile(file, editor, index) { - if (file && window.FileReader) { - var reader = new FileReader(); - reader.onload = function(e) { - var base64Src = e.target.result; - injectImageBlock(base64Src, editor, index); - editor.renderBlockAt(index, true); - }; - reader.readAsDataURL(file); - } - } - - function ImageCommand(options) { - base.call(this, { - name: 'image', - button: '' - }); - this.uploader = new FileUploader({ url: options.serviceUrl, maxFileSize: 5000000 }); - } - inherit(ImageCommand, base); - - ImageCommand.prototype = { - exec: function() { - ImageCommand._super.prototype.exec.call(this); - var fileInput = this.fileInput; - if (!fileInput) { - fileInput = this.fileInput = createFileInput(this); - document.body.appendChild(fileInput); - } - fileInput.dispatchEvent(new MouseEvent('click', { bubbles: false })); - }, - handleFile: function(e) { - var fileInput = e.target; - var file = fileInput.files && fileInput.files[0]; - var editor = this.editorContext; - var embedIntent = this.embedIntent; - var currentEditingIndex = editor.getCurrentBlockIndex(); - - embedIntent.showLoading(); - renderFromFile(file, editor, currentEditingIndex); // render image immediately client-side - this.uploader.upload({ - fileInput: fileInput, - complete: function(response, error) { - embedIntent.hideLoading(); - if (error || !response || !response.url) { - setTimeout(function() { - editor.removeBlockAt(currentEditingIndex); - editor.syncVisual(); - }, 1000); - return new views_message().showError(error.message || 'Error uploading image'); - } - injectImageBlock(response.url, editor, currentEditingIndex); - } - }); - fileInput.value = null; // reset file input - } - }; - - var image = ImageCommand; - - function loadTwitterWidgets(element) { - if (window.twttr) { - window.twttr.widgets.load(element); - } else { - var script = document.createElement('script'); - script.async = true; - script.src = 'http://platform.twitter.com/widgets.js'; - document.head.appendChild(script); - } - } - - function OEmbedCommand(options) { - base.call(this, { - name: 'embed', - button: '', - prompt: new views_prompt({ - command: this, - placeholder: 'Paste a YouTube or Twitter url...' - }) - }); - - this.embedService = new OEmbedder({ url: options.serviceUrl }); - } - inherit(OEmbedCommand, base); - - OEmbedCommand.prototype.exec = function(url) { - var command = this; - var editorContext = command.editorContext; - var embedIntent = command.embedIntent; - var index = editorContext.getCurrentBlockIndex(); - - embedIntent.showLoading(); - this.embedService.fetch({ - url: url, - complete: function(response, error) { - embedIntent.hideLoading(); - if (error) { - var errorMsg = error; - if (error.target && error.target.status === 0) { - errorMsg = 'Error: could not connect to embed service.'; - } else if (typeof error !== 'string') { - errorMsg = 'Error: unexpected embed error.'; - } - new views_message().showError(errorMsg); - embedIntent.show(); - } else if (response.error_message) { - new views_message().showError(response.error_message); - embedIntent.show(); - } else { - var embedModel = new embed(response); - editorContext.insertBlock(embedModel, index); - editorContext.renderBlockAt(index); - if (embedModel.attributes.provider_name.toLowerCase() === 'twitter') { - loadTwitterWidgets(editorContext.element); - } - } - } - }); - }; - - var oembed = OEmbedCommand; - - function injectCardBlock(cardName, cardPayload, editor, index) { - // FIXME: Do we change the block model internal representation here? - var cardBlock = models_block.createWithType(types_type.CARD, { - attributes: { - name: cardName, - payload: cardPayload - } - }); - editor.replaceBlock(cardBlock, index); - } - - function CardCommand() { - base.call(this, { - name: 'card', - button: 'CA' - }); - } - inherit(CardCommand, base); - - CardCommand.prototype = { - exec: function() { - CardCommand._super.prototype.exec.call(this); - var editor = this.editorContext; - var currentEditingIndex = editor.getCurrentBlockIndex(); - - var cardName = 'pick-color'; - var cardPayload = { options: ['red', 'blue'] }; - injectCardBlock(cardName, cardPayload, editor, currentEditingIndex); - editor.renderBlockAt(currentEditingIndex, true); - } - }; - - var card = CardCommand; - - // Based on https://github.com/jeromeetienne/microevent.js/blob/master/microevent.js - // See also: https://github.com/allouis/minivents/blob/master/minivents.js - - var EventEmitter = { - on : function(type, handler){ - var events = this.__events = this.__events || {}; - events[type] = events[type] || []; - events[type].push(handler); - }, - off : function(type, handler){ - var events = this.__events = this.__events || {}; - if (type in events) { - events[type].splice(events[type].indexOf(handler), 1); - } - }, - trigger : function(type) { - var events = this.__events = this.__events || {}; - var eventForTypeCount, i; - if (type in events) { - eventForTypeCount = events[type].length; - for(i = 0; i < eventForTypeCount; i++) { - events[type][i].apply(this, Array.prototype.slice.call(arguments, 1)); - } - } - } - }; - - var event_emitter = EventEmitter; - - var defaults = { - placeholder: 'Write here...', - spellcheck: true, - autofocus: true, - model: null, - serverHost: '', - stickyToolbar: !!('ontouchstart' in window), - textFormatCommands: [ - new bold(), - new italic(), - new commands_link(), - new quote(), - new heading(), - new subheading() - ], - embedCommands: [ - new image({ serviceUrl: '/upload' }), - new oembed({ serviceUrl: '/embed' }), - new card() - ], - autoTypingCommands: [ - new unordered_list(), - new ordered_list() - ], - compiler: null, - cards: {} - }; - - function bindContentEditableTypingListeners(editor) { - - - editor.element.addEventListener('keyup', function(e) { - // Assure there is always a supported block tag, and not empty text nodes or divs. - // On a carrage return, make sure to always generate a 'p' tag - if (!getSelectionBlockElement() || - !editor.element.textContent || - (!e.shiftKey && e.which === Keycodes.ENTER) || (e.ctrlKey && e.which === Keycodes.M)) { - document.execCommand('formatBlock', false, types_type.PARAGRAPH.tag); - } //else if (e.which === Keycodes.BKSP) { - // TODO: Need to rerender when backspacing 2 blocks together - //var cursorIndex = editor.getCursorIndexInCurrentBlock(); - //var currentBlockElement = getSelectionBlockElement(); - //editor.renderBlockAt(editor.getCurrentBlockIndex(), true); - //setCursorIndexInElement(currentBlockElement, cursorIndex); - //} - }); - - // On 'PASTE' sanitize and insert - editor.element.addEventListener('paste', function(e) { - var data = e.clipboardData; - var pastedHTML = data && data.getData && data.getData('text/html'); - var sanitizedHTML = pastedHTML && editor.compiler.rerender(pastedHTML); - if (sanitizedHTML) { - document.execCommand('insertHTML', false, sanitizedHTML); - editor.syncVisual(); - } - e.preventDefault(); - return false; - }); - } - - function bindLiveUpdate(editor) { - editor.element.addEventListener('input', function() { - editor.syncContentEditableBlocks(); - }); - } - - function bindAutoTypingListeners(editor) { - // Watch typing patterns for auto format commands (e.g. lists '- ', '1. ') - editor.element.addEventListener('keyup', function(e) { - var commands = editor.autoTypingCommands; - var count = commands && commands.length; - var selection, i; - - if (count) { - selection = window.getSelection(); - for (i = 0; i < count; i++) { - if (commands[i].checkAutoFormat(selection.anchorNode)) { - e.stopPropagation(); - return; - } - } - } - }); - } - - function bindDragAndDrop() { - // TODO. For now, just prevent redirect when dropping something on the page - window.addEventListener('dragover', function(e) { - e.preventDefault(); // prevents showing cursor where to drop - }); - window.addEventListener('drop', function(e) { - e.preventDefault(); // prevent page from redirecting - }); - } - - function initEmbedCommands(editor) { - var commands = editor.embedCommands; - if(commands) { - return new embed_intent({ - editorContext: editor, - commands: commands, - rootElement: editor.element - }); - } - } - - function applyClassName(editorElement) { - var editorClassName = 'ck-editor'; - var editorClassNameRegExp = new RegExp(editorClassName); - var existingClassName = editorElement.className; - - if (!editorClassNameRegExp.test(existingClassName)) { - existingClassName += (existingClassName ? ' ' : '') + editorClassName; - } - editorElement.className = existingClassName; - } - - function applyPlaceholder(editorElement, placeholder) { - var dataset = editorElement.dataset; - if (placeholder && !dataset.placeholder) { - dataset.placeholder = placeholder; - } - } - - function getNonTextBlocks(blockTypeSet, model) { - var blocks = []; - var len = model.length; - var i, block, type; - for (i = 0; i < len; i++) { - block = model[i]; - type = blockTypeSet.findById(block && block.type); - if (type && !type.isTextType) { - blocks.push(block); - } - } - return blocks; - } - - /** - * @class Editor - * An individual Editor - * @param element `Element` node - * @param options hash of options - */ - function Editor(element, options) { - var editor = this; - mergeWithOptions(editor, defaults, options); - if (!editor.compiler) { - editor.compiler = new compiler({ - includeTypeNames: true, // outputs models with type names, i.e. 'BOLD', for easier debugging - renderer: new editor_html_renderer({ - cards: editor.cards - }) // subclassed HTML renderer that adds dom structure for additional editor interactivity - }); - } - - if (element) { - applyClassName(element); - applyPlaceholder(element, editor.placeholder); - element.spellcheck = editor.spellcheck; - element.setAttribute('contentEditable', true); - editor.element = element; - - if (editor.model) { - editor.loadModel(editor.model); - } else { - editor.sync(); - } - - bindContentEditableTypingListeners(editor); - bindAutoTypingListeners(editor); - bindDragAndDrop(editor); - bindLiveUpdate(editor); - initEmbedCommands(editor); - - editor.textFormatToolbar = new text_format_toolbar({ rootElement: element, commands: editor.textFormatCommands, sticky: editor.stickyToolbar }); - editor.linkTooltips = new views_tooltip({ rootElement: element, showForTag: types_type.LINK.tag }); - - if(editor.autofocus) { element.focus(); } - } - } - - // Add event emitter pub/sub functionality - merge(Editor.prototype, event_emitter); - - Editor.prototype.loadModel = function(model) { - this.model = model; - this.syncVisual(); - this.trigger('update'); - }; - - Editor.prototype.syncModel = function() { - this.model = this.compiler.parse(this.element.innerHTML); - this.trigger('update'); - }; - - Editor.prototype.syncVisual = function() { - this.element.innerHTML = this.compiler.render(this.model); - }; - - Editor.prototype.sync = function() { - this.syncModel(); - this.syncVisual(); - }; - - Editor.prototype.getCurrentBlockIndex = function(element) { - var selectionEl = element || getSelectionBlockElement(); - var blockElements = toArray(this.element.children); - return blockElements.indexOf(selectionEl); - }; - - Editor.prototype.getCursorIndexInCurrentBlock = function() { - var currentBlock = getSelectionBlockElement(); - if (currentBlock) { - return getCursorOffsetInElement(currentBlock); - } - return -1; - }; - - Editor.prototype.insertBlock = function(block, index) { - this.model.splice(index, 0, block); - this.trigger('update'); - }; - - Editor.prototype.removeBlockAt = function(index) { - this.model.splice(index, 1); - this.trigger('update'); - }; - - Editor.prototype.replaceBlock = function(block, index) { - this.model[index] = block; - this.trigger('update'); - }; - - Editor.prototype.renderBlockAt = function(index, replace) { - var modelAtIndex = this.model[index]; - var html = this.compiler.render([modelAtIndex]); - var dom = document.createElement('div'); - dom.innerHTML = html; - var newEl = dom.firstChild; - newEl.dataset.modelIndex = index; - var sibling = this.element.children[index]; - if (replace) { - this.element.replaceChild(newEl, sibling); - } else { - this.element.insertBefore(newEl, sibling); - } - }; - - Editor.prototype.syncContentEditableBlocks = function() { - var nonTextBlocks = getNonTextBlocks(this.compiler.blockTypes, this.model); - var blockElements = toArray(this.element.children); - var len = blockElements.length; - var updatedModel = []; - var i, block, blockEl; - for (i = 0; i < len; i++) { - blockEl = blockElements[i]; - if(blockEl.isContentEditable) { - updatedModel.push(this.compiler.parser.serializeBlockNode(blockEl)); - } else { - if (blockEl.dataset.modelIndex) { - block = this.model[blockEl.dataset.modelIndex]; - updatedModel.push(block); - } else { - updatedModel.push(nonTextBlocks.shift()); - } - } - } - this.model = updatedModel; - this.trigger('update'); - }; - - - var editor_editor = Editor; - - function EditorFactory(element, options) { - var editors = []; - var elements, elementsLen, i; - - if (!element) { - return new editor_editor(element, options); - } - - if (typeof element === 'string') { - elements = document.querySelectorAll(element); - } else if (element && element.length) { - elements = element; - } else if (element) { - elements = [element]; - } - - if (elements) { - elementsLen = elements.length; - for (i = 0; i < elementsLen; i++) { - editors.push(new editor_editor(elements[i], options)); - } - } - - return editors.length > 1 ? editors : editors[0]; - } - - EditorFactory.prototype = editor_editor.prototype; - - var editor_factory = EditorFactory; - - var ContentKit = {}; - ContentKit.Type = types_type; - ContentKit.BlockModel = models_block; - ContentKit.EmbedModel = embed; - ContentKit.Compiler = compiler; - ContentKit.HTMLParser = html_parser; - ContentKit.HTMLRenderer = html_renderer; - ContentKit.Editor = editor_factory; - - window.ContentKit = ContentKit; -}(this, document)); diff --git a/package.json b/package.json index 876066e13..608fef4b3 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,9 @@ }, "scripts": { "start": "node server/index.js", - "test": "gulp test" + "test": "gulp test", + "build": "rm -rf dist && broccoli build dist", + "prepublish": "npm run build" }, "keywords": [ "html", @@ -27,6 +29,9 @@ "express": "^4.11.1" }, "devDependencies": { + "broccoli": "^0.16.3", + "broccoli-merge-trees": "^0.2.1", + "broccoli-multi-builder": "^0.1.0", "content-kit-compiler": "0.2.3", "content-kit-utils": "0.1.2", "del": "^1.1.1", diff --git a/src/js/commands/bold.js b/src/js/commands/bold.js index 6f74bc0f9..50e25939a 100644 --- a/src/js/commands/bold.js +++ b/src/js/commands/bold.js @@ -1,7 +1,7 @@ import TextFormatCommand from './text-format'; import { getSelectionBlockTagName } from '../utils/selection-utils'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; -import Type from 'node_modules/content-kit-compiler/src/types/type'; +import { inherit } from 'content-kit-utils'; +import { Type } from 'content-kit-compiler'; var RegExpHeadingTag = /^(h1|h2|h3|h4|h5|h6)$/i; diff --git a/src/js/commands/card.js b/src/js/commands/card.js index 1a94b9f9c..f5f0455cf 100644 --- a/src/js/commands/card.js +++ b/src/js/commands/card.js @@ -1,7 +1,9 @@ import Command from './base'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; -import BlockModel from 'node_modules/content-kit-compiler/src/models/block'; -import Type from 'node_modules/content-kit-compiler/src/types/type'; +import { inherit } from 'content-kit-utils'; +import { + BlockModel, + Type +} from 'content-kit-compiler'; function injectCardBlock(cardName, cardPayload, editor, index) { // FIXME: Do we change the block model internal representation here? diff --git a/src/js/commands/format-block.js b/src/js/commands/format-block.js index 81e2a059f..60a329ab2 100644 --- a/src/js/commands/format-block.js +++ b/src/js/commands/format-block.js @@ -1,7 +1,8 @@ import TextFormatCommand from './text-format'; import { getSelectionBlockElement, selectNode } from '../utils/selection-utils'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; -import Type from 'node_modules/content-kit-compiler/src/types/type'; +import { inherit } from 'content-kit-utils'; +import { Type } from 'content-kit-compiler'; +import { doc } from 'content-kit-compiler'; function FormatBlockCommand(options) { options = options || {}; @@ -22,7 +23,7 @@ FormatBlockCommand.prototype.exec = function() { // Flattens the selection before applying the block format. // Otherwise, undesirable nested blocks can occur. // TODO: would love to be able to remove this - var flatNode = document.createTextNode(blockElement.textContent); + var flatNode = doc.createTextNode(blockElement.textContent); blockElement.parentNode.insertBefore(flatNode, blockElement); blockElement.parentNode.removeChild(blockElement); selectNode(flatNode); diff --git a/src/js/commands/heading.js b/src/js/commands/heading.js index fa1cbf936..c28816adb 100644 --- a/src/js/commands/heading.js +++ b/src/js/commands/heading.js @@ -1,6 +1,6 @@ import FormatBlockCommand from './format-block'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; -import Type from 'node_modules/content-kit-compiler/src/types/type'; +import { inherit } from 'content-kit-utils'; +import { Type } from 'content-kit-compiler'; function HeadingCommand() { FormatBlockCommand.call(this, { diff --git a/src/js/commands/image.js b/src/js/commands/image.js index 9db3235e2..fb07e1490 100644 --- a/src/js/commands/image.js +++ b/src/js/commands/image.js @@ -1,12 +1,16 @@ import Command from './base'; import Message from '../views/message'; -import Type from 'node_modules/content-kit-compiler/src/types/type'; -import BlockModel from 'node_modules/content-kit-compiler/src/models/block'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; +import { + Type, + BlockModel, + doc, +} from 'content-kit-compiler'; +import win from '../utils/win'; +import { inherit } from 'content-kit-utils'; import { FileUploader } from '../utils/http-utils'; function createFileInput(command) { - var fileInput = document.createElement('input'); + var fileInput = doc.createElement('input'); fileInput.type = 'file'; fileInput.accept = 'image/*'; fileInput.className = 'ck-file-input'; @@ -22,7 +26,7 @@ function injectImageBlock(src, editor, index) { } function renderFromFile(file, editor, index) { - if (file && window.FileReader) { + if (file && win.FileReader) { var reader = new FileReader(); reader.onload = function(e) { var base64Src = e.target.result; @@ -48,7 +52,7 @@ ImageCommand.prototype = { var fileInput = this.fileInput; if (!fileInput) { fileInput = this.fileInput = createFileInput(this); - document.body.appendChild(fileInput); + doc.body.appendChild(fileInput); } fileInput.dispatchEvent(new MouseEvent('click', { bubbles: false })); }, diff --git a/src/js/commands/italic.js b/src/js/commands/italic.js index a14eb0731..5380d09d0 100644 --- a/src/js/commands/italic.js +++ b/src/js/commands/italic.js @@ -1,6 +1,6 @@ import TextFormatCommand from './text-format'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; -import Type from 'node_modules/content-kit-compiler/src/types/type'; +import { inherit } from 'content-kit-utils'; +import { Type }from 'content-kit-compiler'; function ItalicCommand() { TextFormatCommand.call(this, { diff --git a/src/js/commands/link.js b/src/js/commands/link.js index de36b68de..9b79d5bc9 100644 --- a/src/js/commands/link.js +++ b/src/js/commands/link.js @@ -1,8 +1,8 @@ import TextFormatCommand from './text-format'; import Prompt from '../views/prompt'; import { getSelectionTagName } from '../utils/selection-utils'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; -import Type from 'node_modules/content-kit-compiler/src/types/type'; +import { inherit } from 'content-kit-utils'; +import { Type } from 'content-kit-compiler'; var RegExpHttp = /^https?:\/\//i; diff --git a/src/js/commands/list.js b/src/js/commands/list.js index 8474a1c49..a3f94ba5c 100644 --- a/src/js/commands/list.js +++ b/src/js/commands/list.js @@ -1,7 +1,8 @@ import TextFormatCommand from './text-format'; import { getSelectionBlockElement, selectNode, getSelectionTagName } from '../utils/selection-utils'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; -import Type from 'node_modules/content-kit-compiler/src/types/type'; +import { inherit } from 'content-kit-utils'; +import { Type } from 'content-kit-compiler'; +import win from '../utils/win'; function ListCommand(options) { TextFormatCommand.call(this, options); @@ -31,7 +32,7 @@ ListCommand.prototype.checkAutoFormat = function(node) { text = node.textContent; if (Type.LIST_ITEM.tag !== getSelectionTagName() && regex.test(text)) { this.exec(); - window.getSelection().anchorNode.textContent = text.replace(regex, ''); + win.getSelection().anchorNode.textContent = text.replace(regex, ''); return true; } } diff --git a/src/js/commands/oembed.js b/src/js/commands/oembed.js index 7e2cd978d..89d84cbf8 100644 --- a/src/js/commands/oembed.js +++ b/src/js/commands/oembed.js @@ -1,18 +1,22 @@ import Command from './base'; import Prompt from '../views/prompt'; import Message from '../views/message'; -import EmbedModel from 'node_modules/content-kit-compiler/src/models/embed'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; +import { + EmbedModel, + doc +} from 'content-kit-compiler'; +import { inherit } from 'content-kit-utils'; import { OEmbedder } from '../utils/http-utils'; +import win from '../utils/win'; function loadTwitterWidgets(element) { - if (window.twttr) { - window.twttr.widgets.load(element); + if (win.twttr) { + win.twttr.widgets.load(element); } else { - var script = document.createElement('script'); + var script = doc.createElement('script'); script.async = true; script.src = 'http://platform.twitter.com/widgets.js'; - document.head.appendChild(script); + doc.head.appendChild(script); } } diff --git a/src/js/commands/ordered-list.js b/src/js/commands/ordered-list.js index 49395415c..c503aa140 100644 --- a/src/js/commands/ordered-list.js +++ b/src/js/commands/ordered-list.js @@ -1,6 +1,6 @@ import ListCommand from './list'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; -import Type from 'node_modules/content-kit-compiler/src/types/type'; +import { inherit } from 'content-kit-utils'; +import { Type } from 'content-kit-compiler'; function OrderedListCommand() { ListCommand.call(this, { diff --git a/src/js/commands/quote.js b/src/js/commands/quote.js index 9b1a41bd3..a5917f03f 100644 --- a/src/js/commands/quote.js +++ b/src/js/commands/quote.js @@ -1,6 +1,6 @@ import FormatBlockCommand from './format-block'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; -import Type from 'node_modules/content-kit-compiler/src/types/type'; +import { inherit } from 'content-kit-utils'; +import { Type } from 'content-kit-compiler'; function QuoteCommand() { FormatBlockCommand.call(this, { diff --git a/src/js/commands/subheading.js b/src/js/commands/subheading.js index a3b8ba58c..645db6969 100644 --- a/src/js/commands/subheading.js +++ b/src/js/commands/subheading.js @@ -1,6 +1,6 @@ import FormatBlockCommand from './format-block'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; -import Type from 'node_modules/content-kit-compiler/src/types/type'; +import { inherit } from 'content-kit-utils'; +import { Type } from 'content-kit-compiler'; function SubheadingCommand() { FormatBlockCommand.call(this, { diff --git a/src/js/commands/text-format.js b/src/js/commands/text-format.js index ed03cf597..3a47e2157 100644 --- a/src/js/commands/text-format.js +++ b/src/js/commands/text-format.js @@ -1,5 +1,6 @@ import Command from './base'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; +import { inherit } from 'content-kit-utils'; +import { doc } from 'content-kit-compiler'; function TextFormatCommand(options) { options = options || {}; @@ -14,10 +15,10 @@ inherit(TextFormatCommand, Command); TextFormatCommand.prototype = { exec: function(value) { - document.execCommand(this.action, false, value || null); + doc.execCommand(this.action, false, value || null); }, unexec: function(value) { - document.execCommand(this.removeAction, false, value || null); + doc.execCommand(this.removeAction, false, value || null); } }; diff --git a/src/js/commands/unordered-list.js b/src/js/commands/unordered-list.js index ca4e2d800..8fe63c1bf 100644 --- a/src/js/commands/unordered-list.js +++ b/src/js/commands/unordered-list.js @@ -1,6 +1,6 @@ import ListCommand from './list'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; -import Type from 'node_modules/content-kit-compiler/src/types/type'; +import { inherit } from 'content-kit-utils'; +import { Type } from 'content-kit-compiler'; function UnorderedListCommand() { ListCommand.call(this, { diff --git a/src/js/editor/editor-factory.js b/src/js/editor/editor-factory.js index 6cf2637b0..5970ede41 100644 --- a/src/js/editor/editor-factory.js +++ b/src/js/editor/editor-factory.js @@ -1,4 +1,5 @@ import Editor from './editor'; +import { doc } from 'content-kit-compiler'; /** * @class EditorFactory @@ -16,7 +17,7 @@ function EditorFactory(element, options) { } if (typeof element === 'string') { - elements = document.querySelectorAll(element); + elements = doc.querySelectorAll(element); } else if (element && element.length) { elements = element; } else if (element) { diff --git a/src/js/editor/editor.js b/src/js/editor/editor.js index a3c03f2ca..d3ffc9800 100644 --- a/src/js/editor/editor.js +++ b/src/js/editor/editor.js @@ -16,10 +16,13 @@ import CardCommand from '../commands/card'; import Keycodes from '../utils/keycodes'; import { getSelectionBlockElement, getCursorOffsetInElement } from '../utils/selection-utils'; import EventEmitter from '../utils/event-emitter'; -import Compiler from 'node_modules/content-kit-compiler/src/compiler'; -import Type from 'node_modules/content-kit-compiler/src/types/type'; -import { toArray } from 'node_modules/content-kit-utils/src/array-utils'; -import { merge, mergeWithOptions } from 'node_modules/content-kit-utils/src/object-utils'; +import { + Type, + Compiler, + doc +} from 'content-kit-compiler'; +import { toArray, merge, mergeWithOptions } from 'content-kit-utils'; +import win from '../utils/win'; var defaults = { placeholder: 'Write here...', @@ -27,7 +30,7 @@ var defaults = { autofocus: true, model: null, serverHost: '', - stickyToolbar: !!('ontouchstart' in window), + stickyToolbar: !!('ontouchstart' in win), textFormatCommands: [ new BoldCommand(), new ItalicCommand(), @@ -58,7 +61,7 @@ function bindContentEditableTypingListeners(editor) { if (!getSelectionBlockElement() || !editor.element.textContent || (!e.shiftKey && e.which === Keycodes.ENTER) || (e.ctrlKey && e.which === Keycodes.M)) { - document.execCommand('formatBlock', false, Type.PARAGRAPH.tag); + doc.execCommand('formatBlock', false, Type.PARAGRAPH.tag); } //else if (e.which === Keycodes.BKSP) { // TODO: Need to rerender when backspacing 2 blocks together //var cursorIndex = editor.getCursorIndexInCurrentBlock(); @@ -74,7 +77,7 @@ function bindContentEditableTypingListeners(editor) { var pastedHTML = data && data.getData && data.getData('text/html'); var sanitizedHTML = pastedHTML && editor.compiler.rerender(pastedHTML); if (sanitizedHTML) { - document.execCommand('insertHTML', false, sanitizedHTML); + doc.execCommand('insertHTML', false, sanitizedHTML); editor.syncVisual(); } e.preventDefault(); @@ -96,7 +99,7 @@ function bindAutoTypingListeners(editor) { var selection, i; if (count) { - selection = window.getSelection(); + selection = win.getSelection(); for (i = 0; i < count; i++) { if (commands[i].checkAutoFormat(selection.anchorNode)) { e.stopPropagation(); @@ -109,10 +112,10 @@ function bindAutoTypingListeners(editor) { function bindDragAndDrop() { // TODO. For now, just prevent redirect when dropping something on the page - window.addEventListener('dragover', function(e) { + win.addEventListener('dragover', function(e) { e.preventDefault(); // prevents showing cursor where to drop }); - window.addEventListener('drop', function(e) { + win.addEventListener('drop', function(e) { e.preventDefault(); // prevent page from redirecting }); } @@ -259,7 +262,7 @@ Editor.prototype.replaceBlock = function(block, index) { Editor.prototype.renderBlockAt = function(index, replace) { var modelAtIndex = this.model[index]; var html = this.compiler.render([modelAtIndex]); - var dom = document.createElement('div'); + var dom = doc.createElement('div'); dom.innerHTML = html; var newEl = dom.firstChild; newEl.dataset.modelIndex = index; diff --git a/src/js/index.js b/src/js/index.js index bc7779493..7529959c0 100644 --- a/src/js/index.js +++ b/src/js/index.js @@ -1,9 +1,12 @@ -import Type from 'node_modules/content-kit-compiler/src/types/type'; -import BlockModel from 'node_modules/content-kit-compiler/src/models/block'; -import EmbedModel from 'node_modules/content-kit-compiler/src/models/embed'; -import Compiler from 'node_modules/content-kit-compiler/src/compiler'; -import HTMLParser from 'node_modules/content-kit-compiler/src/parsers/html-parser'; -import HTMLRenderer from 'node_modules/content-kit-compiler/src/renderers/html-renderer'; +import { + Type, + BlockModel, + EmbedModel, + Compiler, + HTMLParser, + HTMLRenderer +} from 'content-kit-compiler'; + import EditorFactory from './editor/editor-factory'; // Create a namespace and selectivly expose public modules @@ -16,4 +19,8 @@ ContentKit.HTMLParser = HTMLParser; ContentKit.HTMLRenderer = HTMLRenderer; ContentKit.Editor = EditorFactory; -window.ContentKit = ContentKit; +export function registerGlobal(global) { + global.ContentKit = ContentKit; +} + +export default ContentKit; diff --git a/src/js/renderers/editor-html-renderer.js b/src/js/renderers/editor-html-renderer.js index beeaf4cdb..1b597f4dd 100644 --- a/src/js/renderers/editor-html-renderer.js +++ b/src/js/renderers/editor-html-renderer.js @@ -1,11 +1,13 @@ -import HTMLRenderer from 'node_modules/content-kit-compiler/src/renderers/html-renderer'; -import Type from 'node_modules/content-kit-compiler/src/types/type'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; +import { HTMLRenderer } from 'content-kit-compiler'; +import { Type } from 'content-kit-compiler'; +import { + inherit, + merge +} from 'content-kit-utils'; import YouTubeRenderer from './youtube'; import TwitterRenderer from './twitter'; import InstagramRenderer from './instagram'; import LinkImageRenderer from './link-image-renderer'; -import { merge } from 'node_modules/content-kit-utils/src/object-utils'; /** * A dictionary of supported embeds types that we'll custom render diff --git a/src/js/utils/element-utils.js b/src/js/utils/element-utils.js index 15ce55dff..906047e29 100644 --- a/src/js/utils/element-utils.js +++ b/src/js/utils/element-utils.js @@ -1,5 +1,8 @@ +import { doc } from 'content-kit-compiler'; +import win from '../utils/win'; + function createDiv(className) { - var div = document.createElement('div'); + var div = doc.createElement('div'); if (className) { div.className = className; } @@ -49,9 +52,9 @@ function elementContentIsEmpty(element) { } function getElementRelativeOffset(element) { - var offset = { left: 0, top: -window.pageYOffset }; + var offset = { left: 0, top: -win.pageYOffset }; var offsetParent = element.offsetParent; - var offsetParentPosition = window.getComputedStyle(offsetParent).position; + var offsetParentPosition = win.getComputedStyle(offsetParent).position; var offsetParentRect; if (offsetParentPosition === 'relative') { @@ -63,7 +66,7 @@ function getElementRelativeOffset(element) { } function getElementComputedStyleNumericProp(element, prop) { - return parseFloat(window.getComputedStyle(element)[prop]); + return parseFloat(win.getComputedStyle(element)[prop]); } function positionElementToRect(element, rect, topOffset, leftOffset) { diff --git a/src/js/utils/http-utils.js b/src/js/utils/http-utils.js index 2df74388d..868938214 100644 --- a/src/js/utils/http-utils.js +++ b/src/js/utils/http-utils.js @@ -1,3 +1,4 @@ +import win from '../utils/win'; function createXHR(options) { var xhr = new XMLHttpRequest(); @@ -65,7 +66,7 @@ FileUploader.prototype.upload = function(options) { var file = options.file || (fileInput && fileInput.files && fileInput.files[0]); var callback = options.complete; var maxFileSize = this.maxFileSize; - if (!file || !(file instanceof window.File)) { return; } + if (!file || !(file instanceof win.File)) { return; } if (maxFileSize && file.size > maxFileSize) { if (callback) { callback.call(this, null, { message: 'max file size is ' + maxFileSize + ' bytes' }); } diff --git a/src/js/utils/selection-utils.js b/src/js/utils/selection-utils.js index bc498fa8f..4cd642827 100644 --- a/src/js/utils/selection-utils.js +++ b/src/js/utils/selection-utils.js @@ -1,5 +1,8 @@ import { nodeIsDescendantOfElement } from './element-utils'; -import Type from 'node_modules/content-kit-compiler/src/types/type'; +import { + Type, + doc +} from 'content-kit-compiler'; // TODO: remove, pass in Editor's current block set var RootTags = [ @@ -29,13 +32,13 @@ function getDirectionOfSelection(selection) { } function getSelectionElement(selection) { - selection = selection || window.getSelection(); + selection = selection || win.getSelection(); var node = getDirectionOfSelection(selection) === SelectionDirection.LEFT_TO_RIGHT ? selection.anchorNode : selection.focusNode; return node && (node.nodeType === 3 ? node.parentNode : node); } function getSelectionBlockElement(selection) { - selection = selection || window.getSelection(); + selection = selection || win.getSelection(); var element = getSelectionElement(); var tag = element && element.tagName.toLowerCase(); while (tag && RootTags.indexOf(tag) === -1) { @@ -82,14 +85,14 @@ function selectionIsEditable(selection) { } function restoreRange(range) { - var selection = window.getSelection(); + var selection = win.getSelection(); selection.removeAllRanges(); selection.addRange(range); } function selectNode(node) { - var range = document.createRange(); - var selection = window.getSelection(); + var range = doc.createRange(); + var selection = win.getSelection(); range.setStart(node, 0); range.setEnd(node, node.length); selection.removeAllRanges(); @@ -97,8 +100,8 @@ function selectNode(node) { } function setCursorIndexInElement(element, index) { - var range = document.createRange(); - var selection = window.getSelection(); + var range = doc.createRange(); + var selection = win.getSelection(); range.setStart(element, index); range.collapse(true); selection.removeAllRanges(); @@ -112,7 +115,7 @@ function setCursorToStartOfElement(element) { function getCursorOffsetInElement(element) { // http://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container/4812022#4812022 var caretOffset = 0; - var selection = window.getSelection(); + var selection = win.getSelection(); if (selection.rangeCount > 0) { var range = selection.getRangeAt(0); var preCaretRange = range.cloneRange(); diff --git a/src/js/utils/win.js b/src/js/utils/win.js new file mode 100644 index 000000000..3b9e454de --- /dev/null +++ b/src/js/utils/win.js @@ -0,0 +1,11 @@ +import { doc } from 'content-kit-compiler'; + +var win; +if (typeof window !== 'undefined') { + win = window; +} else { + // jsdom provides a defaultView + win = doc.defaultView; +} + +export default win; diff --git a/src/js/views/embed-intent.js b/src/js/views/embed-intent.js index e22068c83..d9411fb70 100644 --- a/src/js/views/embed-intent.js +++ b/src/js/views/embed-intent.js @@ -1,10 +1,12 @@ import View from './view'; import Toolbar from './toolbar'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; +import { inherit } from 'content-kit-utils'; import { getSelectionBlockElement } from '../utils/selection-utils'; import { elementContentIsEmpty, positionElementToLeftOf, positionElementCenteredIn } from '../utils/element-utils'; import { createDiv } from '../utils/element-utils'; import Keycodes from '../utils/keycodes'; +import { doc } from 'content-kit-compiler'; +import win from '../utils/win'; var LayoutStyle = { GUTTER : 1, @@ -27,7 +29,7 @@ function EmbedIntent(options) { embedIntent.isActive = false; embedIntent.editorContext = options.editorContext; embedIntent.loadingIndicator = createDiv('ck-embed-loading'); - embedIntent.button = document.createElement('button'); + embedIntent.button = doc.createElement('button'); embedIntent.button.className = 'ck-embed-intent-btn'; embedIntent.button.title = 'Insert image or embed...'; embedIntent.element.appendChild(embedIntent.button); @@ -58,17 +60,17 @@ function EmbedIntent(options) { } rootElement.addEventListener('keyup', embedIntentHandler); - document.addEventListener('mouseup', function() { + doc.addEventListener('mouseup', function() { setTimeout(function() { embedIntentHandler(); }); }); - document.addEventListener('keyup', function(e) { + doc.addEventListener('keyup', function(e) { if (e.keyCode === Keycodes.ESC) { embedIntent.hide(); } }); - window.addEventListener('resize', function() { + win.addEventListener('resize', function() { if(embedIntent.isShowing) { embedIntent.reposition(); } diff --git a/src/js/views/message.js b/src/js/views/message.js index 59d72a60f..37844b037 100644 --- a/src/js/views/message.js +++ b/src/js/views/message.js @@ -1,5 +1,5 @@ import View from './view'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; +import { inherit } from 'content-kit-utils'; var defaultClassNames = ['ck-message']; diff --git a/src/js/views/prompt.js b/src/js/views/prompt.js index ed631cdb2..6626edc26 100644 --- a/src/js/views/prompt.js +++ b/src/js/views/prompt.js @@ -1,10 +1,12 @@ import View from './view'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; +import { inherit } from 'content-kit-utils'; import { restoreRange } from '../utils/selection-utils'; import { createDiv, positionElementToRect } from '../utils/element-utils'; import Keycodes from '../utils/keycodes'; +import { doc } from 'content-kit-compiler'; +import win from '../utils/win'; -var container = document.body; +var container = doc.body; var hiliter = createDiv('ck-editor-hilite'); function positionHiliteRange(range) { @@ -32,7 +34,7 @@ function Prompt(options) { } }); - window.addEventListener('resize', function() { + win.addEventListener('resize', function() { var activeHilite = hiliter.parentNode; var range = prompt.range; if(activeHilite && range) { @@ -45,7 +47,7 @@ inherit(Prompt, View); Prompt.prototype.show = function(callback) { var prompt = this; var element = prompt.element; - var selection = window.getSelection(); + var selection = win.getSelection(); var range = selection && selection.rangeCount && selection.getRangeAt(0); element.value = null; prompt.range = range || null; diff --git a/src/js/views/text-format-toolbar.js b/src/js/views/text-format-toolbar.js index cd04aba69..fa61ca0bc 100644 --- a/src/js/views/text-format-toolbar.js +++ b/src/js/views/text-format-toolbar.js @@ -1,14 +1,16 @@ import Toolbar from './toolbar'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; +import { inherit } from 'content-kit-utils'; import { selectionIsEditable, selectionIsInElement } from '../utils/selection-utils'; import Keycodes from '../utils/keycodes'; +import { doc } from 'content-kit-compiler'; +import win from '../utils/win'; function selectionIsEditableByToolbar(selection, toolbar) { return selectionIsEditable(selection) && selectionIsInElement(selection, toolbar.rootElement); } function handleTextSelection(toolbar) { - var selection = window.getSelection(); + var selection = win.getSelection(); if (toolbar.sticky) { toolbar.updateForSelection(selectionIsEditableByToolbar(selection, toolbar) ? selection : null); } else { @@ -27,13 +29,13 @@ function TextFormatToolbar(options) { toolbar.rootElement = options.rootElement; toolbar.rootElement.addEventListener('keyup', function() { handleTextSelection(toolbar); }); - document.addEventListener('mouseup', function() { + doc.addEventListener('mouseup', function() { setTimeout(function() { handleTextSelection(toolbar); }); }); - document.addEventListener('keyup', function(e) { + doc.addEventListener('keyup', function(e) { var key = e.keyCode; if (key === 116) { //F5 toolbar.toggleSticky(); @@ -43,10 +45,10 @@ function TextFormatToolbar(options) { } }); - window.addEventListener('resize', function() { + win.addEventListener('resize', function() { if(!toolbar.sticky && toolbar.isShowing) { var activePromptRange = toolbar.activePrompt && toolbar.activePrompt.range; - toolbar.positionToContent(activePromptRange ? activePromptRange : window.getSelection().getRangeAt(0)); + toolbar.positionToContent(activePromptRange ? activePromptRange : win.getSelection().getRangeAt(0)); } }); } diff --git a/src/js/views/toolbar-button.js b/src/js/views/toolbar-button.js index d2edef4a9..856c1d6d5 100644 --- a/src/js/views/toolbar-button.js +++ b/src/js/views/toolbar-button.js @@ -1,3 +1,4 @@ +import { doc } from 'content-kit-compiler'; var buttonClassName = 'ck-toolbar-btn'; @@ -6,7 +7,7 @@ function ToolbarButton(options) { var toolbar = options.toolbar; var command = options.command; var prompt = command.prompt; - var element = document.createElement('button'); + var element = doc.createElement('button'); button.element = element; button.command = command; diff --git a/src/js/views/toolbar.js b/src/js/views/toolbar.js index d63344c2e..3d89f96ee 100644 --- a/src/js/views/toolbar.js +++ b/src/js/views/toolbar.js @@ -1,8 +1,9 @@ import View from './view'; import ToolbarButton from './toolbar-button'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; +import { inherit } from 'content-kit-utils'; import { tagsInSelection } from '../utils/selection-utils'; import { createDiv, swapElements, positionElementToRightOf, positionElementCenteredAbove } from '../utils/element-utils'; +import { doc } from 'content-kit-compiler'; var ToolbarDirection = { TOP : 1, @@ -57,7 +58,7 @@ function Toolbar(options) { } // Closes prompt if displayed when changing selection - document.addEventListener('mouseup', function() { + doc.addEventListener('mouseup', function() { toolbar.dismissPrompt(); }); } @@ -103,7 +104,7 @@ Toolbar.prototype.dismissPrompt = function() { Toolbar.prototype.updateForSelection = function(selection) { var toolbar = this; - selection = selection || window.getSelection(); + selection = selection || win.getSelection(); if (toolbar.sticky) { updateButtonsForSelection(toolbar.buttons, selection); } else if (!selection.isCollapsed) { @@ -123,7 +124,7 @@ Toolbar.prototype.positionToContent = function(content) { positioningMethod = positionElementCenteredAbove; } position = positioningMethod(this.element, content); - sideEdgeOffset = Math.min(Math.max(10, position.left), document.body.clientWidth - this.element.offsetWidth - 10); + sideEdgeOffset = Math.min(Math.max(10, position.left), doc.body.clientWidth - this.element.offsetWidth - 10); this.contentElement.style.transform = 'translateX(' + (sideEdgeOffset - position.left) + 'px)'; }; diff --git a/src/js/views/tooltip.js b/src/js/views/tooltip.js index b4f8d4309..0d5d05e09 100644 --- a/src/js/views/tooltip.js +++ b/src/js/views/tooltip.js @@ -1,5 +1,5 @@ import View from './view'; -import { inherit } from 'node_modules/content-kit-utils/src/object-utils'; +import { inherit } from 'content-kit-utils'; import { positionElementCenteredBelow, getEventTargetMatchingTag } from '../utils/element-utils'; function Tooltip(options) { diff --git a/src/js/views/view.js b/src/js/views/view.js index 09970877e..eec6bb307 100644 --- a/src/js/views/view.js +++ b/src/js/views/view.js @@ -1,3 +1,5 @@ +import { doc } from 'content-kit-compiler'; + function renderClasses(view) { var classNames = view.classNames; if (classNames && classNames.length) { @@ -11,8 +13,8 @@ function View(options) { options = options || {}; this.tagName = options.tagName || 'div'; this.classNames = options.classNames || []; - this.element = document.createElement(this.tagName); - this.container = options.container || document.body; + this.element = doc.createElement(this.tagName); + this.container = options.container || doc.body; this.isShowing = false; renderClasses(this); } From 532c974d3cde212e95178e30b89b201b6b6648cb Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Tue, 30 Jun 2015 14:27:47 -0400 Subject: [PATCH 07/77] use testem for tests --- .travis.yml | 25 +++++++++++-- Brocfile.js | 8 ++++- README.md | 17 ++++++--- bower.json | 2 +- broccoli/test-tree-builder.js | 58 ++++++++++++++++++++++++++++++ package.json | 8 +++-- src/js/editor/editor-factory.js | 3 +- src/js/index.js | 21 +++++------ testem.json | 16 +++++++++ tests/{tests.js => editor-test.js} | 26 ++++++++------ tests/index.html | 18 ++++++---- 11 files changed, 162 insertions(+), 40 deletions(-) create mode 100644 broccoli/test-tree-builder.js create mode 100644 testem.json rename tests/{tests.js => editor-test.js} (73%) diff --git a/.travis.yml b/.travis.yml index 6b7f05d7b..cc63c5c69 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,24 @@ +--- language: node_js node_js: - - "0.10" -notifications: - email: false \ No newline at end of file + - "0.12" + +sudo: false + +cache: + directories: + - node_modules + +before_install: + - export PATH=/usr/local/phantomjs-2.0.0/bin:$PATH + - "npm config set spin false" + - "npm install -g npm@^2" + +install: + - npm install -g broccoli-cli + - npm install -g bower + - bower install + - npm install + +script: + - npm test diff --git a/Brocfile.js b/Brocfile.js index 4aaeaa955..64270fd00 100644 --- a/Brocfile.js +++ b/Brocfile.js @@ -2,6 +2,7 @@ var multiBuilder = require('broccoli-multi-builder'); var mergeTrees = require('broccoli-merge-trees'); +var testTreeBuilder = require('./broccoli/test-tree-builder'); var jsSrc = './src/js'; var vendoredModules = ['content-kit-compiler', 'content-kit-utils']; @@ -27,4 +28,9 @@ var cjsTree = multiBuilder.buildCJS({ packageName: packageName }); -module.exports = mergeTrees([ amdTree, globalTree, cjsTree ]); +module.exports = mergeTrees([ + amdTree, + globalTree, + cjsTree, + testTreeBuilder.build() +]); diff --git a/README.md b/README.md index c053fd950..3925ea36e 100644 --- a/README.md +++ b/README.md @@ -77,11 +77,20 @@ Running ContentKit tests and demo server locally requires the following dependen * [node.js](http://nodejs.org/) ([install package](http://nodejs.org/download/)) or `brew install node` * `gulp`, via `npm install -g gulp` -To run tests: +### Tests -``` -gulp test -``` +Install npm and bower: + + * `bower i i` + * `npm i` + +Run tests via the built-in broccoli server: + + * `npm run serve && open http://localhost:4200/tests` + +Or run tests via testem: + + * `npm test` To run the demo server: diff --git a/bower.json b/bower.json index 26e506cf4..26f54cbbc 100644 --- a/bower.json +++ b/bower.json @@ -16,6 +16,6 @@ "tests" ], "dependencies": { - "loader.js": "~3.2.1" + "ember-cli-test-loader": "~0.1.3" } } diff --git a/broccoli/test-tree-builder.js b/broccoli/test-tree-builder.js new file mode 100644 index 000000000..6ba62a0ce --- /dev/null +++ b/broccoli/test-tree-builder.js @@ -0,0 +1,58 @@ +/* jshint node:true */ +var funnel = require('broccoli-funnel'); +var es6 = require('broccoli-babel-transpiler'); +var concat = require('broccoli-concat'); +var mergeTrees = require('broccoli-merge-trees'); + +var pkg = require('../package.json'); +var packageName = pkg.name; +var outputFileName = packageName + '-tests.amd.js'; + +function buildTestTree() { + var testJSTree = funnel('./tests', { + include: ['**/*.js'], + destDir: '/tests' + }); + + testJSTree = es6(testJSTree, { + moduleIds: true, + modules: 'amdStrict' + }); + + testJSTree = concat(testJSTree, { + inputFiles: ['**/*.js'], + outputFile: '/tests/' + outputFileName + }); + + var testExtTree = funnel('./node_modules', { + include: [ + 'qunitjs/qunit/qunit.js', + 'qunitjs/qunit/qunit.css' + ], + destDir: '/tests' + }); + + testExtTree = mergeTrees([testExtTree, funnel('./bower_components', { + include: [ + 'ember-cli-test-loader/test-loader.js' + ], + destDir: '/tests' + })]); + + var testHTMLTree = funnel('./tests', { + include: ['index.html'], + destDir: '/tests' + }); + + var testTree = mergeTrees([ + testJSTree, + testExtTree, + testHTMLTree + ]); + + return testTree; +} + +module.exports = { + build: buildTestTree +}; diff --git a/package.json b/package.json index 608fef4b3..569f4d0e0 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ }, "scripts": { "start": "node server/index.js", - "test": "gulp test", + "test": "testem ci", "build": "rm -rf dist && broccoli build dist", "prepublish": "npm run build" }, @@ -30,6 +30,9 @@ }, "devDependencies": { "broccoli": "^0.16.3", + "broccoli-babel-transpiler": "^5.2.3", + "broccoli-concat": "0.0.13", + "broccoli-funnel": "^0.2.3", "broccoli-merge-trees": "^0.2.1", "broccoli-multi-builder": "^0.1.0", "content-kit-compiler": "0.2.3", @@ -46,6 +49,7 @@ "gulp-open": "^0.2.8", "gulp-qunit": "^1.2.1", "gulp-uglify": "^1.1.0", - "qunitjs": "^1.17.1" + "qunitjs": "^1.17.1", + "testem": "^0.8.4" } } diff --git a/src/js/editor/editor-factory.js b/src/js/editor/editor-factory.js index 5970ede41..6cf2637b0 100644 --- a/src/js/editor/editor-factory.js +++ b/src/js/editor/editor-factory.js @@ -1,5 +1,4 @@ import Editor from './editor'; -import { doc } from 'content-kit-compiler'; /** * @class EditorFactory @@ -17,7 +16,7 @@ function EditorFactory(element, options) { } if (typeof element === 'string') { - elements = doc.querySelectorAll(element); + elements = document.querySelectorAll(element); } else if (element && element.length) { elements = element; } else if (element) { diff --git a/src/js/index.js b/src/js/index.js index 7529959c0..4f2926b35 100644 --- a/src/js/index.js +++ b/src/js/index.js @@ -7,20 +7,21 @@ import { HTMLRenderer } from 'content-kit-compiler'; -import EditorFactory from './editor/editor-factory'; +import Editor from './editor/editor-factory'; -// Create a namespace and selectivly expose public modules -var ContentKit = {}; -ContentKit.Type = Type; -ContentKit.BlockModel = BlockModel; -ContentKit.EmbedModel = EmbedModel; -ContentKit.Compiler = Compiler; -ContentKit.HTMLParser = HTMLParser; -ContentKit.HTMLRenderer = HTMLRenderer; -ContentKit.Editor = EditorFactory; +const ContentKit = { + Type, + BlockModel, + EmbedModel, + Compiler, + HTMLParser, + HTMLRenderer, + Editor +}; export function registerGlobal(global) { global.ContentKit = ContentKit; } +export { Editor }; export default ContentKit; diff --git a/testem.json b/testem.json new file mode 100644 index 000000000..2f920c5f0 --- /dev/null +++ b/testem.json @@ -0,0 +1,16 @@ +{ + "framework": "qunit", + "test_page": "dist/tests/index.html", + "src_files": [ + "tests/**/*.js", + "src/**/*.js" + ], + "before_tests": "npm run build", + "launch_in_ci": [ + "PhantomJS" + ], + "launch_in_dev": [ + "PhantomJS", + "Chrome" + ] +} diff --git a/tests/tests.js b/tests/editor-test.js similarity index 73% rename from tests/tests.js rename to tests/editor-test.js index d279d4abb..81afba0be 100644 --- a/tests/tests.js +++ b/tests/editor-test.js @@ -1,8 +1,12 @@ +/* global QUnit, test, asyncTest, ok, equal */ + var fixture = document.getElementById('qunit-fixture'); var editorElement = document.createElement('div'); editorElement.id = 'editor1'; editorElement.className = 'editor'; +import { Editor } from 'content-kit-editor'; + QUnit.module('Editor', { setup: function() { fixture.appendChild(editorElement); @@ -13,35 +17,35 @@ QUnit.module('Editor', { }); test('can create an editor', function() { - var editor = new ContentKit.Editor(); - ok(editor instanceof ContentKit.Editor); + var editor = new Editor(); + ok(editor instanceof Editor); }); test('can create an editor via dom node reference', function() { - var editor = new ContentKit.Editor(editorElement); + var editor = new Editor(editorElement); equal(editor.element, editorElement); }); test('can create an editor via dom node reference from getElementById', function() { - var editor = new ContentKit.Editor(document.getElementById('editor1')); + var editor = new Editor(document.getElementById('editor1')); equal(editor.element, editorElement); }); test('can create an editor via id selector', function() { - var editor = new ContentKit.Editor('#editor1'); + var editor = new Editor('#editor1'); equal(editor.element, editorElement); }); test('can create an editor via class selector', function() { - var editor = new ContentKit.Editor('.editor'); + var editor = new Editor('.editor'); equal(editor.element, editorElement); }); test('can recreate an editor on the same element', function() { - var editor = new ContentKit.Editor('#editor1'); + var editor = new Editor('#editor1'); ok(editor.element === editorElement); - editor = new ContentKit.Editor('.editor'); + editor = new Editor('.editor'); equal(editor.element, editorElement); equal(editor.element.className, 'editor ck-editor'); }); @@ -49,21 +53,21 @@ test('can recreate an editor on the same element', function() { test('creating an editor doesn\'t trash existing class names', function() { editorElement.className = 'some-class'; - var editor = new ContentKit.Editor('.some-class'); + var editor = new Editor('.some-class'); equal(editor.element.className, 'some-class ck-editor'); }); test('creating an editor without a class name adds appropriate class', function() { editorElement.className = ''; - var editor = new ContentKit.Editor(document.getElementById('editor1')); + var editor = new Editor(document.getElementById('editor1')); equal(editor.element.className, 'ck-editor'); }); asyncTest('editor fires update event', function() { expect(2); - var editor = new ContentKit.Editor(); + var editor = new Editor(); editor.on('update', function(data) { equal (this, editor); equal (data.index, 99); diff --git a/tests/index.html b/tests/index.html index 3b36ef372..dd6f7ad70 100644 --- a/tests/index.html +++ b/tests/index.html @@ -2,17 +2,23 @@ - QUnit - + Content-Kit-Editor tests +
- - - - + + + + + + From 26133874bff593a4565d9f4d3ce6ef361c87a503 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Tue, 30 Jun 2015 18:38:44 -0400 Subject: [PATCH 08/77] use content-kit-compiler 0.3.1 --- .npmignore | 4 ++++ package.json | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) create mode 100644 .npmignore diff --git a/.npmignore b/.npmignore new file mode 100644 index 000000000..5ed267a2b --- /dev/null +++ b/.npmignore @@ -0,0 +1,4 @@ +bower_components/ +node_modules/ +tmp/ +tests/ diff --git a/package.json b/package.json index 569f4d0e0..1f293f58d 100644 --- a/package.json +++ b/package.json @@ -35,8 +35,8 @@ "broccoli-funnel": "^0.2.3", "broccoli-merge-trees": "^0.2.1", "broccoli-multi-builder": "^0.1.0", - "content-kit-compiler": "0.2.3", - "content-kit-utils": "0.1.2", + "content-kit-compiler": "^0.3.1", + "content-kit-utils": "^0.2.0", "del": "^1.1.1", "esperanto": "^0.6.32", "gulp": "^3.8.11", From a0c5c563bb4211bce0fdb4fe8566fc2dff2efa5d Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Wed, 1 Jul 2015 13:26:04 -0400 Subject: [PATCH 09/77] update to work with broccoli multi builder 0.2.2, bring in loader.js to tests fix brocfile and tests to work with new dist structure --- Brocfile.js | 34 +++++++++++----------------------- broccoli/test-tree-builder.js | 13 +++++++++++++ package.json | 8 ++++---- tests/index.html | 3 ++- 4 files changed, 30 insertions(+), 28 deletions(-) diff --git a/Brocfile.js b/Brocfile.js index 64270fd00..f070ea8ed 100644 --- a/Brocfile.js +++ b/Brocfile.js @@ -1,36 +1,24 @@ /* jshint node:true */ -var multiBuilder = require('broccoli-multi-builder'); +var builder = require('broccoli-multi-builder'); var mergeTrees = require('broccoli-merge-trees'); var testTreeBuilder = require('./broccoli/test-tree-builder'); -var jsSrc = './src/js'; -var vendoredModules = ['content-kit-compiler', 'content-kit-utils']; +var vendoredModules = [ + {name: 'content-kit-compiler', options: {libDirName: 'src'}}, + {name: 'content-kit-utils', options: {libDirName: 'src'}} +]; var packageName = require('./package.json').name; -var amdTree = multiBuilder.buildAMD({ - isGlobal: false, - src: jsSrc, +var buildOptions = { + libDirName: 'src/js', vendoredModules: vendoredModules, packageName: packageName -}); - -var globalTree = multiBuilder.buildAMD({ - isGlobal: true, - src: jsSrc, - vendoredModules: vendoredModules, - packageName: packageName -}); - -var cjsTree = multiBuilder.buildCJS({ - src: jsSrc, - vendoredModules: vendoredModules, - packageName: packageName -}); +}; module.exports = mergeTrees([ - amdTree, - globalTree, - cjsTree, + builder.build('amd', buildOptions), + builder.build('global', buildOptions), + builder.build('commonjs', buildOptions), testTreeBuilder.build() ]); diff --git a/broccoli/test-tree-builder.js b/broccoli/test-tree-builder.js index 6ba62a0ce..6b1a893a6 100644 --- a/broccoli/test-tree-builder.js +++ b/broccoli/test-tree-builder.js @@ -7,6 +7,15 @@ var mergeTrees = require('broccoli-merge-trees'); var pkg = require('../package.json'); var packageName = pkg.name; var outputFileName = packageName + '-tests.amd.js'; +var path = require('path'); + +function loaderTree() { + var loaderDir = path.dirname(require.resolve('loader.js')); + return funnel(loaderDir, { + include: ['loader.js'], + destDir: '/tests/loader.js' + }); +} function buildTestTree() { var testJSTree = funnel('./tests', { @@ -24,6 +33,7 @@ function buildTestTree() { outputFile: '/tests/' + outputFileName }); + // bring in qunit var testExtTree = funnel('./node_modules', { include: [ 'qunitjs/qunit/qunit.js', @@ -32,6 +42,7 @@ function buildTestTree() { destDir: '/tests' }); + // bring in test-loader testExtTree = mergeTrees([testExtTree, funnel('./bower_components', { include: [ 'ember-cli-test-loader/test-loader.js' @@ -39,12 +50,14 @@ function buildTestTree() { destDir: '/tests' })]); + // include HTML file var testHTMLTree = funnel('./tests', { include: ['index.html'], destDir: '/tests' }); var testTree = mergeTrees([ + loaderTree(), testJSTree, testExtTree, testHTMLTree diff --git a/package.json b/package.json index 1f293f58d..1e2bc3b06 100644 --- a/package.json +++ b/package.json @@ -3,15 +3,14 @@ "version": "0.1.3", "description": "A modern, minimalist WYSIWYG editor.", "repository": "https://github.com/bustlelabs/content-kit-editor", - "main": "dist/content-kit-editor.js", + "main": "dist/commonjs/content-kit-editor/index.js", "engines": { "node": "0.10.x" }, "scripts": { "start": "node server/index.js", "test": "testem ci", - "build": "rm -rf dist && broccoli build dist", - "prepublish": "npm run build" + "build": "rm -rf dist && broccoli build dist" }, "keywords": [ "html", @@ -34,7 +33,7 @@ "broccoli-concat": "0.0.13", "broccoli-funnel": "^0.2.3", "broccoli-merge-trees": "^0.2.1", - "broccoli-multi-builder": "^0.1.0", + "broccoli-multi-builder": "^0.2.2", "content-kit-compiler": "^0.3.1", "content-kit-utils": "^0.2.0", "del": "^1.1.1", @@ -49,6 +48,7 @@ "gulp-open": "^0.2.8", "gulp-qunit": "^1.2.1", "gulp-uglify": "^1.1.0", + "loader.js": "^3.2.0", "qunitjs": "^1.17.1", "testem": "^0.8.4" } diff --git a/tests/index.html b/tests/index.html index dd6f7ad70..8275ebfa9 100644 --- a/tests/index.html +++ b/tests/index.html @@ -12,7 +12,8 @@ - + + + - - + + + + + From 43fd3c63053efbc5160d373276253bef1c1c78f5 Mon Sep 17 00:00:00 2001 From: Matthew Beale Date: Wed, 8 Jul 2015 12:22:59 -0400 Subject: [PATCH 26/77] WIP: Start rewriting the demo TODO: * Watch the mobiledoc to load and re-start the editor * Handle errors gracefully * Show serialized output * Show rendered output * Style, make the code panes dark --- demo/demo.css | 16 +++++---- demo/demo.js | 84 +++++++++------------------------------------- demo/index.html | 88 +++++++++++++++++-------------------------------- src/js/index.js | 2 +- 4 files changed, 57 insertions(+), 133 deletions(-) diff --git a/demo/demo.css b/demo/demo.css index c3bcb4112..35fddad65 100644 --- a/demo/demo.css +++ b/demo/demo.css @@ -16,6 +16,14 @@ body { } } +.container { + display: flex; + justify-content: space-around; +} + +.pane { +} + .editor-pane { max-width: 50em; margin: 0 auto; @@ -55,13 +63,7 @@ body { right: 0; width: 50%; } -.code-pane { - display: none; - position: absolute; - top: 0; - bottom: 0; - left: 0; - width: 100%; +#serialized-mobiledoc, #mobiledoc-to-load { background-color: #2b303b; overflow: hidden; } diff --git a/demo/demo.js b/demo/demo.js index 3c9f1b1ee..d7c76d07d 100644 --- a/demo/demo.js +++ b/demo/demo.js @@ -3,67 +3,12 @@ 'use strict'; var ContentKitDemo = exports.ContentKitDemo = { - toggleCodePane: function() { - if(document.body.className === 'code-pane-open') { - this.closeCodePane(); - } else { - this.openCodePane(editor); - } - }, - - openCodePane: function() { - window.getSelection().removeAllRanges(); - document.body.className = 'code-pane-open'; - location.hash = 'code'; - }, - - closeCodePane: function() { - window.getSelection().removeAllRanges(); - document.body.className = ''; - location.hash = ''; - }, - syncCodePane: function(editor) { - var codePaneJSON = document.getElementById('code-json'); - var codePaneHTML = document.getElementById('code-html'); + var codePaneJSON = document.getElementById('serialized-mobiledoc'); var json = editor.serialize(); codePaneJSON.innerHTML = this.syntaxHighlight(json); }, - formatXML: function(xml) { - // https://gist.github.com/sente/1083506 - xml = xml.replace(/(>)(<)(\/*)/g, '$1\r\n$2$3'); - var formatted = ''; - var pad = 0; - var nodes = xml.split('\r\n'); - var nodeLen = nodes.length; - var node, indent, padding, i, j; - for(i = 0; i < nodeLen; i++) { - node = nodes[i]; - if (node.match( /.+<\/\w[^>]*>$/ )) { - indent = 0; - } else if (node.match( /^<\/\w/ )) { - if (pad != 0) { - pad -= 1; - } - } else if (node.match( /^<\w[^>]*[^\/]>.*$/ )) { - indent = 1; - } else { - indent = 0; - } - - padding = ''; - for (j = 0; j < pad; j++) { - padding += ' '; - } - - formatted += padding + node + '\r\n'; - pad += indent; - } - - return formatted; - }, - syntaxHighlight: function(json) { // http://stackoverflow.com/a/7220510/189440 if (typeof json !== 'string') { @@ -89,19 +34,22 @@ var ContentKitDemo = exports.ContentKitDemo = { }; -// Initialize -if (window.editor) { - ContentKitDemo.syncCodePane(editor); - editor.on('update', function() { - ContentKitDemo.syncCodePane(this); +$(function() { + var textarea = $('#mobiledoc-to-load textarea'); + var textPayload = textarea.val(); + var payload = JSON.parse(textPayload); + var editorF = new ContentKit.Editor($('#editor')[0], { + mobiledoc: payload, + cards: { + 'pick-color': function renderPickColor(payload) { + return 'PICK A COLOR: '+payload.options.join(', '); + } + } }); - var settingsBtn = document.getElementById('settings-btn'); - settingsBtn.addEventListener('click', function() { - ContentKitDemo.toggleCodePane(); + + editorF.on('update', function(editor) { + ContentKitDemo.syncCodePane(editor); }); -} -if (location.hash === '#code') { - ContentKitDemo.openCodePane(); -} +}); }(this, document)); diff --git a/demo/index.html b/demo/index.html index cf3797303..100354f38 100644 --- a/demo/index.html +++ b/demo/index.html @@ -15,73 +15,47 @@ - -
- - -
-

ContentKit Editor

-

A modern, minimalist text editor allowing you to write in a distraction free environment. Simply select any text you would like to format and a toolbar will appear where you can toggle options such as bold and italic, or create a link.

-

Create headings by pressing "H1" on the toolbar

-

Pressing "H2" will create a subheading, like this one.

-
Create block quotes by selecting any text and pressing the "quote" button. Press it again to toggle back to a standard paragraph.
-

To create a list, start typing a dash followed by a space ("- ") on a new line and a list will be automatically created.

-

To create an ordered list, start typing a one followed by a period and a space ("1. ") and the list will be automatically created.

- -

Tips & Tricks:

-
    -
  • Close the formatting toolbar by clicking anywhere, or press ESC
  • -
  • Make the toolbar sticky by pressing F5
  • -
  • Double click a word to select it
  • -
  • You only have to select a portion of a paragraph if you want to change it to a heading, subheading, or quote
  • -
  • To create a soft line break, press shift + enter
  • -
  • Press enter twice to exit a list
  • -
- -

Keyboard shortcuts:

-
    -
  • bold: (cmd+B)
  • -
  • italic: (cmd+I)
  • -
  • undo: (cmd+z)
  • -
  • redo: (cmd+y)
  • -
  • select all text: (cmd+a)
  • -
  • select letters: (hold shift + arrow keys)
  • -
  • close toolbar: (ESC)
  • -
- -

Enjoy focusing on your content and not worrying about formatting!

-
- -
- +
+ +
+

mobiledoc to load

+
+ +
-
+
+

editor

+
+
+
-
-
- +
+

serilized mobiledoc

+
+
-
- + +
+

rendered mobiledoc

+
+
- - - + diff --git a/src/js/index.js b/src/js/index.js index 4f2926b35..778e355d5 100644 --- a/src/js/index.js +++ b/src/js/index.js @@ -7,7 +7,7 @@ import { HTMLRenderer } from 'content-kit-compiler'; -import Editor from './editor/editor-factory'; +import Editor from './editor/editor'; const ContentKit = { Type, From 98075e8c11465f74f2e7df86292c0dd98f7829f6 Mon Sep 17 00:00:00 2001 From: Matthew Beale Date: Wed, 8 Jul 2015 15:52:27 -0400 Subject: [PATCH 27/77] WIP: Add destroy to editor, make mobiledoc observable --- demo/demo.css | 5 +++++ demo/demo.js | 27 +++++++++++++++++++++------ src/js/editor/editor.js | 30 +++++++++++++++++++++++------- 3 files changed, 49 insertions(+), 13 deletions(-) diff --git a/demo/demo.css b/demo/demo.css index 35fddad65..9e2a48cf8 100644 --- a/demo/demo.css +++ b/demo/demo.css @@ -22,6 +22,11 @@ body { } .pane { + max-width: 25%; +} + +.pane textarea { + width: 100%; } .editor-pane { diff --git a/demo/demo.js b/demo/demo.js index d7c76d07d..eb7740441 100644 --- a/demo/demo.js +++ b/demo/demo.js @@ -34,11 +34,8 @@ var ContentKitDemo = exports.ContentKitDemo = { }; -$(function() { - var textarea = $('#mobiledoc-to-load textarea'); - var textPayload = textarea.val(); - var payload = JSON.parse(textPayload); - var editorF = new ContentKit.Editor($('#editor')[0], { +function bootEditor(element, payload) { + var editor = new ContentKit.Editor(element, { mobiledoc: payload, cards: { 'pick-color': function renderPickColor(payload) { @@ -47,9 +44,27 @@ $(function() { } }); - editorF.on('update', function(editor) { + editor.on('update', function() { ContentKitDemo.syncCodePane(editor); }); +} + +function readPayload(textarea) { + var jqueryTextarea = $(textarea); + var textPayload = jqueryTextarea.val(); + return JSON.parse(textPayload); +} + +$(function() { + var textarea = $('#mobiledoc-to-load textarea'); + var editor; + textarea.on('input', function() { + if (editor) { + editor.destroy(); + } + editor = bootEditor($('#editor')[0], readPayload(textarea)); + }); + editor = bootEditor($('#editor')[0], readPayload(textarea)); }); }(this, document)); diff --git a/src/js/editor/editor.js b/src/js/editor/editor.js index 31496366d..3ad47e9d0 100644 --- a/src/js/editor/editor.js +++ b/src/js/editor/editor.js @@ -63,7 +63,7 @@ function forEachChildNode(parentNode, callback) { } function bindContentEditableTypingListeners(editor) { - editor.element.addEventListener('keyup', function(e) { + editor.addEventListener(editor.element, 'keyup', function(e) { // Assure there is always a supported block tag, and not empty text nodes or divs. // On a carrage return, make sure to always generate a 'p' tag if (!getSelectionBlockElement() || @@ -80,7 +80,7 @@ function bindContentEditableTypingListeners(editor) { }); // On 'PASTE' sanitize and insert - editor.element.addEventListener('paste', function(e) { + editor.addEventListener(editor.element, 'paste', function(e) { var data = e.clipboardData; var pastedHTML = data && data.getData && data.getData('text/html'); var sanitizedHTML = pastedHTML && editor.compiler.rerender(pastedHTML); @@ -95,7 +95,7 @@ function bindContentEditableTypingListeners(editor) { function bindAutoTypingListeners(editor) { // Watch typing patterns for auto format commands (e.g. lists '- ', '1. ') - editor.element.addEventListener('keyup', function(e) { + editor.addEventListener(editor.element, 'keyup', function(e) { var commands = editor.autoTypingCommands; var count = commands && commands.length; var selection, i; @@ -112,12 +112,12 @@ function bindAutoTypingListeners(editor) { }); } -function bindDragAndDrop() { +function bindDragAndDrop(editor) { // TODO. For now, just prevent redirect when dropping something on the page - win.addEventListener('dragover', function(e) { + editor.addEventListener(win, 'dragover', function(e) { e.preventDefault(); // prevents showing cursor where to drop }); - win.addEventListener('drop', function(e) { + editor.addEventListener(win, 'drop', function(e) { e.preventDefault(); // prevent page from redirecting }); } @@ -165,6 +165,7 @@ function Editor(element, options) { throw new Error('Editor requires an element as the first argument'); } + this._elementListeners = []; this.element = element; // FIXME: This should merge onto this.options @@ -198,7 +199,7 @@ function Editor(element, options) { bindContentEditableTypingListeners(this); bindAutoTypingListeners(this); bindDragAndDrop(this); - element.addEventListener('input', () => this.handleInput(...arguments)); + this.addEventListener(element, 'input', () => this.handleInput(...arguments)); initEmbedCommands(this); this.textFormatToolbar = new TextFormatToolbar({ @@ -222,6 +223,11 @@ merge(Editor.prototype, EventEmitter); merge(Editor.prototype, { + addEventListener(context, eventName, callback) { + context.addEventListener(eventName, callback); + this._elementListeners.push([context, eventName, callback]); + }, + loadModel(model) { this.model = model; this.syncVisual(); @@ -416,6 +422,16 @@ merge(Editor.prototype, { serialize() { return Serializer.serialize(this.model); + }, + + removeAllEventListeners() { + this._elementListeners.forEach(([context, ...args]) => { + context.removeEventListener(...args); + }) + }, + + destroy() { + this.removeAllEventListeners(); } }); From 7bde2c7c7cc64571fd1ee6d8137996be0e478f3a Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Wed, 8 Jul 2015 16:00:18 -0400 Subject: [PATCH 28/77] minor style cleanup of demo --- demo/demo.css | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/demo/demo.css b/demo/demo.css index 9e2a48cf8..341e0a067 100644 --- a/demo/demo.css +++ b/demo/demo.css @@ -9,6 +9,7 @@ body { color: #454545; margin: 0; padding: 0; + background-color: #EFEFEF; } @media only screen and (max-width: 767px) { body { @@ -25,10 +26,6 @@ body { max-width: 25%; } -.pane textarea { - width: 100%; -} - .editor-pane { max-width: 50em; margin: 0 auto; @@ -69,9 +66,19 @@ body { width: 50%; } #serialized-mobiledoc, #mobiledoc-to-load { - background-color: #2b303b; overflow: hidden; + padding: 0.25em; +} +#serialized-mobiledoc { + white-space: pre; + background-color: #080808; } +#mobiledoc-to-load { +} +#mobiledoc-to-load textarea { + height: 300px; +} + .code-pane:first-child { display: block; } From 8213e30a33a9ffbd5d6d850a98f33ff877b3c98b Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Wed, 8 Jul 2015 16:42:40 -0400 Subject: [PATCH 29/77] Use runtime renderer in demo --- demo/demo.js | 6 ++++++ demo/index.html | 3 +++ src/js/index.js | 4 +++- 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/demo/demo.js b/demo/demo.js index eb7740441..02f5c3cb0 100644 --- a/demo/demo.js +++ b/demo/demo.js @@ -7,6 +7,12 @@ var ContentKitDemo = exports.ContentKitDemo = { var codePaneJSON = document.getElementById('serialized-mobiledoc'); var json = editor.serialize(); codePaneJSON.innerHTML = this.syntaxHighlight(json); + + var renderer = new ContentKit.Runtime.DOMRenderer(); + var rendered = renderer.render(json); + + $('#rendered-mobiledoc').empty(); + $('#rendered-mobiledoc')[0].appendChild(rendered); }, syntaxHighlight: function(json) { diff --git a/demo/index.html b/demo/index.html index 100354f38..a1225adaf 100644 --- a/demo/index.html +++ b/demo/index.html @@ -24,6 +24,9 @@

mobiledoc to load

[ [], [ + [1, "H2", [ + [[], 0, "hello world"] + ]], [1, "P", [ [[], 0, "hello world"] ]] diff --git a/src/js/index.js b/src/js/index.js index 778e355d5..abc0da387 100644 --- a/src/js/index.js +++ b/src/js/index.js @@ -4,7 +4,8 @@ import { EmbedModel, Compiler, HTMLParser, - HTMLRenderer + HTMLRenderer, + Runtime } from 'content-kit-compiler'; import Editor from './editor/editor'; @@ -16,6 +17,7 @@ const ContentKit = { Compiler, HTMLParser, HTMLRenderer, + Runtime, Editor }; From a2bbf96191166d6aeb64c9d24018fd0b50b8a23d Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Wed, 8 Jul 2015 17:25:25 -0400 Subject: [PATCH 30/77] typo fix --- demo/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/index.html b/demo/index.html index a1225adaf..398debdb5 100644 --- a/demo/index.html +++ b/demo/index.html @@ -43,7 +43,7 @@

editor

-

serilized mobiledoc

+

serialized mobiledoc

From d7705e5edcd61d693f58ffebdf07c954c9d26951 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Wed, 8 Jul 2015 17:35:30 -0400 Subject: [PATCH 31/77] fix jshint failure --- src/js/editor/editor.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/js/editor/editor.js b/src/js/editor/editor.js index 3ad47e9d0..faeec000a 100644 --- a/src/js/editor/editor.js +++ b/src/js/editor/editor.js @@ -427,7 +427,7 @@ merge(Editor.prototype, { removeAllEventListeners() { this._elementListeners.forEach(([context, ...args]) => { context.removeEventListener(...args); - }) + }); }, destroy() { From 205f16941b26d08893a4b3fa36dfb907c89b71b2 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Wed, 8 Jul 2015 18:22:18 -0400 Subject: [PATCH 32/77] add npm scripts to build and deploy website * commit built website to website/ --- bin/build-website.sh | 21 + bin/deploy-website.sh | 3 + demo/index.html | 2 +- demo/website-index.html | 10 + package.json | 4 +- website/css/content-kit-editor.css | 606 ++ website/demo/demo.css | 151 + website/demo/demo.js | 76 + website/demo/favicon.ico | Bin 0 -> 1065 bytes website/demo/index.html | 64 + website/demo/jquery/jquery.js | 9210 ++++++++++++++++++++++++++ website/demo/website-index.html | 10 + website/global/content-kit-editor.js | 4208 ++++++++++++ website/index.hml | 10 + 14 files changed, 14373 insertions(+), 2 deletions(-) create mode 100755 bin/build-website.sh create mode 100755 bin/deploy-website.sh create mode 100644 demo/website-index.html create mode 100644 website/css/content-kit-editor.css create mode 100644 website/demo/demo.css create mode 100644 website/demo/demo.js create mode 100644 website/demo/favicon.ico create mode 100644 website/demo/index.html create mode 100644 website/demo/jquery/jquery.js create mode 100644 website/demo/website-index.html create mode 100644 website/global/content-kit-editor.js create mode 100644 website/index.hml diff --git a/bin/build-website.sh b/bin/build-website.sh new file mode 100755 index 000000000..0c4a33344 --- /dev/null +++ b/bin/build-website.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +echo "Building website..." +npm run build + +echo "Arranging built website in website/" +rm -rf website +mkdir website + +# rename demo/website-index.html to be the base index.html +cp dist/demo/website-index.html website/index.hml + +# selectively copy asset dirs from dist to the staging area +cp -R dist/demo website/demo +cp -R dist/css website/css +cp -R dist/global website/global + +CURRENT_SHA="$(git rev-parse HEAD)" +git add website/ +git commit -m "built website from $CURRENT_SHA" +echo "Done." diff --git a/bin/deploy-website.sh b/bin/deploy-website.sh new file mode 100755 index 000000000..7f6f35adb --- /dev/null +++ b/bin/deploy-website.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +git push origin `git subtree split --prefix website`:gh-pages --force diff --git a/demo/index.html b/demo/index.html index 398debdb5..1992c4058 100644 --- a/demo/index.html +++ b/demo/index.html @@ -2,7 +2,7 @@ - ContentKit Editor + Content Kit Editor Demo 0.2.0 diff --git a/demo/website-index.html b/demo/website-index.html new file mode 100644 index 000000000..9f2c4f1bf --- /dev/null +++ b/demo/website-index.html @@ -0,0 +1,10 @@ + + + + Content Kit Editor 0.2.0 + + + + Click to view the Demo. + + diff --git a/package.json b/package.json index 47d440ebc..7a720767b 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,9 @@ "scripts": { "start": "broccoli serve", "test": "testem ci", - "build": "rm -rf dist && broccoli build dist" + "build": "rm -rf dist && broccoli build dist", + "build-website": "./bin/build-website.sh", + "deploy-website": "./bin/deploy-website.sh" }, "keywords": [ "html", diff --git a/website/css/content-kit-editor.css b/website/css/content-kit-editor.css new file mode 100644 index 000000000..c6118cd01 --- /dev/null +++ b/website/css/content-kit-editor.css @@ -0,0 +1,606 @@ +/** + * Animations + */ +@-webkit-keyframes fade-in { + 0% { + opacity: 0; + } + 100% { + opacity: 1; + } +} +@keyframes fade-in { + 0% { + opacity: 0; + } + 100% { + opacity: 1; + } +} +@-webkit-keyframes spin { + to { + -webkit-transform: rotate(360deg); + } +} +@keyframes spin { + to { + transform: rotate(360deg); + } +} +@-webkit-keyframes shake { + 0%, + 100% { + -webkit-transform: translateX(0); + } + 20%, + 60% { + -webkit-transform: translateX(-10px); + } + 40%, + 80% { + -webkit-transform: translateX(10px); + } +} +@keyframes shake { + 0%, + 100% { + transform: translateX(0); + } + 20%, + 60% { + transform: translateX(-10px); + } + 40%, + 80% { + transform: translateX(10px); + } +} +@-webkit-keyframes textGlimmer { + 0% { + background-position: -288px 0; + } + 100% { + background-position: 288px 0; + } +} +@-webkit-keyframes pop-out { + 0% { + opacity: 0.8; + -webkit-transform: scale(0.8); + } + 50% { + opacity: 1; + -webkit-transform: scale(1.1); + } +} +@keyframes pop-out { + 0% { + opacity: 0.8; + transform: scale(0.8); + } + 50% { + opacity: 1; + transform: scale(1.1); + } +} +@-webkit-keyframes pop-up { + 0% { + opacity: 0.8; + -webkit-transform: scale(0.9) translateY(14px); + } + 50% { + opacity: 1; + -webkit-transform: scale(1.05) translateY(-4px); + } +} +@keyframes pop-up { + 0% { + opacity: 0.8; + transform: scale(0.9) translateY(14px); + } + 50% { + opacity: 1; + transform: scale(1.05) translateY(-4px); + } +} +@-webkit-keyframes pop-right { + 0% { + opacity: 0.8; + -webkit-transform: scale(0.9) translateX(-14px) translateY(-50%); + } + 50% { + opacity: 1; + -webkit-transform: scale(1.05) translateX(4px) translateY(-50%); + } +} +@keyframes pop-right { + 0% { + opacity: 0.8; + transform: scale(0.9) translateX(-14px); + } + 50% { + opacity: 1; + transform: scale(1.05) translateX(4px); + } +} +@-webkit-keyframes slide-down { + 0% { + -webkit-transform: translateY(-100%); + } + 100% { + -webkit-transform: none; + } +} +@keyframes slide-down { + 0% { + transform: translateY(-100%); + } + 100% { + transform: none; + } +} +/** + * Editor + */ +.ck-editor { + font-family: 'Lora', Georgia, serif; + margin: 1em 0; + color: #454545; + /* + Chrome bug adds inline styles when backspacing to join 2 blocks. + Fix: Apply font styles to parent element, or use % for font-size, line-height. + http://stackoverflow.com/questions/15015019/prevent-chrome-from-wrapping-contents-of-joined-p-with-a-span + */ + font-size: 120%; + line-height: 160%; +} +.ck-editor:focus { + outline: none; +} +.ck-editor:empty:before { + content: attr(data-placeholder); + color: #bbb; +} +.ck-editor > * { + position: relative; +} +.ck-editor a { + color: #0b8bff; +} +.ck-editor h1, +.ck-editor h2, +.ck-editor h3, +.ck-editor h4, +.ck-editor h5, +.ck-editor h6 { + font-family: 'Merriweather Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif; + font-weight: 800; + letter-spacing: -0.02em; +} +.ck-editor blockquote { + border-left: 4px solid #0b8bff; + margin: 1em 0 1em -1.2em; + padding-left: 1.05em; + color: #a0a0a0; +} +.ck-editor img { + display: block; + max-width: 100%; + margin: 0 auto; +} +.ck-editor div, +.ck-editor iframe { + max-width: 100%; +} +/** + * Embeds + */ +.ck-embed-intent { + position: absolute; +} +.ck-embed-intent .ck-toolbar { + min-width: 100px; + left: 40px; + top: 50%; + -webkit-transform: translateY(-50%); + transform: translateY(-50%); +} +.ck-embed-intent-btn { + position: relative; + display: block; + background: none; + border: none; + outline: none; + margin: 0 0.4em 0 0; + padding: 0; + width: 1em; + height: 1em; + border: 2px solid #ccc; + border-radius: 100%; + color: #ccc; + text-align: center; + font-size: 2em; + line-height: 0.7em; + cursor: pointer; + transition: color 0.1s, border-color 0.1s, transform 0.35s; + -webkit-animation: pop-out 0.25s; + animation: pop-out 0.25s; +} +.ck-embed-intent-btn:hover { + color: #999; + border-color: #999; +} +.ck-embed-intent-btn:active { + color: #666; + border-color: #666; + transition: none; +} +.ck-embed-intent-btn:before { + content: '+'; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; +} +.activated .ck-embed-intent-btn { + -webkit-transform: rotate(-135deg); + transform: rotate(-135deg); +} +.ck-embed-loading { + position: absolute; + top: 0; + left: 50%; + margin-left: -0.75em; + width: 1.5em; + height: 1.5em; + border-radius: 50%; + border: 2px solid #ddd; + border-top-color: #3ea3ff; + animation: spin .5s linear infinite; + -webkit-animation: spin .5s linear infinite; +} +.ck-file-input { + display: none; +} +.ck-embed { + text-align: center; + margin: 1em 0; + -moz-user-select: none; + -webkit-user-select: none; + -ms-user-select: none; + user-select: none; +} +.ck-embed.selected figure { + border: 4px solid #3ea3ff; + margin: -4px; +} +.ck-embed iframe { + margin: 0 auto !important; + width: 100% !important; +} +.ck-embed figure { + position: relative; + margin: 0; +} +.ck-embed figcaption { + color: #999; + font-size: 0.7em; + line-height: 1.35em; + font-style: italic; + margin: 10px 0; +} +.ck-embed figcaption a { + color: #999; + text-decoration: none; +} +.ck-embed figcaption a:hover { + color: #666; + text-decoration: underline; +} +@media screen and (min-width: 1080px) { + .ck-embed figcaption { + position: absolute; + top: 0; + right: -130px; + width: 130px; + text-align: left; + margin: 0; + padding-left: 2em; + } +} +.ck-video-container { + position: relative; + overflow: hidden; + padding-top: 56.25%; +} +.ck-video-container iframe, +.ck-video-container object, +.ck-video-container embed { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; +} +.ck-image-embed { + -webkit-animation: fade-in 1s; + animation: fade-in 1s; +} +/** + * Icons + */ +@font-face { + font-family: 'ck-icons'; + src: url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAALAIAAAwAwT1MvMggi/LwAAAC8AAAAYGNtYXAaVcxdAAABHAAAAExnYXNwAAAAEAAAAWgAAAAIZ2x5Zl5vXY0AAAFwAAAIgGhlYWQBGRzWAAAJ8AAAADZoaGVhBAgCEAAACigAAAAkaG10eA3eACQAAApMAAAALGxvY2EH2AnkAAAKeAAAABhtYXhwABAAtgAACpAAAAAgbmFtZdoByAQAAAqwAAABWnBvc3QAAwAAAAAMDAAAACAAAwIAAZAABQAAAUwBZgAAAEcBTAFmAAAA9QAZAIQAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAABAAADmBgHg/+D/4AHgACAAAAABAAAAAAAAAAAAAAAgAAAAAAACAAAAAwAAABQAAwABAAAAFAAEADgAAAAKAAgAAgACAAEAIOYG//3//wAAAAAAIOYA//3//wAB/+MaBAADAAEAAAAAAAAAAAAAAAEAAf//AA8AAQAAAAAAAAAAAAIAADc5AQAAAAABAAAAAAAAAAAAAgAANzkBAAAAAAEAAAAAAAAAAAACAAA3OQEAAAAAAwAAAAABkgG3AE8AbgCNAAA/ATY3Njc2NzY3Njc0NzQ9ARAnJicmJyYnJiMmIycyNzYzMjMyMzIXFhcWFxYXFhUUBwYHBgcGBwYHFhcWFRQHBgcGBwYHBiMiJyYjIgcGIxMUFxYVFAcUFRQXFjMyNzY3Njc2NTQnJicmJyYjIgcTFBcWFxYzMjU0JyYnJicmJyYjJiMiBxQHFBUUFRQVAAEEFBQKAgIBAQEBAQcBBQUIBwcGCAcBARxFRSUHDQ0GFBMTEhINDQgIBQUGBgwMCQkPLB0dCgoQERcXGBgaDBoZDB85OQmYAQIBAQwTFxIRDg4HCAkIDg8QERMOFwIBAQMVE2sMBwoKCgkODQsKERQIAQAbAQMEBAQEBAUGBAQGBwMTARgNAgICAQEBAQEYAwMEBAgIDAwSEhYODQwICQgIBQQHChwdKh0XFg8OCgoEBAEBBAMBlg8cHQ8IDw8HDQcCBAMJCRERGBQPDwgIBAQD/r4LDQ0GCV8hEwwJCQQFAgMBAw8eHw4DEREKAAAAAAEAAAAAASUBtwBOAAA/ATI3Njc2NzQ3Njc2PQEmJyYnJiM3FhcWFxYzMjc2NzY3BgcGBwYHBgcGFQYHBhUGBwYHFAcGBwYHBhcVFhcGByIHIiMiJyYjIiMiBwYjAAUCFRYKCAQREg8PBwkIDAsFBQoZGBISEQ0PDhQVCAIECBUUCwICAgECAQgREgUDAwMDAgIBBTABBAMGBgMJEBEIJxQOGhsIARgGBgUKEwJQUUpLCgcEAgEBAR4BAQEBAQEBAQEBCw8CBgUEBgYHBQUICAQqTk0YAw4ODAsMDQQFAQgMEAEDAwIDAAAEAAAAAAIlAbcAFAApADEAQgAANxE0NzYzITIXFhURFAcGIyEiJyY1MxQXFjMhMjc2NRE0JyYjISIHBhURNzU3FzcXFSE1NDc2MzIXFhUUBwYjIicmNQANDhMByRMNDg4NE/43Ew4NJQIDBAHJBAIDAwIE/jcEAwIkXC2Tdv5uEBAXFxAQEBAXFxAQLgFbEw0ODg0T/qUTDg0NDhMEAwICAwQBWwQDAgIDBP6lGzdbLZJ3gO4XEBAQEBcXEBAQEBcAAAAAAwAFAAUB1wHXACgAVACAAAATND8BNhc2HwEWFRQHFzYXNh8BFhUUDwEGByYvASY1NDcnBgcmLwEmNRcUHwEWNxY3IicmJyYnJicmNTQ3NjcWMxYXFhcWFxY3NjU0LwEmByYPAQYVFxQfARY3Fj8BNjU0LwEmJwYHFBcWFxYXFhcWFRQHBicGJyInJicmJyYnBhUFGCoYIiIYOxgZGRgjIhg8GBgqGCIjGDsXGRkZIyIYOxg2CDwICwwJAQUEAgEDAwEBCAgMBAQDBAQBAgQFAQkIOwgLCwkqCMkIOwgMCwgqCAg7CAwMCAUFAQICAwEBCAgLBQMEAwQCAgQEAQoBWyIYKRkBARk7GCIkFxoaAQEZOxkhIxcrFgEBFzwXIyIaGBgBARc8FyMBCgk6CQEBCgUDAwEFAgUCBgoJBwEBAgIDAQIEBgEHDQsJOgkBAQkoCQvKCgk7CAEBCCkJCgwHPQcBAQgCBAUBAgMFAgUDDQcJAQECBAICAQUEAgoLAAAAAwANAAUCGAGNABoALwBKAAA3ND8BNjMyHwEWFRQPARcWFRQPAQYjIi8BJjUXEzY3Nh8BFhcWBwMGBwYvASYnJjc3ND8BJyY1ND8BNjMyHwEWFRQPAQYjIi8BJjUNA4UDAwQDDgMDcHADAw4DBAMDhQO+awEDBAMSBAECAWoCAwMEEQQCAgGmA3FxAwMPAgQEA4UDA4UDBAQCDwPJBAOFAwMOAwQEA3BwAwQDAw8CAoYCBLMBcQMCAgEFAQMEA/6PBAICAQUBBAMEPAQDcHADBAQDDgMDhQMEBAKGAgIPAwMAAAAAAQASAAAB7gG3ALMAABM0NzYzMhcWMzI3NjMyFxYVFAcGByIHBgcGHQEUFRY7ATI3NDU3NCcmIyInJjU0NzYzMhcWMzI3NjMyFxYVFAcGIyIHIgcGFREUFxYXFjMyFxYVFAcGIyInJiMiBwYjIicmNTQ3NjcyNzY3NjUnNDUmKwEiBxQdARQXFhcWMzIXFhUUBwYjIicmIyIHBiMiJyY1NDc2NzI3Njc2NSc1MDc0NSY1NCcmJyYnJicmIyYjIicmNRIDBAYOGhoODBgYDAcEAwUFBgYICAQKBAjHBwQBCgUMDAcHAwQHDRkZDQwYGQwHBAQFBQcGCQgECgoECQkGBwUFAwQGDRkaDA0ZGQ0HAwQFBQYGCAkECgEECsELBAoFCQkHCAUGBAMHDRsaDQ0YGAwHAwQEBQYGBwgECgEBAQEBAQECAgIFCAkGBwUFAaMHBwYBAQEBBgcHCQQDAQEBAwYnXAYDAQEDBlwnBgQEAwsHBwYBAQEBBgcHCQQEAQMHJ/7yIgYDAQEEBAkHBwYBAQEBBgYHCQQEAQIBAwYicAYDAQEDBmopBgMBAQQECQcHBgEBAQEGBgcIBQQBAgEDByIQ6QcHAwQHCAQFBgUEAwIDAQQECQAAAAIAAAAbAgEBewAlAEsAADcyHgIVFA4CIyIuAjUnND4CMxUiDgIHDgMHMjY6ATMhMh4CFRQOAiMiLgI1JzQ+AjMVIg4CBw4DBzI2OgEzcBcoHxESHygXGCgfEQEjPVIuEB8dGgsCBAQEAgIEBQQCASAXKB8REh8oFxgoHxEBIz1SLhAfHRoLAgQEBAICBAUEAvsRHygYFykeEhIeKRcQL1E9I0AGDBELAwQFBQIBER8oGBcpHhISHikXEC9RPSNABgwRCwMEBQUCAQAAAAEAAAABAABSja6rXw889QALAgAAAAAAz+ruAQAAAADP6u4BAAAAAAIlAdcAAAAIAAIAAAAAAAAAAQAAAeD/4AAAAiUAAP//AiUAAQAAAAAAAAAAAAAAAAAAAAsAAAAAAAAAAAAAAAABAAAAAZMAAAElAAACJQAAAdwABQIlAA0CAAASAgAAAAAAAAAACgAUAB4A5gFaAbwCfALuA9oEQAABAAAACwC0AAQAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAADgCuAAEAAAAAAAEAEAAAAAEAAAAAAAIADgBaAAEAAAAAAAMAHAAmAAEAAAAAAAQAEABoAAEAAAAAAAUAFgAQAAEAAAAAAAYACABCAAEAAAAAAAoANAB4AAMAAQQJAAEAEAAAAAMAAQQJAAIADgBaAAMAAQQJAAMAHAAmAAMAAQQJAAQAEABoAAMAAQQJAAUAFgAQAAMAAQQJAAYAEABKAAMAAQQJAAoANAB4AGMAawAtAGkAYwBvAG4AcwBWAGUAcgBzAGkAbwBuACAAMQAuADAAYwBrAC0AaQBjAG8AbgBzADoAIAAyADAAMQA0Y2staWNvbnMAYwBrAC0AaQBjAG8AbgBzAFIAZQBnAHUAbABhAHIAYwBrAC0AaQBjAG8AbgBzAEYAbwBuAHQAIABnAGUAbgBlAHIAYQB0AGUAZAAgAGIAeQAgAEkAYwBvAE0AbwBvAG4ALgAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=) format('truetype'), url(data:application/font-woff;charset=utf-8;base64,d09GRk9UVE8AAA1gAAoAAAAADRgAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABDRkYgAAAA9AAACaoAAAmqfszNZk9TLzIAAAqgAAAAYAAAAGAIIvy8Y21hcAAACwAAAABMAAAATBpVzF1nYXNwAAALTAAAAAgAAAAIAAAAEGhlYWQAAAtUAAAANgAAADYBGRzWaGhlYQAAC4wAAAAkAAAAJAQIAhBobXR4AAALsAAAACwAAAAsDd4AJG1heHAAAAvcAAAABgAAAAYAC1AAbmFtZQAAC+QAAAFaAAABWtoByARwb3N0AAANQAAAACAAAAAgAAMAAAEABAQAAQEBCWNrLWljb25zAAECAAEAOvgcAvgbA/gYBB4KABlT/4uLHgoAGVP/i4sMB4tr+Ln4dAUdAAAAnQ8dAAAAohEdAAAACR0AAAmhEgAMAQEJERMVGB0iJywxNjtjay1pY29uc2NrLWljb25zdTB1MXUyMHVFNjAwdUU2MDF1RTYwMnVFNjAzdUU2MDR1RTYwNXVFNjA2AAACAYkACQALAgABAAQABwAKAA0ByAK/A5wFNwY+CHEI5fyUDvyUDvyUDvuUDvsBi4sVjKYFjYyUjJiNmI6VjZKOjI2NjoyOjI6MjouOjI+LjoyOi42Lj4yPi5CLjouNCIueBYv3T4nthpOLjImNh4yIjIaMhoyGjIeMhouHi4aMhouHjIiLiosIiqMFnYusjLmNuY2ujKSLkIuRi5SLlIuRi4+LmIuYiZiJmIiXh5eGl4WVhZSDk4OTgZB/CJB/jn6LfIuCiYGIg4iDh4SHhoeFhYaDhYOGhIaFiIWIg4eBh6iEo36feZ94lHOLbwiLeIh6hHuFfIJ/gIF/gX6DfIV8hHuHe4h7iHuKeYuDi36Leox7i36Mg4t3i22KZYgIZYl1ioWLCPcs+CoVi4GMfYt4jHeMfYuBi4aLg4qBi4GLhIuGi4KLhIyHk4qVipiLmouZjJeOlo2Wj5SRCJSRkpSQlpCWjpmLm4uYiJeFlYaVg5KCkYGRgY+AjYCOf4x+i4KLf4p7iQiN+9YVi4SLg4yCjIKMhY2HmYWYiJiL0ouvq4vKi6GHnIOYhpOFkoWRhJGFj4SOhY6DjoKMCIKNg4yEi4SMgouAi36LgYqGiYuBi3yKd4t3i3uLgouJi4WLf4uAi4KLhAgO+2+LjBWQowWMi5ONmY+aj5WOko+QkY+VjpiLjJGmlsGXwZa/lbyVvZCni5IIi5IFho6GjYWMhYyFi4OMhIuFjIiLCJCpBZKKloucipuKmYqXi5eLl4qWi5SLlIyVi5SLl4yYjJmMlIuRjIqDiYOIgYWKgoh9hwh+iICIhIiKh4mHioeKhoqHi4iKiIqHioWLhoqHi4iFb4NjgFd/WIRph3uLiYqFiYIIiYKJgomDiYSKg4mDioKLhouICIuGBY6KnYirhoqDioGIgYmLiIuHioeLiIuJi4WLg4yAjYCNg4yFi3GLd4t+i4KLfYp6igh5iYCKhYsIDrCLuRWL9+8Fi5iPlZSUlJSWkJiLCPhdiwWXi5aGlIKUgpCBi34Ii/vvBYt+hoCCgoKCgId/iwj8XYsFfouAj4KUgpSHlouYCLCLFYuIi4mNiY2JjYuOiwj4XYsFjYuNi42NjY2MjYuOCIv37wWLjoqNiY2JjImMiYsI/F2LBYiLiYqJiomJi4mLiAiL++8Fr6YVi8Ln5rhe9yf3JvcK+wuL+xT8JosFi/eCFYuakJiWlpaVmJGai5qLmIWWgZaAkH6LfIt8hn6AgICAfoZ8i3yLfpCAloCWhpiLmggOZ5D37xWLopOfm5oItbUFm5uek6KLooueg5t7CMZPBZt8k3eLdIt0gnd7ewikcgWbm5+Uoouii56Dm3sIx08Fm3uTeIt0i3SDeHt7CGFhBXt7d4R1i3SLd5N7mwhQxgV8m4Oei6KLopOfnJwIcqQFenp4g3OLdIt4k3ubCFDGBXubg5+LoQjBixWLhI6EkIYIx1AFkIWRiZOLk4uSjpGRiouJjYiOiI6JjYqMioyKjYmOiY2KjYqOi42KjouOi5KOkpCQCJGQkY6Ti46LjYuOio2KjYqOiY2KjYmMioyKjYmOiI6IjYmMi5GQjpKLk4uTiJKGkAhQxgWGkISOhIuDi4WIhYYIYWIFhoWIhYuDCPdd+10Vi4OOhZCGCMZPBZCGkomTi5KLko2QkAi1tQWQkI6Si5KLk4iRhpAIUMcFhZCFjoOLg4uEiIaFi4qNiY6IjoiNiYyKjIqNiYyJjYiMiYyJjIiLiYuIi4OIhYaFCIaGhIiEi4iLiIyJi4iMiYyJjYiNiYyKjIqMiY2IjoiOiY2LjISFiISLgwgOsJj3XRWLjoyNjY0I9xn3GQWNjY2MjYuOi42KjYkImX0FjYmMiIuJi4mKiImJCPsE+wT3BPsEBY2JjImLiIuJiomJiQh9fAWJiomKiIuJi4mMiYwI+xn3GgWJjIqOi40I91L7RxX2+AUFjI2MjY2MjoyNjI2KCJ2GBY2KjYqMiY2Ii4mKiQgh/AUFioiJiYmKiYqJi4iLCHqQBYiMiY2KjYqNi42Ljgj3OscVi46MjY2NCPcF9wT7BfcEBYmNio6LjYuNjI6NjQiamQWMjY6MjYuOi42KjYkI9xn7GQWNiYyJi4iLiYqIiYoI+xn7GgWJiomKiIuJi4iMiowIfJoFiY2KjYuNCA6d+DcVi5CMj42QjY+PjY+LlIuYi52KnYqYi5SLk4uXi5uMm4yXi5OLkIuOiY6HjYaMh4uGCIuFioeHiIiJh4mHi4eLhouGioaLh4mIiYSHiHyLcQiLLwWLh4uIi4mOi4+KkIsI91uLBZCLj4yNi4uNi46LjwiM5wWLpYeahY+HjoaMg4uDi4WNho2GjYmQi5KLkIyPjZCOj46NkIuUi5eLnIqcipeLlIsIk4uXi5uMnIyXi5OLkIuPiY2HjYaNh4uGi4WJh4iIh4mHiYeLh4uGi4WKhouHioiJCISGiHyLcQiL+6IFi3WOfZKHjomPipGKkYuQio+LkIuPiY6Jj4iMh4uFi4aKhomHiYeHiYeLgot/i3qMCHqMfouDi4KLf4t6inqKf4uCi4eLh42Jj4iPio+LkIuRjI+Pjo6Oj4yPjI+LkIyQjAiRjI+Mjo2Sj46Yi6IIivcEBYuPi46LjYmLhoyEiwj7VYsFhIuGioiLi4mLiIuHCIshBYtwjnuSh46JkIqRipGLkYqPi5CLj4qPiI+IjYeLhYuGioaIh4mHiImGi4KLfot5jAh6jH2Lg4uCi3+Le4p7in+Lg4uGi4iNiY+Ij4qPi5CLkYyPjo6Ojo+Mj4yPi4+MkIwIkIyPjI6NkpCOmIuiCIqbi/d9BYuLi46Mj4uPi4+LjYqOi4+Lj4uQi4+KjouPio6Kj4uPiY6KjYqNiY2KjIiNhoyGiwiFjIaLh4uGi4eMiI6HjoqPi5EIDvcF948VyIu+WYtNi05YWE6LTYtZvovICIqbBYv3EO/v9xCLCItLBWCLY3ttbYWFhoWGhJGMkYuRiwj3tIsVyIu+WYtNi05YWE6LTYtZvovICIqbBYv3EO/v9xCLCItLBWCLY3ttbYWFhoWGhJGMkYuRiwgO+JQU+JQViwwKAAAAAwIAAZAABQAAAUwBZgAAAEcBTAFmAAAA9QAZAIQAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAABAAADmBgHg/+D/4AHgACAAAAABAAAAAAAAAAAAAAAgAAAAAAACAAAAAwAAABQAAwABAAAAFAAEADgAAAAKAAgAAgACAAEAIOYG//3//wAAAAAAIOYA//3//wAB/+MaBAADAAEAAAAAAAAAAAAAAAEAAf//AA8AAQAAAAEAAGLPbdVfDzz1AAsCAAAAAADP6u4BAAAAAM/q7gEAAAAAAiUB1wAAAAgAAgAAAAAAAAABAAAB4P/gAAACJQAA//8CJQABAAAAAAAAAAAAAAAAAAAACwAAAAAAAAAAAAAAAAEAAAABkwAAASUAAAIlAAAB3AAFAiUADQIAABICAAAAAABQAAALAAAAAAAOAK4AAQAAAAAAAQAQAAAAAQAAAAAAAgAOAFoAAQAAAAAAAwAcACYAAQAAAAAABAAQAGgAAQAAAAAABQAWABAAAQAAAAAABgAIAEIAAQAAAAAACgA0AHgAAwABBAkAAQAQAAAAAwABBAkAAgAOAFoAAwABBAkAAwAcACYAAwABBAkABAAQAGgAAwABBAkABQAWABAAAwABBAkABgAQAEoAAwABBAkACgA0AHgAYwBrAC0AaQBjAG8AbgBzAFYAZQByAHMAaQBvAG4AIAAxAC4AMABjAGsALQBpAGMAbwBuAHMAOgAgADIAMAAxADRjay1pY29ucwBjAGsALQBpAGMAbwBuAHMAUgBlAGcAdQBsAGEAcgBjAGsALQBpAGMAbwBuAHMARgBvAG4AdAAgAGcAZQBuAGUAcgBhAHQAZQBkACAAYgB5ACAASQBjAG8ATQBvAG8AbgAuAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==) format('woff'); + font-weight: normal; + font-style: normal; +} +.ck-icon-bold, +.ck-icon-italic, +.ck-icon-image, +.ck-icon-link, +.ck-icon-embed, +.ck-icon-heading, +.ck-icon-quote { + font-family: 'ck-icons'; + speak: none; + font-style: normal; + font-weight: normal; + font-variant: normal; + text-transform: none; + line-height: 1; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} +.ck-icon-bold:before { + content: "\e600"; +} +.ck-icon-italic:before { + content: "\e601"; +} +.ck-icon-image:before { + content: "\e602"; +} +.ck-icon-link:before { + content: "\e603"; +} +.ck-icon-embed:before { + content: "\e604"; +} +.ck-icon-heading:before { + content: "\e605"; +} +.ck-icon-quote:before { + content: "\e606"; +} +.ck-message { + position: fixed; + left: 0; + right: 0; + height: 3em; + line-height: 3em; + top: -3em; + z-index: 2; + padding: 0 1em; + font-weight: 500; + text-align: center; + background-color: rgba(103, 182, 255, 0.98); + border-bottom: 1px solid #4daaff; + -webkit-animation: messageShowHide 3.2s; + animation: messageShowHide 3.2s; +} +.ck-message-error { + color: #a33a3a; + background-color: rgba(233, 106, 106, 0.98); + border-bottom: 1px solid #e75d5d; +} +@-webkit-keyframes messageShowHide { + 8% { + top: 0; + } + 92% { + top: 0; + } + 100% { + top: -3em; + } +} +@keyframes messageShowHide { + 8% { + top: 0; + } + 92% { + top: 0; + } + 100% { + top: -3em; + } +} +/** + * Toolbar + */ +.ck-toolbar { + text-align: center; + position: absolute; + z-index: 1; + transition: left 0.1s, top 0.1s; + margin-bottom: 0.45em; +} +.ck-toolbar:after { + content: ''; + position: absolute; + left: 50%; + width: 0; + height: 0; + border-left: 0.45em solid transparent; + border-right: 0.45em solid transparent; + border-top: 0.45em solid #2b2b2b; + bottom: -0.4em; + margin: 0 0 0 -0.45em; +} +.ck-toolbar.right { + margin: 0 0 0 0.5em; +} +.ck-toolbar.right:after { + left: -0.4em; + top: 50%; + bottom: auto; + margin: -0.45em 0 0 0; + border-top: 0.45em solid transparent; + border-bottom: 0.45em solid transparent; + border-right: 0.45em solid #3d3d3d; + border-left: none; +} +.ck-toolbar, +.ck-toolbar-prompt { + -webkit-animation: pop-up 0.25s; + animation: pop-up 0.25s; +} +.ck-toolbar.right { + -webkit-animation: pop-right 0.25s; + animation: pop-right 0.25s; +} +.ck-toolbar.sticky { + position: fixed; + top: 0; + left: 0; + right: 0; + transition: none; + border-radius: 0; + margin: 0; + border-bottom: 1px solid #e0e0e0; + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03); + background: linear-gradient(to bottom, rgba(252, 252, 252, 0.92) 0%, rgba(252, 252, 252, 0.97) 100%); + box-shadow: none; + -webkit-animation: slide-down 0.25s; + animation: slide-down 0.25s; +} +.ck-toolbar.sticky:after { + content: none; +} +.sticky .ck-toolbar-btn { + color: #454545; + text-shadow: none; +} +.sticky .ck-toolbar-btn:hover, +.sticky .ck-toolbar-btn:active { + background-color: #eee; +} +.ck-toolbar-content { + border-radius: 3px; + background: linear-gradient(to bottom, rgba(74, 74, 74, 0.97) 0%, #2b2b2b 100%); + box-shadow: 0 1px 3px -1px rgba(0, 0, 0, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.12), inset 1px 1px 0 #282828, inset -1px -1px 0 #282828; +} +.ck-toolbar-buttons { + border-radius: 5px; + overflow: hidden; + white-space: nowrap; +} +.ck-toolbar-btn { + display: inline-block; + background-color: transparent; + border: none; + outline: none; + color: #FFF; + font-size: 18px; + padding: 0; + margin: 0; + width: 48px; + height: 44px; + line-height: 42px; + cursor: pointer; + transition: background-color 0.1s linear; + text-shadow: 0 1px 1px rgba(0, 0, 0, 0.65); + -moz-user-select: none; + -webkit-user-select: none; + -ms-user-select: none; +} +.ck-toolbar-btn:hover { + background-color: rgba(43, 43, 43, 0.4); +} +.ck-toolbar-btn:active { + background-color: rgba(43, 43, 43, 0.65); +} +.ck-toolbar-btn:active, +.ck-toolbar-btn.active { + color: #3ea3ff; +} +.ck-toolbar-prompt { + display: none; +} +.ck-toolbar-prompt input { + background: none; + border: none; + color: #f5f5f5; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 14px; + padding: 0 16px; + width: 288px; + height: 44px; + line-height: 1em; +} +.ck-toolbar-prompt input:focus { + outline: none; +} +.ck-toolbar-prompt input::-ms-clear { + display: none; +} +.ck-toolbar-prompt ::-webkit-input-placeholder { + background-color: #a2a2a2; + background-image: -webkit-gradient(linear, left top, right top, color-stop(0, #a2a2a2), color-stop(0.4, #a2a2a2), color-stop(0.5, white), color-stop(0.6, #a2a2a2), color-stop(1, #a2a2a2)); + background-repeat: no-repeat; + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; + -webkit-animation: textGlimmer 4s infinite; +} +.ck-editor-hilite { + position: absolute; + z-index: -1; + background-color: rgba(62, 163, 255, 0.05); + border-bottom: 2px dotted #3ea3ff; +} +/** + * Tooltip + */ +.ck-tooltip { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 0.7em; + white-space: nowrap; + position: absolute; + background-color: rgba(43, 43, 43, 0.9); + border-radius: 3px; + line-height: 1em; + padding: 0.7em 0.9em; + color: #FFF; + -webkit-animation: fade-in 0.2s; + animation: fade-in 0.2s; +} +.ck-tooltip:before { + content: ''; + position: absolute; + left: 50%; + width: 0; + height: 0; + border-left: 0.4em solid transparent; + border-right: 0.4em solid transparent; + border-bottom: 0.4em solid rgba(43, 43, 43, 0.9); + top: -0.4em; + margin-left: -0.4em; +} +.ck-tooltip:after { + /* help keeps mouseover state when moving from link to tooltip */ + content: ''; + position: absolute; + left: 0; + right: 0; + top: -0.4em; + height: 0.4em; +} +.ck-tooltip a { + color: #FFF; + text-decoration: none; +} +.ck-tooltip a:hover { + text-decoration: underline; +} diff --git a/website/demo/demo.css b/website/demo/demo.css new file mode 100644 index 000000000..341e0a067 --- /dev/null +++ b/website/demo/demo.css @@ -0,0 +1,151 @@ +*, +*:before, +*:after { + box-sizing: border-box; +} + +body { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + color: #454545; + margin: 0; + padding: 0; + background-color: #EFEFEF; +} +@media only screen and (max-width: 767px) { + body { + font-size: 0.88em; + } +} + +.container { + display: flex; + justify-content: space-around; +} + +.pane { + max-width: 25%; +} + +.editor-pane { + max-width: 50em; + margin: 0 auto; + padding: 3em 1.45em; + width: 100%; + position: relative; +} +.code-pane-open .editor-pane { + width: 50%; + margin: 0; +} + +.demo-buttons { + position: fixed; + top: 0; + right: 0; + z-index: 2; +} +.demo-buttons a { + display: block; + cursor: pointer; + font-size: 24px; + padding: 9px 12px; + color: #2b303b; + text-shadow: 0 1px 2px rgba(252,252,252,0.7), 0 -1px 2px rgba(252,252,252,0.7), 1px 0 2px rgba(252,252,252,0.7), -1px 0 2px rgba(252,252,252,0.7); +} + +.code-panes { + position: fixed; + top: 0; + bottom: 0; + right: -50%; + width: 0; + z-index: 1; +} +.code-pane-open .code-panes { + right: 0; + width: 50%; +} +#serialized-mobiledoc, #mobiledoc-to-load { + overflow: hidden; + padding: 0.25em; +} +#serialized-mobiledoc { + white-space: pre; + background-color: #080808; +} +#mobiledoc-to-load { +} +#mobiledoc-to-load textarea { + height: 300px; +} + +.code-pane:first-child { + display: block; +} +.code-pane code { + white-space: pre-wrap; + font-family: Consolas, Menlo, Courier, monospace; + font-size: 0.75em; + line-height: 1.2em; + background-color: transparent; + color: #c0c5ce; + padding: 5em 1em 1em; + overflow: auto; + -webkit-overflow-scrolling: touch; + position: absolute; + top: 0; + right: 0; + left: 0; + bottom: 0; +} +.code-pane label { + font-size: 0.8em; + color: #c0c5ce; + background: rgba(30,40,48,0.92); + padding: 0.5em 0.75em; + position: absolute; + z-index: 1; + top: 0; + right: 0; + border-radius: 0 0 0 3px; + border-left: 1px solid rgba(192,197,206,0.25); + border-bottom: 1px solid rgba(192,197,206,0.25); +} + +@font-face { + font-family: 'demo-icons'; + src: url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAALAIAAAwAwT1MvMggi/LYAAAC8AAAAYGNtYXAaVcxXAAABHAAAAExnYXNwAAAAEAAAAWgAAAAIZ2x5ZmOrGnQAAAFwAAABxGhlYWQBePfEAAADNAAAADZoaGVhA5kB5gAAA2wAAAAkaG10eAMAAAAAAAOQAAAAFGxvY2EAKAD2AAADpAAAAAxtYXhwAAgAhgAAA7AAAAAgbmFtZRP8/tEAAAPQAAABYHBvc3QAAwAAAAAFMAAAACAAAwIAAZAABQAAAUwBZgAAAEcBTAFmAAAA9QAZAIQAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAABAAADmAAHg/+D/4AHgACAAAAABAAAAAAAAAAAAAAAgAAAAAAACAAAAAwAAABQAAwABAAAAFAAEADgAAAAKAAgAAgACAAEAIOYA//3//wAAAAAAIOYA//3//wAB/+MaBAADAAEAAAAAAAAAAAAAAAEAAf//AA8AAQAAAAAAAAAAAAIAADc5AQAAAAABAAAAAAAAAAAAAgAANzkBAAAAAAEAAAAAAAAAAAACAAA3OQEAAAAAAgAAAAABtwG3AHIAgwAANzU0NzYzNzY3JicmNTQ3Njc2NxYfATY3Njc2FzcWFxYVFxYXNzY3FhcWFxYVFAcGBwYHFh8BMhcWHQEUBwYnBwYHFhcWFRQHBgcGByYvAQYHBgcGJwcmJyYvASYnBwYHJicmJyY1NDc2NzY3Ji8BIicmNTcUFxYXNjc2NTQnJgcmBwYVAAIDAzUEBwsUAgIIFBUGBAQnDQ0FAwIJPwQDAwgODCkCBQMEJQoCAgUKCgUHBDUDAwICAwM1BQYKFAMCCBUUBgQEJw0NBQQCCD8EAwMBCA4LKQIFBAMkCwICBQoKBQcENQMDApIWFR4fFRYWFR8eFRa8PwQCBAkMDhAYAgUBBQkWEwEBAh8HBCgNCQEBAQIDAzUEByABAQECIw0DAwUCBwwOBg8NCQQCBD8EAgUBCQ8LDRsCBQIEChUTAQEBIAgDKA0JAQEBAQQDNQQHIAEBAQIhDwQCBQIHDA4GDw0JBAIEHh0WFQEBFRYdIBQXAQEXFCAAAAABAAAAAQAA+Wpa1V8PPPUACwIAAAAAANBR24gAAAAA0FHbiAAAAAABtwG3AAAACAACAAAAAAAAAAEAAAHg/+AAAAIAAAAAAAG3AAEAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAQAAAAIAAAAAAAAAAAoAFAAeAOIAAQAAAAUAhAACAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAA4ArgABAAAAAAABABQAAAABAAAAAAACAA4AXAABAAAAAAADABQAKgABAAAAAAAEABQAagABAAAAAAAFABYAFAABAAAAAAAGAAoAPgABAAAAAAAKADQAfgADAAEECQABABQAAAADAAEECQACAA4AXAADAAEECQADABQAKgADAAEECQAEABQAagADAAEECQAFABYAFAADAAEECQAGABQASAADAAEECQAKADQAfgBkAGUAbQBvAC0AaQBjAG8AbgBzAFYAZQByAHMAaQBvAG4AIAAxAC4AMABkAGUAbQBvAC0AaQBjAG8AbgBzZGVtby1pY29ucwBkAGUAbQBvAC0AaQBjAG8AbgBzAFIAZQBnAHUAbABhAHIAZABlAG0AbwAtAGkAYwBvAG4AcwBGAG8AbgB0ACAAZwBlAG4AZQByAGEAdABlAGQAIABiAHkAIABJAGMAbwBNAG8AbwBuAC4AAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==) format('truetype'), + url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAAWcAAsAAAAABVAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABCAAAAGAAAABgCCL8tmNtYXAAAAFoAAAATAAAAEwaVcxXZ2FzcAAAAbQAAAAIAAAACAAAABBnbHlmAAABvAAAAcQAAAHEY6sadGhlYWQAAAOAAAAANgAAADYBePfEaGhlYQAAA7gAAAAkAAAAJAOZAeZobXR4AAAD3AAAABQAAAAUAwAAAGxvY2EAAAPwAAAADAAAAAwAKAD2bWF4cAAAA/wAAAAgAAAAIAAIAIZuYW1lAAAEHAAAAWAAAAFgE/z+0XBvc3QAAAV8AAAAIAAAACAAAwAAAAMCAAGQAAUAAAFMAWYAAABHAUwBZgAAAPUAGQCEAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAA5gAB4P/g/+AB4AAgAAAAAQAAAAAAAAAAAAAAIAAAAAAAAgAAAAMAAAAUAAMAAQAAABQABAA4AAAACgAIAAIAAgABACDmAP/9//8AAAAAACDmAP/9//8AAf/jGgQAAwABAAAAAAAAAAAAAAABAAH//wAPAAEAAAAAAAAAAAACAAA3OQEAAAAAAQAAAAAAAAAAAAIAADc5AQAAAAABAAAAAAAAAAAAAgAANzkBAAAAAAIAAAAAAbcBtwByAIMAADc1NDc2Mzc2NyYnJjU0NzY3NjcWHwE2NzY3Nhc3FhcWFRcWFzc2NxYXFhcWFRQHBgcGBxYfATIXFh0BFAcGJwcGBxYXFhUUBwYHBgcmLwEGBwYHBicHJicmLwEmJwcGByYnJicmNTQ3Njc2NyYvASInJjU3FBcWFzY3NjU0JyYHJgcGFQACAwM1BAcLFAICCBQVBgQEJw0NBQMCCT8EAwMIDgwpAgUDBCUKAgIFCgoFBwQ1AwMCAgMDNQUGChQDAggVFAYEBCcNDQUEAgg/BAMDAQgOCykCBQQDJAsCAgUKCgUHBDUDAwKSFhUeHxUWFhUfHhUWvD8EAgQJDA4QGAIFAQUJFhMBAQIfBwQoDQkBAQECAwM1BAcgAQEBAiMNAwMFAgcMDgYPDQkEAgQ/BAIFAQkPCw0bAgUCBAoVEwEBASAIAygNCQEBAQEEAzUEByABAQECIQ8EAgUCBwwOBg8NCQQCBB4dFhUBARUWHSAUFwEBFxQgAAAAAQAAAAEAAPlqWtVfDzz1AAsCAAAAAADQUduIAAAAANBR24gAAAAAAbcBtwAAAAgAAgAAAAAAAAABAAAB4P/gAAACAAAAAAABtwABAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAEAAAACAAAAAAAAAAAKABQAHgDiAAEAAAAFAIQAAgAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAOAK4AAQAAAAAAAQAUAAAAAQAAAAAAAgAOAFwAAQAAAAAAAwAUACoAAQAAAAAABAAUAGoAAQAAAAAABQAWABQAAQAAAAAABgAKAD4AAQAAAAAACgA0AH4AAwABBAkAAQAUAAAAAwABBAkAAgAOAFwAAwABBAkAAwAUACoAAwABBAkABAAUAGoAAwABBAkABQAWABQAAwABBAkABgAUAEgAAwABBAkACgA0AH4AZABlAG0AbwAtAGkAYwBvAG4AcwBWAGUAcgBzAGkAbwBuACAAMQAuADAAZABlAG0AbwAtAGkAYwBvAG4Ac2RlbW8taWNvbnMAZABlAG0AbwAtAGkAYwBvAG4AcwBSAGUAZwB1AGwAYQByAGQAZQBtAG8ALQBpAGMAbwBuAHMARgBvAG4AdAAgAGcAZQBuAGUAcgBhAHQAZQBkACAAYgB5ACAASQBjAG8ATQBvAG8AbgAuAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=) format('woff'); + font-weight: normal; + font-style: normal; +} +.icon-settings { + font-family: 'demo-icons'; + speak: none; + font-style: normal; + font-weight: normal; + font-variant: normal; + text-transform: none; + line-height: 1; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} +.icon-settings:before { + content: "\e600"; +} + +.json-key { + color: #a8b389; +} +.json-number { + color: #879db3; +} +.json-string { + color: #c0c5ce; +} +.json-boolean { + color: #bf616a; +} +.json-null { + color: #bf616a; +} diff --git a/website/demo/demo.js b/website/demo/demo.js new file mode 100644 index 000000000..02f5c3cb0 --- /dev/null +++ b/website/demo/demo.js @@ -0,0 +1,76 @@ +(function(exports, document, undefined) { + +'use strict'; + +var ContentKitDemo = exports.ContentKitDemo = { + syncCodePane: function(editor) { + var codePaneJSON = document.getElementById('serialized-mobiledoc'); + var json = editor.serialize(); + codePaneJSON.innerHTML = this.syntaxHighlight(json); + + var renderer = new ContentKit.Runtime.DOMRenderer(); + var rendered = renderer.render(json); + + $('#rendered-mobiledoc').empty(); + $('#rendered-mobiledoc')[0].appendChild(rendered); + }, + + syntaxHighlight: function(json) { + // http://stackoverflow.com/a/7220510/189440 + if (typeof json !== 'string') { + json = JSON.stringify(json, undefined, 2); + } + json = json.replace(/&/g, '&').replace(//g, '>'); + return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) { + var cls = 'json-number'; + if (/^"/.test(match)) { + if (/:$/.test(match)) { + cls = 'json-key'; + } else { + cls = 'json-string'; + } + } else if (/true|false/.test(match)) { + cls = 'json-boolean'; + } else if (/null/.test(match)) { + cls = 'json-null'; + } + return '' + match + ''; + }); + } + +}; + +function bootEditor(element, payload) { + var editor = new ContentKit.Editor(element, { + mobiledoc: payload, + cards: { + 'pick-color': function renderPickColor(payload) { + return 'PICK A COLOR: '+payload.options.join(', '); + } + } + }); + + editor.on('update', function() { + ContentKitDemo.syncCodePane(editor); + }); +} + +function readPayload(textarea) { + var jqueryTextarea = $(textarea); + var textPayload = jqueryTextarea.val(); + return JSON.parse(textPayload); +} + +$(function() { + var textarea = $('#mobiledoc-to-load textarea'); + var editor; + textarea.on('input', function() { + if (editor) { + editor.destroy(); + } + editor = bootEditor($('#editor')[0], readPayload(textarea)); + }); + editor = bootEditor($('#editor')[0], readPayload(textarea)); +}); + +}(this, document)); diff --git a/website/demo/favicon.ico b/website/demo/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..00930e1a3d650941bbc48c42f14ffb2fccbb3c53 GIT binary patch literal 1065 zcmaJ=O=#0l98b3?qhrN`iW?}8RE8gG()1%;Lu?lsyh9@ryqL*DnK_-JKqDNuAbnWKB8j`&C{``Kw|L40kJ~rIz z>~|6b(VHFNb9e>z*L@KGt$O_zUiwhFfF|@QR25A~BxJn^K~@!~VGfG&+?CfbLJ*xN zm3#peg!7!FtCVPCsG4eEHbF#UHA9rj5P>3`Rb{DK5unn!fNUN|q2ZIGV0jt5nrb z>E<-egu`K5!{_s0gvXlGkXZ9*mb<0ELrXFh11Y)&Y(=rCS5TD1k?y9T8hf&u)hrV( z7+n($nxVXQN-dxu{2!{SduR*g;C{US6t?nn2BdS)(krHf8#m>)T^U@;gd)<-yspo* zsyJTKk#3cA1EeNca7qv*MY9d38w^3Ql2hFV;CpBrk+wTD49uxB2c$}E&KrmliU(wx#hmOxv* zCRc7BORz1M#=+2bYyWC>%Y^60-tG-9KJ1M?)bPBUc(BR7YnSk)c#!22`PxSD_s&l2 zRlH;1hU4Ip>sV#&QD^43cZ)b`2C}20PdXmE!0dJBw&U~d&9@If4tyBQ~ zx(@X$X0H;(o<+Czj&p7-7v2y@%1guj#=3ixCC&8{5p(71r}@jJ1!?VG_fzE?F?nXy zF}fXp>AD$9{oqQj=ZT*)Ll+O< + + + + Content Kit Editor Demo 0.2.0 + + + + + + + + + + + + +
+ +
+

mobiledoc to load

+
+ +
+
+ +
+

editor

+
+
+
+ +
+

serialized mobiledoc

+
+
+
+ +
+

rendered mobiledoc

+
+
+ +
+ + + + + + + + diff --git a/website/demo/jquery/jquery.js b/website/demo/jquery/jquery.js new file mode 100644 index 000000000..eed17778c --- /dev/null +++ b/website/demo/jquery/jquery.js @@ -0,0 +1,9210 @@ +/*! + * jQuery JavaScript Library v2.1.4 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2015-04-28T16:01Z + */ + +(function( global, factory ) { + + if ( typeof module === "object" && typeof module.exports === "object" ) { + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info. + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Support: Firefox 18+ +// Can't be in strict mode, several libs including ASP.NET trace +// the stack via arguments.caller.callee and Firefox dies if +// you try to trace through "use strict" call chains. (#13335) +// + +var arr = []; + +var slice = arr.slice; + +var concat = arr.concat; + +var push = arr.push; + +var indexOf = arr.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var support = {}; + + + +var + // Use the correct document accordingly with window argument (sandbox) + document = window.document, + + version = "2.1.4", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }, + + // Support: Android<4.1 + // Make sure we trim BOM and NBSP + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +jQuery.fn = jQuery.prototype = { + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // Start with an empty selector + selector: "", + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num != null ? + + // Return just the one element from the set + ( num < 0 ? this[ num + this.length ] : this[ num ] ) : + + // Return all the elements in a clean array + slice.call( this ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + ret.context = this.context; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: arr.sort, + splice: arr.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray, + + isWindow: function( obj ) { + return obj != null && obj === obj.window; + }, + + isNumeric: function( obj ) { + // parseFloat NaNs numeric-cast false positives (null|true|false|"") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + // adding 1 corrects loss of precision from parseFloat (#15100) + return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0; + }, + + isPlainObject: function( obj ) { + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + if ( obj.constructor && + !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { + return false; + } + + // If the function hasn't returned already, we're confident that + // |obj| is a plain object, created by {} or constructed with new Object + return true; + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + type: function( obj ) { + if ( obj == null ) { + return obj + ""; + } + // Support: Android<4.0, iOS<6 (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call(obj) ] || "object" : + typeof obj; + }, + + // Evaluates a script in a global context + globalEval: function( code ) { + var script, + indirect = eval; + + code = jQuery.trim( code ); + + if ( code ) { + // If the code includes a valid, prologue position + // strict mode pragma, execute code by injecting a + // script tag into the document. + if ( code.indexOf("use strict") === 1 ) { + script = document.createElement("script"); + script.text = code; + document.head.appendChild( script ).parentNode.removeChild( script ); + } else { + // Otherwise, avoid the DOM node creation, insertion + // and removal by using an indirect global eval + indirect( code ); + } + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Support: IE9-11+ + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + // args is for internal usage only + each: function( obj, callback, args ) { + var value, + i = 0, + length = obj.length, + isArray = isArraylike( obj ); + + if ( args ) { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } + } + + return obj; + }, + + // Support: Android<4.1 + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArraylike( Object(arr) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, + i = 0, + length = elems.length, + isArray = isArraylike( elems ), + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var tmp, args, proxy; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + now: Date.now, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +}); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +function isArraylike( obj ) { + + // Support: iOS 8.2 (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = "length" in obj && obj.length, + type = jQuery.type( obj ); + + if ( type === "function" || jQuery.isWindow( obj ) ) { + return false; + } + + if ( obj.nodeType === 1 && length ) { + return true; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v2.2.0-pre + * http://sizzlejs.com/ + * + * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-12-16 + */ +(function( window ) { + +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // General-purpose constants + MAX_NEGATIVE = 1 << 31, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf as it's faster than native + // http://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + // http://www.w3.org/TR/css3-syntax/#characters + characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Loosely modeled on CSS identifier characters + // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors + // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = characterEncoding.replace( "w", "w#" ), + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + characterEncoding + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + rescape = /'|\\/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }; + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var match, elem, m, nodeType, + // QSA vars + i, groups, old, nid, newContext, newSelector; + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + + context = context || document; + results = results || []; + nodeType = context.nodeType; + + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + if ( !seed && documentIsHTML ) { + + // Try to shortcut find operations when possible (e.g., not under DocumentFragment) + if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document (jQuery #6963) + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getElementsByClassName ) { + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // QSA path + if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + nid = old = expando; + newContext = context; + newSelector = nodeType !== 1 && selector; + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); + + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", nid ); + } + nid = "[id='" + nid + "'] "; + + i = groups.length; + while ( i-- ) { + groups[i] = nid + toSelector( groups[i] ); + } + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {Function(string, Object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key + " " ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( div.parentNode ) { + div.parentNode.removeChild( div ); + } + // release memory in IE + div = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = attrs.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + ( ~b.sourceIndex || MAX_NEGATIVE ) - + ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== "undefined" && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, parent, + doc = node ? node.ownerDocument || node : preferredDoc; + + // If no document and documentElement is available, return + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Set our document + document = doc; + docElem = doc.documentElement; + parent = doc.defaultView; + + // Support: IE>8 + // If iframe document is assigned to "document" variable and if iframe has been reloaded, + // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 + // IE6-8 do not support the defaultView property so parent will be undefined + if ( parent && parent !== parent.top ) { + // IE11 does not have attachEvent, so all must suffer + if ( parent.addEventListener ) { + parent.addEventListener( "unload", unloadHandler, false ); + } else if ( parent.attachEvent ) { + parent.attachEvent( "onunload", unloadHandler ); + } + } + + /* Support tests + ---------------------------------------------------------------------- */ + documentIsHTML = !isXML( doc ); + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties + // (excepting IE8 booleans) + support.attributes = assert(function( div ) { + div.className = "i"; + return !div.getAttribute("className"); + }); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert(function( div ) { + div.appendChild( doc.createComment("") ); + return !div.getElementsByTagName("*").length; + }); + + // Support: IE<9 + support.getElementsByClassName = rnative.test( doc.getElementsByClassName ); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert(function( div ) { + docElem.appendChild( div ).id = expando; + return !doc.getElementsByName || !doc.getElementsByName( expando ).length; + }); + + // ID find and filter + if ( support.getById ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [ m ] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + // Support: IE6/7 + // getElementById is not reliable as a find shortcut + delete Expr.find["ID"]; + + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + } + + // Tag + Expr.find["TAG"] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); + + // DocumentFragment nodes don't have gEBTN + } else if ( support.qsa ) { + return context.querySelectorAll( tag ); + } + } : + + function( tag, context ) { + var elem, + tmp = [], + i = 0, + // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See http://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + docElem.appendChild( div ).innerHTML = "" + + ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( div.querySelectorAll("[msallowcapture^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+ + if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push("~="); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + + // Support: Safari 8+, iOS 8+ + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibing-combinator selector` fails + if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push(".#.+[+~]"); + } + }); + + assert(function( div ) { + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = doc.createElement("input"); + input.setAttribute( "type", "hidden" ); + div.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( div.querySelectorAll("[name=d]").length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully does not implement inclusive descendent + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { + return -1; + } + if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return doc; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + if ( support.matchesSelector && documentIsHTML && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch (e) {} + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + while ( (node = elem[i++]) ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[6] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[3] ) { + match[2] = match[4] || match[5] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + // Don't keep the element (issue #299) + input[0] = null; + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + text = text.replace( runescape, funescape ); + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( (tokens = []) ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + if ( (oldCache = outerCache[ dir ]) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return (newCache[ 2 ] = oldCache[ 2 ]); + } else { + // Reuse newcache so results back-propagate to previous elements + outerCache[ dir ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { + return true; + } + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + // Avoid hanging onto element (issue #299) + checkContext = null; + return ret; + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), + len = elems.length; + + if ( outermost ) { + outermostContext = context !== document && context; + } + + // Add elements passing elementMatchers directly to results + // Keep `i` a string if there are no elements so `matchedCount` will be "00" below + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( (selector = compiled.selector || selector) ); + + results = results || []; + + // Try to minimize operations if there is no seed and only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + support.getById && context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Support: Chrome 14-35+ +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert(function( div1 ) { + // Should return 1, but returns 4 (following) + return div1.compareDocumentPosition( document.createElement("div") ) & 1; +}); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( div ) { + div.innerHTML = ""; + return div.firstChild.getAttribute("href") === "#" ; +}) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + }); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert(function( div ) { + div.innerHTML = ""; + div.firstChild.setAttribute( "value", "" ); + return div.firstChild.getAttribute( "value" ) === ""; +}) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert(function( div ) { + return div.getAttribute("disabled") == null; +}) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + null; + } + }); +} + +return Sizzle; + +})( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.pseudos; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + + +var rneedsContext = jQuery.expr.match.needsContext; + +var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); + + + +var risSimple = /^.[^:#\[\.,]*$/; + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + /* jshint -W018 */ + return !!qualifier.call( elem, i, elem ) !== not; + }); + + } + + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + }); + + } + + if ( typeof qualifier === "string" ) { + if ( risSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); + } + + qualifier = jQuery.filter( qualifier, elements ); + } + + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; + }); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 && elem.nodeType === 1 ? + jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : + jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + })); +}; + +jQuery.fn.extend({ + find: function( selector ) { + var i, + len = this.length, + ret = [], + self = this; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }) ); + } + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = this.selector ? this.selector + " " + selector : selector; + return ret; + }, + filter: function( selector ) { + return this.pushStack( winnow(this, selector || [], false) ); + }, + not: function( selector ) { + return this.pushStack( winnow(this, selector || [], true) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +}); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, + + init = jQuery.fn.init = function( selector, context ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + + // Option to run scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[1], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[2] ); + + // Support: Blackberry 4.6 + // gEBID returns nodes no longer in the document (#6963) + if ( elem && elem.parentNode ) { + // Inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return typeof rootjQuery.ready !== "undefined" ? + rootjQuery.ready( selector ) : + // Execute immediately if ready is not present + selector( jQuery ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + // Methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.extend({ + dir: function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; + + while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; + }, + + sibling: function( n, elem ) { + var matched = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; + } +}); + +jQuery.fn.extend({ + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; + + return this.filter(function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { + // Always skip document fragments + if ( cur.nodeType < 11 && (pos ? + pos.index(cur) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector(cur, selectors)) ) { + + matched.push( cur ); + break; + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); + }, + + // Determine the position of an element within the set + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } + + // Index in selector + if ( typeof elem === "string" ) { + return indexOf.call( jQuery( elem ), this[ 0 ] ); + } + + // Locate the position of the desired element + return indexOf.call( this, + + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.unique( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +function sibling( cur, dir ) { + while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} + return cur; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return elem.contentDocument || jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); + } + + if ( this.length > 1 ) { + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.unique( matched ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } + } + + return this.pushStack( matched ); + }; +}); +var rnotwhite = (/\S+/g); + + + +// String to Object options format cache +var optionsCache = {}; + +// Convert String-formatted options into Object-formatted ones and store in cache +function createOptions( options ) { + var object = optionsCache[ options ] = {}; + jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + }); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + ( optionsCache[ options ] || createOptions( options ) ) : + jQuery.extend( {}, options ); + + var // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // Flag to know if list is currently firing + firing, + // First callback to fire (used internally by add and fireWith) + firingStart, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !options.once && [], + // Fire callbacks + fire = function( data ) { + memory = options.memory && data; + fired = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + firing = true; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { + memory = false; // To prevent further calls using add + break; + } + } + firing = false; + if ( list ) { + if ( stack ) { + if ( stack.length ) { + fire( stack.shift() ); + } + } else if ( memory ) { + list = []; + } else { + self.disable(); + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + // First, we save the current length + var start = list.length; + (function add( args ) { + jQuery.each( args, function( _, arg ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { + // Inspect recursively + add( arg ); + } + }); + })( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away + } else if ( memory ) { + firingStart = start; + fire( memory ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + // Handle firing indexes + if ( firing ) { + if ( index <= firingLength ) { + firingLength--; + } + if ( index <= firingIndex ) { + firingIndex--; + } + } + } + }); + } + return this; + }, + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); + }, + // Remove all callbacks from the list + empty: function() { + list = []; + firingLength = 0; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( list && ( !fired || stack ) ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( firing ) { + stack.push( args ); + } else { + fire( args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +jQuery.extend({ + + Deferred: function( func ) { + var tuples = [ + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], + [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], + [ "notify", "progress", jQuery.Callbacks("memory") ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred(function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ](function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); + } + }); + }); + fns = null; + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[1] ] = list.add; + + // Handle state + if ( stateString ) { + list.add(function() { + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] + deferred[ tuple[0] ] = function() { + deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); + return this; + }; + deferred[ tuple[0] + "With" ] = list.fireWith; + }); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( values === progressValues ) { + deferred.notifyWith( contexts, values ); + } else if ( !( --remaining ) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // Add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ) + .progress( updateFunc( i, progressContexts, progressValues ) ); + } else { + --remaining; + } + } + } + + // If we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +}); + + +// The deferred used on DOM ready +var readyList; + +jQuery.fn.ready = function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; +}; + +jQuery.extend({ + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.triggerHandler ) { + jQuery( document ).triggerHandler( "ready" ); + jQuery( document ).off( "ready" ); + } + } +}); + +/** + * The ready event handler and self cleanup method + */ +function completed() { + document.removeEventListener( "DOMContentLoaded", completed, false ); + window.removeEventListener( "load", completed, false ); + jQuery.ready(); +} + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // We once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready ); + + } else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed, false ); + } + } + return readyList.promise( obj ); +}; + +// Kick off the DOM ready check even if the user does not +jQuery.ready.promise(); + + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < len; i++ ) { + fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); + } + } + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + len ? fn( elems[0], key ) : emptyGet; +}; + + +/** + * Determines whether an object can have data + */ +jQuery.acceptData = function( owner ) { + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + /* jshint -W018 */ + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +}; + + +function Data() { + // Support: Android<4, + // Old WebKit does not have Object.preventExtensions/freeze method, + // return new empty object instead with no [[set]] accessor + Object.defineProperty( this.cache = {}, 0, { + get: function() { + return {}; + } + }); + + this.expando = jQuery.expando + Data.uid++; +} + +Data.uid = 1; +Data.accepts = jQuery.acceptData; + +Data.prototype = { + key: function( owner ) { + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return the key for a frozen object. + if ( !Data.accepts( owner ) ) { + return 0; + } + + var descriptor = {}, + // Check if the owner object already has a cache key + unlock = owner[ this.expando ]; + + // If not, create one + if ( !unlock ) { + unlock = Data.uid++; + + // Secure it in a non-enumerable, non-writable property + try { + descriptor[ this.expando ] = { value: unlock }; + Object.defineProperties( owner, descriptor ); + + // Support: Android<4 + // Fallback to a less secure definition + } catch ( e ) { + descriptor[ this.expando ] = unlock; + jQuery.extend( owner, descriptor ); + } + } + + // Ensure the cache object + if ( !this.cache[ unlock ] ) { + this.cache[ unlock ] = {}; + } + + return unlock; + }, + set: function( owner, data, value ) { + var prop, + // There may be an unlock assigned to this node, + // if there is no entry for this "owner", create one inline + // and set the unlock as though an owner entry had always existed + unlock = this.key( owner ), + cache = this.cache[ unlock ]; + + // Handle: [ owner, key, value ] args + if ( typeof data === "string" ) { + cache[ data ] = value; + + // Handle: [ owner, { properties } ] args + } else { + // Fresh assignments by object are shallow copied + if ( jQuery.isEmptyObject( cache ) ) { + jQuery.extend( this.cache[ unlock ], data ); + // Otherwise, copy the properties one-by-one to the cache object + } else { + for ( prop in data ) { + cache[ prop ] = data[ prop ]; + } + } + } + return cache; + }, + get: function( owner, key ) { + // Either a valid cache is found, or will be created. + // New caches will be created and the unlock returned, + // allowing direct access to the newly created + // empty data object. A valid owner object must be provided. + var cache = this.cache[ this.key( owner ) ]; + + return key === undefined ? + cache : cache[ key ]; + }, + access: function( owner, key, value ) { + var stored; + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ((key && typeof key === "string") && value === undefined) ) { + + stored = this.get( owner, key ); + + return stored !== undefined ? + stored : this.get( owner, jQuery.camelCase(key) ); + } + + // [*]When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, name, camel, + unlock = this.key( owner ), + cache = this.cache[ unlock ]; + + if ( key === undefined ) { + this.cache[ unlock ] = {}; + + } else { + // Support array or space separated string of keys + if ( jQuery.isArray( key ) ) { + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = key.concat( key.map( jQuery.camelCase ) ); + } else { + camel = jQuery.camelCase( key ); + // Try the string as a key before any manipulation + if ( key in cache ) { + name = [ key, camel ]; + } else { + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + name = camel; + name = name in cache ? + [ name ] : ( name.match( rnotwhite ) || [] ); + } + } + + i = name.length; + while ( i-- ) { + delete cache[ name[ i ] ]; + } + } + }, + hasData: function( owner ) { + return !jQuery.isEmptyObject( + this.cache[ owner[ this.expando ] ] || {} + ); + }, + discard: function( owner ) { + if ( owner[ this.expando ] ) { + delete this.cache[ owner[ this.expando ] ]; + } + } +}; +var data_priv = new Data(); + +var data_user = new Data(); + + + +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /([A-Z])/g; + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + data_user.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} + +jQuery.extend({ + hasData: function( elem ) { + return data_user.hasData( elem ) || data_priv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return data_user.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + data_user.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to data_priv methods, these can be deprecated. + _data: function( elem, name, data ) { + return data_priv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + data_priv.remove( elem, name ); + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = data_user.get( elem ); + + if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE11+ + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.slice(5) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + data_priv.set( elem, "hasDataAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + data_user.set( this, key ); + }); + } + + return access( this, function( value ) { + var data, + camelKey = jQuery.camelCase( key ); + + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { + // Attempt to get data from the cache + // with the key as-is + data = data_user.get( elem, key ); + if ( data !== undefined ) { + return data; + } + + // Attempt to get data from the cache + // with the key camelized + data = data_user.get( elem, camelKey ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, camelKey, undefined ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; + } + + // Set the data... + this.each(function() { + // First, attempt to store a copy or reference of any + // data that might've been store with a camelCased key. + var data = data_user.get( this, camelKey ); + + // For HTML5 data-* attribute interop, we have to + // store property names with dashes in a camelCase form. + // This might not apply to all properties...* + data_user.set( this, camelKey, value ); + + // *... In the case of properties that might _actually_ + // have dashes, we need to also store a copy of that + // unchanged property. + if ( key.indexOf("-") !== -1 && data !== undefined ) { + data_user.set( this, key, value ); + } + }); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each(function() { + data_user.remove( this, key ); + }); + } +}); + + +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = data_priv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray( data ) ) { + queue = data_priv.access( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // Clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // Not public - generate a queueHooks object, or return the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return data_priv.get( elem, key ) || data_priv.access( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + data_priv.remove( elem, [ type + "queue", key ] ); + }) + }); + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } + + return data === undefined ? + this : + this.each(function() { + var queue = jQuery.queue( this, type, data ); + + // Ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = data_priv.get( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +}); +var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var isHidden = function( elem, el ) { + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); + }; + +var rcheckableType = (/^(?:checkbox|radio)$/i); + + + +(function() { + var fragment = document.createDocumentFragment(), + div = fragment.appendChild( document.createElement( "div" ) ), + input = document.createElement( "input" ); + + // Support: Safari<=5.1 + // Check state lost if the name is set (#11217) + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (#14901) + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + + // Support: Safari<=5.1, Android<4.2 + // Older WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE<=11+ + // Make sure textarea (and checkbox) defaultValue is properly cloned + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; +})(); +var strundefined = typeof undefined; + + + +support.focusinBubbles = "onfocusin" in window; + + +var + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = data_priv.get( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !(events = elemData.events) ) { + events = elemData.events = {}; + } + if ( !(eventHandle = elemData.handle) ) { + eventHandle = elemData.handle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !(handlers = events[ type ]) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = data_priv.hasData( elem ) && data_priv.get( elem ); + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; + data_priv.remove( elem, "events" ); + } + }, + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf(".") >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf(":") < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join("."); + event.namespace_re = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === (elem.ownerDocument || document) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && jQuery.acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && + jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); + + var i, j, ret, matched, handleObj, + handlerQueue = [], + args = slice.call( arguments ), + handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or 2) have namespace(s) + // a subset or equal to those in the bound event (both can have no namespace). + if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( (event.result = ret) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, matches, sel, handleObj, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.disabled !== true || event.type !== "click" ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, handlers: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); + } + + return handlerQueue; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; + + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; + } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Support: Cordova 2.5 (WebKit) (#13255) + // All events should have a target; Cordova deviceready doesn't + if ( !event.target ) { + event.target = document; + } + + // Support: Safari 6.0+, Chrome<28 + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, + + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + this.focus(); + return false; + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { + this.click(); + return false; + } + }, + + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return jQuery.nodeName( event.target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +jQuery.removeEvent = function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } +}; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + // Support: Android<4.0 + src.returnValue === false ? + returnTrue : + returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e && e.preventDefault ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e && e.stopPropagation ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && e.stopImmediatePropagation ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +// Support: Chrome 15+ +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// Support: Firefox, Chrome, Safari +// Create "bubbling" focus and blur events +if ( !support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + var doc = this.ownerDocument || this, + attaches = data_priv.access( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this, + attaches = data_priv.access( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + data_priv.remove( doc, fix ); + + } else { + data_priv.access( doc, fix, attaches ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + var elem = this[0]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +}); + + +var + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, + rtagName = /<([\w:]+)/, + rhtml = /<|&#?\w+;/, + rnoInnerhtml = /<(?:script|style|link)/i, + // checked="checked" or checked + rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, + rscriptType = /^$|\/(?:java|ecma)script/i, + rscriptTypeMasked = /^true\/(.*)/, + rcleanScript = /^\s*\s*$/g, + + // We have to close these tags to support XHTML (#13200) + wrapMap = { + + // Support: IE9 + option: [ 1, "" ], + + thead: [ 1, "", "
" ], + col: [ 2, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], + + _default: [ 0, "", "" ] + }; + +// Support: IE9 +wrapMap.optgroup = wrapMap.option; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// Support: 1.x compatibility +// Manipulating tables requires a tbody +function manipulationTarget( elem, content ) { + return jQuery.nodeName( elem, "table" ) && + jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? + + elem.getElementsByTagName("tbody")[0] || + elem.appendChild( elem.ownerDocument.createElement("tbody") ) : + elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + + if ( match ) { + elem.type = match[ 1 ]; + } else { + elem.removeAttribute("type"); + } + + return elem; +} + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + data_priv.set( + elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) + ); + } +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( data_priv.hasData( src ) ) { + pdataOld = data_priv.access( src ); + pdataCur = data_priv.set( dest, pdataOld ); + events = pdataOld.events; + + if ( events ) { + delete pdataCur.handle; + pdataCur.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( data_user.hasData( src ) ) { + udataOld = data_user.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + data_user.set( dest, udataCur ); + } +} + +function getAll( context, tag ) { + var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : + context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : + []; + + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], ret ) : + ret; +} + +// Fix IE bugs, see support tests +function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = jQuery.contains( elem.ownerDocument, elem ); + + // Fix IE cloning issues + if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && + !jQuery.isXMLDoc( elem ) ) { + + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], destElements[ i ] ); + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + buildFragment: function( elems, context, scripts, selection ) { + var elem, tmp, tag, wrap, contains, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + // Support: QtWebKit, PhantomJS + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement("div") ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: QtWebKit, PhantomJS + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (#12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( (elem = nodes[ i++ ]) ) { + + // #4087 - If origin and destination elements are the same, and this is + // that element, do not do anything + if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( (elem = tmp[ j++ ]) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; + }, + + cleanData: function( elems ) { + var data, elem, type, key, + special = jQuery.event.special, + i = 0; + + for ( ; (elem = elems[ i ]) !== undefined; i++ ) { + if ( jQuery.acceptData( elem ) ) { + key = elem[ data_priv.expando ]; + + if ( key && (data = data_priv.cache[ key ]) ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + if ( data_priv.cache[ key ] ) { + // Discard any remaining `private` data + delete data_priv.cache[ key ]; + } + } + } + // Discard any remaining `user` data + delete data_user.cache[ elem[ data_user.expando ] ]; + } + } +}); + +jQuery.fn.extend({ + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().each(function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + }); + }, null, value, arguments.length ); + }, + + append: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + }); + }, + + before: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + }); + }, + + after: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + }); + }, + + remove: function( selector, keepData /* Internal Use Only */ ) { + var elem, + elems = selector ? jQuery.filter( selector, this ) : this, + i = 0; + + for ( ; (elem = elems[i]) != null; i++ ) { + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem ) ); + } + + if ( elem.parentNode ) { + if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { + setGlobalEval( getAll( elem, "script" ) ); + } + elem.parentNode.removeChild( elem ); + } + } + + return this; + }, + + empty: function() { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map(function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch( e ) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var arg = arguments[ 0 ]; + + // Make the changes, replacing each context element with the new content + this.domManip( arguments, function( elem ) { + arg = this.parentNode; + + jQuery.cleanData( getAll( this ) ); + + if ( arg ) { + arg.replaceChild( elem, this ); + } + }); + + // Force removal if there was no new content (e.g., from empty arguments) + return arg && (arg.length || arg.nodeType) ? this : this.remove(); + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, callback ) { + + // Flatten any nested arrays + args = concat.apply( [], args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = this.length, + set = this, + iNoClone = l - 1, + value = args[ 0 ], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return this.each(function( index ) { + var self = set.eq( index ); + if ( isFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + self.domManip( args, callback ); + }); + } + + if ( l ) { + fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + // Support: QtWebKit + // jQuery.merge because push.apply(_, arraylike) throws + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( this[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { + + if ( node.src ) { + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl ) { + jQuery._evalUrl( node.src ); + } + } else { + jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); + } + } + } + } + } + } + + return this; + } +}); + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + + // Support: QtWebKit + // .get() because push.apply(_, arraylike) throws + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +}); + + +var iframe, + elemdisplay = {}; + +/** + * Retrieve the actual display of a element + * @param {String} name nodeName of the element + * @param {Object} doc Document object + */ +// Called only from within defaultDisplay +function actualDisplay( name, doc ) { + var style, + elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), + + // getDefaultComputedStyle might be reliably used only on attached element + display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? + + // Use of this method is a temporary fix (more like optimization) until something better comes along, + // since it was removed from specification and supported only in FF + style.display : jQuery.css( elem[ 0 ], "display" ); + + // We don't have any data stored on the element, + // so use "detach" method as fast way to get rid of the element + elem.detach(); + + return display; +} + +/** + * Try to determine the default display value of an element + * @param {String} nodeName + */ +function defaultDisplay( nodeName ) { + var doc = document, + display = elemdisplay[ nodeName ]; + + if ( !display ) { + display = actualDisplay( nodeName, doc ); + + // If the simple way fails, read from inside an iframe + if ( display === "none" || !display ) { + + // Use the already-created iframe if possible + iframe = (iframe || jQuery( "'; + }; + + exports['default'] = YouTubeRenderer; +}); +define('content-kit-editor/utils/compat', ['exports', 'content-kit-editor/utils/doc', 'content-kit-editor/utils/win'], function (exports, _contentKitEditorUtilsDoc, _contentKitEditorUtilsWin) { + 'use strict'; + + exports.doc = _contentKitEditorUtilsDoc['default']; + exports.win = _contentKitEditorUtilsWin['default']; +}); +define("content-kit-editor/utils/compiler", ["exports"], function (exports) { + "use strict"; + + exports.visit = visit; + exports.compile = compile; + exports.visitArray = visitArray; + + function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } + + function visit(visitor, node, opcodes) { + visitor[node.type](node, opcodes); + } + + function compile(compiler, opcodes) { + for (var i = 0, l = opcodes.length; i < l; i++) { + var _opcodes$i = _toArray(opcodes[i]); + + var method = _opcodes$i[0]; + + var params = _opcodes$i.slice(1); + + if (params.length) { + compiler[method].apply(compiler, params); + } else { + compiler[method].call(compiler); + } + } + } + + function visitArray(visitor, nodes, opcodes) { + if (!nodes || nodes.length === 0) { + return; + } + for (var i = 0, l = nodes.length; i < l; i++) { + visit(visitor, nodes[i], opcodes); + } + } +}); +define("content-kit-editor/utils/doc", ["exports"], function (exports) { + // FIXME in theory, we might want to make this safe for node usage and + // return a jsdom? + // In practice we probably don't need this for the editor since it won't ever + // execute in a solely server-side environment + "use strict"; + + exports["default"] = document; +}); +define("content-kit-editor/utils/dom-utils", ["exports"], function (exports) { + "use strict"; + + exports.detectParentNode = detectParentNode; + + function detectParentNode(element, callback) { + while (element) { + var result = callback(element); + if (result) { + return { + element: element, + result: result + }; + } + element = element.parentNode; + } + + return { + element: null, + result: null + }; + } +}); +define('content-kit-editor/utils/element-map', ['exports'], function (exports) { + // start at one to make the falsy semantics easier + 'use strict'; + + var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + var uuidGenerator = 1; + + var ElementMap = (function () { + function ElementMap() { + _classCallCheck(this, ElementMap); + + this._map = {}; + } + + _createClass(ElementMap, [{ + key: 'set', + value: function set(key, value) { + var uuid = key.dataset.uuid; + if (!uuid) { + key.dataset.uuid = uuid = uuidGenerator++; + } + this._map[uuid] = value; + } + }, { + key: 'get', + value: function get(key) { + if (key.dataset && key.dataset.uuid) { + return this._map[key.dataset.uuid]; + } + return null; + } + }, { + key: 'remove', + value: function remove(key) { + if (!key.dataset.uuid) { + throw new Error('tried to fetch a value for an element not seen before'); + } + delete this._map[key.dataset.uuid]; + } + }]); + + return ElementMap; + })(); + + exports['default'] = ElementMap; +}); +define('content-kit-editor/utils/element-utils', ['exports', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorUtilsCompat) { + 'use strict'; + + function createDiv(className) { + var div = _contentKitEditorUtilsCompat.doc.createElement('div'); + if (className) { + div.className = className; + } + return div; + } + + function hideElement(element) { + element.style.display = 'none'; + } + + function showElement(element) { + element.style.display = 'block'; + } + + function swapElements(elementToShow, elementToHide) { + hideElement(elementToHide); + showElement(elementToShow); + } + + function getEventTargetMatchingTag(tag, target, container) { + // Traverses up DOM from an event target to find the node matching specifed tag + while (target && target !== container) { + if (target.tagName.toLowerCase() === tag) { + return target; + } + target = target.parentNode; + } + } + + function nodeIsDescendantOfElement(node, element) { + var parentNode = node.parentNode; + while (parentNode) { + if (parentNode === element) { + return true; + } + parentNode = parentNode.parentNode; + } + return false; + } + + function elementContentIsEmpty(element) { + var content = element && element.innerHTML; + if (content) { + return content === '' || content === '
'; + } + return false; + } + + function getElementRelativeOffset(element) { + var offset = { left: 0, top: -_contentKitEditorUtilsCompat.win.pageYOffset }; + var offsetParent = element.offsetParent; + var offsetParentPosition = _contentKitEditorUtilsCompat.win.getComputedStyle(offsetParent).position; + var offsetParentRect; + + if (offsetParentPosition === 'relative') { + offsetParentRect = offsetParent.getBoundingClientRect(); + offset.left = offsetParentRect.left; + offset.top = offsetParentRect.top; + } + return offset; + } + + function getElementComputedStyleNumericProp(element, prop) { + return parseFloat(_contentKitEditorUtilsCompat.win.getComputedStyle(element)[prop]); + } + + function positionElementToRect(element, rect, topOffset, leftOffset) { + var relativeOffset = getElementRelativeOffset(element); + var style = element.style; + var round = Math.round; + var left, top; + + topOffset = topOffset || 0; + leftOffset = leftOffset || 0; + left = round(rect.left - relativeOffset.left - leftOffset); + top = round(rect.top - relativeOffset.top - topOffset); + style.left = left + 'px'; + style.top = top + 'px'; + return { left: left, top: top }; + } + + function positionElementHorizontallyCenteredToRect(element, rect, topOffset) { + var horizontalCenter = element.offsetWidth / 2 - rect.width / 2; + return positionElementToRect(element, rect, topOffset, horizontalCenter); + } + + function positionElementCenteredAbove(element, aboveElement) { + var elementMargin = getElementComputedStyleNumericProp(element, 'marginBottom'); + return positionElementHorizontallyCenteredToRect(element, aboveElement.getBoundingClientRect(), element.offsetHeight + elementMargin); + } + + function positionElementCenteredBelow(element, belowElement) { + var elementMargin = getElementComputedStyleNumericProp(element, 'marginTop'); + return positionElementHorizontallyCenteredToRect(element, belowElement.getBoundingClientRect(), -element.offsetHeight - elementMargin); + } + + function positionElementCenteredIn(element, inElement) { + var verticalCenter = inElement.offsetHeight / 2 - element.offsetHeight / 2; + return positionElementHorizontallyCenteredToRect(element, inElement.getBoundingClientRect(), -verticalCenter); + } + + function positionElementToLeftOf(element, leftOfElement) { + var verticalCenter = leftOfElement.offsetHeight / 2 - element.offsetHeight / 2; + var elementMargin = getElementComputedStyleNumericProp(element, 'marginRight'); + return positionElementToRect(element, leftOfElement.getBoundingClientRect(), -verticalCenter, element.offsetWidth + elementMargin); + } + + function positionElementToRightOf(element, rightOfElement) { + var verticalCenter = rightOfElement.offsetHeight / 2 - element.offsetHeight / 2; + var elementMargin = getElementComputedStyleNumericProp(element, 'marginLeft'); + var rightOfElementRect = rightOfElement.getBoundingClientRect(); + return positionElementToRect(element, rightOfElementRect, -verticalCenter, -rightOfElement.offsetWidth - elementMargin); + } + + exports.createDiv = createDiv; + exports.hideElement = hideElement; + exports.showElement = showElement; + exports.swapElements = swapElements; + exports.getEventTargetMatchingTag = getEventTargetMatchingTag; + exports.nodeIsDescendantOfElement = nodeIsDescendantOfElement; + exports.elementContentIsEmpty = elementContentIsEmpty; + exports.getElementRelativeOffset = getElementRelativeOffset; + exports.getElementComputedStyleNumericProp = getElementComputedStyleNumericProp; + exports.positionElementToRect = positionElementToRect; + exports.positionElementHorizontallyCenteredToRect = positionElementHorizontallyCenteredToRect; + exports.positionElementCenteredAbove = positionElementCenteredAbove; + exports.positionElementCenteredBelow = positionElementCenteredBelow; + exports.positionElementCenteredIn = positionElementCenteredIn; + exports.positionElementToLeftOf = positionElementToLeftOf; + exports.positionElementToRightOf = positionElementToRightOf; +}); +define("content-kit-editor/utils/event-emitter", ["exports"], function (exports) { + // Based on https://github.com/jeromeetienne/microevent.js/blob/master/microevent.js + // See also: https://github.com/allouis/minivents/blob/master/minivents.js + + "use strict"; + + var EventEmitter = { + on: function on(type, handler) { + var events = this.__events = this.__events || {}; + events[type] = events[type] || []; + events[type].push(handler); + }, + off: function off(type, handler) { + var events = this.__events = this.__events || {}; + if (type in events) { + events[type].splice(events[type].indexOf(handler), 1); + } + }, + trigger: function trigger(type) { + var events = this.__events = this.__events || {}; + var eventForTypeCount, i; + if (type in events) { + eventForTypeCount = events[type].length; + for (i = 0; i < eventForTypeCount; i++) { + events[type][i].apply(this, Array.prototype.slice.call(arguments, 1)); + } + } + } + }; + + exports["default"] = EventEmitter; +}); +define('content-kit-editor/utils/http-utils', ['exports', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorUtilsCompat) { + /* global JSON */ + 'use strict'; + + function createXHR(options) { + var xhr = new XMLHttpRequest(); + xhr.open(options.method, options.url); + xhr.onload = function () { + var response = xhr.responseText; + if (xhr.status === 200) { + return options.success.call(this, response); + } + options.error.call(this, response); + }; + xhr.onerror = function (error) { + options.error.call(this, error); + }; + return xhr; + } + + function xhrGet(options) { + options.method = 'GET'; + var xhr = createXHR(options); + try { + xhr.send(); + } catch (error) {} + } + + function xhrPost(options) { + options.method = 'POST'; + var xhr = createXHR(options); + var formData = new FormData(); + formData.append('file', options.data); + try { + xhr.send(formData); + } catch (error) {} + } + + function responseJSON(jsonString) { + if (!jsonString) { + return null; + } + try { + return JSON.parse(jsonString); + } catch (e) { + return jsonString; + } + } + + // -------------------------------------------- + + function FileUploader(options) { + options = options || {}; + var url = options.url; + var maxFileSize = options.maxFileSize; + if (url) { + this.url = url; + } else { + throw new Error('FileUploader: setting the `url` to an upload service is required'); + } + if (maxFileSize) { + this.maxFileSize = maxFileSize; + } + } + + FileUploader.prototype.upload = function (options) { + if (!options) { + return; + } + + var fileInput = options.fileInput; + var file = options.file || fileInput && fileInput.files && fileInput.files[0]; + var callback = options.complete; + var maxFileSize = this.maxFileSize; + if (!file || !(file instanceof _contentKitEditorUtilsCompat.win.File)) { + return; + } + + if (maxFileSize && file.size > maxFileSize) { + if (callback) { + callback.call(this, null, { message: 'max file size is ' + maxFileSize + ' bytes' }); + } + return; + } + + xhrPost({ + url: this.url, + data: file, + success: function success(response) { + if (callback) { + callback.call(this, responseJSON(response)); + } + }, + error: function error(_error) { + if (callback) { + callback.call(this, null, responseJSON(_error)); + } + } + }); + }; + + function OEmbedder(options) { + options = options || {}; + var url = options.url; + if (url) { + this.url = url; + } else { + throw new Error('OEmbedder: setting the `url` to an embed service is required'); + } + } + + OEmbedder.prototype.fetch = function (options) { + var callback = options.complete; + xhrGet({ + url: this.url + '?url=' + encodeURI(options.url), + success: function success(response) { + if (callback) { + callback.call(this, responseJSON(response)); + } + }, + error: function error(_error2) { + if (callback) { + callback.call(this, null, responseJSON(_error2)); + } + } + }); + }; + + exports.FileUploader = FileUploader; + exports.OEmbedder = OEmbedder; +}); +define("content-kit-editor/utils/keycodes", ["exports"], function (exports) { + "use strict"; + + exports["default"] = { + BKSP: 8, + ENTER: 13, + ESC: 27, + DEL: 46, + M: 77 + }; +}); +define('content-kit-editor/utils/selection-utils', ['exports', 'content-kit-editor/utils/element-utils', 'content-kit-compiler', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorUtilsElementUtils, _contentKitCompiler, _contentKitEditorUtilsCompat) { + 'use strict'; + + // TODO: remove, pass in Editor's current block set + var RootTags = [_contentKitCompiler.Type.PARAGRAPH.tag, _contentKitCompiler.Type.HEADING.tag, _contentKitCompiler.Type.SUBHEADING.tag, _contentKitCompiler.Type.QUOTE.tag, _contentKitCompiler.Type.LIST.tag, _contentKitCompiler.Type.ORDERED_LIST.tag]; + + var SelectionDirection = { + LEFT_TO_RIGHT: 1, + RIGHT_TO_LEFT: 2, + SAME_NODE: 3 + }; + + function getDirectionOfSelection(selection) { + var node = selection.anchorNode; + var position = node && node.compareDocumentPosition(selection.focusNode); + if (position & Node.DOCUMENT_POSITION_FOLLOWING) { + return SelectionDirection.LEFT_TO_RIGHT; + } else if (position & Node.DOCUMENT_POSITION_PRECEDING) { + return SelectionDirection.RIGHT_TO_LEFT; + } + return SelectionDirection.SAME_NODE; + } + + function getSelectionElement(selection) { + selection = selection || _contentKitEditorUtilsCompat.win.getSelection(); + var node = getDirectionOfSelection(selection) === SelectionDirection.LEFT_TO_RIGHT ? selection.anchorNode : selection.focusNode; + return node && (node.nodeType === 3 ? node.parentNode : node); + } + + function getSelectionBlockElement(selection) { + selection = selection || _contentKitEditorUtilsCompat.win.getSelection(); + var element = getSelectionElement(); + var tag = element && element.tagName.toLowerCase(); + while (tag && RootTags.indexOf(tag) === -1) { + if (element.contentEditable === 'true') { + return null; // Stop traversing up dom when hitting an editor element + } + element = element.parentNode; + tag = element.tagName && element.tagName.toLowerCase(); + } + return element; + } + + function getSelectionTagName() { + var element = getSelectionElement(); + return element ? element.tagName.toLowerCase() : null; + } + + function getSelectionBlockTagName() { + var element = getSelectionBlockElement(); + return element ? element.tagName && element.tagName.toLowerCase() : null; + } + + function tagsInSelection(selection) { + var element = getSelectionElement(selection); + var tags = []; + while (element) { + if (element.contentEditable === 'true') { + break; + } // Stop traversing up dom when hitting an editor element + if (element.tagName) { + tags.push(element.tagName.toLowerCase()); + } + element = element.parentNode; + } + return tags; + } + + function selectionIsInElement(selection, element) { + var node = selection.anchorNode; + return node && (0, _contentKitEditorUtilsElementUtils.nodeIsDescendantOfElement)(node, element); + } + + function selectionIsEditable(selection) { + var el = getSelectionBlockElement(selection); + return el && el.isContentEditable; + } + + function restoreRange(range) { + var selection = _contentKitEditorUtilsCompat.win.getSelection(); + selection.removeAllRanges(); + selection.addRange(range); + } + + function selectNode(node) { + var range = _contentKitEditorUtilsCompat.doc.createRange(); + var selection = _contentKitEditorUtilsCompat.win.getSelection(); + range.setStart(node, 0); + range.setEnd(node, node.length); + selection.removeAllRanges(); + selection.addRange(range); + } + + function setCursorIndexInElement(element, index) { + var range = _contentKitEditorUtilsCompat.doc.createRange(); + var selection = _contentKitEditorUtilsCompat.win.getSelection(); + range.setStart(element, index); + range.collapse(true); + selection.removeAllRanges(); + selection.addRange(range); + } + + function setCursorToStartOfElement(element) { + setCursorIndexInElement(element, 0); + } + + function getCursorOffsetInElement(element) { + // http://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container/4812022#4812022 + var caretOffset = 0; + var selection = _contentKitEditorUtilsCompat.win.getSelection(); + if (selection.rangeCount > 0) { + var range = selection.getRangeAt(0); + var preCaretRange = range.cloneRange(); + preCaretRange.selectNodeContents(element); + preCaretRange.setEnd(range.endContainer, range.endOffset); + caretOffset = preCaretRange.toString().length; + } + return caretOffset; + } + + exports.getDirectionOfSelection = getDirectionOfSelection; + exports.getSelectionElement = getSelectionElement; + exports.getSelectionBlockElement = getSelectionBlockElement; + exports.getSelectionTagName = getSelectionTagName; + exports.getSelectionBlockTagName = getSelectionBlockTagName; + exports.tagsInSelection = tagsInSelection; + exports.selectionIsInElement = selectionIsInElement; + exports.selectionIsEditable = selectionIsEditable; + exports.restoreRange = restoreRange; + exports.selectNode = selectNode; + exports.setCursorToStartOfElement = setCursorToStartOfElement; + exports.setCursorIndexInElement = setCursorIndexInElement; + exports.getCursorOffsetInElement = getCursorOffsetInElement; +}); +define('content-kit-editor/utils/win', ['exports', 'content-kit-compiler'], function (exports, _contentKitCompiler) { + 'use strict'; + + var win; + if (typeof window !== 'undefined') { + win = window; + } else { + // jsdom provides a defaultView + win = _contentKitCompiler.doc.defaultView; + } + + exports['default'] = win; +}); +define('content-kit-editor/views/embed-intent', ['exports', 'content-kit-editor/views/view', 'content-kit-editor/views/toolbar', 'content-kit-utils', 'content-kit-editor/utils/selection-utils', 'content-kit-editor/utils/element-utils', 'content-kit-editor/utils/keycodes', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorViewsView, _contentKitEditorViewsToolbar, _contentKitUtils, _contentKitEditorUtilsSelectionUtils, _contentKitEditorUtilsElementUtils, _contentKitEditorUtilsKeycodes, _contentKitEditorUtilsCompat) { + 'use strict'; + + var LayoutStyle = { + GUTTER: 1, + CENTERED: 2 + }; + + function computeLayoutStyle(rootElement) { + if (rootElement.getBoundingClientRect().left > 100) { + return LayoutStyle.GUTTER; + } + return LayoutStyle.CENTERED; + } + + function EmbedIntent(options) { + var embedIntent = this; + var rootElement = embedIntent.rootElement = options.rootElement; + options.classNames = ['ck-embed-intent']; + _contentKitEditorViewsView['default'].call(embedIntent, options); + + embedIntent.isActive = false; + embedIntent.editorContext = options.editorContext; + embedIntent.loadingIndicator = (0, _contentKitEditorUtilsElementUtils.createDiv)('ck-embed-loading'); + embedIntent.button = _contentKitEditorUtilsCompat.doc.createElement('button'); + embedIntent.button.className = 'ck-embed-intent-btn'; + embedIntent.button.title = 'Insert image or embed...'; + embedIntent.element.appendChild(embedIntent.button); + embedIntent.button.addEventListener('mouseup', function (e) { + if (embedIntent.isActive) { + embedIntent.deactivate(); + } else { + embedIntent.activate(); + } + e.stopPropagation(); + }); + + embedIntent.toolbar = new _contentKitEditorViewsToolbar['default']({ + container: embedIntent.element, + embedIntent: embedIntent, + editor: embedIntent.editorContext, + commands: options.commands, + direction: _contentKitEditorViewsToolbar['default'].Direction.RIGHT + }); + + function embedIntentHandler() { + var blockElement = (0, _contentKitEditorUtilsSelectionUtils.getSelectionBlockElement)(); + if (blockElement && (0, _contentKitEditorUtilsElementUtils.elementContentIsEmpty)(blockElement)) { + embedIntent.showAt(blockElement); + } else { + embedIntent.hide(); + } + } + + rootElement.addEventListener('keyup', embedIntentHandler); + _contentKitEditorUtilsCompat.doc.addEventListener('mouseup', function () { + setTimeout(function () { + embedIntentHandler(); + }); + }); + + _contentKitEditorUtilsCompat.doc.addEventListener('keyup', function (e) { + if (e.keyCode === _contentKitEditorUtilsKeycodes['default'].ESC) { + embedIntent.hide(); + } + }); + + _contentKitEditorUtilsCompat.win.addEventListener('resize', function () { + if (embedIntent.isShowing) { + embedIntent.reposition(); + } + }); + } + (0, _contentKitUtils.inherit)(EmbedIntent, _contentKitEditorViewsView['default']); + + EmbedIntent.prototype.hide = function () { + if (EmbedIntent._super.prototype.hide.call(this)) { + this.deactivate(); + } + }; + + EmbedIntent.prototype.showAt = function (node) { + this.atNode = node; + this.show(); + this.deactivate(); + this.reposition(); + }; + + EmbedIntent.prototype.reposition = function () { + if (computeLayoutStyle(this.rootElement) === LayoutStyle.GUTTER) { + (0, _contentKitEditorUtilsElementUtils.positionElementToLeftOf)(this.element, this.atNode); + } else { + (0, _contentKitEditorUtilsElementUtils.positionElementCenteredIn)(this.element, this.atNode); + } + }; + + EmbedIntent.prototype.activate = function () { + if (!this.isActive) { + this.addClass('activated'); + this.toolbar.show(); + this.isActive = true; + } + }; + + EmbedIntent.prototype.deactivate = function () { + if (this.isActive) { + this.removeClass('activated'); + this.toolbar.hide(); + this.isActive = false; + } + }; + + EmbedIntent.prototype.showLoading = function () { + var embedIntent = this; + var loadingIndicator = embedIntent.loadingIndicator; + embedIntent.hide(); + embedIntent.atNode.appendChild(loadingIndicator); + }; + + EmbedIntent.prototype.hideLoading = function () { + this.atNode.removeChild(this.loadingIndicator); + }; + + exports['default'] = EmbedIntent; +}); +define('content-kit-editor/views/message', ['exports', 'content-kit-editor/views/view', 'content-kit-utils'], function (exports, _contentKitEditorViewsView, _contentKitUtils) { + 'use strict'; + + var defaultClassNames = ['ck-message']; + + function Message(options) { + options = options || {}; + options.classNames = defaultClassNames; + _contentKitEditorViewsView['default'].call(this, options); + } + (0, _contentKitUtils.inherit)(Message, _contentKitEditorViewsView['default']); + + function show(view, message) { + view.element.innerHTML = message; + Message._super.prototype.show.call(view); + setTimeout(function () { + view.hide(); + }, 3200); + } + + Message.prototype.showInfo = function (message) { + this.setClasses(defaultClassNames); + show(this, message); + }; + + Message.prototype.showError = function (message) { + this.addClass('ck-message-error'); + show(this, message); + }; + + exports['default'] = Message; +}); +define('content-kit-editor/views/prompt', ['exports', 'content-kit-editor/views/view', 'content-kit-utils', 'content-kit-editor/utils/selection-utils', 'content-kit-editor/utils/element-utils', 'content-kit-editor/utils/keycodes', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorViewsView, _contentKitUtils, _contentKitEditorUtilsSelectionUtils, _contentKitEditorUtilsElementUtils, _contentKitEditorUtilsKeycodes, _contentKitEditorUtilsCompat) { + 'use strict'; + + var container = _contentKitEditorUtilsCompat.doc.body; + var hiliter = (0, _contentKitEditorUtilsElementUtils.createDiv)('ck-editor-hilite'); + + function positionHiliteRange(range) { + var rect = range.getBoundingClientRect(); + var style = hiliter.style; + style.width = rect.width + 'px'; + style.height = rect.height + 'px'; + (0, _contentKitEditorUtilsElementUtils.positionElementToRect)(hiliter, rect); + } + + function Prompt(options) { + var prompt = this; + options.tagName = 'input'; + _contentKitEditorViewsView['default'].call(prompt, options); + + prompt.command = options.command; + prompt.element.placeholder = options.placeholder || ''; + prompt.element.addEventListener('mouseup', function (e) { + e.stopPropagation(); + }); // prevents closing prompt when clicking input + prompt.element.addEventListener('keyup', function (e) { + var entry = this.value; + if (entry && prompt.range && !e.shiftKey && e.which === _contentKitEditorUtilsKeycodes['default'].ENTER) { + (0, _contentKitEditorUtilsSelectionUtils.restoreRange)(prompt.range); + prompt.command.exec(entry); + if (prompt.onComplete) { + prompt.onComplete(); + } + } + }); + + _contentKitEditorUtilsCompat.win.addEventListener('resize', function () { + var activeHilite = hiliter.parentNode; + var range = prompt.range; + if (activeHilite && range) { + positionHiliteRange(range); + } + }); + } + (0, _contentKitUtils.inherit)(Prompt, _contentKitEditorViewsView['default']); + + Prompt.prototype.show = function (callback) { + var prompt = this; + var element = prompt.element; + var selection = _contentKitEditorUtilsCompat.win.getSelection(); + var range = selection && selection.rangeCount && selection.getRangeAt(0); + element.value = null; + prompt.range = range || null; + if (range) { + container.appendChild(hiliter); + positionHiliteRange(prompt.range); + setTimeout(function () { + element.focus(); + }); // defer focus (disrupts mouseup events) + if (callback) { + prompt.onComplete = callback; + } + } + }; + + Prompt.prototype.hide = function () { + if (hiliter.parentNode) { + container.removeChild(hiliter); + } + }; + + exports['default'] = Prompt; +}); +define('content-kit-editor/views/text-format-toolbar', ['exports', 'content-kit-editor/views/toolbar', 'content-kit-utils', 'content-kit-editor/utils/selection-utils', 'content-kit-editor/utils/keycodes', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorViewsToolbar, _contentKitUtils, _contentKitEditorUtilsSelectionUtils, _contentKitEditorUtilsKeycodes, _contentKitEditorUtilsCompat) { + 'use strict'; + + function selectionIsEditableByToolbar(selection, toolbar) { + return (0, _contentKitEditorUtilsSelectionUtils.selectionIsEditable)(selection) && (0, _contentKitEditorUtilsSelectionUtils.selectionIsInElement)(selection, toolbar.rootElement); + } + + function handleTextSelection(toolbar) { + var selection = _contentKitEditorUtilsCompat.win.getSelection(); + if (toolbar.sticky) { + toolbar.updateForSelection(selectionIsEditableByToolbar(selection, toolbar) ? selection : null); + } else { + if (selection.isCollapsed || selection.toString().trim() === '' || !selectionIsEditableByToolbar(selection, toolbar)) { + toolbar.hide(); + } else { + toolbar.show(); + toolbar.updateForSelection(selection); + } + } + } + + function TextFormatToolbar(options) { + var toolbar = this; + _contentKitEditorViewsToolbar['default'].call(this, options); + toolbar.rootElement = options.rootElement; + toolbar.rootElement.addEventListener('keyup', function () { + handleTextSelection(toolbar); + }); + + _contentKitEditorUtilsCompat.doc.addEventListener('mouseup', function () { + setTimeout(function () { + handleTextSelection(toolbar); + }); + }); + + _contentKitEditorUtilsCompat.doc.addEventListener('keyup', function (e) { + var key = e.keyCode; + if (key === 116) { + //F5 + toolbar.toggleSticky(); + handleTextSelection(toolbar); + } else if (!toolbar.sticky && key === _contentKitEditorUtilsKeycodes['default'].ESC) { + toolbar.hide(); + } + }); + + _contentKitEditorUtilsCompat.win.addEventListener('resize', function () { + if (!toolbar.sticky && toolbar.isShowing) { + var activePromptRange = toolbar.activePrompt && toolbar.activePrompt.range; + toolbar.positionToContent(activePromptRange ? activePromptRange : _contentKitEditorUtilsCompat.win.getSelection().getRangeAt(0)); + } + }); + } + (0, _contentKitUtils.inherit)(TextFormatToolbar, _contentKitEditorViewsToolbar['default']); + + exports['default'] = TextFormatToolbar; +}); +define('content-kit-editor/views/toolbar-button', ['exports', 'content-kit-compiler'], function (exports, _contentKitCompiler) { + 'use strict'; + + var buttonClassName = 'ck-toolbar-btn'; + + function ToolbarButton(options) { + var button = this; + var toolbar = options.toolbar; + var command = options.command; + var prompt = command.prompt; + var element = _contentKitCompiler.doc.createElement('button'); + + button.element = element; + button.command = command; + button.isActive = false; + + element.title = command.name; + element.className = buttonClassName; + element.innerHTML = command.button; + element.addEventListener('mouseup', function (e) { + if (!button.isActive && prompt) { + toolbar.displayPrompt(prompt); + } else { + command.exec(); + toolbar.updateForSelection(); + } + e.stopPropagation(); + }); + } + + ToolbarButton.prototype = { + setActive: function setActive() { + var button = this; + if (!button.isActive) { + button.element.className = buttonClassName + ' active'; + button.isActive = true; + } + }, + setInactive: function setInactive() { + var button = this; + if (button.isActive) { + button.element.className = buttonClassName; + button.isActive = false; + } + } + }; + + exports['default'] = ToolbarButton; +}); +define('content-kit-editor/views/toolbar', ['exports', 'content-kit-editor/views/view', 'content-kit-editor/views/toolbar-button', 'content-kit-utils', 'content-kit-editor/utils/selection-utils', 'content-kit-editor/utils/element-utils', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorViewsView, _contentKitEditorViewsToolbarButton, _contentKitUtils, _contentKitEditorUtilsSelectionUtils, _contentKitEditorUtilsElementUtils, _contentKitEditorUtilsCompat) { + 'use strict'; + + var ToolbarDirection = { + TOP: 1, + RIGHT: 2 + }; + + function selectionContainsButtonsTag(selectedTags, buttonsTags) { + return selectedTags.filter(function (tag) { + return buttonsTags.indexOf(tag) > -1; + }).length; + } + + function updateButtonsForSelection(buttons, selection) { + var selectedTags = (0, _contentKitEditorUtilsSelectionUtils.tagsInSelection)(selection); + var len = buttons.length; + var i, button; + + for (i = 0; i < len; i++) { + button = buttons[i]; + if (selectionContainsButtonsTag(selectedTags, button.command.mappedTags)) { + button.setActive(); + } else { + button.setInactive(); + } + } + } + + function Toolbar(options) { + options = options || {}; + var toolbar = this; + var commands = options.commands; + var commandCount = commands && commands.length, + i; + options.classNames = ['ck-toolbar']; + _contentKitEditorViewsView['default'].call(toolbar, options); + + toolbar.setSticky(options.sticky || false); + toolbar.setDirection(options.direction || ToolbarDirection.TOP); + toolbar.editor = options.editor || null; + toolbar.embedIntent = options.embedIntent || null; + toolbar.activePrompt = null; + toolbar.buttons = []; + + toolbar.contentElement = (0, _contentKitEditorUtilsElementUtils.createDiv)('ck-toolbar-content'); + toolbar.promptContainerElement = (0, _contentKitEditorUtilsElementUtils.createDiv)('ck-toolbar-prompt'); + toolbar.buttonContainerElement = (0, _contentKitEditorUtilsElementUtils.createDiv)('ck-toolbar-buttons'); + toolbar.contentElement.appendChild(toolbar.promptContainerElement); + toolbar.contentElement.appendChild(toolbar.buttonContainerElement); + toolbar.element.appendChild(toolbar.contentElement); + + for (i = 0; i < commandCount; i++) { + this.addCommand(commands[i]); + } + + // Closes prompt if displayed when changing selection + _contentKitEditorUtilsCompat.doc.addEventListener('mouseup', function () { + toolbar.dismissPrompt(); + }); + } + (0, _contentKitUtils.inherit)(Toolbar, _contentKitEditorViewsView['default']); + + Toolbar.prototype.hide = function () { + if (Toolbar._super.prototype.hide.call(this)) { + var style = this.element.style; + style.left = ''; + style.top = ''; + this.dismissPrompt(); + } + }; + + Toolbar.prototype.addCommand = function (command) { + command.editorContext = this.editor; + command.embedIntent = this.embedIntent; + var button = new _contentKitEditorViewsToolbarButton['default']({ command: command, toolbar: this }); + this.buttons.push(button); + this.buttonContainerElement.appendChild(button.element); + }; + + Toolbar.prototype.displayPrompt = function (prompt) { + var toolbar = this; + (0, _contentKitEditorUtilsElementUtils.swapElements)(toolbar.promptContainerElement, toolbar.buttonContainerElement); + toolbar.promptContainerElement.appendChild(prompt.element); + prompt.show(function () { + toolbar.dismissPrompt(); + toolbar.updateForSelection(); + }); + toolbar.activePrompt = prompt; + }; + + Toolbar.prototype.dismissPrompt = function () { + var toolbar = this; + var activePrompt = toolbar.activePrompt; + if (activePrompt) { + activePrompt.hide(); + (0, _contentKitEditorUtilsElementUtils.swapElements)(toolbar.buttonContainerElement, toolbar.promptContainerElement); + toolbar.activePrompt = null; + } + }; + + Toolbar.prototype.updateForSelection = function (selection) { + var toolbar = this; + selection = selection || _contentKitEditorUtilsCompat.win.getSelection(); + if (toolbar.sticky) { + updateButtonsForSelection(toolbar.buttons, selection); + } else if (!selection.isCollapsed) { + toolbar.positionToContent(selection.getRangeAt(0)); + updateButtonsForSelection(toolbar.buttons, selection); + } + }; + + Toolbar.prototype.positionToContent = function (content) { + var directions = ToolbarDirection; + var positioningMethod, position, sideEdgeOffset; + switch (this.direction) { + case directions.RIGHT: + positioningMethod = _contentKitEditorUtilsElementUtils.positionElementToRightOf; + break; + default: + positioningMethod = _contentKitEditorUtilsElementUtils.positionElementCenteredAbove; + } + position = positioningMethod(this.element, content); + sideEdgeOffset = Math.min(Math.max(10, position.left), _contentKitEditorUtilsCompat.doc.body.clientWidth - this.element.offsetWidth - 10); + this.contentElement.style.transform = 'translateX(' + (sideEdgeOffset - position.left) + 'px)'; + }; + + Toolbar.prototype.setDirection = function (direction) { + this.direction = direction; + if (direction === ToolbarDirection.RIGHT) { + this.addClass('right'); + } else { + this.removeClass('right'); + } + }; + + Toolbar.prototype.setSticky = function (sticky) { + this.sticky = sticky; + if (sticky) { + this.addClass('sticky'); + this.element.removeAttribute('style'); // clears any prior positioning + this.show(); + } else { + this.removeClass('sticky'); + this.hide(); + } + }; + + Toolbar.prototype.toggleSticky = function () { + this.setSticky(!this.sticky); + }; + + Toolbar.Direction = ToolbarDirection; + + exports['default'] = Toolbar; +}); +define('content-kit-editor/views/tooltip', ['exports', 'content-kit-editor/views/view', 'content-kit-utils', 'content-kit-editor/utils/element-utils'], function (exports, _contentKitEditorViewsView, _contentKitUtils, _contentKitEditorUtilsElementUtils) { + 'use strict'; + + function Tooltip(options) { + var tooltip = this; + var rootElement = options.rootElement; + var delay = options.delay || 200; + var timeout; + options.classNames = ['ck-tooltip']; + _contentKitEditorViewsView['default'].call(tooltip, options); + + rootElement.addEventListener('mouseover', function (e) { + var target = (0, _contentKitEditorUtilsElementUtils.getEventTargetMatchingTag)(options.showForTag, e.target, rootElement); + if (target && target.isContentEditable) { + timeout = setTimeout(function () { + tooltip.showLink(target.href, target); + }, delay); + } + }); + + rootElement.addEventListener('mouseout', function (e) { + clearTimeout(timeout); + var toElement = e.toElement || e.relatedTarget; + if (toElement && toElement.className !== tooltip.element.className) { + tooltip.hide(); + } + }); + } + (0, _contentKitUtils.inherit)(Tooltip, _contentKitEditorViewsView['default']); + + Tooltip.prototype.showMessage = function (message, element) { + var tooltip = this; + var tooltipElement = tooltip.element; + tooltipElement.innerHTML = message; + tooltip.show(); + (0, _contentKitEditorUtilsElementUtils.positionElementCenteredBelow)(tooltipElement, element); + }; + + Tooltip.prototype.showLink = function (link, element) { + var message = '' + link + ''; + this.showMessage(message, element); + }; + + exports['default'] = Tooltip; +}); +define('content-kit-editor/views/view', ['exports', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorUtilsCompat) { + 'use strict'; + + function renderClasses(view) { + var classNames = view.classNames; + if (classNames && classNames.length) { + view.element.className = classNames.join(' '); + } else if (view.element.className) { + view.element.removeAttribute('className'); + } + } + + function View(options) { + options = options || {}; + this.tagName = options.tagName || 'div'; + this.classNames = options.classNames || []; + this.element = _contentKitEditorUtilsCompat.doc.createElement(this.tagName); + this.container = options.container || _contentKitEditorUtilsCompat.doc.body; + this.isShowing = false; + renderClasses(this); + } + + View.prototype = { + show: function show() { + var view = this; + if (!view.isShowing) { + view.container.appendChild(view.element); + view.isShowing = true; + return true; + } + }, + hide: function hide() { + var view = this; + if (view.isShowing) { + view.container.removeChild(view.element); + view.isShowing = false; + return true; + } + }, + addClass: function addClass(className) { + var index = this.classNames && this.classNames.indexOf(className); + if (index === -1) { + this.classNames.push(className); + renderClasses(this); + } + }, + removeClass: function removeClass(className) { + var index = this.classNames && this.classNames.indexOf(className); + if (index > -1) { + this.classNames.splice(index, 1); + renderClasses(this); + } + }, + setClasses: function setClasses(classNameArr) { + this.classNames = classNameArr; + renderClasses(this); + } + }; + + exports['default'] = View; +}); +define("content-kit-utils/array-utils", ["exports"], function (exports) { + /** + * Converts an array-like object (i.e. NodeList) to Array + * Note: could just use Array.prototype.slice but does not work in IE <= 8 + */ + "use strict"; + + function toArray(obj) { + var array = []; + var i = obj && obj.length >>> 0; // cast to Uint32 + while (i--) { + array[i] = obj[i]; + } + return array; + } + + /** + * Computes the sum of values in a (sparse) array + */ + function sumSparseArray(array) { + var sum = 0, + i; + for (i in array) { + // 'for in' is better for sparse arrays + if (array.hasOwnProperty(i)) { + sum += array[i]; + } + } + return sum; + } + + exports.toArray = toArray; + exports.sumSparseArray = sumSparseArray; +}); +define('content-kit-utils', ['exports', 'content-kit-utils/array-utils', 'content-kit-utils/node-utils', 'content-kit-utils/object-utils', 'content-kit-utils/string-utils'], function (exports, _contentKitUtilsArrayUtils, _contentKitUtilsNodeUtils, _contentKitUtilsObjectUtils, _contentKitUtilsStringUtils) { + 'use strict'; + + exports.toArray = _contentKitUtilsArrayUtils.toArray; + exports.sumSparseArray = _contentKitUtilsArrayUtils.sumSparseArray; + exports.textOfNode = _contentKitUtilsNodeUtils.textOfNode; + exports.unwrapNode = _contentKitUtilsNodeUtils.unwrapNode; + exports.attributesForNode = _contentKitUtilsNodeUtils.attributesForNode; + exports.mergeWithOptions = _contentKitUtilsObjectUtils.mergeWithOptions; + exports.merge = _contentKitUtilsObjectUtils.merge; + exports.inherit = _contentKitUtilsObjectUtils.inherit; + exports.trim = _contentKitUtilsStringUtils.trim; + exports.trimLeft = _contentKitUtilsStringUtils.trimLeft; + exports.underscore = _contentKitUtilsStringUtils.underscore; + exports.sanitizeWhitespace = _contentKitUtilsStringUtils.sanitizeWhitespace; + exports.injectIntoString = _contentKitUtilsStringUtils.injectIntoString; + + // needs a default export to be compatible with + // broccoli-multi-builder + exports['default'] = {}; +}); +define('content-kit-utils/node-utils', ['exports', 'content-kit-utils/string-utils', 'content-kit-utils/array-utils'], function (exports, _contentKitUtilsStringUtils, _contentKitUtilsArrayUtils) { + 'use strict'; + + /** + * Returns plain-text of a `Node` + */ + function textOfNode(node) { + var text = node.textContent || node.innerText; + return text ? (0, _contentKitUtilsStringUtils.sanitizeWhitespace)(text) : ''; + } + + /** + * Replaces a `Node` with its children + */ + function unwrapNode(node) { + if (node.hasChildNodes()) { + var children = (0, _contentKitUtilsArrayUtils.toArray)(node.childNodes); + var len = children.length; + var parent = node.parentNode, + i; + for (i = 0; i < len; i++) { + parent.insertBefore(children[i], node); + } + } + } + + /** + * Extracts attributes of a `Node` to a hash of key/value pairs + */ + function attributesForNode(node, blacklist) { + var attrs = node.attributes; + var len = attrs && attrs.length; + var i, attr, name, hash; + + for (i = 0; i < len; i++) { + attr = attrs[i]; + name = attr.name; + if (attr.specified && attr.value) { + if (blacklist && name in blacklist) { + continue; + } + hash = hash || {}; + hash[name] = attr.value; + } + } + return hash; + } + + exports.textOfNode = textOfNode; + exports.unwrapNode = unwrapNode; + exports.attributesForNode = attributesForNode; +}); +define("content-kit-utils/object-utils", ["exports"], function (exports) { + /** + * Merges defaults/options into an Object + * Useful for constructors + */ + "use strict"; + + function mergeWithOptions(original, updates, options) { + options = options || {}; + for (var prop in updates) { + if (options.hasOwnProperty(prop)) { + original[prop] = options[prop]; + } else if (updates.hasOwnProperty(prop)) { + original[prop] = updates[prop]; + } + } + return original; + } + + /** + * Merges properties of one object into another + */ + function merge(original, updates) { + return mergeWithOptions(original, updates); + } + + /** + * Prototype inheritance helper + */ + function inherit(Subclass, Superclass) { + for (var key in Superclass) { + if (Superclass.hasOwnProperty(key)) { + Subclass[key] = Superclass[key]; + } + } + Subclass.prototype = new Superclass(); + Subclass.constructor = Subclass; + Subclass._super = Superclass; + } + + exports.mergeWithOptions = mergeWithOptions; + exports.merge = merge; + exports.inherit = inherit; +}); +define('content-kit-utils/string-utils', ['exports'], function (exports) { + 'use strict'; + + var RegExpTrim = /^\s+|\s+$/g; + var RegExpTrimLeft = /^\s+/; + var RegExpWSChars = /(\r\n|\n|\r|\t)/gm; + var RegExpMultiWS = /\s+/g; + var RegExpNonAlphaNum = /[^a-zA-Z\d]/g; + + /** + * String.prototype.trim polyfill + * Removes whitespace at beginning and end of string + */ + function trim(string) { + return string ? (string + '').replace(RegExpTrim, '') : ''; + } + + /** + * String.prototype.trimLeft polyfill + * Removes whitespace at beginning of string + */ + function trimLeft(string) { + return string ? (string + '').replace(RegExpTrimLeft, '') : ''; + } + + /** + * Replaces non-alphanumeric chars with underscores + */ + function underscore(string) { + return string ? trim(string + '').replace(RegExpNonAlphaNum, '_') : ''; + } + + /** + * Cleans line breaks, tabs, then multiple occuring whitespaces. + */ + function sanitizeWhitespace(string) { + return string ? (string + '').replace(RegExpWSChars, '').replace(RegExpMultiWS, ' ') : ''; + } + + /** + * Injects a string into another string at the index specified + */ + function injectIntoString(string, injection, index) { + return string.substr(0, index) + injection + string.substr(index); + } + + exports.trim = trim; + exports.trimLeft = trimLeft; + exports.underscore = underscore; + exports.sanitizeWhitespace = sanitizeWhitespace; + exports.injectIntoString = injectIntoString; +}); +require("content-kit-editor")["registerGlobal"](window, document); +})(); \ No newline at end of file diff --git a/website/index.hml b/website/index.hml new file mode 100644 index 000000000..343a43d54 --- /dev/null +++ b/website/index.hml @@ -0,0 +1,10 @@ + + + + + Content Kit Editor 0.2.0 + + + Click to view the Demo. + + From bb36364c86f87721b6572f6e8adbe5ff2e8b2ca8 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Thu, 9 Jul 2015 09:50:14 -0400 Subject: [PATCH 33/77] explain how to deploy website in readme --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index c177d8b66..b16779de8 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,13 @@ var editor = new ContentKit.Editor(this.element, options); * `editor.loadPost(post)` - render the editor with a post. **[FIXME Implement]** * `editor.serializePost()` - serialize the current post for persistence. **[FIXME Implement]** +### Deploy the demo website + +The demo website is hosted at github pages. +To build the website, run `npm run build-website`. +To deploy it to the gh-pages branch run `npm run deploy-website`. +Visit [http://bustlelabs.github.io/content-kit-editor/demo](http://bustlelabs.github.io/content-kit-editor/demo). + ### Contributing Running ContentKit tests and demo server locally requires the following dependencies: From 45ce1f03e7d21ddcdd051bcdef3c307faa9dc2d6 Mon Sep 17 00:00:00 2001 From: Matthew Beale Date: Thu, 9 Jul 2015 11:33:11 -0400 Subject: [PATCH 34/77] Drop compiler dependency --- Brocfile.js | 3 +- package.json | 1 - src/js/commands/bold.js | 5 +- src/js/commands/card.js | 5 +- src/js/commands/format-block.js | 5 +- src/js/commands/heading.js | 3 +- src/js/commands/image.js | 12 +- src/js/commands/italic.js | 5 +- src/js/commands/link.js | 3 +- src/js/commands/list.js | 8 +- src/js/commands/oembed.js | 14 +- src/js/commands/ordered-list.js | 3 +- src/js/commands/quote.js | 3 +- src/js/commands/subheading.js | 3 +- src/js/commands/text-format.js | 5 +- src/js/commands/unordered-list.js | 3 +- src/js/editor/editor-factory.js | 38 ---- src/js/editor/editor.js | 116 ++++++------ src/js/index.js | 24 +-- src/js/models/post.js | 60 +++++++ src/js/parsers/dom.js | 168 ++++++++++++++++++ src/js/parsers/mobiledoc.js | 66 +++++++ .../{new-dom-renderer.js => editor-dom.js} | 0 src/js/renderers/editor-html-renderer.js | 70 -------- src/js/renderers/instagram.js | 7 - src/js/renderers/link-image-renderer.js | 7 - .../{new-serializer.js => mobiledoc.js} | 2 +- src/js/renderers/twitter.js | 7 - src/js/renderers/youtube.js | 19 -- src/js/runtime/renderers/mobiledoc-dom.js | 90 ++++++++++ src/js/utils/doc.js | 5 - src/js/utils/element-map.js | 12 +- src/js/utils/element-utils.js | 10 +- src/js/utils/http-utils.js | 5 +- src/js/utils/post-builder.js | 59 ++++++ src/js/utils/selection-utils.js | 27 +-- src/js/utils/win.js | 11 -- src/js/views/embed-intent.js | 9 +- src/js/views/prompt.js | 7 +- src/js/views/text-format-toolbar.js | 11 +- src/js/views/toolbar-button.js | 4 +- src/js/views/toolbar.js | 7 +- src/js/views/view.js | 6 +- 43 files changed, 572 insertions(+), 356 deletions(-) delete mode 100644 src/js/editor/editor-factory.js create mode 100644 src/js/models/post.js create mode 100644 src/js/parsers/dom.js create mode 100644 src/js/parsers/mobiledoc.js rename src/js/renderers/{new-dom-renderer.js => editor-dom.js} (100%) delete mode 100644 src/js/renderers/editor-html-renderer.js delete mode 100644 src/js/renderers/instagram.js delete mode 100644 src/js/renderers/link-image-renderer.js rename src/js/renderers/{new-serializer.js => mobiledoc.js} (98%) delete mode 100644 src/js/renderers/twitter.js delete mode 100644 src/js/renderers/youtube.js create mode 100644 src/js/runtime/renderers/mobiledoc-dom.js delete mode 100644 src/js/utils/doc.js create mode 100644 src/js/utils/post-builder.js delete mode 100644 src/js/utils/win.js diff --git a/Brocfile.js b/Brocfile.js index 1d32bcaf0..45d176238 100644 --- a/Brocfile.js +++ b/Brocfile.js @@ -8,8 +8,7 @@ var demo = require('./broccoli/demo'); var jquery = require('./broccoli/jquery'); var vendoredModules = [ - {name: 'content-kit-compiler', options: {libDirName: 'src'}}, - {name: 'content-kit-utils', options: {libDirName: 'src'}} + {name: 'content-kit-utils', options: {libDirName: 'src'}} ]; var packageName = require('./package.json').name; diff --git a/package.json b/package.json index 7a720767b..5f7aa9f1f 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,6 @@ "broccoli-merge-trees": "^0.2.1", "broccoli-multi-builder": "^0.2.5", "broccoli-test-builder": "^0.1.0", - "content-kit-compiler": "^0.3.1", "content-kit-utils": "^0.2.0", "del": "^1.1.1", "esperanto": "^0.6.32", diff --git a/src/js/commands/bold.js b/src/js/commands/bold.js index 50e25939a..e9af24aaa 100644 --- a/src/js/commands/bold.js +++ b/src/js/commands/bold.js @@ -1,15 +1,14 @@ import TextFormatCommand from './text-format'; import { getSelectionBlockTagName } from '../utils/selection-utils'; import { inherit } from 'content-kit-utils'; -import { Type } from 'content-kit-compiler'; var RegExpHeadingTag = /^(h1|h2|h3|h4|h5|h6)$/i; function BoldCommand() { TextFormatCommand.call(this, { name: 'bold', - tag: Type.BOLD.tag, - mappedTags: Type.BOLD.mappedTags, + tag: 'strong', + mappedTags: ['b'], button: '' }); } diff --git a/src/js/commands/card.js b/src/js/commands/card.js index f5f0455cf..00422eed9 100644 --- a/src/js/commands/card.js +++ b/src/js/commands/card.js @@ -1,11 +1,8 @@ import Command from './base'; import { inherit } from 'content-kit-utils'; -import { - BlockModel, - Type -} from 'content-kit-compiler'; function injectCardBlock(cardName, cardPayload, editor, index) { + throw new Error('Unimplemented: BlockModel and Type.CARD are no longer things'); // FIXME: Do we change the block model internal representation here? var cardBlock = BlockModel.createWithType(Type.CARD, { attributes: { diff --git a/src/js/commands/format-block.js b/src/js/commands/format-block.js index 60a329ab2..47fc11de2 100644 --- a/src/js/commands/format-block.js +++ b/src/js/commands/format-block.js @@ -1,8 +1,6 @@ import TextFormatCommand from './text-format'; import { getSelectionBlockElement, selectNode } from '../utils/selection-utils'; import { inherit } from 'content-kit-utils'; -import { Type } from 'content-kit-compiler'; -import { doc } from 'content-kit-compiler'; function FormatBlockCommand(options) { options = options || {}; @@ -18,12 +16,13 @@ FormatBlockCommand.prototype.exec = function() { var blockElement = getSelectionBlockElement(); // Allow block commands to be toggled back to a text block if(tag === blockElement.tagName.toLowerCase()) { + throw new Error('Unimplemented: Type.BOLD.paragraph must be replaced'); value = Type.PARAGRAPH.tag; } else { // Flattens the selection before applying the block format. // Otherwise, undesirable nested blocks can occur. // TODO: would love to be able to remove this - var flatNode = doc.createTextNode(blockElement.textContent); + var flatNode = document.createTextNode(blockElement.textContent); blockElement.parentNode.insertBefore(flatNode, blockElement); blockElement.parentNode.removeChild(blockElement); selectNode(flatNode); diff --git a/src/js/commands/heading.js b/src/js/commands/heading.js index c28816adb..ac102035d 100644 --- a/src/js/commands/heading.js +++ b/src/js/commands/heading.js @@ -1,11 +1,10 @@ import FormatBlockCommand from './format-block'; import { inherit } from 'content-kit-utils'; -import { Type } from 'content-kit-compiler'; function HeadingCommand() { FormatBlockCommand.call(this, { name: 'heading', - tag: Type.HEADING.tag, + tag: 'h2', button: '1' }); } diff --git a/src/js/commands/image.js b/src/js/commands/image.js index 5df159531..3b61fd432 100644 --- a/src/js/commands/image.js +++ b/src/js/commands/image.js @@ -1,15 +1,10 @@ import Command from './base'; import Message from '../views/message'; -import { - Type, - BlockModel, -} from 'content-kit-compiler'; -import { win, doc } from 'content-kit-editor/utils/compat'; import { inherit } from 'content-kit-utils'; import { FileUploader } from '../utils/http-utils'; function createFileInput(command) { - var fileInput = doc.createElement('input'); + var fileInput = document.createElement('input'); fileInput.type = 'file'; fileInput.accept = 'image/*'; fileInput.className = 'ck-file-input'; @@ -20,12 +15,13 @@ function createFileInput(command) { } function injectImageBlock(src, editor, index) { + throw new Error('Unimplemented: BlockModel and Type.IMAGE are no longer things'); var imageModel = BlockModel.createWithType(Type.IMAGE, { attributes: { src: src } }); editor.replaceBlock(imageModel, index); } function renderFromFile(file, editor, index) { - if (file && win.FileReader) { + if (file && window.FileReader) { var reader = new FileReader(); reader.onload = function(e) { var base64Src = e.target.result; @@ -51,7 +47,7 @@ ImageCommand.prototype = { var fileInput = this.fileInput; if (!fileInput) { fileInput = this.fileInput = createFileInput(this); - doc.body.appendChild(fileInput); + document.body.appendChild(fileInput); } fileInput.dispatchEvent(new MouseEvent('click', { bubbles: false })); }, diff --git a/src/js/commands/italic.js b/src/js/commands/italic.js index 5380d09d0..f361a89ea 100644 --- a/src/js/commands/italic.js +++ b/src/js/commands/italic.js @@ -1,12 +1,11 @@ import TextFormatCommand from './text-format'; import { inherit } from 'content-kit-utils'; -import { Type }from 'content-kit-compiler'; function ItalicCommand() { TextFormatCommand.call(this, { name: 'italic', - tag: Type.ITALIC.tag, - mappedTags: Type.ITALIC.mappedTags, + tag: 'em', + mappedTags: ['i'], button: '' }); } diff --git a/src/js/commands/link.js b/src/js/commands/link.js index 9b79d5bc9..ad6e065cd 100644 --- a/src/js/commands/link.js +++ b/src/js/commands/link.js @@ -2,14 +2,13 @@ import TextFormatCommand from './text-format'; import Prompt from '../views/prompt'; import { getSelectionTagName } from '../utils/selection-utils'; import { inherit } from 'content-kit-utils'; -import { Type } from 'content-kit-compiler'; var RegExpHttp = /^https?:\/\//i; function LinkCommand() { TextFormatCommand.call(this, { name: 'link', - tag: Type.LINK.tag, + tag: 'a', action: 'createLink', removeAction: 'unlink', button: '', diff --git a/src/js/commands/list.js b/src/js/commands/list.js index c24a0d6f3..2a9e5739e 100644 --- a/src/js/commands/list.js +++ b/src/js/commands/list.js @@ -1,8 +1,6 @@ import TextFormatCommand from './text-format'; import { getSelectionBlockElement, selectNode, getSelectionTagName } from '../utils/selection-utils'; import { inherit } from 'content-kit-utils'; -import { Type } from 'content-kit-compiler'; -import { win } from 'content-kit-editor/utils/compat'; function ListCommand(options) { TextFormatCommand.call(this, options); @@ -11,7 +9,7 @@ inherit(ListCommand, TextFormatCommand); ListCommand.prototype.exec = function() { ListCommand._super.prototype.exec.call(this); - + // After creation, lists need to be unwrapped // TODO: eventually can remove this when direct model manipulation is ready var listElement = getSelectionBlockElement(); @@ -30,9 +28,9 @@ ListCommand.prototype.checkAutoFormat = function(node) { var regex = this.autoFormatRegex, text; if (node && regex) { text = node.textContent; - if (Type.LIST_ITEM.tag !== getSelectionTagName() && regex.test(text)) { + if ('li' !== getSelectionTagName() && regex.test(text)) { this.exec(); - win.getSelection().anchorNode.textContent = text.replace(regex, ''); + window.getSelection().anchorNode.textContent = text.replace(regex, ''); return true; } } diff --git a/src/js/commands/oembed.js b/src/js/commands/oembed.js index 643a7b6fb..5d3b2da5f 100644 --- a/src/js/commands/oembed.js +++ b/src/js/commands/oembed.js @@ -1,22 +1,17 @@ import Command from './base'; import Prompt from '../views/prompt'; import Message from '../views/message'; -import { - EmbedModel, - doc -} from 'content-kit-compiler'; import { inherit } from 'content-kit-utils'; import { OEmbedder } from '../utils/http-utils'; -import { win } from 'content-kit-editor/utils/compat'; function loadTwitterWidgets(element) { - if (win.twttr) { - win.twttr.widgets.load(element); + if (window.twttr) { + window.twttr.widgets.load(element); } else { - var script = doc.createElement('script'); + var script = document.createElement('script'); script.async = true; script.src = 'http://platform.twitter.com/widgets.js'; - doc.head.appendChild(script); + document.head.appendChild(script); } } @@ -58,6 +53,7 @@ OEmbedCommand.prototype.exec = function(url) { new Message().showError(response.error_message); embedIntent.show(); } else { + throw new Error('Unimplemented EmbedModel is not a thing'); var embedModel = new EmbedModel(response); editorContext.insertBlock(embedModel, index); editorContext.renderBlockAt(index); diff --git a/src/js/commands/ordered-list.js b/src/js/commands/ordered-list.js index c503aa140..b886e7da4 100644 --- a/src/js/commands/ordered-list.js +++ b/src/js/commands/ordered-list.js @@ -1,11 +1,10 @@ import ListCommand from './list'; import { inherit } from 'content-kit-utils'; -import { Type } from 'content-kit-compiler'; function OrderedListCommand() { ListCommand.call(this, { name: 'ordered list', - tag: Type.ORDERED_LIST.tag, + tag: 'ol', action: 'insertOrderedList' }); } diff --git a/src/js/commands/quote.js b/src/js/commands/quote.js index a5917f03f..2fa01af92 100644 --- a/src/js/commands/quote.js +++ b/src/js/commands/quote.js @@ -1,11 +1,10 @@ import FormatBlockCommand from './format-block'; import { inherit } from 'content-kit-utils'; -import { Type } from 'content-kit-compiler'; function QuoteCommand() { FormatBlockCommand.call(this, { name: 'quote', - tag: Type.QUOTE.tag, + tag: 'blockquote', button: '' }); } diff --git a/src/js/commands/subheading.js b/src/js/commands/subheading.js index 645db6969..849030a5f 100644 --- a/src/js/commands/subheading.js +++ b/src/js/commands/subheading.js @@ -1,11 +1,10 @@ import FormatBlockCommand from './format-block'; import { inherit } from 'content-kit-utils'; -import { Type } from 'content-kit-compiler'; function SubheadingCommand() { FormatBlockCommand.call(this, { name: 'subheading', - tag: Type.SUBHEADING.tag, + tag: 'h3', button: '2' }); } diff --git a/src/js/commands/text-format.js b/src/js/commands/text-format.js index 3a47e2157..a0ae5ca04 100644 --- a/src/js/commands/text-format.js +++ b/src/js/commands/text-format.js @@ -1,6 +1,5 @@ import Command from './base'; import { inherit } from 'content-kit-utils'; -import { doc } from 'content-kit-compiler'; function TextFormatCommand(options) { options = options || {}; @@ -15,10 +14,10 @@ inherit(TextFormatCommand, Command); TextFormatCommand.prototype = { exec: function(value) { - doc.execCommand(this.action, false, value || null); + document.execCommand(this.action, false, value || null); }, unexec: function(value) { - doc.execCommand(this.removeAction, false, value || null); + document.execCommand(this.removeAction, false, value || null); } }; diff --git a/src/js/commands/unordered-list.js b/src/js/commands/unordered-list.js index 8fe63c1bf..e91687a58 100644 --- a/src/js/commands/unordered-list.js +++ b/src/js/commands/unordered-list.js @@ -1,11 +1,10 @@ import ListCommand from './list'; import { inherit } from 'content-kit-utils'; -import { Type } from 'content-kit-compiler'; function UnorderedListCommand() { ListCommand.call(this, { name: 'list', - tag: Type.LIST.tag, + tag: 'ul', action: 'insertUnorderedList' }); } diff --git a/src/js/editor/editor-factory.js b/src/js/editor/editor-factory.js deleted file mode 100644 index 6cf2637b0..000000000 --- a/src/js/editor/editor-factory.js +++ /dev/null @@ -1,38 +0,0 @@ -import Editor from './editor'; - -/** - * @class EditorFactory - * @private - * `EditorFactory` is publically exposed as `Editor` - * It takes an `element` param which can be a css selector, Node, or NodeList - * and sets up indiviual `Editor` instances - */ -function EditorFactory(element, options) { - var editors = []; - var elements, elementsLen, i; - - if (!element) { - return new Editor(element, options); - } - - if (typeof element === 'string') { - elements = document.querySelectorAll(element); - } else if (element && element.length) { - elements = element; - } else if (element) { - elements = [element]; - } - - if (elements) { - elementsLen = elements.length; - for (i = 0; i < elementsLen; i++) { - editors.push(new Editor(elements[i], options)); - } - } - - return editors.length > 1 ? editors : editors[0]; -} - -EditorFactory.prototype = Editor.prototype; - -export default EditorFactory; diff --git a/src/js/editor/editor.js b/src/js/editor/editor.js index faeec000a..d9c66262e 100644 --- a/src/js/editor/editor.js +++ b/src/js/editor/editor.js @@ -1,7 +1,7 @@ -import NewDOMRenderer from '../renderers/new-dom-renderer'; import TextFormatToolbar from '../views/text-format-toolbar'; import Tooltip from '../views/tooltip'; import EmbedIntent from '../views/embed-intent'; + import BoldCommand from '../commands/bold'; import ItalicCommand from '../commands/italic'; import LinkCommand from '../commands/link'; @@ -13,26 +13,26 @@ import OrderedListCommand from '../commands/ordered-list'; import ImageCommand from '../commands/image'; import OEmbedCommand from '../commands/oembed'; import CardCommand from '../commands/card'; + import Keycodes from '../utils/keycodes'; import { getSelectionBlockElement, getCursorOffsetInElement } from '../utils/selection-utils'; import EventEmitter from '../utils/event-emitter'; -import { - Type, - Compiler, - MobiledocParser -} from 'content-kit-compiler'; + +import MobiledocParser from "../parsers/mobiledoc"; +import DOMParser from "../parsers/dom"; +import EditorDOMRenderer from "../renderers/editor-dom"; +import MobiledocRenderer from '../renderers/mobiledoc'; + import { toArray, merge, mergeWithOptions } from 'content-kit-utils'; -import { win, doc } from 'content-kit-editor/utils/compat'; import { detectParentNode } from '../utils/dom-utils'; -import Serializer from '../renderers/new-serializer'; var defaults = { placeholder: 'Write here...', spellcheck: true, autofocus: true, - model: null, + post: null, serverHost: '', - stickyToolbar: !!('ontouchstart' in win), + stickyToolbar: !!('ontouchstart' in window), textFormatCommands: [ new BoldCommand(), new ItalicCommand(), @@ -50,7 +50,6 @@ var defaults = { new UnorderedListCommand(), new OrderedListCommand() ], - compiler: null, cards: {}, mobiledoc: null }; @@ -69,7 +68,7 @@ function bindContentEditableTypingListeners(editor) { if (!getSelectionBlockElement() || !editor.element.textContent || (!e.shiftKey && e.which === Keycodes.ENTER) || (e.ctrlKey && e.which === Keycodes.M)) { - doc.execCommand('formatBlock', false, Type.PARAGRAPH.tag); + document.execCommand('formatBlock', false, 'p'); } //else if (e.which === Keycodes.BKSP) { // TODO: Need to rerender when backspacing 2 blocks together //var cursorIndex = editor.getCursorIndexInCurrentBlock(); @@ -83,9 +82,9 @@ function bindContentEditableTypingListeners(editor) { editor.addEventListener(editor.element, 'paste', function(e) { var data = e.clipboardData; var pastedHTML = data && data.getData && data.getData('text/html'); - var sanitizedHTML = pastedHTML && editor.compiler.rerender(pastedHTML); + var sanitizedHTML = pastedHTML && editor._renderer.rerender(pastedHTML); if (sanitizedHTML) { - doc.execCommand('insertHTML', false, sanitizedHTML); + document.execCommand('insertHTML', false, sanitizedHTML); editor.syncVisual(); } e.preventDefault(); @@ -101,7 +100,7 @@ function bindAutoTypingListeners(editor) { var selection, i; if (count) { - selection = win.getSelection(); + selection = window.getSelection(); for (i = 0; i < count; i++) { if (commands[i].checkAutoFormat(selection.anchorNode)) { e.stopPropagation(); @@ -114,10 +113,10 @@ function bindAutoTypingListeners(editor) { function bindDragAndDrop(editor) { // TODO. For now, just prevent redirect when dropping something on the page - editor.addEventListener(win, 'dragover', function(e) { + editor.addEventListener(window, 'dragover', function(e) { e.preventDefault(); // prevents showing cursor where to drop }); - editor.addEventListener(win, 'drop', function(e) { + editor.addEventListener(window, 'drop', function(e) { e.preventDefault(); // prevent page from redirecting }); } @@ -133,12 +132,12 @@ function initEmbedCommands(editor) { } } -function getNonTextBlocks(blockTypeSet, model) { +function getNonTextBlocks(blockTypeSet, post) { var blocks = []; - var len = model.length; + var len = post.length; var i, block, type; for (i = 0; i < len; i++) { - block = model[i]; + block = post[i]; type = blockTypeSet.findById(block && block.type); if (type && !type.isTextType) { blocks.push(block); @@ -171,13 +170,8 @@ function Editor(element, options) { // FIXME: This should merge onto this.options mergeWithOptions(this, defaults, options); - if (!this.compiler) { - this.compiler = new Compiler({ - // outputs models with type names, i.e. 'BOLD', for easier debugging - includeTypeNames: true, - renderer: new NewDOMRenderer(window.document, this.cards) - }); - } + this._renderer = new EditorDOMRenderer(window.document, this.cards) + this._parser = new DOMParser(); this.applyClassName(); this.applyPlaceholder(); @@ -210,7 +204,7 @@ function Editor(element, options) { this.linkTooltips = new Tooltip({ rootElement: element, - showForTag: Type.LINK.tag + showForTag: 'a' }); if (this.autofocus) { @@ -228,24 +222,24 @@ merge(Editor.prototype, { this._elementListeners.push([context, eventName, callback]); }, - loadModel(model) { - this.model = model; + loadModel(post) { + this.post = post; this.syncVisual(); this.trigger('update'); }, parseModelFromDOM(element) { - this.model = this.compiler.parse(element); + this.post = this._parser.parse(element); this.trigger('update'); }, parseModelFromMobiledoc(mobiledoc) { - this.model = new MobiledocParser().parse(mobiledoc); + this.post = new MobiledocParser().parse(mobiledoc); this.trigger('update'); }, syncVisual() { - this.compiler.render(this.model, this.element); + this._renderer.render(this.post, this.element); }, getCurrentBlockIndex() { @@ -263,24 +257,25 @@ merge(Editor.prototype, { }, insertBlock(block, index) { - this.model.splice(index, 0, block); + this.post.splice(index, 0, block); this.trigger('update'); }, removeBlockAt(index) { - this.model.splice(index, 1); + this.post.splice(index, 1); this.trigger('update'); }, replaceBlock(block, index) { - this.model[index] = block; + this.post[index] = block; this.trigger('update'); }, renderBlockAt(index, replace) { - var modelAtIndex = this.model[index]; + throw new Error('Unimplemented'); + var modelAtIndex = this.post[index]; var html = this.compiler.render([modelAtIndex]); - var dom = doc.createElement('div'); + var dom = document.createElement('div'); dom.innerHTML = html; var newEl = dom.firstChild; newEl.dataset.modelIndex = index; @@ -293,7 +288,8 @@ merge(Editor.prototype, { }, syncContentEditableBlocks() { - var nonTextBlocks = getNonTextBlocks(this.compiler.blockTypes, this.model); + throw new Error('Unimplemented'); + var nonTextBlocks = getNonTextBlocks(this.compiler.blockTypes, this.post); var blockElements = toArray(this.element.children); var len = blockElements.length; var updatedModel = []; @@ -301,7 +297,7 @@ merge(Editor.prototype, { for (i = 0; i < len; i++) { blockEl = blockElements[i]; if(blockEl.isContentEditable) { - updatedModel.push(this.compiler.parser.serializeBlockNode(blockEl)); + updatedModel.push(this._parser.serializeBlockNode(blockEl)); } else { if (blockEl.dataset.modelIndex) { block = this.model[blockEl.dataset.modelIndex]; @@ -311,7 +307,7 @@ merge(Editor.prototype, { } } } - this.model = updatedModel; + this.post = updatedModel; this.trigger('update'); }, @@ -340,18 +336,18 @@ merge(Editor.prototype, { let newSections = []; let previousSection; forEachChildNode(this.element, (node) => { - let section = this.model.getElementSection(node); + let section = this.post.getElementSection(node); if (!section) { - section = this.compiler.parseSection( + section = this._parser.parseSection( previousSection, node ); - this.model.setSectionElement(section, node); + this.post.setSectionElement(section, node); newSections.push(section); if (previousSection) { - this.model.insertSectionAfter(section, previousSection); + this.post.insertSectionAfter(section, previousSection); } else { - this.model.prependSection(section); + this.post.prependSection(section); } } // may cause duplicates to be included @@ -361,10 +357,10 @@ merge(Editor.prototype, { // remove deleted nodes let i; - for (i=this.model.sections.length-1;i>=0;i--) { - let section = this.model.sections[i]; + for (i=this.post.sections.length-1;i>=0;i--) { + let section = this.post.sections[i]; if (sectionsInDOM.indexOf(section) === -1) { - this.model.removeSection(section); + this.post.removeSection(section); } } @@ -374,7 +370,7 @@ merge(Editor.prototype, { // user presses enter (or pastes a newline) let firstSection = sectionsWithCursor[0]; if (firstSection) { - let previousSection = this.model.getPreviousSection(firstSection); + let previousSection = this.post.getPreviousSection(firstSection); if (previousSection) { sectionsWithCursor.unshift(previousSection); } @@ -396,32 +392,32 @@ merge(Editor.prototype, { let { startContainer:startElement, endContainer:endElement } = range; - let getElementSection = (e) => this.model.getElementSection(e); + let getElementSection = (e) => this.post.getElementSection(e); let { result:startSection } = detectParentNode(startElement, getElementSection); let { result:endSection } = detectParentNode(endElement, getElementSection); - let startIndex = this.model.sections.indexOf(startSection), - endIndex = this.model.sections.indexOf(endSection); + let startIndex = this.post.sections.indexOf(startSection), + endIndex = this.post.sections.indexOf(endSection); - return this.model.sections.slice(startIndex, endIndex+1); + return this.post.sections.slice(startIndex, endIndex+1); }, reparseSection(section) { - let sectionElement = this.model.getSectionElement(section); - let previousSection = this.model.getPreviousSection(section); + let sectionElement = this.post.getSectionElement(section); + let previousSection = this.post.getPreviousSection(section); - var newSection = this.compiler.parseSection( + var newSection = this._parser.parseSection( previousSection, sectionElement ); - this.model.replaceSection(section, newSection); - this.model.setSectionElement(newSection, sectionElement); + this.post.replaceSection(section, newSection); + this.post.setSectionElement(newSection, sectionElement); this.trigger('update'); }, serialize() { - return Serializer.serialize(this.model); + return MobiledocRenderer.render(this.post); }, removeAllEventListeners() { diff --git a/src/js/index.js b/src/js/index.js index abc0da387..a36b1bdcc 100644 --- a/src/js/index.js +++ b/src/js/index.js @@ -1,24 +1,12 @@ -import { - Type, - BlockModel, - EmbedModel, - Compiler, - HTMLParser, - HTMLRenderer, - Runtime -} from 'content-kit-compiler'; - import Editor from './editor/editor'; +import DOMRenderer from './runtime/renderers/mobiledoc-dom'; + +const Runtime = { + DOMRenderer +} const ContentKit = { - Type, - BlockModel, - EmbedModel, - Compiler, - HTMLParser, - HTMLRenderer, - Runtime, - Editor + Editor, Runtime }; export function registerGlobal(global) { diff --git a/src/js/models/post.js b/src/js/models/post.js new file mode 100644 index 000000000..8638393a3 --- /dev/null +++ b/src/js/models/post.js @@ -0,0 +1,60 @@ +import ElementMap from "../utils/element-map"; + +// FIXME: making sections a linked-list would greatly improve this +export default class Post { + constructor() { + this.type = 'post'; + this.sections = []; + this.sectionElementMap = new ElementMap(); + } + appendSection(section) { + this.sections.push(section); + } + prependSection(section) { + this.sections.unshift(section); + } + replaceSection(section, newSection) { + this.insertSectionAfter(newSection, section); + this.removeSection(section); + } + insertSectionAfter(section, previousSection) { + var i, l; + for (i=0,l=this.sections.length;i

, etc + if (MARKUP_SECTION_TAG_NAMES.indexOf(tagName) !== -1) { + section = postBuilder.generateSection(tagName, readAttributes(sectionElement)); + var node = sectionElement.firstChild; + while (node) { + parseMarkers(section, postBuilder, node); + node = node.nextSibling; + } + // , etc + } else { + if (previousSection && previousSection.isGenerated) { + section = previousSection; + } else { + section = postBuilder.generateSection('P', {}, true); + } + parseMarkers(section, postBuilder, sectionElement); + } + break; + case TEXT_NODE: + if (previousSection && previousSection.isGenerated) { + section = previousSection; + } else { + section = postBuilder.generateSection('P', {}, true); + } + parseMarkers(section, postBuilder, sectionElement); + break; + } + return section; + }, + parse: function(postElement) { + var post = this.postBuilder.generatePost(); + var i, l, section, previousSection, sectionElement; + // FIXME: Instead of storing isGenerated on sections, and passing + // the previous section to the parser, we could instead do a two-pass + // parse. The first pass identifies sections and gathers a list of + // dom nodes that can be parsed for markers, the second pass parses + // for markers. + for (i=0, l=postElement.childNodes.length;i this.parseMarkerType(markerType)); + } + + parseMarkerType([tagName, attributes]) { + return this.builder.generateMarkerType(tagName, attributes); + } + + parseSections(sections, post) { + sections.forEach((section) => this.parseSection(section, post)); + } + + parseSection(section, post) { + let [type] = section; + switch(type) { + case 1: // markup section + this.parseMarkupSection(section, post); + break; + default: + throw new Error(`Unexpected section type ${type}`); + } + } + + parseMarkupSection([type, tagName, markers], post) { + const attributes = null; + const isGenerated = false; + const section = this.builder.generateSection(tagName, attributes, isGenerated); + + post.appendSection(section); + this.parseMarkers(markers, section); + } + + parseMarkers(markers, section) { + markers.forEach((marker) => this.parseMarker(marker, section)); + } + + parseMarker([markerTypeIndexes, closeCount, value], section) { + const markerTypes = markerTypeIndexes.map(index => this.markerTypes[index]); + const marker = this.builder.generateMarker(markerTypes, closeCount, value); + section.markers.push(marker); + } +} diff --git a/src/js/renderers/new-dom-renderer.js b/src/js/renderers/editor-dom.js similarity index 100% rename from src/js/renderers/new-dom-renderer.js rename to src/js/renderers/editor-dom.js diff --git a/src/js/renderers/editor-html-renderer.js b/src/js/renderers/editor-html-renderer.js deleted file mode 100644 index 1b597f4dd..000000000 --- a/src/js/renderers/editor-html-renderer.js +++ /dev/null @@ -1,70 +0,0 @@ -import { HTMLRenderer } from 'content-kit-compiler'; -import { Type } from 'content-kit-compiler'; -import { - inherit, - merge -} from 'content-kit-utils'; -import YouTubeRenderer from './youtube'; -import TwitterRenderer from './twitter'; -import InstagramRenderer from './instagram'; -import LinkImageRenderer from './link-image-renderer'; - -/** - * A dictionary of supported embeds types that we'll custom render - * for the editor, instead of the default oembed html. - */ -var embedRenderers = { - YOUTUBE : new YouTubeRenderer(), - TWITTER : new TwitterRenderer(), - INSTAGRAM : new InstagramRenderer(), - LINK_IMAGE : new LinkImageRenderer() -}; - -function embedRenderer(model) { - var embedAttrs = model.attributes; - var embedType = embedAttrs.embed_type; - var isVideo = embedType === 'video'; - var providerName = embedAttrs.provider_name; - var customRendererId = providerName && providerName.toUpperCase(); - var customRenderer = embedRenderers[customRendererId]; - if (!customRenderer && embedType === 'link' && embedAttrs.thumbnail) { - customRenderer = embedRenderers.LINK_IMAGE; - } - var renderer = customRenderer ? customRenderer : this; - - return '
' + - '
' + - (isVideo ? '
' : '') + renderer.render(model) + (isVideo ? '
' : '') + - '
' + - '' + embedAttrs.title + '' + - '
' + - '
' + - '
'; -} - -function imageRenderer(model) { - return '
' + - '
' + this.render(model) + '
' + - '
'; -} - -var typeRenderers = {}; -typeRenderers[Type.EMBED.id] = embedRenderer; -typeRenderers[Type.IMAGE.id] = imageRenderer; - -/** - * @class EditorHTMLRenderer - * @constructor - * Subclass of HTMLRenderer specifically for the Editor - * Wraps interactive elements to add functionality - */ -function EditorHTMLRenderer(options) { - var rendererOptions = { - typeRenderers: typeRenderers - }; - merge(rendererOptions, options); - HTMLRenderer.call(this, rendererOptions); -} -inherit(EditorHTMLRenderer, HTMLRenderer); - -export default EditorHTMLRenderer; diff --git a/src/js/renderers/instagram.js b/src/js/renderers/instagram.js deleted file mode 100644 index b92005bb3..000000000 --- a/src/js/renderers/instagram.js +++ /dev/null @@ -1,7 +0,0 @@ - -function InstagramRenderer() {} -InstagramRenderer.prototype.render = function(model) { - return ''; -}; - -export default InstagramRenderer; diff --git a/src/js/renderers/link-image-renderer.js b/src/js/renderers/link-image-renderer.js deleted file mode 100644 index 8cf5e8619..000000000 --- a/src/js/renderers/link-image-renderer.js +++ /dev/null @@ -1,7 +0,0 @@ - -function LinkImageRenderer() {} -LinkImageRenderer.prototype.render = function(model) { - return ''; -}; - -export default LinkImageRenderer; diff --git a/src/js/renderers/new-serializer.js b/src/js/renderers/mobiledoc.js similarity index 98% rename from src/js/renderers/new-serializer.js rename to src/js/renderers/mobiledoc.js index e61e48f03..bac38670a 100644 --- a/src/js/renderers/new-serializer.js +++ b/src/js/renderers/mobiledoc.js @@ -56,7 +56,7 @@ let postOpcodeCompiler = { }; export default { - serialize(post) { + render(post) { let opcodes = []; visit(visitor, post, opcodes); let compiler = Object.create(postOpcodeCompiler); diff --git a/src/js/renderers/twitter.js b/src/js/renderers/twitter.js deleted file mode 100644 index 167e09a63..000000000 --- a/src/js/renderers/twitter.js +++ /dev/null @@ -1,7 +0,0 @@ - -function TwitterRenderer() {} -TwitterRenderer.prototype.render = function(model) { - return ''; -}; - -export default TwitterRenderer; diff --git a/src/js/renderers/youtube.js b/src/js/renderers/youtube.js deleted file mode 100644 index 3d9b4bf61..000000000 --- a/src/js/renderers/youtube.js +++ /dev/null @@ -1,19 +0,0 @@ - -var RegExVideoId = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/; - -function getVideoIdFromUrl(url) { - var match = url && url.match(RegExVideoId); - if (match && match[1].length === 11){ - return match[1]; - } - return null; -} - -function YouTubeRenderer() {} -YouTubeRenderer.prototype.render = function(model) { - var videoId = getVideoIdFromUrl(model.attributes.url); - var embedUrl = 'http://www.youtube.com/embed/' + videoId + '?controls=2&showinfo=0&color=white&theme=light'; - return ''; -}; - -export default YouTubeRenderer; \ No newline at end of file diff --git a/src/js/runtime/renderers/mobiledoc-dom.js b/src/js/runtime/renderers/mobiledoc-dom.js new file mode 100644 index 000000000..b086f9171 --- /dev/null +++ b/src/js/runtime/renderers/mobiledoc-dom.js @@ -0,0 +1,90 @@ +/** + * runtime DOM renderer + * renders a mobiledoc to DOM + * + * input: mobiledoc + * output: DOM + */ + +const utils = { + createElement(tagName) { + return document.createElement(tagName); + }, + appendChild(target, child) { + target.appendChild(child); + }, + createTextNode(text) { + return document.createTextNode(text); + } +}; + +function createElementFromMarkerType([tagName, attributes]){ + let element = utils.createElement(tagName); + attributes = attributes || []; + + for (let i=0,l=attributes.length; i this.renderSection(section)); + + return this.root; + } + + renderSection(section) { + const [type] = section; + switch (type) { + case 1: + let rendered = this.renderParagraphSection(section); + utils.appendChild(this.root, rendered); + break; + default: + throw new Error('Unimplement renderer for type ' + type); + } + } + + renderParagraphSection([type, tagName, markers]) { + let element = utils.createElement(tagName); + let elements = [element]; + let currentElement = element; + + for (let i=0, l=markers.length; i maxFileSize) { if (callback) { callback.call(this, null, { message: 'max file size is ' + maxFileSize + ' bytes' }); } diff --git a/src/js/utils/post-builder.js b/src/js/utils/post-builder.js new file mode 100644 index 000000000..3a462904a --- /dev/null +++ b/src/js/utils/post-builder.js @@ -0,0 +1,59 @@ +import Post from "../models/post"; + +var builder = { + generatePost() { + return new Post(); + }, + generateSection(tagName, attributes, isGenerated) { + var section = { + type: 'markupSection', + tagName: tagName, + markers: [] + }; + if (attributes && attributes.length) { + section.attributes = attributes; + } + if (isGenerated) { + section.isGenerated = !!isGenerated; + } + return section; + }, + // open: Array + // close: Integer + // value: String + generateMarker: function(open, close, value) { + return { + type: 'marker', + open: open, + close: close, + value: value + }; + }, + generateMarkerType: function(tagName, attributes) { + if (attributes) { + // FIXME: This could also be cached + return { + type: 'markerType', + tagName: tagName, + attributes: attributes + }; + } + var markerType = this._markerTypeCache[tagName]; + if (!markerType) { + this._markerTypeCache[tagName] = markerType = { + type: 'markerType', + tagName: tagName + }; + } + return markerType; + } +}; + +function reset(builder){ + builder._markerTypeCache = {}; +} + +export function generateBuilder(){ + reset(builder); + return builder; +} diff --git a/src/js/utils/selection-utils.js b/src/js/utils/selection-utils.js index f31d4ee30..490c6daa6 100644 --- a/src/js/utils/selection-utils.js +++ b/src/js/utils/selection-utils.js @@ -1,17 +1,8 @@ import { nodeIsDescendantOfElement } from './element-utils'; -import { - Type -} from 'content-kit-compiler'; -import { win, doc } from 'content-kit-editor/utils/compat'; // TODO: remove, pass in Editor's current block set var RootTags = [ - Type.PARAGRAPH.tag, - Type.HEADING.tag, - Type.SUBHEADING.tag, - Type.QUOTE.tag, - Type.LIST.tag, - Type.ORDERED_LIST.tag + 'p', 'h2', 'h3', 'blockquote', 'ul', 'ol' ]; var SelectionDirection = { @@ -32,13 +23,13 @@ function getDirectionOfSelection(selection) { } function getSelectionElement(selection) { - selection = selection || win.getSelection(); + selection = selection || window.getSelection(); var node = getDirectionOfSelection(selection) === SelectionDirection.LEFT_TO_RIGHT ? selection.anchorNode : selection.focusNode; return node && (node.nodeType === 3 ? node.parentNode : node); } function getSelectionBlockElement(selection) { - selection = selection || win.getSelection(); + selection = selection || window.getSelection(); var element = getSelectionElement(); var tag = element && element.tagName.toLowerCase(); while (tag && RootTags.indexOf(tag) === -1) { @@ -85,14 +76,14 @@ function selectionIsEditable(selection) { } function restoreRange(range) { - var selection = win.getSelection(); + var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); } function selectNode(node) { - var range = doc.createRange(); - var selection = win.getSelection(); + var range = document.createRange(); + var selection = window.getSelection(); range.setStart(node, 0); range.setEnd(node, node.length); selection.removeAllRanges(); @@ -100,8 +91,8 @@ function selectNode(node) { } function setCursorIndexInElement(element, index) { - var range = doc.createRange(); - var selection = win.getSelection(); + var range = document.createRange(); + var selection = window.getSelection(); range.setStart(element, index); range.collapse(true); selection.removeAllRanges(); @@ -115,7 +106,7 @@ function setCursorToStartOfElement(element) { function getCursorOffsetInElement(element) { // http://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container/4812022#4812022 var caretOffset = 0; - var selection = win.getSelection(); + var selection = window.getSelection(); if (selection.rangeCount > 0) { var range = selection.getRangeAt(0); var preCaretRange = range.cloneRange(); diff --git a/src/js/utils/win.js b/src/js/utils/win.js deleted file mode 100644 index 3b9e454de..000000000 --- a/src/js/utils/win.js +++ /dev/null @@ -1,11 +0,0 @@ -import { doc } from 'content-kit-compiler'; - -var win; -if (typeof window !== 'undefined') { - win = window; -} else { - // jsdom provides a defaultView - win = doc.defaultView; -} - -export default win; diff --git a/src/js/views/embed-intent.js b/src/js/views/embed-intent.js index 4e19fb860..06754d67e 100644 --- a/src/js/views/embed-intent.js +++ b/src/js/views/embed-intent.js @@ -5,7 +5,6 @@ import { getSelectionBlockElement } from '../utils/selection-utils'; import { elementContentIsEmpty, positionElementToLeftOf, positionElementCenteredIn } from '../utils/element-utils'; import { createDiv } from '../utils/element-utils'; import Keycodes from '../utils/keycodes'; -import { win, doc } from 'content-kit-editor/utils/compat'; var LayoutStyle = { GUTTER : 1, @@ -28,7 +27,7 @@ function EmbedIntent(options) { embedIntent.isActive = false; embedIntent.editorContext = options.editorContext; embedIntent.loadingIndicator = createDiv('ck-embed-loading'); - embedIntent.button = doc.createElement('button'); + embedIntent.button = document.createElement('button'); embedIntent.button.className = 'ck-embed-intent-btn'; embedIntent.button.title = 'Insert image or embed...'; embedIntent.element.appendChild(embedIntent.button); @@ -59,17 +58,17 @@ function EmbedIntent(options) { } rootElement.addEventListener('keyup', embedIntentHandler); - doc.addEventListener('mouseup', function() { + document.addEventListener('mouseup', function() { setTimeout(function() { embedIntentHandler(); }); }); - doc.addEventListener('keyup', function(e) { + document.addEventListener('keyup', function(e) { if (e.keyCode === Keycodes.ESC) { embedIntent.hide(); } }); - win.addEventListener('resize', function() { + window.addEventListener('resize', function() { if(embedIntent.isShowing) { embedIntent.reposition(); } diff --git a/src/js/views/prompt.js b/src/js/views/prompt.js index a4df59732..bb0eecda4 100644 --- a/src/js/views/prompt.js +++ b/src/js/views/prompt.js @@ -3,9 +3,8 @@ import { inherit } from 'content-kit-utils'; import { restoreRange } from '../utils/selection-utils'; import { createDiv, positionElementToRect } from '../utils/element-utils'; import Keycodes from '../utils/keycodes'; -import { win, doc } from 'content-kit-editor/utils/compat'; -var container = doc.body; +var container = document.body; var hiliter = createDiv('ck-editor-hilite'); function positionHiliteRange(range) { @@ -33,7 +32,7 @@ function Prompt(options) { } }); - win.addEventListener('resize', function() { + window.addEventListener('resize', function() { var activeHilite = hiliter.parentNode; var range = prompt.range; if(activeHilite && range) { @@ -46,7 +45,7 @@ inherit(Prompt, View); Prompt.prototype.show = function(callback) { var prompt = this; var element = prompt.element; - var selection = win.getSelection(); + var selection = window.getSelection(); var range = selection && selection.rangeCount && selection.getRangeAt(0); element.value = null; prompt.range = range || null; diff --git a/src/js/views/text-format-toolbar.js b/src/js/views/text-format-toolbar.js index 64fe8d012..381419ecf 100644 --- a/src/js/views/text-format-toolbar.js +++ b/src/js/views/text-format-toolbar.js @@ -2,14 +2,13 @@ import Toolbar from './toolbar'; import { inherit } from 'content-kit-utils'; import { selectionIsEditable, selectionIsInElement } from '../utils/selection-utils'; import Keycodes from '../utils/keycodes'; -import { win, doc } from 'content-kit-editor/utils/compat'; function selectionIsEditableByToolbar(selection, toolbar) { return selectionIsEditable(selection) && selectionIsInElement(selection, toolbar.rootElement); } function handleTextSelection(toolbar) { - var selection = win.getSelection(); + var selection = window.getSelection(); if (toolbar.sticky) { toolbar.updateForSelection(selectionIsEditableByToolbar(selection, toolbar) ? selection : null); } else { @@ -28,13 +27,13 @@ function TextFormatToolbar(options) { toolbar.rootElement = options.rootElement; toolbar.rootElement.addEventListener('keyup', function() { handleTextSelection(toolbar); }); - doc.addEventListener('mouseup', function() { + document.addEventListener('mouseup', function() { setTimeout(function() { handleTextSelection(toolbar); }); }); - doc.addEventListener('keyup', function(e) { + document.addEventListener('keyup', function(e) { var key = e.keyCode; if (key === 116) { //F5 toolbar.toggleSticky(); @@ -44,10 +43,10 @@ function TextFormatToolbar(options) { } }); - win.addEventListener('resize', function() { + window.addEventListener('resize', function() { if(!toolbar.sticky && toolbar.isShowing) { var activePromptRange = toolbar.activePrompt && toolbar.activePrompt.range; - toolbar.positionToContent(activePromptRange ? activePromptRange : win.getSelection().getRangeAt(0)); + toolbar.positionToContent(activePromptRange ? activePromptRange : window.getSelection().getRangeAt(0)); } }); } diff --git a/src/js/views/toolbar-button.js b/src/js/views/toolbar-button.js index 856c1d6d5..a3ecaf3e2 100644 --- a/src/js/views/toolbar-button.js +++ b/src/js/views/toolbar-button.js @@ -1,5 +1,3 @@ -import { doc } from 'content-kit-compiler'; - var buttonClassName = 'ck-toolbar-btn'; function ToolbarButton(options) { @@ -7,7 +5,7 @@ function ToolbarButton(options) { var toolbar = options.toolbar; var command = options.command; var prompt = command.prompt; - var element = doc.createElement('button'); + var element = document.createElement('button'); button.element = element; button.command = command; diff --git a/src/js/views/toolbar.js b/src/js/views/toolbar.js index 63fa5b075..7bfd198af 100644 --- a/src/js/views/toolbar.js +++ b/src/js/views/toolbar.js @@ -3,7 +3,6 @@ import ToolbarButton from './toolbar-button'; import { inherit } from 'content-kit-utils'; import { tagsInSelection } from '../utils/selection-utils'; import { createDiv, swapElements, positionElementToRightOf, positionElementCenteredAbove } from '../utils/element-utils'; -import { win, doc } from 'content-kit-editor/utils/compat'; var ToolbarDirection = { TOP : 1, @@ -58,7 +57,7 @@ function Toolbar(options) { } // Closes prompt if displayed when changing selection - doc.addEventListener('mouseup', function() { + document.addEventListener('mouseup', function() { toolbar.dismissPrompt(); }); } @@ -104,7 +103,7 @@ Toolbar.prototype.dismissPrompt = function() { Toolbar.prototype.updateForSelection = function(selection) { var toolbar = this; - selection = selection || win.getSelection(); + selection = selection || window.getSelection(); if (toolbar.sticky) { updateButtonsForSelection(toolbar.buttons, selection); } else if (!selection.isCollapsed) { @@ -124,7 +123,7 @@ Toolbar.prototype.positionToContent = function(content) { positioningMethod = positionElementCenteredAbove; } position = positioningMethod(this.element, content); - sideEdgeOffset = Math.min(Math.max(10, position.left), doc.body.clientWidth - this.element.offsetWidth - 10); + sideEdgeOffset = Math.min(Math.max(10, position.left), document.body.clientWidth - this.element.offsetWidth - 10); this.contentElement.style.transform = 'translateX(' + (sideEdgeOffset - position.left) + 'px)'; }; diff --git a/src/js/views/view.js b/src/js/views/view.js index eb9032c6a..09970877e 100644 --- a/src/js/views/view.js +++ b/src/js/views/view.js @@ -1,5 +1,3 @@ -import { doc } from 'content-kit-editor/utils/compat'; - function renderClasses(view) { var classNames = view.classNames; if (classNames && classNames.length) { @@ -13,8 +11,8 @@ function View(options) { options = options || {}; this.tagName = options.tagName || 'div'; this.classNames = options.classNames || []; - this.element = doc.createElement(this.tagName); - this.container = options.container || doc.body; + this.element = document.createElement(this.tagName); + this.container = options.container || document.body; this.isShowing = false; renderClasses(this); } From 99372eedea3a2a9da5e6129cdbfe320331a061d9 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Thu, 9 Jul 2015 09:54:31 -0400 Subject: [PATCH 35/77] built website from bb36364c86f87721b6572f6e8adbe5ff2e8b2ca8 --- website/demo/website-index.html | 4 ++-- website/index.hml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/website/demo/website-index.html b/website/demo/website-index.html index 343a43d54..9f2c4f1bf 100644 --- a/website/demo/website-index.html +++ b/website/demo/website-index.html @@ -1,10 +1,10 @@ - Content Kit Editor 0.2.0 - Click to view the Demo. + + Click to view the Demo. diff --git a/website/index.hml b/website/index.hml index 343a43d54..9f2c4f1bf 100644 --- a/website/index.hml +++ b/website/index.hml @@ -1,10 +1,10 @@ - Content Kit Editor 0.2.0 - Click to view the Demo. + + Click to view the Demo. From 9bf4ab043c0508ad671da6dd10a7fa63c39a199d Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Thu, 9 Jul 2015 11:28:13 -0400 Subject: [PATCH 36/77] Specify libDirName for testTreeBuilder --- Brocfile.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Brocfile.js b/Brocfile.js index 45d176238..9b60bb4e6 100644 --- a/Brocfile.js +++ b/Brocfile.js @@ -19,7 +19,7 @@ var buildOptions = { }; var jqueryTree = jquery.build('/demo/jquery'); -var testTree = testTreeBuilder.build(); +var testTree = testTreeBuilder.build({libDirName: 'src'}); var demoTree = demo(); demoTree = mergeTrees([demoTree, jqueryTree]); From a78b990ee92ec83974e5d5d7c6a24f9e10371dc2 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Thu, 9 Jul 2015 12:55:54 -0400 Subject: [PATCH 37/77] Bring in DOMRenderer from external dep mobiledoc-dom-renderer --- Brocfile.js | 3 +- package.json | 1 + src/js/runtime/renderers/mobiledoc-dom.js | 91 +---------------------- 3 files changed, 5 insertions(+), 90 deletions(-) diff --git a/Brocfile.js b/Brocfile.js index 9b60bb4e6..69ddef2f0 100644 --- a/Brocfile.js +++ b/Brocfile.js @@ -8,7 +8,8 @@ var demo = require('./broccoli/demo'); var jquery = require('./broccoli/jquery'); var vendoredModules = [ - {name: 'content-kit-utils', options: {libDirName: 'src'}} + {name: 'content-kit-utils', options: {libDirName: 'src'}}, + {name: 'mobiledoc-dom-renderer'} ]; var packageName = require('./package.json').name; diff --git a/package.json b/package.json index 5f7aa9f1f..afedb1965 100644 --- a/package.json +++ b/package.json @@ -57,6 +57,7 @@ "gulp-qunit": "^1.2.1", "gulp-uglify": "^1.1.0", "jquery": "^2.1.4", + "mobiledoc-dom-renderer": "^0.1.2", "testem": "^0.8.4" } } diff --git a/src/js/runtime/renderers/mobiledoc-dom.js b/src/js/runtime/renderers/mobiledoc-dom.js index b086f9171..0733911fc 100644 --- a/src/js/runtime/renderers/mobiledoc-dom.js +++ b/src/js/runtime/renderers/mobiledoc-dom.js @@ -1,90 +1,3 @@ -/** - * runtime DOM renderer - * renders a mobiledoc to DOM - * - * input: mobiledoc - * output: DOM - */ +import DOMRenderer from 'mobiledoc-dom-renderer'; -const utils = { - createElement(tagName) { - return document.createElement(tagName); - }, - appendChild(target, child) { - target.appendChild(child); - }, - createTextNode(text) { - return document.createTextNode(text); - } -}; - -function createElementFromMarkerType([tagName, attributes]){ - let element = utils.createElement(tagName); - attributes = attributes || []; - - for (let i=0,l=attributes.length; i this.renderSection(section)); - - return this.root; - } - - renderSection(section) { - const [type] = section; - switch (type) { - case 1: - let rendered = this.renderParagraphSection(section); - utils.appendChild(this.root, rendered); - break; - default: - throw new Error('Unimplement renderer for type ' + type); - } - } - - renderParagraphSection([type, tagName, markers]) { - let element = utils.createElement(tagName); - let elements = [element]; - let currentElement = element; - - for (let i=0, l=markers.length; i Date: Thu, 9 Jul 2015 15:00:41 -0400 Subject: [PATCH 38/77] Add more options to the demo, clean up its style and UI --- demo/demo.css | 9 ++- demo/demo.js | 112 ++++++++++++++++++++++++++++++++---- demo/index.html | 43 +++++++++----- src/js/parsers/mobiledoc.js | 2 +- 4 files changed, 139 insertions(+), 27 deletions(-) diff --git a/demo/demo.css b/demo/demo.css index 341e0a067..f29d99e74 100644 --- a/demo/demo.css +++ b/demo/demo.css @@ -24,6 +24,12 @@ body { .pane { max-width: 25%; + padding: 0 1em; +} + +.pane p.desc { + height: 150px; + overflow: scroll; } .editor-pane { @@ -76,7 +82,8 @@ body { #mobiledoc-to-load { } #mobiledoc-to-load textarea { - height: 300px; + height: 500px; + width: 100%; } .code-pane:first-child { diff --git a/demo/demo.js b/demo/demo.js index 02f5c3cb0..0571d2408 100644 --- a/demo/demo.js +++ b/demo/demo.js @@ -2,6 +2,9 @@ 'use strict'; +var ContentKit = exports.ContentKit, + $ = exports.$; + var ContentKitDemo = exports.ContentKitDemo = { syncCodePane: function(editor) { var codePaneJSON = document.getElementById('serialized-mobiledoc'); @@ -40,9 +43,10 @@ var ContentKitDemo = exports.ContentKitDemo = { }; -function bootEditor(element, payload) { +function bootEditor(element, mobiledoc) { var editor = new ContentKit.Editor(element, { - mobiledoc: payload, + autofocus: false, + mobiledoc: mobiledoc, cards: { 'pick-color': function renderPickColor(payload) { return 'PICK A COLOR: '+payload.options.join(', '); @@ -55,22 +59,106 @@ function bootEditor(element, payload) { }); } -function readPayload(textarea) { - var jqueryTextarea = $(textarea); - var textPayload = jqueryTextarea.val(); - return JSON.parse(textPayload); +function readMobiledoc(string) { + return JSON.parse(string); } -$(function() { - var textarea = $('#mobiledoc-to-load textarea'); - var editor; - textarea.on('input', function() { +function isValidJSON(string) { + try { + JSON.parse(string); + return true; + } catch(e) { + return false; + } +} + +function attemptEditorReboot(editor, textarea) { + var textPayload = $(textarea).val(); + if (isValidJSON(textPayload)) { + var mobiledoc = readMobiledoc(textPayload); if (editor) { editor.destroy(); } - editor = bootEditor($('#editor')[0], readPayload(textarea)); + bootEditor($('#editor')[0], mobiledoc); + } +} + +var sampleMobiledocs = { + simpleMobiledoc: [ + [], + [ + [1, "H2", [ + [[], 0, "headline h2"] + ]], + [1, "P", [ + [[], 0, "hello world"] + ]] + ] + ], + + mobileDocWithMarker: [ + [['B']], + [ + [1, "H2", [ + [[], 0, "headline h2"] + ]], + [1, "P", [ + [[0], 1, "bold world"] + ]] + ] + ], + + mobileDocWithMultipleMarkers: [ + [['B'], ['I']], + [ + [1, "H2", [ + [[], 0, "headline h2"] + ]], + [1, "P", [ + [[], 0, "hello "], + [[0], 1, "bold, "], + [[1], 1, "italic "], + [[], 0, "world."] + ]] + ] + ], + + mobileDocWithAttributeMarker: [ + [['A', ['href', 'http://github.com/bustlelabs/content-kit-editor']]], + [ + [1, "H2", [ + [[], 0, "headline h2"] + ]], + [1, "P", [ + [[], 0, "see it "], + [[0], 1, "on github."] + ]] + ] + ] +}; + + +$(function() { + var editor; + var editorEl = $('#editor')[0]; + var mobiledoc = sampleMobiledocs.simpleMobiledoc; + + var textarea = $('#mobiledoc-to-load textarea'); + textarea.val(JSON.stringify(mobiledoc, false, 2)); + + textarea.on('input', function() { + attemptEditorReboot(editor, textarea); }); - editor = bootEditor($('#editor')[0], readPayload(textarea)); + + $('#select-mobiledoc').on('change', function() { + var mobiledocName = $(this).val(); + var mobiledoc = sampleMobiledocs[mobiledocName]; + textarea.val(JSON.stringify(mobiledoc, false, 2)); + textarea.trigger('input'); + }); + + bootEditor(editorEl, mobiledoc); + $(editorEl).focus(); }); }(this, document)); diff --git a/demo/index.html b/demo/index.html index 1992c4058..a895c7415 100644 --- a/demo/index.html +++ b/demo/index.html @@ -1,5 +1,6 @@ + Content Kit Editor Demo 0.2.0 @@ -14,42 +15,58 @@ +

mobiledoc to load

+

+ This mobiledoc will be loaded into the editor. + You can change it and see the editor reload with the new contents. + (If there is a JSON syntax error it will be ignored; if there is a parser + error the editor may stop responding.) +
+ Select a preloaded mobiledoc here: + +

- +

editor

+

+ The live-editing surface. Changes here are serialized to mobiledoc + format and displayed to the right. +

serialized mobiledoc

+

+ When the editor updates, it prints its serialized mobiledoc here. +

rendered mobiledoc

+

+ This is the output of using the runtime (client-side) + mobiledoc-dom-renderer + on the serialized mobiledoc. +

diff --git a/src/js/parsers/mobiledoc.js b/src/js/parsers/mobiledoc.js index ce0e97fdc..3baeeb3aa 100644 --- a/src/js/parsers/mobiledoc.js +++ b/src/js/parsers/mobiledoc.js @@ -49,7 +49,7 @@ export default class MobiledocParser { const attributes = null; const isGenerated = false; const section = this.builder.generateSection(tagName, attributes, isGenerated); - + post.appendSection(section); this.parseMarkers(markers, section); } From 433947dfd948550af7eca9070b4cdf789ad75d5a Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Thu, 9 Jul 2015 15:01:00 -0400 Subject: [PATCH 39/77] built website from 6b0c45a130fd3a96be7ccb8b7e7186c494c7dfed --- website/demo/demo.css | 9 +- website/demo/demo.js | 112 +- website/demo/index.html | 43 +- website/global/content-kit-editor.js | 3186 +++++++++----------------- 4 files changed, 1225 insertions(+), 2125 deletions(-) diff --git a/website/demo/demo.css b/website/demo/demo.css index 341e0a067..f29d99e74 100644 --- a/website/demo/demo.css +++ b/website/demo/demo.css @@ -24,6 +24,12 @@ body { .pane { max-width: 25%; + padding: 0 1em; +} + +.pane p.desc { + height: 150px; + overflow: scroll; } .editor-pane { @@ -76,7 +82,8 @@ body { #mobiledoc-to-load { } #mobiledoc-to-load textarea { - height: 300px; + height: 500px; + width: 100%; } .code-pane:first-child { diff --git a/website/demo/demo.js b/website/demo/demo.js index 02f5c3cb0..0571d2408 100644 --- a/website/demo/demo.js +++ b/website/demo/demo.js @@ -2,6 +2,9 @@ 'use strict'; +var ContentKit = exports.ContentKit, + $ = exports.$; + var ContentKitDemo = exports.ContentKitDemo = { syncCodePane: function(editor) { var codePaneJSON = document.getElementById('serialized-mobiledoc'); @@ -40,9 +43,10 @@ var ContentKitDemo = exports.ContentKitDemo = { }; -function bootEditor(element, payload) { +function bootEditor(element, mobiledoc) { var editor = new ContentKit.Editor(element, { - mobiledoc: payload, + autofocus: false, + mobiledoc: mobiledoc, cards: { 'pick-color': function renderPickColor(payload) { return 'PICK A COLOR: '+payload.options.join(', '); @@ -55,22 +59,106 @@ function bootEditor(element, payload) { }); } -function readPayload(textarea) { - var jqueryTextarea = $(textarea); - var textPayload = jqueryTextarea.val(); - return JSON.parse(textPayload); +function readMobiledoc(string) { + return JSON.parse(string); } -$(function() { - var textarea = $('#mobiledoc-to-load textarea'); - var editor; - textarea.on('input', function() { +function isValidJSON(string) { + try { + JSON.parse(string); + return true; + } catch(e) { + return false; + } +} + +function attemptEditorReboot(editor, textarea) { + var textPayload = $(textarea).val(); + if (isValidJSON(textPayload)) { + var mobiledoc = readMobiledoc(textPayload); if (editor) { editor.destroy(); } - editor = bootEditor($('#editor')[0], readPayload(textarea)); + bootEditor($('#editor')[0], mobiledoc); + } +} + +var sampleMobiledocs = { + simpleMobiledoc: [ + [], + [ + [1, "H2", [ + [[], 0, "headline h2"] + ]], + [1, "P", [ + [[], 0, "hello world"] + ]] + ] + ], + + mobileDocWithMarker: [ + [['B']], + [ + [1, "H2", [ + [[], 0, "headline h2"] + ]], + [1, "P", [ + [[0], 1, "bold world"] + ]] + ] + ], + + mobileDocWithMultipleMarkers: [ + [['B'], ['I']], + [ + [1, "H2", [ + [[], 0, "headline h2"] + ]], + [1, "P", [ + [[], 0, "hello "], + [[0], 1, "bold, "], + [[1], 1, "italic "], + [[], 0, "world."] + ]] + ] + ], + + mobileDocWithAttributeMarker: [ + [['A', ['href', 'http://github.com/bustlelabs/content-kit-editor']]], + [ + [1, "H2", [ + [[], 0, "headline h2"] + ]], + [1, "P", [ + [[], 0, "see it "], + [[0], 1, "on github."] + ]] + ] + ] +}; + + +$(function() { + var editor; + var editorEl = $('#editor')[0]; + var mobiledoc = sampleMobiledocs.simpleMobiledoc; + + var textarea = $('#mobiledoc-to-load textarea'); + textarea.val(JSON.stringify(mobiledoc, false, 2)); + + textarea.on('input', function() { + attemptEditorReboot(editor, textarea); }); - editor = bootEditor($('#editor')[0], readPayload(textarea)); + + $('#select-mobiledoc').on('change', function() { + var mobiledocName = $(this).val(); + var mobiledoc = sampleMobiledocs[mobiledocName]; + textarea.val(JSON.stringify(mobiledoc, false, 2)); + textarea.trigger('input'); + }); + + bootEditor(editorEl, mobiledoc); + $(editorEl).focus(); }); }(this, document)); diff --git a/website/demo/index.html b/website/demo/index.html index 1992c4058..a895c7415 100644 --- a/website/demo/index.html +++ b/website/demo/index.html @@ -1,5 +1,6 @@ + Content Kit Editor Demo 0.2.0 @@ -14,42 +15,58 @@ +

mobiledoc to load

+

+ This mobiledoc will be loaded into the editor. + You can change it and see the editor reload with the new contents. + (If there is a JSON syntax error it will be ignored; if there is a parser + error the editor may stop responding.) +
+ Select a preloaded mobiledoc here: + +

- +

editor

+

+ The live-editing surface. Changes here are serialized to mobiledoc + format and displayed to the right. +

serialized mobiledoc

+

+ When the editor updates, it prints its serialized mobiledoc here. +

rendered mobiledoc

+

+ This is the output of using the runtime (client-side) + mobiledoc-dom-renderer + on the serialized mobiledoc. +

diff --git a/website/global/content-kit-editor.js b/website/global/content-kit-editor.js index a7d522601..1a0cfe368 100644 --- a/website/global/content-kit-editor.js +++ b/website/global/content-kit-editor.js @@ -193,1892 +193,450 @@ var define, requireModule, require, requirejs; }; })(); -define('content-kit-compiler/compiler', ['exports', 'content-kit-compiler/parsers/new-html-parser', 'content-kit-compiler/types/default-types', 'content-kit-utils'], function (exports, _contentKitCompilerParsersNewHtmlParser, _contentKitCompilerTypesDefaultTypes, _contentKitUtils) { - 'use strict'; +define("content-kit-editor/commands/base", ["exports"], function (exports) { + "use strict"; - /** - * @class Compiler - * @constructor - * @param options - */ - function Compiler(options) { - var parser = new _contentKitCompilerParsersNewHtmlParser['default'](); - var defaults = { - renderer: null, - parser: parser, - blockTypes: _contentKitCompilerTypesDefaultTypes.DefaultBlockTypeSet, - markupTypes: _contentKitCompilerTypesDefaultTypes.DefaultMarkupTypeSet, - // Outputs `type_name:'HEADING'` etc. when parsing. Good - // for debugging. - includeTypeNames: false - }; - (0, _contentKitUtils.mergeWithOptions)(this, defaults, options); - if (!this.renderer) { - throw new Error('renderer required'); + function Command(options) { + options = options || {}; + var command = this; + var name = options.name; + var prompt = options.prompt; + command.name = name; + command.button = options.button || name; + if (prompt) { + command.prompt = prompt; } } - /** - * @method parse - * @param input - * @return Array - */ - Compiler.prototype.parse = function (input) { - return this.parser.parse(input); - }; + Command.prototype.exec = function () {}; - /** - * @method render - * @param model - * @return String - */ - Compiler.prototype.render = function (model, target) { - return this.renderer.render(model, target); - }; + exports["default"] = Command; +}); +define('content-kit-editor/commands/bold', ['exports', 'content-kit-editor/commands/text-format', 'content-kit-editor/utils/selection-utils', 'content-kit-utils'], function (exports, _contentKitEditorCommandsTextFormat, _contentKitEditorUtilsSelectionUtils, _contentKitUtils) { + 'use strict'; - /** - * @method rerender - * @param input - * @return String - */ - Compiler.prototype.rerender = function (input) { - return this.render(this.parse(input)); - }; + var RegExpHeadingTag = /^(h1|h2|h3|h4|h5|h6)$/i; - /** - * @method reparse - * @param model - * @return String - */ - Compiler.prototype.reparse = function (model) { - return this.parse(this.render(model)); - }; + function BoldCommand() { + _contentKitEditorCommandsTextFormat['default'].call(this, { + name: 'bold', + tag: 'strong', + mappedTags: ['b'], + button: '' + }); + } + (0, _contentKitUtils.inherit)(BoldCommand, _contentKitEditorCommandsTextFormat['default']); - /** - * @method registerBlockType - * @param {Type} type - */ - Compiler.prototype.registerBlockType = function (type) { - return this.blockTypes.addType(type); + BoldCommand.prototype.exec = function () { + // Don't allow executing bold command on heading tags + if (!RegExpHeadingTag.test((0, _contentKitEditorUtilsSelectionUtils.getSelectionBlockTagName)())) { + BoldCommand._super.prototype.exec.call(this); + } }; - /** - * @method registerMarkupType - * @param {Type} type - */ - Compiler.prototype.registerMarkupType = function (type) { - return this.markupTypes.addType(type); - }; + exports['default'] = BoldCommand; +}); +define('content-kit-editor/commands/card', ['exports', 'content-kit-editor/commands/base', 'content-kit-utils'], function (exports, _contentKitEditorCommandsBase, _contentKitUtils) { + 'use strict'; + + function injectCardBlock(cardName, cardPayload, editor, index) { + throw new Error('Unimplemented: BlockModel and Type.CARD are no longer things'); + // FIXME: Do we change the block model internal representation here? + var cardBlock = BlockModel.createWithType(Type.CARD, { + attributes: { + name: cardName, + payload: cardPayload + } + }); + editor.replaceBlock(cardBlock, index); + } + + function CardCommand() { + _contentKitEditorCommandsBase['default'].call(this, { + name: 'card', + button: 'CA' + }); + } + (0, _contentKitUtils.inherit)(CardCommand, _contentKitEditorCommandsBase['default']); + + CardCommand.prototype = { + exec: function exec() { + CardCommand._super.prototype.exec.call(this); + var editor = this.editorContext; + var currentEditingIndex = editor.getCurrentBlockIndex(); - Compiler.prototype.parseSection = function (previousSection, sectionElement) { - return this.parser.parseSection(previousSection, sectionElement); + var cardName = 'pick-color'; + var cardPayload = { options: ['red', 'blue'] }; + injectCardBlock(cardName, cardPayload, editor, currentEditingIndex); + editor.renderBlockAt(currentEditingIndex, true); + } }; - exports['default'] = Compiler; + exports['default'] = CardCommand; }); -define('content-kit-compiler', ['exports', 'content-kit-compiler/types/type', 'content-kit-compiler/models/block', 'content-kit-compiler/models/embed', 'content-kit-compiler/compiler', 'content-kit-compiler/parsers/html-parser', 'content-kit-compiler/renderers/html-renderer', 'content-kit-compiler/parsers/new-html-parser', 'content-kit-compiler/parsers/document', 'content-kit-compiler/parsers/mobiledoc', 'content-kit-compiler/runtime/renderers/dom'], function (exports, _contentKitCompilerTypesType, _contentKitCompilerModelsBlock, _contentKitCompilerModelsEmbed, _contentKitCompilerCompiler, _contentKitCompilerParsersHtmlParser, _contentKitCompilerRenderersHtmlRenderer, _contentKitCompilerParsersNewHtmlParser, _contentKitCompilerParsersDocument, _contentKitCompilerParsersMobiledoc, _contentKitCompilerRuntimeRenderersDom) { +define('content-kit-editor/commands/format-block', ['exports', 'content-kit-editor/commands/text-format', 'content-kit-editor/utils/selection-utils', 'content-kit-utils'], function (exports, _contentKitEditorCommandsTextFormat, _contentKitEditorUtilsSelectionUtils, _contentKitUtils) { 'use strict'; - exports.registerGlobal = registerGlobal; + function FormatBlockCommand(options) { + options = options || {}; + options.action = 'formatBlock'; + _contentKitEditorCommandsTextFormat['default'].call(this, options); + } + (0, _contentKitUtils.inherit)(FormatBlockCommand, _contentKitEditorCommandsTextFormat['default']); - var Runtime = { - DOMRenderer: _contentKitCompilerRuntimeRenderersDom['default'] - }; + FormatBlockCommand.prototype.exec = function () { + var tag = this.tag; + // Brackets neccessary for certain browsers + var value = '<' + tag + '>'; + var blockElement = (0, _contentKitEditorUtilsSelectionUtils.getSelectionBlockElement)(); + // Allow block commands to be toggled back to a text block + if (tag === blockElement.tagName.toLowerCase()) { + throw new Error('Unimplemented: Type.BOLD.paragraph must be replaced'); + value = Type.PARAGRAPH.tag; + } else { + // Flattens the selection before applying the block format. + // Otherwise, undesirable nested blocks can occur. + // TODO: would love to be able to remove this + var flatNode = document.createTextNode(blockElement.textContent); + blockElement.parentNode.insertBefore(flatNode, blockElement); + blockElement.parentNode.removeChild(blockElement); + (0, _contentKitEditorUtilsSelectionUtils.selectNode)(flatNode); + } - /** - * @namespace ContentKit - * Register public ContentKit compiler modules - */ - var ContentKitCompiler = { - Type: _contentKitCompilerTypesType['default'], - BlockModel: _contentKitCompilerModelsBlock['default'], - EmbedModel: _contentKitCompilerModelsEmbed['default'], - Compiler: _contentKitCompilerCompiler['default'], - HTMLParser: _contentKitCompilerParsersHtmlParser['default'], - HTMLRenderer: _contentKitCompilerRenderersHtmlRenderer['default'], - NewHTMLParser: _contentKitCompilerParsersNewHtmlParser['default'], - MobiledocParser: _contentKitCompilerParsersMobiledoc['default'], - Runtime: Runtime + FormatBlockCommand._super.prototype.exec.call(this, value); }; - exports.Type = _contentKitCompilerTypesType['default']; - exports.BlockModel = _contentKitCompilerModelsBlock['default']; - exports.EmbedModel = _contentKitCompilerModelsEmbed['default']; - exports.Compiler = _contentKitCompilerCompiler['default']; - exports.HTMLParser = _contentKitCompilerParsersHtmlParser['default']; - exports.HTMLRenderer = _contentKitCompilerRenderersHtmlRenderer['default']; - exports.NewHTMLParser = _contentKitCompilerParsersNewHtmlParser['default']; - exports.MobiledocParser = _contentKitCompilerParsersMobiledoc['default']; - exports.Runtime = Runtime; - exports.doc = _contentKitCompilerParsersDocument['default']; + exports['default'] = FormatBlockCommand; +}); +define('content-kit-editor/commands/heading', ['exports', 'content-kit-editor/commands/format-block', 'content-kit-utils'], function (exports, _contentKitEditorCommandsFormatBlock, _contentKitUtils) { + 'use strict'; - function registerGlobal(window) { - window.ContentKitCompiler = ContentKitCompiler; + function HeadingCommand() { + _contentKitEditorCommandsFormatBlock['default'].call(this, { + name: 'heading', + tag: 'h2', + button: '1' + }); } + (0, _contentKitUtils.inherit)(HeadingCommand, _contentKitEditorCommandsFormatBlock['default']); - exports['default'] = ContentKitCompiler; + exports['default'] = HeadingCommand; }); -define('content-kit-compiler/models/block', ['exports', 'content-kit-compiler/models/model', 'content-kit-utils'], function (exports, _contentKitCompilerModelsModel, _contentKitUtils) { +define('content-kit-editor/commands/image', ['exports', 'content-kit-editor/commands/base', 'content-kit-editor/views/message', 'content-kit-utils', 'content-kit-editor/utils/http-utils'], function (exports, _contentKitEditorCommandsBase, _contentKitEditorViewsMessage, _contentKitUtils, _contentKitEditorUtilsHttpUtils) { 'use strict'; - /** - * Ensures block markups at the same index are always in a specific order. - * For example, so all bold links are consistently marked up - * as text instead of text - */ - function sortBlockMarkups(markups) { - return markups.sort(function (a, b) { - if (a.start === b.start && a.end === b.end) { - return b.type - a.type; - } - return 0; + function createFileInput(command) { + var fileInput = document.createElement('input'); + fileInput.type = 'file'; + fileInput.accept = 'image/*'; + fileInput.className = 'ck-file-input'; + fileInput.addEventListener('change', function (e) { + command.handleFile(e); }); + return fileInput; } - /** - * @class BlockModel - * @constructor - * @extends Model - */ - function BlockModel(options) { - options = options || {}; - _contentKitCompilerModelsModel['default'].call(this, options); - this.value = options.value || ''; - this.markup = sortBlockMarkups(options.markup || []); + function injectImageBlock(src, editor, index) { + throw new Error('Unimplemented: BlockModel and Type.IMAGE are no longer things'); + var imageModel = BlockModel.createWithType(Type.IMAGE, { attributes: { src: src } }); + editor.replaceBlock(imageModel, index); } - (0, _contentKitUtils.inherit)(BlockModel, _contentKitCompilerModelsModel['default']); - - exports['default'] = BlockModel; -}); -define('content-kit-compiler/models/embed', ['exports', 'content-kit-compiler/models/model', 'content-kit-compiler/types/type'], function (exports, _contentKitCompilerModelsModel, _contentKitCompilerTypesType) { - 'use strict'; - - /** - * @class EmbedModel - * @constructor - * @extends Model - * Massages data from an oEmbed response into an EmbedModel - */ - function EmbedModel(options) { - if (!options) { - return null; + function renderFromFile(file, editor, index) { + if (file && window.FileReader) { + var reader = new FileReader(); + reader.onload = function (e) { + var base64Src = e.target.result; + injectImageBlock(base64Src, editor, index); + editor.renderBlockAt(index, true); + }; + reader.readAsDataURL(file); } + } - _contentKitCompilerModelsModel['default'].call(this, { - type: _contentKitCompilerTypesType['default'].EMBED.id, - type_name: _contentKitCompilerTypesType['default'].EMBED.name, - attributes: {} + function ImageCommand(options) { + _contentKitEditorCommandsBase['default'].call(this, { + name: 'image', + button: '' }); + this.uploader = new _contentKitEditorUtilsHttpUtils.FileUploader({ url: options.serviceUrl, maxFileSize: 5000000 }); + } + (0, _contentKitUtils.inherit)(ImageCommand, _contentKitEditorCommandsBase['default']); - // Massage the oEmbed data - var attributes = this.attributes; - var embedType = options.type; - var providerName = options.provider_name; - var embedUrl = options.url; - var embedTitle = options.title; - var embedThumbnail = options.thumbnail_url; - var embedHtml = options.html; - - if (embedType) { - attributes.embed_type = embedType; - } - if (providerName) { - attributes.provider_name = providerName; - } - if (embedUrl) { - attributes.url = embedUrl; - } - if (embedTitle) { - attributes.title = embedTitle; - } - - if (embedType === 'photo') { - attributes.thumbnail = options.media_url || embedUrl; - } else if (embedThumbnail) { - attributes.thumbnail = embedThumbnail; - } + ImageCommand.prototype = { + exec: function exec() { + ImageCommand._super.prototype.exec.call(this); + var fileInput = this.fileInput; + if (!fileInput) { + fileInput = this.fileInput = createFileInput(this); + document.body.appendChild(fileInput); + } + fileInput.dispatchEvent(new MouseEvent('click', { bubbles: false })); + }, + handleFile: function handleFile(e) { + var fileInput = e.target; + var file = fileInput.files && fileInput.files[0]; + var editor = this.editorContext; + var embedIntent = this.embedIntent; + var currentEditingIndex = editor.getCurrentBlockIndex(); - if (embedHtml && (embedType === 'rich' || embedType === 'video')) { - attributes.html = embedHtml; + embedIntent.showLoading(); + renderFromFile(file, editor, currentEditingIndex); // render image immediately client-side + this.uploader.upload({ + fileInput: fileInput, + complete: function complete(response, error) { + embedIntent.hideLoading(); + if (error || !response || !response.url) { + setTimeout(function () { + editor.removeBlockAt(currentEditingIndex); + editor.syncVisual(); + }, 1000); + return new _contentKitEditorViewsMessage['default']().showError(error.message || 'Error uploading image'); + } + injectImageBlock(response.url, editor, currentEditingIndex); + } + }); + fileInput.value = null; // reset file input } - } + }; - exports['default'] = EmbedModel; + exports['default'] = ImageCommand; }); -define('content-kit-compiler/models/markup', ['exports', 'content-kit-compiler/models/model', 'content-kit-utils'], function (exports, _contentKitCompilerModelsModel, _contentKitUtils) { +define('content-kit-editor/commands/italic', ['exports', 'content-kit-editor/commands/text-format', 'content-kit-utils'], function (exports, _contentKitEditorCommandsTextFormat, _contentKitUtils) { 'use strict'; - /** - * @class MarkupModel - * @constructor - * @extends Model - */ - function MarkupModel(options) { - options = options || {}; - _contentKitCompilerModelsModel['default'].call(this, options); - this.start = options.start || 0; - this.end = options.end || 0; + function ItalicCommand() { + _contentKitEditorCommandsTextFormat['default'].call(this, { + name: 'italic', + tag: 'em', + mappedTags: ['i'], + button: '' + }); } + (0, _contentKitUtils.inherit)(ItalicCommand, _contentKitEditorCommandsTextFormat['default']); - (0, _contentKitUtils.inherit)(MarkupModel, _contentKitCompilerModelsModel['default']); - - exports['default'] = MarkupModel; + exports['default'] = ItalicCommand; }); -define("content-kit-compiler/models/model", ["exports"], function (exports) { - /** - * @class Model - * @constructor - * @private - */ - "use strict"; +define('content-kit-editor/commands/link', ['exports', 'content-kit-editor/commands/text-format', 'content-kit-editor/views/prompt', 'content-kit-editor/utils/selection-utils', 'content-kit-utils'], function (exports, _contentKitEditorCommandsTextFormat, _contentKitEditorViewsPrompt, _contentKitEditorUtilsSelectionUtils, _contentKitUtils) { + 'use strict'; - function Model(options) { - options = options || {}; - var type_name = options.type_name; - var attributes = options.attributes; + var RegExpHttp = /^https?:\/\//i; - this.type = options.type || null; - if (type_name) { - this.type_name = type_name; - } - if (attributes) { - this.attributes = attributes; - } + function LinkCommand() { + _contentKitEditorCommandsTextFormat['default'].call(this, { + name: 'link', + tag: 'a', + action: 'createLink', + removeAction: 'unlink', + button: '', + prompt: new _contentKitEditorViewsPrompt['default']({ + command: this, + placeholder: 'Enter a url, press return...' + }) + }); } + (0, _contentKitUtils.inherit)(LinkCommand, _contentKitEditorCommandsTextFormat['default']); - /** - * @method createWithType - * @static - * @param type Type - * @param options Object - */ - Model.createWithType = function (type, options) { - options = options || {}; - options.type = type.id; - options.type_name = type.name; - return new this(options); + LinkCommand.prototype.exec = function (url) { + if (!url) { + return LinkCommand._super.prototype.unexec.call(this); + } + + if (this.tag === (0, _contentKitEditorUtilsSelectionUtils.getSelectionTagName)()) { + this.unexec(); + } else { + if (!RegExpHttp.test(url)) { + url = 'http://' + url; + } + LinkCommand._super.prototype.exec.call(this, url); + } }; - exports["default"] = Model; + exports['default'] = LinkCommand; }); -define('content-kit-compiler/models/post', ['exports', 'content-kit-compiler/utils/element-map'], function (exports, _contentKitCompilerUtilsElementMap) { +define('content-kit-editor/commands/list', ['exports', 'content-kit-editor/commands/text-format', 'content-kit-editor/utils/selection-utils', 'content-kit-utils'], function (exports, _contentKitEditorCommandsTextFormat, _contentKitEditorUtilsSelectionUtils, _contentKitUtils) { 'use strict'; - var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + function ListCommand(options) { + _contentKitEditorCommandsTextFormat['default'].call(this, options); + } + (0, _contentKitUtils.inherit)(ListCommand, _contentKitEditorCommandsTextFormat['default']); - // FIXME: making sections a linked-list would greatly improve this - - var Post = (function () { - function Post() { - _classCallCheck(this, Post); + ListCommand.prototype.exec = function () { + ListCommand._super.prototype.exec.call(this); - this.type = 'post'; - this.sections = []; - this.sectionElementMap = new _contentKitCompilerUtilsElementMap['default'](); + // After creation, lists need to be unwrapped + // TODO: eventually can remove this when direct model manipulation is ready + var listElement = (0, _contentKitEditorUtilsSelectionUtils.getSelectionBlockElement)(); + var wrapperNode = listElement.parentNode; + if (wrapperNode.firstChild === listElement) { + var editorNode = wrapperNode.parentNode; + editorNode.insertBefore(listElement, wrapperNode); + editorNode.removeChild(wrapperNode); + (0, _contentKitEditorUtilsSelectionUtils.selectNode)(listElement); } + }; - _createClass(Post, [{ - key: 'appendSection', - value: function appendSection(section) { - this.sections.push(section); - } - }, { - key: 'prependSection', - value: function prependSection(section) { - this.sections.unshift(section); - } - }, { - key: 'replaceSection', - value: function replaceSection(section, newSection) { - this.insertSectionAfter(newSection, section); - this.removeSection(section); - } - }, { - key: 'insertSectionAfter', - value: function insertSectionAfter(section, previousSection) { - var i, l; - for (i = 0, l = this.sections.length; i < l; i++) { - if (this.sections[i] === previousSection) { - this.sections.splice(i + 1, 0, section); - return; - } - } - throw new Error('Previous section was not found in post.sections'); - } - }, { - key: 'setSectionElement', - value: function setSectionElement(section, element) { - section.element = element; - this.sectionElementMap.set(element, section); - } - }, { - key: 'getSectionElement', - value: function getSectionElement(section) { - return section && section.element; - } - }, { - key: 'getElementSection', - value: function getElementSection(element) { - return this.sectionElementMap.get(element); - } - }, { - key: 'removeSection', - value: function removeSection(section) { - this.sectionElementMap.remove(section.element); - var i, l; - for (i = 0, l = this.sections.length; i < l; i++) { - if (this.sections[i] === section) { - this.sections.splice(i, 1); - return; - } - } - } - }, { - key: 'getPreviousSection', - value: function getPreviousSection(section) { - var i, l; - if (this.sections[0] !== section) { - for (i = 1, l = this.sections.length; i < l; i++) { - if (this.sections[i] === section) { - return this.sections[i - 1]; - } - } - } + ListCommand.prototype.checkAutoFormat = function (node) { + // Creates unordered lists when node starts with '- ' + // or ordered list if node starts with '1. ' + var regex = this.autoFormatRegex, + text; + if (node && regex) { + text = node.textContent; + if ('li' !== (0, _contentKitEditorUtilsSelectionUtils.getSelectionTagName)() && regex.test(text)) { + this.exec(); + window.getSelection().anchorNode.textContent = text.replace(regex, ''); + return true; } - }]); - - return Post; - })(); - - exports['default'] = Post; -}); -define('content-kit-compiler/parsers/document', ['exports'], function (exports) { - /** - * Abstracted `document` between node.js and browser - */ - - 'use strict'; - - var doc; - - if (typeof module !== 'undefined' && module.exports) { - var jsdom = require('jsdom').jsdom; - doc = jsdom(); - } else { - // A document instance separate from the html page document. (if browser supports it) - // Prevents images, scripts, and styles from executing while parsing - var implementation = document.implementation; - var createHTMLDocument = implementation.createHTMLDocument; - if (createHTMLDocument) { - doc = createHTMLDocument.call(implementation, ''); - } else { - doc = document; } - } + return false; + }; - exports['default'] = doc; + exports['default'] = ListCommand; }); -define('content-kit-compiler/parsers/html-parser', ['exports', 'content-kit-compiler/parsers/document', 'content-kit-compiler/models/block', 'content-kit-compiler/models/markup', 'content-kit-compiler/types/type', 'content-kit-compiler/types/default-types', 'content-kit-utils'], function (exports, _contentKitCompilerParsersDocument, _contentKitCompilerModelsBlock, _contentKitCompilerModelsMarkup, _contentKitCompilerTypesType, _contentKitCompilerTypesDefaultTypes, _contentKitUtils) { +define('content-kit-editor/commands/oembed', ['exports', 'content-kit-editor/commands/base', 'content-kit-editor/views/prompt', 'content-kit-editor/views/message', 'content-kit-utils', 'content-kit-editor/utils/http-utils'], function (exports, _contentKitEditorCommandsBase, _contentKitEditorViewsPrompt, _contentKitEditorViewsMessage, _contentKitUtils, _contentKitEditorUtilsHttpUtils) { 'use strict'; - var ELEMENT_NODE = 1; - var TEXT_NODE = 3; - var defaultAttributeBlacklist = { 'style': 1, 'class': 1 }; - - /** - * Returns the last block in the set or creates a default block if none exist yet. - */ - function getLastBlockOrCreate(blocks) { - var blockCount = blocks.length, - block; - if (blockCount) { - block = blocks[blockCount - 1]; + function loadTwitterWidgets(element) { + if (window.twttr) { + window.twttr.widgets.load(element); } else { - block = _contentKitCompilerModelsBlock['default'].createWithType(_contentKitCompilerTypesType['default'].PARAGRAPH); - blocks.push(block); + var script = document.createElement('script'); + script.async = true; + script.src = 'http://platform.twitter.com/widgets.js'; + document.head.appendChild(script); } - return block; } - /** - * Helper to parse elements at the root that aren't blocks - */ - function handleNonBlockAtRoot(parser, elementNode, blocks) { - var block = getLastBlockOrCreate(blocks); - var markup = parser.parseMarkupForElement(elementNode, block.value.length); - if (markup) { - block.markup = block.markup.concat(markup); - } - block.value += (0, _contentKitUtils.textOfNode)(elementNode); - } + function OEmbedCommand(options) { + _contentKitEditorCommandsBase['default'].call(this, { + name: 'embed', + button: '', + prompt: new _contentKitEditorViewsPrompt['default']({ + command: this, + placeholder: 'Paste a YouTube or Twitter url...' + }) + }); - /** - * @class HTMLParser - * @constructor - */ - function HTMLParser(options) { - var defaults = { - blockTypes: _contentKitCompilerTypesDefaultTypes.DefaultBlockTypeSet, - markupTypes: _contentKitCompilerTypesDefaultTypes.DefaultMarkupTypeSet, - attributeBlacklist: defaultAttributeBlacklist, - includeTypeNames: false - }; - (0, _contentKitUtils.mergeWithOptions)(this, defaults, options); + this.embedService = new _contentKitEditorUtilsHttpUtils.OEmbedder({ url: options.serviceUrl }); } + (0, _contentKitUtils.inherit)(OEmbedCommand, _contentKitEditorCommandsBase['default']); - /** - * @method parse - * @param html String of HTML content - * @return Array Parsed JSON content array - */ - HTMLParser.prototype.parse = function (html) { - var parsingNode = _contentKitCompilerParsersDocument['default'].createElement('div'); - parsingNode.innerHTML = (0, _contentKitUtils.sanitizeWhitespace)(html); - - var nodes = (0, _contentKitUtils.toArray)(parsingNode.childNodes); - var nodeCount = nodes.length; - var blocks = []; - var i, node, nodeType, block, text; - - for (i = 0; i < nodeCount; i++) { - node = nodes[i]; - nodeType = node.nodeType; + OEmbedCommand.prototype.exec = function (url) { + var command = this; + var editorContext = command.editorContext; + var embedIntent = command.embedIntent; + var index = editorContext.getCurrentBlockIndex(); - if (nodeType === ELEMENT_NODE) { - block = this.serializeBlockNode(node); - if (block) { - blocks.push(block); + embedIntent.showLoading(); + this.embedService.fetch({ + url: url, + complete: function complete(response, error) { + embedIntent.hideLoading(); + if (error) { + var errorMsg = error; + if (error.target && error.target.status === 0) { + errorMsg = 'Error: could not connect to embed service.'; + } else if (typeof error !== 'string') { + errorMsg = 'Error: unexpected embed error.'; + } + new _contentKitEditorViewsMessage['default']().showError(errorMsg); + embedIntent.show(); + } else if (response.error_message) { + new _contentKitEditorViewsMessage['default']().showError(response.error_message); + embedIntent.show(); } else { - handleNonBlockAtRoot(this, node, blocks); - } - } else if (nodeType === TEXT_NODE) { - text = node.nodeValue; - if ((0, _contentKitUtils.trim)(text)) { - block = getLastBlockOrCreate(blocks); - block.value += text; + throw new Error('Unimplemented EmbedModel is not a thing'); + var embedModel = new EmbedModel(response); + editorContext.insertBlock(embedModel, index); + editorContext.renderBlockAt(index); + if (embedModel.attributes.provider_name.toLowerCase() === 'twitter') { + loadTwitterWidgets(editorContext.element); + } } } - } - - return blocks; + }); }; - /** - * @method parseMarkupForElement - * @param node element node to parse - * @return {Array} parsed markups - */ - HTMLParser.prototype.parseMarkupForElement = function (node, startOffset) { - var index = 0; - var markups = []; - var currentNode, nodeType, markup; - - startOffset = startOffset || 0; - node = node.cloneNode(true); - markup = this.serializeMarkupNode(node, startOffset); - if (markup) { - markups.push(markup); - } + exports['default'] = OEmbedCommand; +}); +define('content-kit-editor/commands/ordered-list', ['exports', 'content-kit-editor/commands/list', 'content-kit-utils'], function (exports, _contentKitEditorCommandsList, _contentKitUtils) { + 'use strict'; - while (node.hasChildNodes()) { - currentNode = node.firstChild; - nodeType = currentNode.nodeType; + function OrderedListCommand() { + _contentKitEditorCommandsList['default'].call(this, { + name: 'ordered list', + tag: 'ol', + action: 'insertOrderedList' + }); + } + (0, _contentKitUtils.inherit)(OrderedListCommand, _contentKitEditorCommandsList['default']); - if (nodeType === ELEMENT_NODE) { - markup = this.serializeMarkupNode(currentNode, startOffset); - if (markup) { - markups.push(markup); - } - (0, _contentKitUtils.unwrapNode)(currentNode); - } else if (nodeType === TEXT_NODE) { - var text = (0, _contentKitUtils.sanitizeWhitespace)(currentNode.nodeValue); - if (index === 0) { - text = (0, _contentKitUtils.trimLeft)(text); - } - if (text) { - startOffset += text.length; - } - } + OrderedListCommand.prototype.autoFormatRegex = /^1\.\s/; - currentNode.parentNode.removeChild(currentNode); - index++; - } + exports['default'] = OrderedListCommand; +}); +define('content-kit-editor/commands/quote', ['exports', 'content-kit-editor/commands/format-block', 'content-kit-utils'], function (exports, _contentKitEditorCommandsFormatBlock, _contentKitUtils) { + 'use strict'; - return markups; - }; + function QuoteCommand() { + _contentKitEditorCommandsFormatBlock['default'].call(this, { + name: 'quote', + tag: 'blockquote', + button: '' + }); + } + (0, _contentKitUtils.inherit)(QuoteCommand, _contentKitEditorCommandsFormatBlock['default']); - /** - * @method serializeBlockNode - * @param node element node to parse - * @return {BlockModel} parsed block model - * Serializes a single block type node into a model - */ - HTMLParser.prototype.serializeBlockNode = function (node) { - var type = this.blockTypes.findByNode(node); - if (type) { - return new _contentKitCompilerModelsBlock['default']({ - type: type.id, - type_name: this.includeTypeNames && type.name, - value: (0, _contentKitUtils.trim)((0, _contentKitUtils.textOfNode)(node)), - attributes: (0, _contentKitUtils.attributesForNode)(node, this.attributeBlacklist), - markup: this.parseMarkupForElement(node) - }); - } - }; + exports['default'] = QuoteCommand; +}); +define('content-kit-editor/commands/subheading', ['exports', 'content-kit-editor/commands/format-block', 'content-kit-utils'], function (exports, _contentKitEditorCommandsFormatBlock, _contentKitUtils) { + 'use strict'; - /** - * @method serializeMarkupNode - * @param node element node to parse - * @param startIndex - * @return {MarkupModel} markup model - * Serializes markup of a single html element node (no child elements) - */ - HTMLParser.prototype.serializeMarkupNode = function (node, startIndex) { - var type = this.markupTypes.findByNode(node); - var selfClosing, endIndex; - - if (type) { - selfClosing = type.selfClosing; - if (!selfClosing && !node.hasChildNodes()) { - return; - } // check for empty nodes - - endIndex = startIndex + (selfClosing ? 0 : (0, _contentKitUtils.textOfNode)(node).length); - if (endIndex > startIndex || selfClosing && endIndex === startIndex) { - // check for empty nodes - return new _contentKitCompilerModelsMarkup['default']({ - type: type.id, - type_name: this.includeTypeNames && type.name, - start: startIndex, - end: endIndex, - attributes: (0, _contentKitUtils.attributesForNode)(node, this.attributeBlacklist) - }); - } - } - }; + function SubheadingCommand() { + _contentKitEditorCommandsFormatBlock['default'].call(this, { + name: 'subheading', + tag: 'h3', + button: '2' + }); + } + (0, _contentKitUtils.inherit)(SubheadingCommand, _contentKitEditorCommandsFormatBlock['default']); - exports['default'] = HTMLParser; + exports['default'] = SubheadingCommand; }); -define('content-kit-compiler/parsers/mobiledoc', ['exports', 'content-kit-compiler/post-builder'], function (exports, _contentKitCompilerPostBuilder) { +define('content-kit-editor/commands/text-format', ['exports', 'content-kit-editor/commands/base', 'content-kit-utils'], function (exports, _contentKitEditorCommandsBase, _contentKitUtils) { 'use strict'; - var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); + function TextFormatCommand(options) { + options = options || {}; + _contentKitEditorCommandsBase['default'].call(this, options); + this.tag = options.tag; + this.mappedTags = options.mappedTags || []; + this.mappedTags.push(this.tag); + this.action = options.action || this.name; + this.removeAction = options.removeAction || this.action; + } + (0, _contentKitUtils.inherit)(TextFormatCommand, _contentKitEditorCommandsBase['default']); - var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + TextFormatCommand.prototype = { + exec: function exec(value) { + document.execCommand(this.action, false, value || null); + }, + unexec: function unexec(value) { + document.execCommand(this.removeAction, false, value || null); + } + }; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - /* - * input mobiledoc: [ markers, elements ] - * output: Post - * - */ - - var MobiledocParser = (function () { - function MobiledocParser() { - _classCallCheck(this, MobiledocParser); - - this.builder = (0, _contentKitCompilerPostBuilder.generateBuilder)(); - } - - _createClass(MobiledocParser, [{ - key: 'parse', - value: function parse(mobiledoc) { - var markerTypes = mobiledoc[0]; - var sections = mobiledoc[1]; - - var post = this.builder.generatePost(); - - this.markerTypes = this.parseMarkerTypes(markerTypes); - this.parseSections(sections, post); - - return post; - } - }, { - key: 'parseMarkerTypes', - value: function parseMarkerTypes(markerTypes) { - var _this = this; - - return markerTypes.map(function (markerType) { - return _this.parseMarkerType(markerType); - }); - } - }, { - key: 'parseMarkerType', - value: function parseMarkerType(_ref) { - var _ref2 = _slicedToArray(_ref, 2); - - var tagName = _ref2[0]; - var attributes = _ref2[1]; - - return this.builder.generateMarkerType(tagName, attributes); - } - }, { - key: 'parseSections', - value: function parseSections(sections, post) { - var _this2 = this; - - sections.forEach(function (section) { - return _this2.parseSection(section, post); - }); - } - }, { - key: 'parseSection', - value: function parseSection(section, post) { - var _section = _slicedToArray(section, 1); - - var type = _section[0]; - - switch (type) { - case 1: - // markup section - this.parseMarkupSection(section, post); - break; - default: - throw new Error('Unexpected section type ' + type); - } - } - }, { - key: 'parseMarkupSection', - value: function parseMarkupSection(_ref3, post) { - var _ref32 = _slicedToArray(_ref3, 3); - - var type = _ref32[0]; - var tagName = _ref32[1]; - var markers = _ref32[2]; - - var attributes = null; - var isGenerated = false; - var section = this.builder.generateSection(tagName, attributes, isGenerated); - - post.appendSection(section); - this.parseMarkers(markers, section); - } - }, { - key: 'parseMarkers', - value: function parseMarkers(markers, section) { - var _this3 = this; - - markers.forEach(function (marker) { - return _this3.parseMarker(marker, section); - }); - } - }, { - key: 'parseMarker', - value: function parseMarker(_ref4, section) { - var _this4 = this; - - var _ref42 = _slicedToArray(_ref4, 3); - - var markerTypeIndexes = _ref42[0]; - var closeCount = _ref42[1]; - var value = _ref42[2]; - - var markerTypes = markerTypeIndexes.map(function (index) { - return _this4.markerTypes[index]; - }); - var marker = this.builder.generateMarker(markerTypes, closeCount, value); - section.markers.push(marker); - } - }]); - - return MobiledocParser; - })(); - - exports['default'] = MobiledocParser; -}); -define('content-kit-compiler/parsers/new-html-parser', ['exports', 'content-kit-compiler/post-builder', 'content-kit-utils'], function (exports, _contentKitCompilerPostBuilder, _contentKitUtils) { - 'use strict'; - - var ELEMENT_NODE = 1; - var TEXT_NODE = 3; - - var MARKUP_SECTION_TAG_NAMES = ['P', 'H3', 'H2', 'H1', 'BLOCKQUOTE', 'UL', 'IMG', 'OL']; - - var ALLOWED_ATTRIBUTES = ['href', 'rel', 'src']; - - function isEmptyTextNode(node) { - return node.nodeType === TEXT_NODE && (0, _contentKitUtils.trim)(node.textContent) === ''; - } - - // FIXME: should probably always return an array - function readAttributes(node) { - var attributes = null; - if (node.hasAttributes()) { - attributes = []; - var i, l; - for (i = 0, l = node.attributes.length; i < l; i++) { - if (ALLOWED_ATTRIBUTES.indexOf(node.attributes[i].name) !== -1) { - attributes.push(node.attributes[i].name); - attributes.push(node.attributes[i].value); - } - } - if (attributes.length === 0) { - return null; - } - } - return attributes; - } - - var VALID_MARKER_ELEMENTS = ['B', 'I', 'STRONG', 'EM', 'A']; - - function isValidMarkerElement(element) { - return VALID_MARKER_ELEMENTS.indexOf(element.tagName) !== -1; - } - - function parseMarkers(section, postBuilder, topNode) { - var markerTypes = []; - var text = null; - var currentNode = topNode; - while (currentNode) { - switch (currentNode.nodeType) { - case ELEMENT_NODE: - if (isValidMarkerElement(currentNode)) { - markerTypes.push(postBuilder.generateMarkerType(currentNode.tagName, readAttributes(currentNode))); - } - break; - case TEXT_NODE: - text = (text || '') + currentNode.textContent; - break; - } - - if (currentNode.firstChild) { - if (isValidMarkerElement(currentNode) && text !== null) { - section.markers.push(postBuilder.generateMarker(markerTypes, 0, text)); - markerTypes = []; - text = null; - } - currentNode = currentNode.firstChild; - } else if (currentNode.nextSibling) { - if (currentNode === topNode) { - section.markers.push(postBuilder.generateMarker(markerTypes, markerTypes.length, text)); - break; - } else { - currentNode = currentNode.nextSibling; - if (currentNode.nodeType === ELEMENT_NODE && isValidMarkerElement(currentNode) && text !== null) { - section.markers.push(postBuilder.generateMarker(markerTypes, 0, text)); - markerTypes = []; - text = null; - } - } - } else { - var toClose = 0; - while (currentNode && !currentNode.nextSibling && currentNode !== topNode) { - currentNode = currentNode.parentNode; - if (isValidMarkerElement(currentNode)) { - toClose++; - } - } - - section.markers.push(postBuilder.generateMarker(markerTypes, toClose, text)); - markerTypes = []; - text = null; - - if (currentNode === topNode) { - break; - } else { - currentNode = currentNode.nextSibling; - if (currentNode === topNode) { - break; - } - } - } - } - } - - function NewHTMLParser() { - this.postBuilder = (0, _contentKitCompilerPostBuilder.generateBuilder)(); - } - - NewHTMLParser.prototype = { - parseSection: function parseSection(previousSection, sectionElement) { - var postBuilder = this.postBuilder; - var section; - switch (sectionElement.nodeType) { - case ELEMENT_NODE: - var tagName = sectionElement.tagName; - //

, etc - if (MARKUP_SECTION_TAG_NAMES.indexOf(tagName) !== -1) { - section = postBuilder.generateSection(tagName, readAttributes(sectionElement)); - var node = sectionElement.firstChild; - while (node) { - parseMarkers(section, postBuilder, node); - node = node.nextSibling; - } - // , etc - } else { - if (previousSection && previousSection.isGenerated) { - section = previousSection; - } else { - section = postBuilder.generateSection('P', {}, true); - } - parseMarkers(section, postBuilder, sectionElement); - } - break; - case TEXT_NODE: - if (previousSection && previousSection.isGenerated) { - section = previousSection; - } else { - section = postBuilder.generateSection('P', {}, true); - } - parseMarkers(section, postBuilder, sectionElement); - break; - } - return section; - }, - parse: function parse(postElement) { - var post = this.postBuilder.generatePost(); - var i, l, section, previousSection, sectionElement; - // FIXME: Instead of storing isGenerated on sections, and passing - // the previous section to the parser, we could instead do a two-pass - // parse. The first pass identifies sections and gathers a list of - // dom nodes that can be parsed for markers, the second pass parses - // for markers. - for (i = 0, l = postElement.childNodes.length; i < l; i++) { - sectionElement = postElement.childNodes[i]; - if (!isEmptyTextNode(sectionElement)) { - section = this.parseSection(previousSection, sectionElement); - if (section !== previousSection) { - post.appendSection(section); - previousSection = section; - } - } - } - return post; - } - }; - - exports['default'] = NewHTMLParser; -}); -define('content-kit-compiler/post-builder', ['exports', 'content-kit-compiler/models/post'], function (exports, _contentKitCompilerModelsPost) { - 'use strict'; - - exports.generateBuilder = generateBuilder; - - var builder = { - generatePost: function generatePost() { - return new _contentKitCompilerModelsPost['default'](); - }, - generateSection: function generateSection(tagName, attributes, isGenerated) { - var section = { - type: 'markupSection', - tagName: tagName, - markers: [] - }; - if (attributes && attributes.length) { - section.attributes = attributes; - } - if (isGenerated) { - section.isGenerated = !!isGenerated; - } - return section; - }, - // open: Array - // close: Integer - // value: String - generateMarker: function generateMarker(open, close, value) { - return { - type: 'marker', - open: open, - close: close, - value: value - }; - }, - generateMarkerType: function generateMarkerType(tagName, attributes) { - if (attributes) { - // FIXME: This could also be cached - return { - type: 'markerType', - tagName: tagName, - attributes: attributes - }; - } - var markerType = this._markerTypeCache[tagName]; - if (!markerType) { - this._markerTypeCache[tagName] = markerType = { - type: 'markerType', - tagName: tagName - }; - } - return markerType; - } - }; - - function reset(builder) { - builder._markerTypeCache = {}; - } - - function generateBuilder() { - reset(builder); - return builder; - } -}); -define('content-kit-compiler/renderers/card-renderer', ['exports'], function (exports) { - /** - * @class CardRenderer - * @constructor - */ - 'use strict'; - - function CardRenderer(cards) { - this.cards = cards; - } - - /** - * @method render - * @param model a card model - * @return String html - */ - CardRenderer.prototype.render = function (model) { - var render = this.cards[model.attributes.name]; - return '
' + render(model.attributes.payload) + '
'; - }; - - exports['default'] = CardRenderer; -}); -define('content-kit-compiler/renderers/html-element-renderer', ['exports', 'content-kit-utils'], function (exports, _contentKitUtils) { - 'use strict'; - - /** - * Builds an opening html tag. i.e. '

'; - } + var type = _ref32[0]; + var tagName = _ref32[1]; + var markers = _ref32[2]; - function imageRenderer(model) { - return '
' + '
' + this.render(model) + '
' + '
'; - } + var attributes = null; + var isGenerated = false; + var section = this.builder.generateSection(tagName, attributes, isGenerated); - var typeRenderers = {}; - typeRenderers[_contentKitCompiler.Type.EMBED.id] = embedRenderer; - typeRenderers[_contentKitCompiler.Type.IMAGE.id] = imageRenderer; + post.appendSection(section); + this.parseMarkers(markers, section); + } + }, { + key: 'parseMarkers', + value: function parseMarkers(markers, section) { + var _this3 = this; - /** - * @class EditorHTMLRenderer - * @constructor - * Subclass of HTMLRenderer specifically for the Editor - * Wraps interactive elements to add functionality - */ - function EditorHTMLRenderer(options) { - var rendererOptions = { - typeRenderers: typeRenderers - }; - (0, _contentKitUtils.merge)(rendererOptions, options); - _contentKitCompiler.HTMLRenderer.call(this, rendererOptions); - } - (0, _contentKitUtils.inherit)(EditorHTMLRenderer, _contentKitCompiler.HTMLRenderer); + markers.forEach(function (marker) { + return _this3.parseMarker(marker, section); + }); + } + }, { + key: 'parseMarker', + value: function parseMarker(_ref4, section) { + var _this4 = this; - exports['default'] = EditorHTMLRenderer; -}); -define('content-kit-editor/renderers/instagram', ['exports'], function (exports) { - 'use strict'; + var _ref42 = _slicedToArray(_ref4, 3); - function InstagramRenderer() {} - InstagramRenderer.prototype.render = function (model) { - return ''; - }; + var markerTypeIndexes = _ref42[0]; + var closeCount = _ref42[1]; + var value = _ref42[2]; - exports['default'] = InstagramRenderer; -}); -define('content-kit-editor/renderers/link-image-renderer', ['exports'], function (exports) { - 'use strict'; + var markerTypes = markerTypeIndexes.map(function (index) { + return _this4.markerTypes[index]; + }); + var marker = this.builder.generateMarker(markerTypes, closeCount, value); + section.markers.push(marker); + } + }]); - function LinkImageRenderer() {} - LinkImageRenderer.prototype.render = function (model) { - return ''; - }; + return MobiledocParser; + })(); - exports['default'] = LinkImageRenderer; + exports['default'] = MobiledocParser; }); -define('content-kit-editor/renderers/new-dom-renderer', ['exports'], function (exports) { +define('content-kit-editor/renderers/editor-dom', ['exports'], function (exports) { 'use strict'; function createElementFromMarkerType(doc, markerType) { @@ -2726,7 +1547,7 @@ define('content-kit-editor/renderers/new-dom-renderer', ['exports'], function (e exports['default'] = NewDOMRenderer; }); -define('content-kit-editor/renderers/new-serializer', ['exports', 'content-kit-editor/utils/compiler'], function (exports, _contentKitEditorUtilsCompiler) { +define('content-kit-editor/renderers/mobiledoc', ['exports', 'content-kit-editor/utils/compiler'], function (exports, _contentKitEditorUtilsCompiler) { 'use strict'; var visitor = { @@ -2781,7 +1602,7 @@ define('content-kit-editor/renderers/new-serializer', ['exports', 'content-kit-e }; exports['default'] = { - serialize: function serialize(post) { + render: function render(post) { var opcodes = []; (0, _contentKitEditorUtilsCompiler.visit)(visitor, post, opcodes); var compiler = Object.create(postOpcodeCompiler); @@ -2790,37 +1611,10 @@ define('content-kit-editor/renderers/new-serializer', ['exports', 'content-kit-e } }; }); -define('content-kit-editor/renderers/twitter', ['exports'], function (exports) { - 'use strict'; - - function TwitterRenderer() {} - TwitterRenderer.prototype.render = function (model) { - return ''; - }; - - exports['default'] = TwitterRenderer; -}); -define('content-kit-editor/renderers/youtube', ['exports'], function (exports) { +define('content-kit-editor/runtime/renderers/mobiledoc-dom', ['exports', 'mobiledoc-dom-renderer'], function (exports, _mobiledocDomRenderer) { 'use strict'; - var RegExVideoId = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/; - - function getVideoIdFromUrl(url) { - var match = url && url.match(RegExVideoId); - if (match && match[1].length === 11) { - return match[1]; - } - return null; - } - - function YouTubeRenderer() {} - YouTubeRenderer.prototype.render = function (model) { - var videoId = getVideoIdFromUrl(model.attributes.url); - var embedUrl = 'http://www.youtube.com/embed/' + videoId + '?controls=2&showinfo=0&color=white&theme=light'; - return ''; - }; - - exports['default'] = YouTubeRenderer; + exports['default'] = _mobiledocDomRenderer['default']; }); define('content-kit-editor/utils/compat', ['exports', 'content-kit-editor/utils/doc', 'content-kit-editor/utils/win'], function (exports, _contentKitEditorUtilsDoc, _contentKitEditorUtilsWin) { 'use strict'; @@ -2866,15 +1660,6 @@ define("content-kit-editor/utils/compiler", ["exports"], function (exports) { } } }); -define("content-kit-editor/utils/doc", ["exports"], function (exports) { - // FIXME in theory, we might want to make this safe for node usage and - // return a jsdom? - // In practice we probably don't need this for the editor since it won't ever - // execute in a solely server-side environment - "use strict"; - - exports["default"] = document; -}); define("content-kit-editor/utils/dom-utils", ["exports"], function (exports) { "use strict"; @@ -2918,27 +1703,27 @@ define('content-kit-editor/utils/element-map', ['exports'], function (exports) { _createClass(ElementMap, [{ key: 'set', value: function set(key, value) { - var uuid = key.dataset.uuid; + var uuid = key._uuid; if (!uuid) { - key.dataset.uuid = uuid = uuidGenerator++; + key._uuid = uuid = '' + uuidGenerator++; } this._map[uuid] = value; } }, { key: 'get', value: function get(key) { - if (key.dataset && key.dataset.uuid) { - return this._map[key.dataset.uuid]; + if (key._uuid) { + return this._map[key._uuid]; } return null; } }, { key: 'remove', value: function remove(key) { - if (!key.dataset.uuid) { + if (!key._uuid) { throw new Error('tried to fetch a value for an element not seen before'); } - delete this._map[key.dataset.uuid]; + delete this._map[key._uuid]; } }]); @@ -2947,11 +1732,11 @@ define('content-kit-editor/utils/element-map', ['exports'], function (exports) { exports['default'] = ElementMap; }); -define('content-kit-editor/utils/element-utils', ['exports', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorUtilsCompat) { +define('content-kit-editor/utils/element-utils', ['exports'], function (exports) { 'use strict'; function createDiv(className) { - var div = _contentKitEditorUtilsCompat.doc.createElement('div'); + var div = document.createElement('div'); if (className) { div.className = className; } @@ -3001,9 +1786,9 @@ define('content-kit-editor/utils/element-utils', ['exports', 'content-kit-editor } function getElementRelativeOffset(element) { - var offset = { left: 0, top: -_contentKitEditorUtilsCompat.win.pageYOffset }; + var offset = { left: 0, top: -window.pageYOffset }; var offsetParent = element.offsetParent; - var offsetParentPosition = _contentKitEditorUtilsCompat.win.getComputedStyle(offsetParent).position; + var offsetParentPosition = window.getComputedStyle(offsetParent).position; var offsetParentRect; if (offsetParentPosition === 'relative') { @@ -3015,7 +1800,7 @@ define('content-kit-editor/utils/element-utils', ['exports', 'content-kit-editor } function getElementComputedStyleNumericProp(element, prop) { - return parseFloat(_contentKitEditorUtilsCompat.win.getComputedStyle(element)[prop]); + return parseFloat(window.getComputedStyle(element)[prop]); } function positionElementToRect(element, rect, topOffset, leftOffset) { @@ -3115,8 +1900,7 @@ define("content-kit-editor/utils/event-emitter", ["exports"], function (exports) exports["default"] = EventEmitter; }); -define('content-kit-editor/utils/http-utils', ['exports', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorUtilsCompat) { - /* global JSON */ +define('content-kit-editor/utils/http-utils', ['exports'], function (exports) { 'use strict'; function createXHR(options) { @@ -3189,7 +1973,7 @@ define('content-kit-editor/utils/http-utils', ['exports', 'content-kit-editor/ut var file = options.file || fileInput && fileInput.files && fileInput.files[0]; var callback = options.complete; var maxFileSize = this.maxFileSize; - if (!file || !(file instanceof _contentKitEditorUtilsCompat.win.File)) { + if (!file || !(file instanceof window.File)) { return; } @@ -3257,11 +2041,74 @@ define("content-kit-editor/utils/keycodes", ["exports"], function (exports) { M: 77 }; }); -define('content-kit-editor/utils/selection-utils', ['exports', 'content-kit-editor/utils/element-utils', 'content-kit-compiler', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorUtilsElementUtils, _contentKitCompiler, _contentKitEditorUtilsCompat) { +define('content-kit-editor/utils/post-builder', ['exports', 'content-kit-editor/models/post'], function (exports, _contentKitEditorModelsPost) { + 'use strict'; + + exports.generateBuilder = generateBuilder; + + var builder = { + generatePost: function generatePost() { + return new _contentKitEditorModelsPost['default'](); + }, + generateSection: function generateSection(tagName, attributes, isGenerated) { + var section = { + type: 'markupSection', + tagName: tagName, + markers: [] + }; + if (attributes && attributes.length) { + section.attributes = attributes; + } + if (isGenerated) { + section.isGenerated = !!isGenerated; + } + return section; + }, + // open: Array + // close: Integer + // value: String + generateMarker: function generateMarker(open, close, value) { + return { + type: 'marker', + open: open, + close: close, + value: value + }; + }, + generateMarkerType: function generateMarkerType(tagName, attributes) { + if (attributes) { + // FIXME: This could also be cached + return { + type: 'markerType', + tagName: tagName, + attributes: attributes + }; + } + var markerType = this._markerTypeCache[tagName]; + if (!markerType) { + this._markerTypeCache[tagName] = markerType = { + type: 'markerType', + tagName: tagName + }; + } + return markerType; + } + }; + + function reset(builder) { + builder._markerTypeCache = {}; + } + + function generateBuilder() { + reset(builder); + return builder; + } +}); +define('content-kit-editor/utils/selection-utils', ['exports', 'content-kit-editor/utils/element-utils'], function (exports, _contentKitEditorUtilsElementUtils) { 'use strict'; // TODO: remove, pass in Editor's current block set - var RootTags = [_contentKitCompiler.Type.PARAGRAPH.tag, _contentKitCompiler.Type.HEADING.tag, _contentKitCompiler.Type.SUBHEADING.tag, _contentKitCompiler.Type.QUOTE.tag, _contentKitCompiler.Type.LIST.tag, _contentKitCompiler.Type.ORDERED_LIST.tag]; + var RootTags = ['p', 'h2', 'h3', 'blockquote', 'ul', 'ol']; var SelectionDirection = { LEFT_TO_RIGHT: 1, @@ -3281,13 +2128,13 @@ define('content-kit-editor/utils/selection-utils', ['exports', 'content-kit-edit } function getSelectionElement(selection) { - selection = selection || _contentKitEditorUtilsCompat.win.getSelection(); + selection = selection || window.getSelection(); var node = getDirectionOfSelection(selection) === SelectionDirection.LEFT_TO_RIGHT ? selection.anchorNode : selection.focusNode; return node && (node.nodeType === 3 ? node.parentNode : node); } function getSelectionBlockElement(selection) { - selection = selection || _contentKitEditorUtilsCompat.win.getSelection(); + selection = selection || window.getSelection(); var element = getSelectionElement(); var tag = element && element.tagName.toLowerCase(); while (tag && RootTags.indexOf(tag) === -1) { @@ -3336,14 +2183,14 @@ define('content-kit-editor/utils/selection-utils', ['exports', 'content-kit-edit } function restoreRange(range) { - var selection = _contentKitEditorUtilsCompat.win.getSelection(); + var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); } function selectNode(node) { - var range = _contentKitEditorUtilsCompat.doc.createRange(); - var selection = _contentKitEditorUtilsCompat.win.getSelection(); + var range = document.createRange(); + var selection = window.getSelection(); range.setStart(node, 0); range.setEnd(node, node.length); selection.removeAllRanges(); @@ -3351,8 +2198,8 @@ define('content-kit-editor/utils/selection-utils', ['exports', 'content-kit-edit } function setCursorIndexInElement(element, index) { - var range = _contentKitEditorUtilsCompat.doc.createRange(); - var selection = _contentKitEditorUtilsCompat.win.getSelection(); + var range = document.createRange(); + var selection = window.getSelection(); range.setStart(element, index); range.collapse(true); selection.removeAllRanges(); @@ -3366,7 +2213,7 @@ define('content-kit-editor/utils/selection-utils', ['exports', 'content-kit-edit function getCursorOffsetInElement(element) { // http://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container/4812022#4812022 var caretOffset = 0; - var selection = _contentKitEditorUtilsCompat.win.getSelection(); + var selection = window.getSelection(); if (selection.rangeCount > 0) { var range = selection.getRangeAt(0); var preCaretRange = range.cloneRange(); @@ -3391,20 +2238,7 @@ define('content-kit-editor/utils/selection-utils', ['exports', 'content-kit-edit exports.setCursorIndexInElement = setCursorIndexInElement; exports.getCursorOffsetInElement = getCursorOffsetInElement; }); -define('content-kit-editor/utils/win', ['exports', 'content-kit-compiler'], function (exports, _contentKitCompiler) { - 'use strict'; - - var win; - if (typeof window !== 'undefined') { - win = window; - } else { - // jsdom provides a defaultView - win = _contentKitCompiler.doc.defaultView; - } - - exports['default'] = win; -}); -define('content-kit-editor/views/embed-intent', ['exports', 'content-kit-editor/views/view', 'content-kit-editor/views/toolbar', 'content-kit-utils', 'content-kit-editor/utils/selection-utils', 'content-kit-editor/utils/element-utils', 'content-kit-editor/utils/keycodes', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorViewsView, _contentKitEditorViewsToolbar, _contentKitUtils, _contentKitEditorUtilsSelectionUtils, _contentKitEditorUtilsElementUtils, _contentKitEditorUtilsKeycodes, _contentKitEditorUtilsCompat) { +define('content-kit-editor/views/embed-intent', ['exports', 'content-kit-editor/views/view', 'content-kit-editor/views/toolbar', 'content-kit-utils', 'content-kit-editor/utils/selection-utils', 'content-kit-editor/utils/element-utils', 'content-kit-editor/utils/keycodes'], function (exports, _contentKitEditorViewsView, _contentKitEditorViewsToolbar, _contentKitUtils, _contentKitEditorUtilsSelectionUtils, _contentKitEditorUtilsElementUtils, _contentKitEditorUtilsKeycodes) { 'use strict'; var LayoutStyle = { @@ -3428,7 +2262,7 @@ define('content-kit-editor/views/embed-intent', ['exports', 'content-kit-editor/ embedIntent.isActive = false; embedIntent.editorContext = options.editorContext; embedIntent.loadingIndicator = (0, _contentKitEditorUtilsElementUtils.createDiv)('ck-embed-loading'); - embedIntent.button = _contentKitEditorUtilsCompat.doc.createElement('button'); + embedIntent.button = document.createElement('button'); embedIntent.button.className = 'ck-embed-intent-btn'; embedIntent.button.title = 'Insert image or embed...'; embedIntent.element.appendChild(embedIntent.button); @@ -3459,19 +2293,19 @@ define('content-kit-editor/views/embed-intent', ['exports', 'content-kit-editor/ } rootElement.addEventListener('keyup', embedIntentHandler); - _contentKitEditorUtilsCompat.doc.addEventListener('mouseup', function () { + document.addEventListener('mouseup', function () { setTimeout(function () { embedIntentHandler(); }); }); - _contentKitEditorUtilsCompat.doc.addEventListener('keyup', function (e) { + document.addEventListener('keyup', function (e) { if (e.keyCode === _contentKitEditorUtilsKeycodes['default'].ESC) { embedIntent.hide(); } }); - _contentKitEditorUtilsCompat.win.addEventListener('resize', function () { + window.addEventListener('resize', function () { if (embedIntent.isShowing) { embedIntent.reposition(); } @@ -3561,10 +2395,10 @@ define('content-kit-editor/views/message', ['exports', 'content-kit-editor/views exports['default'] = Message; }); -define('content-kit-editor/views/prompt', ['exports', 'content-kit-editor/views/view', 'content-kit-utils', 'content-kit-editor/utils/selection-utils', 'content-kit-editor/utils/element-utils', 'content-kit-editor/utils/keycodes', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorViewsView, _contentKitUtils, _contentKitEditorUtilsSelectionUtils, _contentKitEditorUtilsElementUtils, _contentKitEditorUtilsKeycodes, _contentKitEditorUtilsCompat) { +define('content-kit-editor/views/prompt', ['exports', 'content-kit-editor/views/view', 'content-kit-utils', 'content-kit-editor/utils/selection-utils', 'content-kit-editor/utils/element-utils', 'content-kit-editor/utils/keycodes'], function (exports, _contentKitEditorViewsView, _contentKitUtils, _contentKitEditorUtilsSelectionUtils, _contentKitEditorUtilsElementUtils, _contentKitEditorUtilsKeycodes) { 'use strict'; - var container = _contentKitEditorUtilsCompat.doc.body; + var container = document.body; var hiliter = (0, _contentKitEditorUtilsElementUtils.createDiv)('ck-editor-hilite'); function positionHiliteRange(range) { @@ -3596,7 +2430,7 @@ define('content-kit-editor/views/prompt', ['exports', 'content-kit-editor/views/ } }); - _contentKitEditorUtilsCompat.win.addEventListener('resize', function () { + window.addEventListener('resize', function () { var activeHilite = hiliter.parentNode; var range = prompt.range; if (activeHilite && range) { @@ -3609,7 +2443,7 @@ define('content-kit-editor/views/prompt', ['exports', 'content-kit-editor/views/ Prompt.prototype.show = function (callback) { var prompt = this; var element = prompt.element; - var selection = _contentKitEditorUtilsCompat.win.getSelection(); + var selection = window.getSelection(); var range = selection && selection.rangeCount && selection.getRangeAt(0); element.value = null; prompt.range = range || null; @@ -3633,7 +2467,7 @@ define('content-kit-editor/views/prompt', ['exports', 'content-kit-editor/views/ exports['default'] = Prompt; }); -define('content-kit-editor/views/text-format-toolbar', ['exports', 'content-kit-editor/views/toolbar', 'content-kit-utils', 'content-kit-editor/utils/selection-utils', 'content-kit-editor/utils/keycodes', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorViewsToolbar, _contentKitUtils, _contentKitEditorUtilsSelectionUtils, _contentKitEditorUtilsKeycodes, _contentKitEditorUtilsCompat) { +define('content-kit-editor/views/text-format-toolbar', ['exports', 'content-kit-editor/views/toolbar', 'content-kit-utils', 'content-kit-editor/utils/selection-utils', 'content-kit-editor/utils/keycodes'], function (exports, _contentKitEditorViewsToolbar, _contentKitUtils, _contentKitEditorUtilsSelectionUtils, _contentKitEditorUtilsKeycodes) { 'use strict'; function selectionIsEditableByToolbar(selection, toolbar) { @@ -3641,7 +2475,7 @@ define('content-kit-editor/views/text-format-toolbar', ['exports', 'content-kit- } function handleTextSelection(toolbar) { - var selection = _contentKitEditorUtilsCompat.win.getSelection(); + var selection = window.getSelection(); if (toolbar.sticky) { toolbar.updateForSelection(selectionIsEditableByToolbar(selection, toolbar) ? selection : null); } else { @@ -3662,13 +2496,13 @@ define('content-kit-editor/views/text-format-toolbar', ['exports', 'content-kit- handleTextSelection(toolbar); }); - _contentKitEditorUtilsCompat.doc.addEventListener('mouseup', function () { + document.addEventListener('mouseup', function () { setTimeout(function () { handleTextSelection(toolbar); }); }); - _contentKitEditorUtilsCompat.doc.addEventListener('keyup', function (e) { + document.addEventListener('keyup', function (e) { var key = e.keyCode; if (key === 116) { //F5 @@ -3679,10 +2513,10 @@ define('content-kit-editor/views/text-format-toolbar', ['exports', 'content-kit- } }); - _contentKitEditorUtilsCompat.win.addEventListener('resize', function () { + window.addEventListener('resize', function () { if (!toolbar.sticky && toolbar.isShowing) { var activePromptRange = toolbar.activePrompt && toolbar.activePrompt.range; - toolbar.positionToContent(activePromptRange ? activePromptRange : _contentKitEditorUtilsCompat.win.getSelection().getRangeAt(0)); + toolbar.positionToContent(activePromptRange ? activePromptRange : window.getSelection().getRangeAt(0)); } }); } @@ -3690,7 +2524,7 @@ define('content-kit-editor/views/text-format-toolbar', ['exports', 'content-kit- exports['default'] = TextFormatToolbar; }); -define('content-kit-editor/views/toolbar-button', ['exports', 'content-kit-compiler'], function (exports, _contentKitCompiler) { +define('content-kit-editor/views/toolbar-button', ['exports'], function (exports) { 'use strict'; var buttonClassName = 'ck-toolbar-btn'; @@ -3700,7 +2534,7 @@ define('content-kit-editor/views/toolbar-button', ['exports', 'content-kit-compi var toolbar = options.toolbar; var command = options.command; var prompt = command.prompt; - var element = _contentKitCompiler.doc.createElement('button'); + var element = document.createElement('button'); button.element = element; button.command = command; @@ -3739,7 +2573,7 @@ define('content-kit-editor/views/toolbar-button', ['exports', 'content-kit-compi exports['default'] = ToolbarButton; }); -define('content-kit-editor/views/toolbar', ['exports', 'content-kit-editor/views/view', 'content-kit-editor/views/toolbar-button', 'content-kit-utils', 'content-kit-editor/utils/selection-utils', 'content-kit-editor/utils/element-utils', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorViewsView, _contentKitEditorViewsToolbarButton, _contentKitUtils, _contentKitEditorUtilsSelectionUtils, _contentKitEditorUtilsElementUtils, _contentKitEditorUtilsCompat) { +define('content-kit-editor/views/toolbar', ['exports', 'content-kit-editor/views/view', 'content-kit-editor/views/toolbar-button', 'content-kit-utils', 'content-kit-editor/utils/selection-utils', 'content-kit-editor/utils/element-utils'], function (exports, _contentKitEditorViewsView, _contentKitEditorViewsToolbarButton, _contentKitUtils, _contentKitEditorUtilsSelectionUtils, _contentKitEditorUtilsElementUtils) { 'use strict'; var ToolbarDirection = { @@ -3796,7 +2630,7 @@ define('content-kit-editor/views/toolbar', ['exports', 'content-kit-editor/views } // Closes prompt if displayed when changing selection - _contentKitEditorUtilsCompat.doc.addEventListener('mouseup', function () { + document.addEventListener('mouseup', function () { toolbar.dismissPrompt(); }); } @@ -3842,7 +2676,7 @@ define('content-kit-editor/views/toolbar', ['exports', 'content-kit-editor/views Toolbar.prototype.updateForSelection = function (selection) { var toolbar = this; - selection = selection || _contentKitEditorUtilsCompat.win.getSelection(); + selection = selection || window.getSelection(); if (toolbar.sticky) { updateButtonsForSelection(toolbar.buttons, selection); } else if (!selection.isCollapsed) { @@ -3862,7 +2696,7 @@ define('content-kit-editor/views/toolbar', ['exports', 'content-kit-editor/views positioningMethod = _contentKitEditorUtilsElementUtils.positionElementCenteredAbove; } position = positioningMethod(this.element, content); - sideEdgeOffset = Math.min(Math.max(10, position.left), _contentKitEditorUtilsCompat.doc.body.clientWidth - this.element.offsetWidth - 10); + sideEdgeOffset = Math.min(Math.max(10, position.left), document.body.clientWidth - this.element.offsetWidth - 10); this.contentElement.style.transform = 'translateX(' + (sideEdgeOffset - position.left) + 'px)'; }; @@ -3940,7 +2774,7 @@ define('content-kit-editor/views/tooltip', ['exports', 'content-kit-editor/views exports['default'] = Tooltip; }); -define('content-kit-editor/views/view', ['exports', 'content-kit-editor/utils/compat'], function (exports, _contentKitEditorUtilsCompat) { +define('content-kit-editor/views/view', ['exports'], function (exports) { 'use strict'; function renderClasses(view) { @@ -3956,8 +2790,8 @@ define('content-kit-editor/views/view', ['exports', 'content-kit-editor/utils/co options = options || {}; this.tagName = options.tagName || 'div'; this.classNames = options.classNames || []; - this.element = _contentKitEditorUtilsCompat.doc.createElement(this.tagName); - this.container = options.container || _contentKitEditorUtilsCompat.doc.body; + this.element = document.createElement(this.tagName); + this.container = options.container || document.body; this.isShowing = false; renderClasses(this); } @@ -4204,5 +3038,159 @@ define('content-kit-utils/string-utils', ['exports'], function (exports) { exports.sanitizeWhitespace = sanitizeWhitespace; exports.injectIntoString = injectIntoString; }); +define('mobiledoc-dom-renderer/dom-renderer', ['exports'], function (exports) { + /** + * runtime DOM renderer + * renders a mobiledoc to DOM + * + * input: mobiledoc + * output: DOM + */ + + 'use strict'; + + var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); + + var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + var utils = { + createElement: function createElement(tagName) { + return document.createElement(tagName); + }, + appendChild: function appendChild(target, child) { + target.appendChild(child); + }, + createTextNode: function createTextNode(text) { + return document.createTextNode(text); + } + }; + + function createElementFromMarkerType() { + var _ref = arguments[0] === undefined ? ['', []] : arguments[0]; + + var _ref2 = _slicedToArray(_ref, 2); + + var tagName = _ref2[0]; + var attributes = _ref2[1]; + + var element = utils.createElement(tagName); + attributes = attributes || []; + + for (var i = 0, l = attributes.length; i < l; i = i + 2) { + var propName = attributes[i], + propValue = attributes[i + 1]; + element.setAttribute(propName, propValue); + } + return element; + } + + var DOMRenderer = (function () { + function DOMRenderer() { + _classCallCheck(this, DOMRenderer); + } + + _createClass(DOMRenderer, [{ + key: 'render', + + /** + * @param mobiledoc + * @param rootElement optional, defaults to an empty div + * @return DOMNode + */ + value: function render(mobiledoc) { + var _this = this; + + var rootElement = arguments[1] === undefined ? utils.createElement('div') : arguments[1]; + + var _mobiledoc = _slicedToArray(mobiledoc, 2); + + var markerTypes = _mobiledoc[0]; + var sections = _mobiledoc[1]; + + this.root = rootElement; + this.markerTypes = markerTypes; + + sections.forEach(function (section) { + return _this.renderSection(section); + }); + + return this.root; + } + }, { + key: 'renderSection', + value: function renderSection(section) { + var _section = _slicedToArray(section, 1); + + var type = _section[0]; + + switch (type) { + case 1: + var rendered = this.renderParagraphSection(section); + utils.appendChild(this.root, rendered); + break; + default: + throw new Error('Unimplement renderer for type ' + type); + } + } + }, { + key: 'renderParagraphSection', + value: function renderParagraphSection(_ref3) { + var _ref32 = _slicedToArray(_ref3, 3); + + var type = _ref32[0]; + var tagName = _ref32[1]; + var markers = _ref32[2]; + + var element = utils.createElement(tagName); + var elements = [element]; + var currentElement = element; + + for (var i = 0, l = markers.length; i < l; i++) { + var marker = markers[i]; + + var _marker = _slicedToArray(marker, 3); + + var openTypes = _marker[0]; + var closeTypes = _marker[1]; + var text = _marker[2]; + + for (var j = 0, m = openTypes.length; j < m; j++) { + var markerType = this.markerTypes[openTypes[j]]; + var openedElement = createElementFromMarkerType(markerType); + utils.appendChild(currentElement, openedElement); + elements.push(openedElement); + currentElement = openedElement; + } + + utils.appendChild(currentElement, utils.createTextNode(text)); + + for (var j = 0, m = closeTypes; j < m; j++) { + elements.pop(); + currentElement = elements[elements.length - 1]; + } + } + + return element; + } + }]); + + return DOMRenderer; + })(); + + exports['default'] = DOMRenderer; +}); +define('mobiledoc-dom-renderer', ['exports', 'mobiledoc-dom-renderer/dom-renderer'], function (exports, _mobiledocDomRendererDomRenderer) { + 'use strict'; + + exports.registerGlobal = registerGlobal; + + function registerGlobal(window) { + window.MobiledocDOMRenderer = _mobiledocDomRendererDomRenderer['default']; + } + + exports['default'] = _mobiledocDomRendererDomRenderer['default']; +}); require("content-kit-editor")["registerGlobal"](window, document); })(); \ No newline at end of file From 1926c95e73e69e0d00caa44994aff64aeae97a40 Mon Sep 17 00:00:00 2001 From: Matthew Beale Date: Thu, 9 Jul 2015 14:59:56 -0400 Subject: [PATCH 40/77] Only reference runtime in demo --- Brocfile.js | 3 +-- broccoli/demo.js | 33 ++++++++++++++++------- demo/demo.js | 2 +- demo/index.html | 1 + package.json | 2 +- src/js/index.js | 7 +---- src/js/runtime/renderers/mobiledoc-dom.js | 3 --- 7 files changed, 29 insertions(+), 22 deletions(-) delete mode 100644 src/js/runtime/renderers/mobiledoc-dom.js diff --git a/Brocfile.js b/Brocfile.js index 69ddef2f0..9b60bb4e6 100644 --- a/Brocfile.js +++ b/Brocfile.js @@ -8,8 +8,7 @@ var demo = require('./broccoli/demo'); var jquery = require('./broccoli/jquery'); var vendoredModules = [ - {name: 'content-kit-utils', options: {libDirName: 'src'}}, - {name: 'mobiledoc-dom-renderer'} + {name: 'content-kit-utils', options: {libDirName: 'src'}} ]; var packageName = require('./package.json').name; diff --git a/broccoli/demo.js b/broccoli/demo.js index 4c480dfdf..b925ac676 100644 --- a/broccoli/demo.js +++ b/broccoli/demo.js @@ -2,16 +2,31 @@ 'use strict'; var funnel = require('broccoli-funnel'); +var mergeTrees = require('broccoli-merge-trees'); +var path = require('path'); module.exports = function() { var demoDir = 'demo'; - return funnel(demoDir, { - include: [ - '**/*.css', - '**/*.js', - 'favicon.ico', - '**/*.html' - ], - destDir: '/demo' - }); + var rendererDir = path.join( + path.dirname( + require.resolve('mobiledoc-dom-renderer') + ) + ); + return mergeTrees([ + funnel(demoDir, { + include: [ + '**/*.css', + '**/*.js', + 'favicon.ico', + '**/*.html' + ], + destDir: '/demo' + }), + funnel(rendererDir, { + include: [ + 'mobiledoc-dom-renderer.js' + ], + destDir: '/demo' + }) + ]); }; diff --git a/demo/demo.js b/demo/demo.js index 0571d2408..811355bf7 100644 --- a/demo/demo.js +++ b/demo/demo.js @@ -11,7 +11,7 @@ var ContentKitDemo = exports.ContentKitDemo = { var json = editor.serialize(); codePaneJSON.innerHTML = this.syntaxHighlight(json); - var renderer = new ContentKit.Runtime.DOMRenderer(); + var renderer = new MobiledocDOMRenderer(); var rendered = renderer.render(json); $('#rendered-mobiledoc').empty(); diff --git a/demo/index.html b/demo/index.html index a895c7415..9569c899a 100644 --- a/demo/index.html +++ b/demo/index.html @@ -75,6 +75,7 @@

rendered mobiledoc

+ diff --git a/package.json b/package.json index afedb1965..89b50c1d8 100644 --- a/package.json +++ b/package.json @@ -57,7 +57,7 @@ "gulp-qunit": "^1.2.1", "gulp-uglify": "^1.1.0", "jquery": "^2.1.4", - "mobiledoc-dom-renderer": "^0.1.2", + "mobiledoc-dom-renderer": "^0.1.3", "testem": "^0.8.4" } } diff --git a/src/js/index.js b/src/js/index.js index a36b1bdcc..4211501ce 100644 --- a/src/js/index.js +++ b/src/js/index.js @@ -1,12 +1,7 @@ import Editor from './editor/editor'; -import DOMRenderer from './runtime/renderers/mobiledoc-dom'; - -const Runtime = { - DOMRenderer -} const ContentKit = { - Editor, Runtime + Editor }; export function registerGlobal(global) { diff --git a/src/js/runtime/renderers/mobiledoc-dom.js b/src/js/runtime/renderers/mobiledoc-dom.js deleted file mode 100644 index 0733911fc..000000000 --- a/src/js/runtime/renderers/mobiledoc-dom.js +++ /dev/null @@ -1,3 +0,0 @@ -import DOMRenderer from 'mobiledoc-dom-renderer'; - -export default DOMRenderer; From d82b6259a33786cab65af060cabb6d37767f6dec Mon Sep 17 00:00:00 2001 From: Matthew Beale Date: Thu, 9 Jul 2015 16:08:47 -0400 Subject: [PATCH 41/77] Add mobiledoc renderer test, fix tests --- tests/acceptance/basic-editor-test.js | 6 ++-- tests/index.html | 1 + tests/unit/{ => editor}/editor-test.js | 34 ++------------------- tests/unit/renderers/mobiledoc-test.js | 41 ++++++++++++++++++++++++++ 4 files changed, 48 insertions(+), 34 deletions(-) rename tests/unit/{ => editor}/editor-test.js (64%) create mode 100644 tests/unit/renderers/mobiledoc-test.js diff --git a/tests/acceptance/basic-editor-test.js b/tests/acceptance/basic-editor-test.js index 5bcb1e401..f66732273 100644 --- a/tests/acceptance/basic-editor-test.js +++ b/tests/acceptance/basic-editor-test.js @@ -7,7 +7,7 @@ const { test, module } = QUnit; let fixture, editor, editorElement; -module('acceptance: basic editor', { +module('Acceptance: basic editor', { beforeEach() { fixture = document.getElementById('qunit-fixture'); editorElement = document.createElement('div'); @@ -21,7 +21,7 @@ module('acceptance: basic editor', { test('sets element as contenteditable', (assert) => { let innerHTML = `

Hello

`; editorElement.innerHTML = innerHTML; - editor = new Editor('#editor'); + editor = new Editor(document.getElementById('editor')); assert.equal(editorElement.getAttribute('contenteditable'), 'true', @@ -33,7 +33,7 @@ test('sets element as contenteditable', (assert) => { test('editing element changes editor post model', (assert) => { let innerHTML = `

Hello

`; editorElement.innerHTML = innerHTML; - editor = new Editor('#editor'); + editor = new Editor(document.getElementById('editor')); let p = editorElement.querySelector('p'); let textElement = p.firstChild; diff --git a/tests/index.html b/tests/index.html index 691eb1da5..f3801d952 100644 --- a/tests/index.html +++ b/tests/index.html @@ -18,6 +18,7 @@ + diff --git a/package.json b/package.json index 89b50c1d8..64e2f6e33 100644 --- a/package.json +++ b/package.json @@ -58,6 +58,7 @@ "gulp-uglify": "^1.1.0", "jquery": "^2.1.4", "mobiledoc-dom-renderer": "^0.1.3", + "mobiledoc-html-renderer": "^0.1.0", "testem": "^0.8.4" } } From 9512f1d4905f6bcc5b2ec7e049db3cddc0482a65 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Thu, 9 Jul 2015 16:38:52 -0400 Subject: [PATCH 44/77] built website from 558499e7b0c5fbc76f554b3265f5a7dfb186d161 --- website/demo/demo.css | 2 +- website/demo/demo.js | 25 +- website/demo/index.html | 16 +- website/demo/mobiledoc-dom-renderer.js | 351 +++++++++++++++++++ website/demo/mobiledoc-html-renderer.js | 444 ++++++++++++++++++++++++ website/global/content-kit-editor.js | 169 +-------- 6 files changed, 830 insertions(+), 177 deletions(-) create mode 100644 website/demo/mobiledoc-dom-renderer.js create mode 100644 website/demo/mobiledoc-html-renderer.js diff --git a/website/demo/demo.css b/website/demo/demo.css index f29d99e74..8a448f606 100644 --- a/website/demo/demo.css +++ b/website/demo/demo.css @@ -23,7 +23,7 @@ body { } .pane { - max-width: 25%; + max-width: 20%; padding: 0 1em; } diff --git a/website/demo/demo.js b/website/demo/demo.js index 0571d2408..98dede0eb 100644 --- a/website/demo/demo.js +++ b/website/demo/demo.js @@ -3,19 +3,28 @@ 'use strict'; var ContentKit = exports.ContentKit, - $ = exports.$; + $ = exports.$, + MobiledocHTMLRenderer = exports.MobiledocHTMLRenderer, + MobiledocDOMRenderer = exports.MobiledocDOMRenderer; var ContentKitDemo = exports.ContentKitDemo = { syncCodePane: function(editor) { var codePaneJSON = document.getElementById('serialized-mobiledoc'); - var json = editor.serialize(); - codePaneJSON.innerHTML = this.syntaxHighlight(json); + var mobiledoc = editor.serialize(); + codePaneJSON.innerHTML = this.syntaxHighlight(mobiledoc); - var renderer = new ContentKit.Runtime.DOMRenderer(); - var rendered = renderer.render(json); + var renderer = new MobiledocDOMRenderer(); + var rendered = renderer.render(mobiledoc); $('#rendered-mobiledoc').empty(); $('#rendered-mobiledoc')[0].appendChild(rendered); + + var htmlRenderer = new MobiledocHTMLRenderer(); + var html = htmlRenderer.render(mobiledoc); + + html = html.replace(/&/g,'&').replace(//g,'>'); + + $('#rendered-mobiledoc-html').html(html); }, syntaxHighlight: function(json) { @@ -65,7 +74,7 @@ function readMobiledoc(string) { function isValidJSON(string) { try { - JSON.parse(string); + window.JSON.parse(string); return true; } catch(e) { return false; @@ -144,7 +153,7 @@ $(function() { var mobiledoc = sampleMobiledocs.simpleMobiledoc; var textarea = $('#mobiledoc-to-load textarea'); - textarea.val(JSON.stringify(mobiledoc, false, 2)); + textarea.val(window.JSON.stringify(mobiledoc, false, 2)); textarea.on('input', function() { attemptEditorReboot(editor, textarea); @@ -153,7 +162,7 @@ $(function() { $('#select-mobiledoc').on('change', function() { var mobiledocName = $(this).val(); var mobiledoc = sampleMobiledocs[mobiledocName]; - textarea.val(JSON.stringify(mobiledoc, false, 2)); + textarea.val(window.JSON.stringify(mobiledoc, false, 2)); textarea.trigger('input'); }); diff --git a/website/demo/index.html b/website/demo/index.html index a895c7415..5c1c38941 100644 --- a/website/demo/index.html +++ b/website/demo/index.html @@ -61,20 +61,32 @@

serialized mobiledoc

-

rendered mobiledoc

+

rendered mobiledoc (dom)

This is the output of using the runtime (client-side) - mobiledoc-dom-renderer + mobiledoc-dom-renderer on the serialized mobiledoc.

+
+

rendered mobiledoc (html)

+

+ This is the output of using the server-side + mobiledoc-html-renderer + on the serialized mobiledoc. +

+
+
+
+ + diff --git a/website/demo/mobiledoc-dom-renderer.js b/website/demo/mobiledoc-dom-renderer.js new file mode 100644 index 000000000..8a94b09c1 --- /dev/null +++ b/website/demo/mobiledoc-dom-renderer.js @@ -0,0 +1,351 @@ +;(function() { + +var define, requireModule, require, requirejs; + +(function() { + + var _isArray; + if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === "[object Array]"; + }; + } else { + _isArray = Array.isArray; + } + + var registry = {}, seen = {}; + var FAILED = false; + + var uuid = 0; + + function tryFinally(tryable, finalizer) { + try { + return tryable(); + } finally { + finalizer(); + } + } + + function unsupportedModule(length) { + throw new Error("an unsupported module was defined, expected `define(name, deps, module)` instead got: `" + length + "` arguments to define`"); + } + + var defaultDeps = ['require', 'exports', 'module']; + + function Module(name, deps, callback, exports) { + this.id = uuid++; + this.name = name; + this.deps = !deps.length && callback.length ? defaultDeps : deps; + this.exports = exports || { }; + this.callback = callback; + this.state = undefined; + this._require = undefined; + } + + + Module.prototype.makeRequire = function() { + var name = this.name; + + return this._require || (this._require = function(dep) { + return require(resolve(dep, name)); + }); + } + + define = function(name, deps, callback) { + if (arguments.length < 2) { + unsupportedModule(arguments.length); + } + + if (!_isArray(deps)) { + callback = deps; + deps = []; + } + + registry[name] = new Module(name, deps, callback); + }; + + // we don't support all of AMD + // define.amd = {}; + // we will support petals... + define.petal = { }; + + function Alias(path) { + this.name = path; + } + + define.alias = function(path) { + return new Alias(path); + }; + + function reify(mod, name, seen) { + var deps = mod.deps; + var length = deps.length; + var reified = new Array(length); + var dep; + // TODO: new Module + // TODO: seen refactor + var module = { }; + + for (var i = 0, l = length; i < l; i++) { + dep = deps[i]; + if (dep === 'exports') { + module.exports = reified[i] = seen; + } else if (dep === 'require') { + reified[i] = mod.makeRequire(); + } else if (dep === 'module') { + mod.exports = seen; + module = reified[i] = mod; + } else { + reified[i] = requireFrom(resolve(dep, name), name); + } + } + + return { + deps: reified, + module: module + }; + } + + function requireFrom(name, origin) { + var mod = registry[name]; + if (!mod) { + throw new Error('Could not find module `' + name + '` imported from `' + origin + '`'); + } + return require(name); + } + + function missingModule(name) { + throw new Error('Could not find module ' + name); + } + requirejs = require = requireModule = function(name) { + var mod = registry[name]; + + + if (mod && mod.callback instanceof Alias) { + mod = registry[mod.callback.name]; + } + + if (!mod) { missingModule(name); } + + if (mod.state !== FAILED && + seen.hasOwnProperty(name)) { + return seen[name]; + } + + var reified; + var module; + var loaded = false; + + seen[name] = { }; // placeholder for run-time cycles + + tryFinally(function() { + reified = reify(mod, name, seen[name]); + module = mod.callback.apply(this, reified.deps); + loaded = true; + }, function() { + if (!loaded) { + mod.state = FAILED; + } + }); + + var obj; + if (module === undefined && reified.module.exports) { + obj = reified.module.exports; + } else { + obj = seen[name] = module; + } + + if (obj !== null && + (typeof obj === 'object' || typeof obj === 'function') && + obj['default'] === undefined) { + obj['default'] = obj; + } + + return (seen[name] = obj); + }; + + function resolve(child, name) { + if (child.charAt(0) !== '.') { return child; } + + var parts = child.split('/'); + var nameParts = name.split('/'); + var parentBase = nameParts.slice(0, -1); + + for (var i = 0, l = parts.length; i < l; i++) { + var part = parts[i]; + + if (part === '..') { + if (parentBase.length === 0) { + throw new Error('Cannot access parent module of root'); + } + parentBase.pop(); + } else if (part === '.') { continue; } + else { parentBase.push(part); } + } + + return parentBase.join('/'); + } + + requirejs.entries = requirejs._eak_seen = registry; + requirejs.clear = function(){ + requirejs.entries = requirejs._eak_seen = registry = {}; + seen = state = {}; + }; +})(); + +define('mobiledoc-dom-renderer/dom-renderer', ['exports'], function (exports) { + /** + * runtime DOM renderer + * renders a mobiledoc to DOM + * + * input: mobiledoc + * output: DOM + */ + + 'use strict'; + + var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); + + var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + var utils = { + createElement: function createElement(tagName) { + return document.createElement(tagName); + }, + appendChild: function appendChild(target, child) { + target.appendChild(child); + }, + createTextNode: function createTextNode(text) { + return document.createTextNode(text); + } + }; + + function createElementFromMarkerType() { + var _ref = arguments.length <= 0 || arguments[0] === undefined ? ['', []] : arguments[0]; + + var _ref2 = _slicedToArray(_ref, 2); + + var tagName = _ref2[0]; + var attributes = _ref2[1]; + + var element = utils.createElement(tagName); + attributes = attributes || []; + + for (var i = 0, l = attributes.length; i < l; i = i + 2) { + var propName = attributes[i], + propValue = attributes[i + 1]; + element.setAttribute(propName, propValue); + } + return element; + } + + var DOMRenderer = (function () { + function DOMRenderer() { + _classCallCheck(this, DOMRenderer); + } + + _createClass(DOMRenderer, [{ + key: 'render', + + /** + * @param mobiledoc + * @param rootElement optional, defaults to an empty div + * @return DOMNode + */ + value: function render(mobiledoc) { + var _this = this; + + var rootElement = arguments.length <= 1 || arguments[1] === undefined ? utils.createElement('div') : arguments[1]; + + var _mobiledoc = _slicedToArray(mobiledoc, 2); + + var markerTypes = _mobiledoc[0]; + var sections = _mobiledoc[1]; + + this.root = rootElement; + this.markerTypes = markerTypes; + + sections.forEach(function (section) { + return _this.renderSection(section); + }); + + return this.root; + } + }, { + key: 'renderSection', + value: function renderSection(section) { + var _section = _slicedToArray(section, 1); + + var type = _section[0]; + + switch (type) { + case 1: + var rendered = this.renderParagraphSection(section); + utils.appendChild(this.root, rendered); + break; + default: + throw new Error('Unimplement renderer for type ' + type); + } + } + }, { + key: 'renderParagraphSection', + value: function renderParagraphSection(_ref3) { + var _ref32 = _slicedToArray(_ref3, 3); + + var type = _ref32[0]; + var tagName = _ref32[1]; + var markers = _ref32[2]; + + var element = utils.createElement(tagName); + var elements = [element]; + var currentElement = element; + + for (var i = 0, l = markers.length; i < l; i++) { + var marker = markers[i]; + + var _marker = _slicedToArray(marker, 3); + + var openTypes = _marker[0]; + var closeTypes = _marker[1]; + var text = _marker[2]; + + for (var j = 0, m = openTypes.length; j < m; j++) { + var markerType = this.markerTypes[openTypes[j]]; + var openedElement = createElementFromMarkerType(markerType); + utils.appendChild(currentElement, openedElement); + elements.push(openedElement); + currentElement = openedElement; + } + + utils.appendChild(currentElement, utils.createTextNode(text)); + + for (var j = 0, m = closeTypes; j < m; j++) { + elements.pop(); + currentElement = elements[elements.length - 1]; + } + } + + return element; + } + }]); + + return DOMRenderer; + })(); + + exports['default'] = DOMRenderer; +}); +define('mobiledoc-dom-renderer', ['exports', 'mobiledoc-dom-renderer/dom-renderer'], function (exports, _mobiledocDomRendererDomRenderer) { + 'use strict'; + + exports.registerGlobal = registerGlobal; + + function registerGlobal(window) { + window.MobiledocDOMRenderer = _mobiledocDomRendererDomRenderer['default']; + } + + exports['default'] = _mobiledocDomRendererDomRenderer['default']; +}); +require("mobiledoc-dom-renderer")["registerGlobal"](window, document); +})(); \ No newline at end of file diff --git a/website/demo/mobiledoc-html-renderer.js b/website/demo/mobiledoc-html-renderer.js new file mode 100644 index 000000000..4e3c6b419 --- /dev/null +++ b/website/demo/mobiledoc-html-renderer.js @@ -0,0 +1,444 @@ +;(function() { + +var define, requireModule, require, requirejs; + +(function() { + + var _isArray; + if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === "[object Array]"; + }; + } else { + _isArray = Array.isArray; + } + + var registry = {}, seen = {}; + var FAILED = false; + + var uuid = 0; + + function tryFinally(tryable, finalizer) { + try { + return tryable(); + } finally { + finalizer(); + } + } + + function unsupportedModule(length) { + throw new Error("an unsupported module was defined, expected `define(name, deps, module)` instead got: `" + length + "` arguments to define`"); + } + + var defaultDeps = ['require', 'exports', 'module']; + + function Module(name, deps, callback, exports) { + this.id = uuid++; + this.name = name; + this.deps = !deps.length && callback.length ? defaultDeps : deps; + this.exports = exports || { }; + this.callback = callback; + this.state = undefined; + this._require = undefined; + } + + + Module.prototype.makeRequire = function() { + var name = this.name; + + return this._require || (this._require = function(dep) { + return require(resolve(dep, name)); + }); + } + + define = function(name, deps, callback) { + if (arguments.length < 2) { + unsupportedModule(arguments.length); + } + + if (!_isArray(deps)) { + callback = deps; + deps = []; + } + + registry[name] = new Module(name, deps, callback); + }; + + // we don't support all of AMD + // define.amd = {}; + // we will support petals... + define.petal = { }; + + function Alias(path) { + this.name = path; + } + + define.alias = function(path) { + return new Alias(path); + }; + + function reify(mod, name, seen) { + var deps = mod.deps; + var length = deps.length; + var reified = new Array(length); + var dep; + // TODO: new Module + // TODO: seen refactor + var module = { }; + + for (var i = 0, l = length; i < l; i++) { + dep = deps[i]; + if (dep === 'exports') { + module.exports = reified[i] = seen; + } else if (dep === 'require') { + reified[i] = mod.makeRequire(); + } else if (dep === 'module') { + mod.exports = seen; + module = reified[i] = mod; + } else { + reified[i] = requireFrom(resolve(dep, name), name); + } + } + + return { + deps: reified, + module: module + }; + } + + function requireFrom(name, origin) { + var mod = registry[name]; + if (!mod) { + throw new Error('Could not find module `' + name + '` imported from `' + origin + '`'); + } + return require(name); + } + + function missingModule(name) { + throw new Error('Could not find module ' + name); + } + requirejs = require = requireModule = function(name) { + var mod = registry[name]; + + + if (mod && mod.callback instanceof Alias) { + mod = registry[mod.callback.name]; + } + + if (!mod) { missingModule(name); } + + if (mod.state !== FAILED && + seen.hasOwnProperty(name)) { + return seen[name]; + } + + var reified; + var module; + var loaded = false; + + seen[name] = { }; // placeholder for run-time cycles + + tryFinally(function() { + reified = reify(mod, name, seen[name]); + module = mod.callback.apply(this, reified.deps); + loaded = true; + }, function() { + if (!loaded) { + mod.state = FAILED; + } + }); + + var obj; + if (module === undefined && reified.module.exports) { + obj = reified.module.exports; + } else { + obj = seen[name] = module; + } + + if (obj !== null && + (typeof obj === 'object' || typeof obj === 'function') && + obj['default'] === undefined) { + obj['default'] = obj; + } + + return (seen[name] = obj); + }; + + function resolve(child, name) { + if (child.charAt(0) !== '.') { return child; } + + var parts = child.split('/'); + var nameParts = name.split('/'); + var parentBase = nameParts.slice(0, -1); + + for (var i = 0, l = parts.length; i < l; i++) { + var part = parts[i]; + + if (part === '..') { + if (parentBase.length === 0) { + throw new Error('Cannot access parent module of root'); + } + parentBase.pop(); + } else if (part === '.') { continue; } + else { parentBase.push(part); } + } + + return parentBase.join('/'); + } + + requirejs.entries = requirejs._eak_seen = registry; + requirejs.clear = function(){ + requirejs.entries = requirejs._eak_seen = registry = {}; + seen = state = {}; + }; +})(); + +define('mobiledoc-html-renderer/html-renderer', ['exports', 'mobiledoc-html-renderer/utils/dom'], function (exports, _mobiledocHtmlRendererUtilsDom) { + /** + * runtime HTML renderer + * renders a mobiledoc to HTML + * + * input: mobiledoc + * output: HTML + */ + + 'use strict'; + + var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); + + var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + function createElementFromMarkerType() { + var _ref = arguments[0] === undefined ? ['', []] : arguments[0]; + + var _ref2 = _slicedToArray(_ref, 2); + + var tagName = _ref2[0]; + var attributes = _ref2[1]; + + var element = _mobiledocHtmlRendererUtilsDom['default'].createElement(tagName); + attributes = attributes || []; + + for (var i = 0, l = attributes.length; i < l; i = i + 2) { + var propName = attributes[i], + propValue = attributes[i + 1]; + _mobiledocHtmlRendererUtilsDom['default'].setAttribute(element, propName, propValue); + } + return element; + } + + var DOMRenderer = (function () { + function DOMRenderer() { + _classCallCheck(this, DOMRenderer); + } + + _createClass(DOMRenderer, [{ + key: 'render', + + /** + * @param mobiledoc + * @param rootElement optional, defaults to an empty div + * @return DOMNode + */ + value: function render(mobiledoc) { + var _this = this; + + var rootElement = arguments[1] === undefined ? _mobiledocHtmlRendererUtilsDom['default'].createElement('div') : arguments[1]; + + var _mobiledoc = _slicedToArray(mobiledoc, 2); + + var markerTypes = _mobiledoc[0]; + var sections = _mobiledoc[1]; + + this.root = rootElement; + this.markerTypes = markerTypes; + + sections.forEach(function (section) { + return _this.renderSection(section); + }); + + return this.root.toString(); + } + }, { + key: 'renderSection', + value: function renderSection(section) { + var _section = _slicedToArray(section, 1); + + var type = _section[0]; + + switch (type) { + case 1: + var rendered = this.renderParagraphSection(section); + _mobiledocHtmlRendererUtilsDom['default'].appendChild(this.root, rendered); + break; + default: + throw new Error('Unimplement renderer for type ' + type); + } + } + }, { + key: 'renderParagraphSection', + value: function renderParagraphSection(_ref3) { + var _ref32 = _slicedToArray(_ref3, 3); + + var type = _ref32[0]; + var tagName = _ref32[1]; + var markers = _ref32[2]; + + var element = _mobiledocHtmlRendererUtilsDom['default'].createElement(tagName); + var elements = [element]; + var currentElement = element; + + for (var i = 0, l = markers.length; i < l; i++) { + var marker = markers[i]; + + var _marker = _slicedToArray(marker, 3); + + var openTypes = _marker[0]; + var closeTypes = _marker[1]; + var text = _marker[2]; + + for (var j = 0, m = openTypes.length; j < m; j++) { + var markerType = this.markerTypes[openTypes[j]]; + var openedElement = createElementFromMarkerType(markerType); + _mobiledocHtmlRendererUtilsDom['default'].appendChild(currentElement, openedElement); + elements.push(openedElement); + currentElement = openedElement; + } + + _mobiledocHtmlRendererUtilsDom['default'].appendChild(currentElement, _mobiledocHtmlRendererUtilsDom['default'].createTextNode(text)); + + for (var j = 0, m = closeTypes; j < m; j++) { + elements.pop(); + currentElement = elements[elements.length - 1]; + } + } + + return element; + } + }]); + + return DOMRenderer; + })(); + + exports['default'] = DOMRenderer; +}); +define('mobiledoc-html-renderer', ['exports', 'mobiledoc-html-renderer/html-renderer'], function (exports, _mobiledocHtmlRendererHtmlRenderer) { + 'use strict'; + + exports.registerGlobal = registerGlobal; + + function registerGlobal(window) { + window.MobiledocHTMLRenderer = _mobiledocHtmlRendererHtmlRenderer['default']; + } + + exports['default'] = _mobiledocHtmlRendererHtmlRenderer['default']; +}); +define("mobiledoc-html-renderer/utils/dom", ["exports"], function (exports) { + "use strict"; + + var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var Element = (function () { + function Element(tagName) { + _classCallCheck(this, Element); + + this.tagName = tagName.toLowerCase(); + this.childNodes = []; + this.attributes = []; + } + + _createClass(Element, [{ + key: "appendChild", + value: function appendChild(element) { + this.childNodes.push(element); + } + }, { + key: "setAttribute", + value: function setAttribute(propName, propValue) { + this.attributes.push(propName, propValue); + } + }, { + key: "toString", + value: function toString() { + var html = "<" + this.tagName; + + if (this.attributes.length) { + for (var i = 0; i < this.attributes.length; i = i + 2) { + var propName = this.attributes[i], + propValue = this.attributes[i + 1]; + html += " " + propName + "=\"" + propValue + "\""; + } + } + html += ">"; + + for (var i = 0; i < this.childNodes.length; i++) { + html += this.childNodes[i].toString(); + } + html += ""; + return html; + } + }]); + + return Element; + })(); + + var TextNode = (function () { + function TextNode(value) { + _classCallCheck(this, TextNode); + + this.value = value; + } + + _createClass(TextNode, [{ + key: "toString", + value: function toString() { + return this.value; + } + }]); + + return TextNode; + })(); + + var Document = (function () { + function Document() { + _classCallCheck(this, Document); + } + + _createClass(Document, [{ + key: "createElement", + value: function createElement(tagName) { + return new Element(tagName); + } + }, { + key: "createTextNode", + value: function createTextNode(text) { + return new TextNode(text); + } + }]); + + return Document; + })(); + + var doc = new Document(); + + exports["default"] = { + createElement: function createElement(tagName) { + return doc.createElement(tagName); + }, + appendChild: function appendChild(target, child) { + target.appendChild(child); + }, + createTextNode: function createTextNode(text) { + return doc.createTextNode(text); + }, + setAttribute: function setAttribute(element, propName, propValue) { + element.setAttribute(propName, propValue); + } + }; +}); +require("mobiledoc-html-renderer")["registerGlobal"](window, document); +})(); \ No newline at end of file diff --git a/website/global/content-kit-editor.js b/website/global/content-kit-editor.js index 1a0cfe368..a195327b0 100644 --- a/website/global/content-kit-editor.js +++ b/website/global/content-kit-editor.js @@ -1063,17 +1063,13 @@ define('content-kit-editor/editor/editor', ['exports', 'content-kit-editor/views exports['default'] = Editor; }); -define('content-kit-editor', ['exports', 'content-kit-editor/editor/editor', 'content-kit-editor/runtime/renderers/mobiledoc-dom'], function (exports, _contentKitEditorEditorEditor, _contentKitEditorRuntimeRenderersMobiledocDom) { +define('content-kit-editor', ['exports', 'content-kit-editor/editor/editor'], function (exports, _contentKitEditorEditorEditor) { 'use strict'; exports.registerGlobal = registerGlobal; - var Runtime = { - DOMRenderer: _contentKitEditorRuntimeRenderersMobiledocDom['default'] - }; - var ContentKit = { - Editor: _contentKitEditorEditorEditor['default'], Runtime: Runtime + Editor: _contentKitEditorEditorEditor['default'] }; function registerGlobal(global) { @@ -1611,11 +1607,6 @@ define('content-kit-editor/renderers/mobiledoc', ['exports', 'content-kit-editor } }; }); -define('content-kit-editor/runtime/renderers/mobiledoc-dom', ['exports', 'mobiledoc-dom-renderer'], function (exports, _mobiledocDomRenderer) { - 'use strict'; - - exports['default'] = _mobiledocDomRenderer['default']; -}); define('content-kit-editor/utils/compat', ['exports', 'content-kit-editor/utils/doc', 'content-kit-editor/utils/win'], function (exports, _contentKitEditorUtilsDoc, _contentKitEditorUtilsWin) { 'use strict'; @@ -1942,7 +1933,7 @@ define('content-kit-editor/utils/http-utils', ['exports'], function (exports) { return null; } try { - return JSON.parse(jsonString); + return window.JSON.parse(jsonString); } catch (e) { return jsonString; } @@ -3038,159 +3029,5 @@ define('content-kit-utils/string-utils', ['exports'], function (exports) { exports.sanitizeWhitespace = sanitizeWhitespace; exports.injectIntoString = injectIntoString; }); -define('mobiledoc-dom-renderer/dom-renderer', ['exports'], function (exports) { - /** - * runtime DOM renderer - * renders a mobiledoc to DOM - * - * input: mobiledoc - * output: DOM - */ - - 'use strict'; - - var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); - - var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - var utils = { - createElement: function createElement(tagName) { - return document.createElement(tagName); - }, - appendChild: function appendChild(target, child) { - target.appendChild(child); - }, - createTextNode: function createTextNode(text) { - return document.createTextNode(text); - } - }; - - function createElementFromMarkerType() { - var _ref = arguments[0] === undefined ? ['', []] : arguments[0]; - - var _ref2 = _slicedToArray(_ref, 2); - - var tagName = _ref2[0]; - var attributes = _ref2[1]; - - var element = utils.createElement(tagName); - attributes = attributes || []; - - for (var i = 0, l = attributes.length; i < l; i = i + 2) { - var propName = attributes[i], - propValue = attributes[i + 1]; - element.setAttribute(propName, propValue); - } - return element; - } - - var DOMRenderer = (function () { - function DOMRenderer() { - _classCallCheck(this, DOMRenderer); - } - - _createClass(DOMRenderer, [{ - key: 'render', - - /** - * @param mobiledoc - * @param rootElement optional, defaults to an empty div - * @return DOMNode - */ - value: function render(mobiledoc) { - var _this = this; - - var rootElement = arguments[1] === undefined ? utils.createElement('div') : arguments[1]; - - var _mobiledoc = _slicedToArray(mobiledoc, 2); - - var markerTypes = _mobiledoc[0]; - var sections = _mobiledoc[1]; - - this.root = rootElement; - this.markerTypes = markerTypes; - - sections.forEach(function (section) { - return _this.renderSection(section); - }); - - return this.root; - } - }, { - key: 'renderSection', - value: function renderSection(section) { - var _section = _slicedToArray(section, 1); - - var type = _section[0]; - - switch (type) { - case 1: - var rendered = this.renderParagraphSection(section); - utils.appendChild(this.root, rendered); - break; - default: - throw new Error('Unimplement renderer for type ' + type); - } - } - }, { - key: 'renderParagraphSection', - value: function renderParagraphSection(_ref3) { - var _ref32 = _slicedToArray(_ref3, 3); - - var type = _ref32[0]; - var tagName = _ref32[1]; - var markers = _ref32[2]; - - var element = utils.createElement(tagName); - var elements = [element]; - var currentElement = element; - - for (var i = 0, l = markers.length; i < l; i++) { - var marker = markers[i]; - - var _marker = _slicedToArray(marker, 3); - - var openTypes = _marker[0]; - var closeTypes = _marker[1]; - var text = _marker[2]; - - for (var j = 0, m = openTypes.length; j < m; j++) { - var markerType = this.markerTypes[openTypes[j]]; - var openedElement = createElementFromMarkerType(markerType); - utils.appendChild(currentElement, openedElement); - elements.push(openedElement); - currentElement = openedElement; - } - - utils.appendChild(currentElement, utils.createTextNode(text)); - - for (var j = 0, m = closeTypes; j < m; j++) { - elements.pop(); - currentElement = elements[elements.length - 1]; - } - } - - return element; - } - }]); - - return DOMRenderer; - })(); - - exports['default'] = DOMRenderer; -}); -define('mobiledoc-dom-renderer', ['exports', 'mobiledoc-dom-renderer/dom-renderer'], function (exports, _mobiledocDomRendererDomRenderer) { - 'use strict'; - - exports.registerGlobal = registerGlobal; - - function registerGlobal(window) { - window.MobiledocDOMRenderer = _mobiledocDomRendererDomRenderer['default']; - } - - exports['default'] = _mobiledocDomRendererDomRenderer['default']; -}); require("content-kit-editor")["registerGlobal"](window, document); })(); \ No newline at end of file From 422f9876b4f1fc4750ad7f66941d426f457922f6 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Thu, 9 Jul 2015 17:04:43 -0400 Subject: [PATCH 45/77] Removes gulp dependencies --- README.md | 21 +++----- gulpfile.js | 140 --------------------------------------------------- package.json | 12 ----- 3 files changed, 7 insertions(+), 166 deletions(-) delete mode 100644 gulpfile.js diff --git a/README.md b/README.md index b16779de8..9b900a149 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ be authored) are built from models. Models represent rows of content, and can be static or dynamic. For example, the teardown of an article might look like: +**FIXME** this needs to be updated: ``` ┌──────────────────────────────────────────────────────────────────────────────┐ @@ -82,7 +83,7 @@ Visit [http://bustlelabs.github.io/content-kit-editor/demo](http://bustlelabs.gi Running ContentKit tests and demo server locally requires the following dependencies: * [node.js](http://nodejs.org/) ([install package](http://nodejs.org/download/)) or `brew install node` -* `gulp`, via `npm install -g gulp` +* `broccoli`, via `npm install -g broccoli-cli` ### Tests @@ -93,7 +94,8 @@ Install npm and bower: Run tests via the built-in broccoli server: - * `npm run serve && open http://localhost:4200/tests` + * `npm run serve` + * `open http://localhost:4200/tests` Or run tests via testem: @@ -103,20 +105,11 @@ To view the demo: * `broccoli serve` * open http://localhost:4200/demo - * (Note that image uploads and embeds require the demo server to be running) + * (Note that image uploads and embeds are not currently working) +#### To Do -To run the demo server: - -``` -npm start && open http://localhost:5000 -``` - -To ensure ContentKit rebuilds while you work with it: - -``` -gulp watch -``` +Bring back image uploads and embed. Notes below: For uploads and embeds to work, you will have to configure AWS and Embedly keys as environment variables: diff --git a/gulpfile.js b/gulpfile.js deleted file mode 100644 index 6911ece67..000000000 --- a/gulpfile.js +++ /dev/null @@ -1,140 +0,0 @@ -var del = require('del'); -var gulp = require('gulp'); -var jshint = require('gulp-jshint'); -var qunit = require('gulp-qunit'); -var less = require('gulp-less'); -var concat = require('gulp-concat'); -var header = require('gulp-header'); -var open = require('gulp-open'); -var uglify = require('gulp-uglify'); -var cssmin = require('gulp-cssmin'); -var file = require('gulp-file'); -var transpile = require('esperanto'); - -// ------------------------------------------- - -var pkg = require('./package.json'); - -var jsSrc = [ - './src/js/**/*.js' -]; - -var jsEntry = './src/js/index.js'; - -var cssSrc = [ - './src/css/variables.less', - './src/css/editor.less', - './src/css/toolbar.less', - './src/css/tooltip.less', - './src/css/embeds.less', - './src/css/message.less', - './src/css/icons.less', - './src/css/animations.less' -]; - -var distDest = './dist/'; -var jsDistName = 'content-kit-editor.js'; -var cssDistName = 'content-kit-editor.css'; -var cssDistPath = distDest + cssDistName; - -var testRunner = './tests/index.html'; -var testScripts = './tests/**/*.js'; -var demo = './demo/index.html'; - -var banner = ['/**', - ' * @overview <%= pkg.name %>: <%= pkg.description %>', - ' * @version <%= pkg.version %>', - ' * @author <%= pkg.author %>', - ' * @license <%= pkg.license %>', - ' */', - ''].join('\n'); - -var iifeHeader = '\n(function(window, document, undefined) {\n\n'; -var iifeFooter = '\n}(this, document));\n'; - -// JSHint javascript code linting -gulp.task('lint', function() { - return gulp.src(jsSrc) - .pipe(jshint('.jshintrc')) - .pipe(jshint.reporter('default')); -}); - -gulp.task('build-js', function() { - return transpile.bundle({ - entry: jsEntry, - resolvePath: function (importee, importer) { - return 'node_modules/' + importee + '.js'; - } - }).then(function(bundle) { - var transpiled = bundle.concat({ - intro: iifeHeader, - outro: iifeFooter - }); - return file(jsDistName, transpiled.code, { src: true }) - .pipe(header(banner, { pkg : pkg } )) - .pipe(gulp.dest(distDest)); - }); -}); - -// Compiles LESS and concatenates css -gulp.task('build-css', function() { - return gulp.src(cssSrc) - .pipe(concat(cssDistName)) - .pipe(less()) - .pipe(gulp.dest(distDest)); -}); - -// Builds the entire suite of js/css -gulp.task('build', ['build-css', 'build-js']); - -// Runs QUnit tests -gulp.task('test', ['build'], function() { - return gulp.src(testRunner).pipe(qunit()); -}); - -// Opens the test runner in your default browser -gulp.task('test-browser', ['build'], function(){ - return gulp.src(testRunner).pipe(open('<% file.path %>')); -}); - -// Opens the demo in your default browser -gulp.task('demo', function(){ - return gulp.src(demo).pipe(open('<% file.path %>')); -}); - -// Removes built output files -gulp.task('clean', function() { - return del([distDest + '*']); -}); - -// Watches when js files change and automatically lints/builds -gulp.task('watch-js', function() { - gulp.watch(jsSrc, ['lint', 'build-js']); -}); - -// Watches test files change and automatically tests -gulp.task('watch-tests', function() { - gulp.watch(testScripts, ['test']); -}); - -// Watches when css files change and automatically builds -gulp.task('watch-css', function() { - gulp.watch(cssSrc, ['build-css']); -}); - -// Watches when any files change and automatically tests/builds -gulp.task('watch', ['watch-js', 'watch-tests', 'watch-css']); - -// Default task -gulp.task('default', ['lint', 'build', 'test']); - -// Deploy task -gulp.task('deploy', ['clean', 'build'], function() { - gulp.src(jsDistPath) - .pipe(uglify()) - .pipe(gulp.dest(distDest)); - - gulp.src(cssDistPath) - .pipe(cssmin()) - .pipe(gulp.dest(distDest)); -}); diff --git a/package.json b/package.json index 64e2f6e33..c6c4c6f64 100644 --- a/package.json +++ b/package.json @@ -44,18 +44,6 @@ "broccoli-multi-builder": "^0.2.5", "broccoli-test-builder": "^0.1.0", "content-kit-utils": "^0.2.0", - "del": "^1.1.1", - "esperanto": "^0.6.32", - "gulp": "^3.8.11", - "gulp-concat": "~2.1.7", - "gulp-cssmin": "^0.1.6", - "gulp-file": "^0.2.0", - "gulp-header": "^1.2.2", - "gulp-jshint": "~1.3.4", - "gulp-less": "^1.3.1", - "gulp-open": "^0.2.8", - "gulp-qunit": "^1.2.1", - "gulp-uglify": "^1.1.0", "jquery": "^2.1.4", "mobiledoc-dom-renderer": "^0.1.3", "mobiledoc-html-renderer": "^0.1.0", From b7bdb12b73b337a3252e0c12978602f49152b559 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Thu, 9 Jul 2015 17:06:46 -0400 Subject: [PATCH 46/77] document building and deploying --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b16779de8..405c5bc63 100644 --- a/README.md +++ b/README.md @@ -73,8 +73,11 @@ var editor = new ContentKit.Editor(this.element, options); ### Deploy the demo website The demo website is hosted at github pages. -To build the website, run `npm run build-website`. -To deploy it to the gh-pages branch run `npm run deploy-website`. +To publish a new version do: + + * `npm run build-website`. This builds the website into `website/` and commits it + * `npm run deploy-website`. Pushes the `website/` subtree to the `gh-pages` branch at github + Visit [http://bustlelabs.github.io/content-kit-editor/demo](http://bustlelabs.github.io/content-kit-editor/demo). ### Contributing From b1b8bec14c2735cc29da8c2f31d2f4c67cc30f5d Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Thu, 9 Jul 2015 19:00:09 -0400 Subject: [PATCH 47/77] mobiledoc documentation --- MOBILEDOC.md | 93 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 MOBILEDOC.md diff --git a/MOBILEDOC.md b/MOBILEDOC.md new file mode 100644 index 000000000..12a0ba529 --- /dev/null +++ b/MOBILEDOC.md @@ -0,0 +1,93 @@ +# mobiledoc format + +mobiledoc is the output format that content-kit-editor produces. +It aims to be a terse format that is efficiently transferred over the wire +for a client (be it web or native) to render. + +## goals for mobiledoc + +### efficient to transfer + +The mobiledoc format is intended to be simple and fairly terse so that it compresses as well or better than HTML. + +### platform-agnostic + +mobiledoc is intended to be largely platform-agnostic. Sample use cases: + + * A web app downloads an article in mobiledoc format via ajax and uses the mobiledoc-dom-renderer to render and display it + * An Ember app is running server-side via fastboot and needs to generate HTML server-side for SEO purposes. It uses the mobiledoc-html-renderer to turn a mobiledoc article that it retrieves from the API into an HTML string + * A native iOS app downloads an article in mobiledoc format and uses a custom renderer to generate a native view to display the article + +In all the above cases, the input is the same: An article in mobiledoc format, provided via an api. + +### content-focused + +mobiledoc is primarily intended to be used for news-related content such as articles and blog posts. It is deliberately simple, and organizes its content in an array of "sections" that are considered as individual blocks of content. + +There is not currently any concept of layout or design built into the format. It is up to the renderer to generate a display appropriate for its context. On mobile this may mean each section is full-width and they are displayed sequentially. On larger displays the sections may be rendered side-by-side. mobiledoc makes no prescription for output display. + +### extensible + +mobiledoc should be open for extension with custom types (called "cards") that bring their own configuration, and possibly their own renderers. Primary renderers (the dom, html, native, etc renderers) should be able to gracefully handle cards that they cannot natively render. + +## format specification + +mobiledoc format is an array with two elements: `markerTypes` and `sections`. The marker types describe all of the possible `markups` that may be applied to `markers` within the sectionssection. + +#### markupTypes + +A `markupType` is an array of 1 or 2 items: `[markerTypes, sections]`. The first item in the array is the type of markup, typically a tagName (such as `"B"`). The markupType can optionally have a second item in its array, which is an array of `attributes` to be applied to it. The attributes are listed as `propName`, `propValue` in the array. Each `nth` item in the array is a propName and each `(n+1)th` item in the array is that propName's propValue. + +Example markupTypes: + + * Bold tag: `["B"]` + * Anchor tag linking to this repository: `["A", ["href", "http://github.com/bustlelabs/content-kit-editor"]]` + * Anchor tag linking to this repository and with `target="_blank"`: `["A", ["href", "http://github.com/bustlelabs/content-kit-editor", "target", "_blank"]]` + +#### sections + +A section is an array of three items: `[sectionType, tagName, markers]`. `sectionType` defines the type of block section that this is. The only supported type now is `1`. `tagName` is the name of the block tag to use. H1-H6 and P are possible values. `markers` is an array of the content within that section, separated by the markup that is to be applied to it. + +#### markers in sections + +A marker is an array of three items: `[openingMarkupTypes, closingMarkupCount, value]`. `openingMarkupTypes` is an array of the indexes of the `markupTypes` to apply to this marker, `closingMarkupCount` is how many markup types are closing at the end of this marker, and `value` is the text value inside the marker. + +Assuming these `markerTypes`: +``` +markerTypes = [ + ["B"], // index 0 + ["I"], // index 1 + ["A", ["href", "google.com"]], // index 2 +] +``` + +And this section: + +``` +section = [ + 1, // type of section + "P", // tagName of section + [ // markers + [ + [1], // open marker type of index 1 (italics) + 0, // close 0 open markers + 'italicized' // the text value + ], + [ + [0], // open marker type of index 0 (bold) + 1, // close 1 markerType (the most-recently opened marker type (bold) will be closed) + 'bold + italicized' + ], + [ + [], // open no marker types + 1, // close 1 marker type (in this case, italics) + 'only italicized' + ], + [ + [2], // start the A tag + 1, // and close it after this text + 'I am a link' + ] + ] +] +``` From 4a6edfb638b3f314db65890798dec99ba326266b Mon Sep 17 00:00:00 2001 From: Matthew Beale Date: Mon, 13 Jul 2015 11:36:59 -0400 Subject: [PATCH 48/77] Add tests for parsers --- src/js/parsers/dom.js | 5 +- tests/unit/parsers/dom-test.js | 510 +++++++++++++++++++++++++++ tests/unit/parsers/mobiledoc-test.js | 79 +++++ 3 files changed, 592 insertions(+), 2 deletions(-) create mode 100644 tests/unit/parsers/dom-test.js create mode 100644 tests/unit/parsers/mobiledoc-test.js diff --git a/src/js/parsers/dom.js b/src/js/parsers/dom.js index bef9ced82..db41f8a88 100644 --- a/src/js/parsers/dom.js +++ b/src/js/parsers/dom.js @@ -4,7 +4,7 @@ import { trim } from 'content-kit-utils'; const ELEMENT_NODE = 1; const TEXT_NODE = 3; -const MARKUP_SECTION_TAG_NAMES = ['P', 'H3', 'H2', 'H1', 'BLOCKQUOTE', 'UL', 'IMG', 'OL']; +const MARKUP_SECTION_TAG_NAMES = ['P', 'H3', 'H2', 'H1', 'BLOCKQUOTE', 'UL', 'OL']; const ALLOWED_ATTRIBUTES = ['href', 'rel', 'src']; @@ -36,7 +36,8 @@ const VALID_MARKER_ELEMENTS = [ 'I', 'STRONG', 'EM', - 'A' + 'A', + 'LI' ]; function isValidMarkerElement(element) { diff --git a/tests/unit/parsers/dom-test.js b/tests/unit/parsers/dom-test.js new file mode 100644 index 000000000..42ffcbe07 --- /dev/null +++ b/tests/unit/parsers/dom-test.js @@ -0,0 +1,510 @@ +import DOMParser from 'content-kit-editor/parsers/dom'; +import { generateBuilder } from 'content-kit-editor/utils/post-builder'; + +const { module, test } = window.QUnit; + +function buildDOM(html) { + var div = document.createElement('div'); + div.innerHTML = html; + return div; +} + +let parser, builder, expectedPost; + +module('Unit: DOMParser', { + beforeEach() { + parser = new DOMParser(); + builder = generateBuilder(); + expectedPost = builder.generatePost(); + }, + afterEach() { + parser = null; + builder = null; + expectedPost = null; + } +}); + +test('parse empty content', (assert) => { + const post = parser.parse(buildDOM('')); + assert.deepEqual(post, expectedPost); +}); + +test('blank textnodes are ignored', (assert) => { + let post = parser.parse(buildDOM('

first line

\n

second line

')); + + let expectedFirst = builder.generateSection('P'); + expectedFirst.markers.push(builder.generateMarker([], 0, 'first line')); + expectedPost.appendSection(expectedFirst); + let expectedSecond = builder.generateSection('P'); + expectedSecond.markers.push(builder.generateMarker([], 0, 'second line')); + expectedPost.appendSection(expectedSecond); + + assert.deepEqual(post, expectedPost); +}); + +test('textnode adjacent to p tag becomes section', (assert) => { + const post = parser.parse(buildDOM('

first line

second line')); + + let expectedFirst = builder.generateSection('P'); + expectedFirst.markers.push(builder.generateMarker([], 0, 'first line')); + expectedPost.appendSection(expectedFirst); + let expectedSecond = builder.generateSection('P', {}, true); + expectedSecond.markers.push(builder.generateMarker([], 0, 'second line')); + expectedPost.appendSection(expectedSecond); + + assert.deepEqual(post, expectedPost); +}); + +test('p tag (section markup) should create a block', (assert) => { + const post = parser.parse(buildDOM('

text

')); + + let expectedFirst = builder.generateSection('P'); + expectedFirst.markers.push(builder.generateMarker([], 0, 'text')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('strong tag (stray markup) without a block should create a block', (assert) => { + const post = parser.parse(buildDOM('text')); + + let expectedFirst = builder.generateSection('P', {}, true); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('STRONG') + ], 1, 'text')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('strong tag with inner em (stray markup) without a block should create a block', (assert) => { + const post = parser.parse(buildDOM('stray markup tags.')); + + let expectedFirst = builder.generateSection('P', {}, true); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('STRONG'), + builder.generateMarkerType('EM') + ], 1, 'stray')); + expectedFirst.markers.push(builder.generateMarker([], 1, ' markup tags')); + expectedFirst.markers.push(builder.generateMarker([], 0, '.')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('stray text (stray markup) should create a block', (assert) => { + const post = parser.parse(buildDOM('text')); + + let expectedFirst = builder.generateSection('P', {}, true); + expectedFirst.markers.push(builder.generateMarker([], 0, 'text')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('text node, strong tag, text node (stray markup) without a block should create a block', (assert) => { + const post = parser.parse(buildDOM('start bold end')); + + let expectedFirst = builder.generateSection('P', {}, true); + expectedFirst.markers.push(builder.generateMarker([], 0, 'start ')); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('STRONG') + ], 1, 'bold')); + expectedFirst.markers.push(builder.generateMarker([], 0, ' end')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('italic tag (stray markup) without a block should create a block', (assert) => { + const post = parser.parse(buildDOM('text')); + + let expectedFirst = builder.generateSection('P', {}, true); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('EM') + ], 1, 'text')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('u tag (stray markup) without a block should strip U and create a block', (assert) => { + const post = parser.parse(buildDOM('text')); + + let expectedFirst = builder.generateSection('P', {}, true); + expectedFirst.markers.push(builder.generateMarker([], 0, 'text')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('a tag (stray markup) without a block should create a block', (assert) => { + var url = "http://test.com"; + const post = parser.parse(buildDOM('text')); + + let expectedFirst = builder.generateSection('P', {}, true); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('A', ['href', url]) + ], 1, 'text')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +/* FIXME: What should happen with br +test('markup: break', (assert) => { + const post = parser.parse(buildDOM('line
break')); + + let expectedFirst = builder.generateSection('P', {}, true); + expectedFirst.markers.push(builder.generateMarker([], 0, 'line ')); + expectedFirst.markers.push(builder.generateMarker([], 0, 'break')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); +*/ + +test('sub tag (stray markup) without a block should filter SUB and create a block', (assert) => { + const post = parser.parse(buildDOM('footnote1')); + + let expectedFirst = builder.generateSection('P', {}, true); + expectedFirst.markers.push(builder.generateMarker([], 0, 'footnote')); + expectedFirst.markers.push(builder.generateMarker([], 0, '1')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('sup tag (stray markup) without a block should filter SUP and create a block', (assert) => { + const post = parser.parse(buildDOM('e=mc2')); + + let expectedFirst = builder.generateSection('P', {}, true); + expectedFirst.markers.push(builder.generateMarker([], 0, 'e=mc')); + expectedFirst.markers.push(builder.generateMarker([], 0, '2')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('list (stray markup) without a block should create a block', (assert) => { + const post = parser.parse(buildDOM('
  • Item 1
  • Item 2
')); + + let expectedFirst = builder.generateSection('UL'); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('LI') + ], 1, 'Item 1')); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('LI') + ], 1, 'Item 2')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('nested tags (section markup) should create a block', (assert) => { + const post = parser.parse(buildDOM('

Double. Double staggered start. Double staggered end. Double staggered middle.

')); + + let expectedFirst = builder.generateSection('P'); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('EM'), + builder.generateMarkerType('STRONG') + ], 2, 'Double.')); + expectedFirst.markers.push(builder.generateMarker([], 0, ' ')); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('STRONG'), + builder.generateMarkerType('EM') + ], 1, 'Double staggered')); + expectedFirst.markers.push(builder.generateMarker([], 1, ' start.')); + expectedFirst.markers.push(builder.generateMarker([], 0, ' ')); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('STRONG') + ], 0, 'Double ')); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('EM') + ], 2, 'staggered end.')); + expectedFirst.markers.push(builder.generateMarker([], 0, ' ')); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('STRONG') + ], 0, 'Double ')); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('EM') + ], 1, 'staggered')); + expectedFirst.markers.push(builder.generateMarker([], 1, ' middle.')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +/* + * FIXME: Update these tests to use the renderer + * +test('markup: nested/unsupported tags', (assert) => { + var parsed = compiler.parse('

Test one two three four five six seven

'); + + equal ( parsed.length, 1 ); + equal ( parsed[0].type, Type.PARAGRAPH.id ); + equal ( parsed[0].value, 'Test one two three four five six seven' ); + equal ( parsed[0].markup.length, 5 ); + + equal ( parsed[0].markup[0].type, Type.BOLD.id ); + equal ( parsed[0].markup[0].start, 9 ); + equal ( parsed[0].markup[0].end, 12 ); + + equal ( parsed[0].markup[1].type, Type.ITALIC.id ); + equal ( parsed[0].markup[1].start, 13 ); + equal ( parsed[0].markup[1].end, 18 ); + + equal ( parsed[0].markup[2].type, Type.BOLD.id ); + equal ( parsed[0].markup[2].start, 13 ); + equal ( parsed[0].markup[2].end, 18 ); + + equal ( parsed[0].markup[3].type, Type.BOLD.id ); + equal ( parsed[0].markup[3].start, 24 ); + equal ( parsed[0].markup[3].end, 28 ); + + equal ( parsed[0].markup[4].type, Type.BOLD.id ); + equal ( parsed[0].markup[4].start, 29 ); + equal ( parsed[0].markup[4].end, 32 ); +}); + +test('markup: preserves spaces in empty tags', (assert) => { + var rendered = compiler.rerender('

Testing a space

'); + equal ( rendered, '

Testing a space

'); +}); + +test('markup: self-closing tags with nesting', (assert) => { + var input = '

Blah
blah

blah

'; + var parsed = compiler.parse(input); + + equal ( parsed[0].value, 'Blah blah blah' ); + equal ( parsed[0].markup.length, 3 ); + + equal ( parsed[0].markup[0].type, Type.BOLD.id ); + equal ( parsed[0].markup[0].start, 0 ); + equal ( parsed[0].markup[0].end, 9 ); + + equal ( parsed[0].markup[1].type, Type.BREAK.id ); + equal ( parsed[0].markup[1].start, 5 ); + equal ( parsed[0].markup[1].end, 5 ); + + equal ( parsed[0].markup[2].type, Type.BREAK.id ); + equal ( parsed[0].markup[2].start, 10 ); + equal ( parsed[0].markup[2].end, 10 ); +}); + +test('markup: whitespace', (assert) => { + var parsed = compiler.parse('
    ' + + '\t
  • Item 1
  •  \n' + + '
  • Item 2
  • \r\n   ' + + '\t\t
  • Item 3
  • \r' + + '
'); + equal ( parsed.length, 1 ); + equal ( parsed[0].value, 'Item 1 Item 2 Item 3' ); + + var markup = parsed[0].markup + equal ( markup.length, 6); + equal ( markup[0].type, Type.LIST_ITEM.id ); + equal ( markup[0].start, 0 ); + equal ( markup[0].end, 6 ); + equal ( markup[1].type, Type.ITALIC.id ); + equal ( markup[1].start, 5 ); + equal ( markup[1].end, 6 ); + equal ( markup[2].type, Type.LIST_ITEM.id ); + equal ( markup[2].start, 7 ); + equal ( markup[2].end, 13 ); + equal ( markup[3].type, Type.BOLD.id ); + equal ( markup[3].start, 7 ); + equal ( markup[3].end, 13 ); + equal ( markup[4].type, Type.LIST_ITEM.id ); + equal ( markup[4].start, 14 ); + equal ( markup[4].end, 20 ); + equal ( markup[5].type, Type.BOLD.id ); + equal ( markup[5].start, 14 ); + equal ( markup[5].end, 18 ); +}); + +test('markup: consistent order', (assert) => { + var correctlyOrdered = compiler.parse('

text

'); + var incorrectlyOrdered = compiler.parse('

text

'); + + equal( compiler.render(correctlyOrdered), compiler.render(incorrectlyOrdered) ); +}); +*/ + +test('attributes', (assert) => { + var href = 'http://google.com'; + var rel = 'nofollow'; + const post = parser.parse(buildDOM('

Link to google.com

')); + + let expectedFirst = builder.generateSection('P'); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('A', ['href', href, 'rel', rel]) + ], 1, 'Link to google.com')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('attributes filters out inline styles and classes', (assert) => { + const post = parser.parse(buildDOM('

test

')); + + let expectedFirst = builder.generateSection('P'); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('B') + ], 1, 'test')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('blocks: paragraph', (assert) => { + const post = parser.parse(buildDOM('

TEXT

')); + + let expectedFirst = builder.generateSection('P'); + expectedFirst.markers.push(builder.generateMarker([], 0, 'TEXT')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('blocks: heading', (assert) => { + const post = parser.parse(buildDOM('

TEXT

')); + + let expectedFirst = builder.generateSection('H2'); + expectedFirst.markers.push(builder.generateMarker([], 0, 'TEXT')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('blocks: subheading', (assert) => { + const post = parser.parse(buildDOM('

TEXT

')); + + let expectedFirst = builder.generateSection('H3'); + expectedFirst.markers.push(builder.generateMarker([], 0, 'TEXT')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +/* FIXME: should not create a markup type section +test('blocks: image', (assert) => { + var url = "http://domain.com/text.png"; + const post = parser.parse(buildDOM('')); + assert.deepEqual( post, { + sections: [{ + type: MARKUP_SECTION, + tagName: 'IMG', + attributes: ['src', url], + markups: [] + }] + }); +}); +*/ + +test('blocks: quote', (assert) => { + const post = parser.parse(buildDOM('
quote
')); + + let expectedFirst = builder.generateSection('BLOCKQUOTE'); + expectedFirst.markers.push(builder.generateMarker([], 0, 'quote')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('blocks: list', (assert) => { + const post = parser.parse(buildDOM('
  • Item 1
  • Item 2
')); + + let expectedFirst = builder.generateSection('UL'); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('LI') + ], 1, 'Item 1')); + expectedFirst.markers.push(builder.generateMarker([], 0, ' ')); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('LI') + ], 1, 'Item 2')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +test('blocks: ordered list', (assert) => { + const post = parser.parse(buildDOM('
  1. Item 1
  2. Item 2
')); + + let expectedFirst = builder.generateSection('OL'); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('LI') + ], 1, 'Item 1')); + expectedFirst.markers.push(builder.generateMarker([], 0, ' ')); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('LI') + ], 1, 'Item 2')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); + +/* +test('blocks: mixed', (assert) => { + var input = '

The Title

The Subtitle

TEXT 1

TEXT 2

TEXT with a link.

Quote
'; + var parsed = compiler.parse(input); + + equal ( parsed.length, 6 ); + equal ( parsed[0].type, Type.HEADING.id ); + equal ( parsed[1].type, Type.SUBHEADING.id ); + equal ( parsed[2].type, Type.PARAGRAPH.id ); + equal ( parsed[3].type, Type.PARAGRAPH.id ); + equal ( parsed[4].type, Type.PARAGRAPH.id ); + equal ( parsed[5].type, Type.QUOTE.id ); +}); +*/ + +/* FIXME: needs images, br support +test('blocks: self-closing', (assert) => { + var url = 'http://domain.com/test.png'; + const post = parser.parse(buildDOM('

Line
break

')); + + assert.deepEqual( post, { + sections: [{ + type: MARKUP_SECTION, + tagName: 'IMG', + attributes: ['src', url], + markups: [] + }, { + type: MARKUP_SECTION, + tagName: 'P', + markups: [{ + open: [], + close: 0, + value: 'Line' + }, { + open: [{ + tagName: 'BR' + }], + close: 1, + value: null + }, { + open: [], + close: 0, + value: 'break' + }] + }] + }); +}); +*/ + +test('converts tags to mapped values', (assert) => { + // FIXME: Should probably be normalizing b to strong etc + const post = parser.parse(buildDOM('

Converts tags.

')); + + let expectedFirst = builder.generateSection('P'); + expectedFirst.markers.push(builder.generateMarker([ + builder.generateMarkerType('B'), + builder.generateMarkerType('I') + ], 1, 'Converts')); + expectedFirst.markers.push(builder.generateMarker([], 1, ' tags')); + expectedFirst.markers.push(builder.generateMarker([], 0, '.')); + expectedPost.appendSection(expectedFirst); + + assert.deepEqual(post, expectedPost); +}); diff --git a/tests/unit/parsers/mobiledoc-test.js b/tests/unit/parsers/mobiledoc-test.js new file mode 100644 index 000000000..d12a479b5 --- /dev/null +++ b/tests/unit/parsers/mobiledoc-test.js @@ -0,0 +1,79 @@ +import MobiledocParser from 'content-kit-editor/parsers/mobiledoc'; +import { generateBuilder } from 'content-kit-editor/utils/post-builder'; + +const { module, test } = window.QUnit; + +let parser, builder, post; + +module('Unit: Parsers: Mobiledoc', { + beforeEach() { + parser = new MobiledocParser(); + builder = generateBuilder(); + post = builder.generatePost(); + }, + afterEach() { + parser = null; + builder = null; + post = null; + } +}); + +test('#parse empty doc returns an empty post', (assert) => { + assert.deepEqual(parser.parse([[], []]), + post); +}); + +test('#parse doc without marker types', (assert) => { + const mobiledoc = [ + [], + [[ + 1,'P', [[[], 0, 'hello world']] + ]] + ]; + const parsed = parser.parse(mobiledoc); + + let section = builder.generateSection('P', [], false); + let marker = builder.generateMarker([], 0, 'hello world'); + section.markers.push(marker); + post.appendSection(section); + + assert.deepEqual( + parsed, + post + ); +}); + +test('#parse doc with marker type', (assert) => { + const mobiledoc = [ + [ + ['B'], + ['A', ['href', 'google.com']] + ], + [[ + 1,'P', [ + [[1], 0, 'hello'], // a tag open + [[0], 1, 'brave new'], // b tag open/close + [[], 1, 'world'] // a tag close + ] + ]] + ]; + const parsed = parser.parse(mobiledoc); + + let section = builder.generateSection('P', [], false); + let aMarkerType = builder.generateMarkerType('A', ['href', 'google.com']); + let bMarkerType = builder.generateMarkerType('B'); + + let markers = [ + builder.generateMarker([aMarkerType], 0, 'hello'), + builder.generateMarker([bMarkerType], 1, 'brave new'), + builder.generateMarker([], 1, 'world') + ]; + section.markers = markers; + post.appendSection(section); + + assert.deepEqual( + parsed, + post + ); +}); + From 710664fd10748901c7685423542cf3fa55c19849 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Mon, 13 Jul 2015 13:13:07 -0400 Subject: [PATCH 49/77] add $ and QUnit to jshint globals --- .jshintrc | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.jshintrc b/.jshintrc index 0b5a4325d..a5a5ed159 100644 --- a/.jshintrc +++ b/.jshintrc @@ -95,6 +95,8 @@ // to your app that hang off `window`. "predef": [ - "define" // amd loader + "define", // amd loader + "$", + "QUnit" ] -} \ No newline at end of file +} From 9a10d7ae182d09329125a5fd6aa4449a908a55e8 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Mon, 13 Jul 2015 12:19:17 -0400 Subject: [PATCH 50/77] Test: displaying toolbar, clicking format butons, creating links * add `Helpers.dom.triggerKeyEvent` for simulating key events * add `Helpers.dom.triggerEvent` for simulating mouse events * Add View#destroy, destroy all views when destroying editor --- Brocfile.js | 4 +- broccoli/jquery.js | 13 ++- src/js/commands/card.js | 4 +- src/js/commands/format-block.js | 4 +- src/js/commands/image.js | 4 +- src/js/commands/oembed.js | 8 +- src/js/editor/editor.js | 32 +++++-- src/js/views/view.js | 4 + tests/acceptance/basic-editor-test.js | 4 +- tests/acceptance/editor-commands-test.js | 115 +++++++++++++++++++++++ tests/helpers/assertions.js | 15 +++ tests/helpers/dom.js | 106 +++++++++++++++++++++ tests/index.html | 9 ++ tests/test-helpers.js | 15 ++- tests/unit/editor/editor-destroy-test.js | 32 +++++++ tests/unit/editor/editor-test.js | 14 +-- 16 files changed, 348 insertions(+), 35 deletions(-) create mode 100644 tests/acceptance/editor-commands-test.js create mode 100644 tests/helpers/assertions.js create mode 100644 tests/helpers/dom.js create mode 100644 tests/unit/editor/editor-destroy-test.js diff --git a/Brocfile.js b/Brocfile.js index 9b60bb4e6..42db94a37 100644 --- a/Brocfile.js +++ b/Brocfile.js @@ -18,10 +18,10 @@ var buildOptions = { packageName: packageName }; -var jqueryTree = jquery.build('/demo/jquery'); var testTree = testTreeBuilder.build({libDirName: 'src'}); +testTree = jquery.build(testTree, '/tests/jquery'); var demoTree = demo(); -demoTree = mergeTrees([demoTree, jqueryTree]); +demoTree = jquery.build(demoTree, '/demo/jquery'); module.exports = mergeTrees([ builder.build('amd', buildOptions), diff --git a/broccoli/jquery.js b/broccoli/jquery.js index 7127020a7..306325f97 100644 --- a/broccoli/jquery.js +++ b/broccoli/jquery.js @@ -1,17 +1,22 @@ /* jshint node:true */ var funnel = require('broccoli-funnel'); +var mergeTrees = require('broccoli-merge-trees'); module.exports = { - build: function(destDir) { + /** + * @param {Tree} tree existing tree to mix jquery into + * @param {String} destDir the destination directory for 'jquery.js' to go into + * @return {Tree} A tree with jquery mixed into it at the location requested + */ + build: function(tree, destDir) { var path = require('path'); var jqueryPath = path.dirname( require.resolve('jquery') ); - var tree = funnel(jqueryPath, { + var jqueryTree = funnel(jqueryPath, { include: ['jquery.js'], destDir: destDir }); - - return tree; + return mergeTrees([tree, jqueryTree]); } }; diff --git a/src/js/commands/card.js b/src/js/commands/card.js index 00422eed9..525f3d101 100644 --- a/src/js/commands/card.js +++ b/src/js/commands/card.js @@ -1,9 +1,10 @@ import Command from './base'; import { inherit } from 'content-kit-utils'; -function injectCardBlock(cardName, cardPayload, editor, index) { +function injectCardBlock(/* cardName, cardPayload, editor, index */) { throw new Error('Unimplemented: BlockModel and Type.CARD are no longer things'); // FIXME: Do we change the block model internal representation here? + /* var cardBlock = BlockModel.createWithType(Type.CARD, { attributes: { name: cardName, @@ -11,6 +12,7 @@ function injectCardBlock(cardName, cardPayload, editor, index) { } }); editor.replaceBlock(cardBlock, index); + */ } function CardCommand() { diff --git a/src/js/commands/format-block.js b/src/js/commands/format-block.js index 47fc11de2..01b2d38fe 100644 --- a/src/js/commands/format-block.js +++ b/src/js/commands/format-block.js @@ -17,7 +17,9 @@ FormatBlockCommand.prototype.exec = function() { // Allow block commands to be toggled back to a text block if(tag === blockElement.tagName.toLowerCase()) { throw new Error('Unimplemented: Type.BOLD.paragraph must be replaced'); + /* value = Type.PARAGRAPH.tag; + */ } else { // Flattens the selection before applying the block format. // Otherwise, undesirable nested blocks can occur. @@ -27,7 +29,7 @@ FormatBlockCommand.prototype.exec = function() { blockElement.parentNode.removeChild(blockElement); selectNode(flatNode); } - + FormatBlockCommand._super.prototype.exec.call(this, value); }; diff --git a/src/js/commands/image.js b/src/js/commands/image.js index 3b61fd432..846866be1 100644 --- a/src/js/commands/image.js +++ b/src/js/commands/image.js @@ -14,10 +14,12 @@ function createFileInput(command) { return fileInput; } -function injectImageBlock(src, editor, index) { +function injectImageBlock(/* src, editor, index */) { throw new Error('Unimplemented: BlockModel and Type.IMAGE are no longer things'); + /* var imageModel = BlockModel.createWithType(Type.IMAGE, { attributes: { src: src } }); editor.replaceBlock(imageModel, index); + */ } function renderFromFile(file, editor, index) { diff --git a/src/js/commands/oembed.js b/src/js/commands/oembed.js index 5d3b2da5f..1ec9b9d03 100644 --- a/src/js/commands/oembed.js +++ b/src/js/commands/oembed.js @@ -4,6 +4,7 @@ import Message from '../views/message'; import { inherit } from 'content-kit-utils'; import { OEmbedder } from '../utils/http-utils'; +/* function loadTwitterWidgets(element) { if (window.twttr) { window.twttr.widgets.load(element); @@ -14,6 +15,7 @@ function loadTwitterWidgets(element) { document.head.appendChild(script); } } +*/ function OEmbedCommand(options) { Command.call(this, { @@ -31,9 +33,9 @@ inherit(OEmbedCommand, Command); OEmbedCommand.prototype.exec = function(url) { var command = this; - var editorContext = command.editorContext; + // var editorContext = command.editorContext; var embedIntent = command.embedIntent; - var index = editorContext.getCurrentBlockIndex(); + // var index = editorContext.getCurrentBlockIndex(); embedIntent.showLoading(); this.embedService.fetch({ @@ -54,12 +56,14 @@ OEmbedCommand.prototype.exec = function(url) { embedIntent.show(); } else { throw new Error('Unimplemented EmbedModel is not a thing'); + /* var embedModel = new EmbedModel(response); editorContext.insertBlock(embedModel, index); editorContext.renderBlockAt(index); if (embedModel.attributes.provider_name.toLowerCase() === 'twitter') { loadTwitterWidgets(editorContext.element); } + */ } } }); diff --git a/src/js/editor/editor.js b/src/js/editor/editor.js index d9c66262e..4c788b388 100644 --- a/src/js/editor/editor.js +++ b/src/js/editor/editor.js @@ -124,14 +124,15 @@ function bindDragAndDrop(editor) { function initEmbedCommands(editor) { var commands = editor.embedCommands; if(commands) { - return new EmbedIntent({ + editor.addView(new EmbedIntent({ editorContext: editor, commands: commands, rootElement: editor.element - }); + })); } } +/* unused function getNonTextBlocks(blockTypeSet, post) { var blocks = []; var len = post.length; @@ -145,6 +146,7 @@ function getNonTextBlocks(blockTypeSet, post) { } return blocks; } +*/ function clearChildNodes(element) { while (element.childNodes.length) { @@ -165,12 +167,13 @@ function Editor(element, options) { } this._elementListeners = []; + this._views = []; this.element = element; // FIXME: This should merge onto this.options mergeWithOptions(this, defaults, options); - this._renderer = new EditorDOMRenderer(window.document, this.cards) + this._renderer = new EditorDOMRenderer(window.document, this.cards); this._parser = new DOMParser(); this.applyClassName(); @@ -196,16 +199,16 @@ function Editor(element, options) { this.addEventListener(element, 'input', () => this.handleInput(...arguments)); initEmbedCommands(this); - this.textFormatToolbar = new TextFormatToolbar({ + this.addView(new TextFormatToolbar({ rootElement: element, commands: this.textFormatCommands, sticky: this.stickyToolbar - }); + })); - this.linkTooltips = new Tooltip({ + this.addView(new Tooltip({ rootElement: element, showForTag: 'a' - }); + })); if (this.autofocus) { element.focus(); @@ -216,6 +219,9 @@ function Editor(element, options) { merge(Editor.prototype, EventEmitter); merge(Editor.prototype, { + addView(view) { + this._views.push(view); + }, addEventListener(context, eventName, callback) { context.addEventListener(eventName, callback); @@ -271,8 +277,9 @@ merge(Editor.prototype, { this.trigger('update'); }, - renderBlockAt(index, replace) { + renderBlockAt(/* index, replace */) { throw new Error('Unimplemented'); + /* var modelAtIndex = this.post[index]; var html = this.compiler.render([modelAtIndex]); var dom = document.createElement('div'); @@ -285,10 +292,12 @@ merge(Editor.prototype, { } else { this.element.insertBefore(newEl, sibling); } + */ }, syncContentEditableBlocks() { throw new Error('Unimplemented'); + /* var nonTextBlocks = getNonTextBlocks(this.compiler.blockTypes, this.post); var blockElements = toArray(this.element.children); var len = blockElements.length; @@ -309,6 +318,7 @@ merge(Editor.prototype, { } this.post = updatedModel; this.trigger('update'); + */ }, applyClassName() { @@ -426,8 +436,14 @@ merge(Editor.prototype, { }); }, + removeAllViews() { + this._views.forEach((v) => v.destroy()); + this._views = []; + }, + destroy() { this.removeAllEventListeners(); + this.removeAllViews(); } }); diff --git a/src/js/views/view.js b/src/js/views/view.js index 09970877e..d11537218 100644 --- a/src/js/views/view.js +++ b/src/js/views/view.js @@ -51,6 +51,10 @@ View.prototype = { setClasses: function(classNameArr) { this.classNames = classNameArr; renderClasses(this); + }, + destroy() { + // FIXME should also clean up event listeners + this.hide(); } }; diff --git a/tests/acceptance/basic-editor-test.js b/tests/acceptance/basic-editor-test.js index f66732273..8638cd04f 100644 --- a/tests/acceptance/basic-editor-test.js +++ b/tests/acceptance/basic-editor-test.js @@ -1,7 +1,7 @@ /* global QUnit */ import { Editor } from 'content-kit-editor'; -import { moveCursorTo } from '../test-helpers'; +import Helpers from '../test-helpers'; const { test, module } = QUnit; @@ -38,7 +38,7 @@ test('editing element changes editor post model', (assert) => { let p = editorElement.querySelector('p'); let textElement = p.firstChild; - moveCursorTo(textElement, 0); + Helpers.dom.moveCursorTo(textElement, 0); document.execCommand('insertText', false, 'A'); assert.equal(p.textContent, 'AHello'); diff --git a/tests/acceptance/editor-commands-test.js b/tests/acceptance/editor-commands-test.js new file mode 100644 index 000000000..2adceefc4 --- /dev/null +++ b/tests/acceptance/editor-commands-test.js @@ -0,0 +1,115 @@ +import { Editor } from 'content-kit-editor'; +import Helpers from '../test-helpers'; + +const { test, module } = QUnit; + +let fixture, editor, editorElement, selectedText; + +module('Acceptance: Editor commands', { + beforeEach() { + fixture = document.getElementById('qunit-fixture'); + editorElement = document.createElement('div'); + editorElement.setAttribute('id', 'editor'); + editorElement.innerHTML = 'THIS IS A TEST'; + fixture.appendChild(editorElement); + editor = new Editor(editorElement); + + selectedText = 'IS A'; + Helpers.dom.selectText(selectedText, editorElement); + Helpers.dom.triggerEvent(document, 'mouseup'); + }, + + afterEach() { + editor.destroy(); + } +}); + +function clickToolbarButton(name, assert) { + let btnSelector = `.ck-toolbar-btn[title="${name}"]`; + let button = assert.hasElement(btnSelector); + + Helpers.dom.triggerEvent(button[0], 'mouseup'); +} + +test('when text is highlighted, shows toolbar', (assert) => { + let done = assert.async(); + + setTimeout(() => { + assert.hasElement('.ck-toolbar', 'displays toolbar'); + assert.hasElement('.ck-toolbar-btn', 'displays toolbar buttons'); + let boldBtnSelector = '.ck-toolbar-btn[title="bold"]'; + assert.hasElement(boldBtnSelector, 'has bold button'); + done(); + }, 10); +}); + +test('highlight text, click "bold" button bolds text', (assert) => { + let done = assert.async(); + + setTimeout(() => { + clickToolbarButton('bold', assert); + assert.hasElement('#editor b:contains(IS A)'); + + done(); + }, 10); +}); + +test('highlight text, click "italic" button italicizes text', (assert) => { + let done = assert.async(); + + setTimeout(() => { + clickToolbarButton('italic', assert); + assert.hasElement('#editor i:contains(IS A)'); + + done(); + }, 10); +}); + +test('highlight text, click "heading" button turns text into h2 header', (assert) => { + let done = assert.async(); + + setTimeout(() => { + clickToolbarButton('heading', assert); + assert.hasElement('#editor h2:contains(THIS IS A TEST)'); + + done(); + }, 10); +}); + +test('highlight text, click "subheading" button turns text into h3 header', (assert) => { + let done = assert.async(); + + setTimeout(() => { + clickToolbarButton('subheading', assert); + assert.hasElement('#editor h3:contains(THIS IS A TEST)'); + + done(); + }, 10); +}); + +test('highlight text, click "quote" button turns text into blockquote', (assert) => { + let done = assert.async(); + + setTimeout(() => { + clickToolbarButton('quote', assert); + assert.hasElement('#editor blockquote:contains(THIS IS A TEST)'); + + done(); + }, 10); +}); + +test('highlight text, click "link" button shows input for URL, makes link', (assert) => { + let done = assert.async(); + + setTimeout(() => { + clickToolbarButton('link', assert); + let input = assert.hasElement('.ck-toolbar-prompt input'); + let url = 'http://google.com'; + $(input).val(url); + Helpers.dom.triggerKeyEvent(input[0], 'keyup'); + + assert.hasElement(`#editor a[href="${url}"]:contains(${selectedText})`); + + done(); + }, 10); +}); diff --git a/tests/helpers/assertions.js b/tests/helpers/assertions.js new file mode 100644 index 000000000..c2c8a79b7 --- /dev/null +++ b/tests/helpers/assertions.js @@ -0,0 +1,15 @@ +/* global QUnit, $ */ + +export default function registerAssertions() { + QUnit.assert.hasElement = function(selector, message=`hasElement "${selector}"`) { + let found = $(selector); + this.push(found.length > 0, found.length, selector, message); + return found; + }; + + QUnit.assert.hasNoElement = function(selector, message=`hasNoElement "${selector}"`) { + let found = $(selector); + this.push(found.length === 0, found.length, selector, message); + return found; + }; +} diff --git a/tests/helpers/dom.js b/tests/helpers/dom.js new file mode 100644 index 000000000..6150a01f0 --- /dev/null +++ b/tests/helpers/dom.js @@ -0,0 +1,106 @@ +const TEXT_NODE = 3; + +function moveCursorTo(element, offset) { + let range = document.createRange(); + range.setStart(element, offset); + range.setEnd(element, offset); + + let selection = window.getSelection(); + selection.removeAllRanges(); + selection.addRange(range); +} + + +function walkDOMUntil(topNode, conditionFn=() => {}) { + let stack = [topNode]; + let currentElement; + + while (stack.length) { + currentElement = stack.pop(); + + if (conditionFn(currentElement)) { + return currentElement; + } + + for (let i=0; i < currentElement.childNodes.length; i++) { + stack.push(currentElement.childNodes[i]); + } + if (currentElement.nextSibling) { + stack.push(currentElement.nextSibling); + } + } +} + + +function selectText(text, containingElement) { + let textNode = walkDOMUntil(containingElement, (el) => { + if (el.nodeType !== TEXT_NODE) { return; } + + return el.textContent.indexOf(text) !== -1; + }); + if (!textNode) { + throw new Error(`Could not find a textNode containing "${text}"`); + } + let range = document.createRange(); + let startOffset = textNode.textContent.indexOf(text), + endOffset = startOffset + text.length; + range.setStart(textNode, startOffset); + range.setEnd(textNode, endOffset); + + let selection = window.getSelection(); + if (selection.rangeCount > 0) { selection.removeAllRanges(); } + selection.addRange(range); +} + +function triggerEvent(node, eventType) { + if (!node) { throw new Error(`Attempted to trigger event "${eventType}" on undefined node`); } + + let clickEvent = document.createEvent('MouseEvents'); + clickEvent.initEvent(eventType, true, true); + node.dispatchEvent(clickEvent); +} + +// see https://gist.github.com/ejoubaud/7d7c57cda1c10a4fae8c +function createKeyEvent(eventType, key) { + var oEvent = document.createEvent('KeyboardEvent'); + + // Chromium Hack + Object.defineProperty(oEvent, 'keyCode', { + get : function() { + return this.keyCodeVal; + } + }); + Object.defineProperty(oEvent, 'which', { + get : function() { + return this.keyCodeVal; + } + }); + + if (oEvent.initKeyboardEvent) { + oEvent.initKeyboardEvent(eventType, true, true, document.defaultView, key, key, "", "", false, ""); + } else { + oEvent.initKeyEvent(eventType, true, true, document.defaultView, false, false, false, false, key, 0); + } + + oEvent.keyCodeVal = key; + + if (oEvent.keyCode !== key) { + throw new Error("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")"); + } + + return oEvent; +} + +const ENTER_KEY_CODE = 13; +function triggerKeyEvent(node, eventType, keyCode=ENTER_KEY_CODE) { + let event = createKeyEvent('keyup', keyCode); + + node.dispatchEvent(event); +} + +export default { + moveCursorTo, + selectText, + triggerEvent, + triggerKeyEvent +}; diff --git a/tests/index.html b/tests/index.html index f3801d952..164b81c8a 100644 --- a/tests/index.html +++ b/tests/index.html @@ -4,6 +4,15 @@ Content-Kit-Editor tests + diff --git a/tests/test-helpers.js b/tests/test-helpers.js index 33df62a9a..4c72d16ff 100644 --- a/tests/test-helpers.js +++ b/tests/test-helpers.js @@ -1,9 +1,8 @@ -export function moveCursorTo(element, offset) { - let range = document.createRange(); - range.setStart(element, offset); - range.setEnd(element, offset); +import registerAssertions from './helpers/assertions'; +registerAssertions(); - let selection = window.getSelection(); - selection.removeAllRanges(); - selection.addRange(range); -} +import DOMHelpers from './helpers/dom'; + +export default { + dom: DOMHelpers +}; diff --git a/tests/unit/editor/editor-destroy-test.js b/tests/unit/editor/editor-destroy-test.js new file mode 100644 index 000000000..903dd4afb --- /dev/null +++ b/tests/unit/editor/editor-destroy-test.js @@ -0,0 +1,32 @@ +const { module, test } = window.QUnit; +import Helpers from '../../test-helpers'; + +import { Editor } from 'content-kit-editor'; + +let editor; +let fixture; + +module('Unit: Editor #destroy', { + beforeEach() { + fixture = $('#qunit-fixture'); + fixture.html('the editor'); + editor = new Editor(fixture[0]); + }, + afterEach() { + } +}); + +test('removes toolbar from DOM', (assert) => { + let done = assert.async(); + + Helpers.dom.selectText('the editor', fixture[0]); + Helpers.dom.triggerEvent(document, 'mouseup'); + + setTimeout(() => { + assert.hasElement('.ck-toolbar', 'toolbar is shown'); + editor.destroy(); + assert.hasNoElement('.ck-toolbar', 'toolbar is removed'); + + done(); + }); +}); diff --git a/tests/unit/editor/editor-test.js b/tests/unit/editor/editor-test.js index f45b66bb0..86f05e7ca 100644 --- a/tests/unit/editor/editor-test.js +++ b/tests/unit/editor/editor-test.js @@ -1,5 +1,6 @@ -var fixture = document.getElementById('qunit-fixture'); -var editorElement = document.createElement('div'); +let fixture = document.getElementById('qunit-fixture'); +let editorElement = document.createElement('div'); +let editor; editorElement.id = 'editor1'; editorElement.className = 'editor'; @@ -8,21 +9,22 @@ import Editor from 'content-kit-editor/editor/editor'; const { module, test } = window.QUnit; module('Unit: Editor', { - setup: function() { + beforeEach: function() { fixture.appendChild(editorElement); }, - teardown: function() { + afterEach: function() { + editor.destroy(); fixture.removeChild(editorElement); } }); test('can create an editor via dom node reference', (assert) => { - var editor = new Editor(editorElement); + editor = new Editor(editorElement); assert.equal(editor.element, editorElement); }); test('can create an editor via dom node reference from getElementById', (assert) => { - var editor = new Editor(document.getElementById('editor1')); + editor = new Editor(document.getElementById('editor1')); assert.equal(editor.element, editorElement); }); From 7557d43622dd05b942c3da4e252fadd9761c407a Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Mon, 13 Jul 2015 13:24:27 -0400 Subject: [PATCH 51/77] skip link test in phantomjs --- tests/acceptance/basic-editor-test.js | 3 +- tests/acceptance/editor-commands-test.js | 10 ++++++ tests/helpers/dom.js | 45 ++++++++++-------------- tests/unit/editor/editor-destroy-test.js | 1 - 4 files changed, 30 insertions(+), 29 deletions(-) diff --git a/tests/acceptance/basic-editor-test.js b/tests/acceptance/basic-editor-test.js index 8638cd04f..a840e7517 100644 --- a/tests/acceptance/basic-editor-test.js +++ b/tests/acceptance/basic-editor-test.js @@ -1,5 +1,3 @@ -/* global QUnit */ - import { Editor } from 'content-kit-editor'; import Helpers from '../test-helpers'; @@ -15,6 +13,7 @@ module('Acceptance: basic editor', { fixture.appendChild(editorElement); }, afterEach() { + editor.destroy(); } }); diff --git a/tests/acceptance/editor-commands-test.js b/tests/acceptance/editor-commands-test.js index 2adceefc4..14d0235a1 100644 --- a/tests/acceptance/editor-commands-test.js +++ b/tests/acceptance/editor-commands-test.js @@ -39,6 +39,7 @@ test('when text is highlighted, shows toolbar', (assert) => { assert.hasElement('.ck-toolbar-btn', 'displays toolbar buttons'); let boldBtnSelector = '.ck-toolbar-btn[title="bold"]'; assert.hasElement(boldBtnSelector, 'has bold button'); + done(); }, 10); }); @@ -102,6 +103,15 @@ test('highlight text, click "link" button shows input for URL, makes link', (ass let done = assert.async(); setTimeout(() => { + // FIXME PhantomJS doesn't create keyboard events properly (they have no keyCode or which) + // see https://bugs.webkit.org/show_bug.cgi?id=36423 + let skippable = navigator.userAgent.indexOf('PhantomJS') !== -1; + if (skippable) { + assert.ok(true, 'Skipping test in phantomjs'); + done(); + return; + } + clickToolbarButton('link', assert); let input = assert.hasElement('.ck-toolbar-prompt input'); let url = 'http://google.com'; diff --git a/tests/helpers/dom.js b/tests/helpers/dom.js index 6150a01f0..3ed2b525a 100644 --- a/tests/helpers/dom.js +++ b/tests/helpers/dom.js @@ -1,4 +1,5 @@ const TEXT_NODE = 3; +const ENTER_KEY_CODE = 13; function moveCursorTo(element, offset) { let range = document.createRange(); @@ -60,42 +61,34 @@ function triggerEvent(node, eventType) { node.dispatchEvent(clickEvent); } -// see https://gist.github.com/ejoubaud/7d7c57cda1c10a4fae8c -function createKeyEvent(eventType, key) { - var oEvent = document.createEvent('KeyboardEvent'); - - // Chromium Hack - Object.defineProperty(oEvent, 'keyCode', { - get : function() { - return this.keyCodeVal; - } - }); - Object.defineProperty(oEvent, 'which', { - get : function() { - return this.keyCodeVal; - } - }); - +function createKeyEvent(eventType, keyCode=ENTER_KEY_CODE) { + let oEvent = document.createEvent('KeyboardEvent'); if (oEvent.initKeyboardEvent) { - oEvent.initKeyboardEvent(eventType, true, true, document.defaultView, key, key, "", "", false, ""); - } else { - oEvent.initKeyEvent(eventType, true, true, document.defaultView, false, false, false, false, key, 0); + oEvent.initKeyboardEvent(eventType, true, true, window, 0, 0, 0, 0, 0, keyCode); + } else if (oEvent.initKeyEvent) { + oEvent.initKeyEvent(eventType, true, true, window, 0, 0, 0, 0, 0, keyCode); } - oEvent.keyCodeVal = key; + // Hack for Chrome to force keyCode/which value + try { + Object.defineProperty(oEvent, 'keyCode', {get: function() { return keyCode; }}); + Object.defineProperty(oEvent, 'which', {get: function() { return keyCode; }}); + } catch(e) { + // FIXME + // PhantomJS/webkit will throw an error "ERROR: Attempting to change access mechanism for an unconfigurable property" + // see https://bugs.webkit.org/show_bug.cgi?id=36423 + } - if (oEvent.keyCode !== key) { - throw new Error("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")"); + if (oEvent.keyCode !== keyCode || oEvent.which !== keyCode) { + throw new Error(`Failed to create key event with keyCode ${keyCode}. \`keyCode\`: ${oEvent.keyCode}, \`which\`: ${oEvent.which}`); } return oEvent; } -const ENTER_KEY_CODE = 13; function triggerKeyEvent(node, eventType, keyCode=ENTER_KEY_CODE) { - let event = createKeyEvent('keyup', keyCode); - - node.dispatchEvent(event); + let oEvent = createKeyEvent(eventType, keyCode); + node.dispatchEvent(oEvent); } export default { diff --git a/tests/unit/editor/editor-destroy-test.js b/tests/unit/editor/editor-destroy-test.js index 903dd4afb..05435cd63 100644 --- a/tests/unit/editor/editor-destroy-test.js +++ b/tests/unit/editor/editor-destroy-test.js @@ -26,7 +26,6 @@ test('removes toolbar from DOM', (assert) => { assert.hasElement('.ck-toolbar', 'toolbar is shown'); editor.destroy(); assert.hasNoElement('.ck-toolbar', 'toolbar is removed'); - done(); }); }); From 6e30ac8f5da89973f6aaeb8daa9f47752711a776 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Mon, 13 Jul 2015 15:58:24 -0400 Subject: [PATCH 52/77] Use phantomjs at travis --- .travis.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index cc63c5c69..b4fff81b4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,7 +10,11 @@ cache: - node_modules before_install: - - export PATH=/usr/local/phantomjs-2.0.0/bin:$PATH + # See https://mediocre.com/forum/topics/phantomjs-2-and-travis-ci-we-beat-our-heads-against-a-wall-so-you-dont-have-to + # modified to not use sudo (just puts $PWD on the path so that $PWD/phantomjs is the phantom used + - wget https://s3.amazonaws.com/travis-phantomjs/phantomjs-2.0.0-ubuntu-12.04.tar.bz2 + - tar -xjf phantomjs-2.0.0-ubuntu-12.04.tar.bz2 + - export PATH=$PWD:$PATH - "npm config set spin false" - "npm install -g npm@^2" From 9d9a530d44bc73d82405a09e3b3129618a420a5d Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Mon, 13 Jul 2015 19:33:04 -0400 Subject: [PATCH 53/77] compatibility fixes for IE10 --- src/js/editor/editor.js | 11 ++++++----- src/js/utils/element-utils.js | 22 ++++++++++++++++++++++ src/js/utils/event-emitter.js | 2 +- src/js/utils/string-utils.js | 11 +++++++++++ 4 files changed, 40 insertions(+), 6 deletions(-) create mode 100644 src/js/utils/string-utils.js diff --git a/src/js/editor/editor.js b/src/js/editor/editor.js index 4c788b388..3ea0e029e 100644 --- a/src/js/editor/editor.js +++ b/src/js/editor/editor.js @@ -25,6 +25,7 @@ import MobiledocRenderer from '../renderers/mobiledoc'; import { toArray, merge, mergeWithOptions } from 'content-kit-utils'; import { detectParentNode } from '../utils/dom-utils'; +import { getData, setData } from '../utils/element-utils'; var defaults = { placeholder: 'Write here...', @@ -150,11 +151,10 @@ function getNonTextBlocks(blockTypeSet, post) { function clearChildNodes(element) { while (element.childNodes.length) { - element.childNodes[0].remove(); + element.removeChild(element.childNodes[0]); } } - /** * @class Editor * An individual Editor @@ -333,10 +333,11 @@ merge(Editor.prototype, { }, applyPlaceholder() { - var dataset = this.element.dataset; const placeholder = this.placeholder; - if (placeholder && !dataset.placeholder) { - dataset.placeholder = placeholder; + const existingPlaceholder = getData(this.element, 'placeholder'); + + if (placeholder && !existingPlaceholder) { + setData(this.element, 'placeholder', placeholder); } }, diff --git a/src/js/utils/element-utils.js b/src/js/utils/element-utils.js index 15ce55dff..b4903fa9d 100644 --- a/src/js/utils/element-utils.js +++ b/src/js/utils/element-utils.js @@ -1,3 +1,5 @@ +import { dasherize } from 'content-kit-editor/utils/string-utils'; + function createDiv(className) { var div = document.createElement('div'); if (className) { @@ -114,7 +116,27 @@ function positionElementToRightOf(element, rightOfElement) { return positionElementToRect(element, rightOfElementRect, -verticalCenter, -rightOfElement.offsetWidth - elementMargin); } +function getData(element, name) { + if (element.dataset) { + return element.dataset[name]; + } else { + const dataName = dasherize(name); + return element.getAttribute(dataName); + } +} + +function setData(element, name, value) { + if (element.dataset) { + element.dataset[name] = value; + } else { + const dataName = dasherize(name); + return element.setAttribute(dataName, value); + } +} + export { + getData, + setData, createDiv, hideElement, showElement, diff --git a/src/js/utils/event-emitter.js b/src/js/utils/event-emitter.js index 4941add6a..7518555fe 100644 --- a/src/js/utils/event-emitter.js +++ b/src/js/utils/event-emitter.js @@ -25,4 +25,4 @@ var EventEmitter = { } }; -export default EventEmitter; \ No newline at end of file +export default EventEmitter; diff --git a/src/js/utils/string-utils.js b/src/js/utils/string-utils.js new file mode 100644 index 000000000..20b2f88b5 --- /dev/null +++ b/src/js/utils/string-utils.js @@ -0,0 +1,11 @@ +/* + * @param {String} string + * @return {String} a dasherized string. 'modelIndex' -> 'model-index', etc + */ +export function dasherize(string) { + return string.replace(/[A-Z]/g, (match, offset) => { + const lower = match.toLowerCase(); + + return (offset === 0 ? lower : '-' + lower); + }); +} From 2839ce561cd7ebdffbc5b3d6127297401998fed5 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Mon, 13 Jul 2015 19:02:42 -0400 Subject: [PATCH 54/77] Use custom IE flexbox CSS for demo --- demo/demo.css | 3 +++ 1 file changed, 3 insertions(+) diff --git a/demo/demo.css b/demo/demo.css index 8a448f606..9a8592e25 100644 --- a/demo/demo.css +++ b/demo/demo.css @@ -18,7 +18,10 @@ body { } .container { + display: -ms-flexbox; display: flex; + + -ms-flex-pack: justify; justify-content: space-around; } From 9ef8f5957e7cfb3194fa833f5645bd248e1eebb9 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Mon, 13 Jul 2015 18:17:26 -0400 Subject: [PATCH 55/77] use EventListener mixin to ensure listeners are destroyed by views --- src/js/commands/image.js | 1 + src/js/editor/editor.js | 16 ++--- src/js/utils/event-listener.js | 14 +++++ src/js/utils/mixin.js | 14 +++++ src/js/views/embed-intent.js | 15 +++-- src/js/views/prompt.js | 94 ++++++++++++++++------------- src/js/views/text-format-toolbar.js | 10 +-- src/js/views/toolbar-button.js | 6 +- src/js/views/toolbar.js | 2 +- src/js/views/tooltip.js | 4 +- src/js/views/view.js | 53 +++++++++------- 11 files changed, 139 insertions(+), 90 deletions(-) create mode 100644 src/js/utils/event-listener.js create mode 100644 src/js/utils/mixin.js diff --git a/src/js/commands/image.js b/src/js/commands/image.js index 846866be1..1f0a5e553 100644 --- a/src/js/commands/image.js +++ b/src/js/commands/image.js @@ -8,6 +8,7 @@ function createFileInput(command) { fileInput.type = 'file'; fileInput.accept = 'image/*'; fileInput.className = 'ck-file-input'; + // FIXME should this listener be torn down when the ImageCommand is not active? fileInput.addEventListener('change', function(e) { command.handleFile(e); }); diff --git a/src/js/editor/editor.js b/src/js/editor/editor.js index 3ea0e029e..1d175e365 100644 --- a/src/js/editor/editor.js +++ b/src/js/editor/editor.js @@ -26,6 +26,8 @@ import MobiledocRenderer from '../renderers/mobiledoc'; import { toArray, merge, mergeWithOptions } from 'content-kit-utils'; import { detectParentNode } from '../utils/dom-utils'; import { getData, setData } from '../utils/element-utils'; +import mixin from '../utils/mixin'; +import EventListenerMixin from '../utils/event-listener'; var defaults = { placeholder: 'Write here...', @@ -223,11 +225,6 @@ merge(Editor.prototype, { this._views.push(view); }, - addEventListener(context, eventName, callback) { - context.addEventListener(eventName, callback); - this._elementListeners.push([context, eventName, callback]); - }, - loadModel(post) { this.post = post; this.syncVisual(); @@ -431,12 +428,6 @@ merge(Editor.prototype, { return MobiledocRenderer.render(this.post); }, - removeAllEventListeners() { - this._elementListeners.forEach(([context, ...args]) => { - context.removeEventListener(...args); - }); - }, - removeAllViews() { this._views.forEach((v) => v.destroy()); this._views = []; @@ -446,7 +437,8 @@ merge(Editor.prototype, { this.removeAllEventListeners(); this.removeAllViews(); } - }); +mixin(Editor, EventListenerMixin); + export default Editor; diff --git a/src/js/utils/event-listener.js b/src/js/utils/event-listener.js new file mode 100644 index 000000000..aac0b8151 --- /dev/null +++ b/src/js/utils/event-listener.js @@ -0,0 +1,14 @@ +export default class EventListenerMixin { + addEventListener(context, eventName, listener) { + if (!this._eventListeners) { this._eventListeners = []; } + context.addEventListener(eventName, listener); + this._eventListeners.push([context, eventName, listener]); + } + + removeAllEventListeners() { + const listeners = this._eventListeners || []; + listeners.forEach(([context, ...args]) => { + context.removeEventListener(...args); + }); + } +} diff --git a/src/js/utils/mixin.js b/src/js/utils/mixin.js new file mode 100644 index 000000000..3bce8b88e --- /dev/null +++ b/src/js/utils/mixin.js @@ -0,0 +1,14 @@ +const CONSTRUCTOR_FN_NAME = 'constructor'; + +export default function mixin(target, source) { + target = target.prototype; + source = source.prototype; + + Object.getOwnPropertyNames(source).forEach((name) => { + if (name !== CONSTRUCTOR_FN_NAME) { + const descriptor = Object.getOwnPropertyDescriptor(source, name); + + Object.defineProperty(target, name, descriptor); + } + }); +} diff --git a/src/js/views/embed-intent.js b/src/js/views/embed-intent.js index 06754d67e..2344b0576 100644 --- a/src/js/views/embed-intent.js +++ b/src/js/views/embed-intent.js @@ -31,7 +31,8 @@ function EmbedIntent(options) { embedIntent.button.className = 'ck-embed-intent-btn'; embedIntent.button.title = 'Insert image or embed...'; embedIntent.element.appendChild(embedIntent.button); - embedIntent.button.addEventListener('mouseup', function(e) { + + this.addEventListener(embedIntent.button, 'mouseup', (e) => { if (embedIntent.isActive) { embedIntent.deactivate(); } else { @@ -57,18 +58,20 @@ function EmbedIntent(options) { } } - rootElement.addEventListener('keyup', embedIntentHandler); - document.addEventListener('mouseup', function() { - setTimeout(function() { embedIntentHandler(); }); + this.addEventListener(rootElement, 'keyup', embedIntentHandler); + this.addEventListener(document, 'mouseup', () => { + setTimeout(() => { + embedIntentHandler(); + }); }); - document.addEventListener('keyup', function(e) { + this.addEventListener(document, 'keyup', (e) => { if (e.keyCode === Keycodes.ESC) { embedIntent.hide(); } }); - window.addEventListener('resize', function() { + this.addEventListener(window, 'resize', () => { if(embedIntent.isShowing) { embedIntent.reposition(); } diff --git a/src/js/views/prompt.js b/src/js/views/prompt.js index bb0eecda4..eb97a935e 100644 --- a/src/js/views/prompt.js +++ b/src/js/views/prompt.js @@ -1,5 +1,4 @@ import View from './view'; -import { inherit } from 'content-kit-utils'; import { restoreRange } from '../utils/selection-utils'; import { createDiv, positionElementToRect } from '../utils/element-utils'; import Keycodes from '../utils/keycodes'; @@ -15,52 +14,63 @@ function positionHiliteRange(range) { positionElementToRect(hiliter, rect); } -function Prompt(options) { - var prompt = this; - options.tagName = 'input'; - View.call(prompt, options); +class Prompt extends View { + constructor(options) { + options.tagName = 'input'; + super(options); - prompt.command = options.command; - prompt.element.placeholder = options.placeholder || ''; - prompt.element.addEventListener('mouseup', function(e) { e.stopPropagation(); }); // prevents closing prompt when clicking input - prompt.element.addEventListener('keyup', function(e) { - var entry = this.value; - if(entry && prompt.range && !e.shiftKey && e.which === Keycodes.ENTER) { - restoreRange(prompt.range); - prompt.command.exec(entry); - if (prompt.onComplete) { prompt.onComplete(); } - } - }); + var prompt = this; - window.addEventListener('resize', function() { - var activeHilite = hiliter.parentNode; - var range = prompt.range; - if(activeHilite && range) { - positionHiliteRange(range); - } - }); -} -inherit(Prompt, View); + prompt.command = options.command; + prompt.element.placeholder = options.placeholder || ''; + this.addEventListener(prompt.element, 'mouseup', (e) => { + // prevents closing prompt when clicking input + e.stopPropagation(); + }); + this.addEventListener(prompt.element, 'keyup', (e) => { + const entry = prompt.element.value; + + if (entry && prompt.range && !e.shiftKey && e.which === Keycodes.ENTER) { + restoreRange(prompt.range); + this.command.exec(entry); + if (this.onComplete) { this.onComplete(); } + } + }); + + this.addEventListener(window, 'resize', () => { + var activeHilite = hiliter.parentNode; + var range = prompt.range; + if(activeHilite && range) { + positionHiliteRange(range); + } + }); + } + + show(callback) { + var element = this.element; + var selection = window.getSelection(); + var range = selection && selection.rangeCount && selection.getRangeAt(0); + element.value = null; + this.range = range || null; -Prompt.prototype.show = function(callback) { - var prompt = this; - var element = prompt.element; - var selection = window.getSelection(); - var range = selection && selection.rangeCount && selection.getRangeAt(0); - element.value = null; - prompt.range = range || null; - if (range) { - container.appendChild(hiliter); - positionHiliteRange(prompt.range); - setTimeout(function(){ element.focus(); }); // defer focus (disrupts mouseup events) - if (callback) { prompt.onComplete = callback; } + if (range) { + container.appendChild(hiliter); + positionHiliteRange(this.range); + setTimeout(() => { + // defer focus (disrupts mouseup events) + element.focus(); + }); + if (callback) { + this.onComplete = callback; + } + } } -}; -Prompt.prototype.hide = function() { - if (hiliter.parentNode) { - container.removeChild(hiliter); + hide() { + if (hiliter.parentNode) { + container.removeChild(hiliter); + } } -}; +} export default Prompt; diff --git a/src/js/views/text-format-toolbar.js b/src/js/views/text-format-toolbar.js index 381419ecf..10600d171 100644 --- a/src/js/views/text-format-toolbar.js +++ b/src/js/views/text-format-toolbar.js @@ -25,15 +25,17 @@ function TextFormatToolbar(options) { var toolbar = this; Toolbar.call(this, options); toolbar.rootElement = options.rootElement; - toolbar.rootElement.addEventListener('keyup', function() { handleTextSelection(toolbar); }); + this.addEventListener(toolbar.rootElement, 'keyup', () => { + handleTextSelection(toolbar); + }); - document.addEventListener('mouseup', function() { + this.addEventListener(document, 'mouseup', () => { setTimeout(function() { handleTextSelection(toolbar); }); }); - document.addEventListener('keyup', function(e) { + this.addEventListener(document, 'keyup', (e) => { var key = e.keyCode; if (key === 116) { //F5 toolbar.toggleSticky(); @@ -43,7 +45,7 @@ function TextFormatToolbar(options) { } }); - window.addEventListener('resize', function() { + this.addEventListener(window, 'resize', () => { if(!toolbar.sticky && toolbar.isShowing) { var activePromptRange = toolbar.activePrompt && toolbar.activePrompt.range; toolbar.positionToContent(activePromptRange ? activePromptRange : window.getSelection().getRangeAt(0)); diff --git a/src/js/views/toolbar-button.js b/src/js/views/toolbar-button.js index a3ecaf3e2..19e7010d5 100644 --- a/src/js/views/toolbar-button.js +++ b/src/js/views/toolbar-button.js @@ -1,4 +1,6 @@ var buttonClassName = 'ck-toolbar-btn'; +import mixin from '../utils/mixin'; +import EventListenerMixin from '../utils/event-listener'; function ToolbarButton(options) { var button = this; @@ -14,7 +16,7 @@ function ToolbarButton(options) { element.title = command.name; element.className = buttonClassName; element.innerHTML = command.button; - element.addEventListener('mouseup', function(e) { + this.addEventListener(element, 'mouseup', (e) => { if (!button.isActive && prompt) { toolbar.displayPrompt(prompt); } else { @@ -42,4 +44,6 @@ ToolbarButton.prototype = { } }; +mixin(ToolbarButton, EventListenerMixin); + export default ToolbarButton; diff --git a/src/js/views/toolbar.js b/src/js/views/toolbar.js index 7bfd198af..853e986b9 100644 --- a/src/js/views/toolbar.js +++ b/src/js/views/toolbar.js @@ -57,7 +57,7 @@ function Toolbar(options) { } // Closes prompt if displayed when changing selection - document.addEventListener('mouseup', function() { + this.addEventListener(document, 'mouseup', () => { toolbar.dismissPrompt(); }); } diff --git a/src/js/views/tooltip.js b/src/js/views/tooltip.js index 0d5d05e09..9ffc3cb15 100644 --- a/src/js/views/tooltip.js +++ b/src/js/views/tooltip.js @@ -10,7 +10,7 @@ function Tooltip(options) { options.classNames = ['ck-tooltip']; View.call(tooltip, options); - rootElement.addEventListener('mouseover', function(e) { + this.addEventListener(rootElement, 'mouseover', (e) => { var target = getEventTargetMatchingTag(options.showForTag, e.target, rootElement); if (target && target.isContentEditable) { timeout = setTimeout(function() { @@ -19,7 +19,7 @@ function Tooltip(options) { } }); - rootElement.addEventListener('mouseout', function(e) { + this.addEventListener(rootElement, 'mouseout', (e) => { clearTimeout(timeout); var toElement = e.toElement || e.relatedTarget; if (toElement && toElement.className !== tooltip.element.className) { diff --git a/src/js/views/view.js b/src/js/views/view.js index d11537218..8fcf2baf5 100644 --- a/src/js/views/view.js +++ b/src/js/views/view.js @@ -1,3 +1,6 @@ +import mixin from '../utils/mixin'; +import EventListenerMixin from '../utils/event-listener'; + function renderClasses(view) { var classNames = view.classNames; if (classNames && classNames.length) { @@ -7,55 +10,61 @@ function renderClasses(view) { } } -function View(options) { - options = options || {}; - this.tagName = options.tagName || 'div'; - this.classNames = options.classNames || []; - this.element = document.createElement(this.tagName); - this.container = options.container || document.body; - this.isShowing = false; - renderClasses(this); -} +class View { + constructor(options={}) { + this.tagName = options.tagName || 'div'; + this.classNames = options.classNames || []; + this.element = document.createElement(this.tagName); + this.container = options.container || document.body; + this.isShowing = false; + renderClasses(this); + } -View.prototype = { - show: function() { + show() { var view = this; if(!view.isShowing) { view.container.appendChild(view.element); view.isShowing = true; return true; } - }, - hide: function() { + } + + hide() { var view = this; if(view.isShowing) { view.container.removeChild(view.element); view.isShowing = false; return true; } - }, - addClass: function(className) { + } + + addClass(className) { var index = this.classNames && this.classNames.indexOf(className); if (index === -1) { this.classNames.push(className); renderClasses(this); } - }, - removeClass: function(className) { + } + + removeClass(className) { var index = this.classNames && this.classNames.indexOf(className); if (index > -1) { this.classNames.splice(index, 1); renderClasses(this); } - }, - setClasses: function(classNameArr) { + } + + setClasses(classNameArr) { this.classNames = classNameArr; renderClasses(this); - }, + } + destroy() { - // FIXME should also clean up event listeners + this.removeAllEventListeners(); this.hide(); } -}; +} + +mixin(View, EventListenerMixin); export default View; From 3bc230a52493172c0be1d0a3f608f284aae298ed Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Tue, 14 Jul 2015 12:42:05 -0400 Subject: [PATCH 56/77] remove unused ember-cli-test-loader bower component --- bower.json | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/bower.json b/bower.json index 26f54cbbc..a941e2d24 100644 --- a/bower.json +++ b/bower.json @@ -15,7 +15,5 @@ "test", "tests" ], - "dependencies": { - "ember-cli-test-loader": "~0.1.3" - } + "dependencies": {} } From 3976fd00004665b1b57eb7b90142d644ed271eb1 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Tue, 14 Jul 2015 17:28:04 -0400 Subject: [PATCH 57/77] Fix failing test on Firefox due to non-deterministic attr ordering --- src/js/parsers/dom.js | 28 +++++++++++++++++++++++++++- tests/unit/parsers/dom-test.js | 6 +++--- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/js/parsers/dom.js b/src/js/parsers/dom.js index db41f8a88..5db82ac67 100644 --- a/src/js/parsers/dom.js +++ b/src/js/parsers/dom.js @@ -12,6 +12,29 @@ function isEmptyTextNode(node) { return node.nodeType === TEXT_NODE && trim(node.textContent) === ''; } +// FIXME we need sorted attributes for deterministic tests. This is not +// a particularly elegant method, since it loops at least 3 times. +function sortAttributes(attributes) { + let keyValueAttributes = []; + let currentKey; + attributes.forEach((keyOrValue, index) => { + if (index % 2 === 0) { + currentKey = keyOrValue; + } else { + keyValueAttributes.push({key:currentKey, value:keyOrValue}); + } + }); + keyValueAttributes.sort((a,b) => { + return a.key === b.key ? 0 : + a.key > b.key ? 1 : - 1; + }); + let sortedAttributes = []; + keyValueAttributes.forEach(({key, value}) => { + sortedAttributes.push(key, value); + }); + return sortedAttributes; +} + // FIXME: should probably always return an array function readAttributes(node) { var attributes = null; @@ -26,9 +49,12 @@ function readAttributes(node) { } if (attributes.length === 0) { return null; + } else { + return sortAttributes(attributes); } } - return attributes; + + return null; } const VALID_MARKER_ELEMENTS = [ diff --git a/tests/unit/parsers/dom-test.js b/tests/unit/parsers/dom-test.js index 42ffcbe07..8ee581a42 100644 --- a/tests/unit/parsers/dom-test.js +++ b/tests/unit/parsers/dom-test.js @@ -332,9 +332,9 @@ test('markup: consistent order', (assert) => { */ test('attributes', (assert) => { - var href = 'http://google.com'; - var rel = 'nofollow'; - const post = parser.parse(buildDOM('

Link to google.com

')); + const href = 'http://google.com'; + const rel = 'nofollow'; + const post = parser.parse(buildDOM(`

Link to google.com

`)); let expectedFirst = builder.generateSection('P'); expectedFirst.markers.push(builder.generateMarker([ From ed0410aaded8d0cce3c4ea8204d615408873bd71 Mon Sep 17 00:00:00 2001 From: Matthew Beale Date: Tue, 14 Jul 2015 11:36:40 -0400 Subject: [PATCH 58/77] Ignore .env for AWS keys --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 9ad0bd2d1..d3dc6f386 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,7 @@ coverage # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) .grunt +.env # Compiled binary addons (http://nodejs.org/api/addons.html) build/Release From 6261c7c02f5e83e38ea52c06d830d0343796603a Mon Sep 17 00:00:00 2001 From: Matthew Beale Date: Tue, 14 Jul 2015 11:36:56 -0400 Subject: [PATCH 59/77] Tweak docs to show booting node server --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 37813df0a..96266bdf9 100644 --- a/README.md +++ b/README.md @@ -125,3 +125,11 @@ export EMBEDLY_KEY=XXXXXX Also, set the `bucketName` in `server/config.json` with the name of your AWS S3 bucket for uploading files. + +Then to boot the server: + +``` +node server/index.js +``` + +And visit http://localhost:5000/dist/demo/index.html From 67c2e0d41049128bda81f8757c25ff7b30e42a84 Mon Sep 17 00:00:00 2001 From: Matthew Beale Date: Mon, 13 Jul 2015 12:20:42 -0400 Subject: [PATCH 60/77] Refactor Image and Card sections to a new renderer --- package.json | 4 +- server/config.json | 6 +- server/index.js | 1 - src/js/commands/image.js | 104 +++++------ src/js/editor/editor.js | 103 ++++++++--- src/js/models/card-node.js | 53 ++++++ src/js/models/image.js | 6 + src/js/models/post.js | 14 -- src/js/models/render-node.js | 75 ++++++++ src/js/models/render-tree.js | 18 ++ src/js/parsers/mobiledoc.js | 18 ++ src/js/renderers/editor-dom.js | 175 +++++++++++++++--- src/js/renderers/mobiledoc.js | 14 +- src/js/utils/array-utils.js | 11 ++ src/js/utils/post-builder.js | 12 ++ tests/unit/editor/card-lifecycle-test.js | 218 +++++++++++++++++++++++ tests/unit/editor/editor-test.js | 4 +- tests/unit/parsers/mobiledoc-test.js | 36 ++++ tests/unit/renderers/editor-dom-test.js | 169 ++++++++++++++++++ tests/unit/renderers/mobiledoc-test.js | 45 +++++ 20 files changed, 958 insertions(+), 128 deletions(-) create mode 100644 src/js/models/card-node.js create mode 100644 src/js/models/image.js create mode 100644 src/js/models/render-node.js create mode 100644 src/js/models/render-tree.js create mode 100644 src/js/utils/array-utils.js create mode 100644 tests/unit/editor/card-lifecycle-test.js create mode 100644 tests/unit/renderers/editor-dom-test.js diff --git a/package.json b/package.json index c6c4c6f64..26d08573c 100644 --- a/package.json +++ b/package.json @@ -45,8 +45,8 @@ "broccoli-test-builder": "^0.1.0", "content-kit-utils": "^0.2.0", "jquery": "^2.1.4", - "mobiledoc-dom-renderer": "^0.1.3", - "mobiledoc-html-renderer": "^0.1.0", + "mobiledoc-dom-renderer": "^0.1.4", + "mobiledoc-html-renderer": "^0.1.1", "testem": "^0.8.4" } } diff --git a/server/config.json b/server/config.json index 2ebd149aa..3c7e6d010 100644 --- a/server/config.json +++ b/server/config.json @@ -1,5 +1,5 @@ -{ +{ "s3" : { - "bucketName" : "content-kit" + "bucketName" : "201-bustle-demo" } -} \ No newline at end of file +} diff --git a/server/index.js b/server/index.js index 4547b4e6e..73e1e5989 100644 --- a/server/index.js +++ b/server/index.js @@ -4,7 +4,6 @@ var EmbedService = require('./services/embed'); // Express app var app = express(); -app.use(express.static('demo')); app.use('/dist', express.static('dist')); // Enable cors diff --git a/src/js/commands/image.js b/src/js/commands/image.js index 1f0a5e553..e3b46abb0 100644 --- a/src/js/commands/image.js +++ b/src/js/commands/image.js @@ -2,37 +2,12 @@ import Command from './base'; import Message from '../views/message'; import { inherit } from 'content-kit-utils'; import { FileUploader } from '../utils/http-utils'; +import { generateBuilder } from '../utils/post-builder'; -function createFileInput(command) { - var fileInput = document.createElement('input'); - fileInput.type = 'file'; - fileInput.accept = 'image/*'; - fileInput.className = 'ck-file-input'; - // FIXME should this listener be torn down when the ImageCommand is not active? - fileInput.addEventListener('change', function(e) { - command.handleFile(e); - }); - return fileInput; -} - -function injectImageBlock(/* src, editor, index */) { - throw new Error('Unimplemented: BlockModel and Type.IMAGE are no longer things'); - /* - var imageModel = BlockModel.createWithType(Type.IMAGE, { attributes: { src: src } }); - editor.replaceBlock(imageModel, index); - */ -} - -function renderFromFile(file, editor, index) { - if (file && window.FileReader) { - var reader = new FileReader(); - reader.onload = function(e) { - var base64Src = e.target.result; - injectImageBlock(base64Src, editor, index); - editor.renderBlockAt(index, true); - }; - reader.readAsDataURL(file); - } +function readFromFile(file, callback) { + var reader = new FileReader(); + reader.onload = ({target}) => callback(target.result); + reader.readAsDataURL(file); } function ImageCommand(options) { @@ -40,44 +15,61 @@ function ImageCommand(options) { name: 'image', button: '' }); - this.uploader = new FileUploader({ url: options.serviceUrl, maxFileSize: 5000000 }); + this.uploader = new FileUploader({ + url: options.serviceUrl, + maxFileSize: 5000000 + }); } inherit(ImageCommand, Command); ImageCommand.prototype = { - exec: function() { + exec() { ImageCommand._super.prototype.exec.call(this); - var fileInput = this.fileInput; - if (!fileInput) { - fileInput = this.fileInput = createFileInput(this); - document.body.appendChild(fileInput); - } + var fileInput = this.getFileInput(); fileInput.dispatchEvent(new MouseEvent('click', { bubbles: false })); }, - handleFile: function(e) { - var fileInput = e.target; - var file = fileInput.files && fileInput.files[0]; - var editor = this.editorContext; - var embedIntent = this.embedIntent; - var currentEditingIndex = editor.getCurrentBlockIndex(); + getFileInput() { + if (this._fileInput) { + return this._fileInput; + } + + var fileInput = document.createElement('input'); + fileInput.type = 'file'; + fileInput.accept = 'image/*'; + fileInput.className = 'ck-file-input'; + fileInput.addEventListener('change', e => this.handleFile(e)); + document.body.appendChild(fileInput); + + return fileInput; + }, + handleFile({target: fileInput}) { + let imageSection; + + let file = fileInput.files[0]; + readFromFile(file, (base64Image) => { + imageSection = generateBuilder().generateImageSection(base64Image); + this.editorContext.insertSectionAtCursor(imageSection); + this.editorContext.rerender(); + }); - embedIntent.showLoading(); - renderFromFile(file, editor, currentEditingIndex); // render image immediately client-side this.uploader.upload({ - fileInput: fileInput, - complete: function(response, error) { - embedIntent.hideLoading(); - if (error || !response || !response.url) { - setTimeout(function() { - editor.removeBlockAt(currentEditingIndex); - editor.syncVisual(); - }, 1000); - return new Message().showError(error.message || 'Error uploading image'); + fileInput, + complete: (response, error) => { + if (!imageSection) { + throw new Error('Upload completed before the image was read into memory'); + } + if (!error && response && response.url) { + imageSection.src = response.url; + imageSection.renderNode.markDirty(); + this.editorContext.rerender(); + this.editorContext.trigger('update'); + } else { + this.editorContext.removeSection(imageSection); + new Message().showError(error.message || 'Error uploading image'); } - injectImageBlock(response.url, editor, currentEditingIndex); + this.editorContext.rerender(); } }); - fileInput.value = null; // reset file input } }; diff --git a/src/js/editor/editor.js b/src/js/editor/editor.js index 1d175e365..1f422cbda 100644 --- a/src/js/editor/editor.js +++ b/src/js/editor/editor.js @@ -20,7 +20,8 @@ import EventEmitter from '../utils/event-emitter'; import MobiledocParser from "../parsers/mobiledoc"; import DOMParser from "../parsers/dom"; -import EditorDOMRenderer from "../renderers/editor-dom"; +import Renderer from 'content-kit-editor/renderers/editor-dom'; +import RenderTree from 'content-kit-editor/models/render-tree'; import MobiledocRenderer from '../renderers/mobiledoc'; import { toArray, merge, mergeWithOptions } from 'content-kit-utils'; @@ -53,7 +54,9 @@ var defaults = { new UnorderedListCommand(), new OrderedListCommand() ], - cards: {}, + cards: [], + cardOptions: {}, + unknownCardHandler: () => { throw new Error('Unknown card encountered'); }, mobiledoc: null }; @@ -88,7 +91,7 @@ function bindContentEditableTypingListeners(editor) { var sanitizedHTML = pastedHTML && editor._renderer.rerender(pastedHTML); if (sanitizedHTML) { document.execCommand('insertHTML', false, sanitizedHTML); - editor.syncVisual(); + editor.rerender(); } e.preventDefault(); return false; @@ -175,8 +178,8 @@ function Editor(element, options) { // FIXME: This should merge onto this.options mergeWithOptions(this, defaults, options); - this._renderer = new EditorDOMRenderer(window.document, this.cards); this._parser = new DOMParser(); + this._renderer = new Renderer(this.cards, this.unknownCardHandler, this.cardOptions); this.applyClassName(); this.applyPlaceholder(); @@ -193,12 +196,12 @@ function Editor(element, options) { } clearChildNodes(element); - this.syncVisual(); + this.rerender(); bindContentEditableTypingListeners(this); bindAutoTypingListeners(this); bindDragAndDrop(this); - this.addEventListener(element, 'input', () => this.handleInput(...arguments)); + this.addEventListener(element, 'input', () => this.handleInput()); initEmbedCommands(this); this.addView(new TextFormatToolbar({ @@ -227,22 +230,34 @@ merge(Editor.prototype, { loadModel(post) { this.post = post; - this.syncVisual(); + this.rerender(); this.trigger('update'); }, parseModelFromDOM(element) { this.post = this._parser.parse(element); + this._renderTree = new RenderTree(); + let node = this._renderTree.buildRenderNode(this.post); + this._renderTree.node = node; this.trigger('update'); }, parseModelFromMobiledoc(mobiledoc) { this.post = new MobiledocParser().parse(mobiledoc); + this._renderTree = new RenderTree(); + let node = this._renderTree.buildRenderNode(this.post); + this._renderTree.node = node; this.trigger('update'); }, - syncVisual() { - this._renderer.render(this.post, this.element); + rerender() { + let postRenderNode = this.post.renderNode; + if (!postRenderNode.element) { + postRenderNode.element = this.element; + postRenderNode.markDirty(); + } + + this._renderer.render(this._renderTree); }, getCurrentBlockIndex() { @@ -344,21 +359,28 @@ merge(Editor.prototype, { let newSections = []; let previousSection; forEachChildNode(this.element, (node) => { - let section = this.post.getElementSection(node); - if (!section) { - section = this._parser.parseSection( + let sectionRenderNode = this._renderTree.getElementRenderNode(node); + if (!sectionRenderNode) { + let section = this._parser.parseSection( previousSection, node ); - this.post.setSectionElement(section, node); newSections.push(section); + + sectionRenderNode = this._renderTree.buildRenderNode(section); + sectionRenderNode.element = node; + sectionRenderNode.markClean(); + if (previousSection) { this.post.insertSectionAfter(section, previousSection); + this._renderTree.node.insertAfter(sectionRenderNode, previousSection.renderNode); } else { this.post.prependSection(section); + this._renderTree.node.insertAfter(sectionRenderNode, null); } } // may cause duplicates to be included + let section = sectionRenderNode.postNode; sectionsInDOM.push(section); previousSection = section; }); @@ -368,7 +390,11 @@ merge(Editor.prototype, { for (i=this.post.sections.length-1;i>=0;i--) { let section = this.post.sections[i]; if (sectionsInDOM.indexOf(section) === -1) { - this.post.removeSection(section); + if (section.renderNode) { + section.renderNode.scheduleForRemoval(); + } else { + throw new Error('All sections are expected to have a renderNode'); + } } } @@ -388,9 +414,18 @@ merge(Editor.prototype, { this.reparseSection(section); } }); + + this.rerender(); + this.trigger('update'); }, getSectionsWithCursor() { + return this.getRenderNodesWithCursor().map( renderNode => { + return renderNode.postNode; + }); + }, + + getRenderNodesWithCursor() { const selection = document.getSelection(); if (selection.rangeCount === 0) { return null; @@ -400,26 +435,32 @@ merge(Editor.prototype, { let { startContainer:startElement, endContainer:endElement } = range; - let getElementSection = (e) => this.post.getElementSection(e); - let { result:startSection } = detectParentNode(startElement, getElementSection); - let { result:endSection } = detectParentNode(endElement, getElementSection); - - let startIndex = this.post.sections.indexOf(startSection), - endIndex = this.post.sections.indexOf(endSection); + let getElementRenderNode = (e) => { + return this._renderTree.getElementRenderNode(e); + }; + let { result:startRenderNode } = detectParentNode(startElement, getElementRenderNode); + let { result:endRenderNode } = detectParentNode(endElement, getElementRenderNode); + + let nodes = []; + let node = startRenderNode; + while (node && (!endRenderNode.nextSibling || endRenderNode.nextSibling !== node)) { + nodes.push(node); + node = node.nextSibling; + } - return this.post.sections.slice(startIndex, endIndex+1); + return nodes; }, reparseSection(section) { - let sectionElement = this.post.getSectionElement(section); + let sectionRenderNode = section.renderNode; + let sectionElement = sectionRenderNode.element; let previousSection = this.post.getPreviousSection(section); var newSection = this._parser.parseSection( previousSection, sectionElement ); - this.post.replaceSection(section, newSection); - this.post.setSectionElement(newSection, sectionElement); + section.markers = newSection.markers; this.trigger('update'); }, @@ -433,6 +474,20 @@ merge(Editor.prototype, { this._views = []; }, + insertSectionAtCursor(newSection) { + let newRenderNode = this._renderTree.buildRenderNode(newSection); + let renderNodes = this.getRenderNodesWithCursor(); + let lastRenderNode = renderNodes[renderNodes.length-1]; + lastRenderNode.parentNode.insertAfter(newRenderNode, lastRenderNode); + this.post.insertSectionAfter(newSection, lastRenderNode.postNode); + renderNodes.forEach(renderNode => renderNode.scheduleForRemoval()); + this.trigger('update'); + }, + + removeSection(section) { + this.post.removeSection(section); + }, + destroy() { this.removeAllEventListeners(); this.removeAllViews(); diff --git a/src/js/models/card-node.js b/src/js/models/card-node.js new file mode 100644 index 000000000..a5997fd5a --- /dev/null +++ b/src/js/models/card-node.js @@ -0,0 +1,53 @@ +export default class CardNode { + constructor(card, section, element, cardOptions) { + this.card = card; + this.section = section; + this.cardOptions = cardOptions; + this.element = element; + + this.mode = null; + this.setupResult = null; + } + + render(mode) { + if (this.mode === mode) { return; } + + this.teardown(); + + this.mode = mode; + this.setupResult = this.card[mode].setup( + this.element, + this.cardOptions, + this.env, + this.section.payload + ); + } + + get env() { + return { + name: this.card.name, + edit: () => { this.edit(); }, + save: (payload) => { + this.section.payload = payload; + this.display(); + }, + cancel: () => { this.display(); } + }; + } + + display() { + this.render('display'); + } + + edit() { + this.render('edit'); + } + + teardown() { + if (this.mode) { + if (this.card[this.mode].teardown) { + this.card[this.mode].teardown(this.setupResult); + } + } + } +} diff --git a/src/js/models/image.js b/src/js/models/image.js new file mode 100644 index 000000000..b78610114 --- /dev/null +++ b/src/js/models/image.js @@ -0,0 +1,6 @@ +export default class Image { + constructor() { + this.type = 'imageSection'; + this.src = null; + } +} diff --git a/src/js/models/post.js b/src/js/models/post.js index 8638393a3..512ec22a3 100644 --- a/src/js/models/post.js +++ b/src/js/models/post.js @@ -1,11 +1,8 @@ -import ElementMap from "../utils/element-map"; - // FIXME: making sections a linked-list would greatly improve this export default class Post { constructor() { this.type = 'post'; this.sections = []; - this.sectionElementMap = new ElementMap(); } appendSection(section) { this.sections.push(section); @@ -27,18 +24,7 @@ export default class Post { } throw new Error('Previous section was not found in post.sections'); } - setSectionElement(section, element) { - section.element = element; - this.sectionElementMap.set(element, section); - } - getSectionElement(section) { - return section && section.element; - } - getElementSection(element) { - return this.sectionElementMap.get(element); - } removeSection(section) { - this.sectionElementMap.remove(section.element); var i, l; for (i=0,l=this.sections.length;i card.name === section.name); + + const env = { name: section.name }; + renderNode.element = document.createElement('div'); + renderNode.parentNode.element.appendChild(renderNode.element); + + if (card) { + let cardNode = new CardNode(card, section, renderNode.element, this.options); + renderNode.cardNode = cardNode; + cardNode.display(); + } else { + this.unknownCardHandler(renderNode.element, this.options, env, section.payload); + } } - this.cards = cards; } -NewDOMRenderer.prototype.render = function NewDOMRenderer_render(post, target) { - var sections = post.sections; - var i, l, section, node; - for (i=0, l=sections.length;i { + let node = lookupNode(renderTree, parentNode, section, previousNode); + if (node.isDirty) { + nodes.push(node); + } + previousNode = node; + }); + } + let node = nodes.shift(); + while (node) { + removeChildren(node); + visitor[node.postNode.type](node, node.postNode, visit); + node.markClean(); + node = nodes.shift(); + } +} + +export default class Render { + constructor(cards, unknownCardHandler, options) { + this.visitor = new Visitor(cards, unknownCardHandler, options); + } + + render(renderTree) { + renderInternal(renderTree, this.visitor); + } +} diff --git a/src/js/renderers/mobiledoc.js b/src/js/renderers/mobiledoc.js index bac38670a..e967d0526 100644 --- a/src/js/renderers/mobiledoc.js +++ b/src/js/renderers/mobiledoc.js @@ -9,6 +9,12 @@ let visitor = { opcodes.push(['openMarkupSection', node.tagName]); visitArray(visitor, node.markers, opcodes); }, + imageSection(node, opcodes) { + opcodes.push(['openImageSection', node.src]); + }, + card(node, opcodes) { + opcodes.push(['openCardSection', node.name, node.payload]); + }, marker(node, opcodes) { opcodes.push(['openMarker', node.close, node.value]); visitArray(visitor, node.open, opcodes); @@ -24,13 +30,19 @@ let postOpcodeCompiler = { this.markers.push([ this.markupMarkerIds, closeCount, - value + value || '' ]); }, openMarkupSection(tagName) { this.markers = []; this.sections.push([1, tagName, this.markers]); }, + openImageSection(url) { + this.sections.push([2, url]); + }, + openCardSection(name, payload) { + this.sections.push([10, name, payload]); + }, openPost() { this.markerTypes = []; this.sections = []; diff --git a/src/js/utils/array-utils.js b/src/js/utils/array-utils.js new file mode 100644 index 000000000..9cb929864 --- /dev/null +++ b/src/js/utils/array-utils.js @@ -0,0 +1,11 @@ +function detect(array, callback) { + for (let i=0; i { + assert.expect(4); + + const payload = { + foo: 'bar' + }; + const cardOptions = { boo: 'baz' }; + + const card = { + name: 'test-card', + display: { + setup(element, options, env, setupPayload) { + assert.ok(editorElement.contains(element), + 'card element is part of the editor element'); + assert.deepEqual(payload, setupPayload, + 'the payload is passed to the card'); + assert.equal(env.name, 'test-card', + 'env.name is correct'); + assert.deepEqual(options, cardOptions, 'correct cardOptions'); + }, + teardown() { + } + } + }; + + const mobiledoc = [ + [], + [ + [10, 'test-card', payload] + ] + ]; + editor = new Editor(editorElement, { + mobiledoc, + cards: [card], + cardOptions + }); +}); + +test('rendering a mobiledoc for editing calls #unknownCardHandler when it encounters an unknown card', (assert) => { + assert.expect(1); + + const cardName = 'my-card'; + + const unknownCardHandler = (element, options, env /*,setupPayload*/) => { + assert.equal(env.name, cardName, 'includes card name in env'); + }; + + const mobiledoc = [ + [], + [ + [10, cardName, {}] + ] + ]; + + editor = new Editor(editorElement, {mobiledoc, unknownCardHandler}); +}); + +test('rendered card can fire edit hook to enter editing mode', (assert) => { + assert.expect(7); + + const payload = { foo: 'bar' }; + const cardOptions = { boo: 'baz' }; + + let returnedSetupValue = {some: 'object'}; + let span; + const card = { + name: 'test-card', + display: { + setup(element, options, env/*, setupPayload*/) { + span = document.createElement('span'); + span.onclick = function() { + assert.ok(true, 'precond - click occurred'); + env.edit(); + }; + element.appendChild(span); + return returnedSetupValue; + }, + teardown(passedValue) { + assert.ok(true, 'teardown called'); + assert.equal(passedValue, returnedSetupValue, + 'teardown called with return value of setup'); + } + }, + edit: { + setup(element, options, env, setupPayload) { + assert.ok(editorElement.contains(element), + 'card element is part of the editor element'); + assert.deepEqual(payload, setupPayload, + 'the payload is passed to the card'); + assert.equal(env.name, 'test-card', + 'env.name is correct'); + assert.deepEqual(options, cardOptions, 'correct cardOptions'); + } + } + }; + + const mobiledoc = [ + [], + [ + [10, 'test-card', payload] + ] + ]; + editor = new Editor(editorElement, { + mobiledoc, + cards: [card], + cardOptions + }); + + Helpers.dom.triggerEvent(span, 'click'); +}); + +test('rendered card can fire edit hook to enter editing mode, then save', (assert) => { + assert.expect(3); + + let setupPayloads = []; + let newPayload = {some: 'new values'}; + let doEdit, doSave; + const card = { + name: 'test-card', + display: { + setup(element, options, env, setupPayload) { + setupPayloads.push(setupPayload); + doEdit = () => { + env.edit(); + }; + } + }, + edit: { + setup(element, options, env) { + assert.ok(env.save, + 'env exposes save hook'); + doSave = () => { + env.save(newPayload); + }; + } + } + }; + + const payload = { foo: 'bar' }; + const mobiledoc = [ + [], + [ + [10, 'test-card', payload] + ] + ]; + editor = new Editor(editorElement, { + mobiledoc, + cards: [card] + }); + + doEdit(); + doSave(); + let [firstPayload, secondPayload] = setupPayloads; + assert.equal(firstPayload, payload, 'first display with mobiledoc payload'); + assert.equal(secondPayload, newPayload, 'second display with new payload'); +}); + +test('rendered card can fire edit hook to enter editing mode, then cancel', (assert) => { + assert.expect(3); + + let setupPayloads = []; + let doEdit, doCancel; + const card = { + name: 'test-card', + display: { + setup(element, options, env, setupPayload) { + setupPayloads.push(setupPayload); + doEdit = () => { + env.edit(); + }; + } + }, + edit: { + setup(element, options, env) { + assert.ok(env.cancel, 'env exposes cancel hook'); + doCancel = () => { + env.cancel(); + }; + } + } + }; + + const payload = { foo: 'bar' }; + const mobiledoc = [ + [], + [ + [10, 'test-card', payload] + ] + ]; + editor = new Editor(editorElement, { + mobiledoc, + cards: [card] + }); + + doEdit(); + doCancel(); + let [firstPayload, secondPayload] = setupPayloads; + assert.equal(firstPayload, payload, 'first display with mobiledoc payload'); + assert.equal(secondPayload, payload, 'second display with mobiledoc payload'); +}); diff --git a/tests/unit/editor/editor-test.js b/tests/unit/editor/editor-test.js index 86f05e7ca..b6dca0375 100644 --- a/tests/unit/editor/editor-test.js +++ b/tests/unit/editor/editor-test.js @@ -13,7 +13,9 @@ module('Unit: Editor', { fixture.appendChild(editorElement); }, afterEach: function() { - editor.destroy(); + if (editor) { + editor.destroy(); + } fixture.removeChild(editorElement); } }); diff --git a/tests/unit/parsers/mobiledoc-test.js b/tests/unit/parsers/mobiledoc-test.js index d12a479b5..53d1a737b 100644 --- a/tests/unit/parsers/mobiledoc-test.js +++ b/tests/unit/parsers/mobiledoc-test.js @@ -1,6 +1,7 @@ import MobiledocParser from 'content-kit-editor/parsers/mobiledoc'; import { generateBuilder } from 'content-kit-editor/utils/post-builder'; +const DATA_URL = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs="; const { module, test } = window.QUnit; let parser, builder, post; @@ -77,3 +78,38 @@ test('#parse doc with marker type', (assert) => { ); }); +test('#parse doc with image section', (assert) => { + const mobiledoc = [ + [], + [ + [2, DATA_URL] + ] + ]; + + const parsed = parser.parse(mobiledoc); + + let section = builder.generateImageSection(DATA_URL); + post.appendSection(section); + assert.deepEqual( + parsed, + post + ); +}); + +test('#parse doc with custom card type', (assert) => { + const mobiledoc = [ + [], + [ + [10, 'custom-card', {}] + ] + ]; + + const parsed = parser.parse(mobiledoc); + + let section = builder.generateCardSection('custom-card'); + post.appendSection(section); + assert.deepEqual( + parsed, + post + ); +}); diff --git a/tests/unit/renderers/editor-dom-test.js b/tests/unit/renderers/editor-dom-test.js new file mode 100644 index 000000000..df0d07507 --- /dev/null +++ b/tests/unit/renderers/editor-dom-test.js @@ -0,0 +1,169 @@ +import { generateBuilder } from 'content-kit-editor/utils/post-builder'; +const { module, test } = window.QUnit; +import Renderer from 'content-kit-editor/renderers/render'; +import RenderNode from 'content-kit-editor/models/render-node'; +import RenderTree from 'content-kit-editor/models/render-tree'; + +const DATA_URL = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs="; +let builder; + +function render(renderTree) { + let renderer = new Renderer([]); + return renderer.render(renderTree); +} + +module("Unit: Renderer", { + beforeEach() { + builder = generateBuilder(); + } +}); + +test("It renders a dirty post", (assert) => { + /* + * renderTree is: + * + * renderNode + * + */ + let renderNode = new RenderNode(builder.generatePost()); + let renderTree = new RenderTree(renderNode); + renderNode.renderTree = renderTree; + + render(renderTree); + + assert.ok(renderTree.node.element, 'renderTree renders element for post'); + assert.ok(!renderTree.node.isDirty, 'dirty node becomes clean'); + assert.equal(renderTree.node.element.tagName, 'DIV', 'renderTree renders element for post'); +}); + +test("It renders a dirty post with un-rendered sections", (assert) => { + let post = builder.generatePost(); + let sectionA = builder.generateSection('P'); + post.appendSection(sectionA); + let sectionB = builder.generateSection('P'); + post.appendSection(sectionB); + + let renderNode = new RenderNode(post); + let renderTree = new RenderTree(renderNode); + renderNode.renderTree = renderTree; + + render(renderTree); + + assert.equal(renderTree.node.element.outerHTML, '

', + 'correct HTML is rendered'); + + assert.ok(renderTree.node.firstChild, + 'sectionA creates a first child'); + assert.equal(renderTree.node.firstChild.postNode, sectionA, + 'sectionA is first renderNode child'); + assert.ok(!renderTree.node.firstChild.isDirty, 'sectionA node is clean'); + assert.equal(renderTree.node.lastChild.postNode, sectionB, + 'sectionB is second renderNode child'); + assert.ok(!renderTree.node.lastChild.isDirty, 'sectionB node is clean'); +}); + +[ + { + name: 'markup', + section: (builder) => builder.generateSection('P') + }, + { + name: 'image', + section: (builder) => builder.generateImageSection(DATA_URL) + }, + { + name: 'card', + section: (builder) => builder.generateCardSection('new-card') + } +].forEach((testInfo) => { + test(`Remove nodes with ${testInfo.name} section`, (assert) => { + let post = builder.generatePost(); + let section = testInfo.section(builder); + post.appendSection(section); + + let postElement = document.createElement('div'); + let sectionElement = document.createElement('p'); + postElement.appendChild(sectionElement); + + let postRenderNode = new RenderNode(post); + + let renderTree = new RenderTree(postRenderNode); + postRenderNode.renderTree = renderTree; + postRenderNode.element = postElement; + + let sectionRenderNode = renderTree.buildRenderNode(section); + sectionRenderNode.element = sectionElement; + sectionRenderNode.scheduleForRemoval(); + postRenderNode.appendChild(sectionRenderNode); + + render(renderTree); + + assert.equal(renderTree.node.element, postElement, + 'post element remains'); + + assert.equal(renderTree.node.element.firstChild, null, + 'section element removed'); + + assert.equal(renderTree.node.firstChild, null, + 'section renderNode is removed'); + }); +}); + +test('renders a post with marker', (assert) => { + let post = builder.generatePost(); + let section = builder.generateSection('P'); + post.appendSection(section); + section.markers.push( + builder.generateMarker([ + builder.generateMarkerType('STRONG') + ], 1, 'Hi') + ); + + let node = new RenderNode(post); + let renderTree = new RenderTree(node); + node.renderTree = renderTree; + render(renderTree); + assert.equal(node.element.innerHTML, '

Hi

'); +}); + +test('renders a post with image', (assert) => { + let url = DATA_URL; + let post = builder.generatePost(); + let section = builder.generateImageSection(url); + post.appendSection(section); + + let node = new RenderNode(post); + let renderTree = new RenderTree(node); + node.renderTree = renderTree; + render(renderTree); + assert.equal(node.element.innerHTML, ``); +}); + +/* +test("It renders a renderTree with rendered dirty section", (assert) => { + /* + * renderTree is: + * + * post + * / \ + * / \ + * section section + * + let post = builder.generatePost + let postRenderNode = { + element: null, + parent: null, + isDirty: true, + postNode: builder.generatePost() + } + let renderTree = { + node: renderNode + } + + render(renderTree); + + assert.ok(renderTree.node.element, 'renderTree renders element for post'); + assert.ok(!renderTree.node.isDirty, 'dirty node becomes clean'); + assert.equal(renderTree.node.element.tagName, 'DIV', 'renderTree renders element for post'); +}); +*/ diff --git a/tests/unit/renderers/mobiledoc-test.js b/tests/unit/renderers/mobiledoc-test.js index 12145c7f2..f31da6c27 100644 --- a/tests/unit/renderers/mobiledoc-test.js +++ b/tests/unit/renderers/mobiledoc-test.js @@ -39,3 +39,48 @@ test('renders a post with marker', (assert) => { ] ]); }); + +test('renders a post with image', (assert) => { + let url = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs="; + let post = builder.generatePost(); + let section = builder.generateImageSection(url); + post.appendSection(section); + + let mobiledoc = render(post); + assert.deepEqual(mobiledoc, [ + [], + [ + [2, url] + ] + ]); +}); + +test('renders a post with image and null src', (assert) => { + let post = builder.generatePost(); + let section = builder.generateImageSection(); + post.appendSection(section); + + let mobiledoc = render(post); + assert.deepEqual(mobiledoc, [ + [], + [ + [2, null] + ] + ]); +}); + +test('renders a post with card', (assert) => { + let cardName = 'super-card'; + let payload = { bar: 'baz' }; + let post = builder.generatePost(); + let section = builder.generateCardSection(cardName, payload); + post.appendSection(section); + + let mobiledoc = render(post); + assert.deepEqual(mobiledoc, [ + [], + [ + [10, cardName, payload] + ] + ]); +}); From 055776e73b6a55fe47548e7632bda66a4ec1fc1b Mon Sep 17 00:00:00 2001 From: Matthew Beale Date: Wed, 15 Jul 2015 17:12:34 -0400 Subject: [PATCH 61/77] Bump for renderers to support cards --- demo/demo.js | 4 +++- package.json | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/demo/demo.js b/demo/demo.js index 98dede0eb..5e07ce944 100644 --- a/demo/demo.js +++ b/demo/demo.js @@ -14,7 +14,9 @@ var ContentKitDemo = exports.ContentKitDemo = { codePaneJSON.innerHTML = this.syntaxHighlight(mobiledoc); var renderer = new MobiledocDOMRenderer(); - var rendered = renderer.render(mobiledoc); + var rendered = renderer.render(mobiledoc, document.createElement('div'), { + /* cards */ + }); $('#rendered-mobiledoc').empty(); $('#rendered-mobiledoc')[0].appendChild(rendered); diff --git a/package.json b/package.json index 26d08573c..c0ab01446 100644 --- a/package.json +++ b/package.json @@ -45,8 +45,8 @@ "broccoli-test-builder": "^0.1.0", "content-kit-utils": "^0.2.0", "jquery": "^2.1.4", - "mobiledoc-dom-renderer": "^0.1.4", - "mobiledoc-html-renderer": "^0.1.1", + "mobiledoc-dom-renderer": "^0.1.5", + "mobiledoc-html-renderer": "^0.1.2", "testem": "^0.8.4" } } From 6a440dc428ea03a3fcd142a5a65f9e2b2205e856 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Wed, 15 Jul 2015 16:37:36 -0400 Subject: [PATCH 62/77] sample cards: simple, edit, input --- demo/demo.js | 130 +++++++++++++++++++++++++++++++++++++++++++++--- demo/index.html | 3 ++ 2 files changed, 127 insertions(+), 6 deletions(-) diff --git a/demo/demo.js b/demo/demo.js index 5e07ce944..7e2a3dc7d 100644 --- a/demo/demo.js +++ b/demo/demo.js @@ -1,7 +1,99 @@ (function(exports, document, undefined) { - 'use strict'; +function removeChildren(element) { + for (var i=0; i < element.childNodes.length; i++) { + element.removeChild(element.childNodes[i]); + } +} + +var simpleCard = { + name: 'simple-card', + display: { + setup: function(element) { + let card = document.createElement('span'); + card.innerHTML = 'Hello, world'; + element.appendChild(card); + } + } +}; + +var cardWithEditMode = { + name: 'edit-card', + display: { + setup: function(element, options, env) { + removeChildren(element); + let card = document.createElement('div'); + card.innerHTML = 'I am in display mode'; + + let button = document.createElement('button'); + button.innerText = 'Change to edit'; + button.onclick = env.edit; + + card.appendChild(button); + element.appendChild(card); + } + }, + edit: { + setup: function(element, options, env) { + removeChildren(element); + let card = document.createElement('div'); + card.innerHTML = 'I am in edit mode'; + + let button = document.createElement('button'); + button.innerText = 'Change to display'; + button.onclick = env.save; + + card.appendChild(button); + element.appendChild(card); + } + } +}; + +var cardWithInput = { + name: 'input-card', + display: { + setup: function(element, options, env, payload) { + removeChildren(element); + + var text = 'I am in display mode'; + if (payload.name) { + text = 'Hello, ' + payload.name + '!'; + } + let card = document.createElement('div'); + card.innerText = text; + + let button = document.createElement('button'); + button.innerText = 'Edit'; + button.onclick = env.edit; + + card.appendChild(button); + element.appendChild(card); + } + }, + edit: { + setup: function(element, options, env) { + removeChildren(element); + let card = document.createElement('div'); + card.innerHTML = 'What is your name?'; + + let input = document.createElement('input'); + input.placeholder = 'Enter your name...'; + + let button = document.createElement('button'); + button.innerText = 'Save'; + button.onclick = function() { + var name = input.value; + env.save({name:name}); + }; + + card.appendChild(input); + card.appendChild(button); + element.appendChild(card); + } + } +}; + var ContentKit = exports.ContentKit, $ = exports.$, MobiledocHTMLRenderer = exports.MobiledocHTMLRenderer, @@ -58,11 +150,7 @@ function bootEditor(element, mobiledoc) { var editor = new ContentKit.Editor(element, { autofocus: false, mobiledoc: mobiledoc, - cards: { - 'pick-color': function renderPickColor(payload) { - return 'PICK A COLOR: '+payload.options.join(', '); - } - } + cards: [simpleCard, cardWithEditMode, cardWithInput] }); editor.on('update', function() { @@ -145,6 +233,36 @@ var sampleMobiledocs = { [[0], 1, "on github."] ]] ] + ], + + mobileDocWithSimpleCard: [ + [], + [ + [1, "H2", [ + [[], 0, "Simple Card"] + ]], + [10, "simple-card"] + ] + ], + + mobileDocWithEditCard: [ + [], + [ + [1, "H2", [ + [[], 0, "Edit Card"] + ]], + [10, "edit-card"] + ] + ], + + mobileDocWithInputCard: [ + [], + [ + [1, "H2", [ + [[], 0, "Input Card"] + ]], + [10, "input-card"] + ] ] }; diff --git a/demo/index.html b/demo/index.html index 5c1c38941..b588d91c5 100644 --- a/demo/index.html +++ b/demo/index.html @@ -31,6 +31,9 @@

mobiledoc to load