├── .eslintrc ├── .gitignore ├── LICENSE ├── README.md ├── lib ├── index.js ├── manager.js ├── mixins │ ├── edit_paragraph.js │ ├── index.js │ ├── menu.js │ ├── re.js │ └── reject_tokens.js ├── type.js ├── utils.js └── widget.js └── package.json /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "indent": [ 2, 4 ], 4 | "quotes": [ 2, "single" ], 5 | "linebreak-style": [ 2, "unix" ], 6 | "semi": [ 2, "always" ], 7 | "no-unused-vars": [ 2, { 8 | "vars": "all", 9 | "args": "none" 10 | } ], 11 | "spaced-comment": [ 2, "always" ] 12 | }, 13 | "ecmaFeatures": { 14 | "jsx": true, 15 | "experimentalObjectRestSpread": true 16 | }, 17 | "env": { 18 | "node": true, 19 | "browser": true 20 | }, 21 | "plugins": [ 22 | "react" 23 | ], 24 | "globals": { 25 | "electronRequire": true, 26 | "remote": true 27 | }, 28 | "extends": "eslint:recommended" 29 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # Compiled binary addons (http://nodejs.org/api/addons.html) 20 | build/Release 21 | 22 | # Dependency directory 23 | # Commenting this out is preferred by some people, see 24 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- 25 | node_modules 26 | 27 | # Users Environment Variables 28 | .lock-wscript 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # codemirror-widgets 2 | 3 | Utility to easily write interactive widgets for CodeMirror. 4 | 5 | ### Installation 6 | 7 | ``` 8 | $ npm install codemirror-widgets 9 | ``` 10 | 11 | ### Usage 12 | 13 | Example, replace LaTeX math (`$$ ... $$`) by a preview using [KaTeX](https://github.com/Khan/KaTeX) 14 | 15 | ```js 16 | var widgets = require('codemirror-widgets'); 17 | var katex = require('katex'); 18 | 19 | // Create a type of widget 20 | var WidgetMath = widgets.createType({ 21 | mixins: [ 22 | widgets.mixins.re(/\$\$([^$]+)\$\$/g, function(match) { 23 | return { 24 | props: { 25 | text: match[1] 26 | } 27 | }; 28 | }), 29 | widgets.mixins.editDelimit('$$', '$$') 30 | ], 31 | 32 | createElement: function(widget) { 33 | // Create the spam to replace the formula 34 | var span = document.createElement('span'); 35 | 36 | // Render the formula using katex 37 | katex.render(widget.props.text, span) 38 | 39 | return span; 40 | } 41 | }); 42 | 43 | 44 | // Create a widgets manager connected to an editor 45 | var manager = widgets.createManager(editor); 46 | 47 | // Connect a type of widget to the manager 48 | manager.enable(WidgetLink); 49 | ``` 50 | 51 | ### Mixins 52 | 53 | Some prebuilt mixins make it event easier to create awesome widgets: 54 | 55 | ##### `re` 56 | 57 | Find occurrence using a Regex: 58 | 59 | ```js 60 | var widgetMath = widgets.createType({ 61 | mixins: [ 62 | widgets.mixins.re(/\$\$([^$]+)\$\$/g, function(match) { 63 | return { 64 | props: { 65 | text: match[1] 66 | } 67 | }; 68 | }) 69 | ], 70 | 71 | ... 72 | }); 73 | ``` 74 | 75 | ##### `menu` 76 | 77 | Bind a menu with multiple actions to your widgets. The menu will show up on click (like on Gmail). 78 | 79 | ```js 80 | var widgetLink = widgets.createType({ 81 | mixins: [ 82 | widgets.mixins.menu({ 83 | entries: [ 84 | { 85 | label: 'Open', 86 | click: function(widget) { 87 | window.open(widget.props.href, '_blank') 88 | } 89 | } 90 | ] 91 | }) 92 | ], 93 | 94 | ... 95 | }); 96 | ``` 97 | 98 | 99 | ##### `editParagraph` 100 | 101 | Helper to update a paragraph when user is typing 102 | 103 | ```js 104 | var widgetLink = widgets.createType({ 105 | mixins: [ 106 | widgets.mixins.editParagraph() 107 | ], 108 | 109 | ... 110 | }); 111 | ``` 112 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | 2 | module.exports = { 3 | createType: require('./type').create, 4 | createManager: require('./manager'), 5 | mixins: require('./mixins') 6 | }; 7 | -------------------------------------------------------------------------------- /lib/manager.js: -------------------------------------------------------------------------------- 1 | var _ = require('lodash'); 2 | var CodeMirror = require 3 | var utils = require('./utils'); 4 | 5 | function Manager(editor) { 6 | if (!(this instanceof Manager)) return new Manager(editor); 7 | _.bindAll(this); 8 | 9 | this.id = _.uniqueId('widgetsManager'); 10 | 11 | // Prepare codemirror instance 12 | this.editor = editor; 13 | this.editor._widgets = this; 14 | 15 | this.unrendered = null; 16 | 17 | // Widgets bindings 18 | this.bindings = {}; 19 | } 20 | 21 | // Return doc for this manager 22 | Manager.prototype.doc = function() { 23 | return this.editor.getDoc() 24 | }; 25 | 26 | // Render unrendered marker 27 | Manager.prototype.renderUnrendered = function() { 28 | var that = this; 29 | 30 | if (!this.unrendered) return; 31 | 32 | this.editor.off('cursorActivity', this.onCursorActivity); 33 | 34 | var range = this.unrendered.find(); 35 | if (!range) return; 36 | 37 | var props = this.unrendered.xProps; 38 | var type = this.unrendered.xType; 39 | 40 | this.unrendered.clear(); 41 | this.unrendered = null; 42 | this.get(type).createWidget(range, props); 43 | 44 | that.editor.constructor.signal(that.editor, 'renderUnrendered'); 45 | }; 46 | 47 | 48 | // Set the marker that is not rendered 49 | Manager.prototype.setUnrendered = function(_unrendered) { 50 | var that = this; 51 | 52 | this.renderUnrendered(); 53 | this.unrendered = _unrendered; 54 | this.unrendered.unrendered = true; 55 | 56 | this.editor.on('cursorActivity', this.onCursorActivity); 57 | 58 | that.editor.constructor.signal(that.editor, 'unrender'); 59 | }; 60 | 61 | // Check if manager has an unrendered marker of a certain type 62 | Manager.prototype.hasUnrendered = function(type) { 63 | return (unrendered && unrendered.xType == (type.id || type)); 64 | } 65 | 66 | // Add/Enable a widget type 67 | Manager.prototype.enable = function(Type, opts) { 68 | this.disable(Type); 69 | 70 | this.bindings[Type.id] = new Type(this, opts); 71 | this.bindings[Type.id].enable(); 72 | }; 73 | 74 | // Disable and clear a widget type 75 | Manager.prototype.disable = function(Type) { 76 | if (!this.bindings[Type.id]) return; 77 | 78 | this.bindings[Type.id].disable(); 79 | delete this.bindings[Type.id]; 80 | }; 81 | 82 | // Return a specific type 83 | Manager.prototype.get = function(id) { 84 | return _.find(this.bindings, { 85 | id: id 86 | }); 87 | }; 88 | 89 | // Cursor position changed 90 | // Render the marker if cursor is outside its range 91 | Manager.prototype.onCursorActivity = function() { 92 | if (!this.unrendered) return; 93 | 94 | var doc = this.doc(); 95 | var cursor = doc.getCursor(); 96 | var range = this.unrendered.find(); 97 | if (!range) return; 98 | 99 | if (utils.posOutsideRange(cursor, range)) { 100 | this.renderUnrendered(); 101 | } 102 | }; 103 | 104 | module.exports = Manager; 105 | -------------------------------------------------------------------------------- /lib/mixins/edit_paragraph.js: -------------------------------------------------------------------------------- 1 | /* 2 | Example: 3 | 4 | widgets.mixins.editParagraph() 5 | */ 6 | var _ = require('lodash'); 7 | var utils = require('../utils'); 8 | 9 | 10 | module.exports = function() { 11 | return { 12 | findEditRange: function(range) { 13 | var doc = this.doc(); 14 | var nLines = doc.lineCount(); 15 | 16 | function findParagraph(start, direction) { 17 | var line = start.line; 18 | var content; 19 | 20 | do { 21 | line = line + direction; 22 | content = doc.getLine(line); 23 | 24 | } while(content && line >= 0 && line <= (nLines -1)) 25 | 26 | return line; 27 | } 28 | 29 | return utils.Range( 30 | utils.Pos(findParagraph(range.from, -1), 0), 31 | utils.Pos(findParagraph(range.to, 1), 0) 32 | ); 33 | } 34 | }; 35 | }; 36 | -------------------------------------------------------------------------------- /lib/mixins/index.js: -------------------------------------------------------------------------------- 1 | 2 | module.exports = { 3 | menu: require('./menu'), 4 | re: require('./re'), 5 | editParagraph: require('./edit_paragraph'), 6 | rejectTokens: require('./reject_tokens') 7 | }; 8 | -------------------------------------------------------------------------------- /lib/mixins/menu.js: -------------------------------------------------------------------------------- 1 | var _ = require('lodash'); 2 | var utils = require('../utils'); 3 | 4 | 5 | 6 | module.exports = function(opts) { 7 | opts = _.defaults(opts || {}, { 8 | classOpen: 'widget-menu-open', 9 | 10 | entries: [ 11 | { 12 | label: 'Edit', 13 | click: function(w) { 14 | w.enter(); 15 | } 16 | } 17 | ], 18 | position: function(widget) { 19 | var range = widget.find(); 20 | var pos = widget.editor.charCoords(range.from, 'local'); 21 | 22 | return { 23 | left: pos.left, 24 | top: (pos.top + widget.el.offsetHeight) 25 | }; 26 | } 27 | }); 28 | 29 | return { 30 | 31 | enable: function() { 32 | this.closeMenu(); 33 | this.manager.editor.on('unrender', this.onMenuDocClick); 34 | }, 35 | disable: function() { 36 | this.closeMenu(); 37 | this.manager.editor.off('unrender', this.onMenuDocClick); 38 | }, 39 | 40 | // Click anywhere should close the menu 41 | onMenuDocClick: function() { 42 | this.closeMenu(); 43 | }, 44 | 45 | // Keyboard movement should move cursor 46 | onMenuKeyboardDown: function(e) { 47 | var keyCode = e.keyCode; 48 | var moved = false; 49 | var widget = this.manager.menu.widget; 50 | 51 | if (keyCode == 38) { // UP 52 | widget.moveUp(); 53 | moved = true; 54 | } else if (keyCode == 40) { // DOWN 55 | widget.moveDown(); 56 | moved = true; 57 | } else if (keyCode == 37) { // LEFT 58 | widget.moveBefore(); 59 | moved = true; 60 | } else if (keyCode == 39) { // RIGHT 61 | widget.moveAfter(); 62 | moved = true; 63 | } else if (keyCode == 8 || keyCode == 46) { // DELETE 64 | widget.replace(''); 65 | this.manager.editor.focus(); 66 | } 67 | 68 | if (moved) { 69 | this.manager.editor.focus(); 70 | this.closeMenu(); 71 | } 72 | }, 73 | 74 | // Bind/unbind menu event 75 | bindMenuEvents: function() { 76 | this.editor.on('cursorActivity', this.onMenuDocClick); 77 | document.body.addEventListener('click', this.onMenuDocClick, false); 78 | document.body.addEventListener('keydown', this.onMenuKeyboardDown, false); 79 | }, 80 | unbindMenuEvents: function() { 81 | this.editor.off('cursorActivity', this.onMenuDocClick); 82 | document.body.removeEventListener('click', this.onMenuDocClick, false); 83 | document.body.removeEventListener('keydown', this.onMenuKeyboardDown, false); 84 | }, 85 | 86 | // Close opened menu 87 | closeMenu: function(force) { 88 | if (!this.manager.menu || (force !== true && this.manager.ignoreCloseMenu)) return; 89 | 90 | this.unbindMenuEvents(); 91 | 92 | var el = this.manager.menu.el; 93 | var widget = this.manager.menu.widget; 94 | 95 | el.parentNode.removeChild(el); 96 | 97 | utils.domRemoveClass(widget.el, opts.classOpen); 98 | 99 | this.manager.menu = null; 100 | }, 101 | 102 | // Open menu for a widget 103 | // Open new menu 104 | openMenu: function(widget, direction) { 105 | var that = this; 106 | var editor = this.manager.editor; 107 | 108 | this.closeMenu(true); 109 | 110 | // Prevent closing the menu in the loop 111 | this.manager.ignoreCloseMenu = true; 112 | 113 | if (direction == 'before') widget.moveBefore(); 114 | else if (direction == 'after') widget.moveAfter(); 115 | 116 | utils.nextTick(function() { 117 | that.manager.ignoreCloseMenu = false; 118 | that.bindMenuEvents(); 119 | }); 120 | 121 | // Calcul position for menu 122 | var pos = opts.position(widget); 123 | 124 | // Create new menu 125 | var el = document.createElement('div'); 126 | el.className = 'cm-widget-menu menu-'+this.className; 127 | 128 | // Add entries 129 | _.each(widget.menuEntries, function(menuEntry) { 130 | var a = document.createElement('a'); 131 | a.innerText = menuEntry.label; 132 | a.className = menuEntry.selected? 'selected' : ''; 133 | a.href = '#'; 134 | a.onclick = function(e) { 135 | e.preventDefault(); 136 | 137 | that.closeMenu(); 138 | menuEntry.click(widget); 139 | }; 140 | el.appendChild(a); 141 | }); 142 | 143 | // Mesure its size 144 | el.style.display = 'block'; 145 | el.style.visibility = 'hidden'; 146 | el.style.position = 'initial'; 147 | el.style.float = 'left'; 148 | 149 | // Get parent element 150 | var scrollArea = editor 151 | .getWrapperElement() 152 | .getElementsByClassName('CodeMirror-sizer')[0]; 153 | 154 | // Add to dom 155 | scrollArea.appendChild(el); 156 | 157 | var menuWidth = el.offsetWidth; 158 | var containerWidth = scrollArea.offsetWidth; 159 | if (pos.left > (containerWidth - menuWidth)) { 160 | pos.right = 0; 161 | pos.left = undefined; 162 | } 163 | 164 | el.style.display = 'block'; 165 | el.style.visibility = 'initial'; 166 | el.style.position = 'absolute'; 167 | if (!_.isUndefined(pos.left)) el.style.left = pos.left+'px'; 168 | if (!_.isUndefined(pos.right)) el.style.right = pos.right+'px'; 169 | if (!_.isUndefined(pos.top)) el.style.top = pos.top+'px'; 170 | 171 | // Mark element as selected 172 | this.manager.menu = { 173 | el: el, 174 | widget: widget 175 | }; 176 | utils.domAddClass(widget.el, opts.classOpen); 177 | }, 178 | 179 | // Setup menu for a specific widget 180 | prepareWidget: function(widget) { 181 | var that = this; 182 | 183 | widget.menuEntries = _.isFunction(opts.entries)? opts.entries(widget) : opts.entries; 184 | 185 | // Show menu 186 | widget.el.addEventListener('click', function(e) { 187 | if (e.detail > 1) return; 188 | 189 | e.preventDefault(); 190 | if (widget.menuEntries.length == 1) { 191 | widget.menuEntries[0].click(widget); 192 | } else { 193 | that.openMenu(widget, 'before'); 194 | } 195 | }); 196 | 197 | // Trigger first action on double click 198 | widget.el.addEventListener('dblclick', function(e) { 199 | e.preventDefault(); 200 | widget.menuEntries[0].click(widget); 201 | }); 202 | 203 | // Close menu when marker is cleared 204 | widget.marker.on('clear', function() { 205 | that.closeMenu(); 206 | }); 207 | } 208 | 209 | }; 210 | }; -------------------------------------------------------------------------------- /lib/mixins/re.js: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Example: 4 | 5 | widgets.mixins.re(/\$\$([^$]+)\$\$/g, function(match) { 6 | return { 7 | props: { 8 | text: match[1] 9 | } 10 | }; 11 | }) 12 | */ 13 | 14 | 15 | module.exports = function(re, fn) { 16 | return { 17 | find: function(text) { 18 | var matches = [], found; 19 | 20 | re.lastIndex = 0; 21 | 22 | while ((found = re.exec(text)) && found) { 23 | var token = fn(found); 24 | if (!token) continue; 25 | token.start = token.start || 0; 26 | 27 | matches.push({ 28 | start: found.index + token.start, 29 | end: found.index + found[0].length, 30 | props: token.props 31 | }); 32 | } 33 | 34 | return matches; 35 | } 36 | }; 37 | }; 38 | -------------------------------------------------------------------------------- /lib/mixins/reject_tokens.js: -------------------------------------------------------------------------------- 1 | /* 2 | Example: 3 | 4 | widgets.mixins.rejectTokens([ 'comment' ]) 5 | */ 6 | var _ = require('lodash'); 7 | 8 | 9 | module.exports = function(types) { 10 | return { 11 | enable: function() { 12 | this.renderAllOnChange = true; 13 | }, 14 | 15 | filterMatch: function(range, props) { 16 | var token = this.editor.getTokenAt({ ch: range.from.ch + 1, line: range.from.line }); 17 | 18 | if (!token || !token.type) { 19 | return true; 20 | } 21 | 22 | return _.every(token.type.split(' '), function(type){ 23 | return !_.contains(types, type); 24 | }); 25 | } 26 | }; 27 | }; 28 | -------------------------------------------------------------------------------- /lib/type.js: -------------------------------------------------------------------------------- 1 | var _ = require('lodash'); 2 | var util = require('util'); 3 | var EventEmitter = require('events').EventEmitter; 4 | 5 | var utils = require('./utils'); 6 | var Manager = require('./manager'); 7 | var Widget = require('./widget'); 8 | 9 | function WidgetType(manager, opts) { 10 | this.id = _.uniqueId('widgetsType'); 11 | 12 | this.manager = manager; 13 | this.editor = this.manager.editor; 14 | this.opts = opts || {}; 15 | this.enabled = false; 16 | this.renderAllOnChange = false; 17 | 18 | this.onChange = _.debounce(this._onChange, this.debounceWait); 19 | 20 | _.bindAll(this); 21 | } 22 | util.inherits(WidgetType, EventEmitter); 23 | 24 | WidgetType.prototype.className = 'widget'; 25 | WidgetType.prototype.debounceWait = 500; 26 | 27 | // Return all occurrences in a text 28 | WidgetType.prototype.find = function(text) { 29 | return []; 30 | }; 31 | 32 | // Compare props of markers 33 | WidgetType.prototype.compareProps = function(p1, p2) { 34 | return _.isEqual(p1, p2); 35 | }; 36 | 37 | // If edition is not inside a marker, detect section to process 38 | // For example if the widget is inline, we can limit this to a single line 39 | // Should return a range 40 | WidgetType.prototype.findEditRange = function(range) { 41 | return range; 42 | }; 43 | 44 | // Create the dom element for a specific widget 45 | WidgetType.prototype.createElement = function(widget) { 46 | var el = document.createElement('span'); 47 | return el; 48 | }; 49 | 50 | // Create a new widget 51 | WidgetType.prototype.createWidget = function(range, props) { 52 | var that = this; 53 | var rejected = !this.filterMatch(range, props); 54 | var markers, cursor, doc, exists; 55 | 56 | doc = this.doc(); 57 | 58 | // Check if the marker already exists 59 | markers = doc.findMarksAt(range.from); 60 | exists = _.find(markers, function(marker) { 61 | return (!marker.unrendered && 62 | marker.xType == that.id && 63 | that.compareProps(marker.xProps, props)); 64 | }); 65 | 66 | // Clear existing if rejected 67 | if (rejected) { 68 | if (exists) exists.clear(); 69 | return; 70 | } 71 | 72 | // Don't rerender an identical widget 73 | if (exists) return; 74 | 75 | // Is cursor inside? 76 | cursor = doc.getCursor(); 77 | if (utils.posInsideRange(cursor, range)) { 78 | this.unrenderRange(range, props); 79 | } else { 80 | var widget = new Widget(this, range, props); 81 | 82 | widget.marker.on('clear', function(_from, _to) { 83 | if (!that.enabled) return; 84 | 85 | that.unrenderRange(utils.Range(_from, _to), props); 86 | }); 87 | 88 | that.prepareWidget(widget); 89 | } 90 | }; 91 | 92 | // Prepare a widget 93 | // Can be extend by mixin (see "menu") 94 | WidgetType.prototype.prepareWidget = function(widget) { 95 | 96 | } 97 | 98 | // Render as text a marker 99 | WidgetType.prototype.unrenderRange = function(range, props) { 100 | var doc = this.doc(); 101 | var marker = this.bindMarker(doc.markText(range.from, range.to), props); 102 | this.manager.setUnrendered(marker); 103 | } 104 | 105 | // Bind a marker to be identifiable 106 | WidgetType.prototype.bindMarker = function(marker, props) { 107 | marker.xProps = props; 108 | marker.xType = this.id; 109 | return marker; 110 | }; 111 | 112 | // Create a marker for a widget 113 | WidgetType.prototype.createWidgetMarker = function(from, to, props, opts) { 114 | var marker = this.doc().markText(from, to, _.extend(opts || {}, { 115 | clearOnEnter: true, 116 | atomic: true 117 | })); 118 | return this.bindMarker(marker, props); 119 | }; 120 | 121 | // Filter a match 122 | WidgetType.prototype.filterMatch = function(range, match) { 123 | return true; 124 | }; 125 | 126 | // Convert a list of matches in widgets 127 | WidgetType.prototype.processMatches = function(from, matches) { 128 | if (matches.length == 0) return; 129 | 130 | var that = this; 131 | 132 | that.editor.operation(function() { 133 | 134 | var fromIndex = from? that.editor.indexFromPos(from) : 0; 135 | var doc = that.doc(); 136 | 137 | _.each(matches, function(match) { 138 | var range = utils.Range( 139 | doc.posFromIndex(fromIndex + match.start), 140 | doc.posFromIndex(fromIndex + match.end) 141 | ); 142 | 143 | that.createWidget(range, match.props); 144 | }); 145 | }); 146 | }; 147 | 148 | // Apply widgets in a specific sections 149 | WidgetType.prototype.processRange = function(range) { 150 | // Extract text 151 | var text = this.doc().getRange(range.from, range.to); 152 | 153 | // Extract matches 154 | var matches = this.find(text, range); 155 | 156 | // Process matches 157 | this.processMatches(range.from, matches); 158 | }; 159 | 160 | // Render all widgets 161 | WidgetType.prototype.renderAll = function() { 162 | var that = this; 163 | 164 | // Extract text 165 | var text = this.doc().getValue(); 166 | 167 | // Extract matches 168 | var matches = this.find(text); 169 | 170 | this.processMatches({ 171 | line: 0, 172 | ch: 0 173 | }, matches); 174 | }; 175 | 176 | // Unrender all widgets 177 | WidgetType.prototype.unrenderAll = function() { 178 | var that = this; 179 | 180 | _.each(this.doc().getAllMarks(), function(mark) { 181 | if (mark.xType != that.id) return; 182 | mark.clear(); 183 | }); 184 | }; 185 | 186 | // Cleanup all markers in a specified range 187 | // Return the largest range that contain markers 188 | WidgetType.prototype.cleanupMarkers = function(origin) { 189 | var that = this; 190 | var range = { from: origin.from, to: origin.to }; 191 | 192 | _.each(this.doc().getAllMarks(), function(mark) { 193 | if (mark.xType != that.id) return; 194 | 195 | var markRange = mark.find(); 196 | if (!markRange) return; 197 | 198 | var isInRange = utils.isPos(markRange)? utils.posInsideRange(markRange, origin) : utils.rangesOverlap(markRange, origin); 199 | if (!isInRange) return; 200 | 201 | if (utils.posIsBefore(markRange.from, range.from)) { 202 | range.from = markRange.from; 203 | } 204 | if (utils.posIsBefore(range.to, markRange.to)) { 205 | range.to = markRange.to; 206 | } 207 | 208 | mark.clear(); 209 | }); 210 | 211 | return range; 212 | }; 213 | 214 | // Process change from the editor 215 | WidgetType.prototype.processChange = function(change) { 216 | if (this.renderAllOnChange || change.origin == 'setValue') { 217 | return this.renderAll(); 218 | } 219 | 220 | // Calcul range of change (change is pre-operation) 221 | var changeRange = { 222 | from: utils.Pos(change.from.line, change.from.ch), 223 | to: utils.Pos(change.to.line + (change.text.length - 1), change.to.ch + _.last(change.text).length) 224 | }; 225 | 226 | // Determine large range and cleanup markers in it 227 | var range = this.cleanupMarkers(changeRange); 228 | 229 | // If nothing found, find larger section to process 230 | if (utils.posEqual(changeRange, range)) { 231 | range = this.findEditRange(changeRange); 232 | this.cleanupMarkers(changeRange); 233 | } 234 | 235 | // Update markers in this range 236 | this.processRange(range); 237 | }; 238 | 239 | // Editor content changed 240 | // Debounce processing 241 | WidgetType.prototype._onChange = function(inst, change) { 242 | this.processChange(change); 243 | }; 244 | 245 | 246 | WidgetType.prototype.enable = function() { 247 | if (this.enabled) return; 248 | 249 | this.enabled = true; 250 | this.manager.editor.on('change', this.onChange); 251 | this.renderAll(); 252 | }; 253 | 254 | WidgetType.prototype.disable = function() { 255 | if (!this.enabled) return; 256 | 257 | this.enabled = false; 258 | this.manager.editor.off('change', this.onChange); 259 | this.unrenderAll(); 260 | }; 261 | 262 | // Return the concerned document 263 | WidgetType.prototype.doc = function() { 264 | return this.manager.doc(); 265 | }; 266 | 267 | 268 | // Define option to CodeMirror 269 | function setupOption(Type, CodeMirror) { 270 | CodeMirror.defineOption(Type.prototype.className + 'Widget', false, function(cm, val, old) { 271 | if (old == CodeMirror.Init) old = false; 272 | if (val == old) return; 273 | 274 | // If editor has no manager, add one 275 | if (!cm._widgets) Manager(cm); 276 | 277 | if (val) { 278 | cm._widgets.enable(Type, val); 279 | } else { 280 | cm._widgets.disable(Type); 281 | } 282 | }); 283 | } 284 | 285 | // Create an new type 286 | function createType(type) { 287 | var CustomType = function() { 288 | WidgetType.apply(this, arguments); 289 | }; 290 | util.inherits(CustomType, WidgetType); 291 | 292 | CustomType.prototype = utils.composeMixins( 293 | CustomType.prototype, 294 | (type.mixins || []).concat([type]), 295 | { 296 | composables: ['enable', 'disable', 'prepareWidget'] 297 | } 298 | ); 299 | 300 | CustomType.id = _.uniqueId('WidgetType'); 301 | CustomType.setupOption = _.partial(setupOption, CustomType); 302 | 303 | return CustomType; 304 | } 305 | 306 | 307 | module.exports = { 308 | WidgetType: WidgetType, 309 | create: createType 310 | }; 311 | -------------------------------------------------------------------------------- /lib/utils.js: -------------------------------------------------------------------------------- 1 | var _ = require('lodash'); 2 | 3 | // Compose a prototype and a mixin 4 | function composeMixin(proto, mixin, opts) { 5 | opts = _.defaults(opts || {}, { 6 | // List of methods that are composables 7 | composables: [] 8 | }); 9 | 10 | _.each(mixin, function(method, key) { 11 | var isComposable = _.contains(opts.composables, key); 12 | 13 | if (!isComposable || !proto[key]) { 14 | proto[key] = method; 15 | } else { 16 | var precedent = proto[key]; 17 | proto[key] = function() { 18 | precedent.apply(this, arguments); 19 | method.apply(this, arguments); 20 | }; 21 | } 22 | }); 23 | 24 | return proto; 25 | } 26 | function composeMixins(proto, mixins, opts) { 27 | return _.reduce(mixins, function(p, mixin) { 28 | return composeMixin(p, mixin, opts); 29 | }, proto); 30 | } 31 | 32 | /*** Utility for DOM API ***/ 33 | 34 | function domAddClass(el, className) { 35 | if (el.classList) { 36 | el.classList.add(className); 37 | } else { 38 | el.className += ' ' + className; 39 | } 40 | } 41 | function domRemoveClass(el, className) { 42 | if (el.classList) { 43 | el.classList.remove(className); 44 | } else { 45 | el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); 46 | } 47 | } 48 | 49 | 50 | /*** Utility for ranges and positions ***/ 51 | 52 | function Pos(line, ch) { 53 | return { 54 | line: line, 55 | ch: ch 56 | }; 57 | } 58 | 59 | function Range(from, to) { 60 | return { 61 | from: from, 62 | to: to 63 | }; 64 | } 65 | 66 | // Return true if object is a position 67 | function isPos(pos) { 68 | return _.isUndefined(pos.line); 69 | } 70 | 71 | // Return true if object is a range 72 | function isRange(pos) { 73 | return _.isUndefined(pos.from); 74 | } 75 | 76 | // Return negative / 0 / positive. a < b iff posCmp(a, b) < 0 etc. 77 | function posCmp(a, b) { 78 | return (a.line - b.line) || (a.ch - b.ch); 79 | } 80 | function posIsBefore(a, b) { 81 | return (posCmp(a, b) < 0); 82 | } 83 | 84 | // True if inside, false if on edge. 85 | function posInsideRange(pos, range) { 86 | return posCmp(range.from, pos) < 0 && posCmp(pos, range.to) < 0; 87 | } 88 | 89 | // True if outside, true if on edge 90 | function posOutsideRange(pos, range) { 91 | return posCmp(range.from, pos) > 0 || posCmp(pos, range.to) > 0; 92 | } 93 | 94 | // True if there is at least one character in common, false if just touching. 95 | function rangesOverlap(fromTo1, fromTo2) { 96 | return (posCmp(fromTo1.from, fromTo2.to) < 0 && 97 | posCmp(fromTo2.from, fromTo1.to) < 0); 98 | } 99 | 100 | // True if position are equal 101 | function posEqual(r1, r2) { 102 | return (r1.line == r2.line && r2.ch == r1.ch); 103 | } 104 | 105 | // Process fn in next tick 106 | function nextTick(fn) { 107 | setTimeout(function() { 108 | fn(); 109 | }, 1); 110 | } 111 | 112 | module.exports = { 113 | Pos: Pos, 114 | Range: Range, 115 | 116 | composeMixin: composeMixin, 117 | composeMixins: composeMixins, 118 | 119 | domAddClass: domAddClass, 120 | domRemoveClass: domRemoveClass, 121 | posCmp: posCmp, 122 | posInsideRange: posInsideRange, 123 | posOutsideRange: posOutsideRange, 124 | posIsBefore: posIsBefore, 125 | rangesOverlap: rangesOverlap, 126 | posEqual: posEqual, 127 | isRange: isRange, 128 | isPos: isPos, 129 | 130 | nextTick: nextTick 131 | }; 132 | -------------------------------------------------------------------------------- /lib/widget.js: -------------------------------------------------------------------------------- 1 | var _ = require('lodash'); 2 | 3 | function Widget(type, originalRange, props) { 4 | _.bindAll(this); 5 | 6 | this.originalRange = originalRange; 7 | this.type = type; 8 | this.ctx = this.type.opts; 9 | this.props = props; 10 | 11 | this.doc = this.type.doc(); 12 | this.editor = this.doc.getEditor(); 13 | 14 | // Create DOM element 15 | this.el = this.type.createElement(this); 16 | this.el.className = this.el.className + ' cm-widget'; 17 | 18 | // Create codemirror marker 19 | this.marker = this.type.createWidgetMarker(this.originalRange.from, this.originalRange.to, this.props, { 20 | replacedWith: this.el 21 | }); 22 | } 23 | 24 | // Return exact range of widget 25 | Widget.prototype.find = function() { 26 | return (this.marker? this.marker.find() : this.originalRange); 27 | }; 28 | 29 | // Signal to codemirror that the size of the widget has changed 30 | Widget.prototype.update = function() { 31 | if (this.marker) this.marker.changed(); 32 | }; 33 | 34 | // Move cursor inside the widget 35 | Widget.prototype.enter = function(pos) { 36 | pos = _.defaults(pos || {}, { 37 | line: 0, 38 | ch: 1 39 | }); 40 | var markerPos = this.find(); 41 | 42 | this.doc.setCursor({ 43 | ch: pos.line == 0? (markerPos.from.ch + pos.ch) : pos.ch, 44 | line: markerPos.from.line + pos.line 45 | }); 46 | this.editor.focus(); 47 | }; 48 | 49 | // Move cursor before the widget 50 | Widget.prototype.moveBefore = function() { 51 | var markerPos = this.find(); 52 | this.doc.setCursor({ 53 | ch: markerPos.from.ch, 54 | line: markerPos.from.line 55 | }); 56 | }; 57 | 58 | // Move cursor after the widget 59 | Widget.prototype.moveAfter = function() { 60 | var markerPos = this.find(); 61 | this.doc.setCursor({ 62 | ch: markerPos.to.ch, 63 | line: markerPos.to.line 64 | }); 65 | }; 66 | 67 | // Move cursor the line before the widget 68 | Widget.prototype.moveUp = function() { 69 | var markerPos = this.find(); 70 | this.doc.setCursor({ 71 | ch: markerPos.from.ch, 72 | line: markerPos.from.line - 1 73 | }); 74 | }; 75 | 76 | // Move cursor the line after the widget 77 | Widget.prototype.moveDown = function() { 78 | var markerPos = this.find(); 79 | this.doc.setCursor({ 80 | ch: markerPos.to.ch, 81 | line: markerPos.to.line + 1 82 | }); 83 | }; 84 | 85 | 86 | // Replace widget text 87 | Widget.prototype.replace = function(text) { 88 | var range = this.find(); 89 | this.doc.replaceRange(text, range.from, range.to); 90 | }; 91 | 92 | module.exports = Widget; 93 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "codemirror-widgets", 3 | "version": "1.4.2", 4 | "main": "./lib/index.js", 5 | "author": "Samy Pessé ", 6 | "description": "Utility to write interactive widgets for CodeMirror", 7 | "bugs": "https://github.com/SamyPesse/codemirror-widgets/issues", 8 | "license": "Apache-2.0", 9 | "dependencies": { 10 | "lodash": "^3.10.1", 11 | "escape-regexp": "0.0.1" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "https://github.com/SamyPesse/codemirror-widgets/issues" 16 | } 17 | } --------------------------------------------------------------------------------