editor-commands-controller.js (2382B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 "use strict"; 6 7 /** 8 * The source editor exposes XUL commands that can be used when embedded in a XUL 9 * document. This controller drives the availability and behavior of the commands. When 10 * the editor input field is focused, this controller will update the matching menu item 11 * entries found in application menus or context menus. 12 */ 13 14 /** 15 * Returns a controller object that can be used for editor-specific commands: 16 * - find 17 * - find again 18 * - go to line 19 * - undo 20 * - redo 21 * - delete 22 * - select all 23 */ 24 function createController(ed) { 25 return { 26 supportsCommand(cmd) { 27 switch (cmd) { 28 case "cmd_find": 29 case "cmd_findAgain": 30 case "cmd_gotoLine": 31 case "cmd_undo": 32 case "cmd_redo": 33 case "cmd_delete": 34 case "cmd_selectAll": 35 return true; 36 } 37 38 return false; 39 }, 40 41 isCommandEnabled(cmd) { 42 const cm = ed.codeMirror; 43 44 switch (cmd) { 45 case "cmd_find": 46 case "cmd_gotoLine": 47 case "cmd_selectAll": 48 return true; 49 case "cmd_findAgain": 50 return cm.state.search != null && cm.state.search.query != null; 51 case "cmd_undo": 52 return ed.canUndo(); 53 case "cmd_redo": 54 return ed.canRedo(); 55 case "cmd_delete": 56 return ed.somethingSelected(); 57 } 58 59 return false; 60 }, 61 62 doCommand(cmd) { 63 const cm = ed.codeMirror; 64 65 const map = { 66 cmd_selectAll: "selectAll", 67 cmd_find: "find", 68 cmd_undo: "undo", 69 cmd_redo: "redo", 70 cmd_delete: "delCharAfter", 71 cmd_findAgain: "findNext", 72 }; 73 74 if (map[cmd]) { 75 cm.execCommand(map[cmd]); 76 return; 77 } 78 79 if (cmd == "cmd_gotoLine") { 80 ed.jumpToLine(); 81 } 82 }, 83 84 onEvent() {}, 85 }; 86 } 87 88 /** 89 * Create and insert a commands controller for the provided SourceEditor instance. 90 */ 91 function insertCommandsController(sourceEditor) { 92 const input = sourceEditor.codeMirror.getInputField(); 93 const controller = createController(sourceEditor); 94 input.controllers.insertControllerAt(0, controller); 95 } 96 97 module.exports = { insertCommandsController };