How to use completion method in Karma

Best JavaScript code snippet using karma

TsCodeCompletion.js

Source:TsCodeCompletion.js Github

copy

Full Screen

1/*2 * This file is part of the TYPO3 CMS project.3 *4 * It is free software; you can redistribute it and/or modify it under5 * the terms of the GNU General Public License, either version 26 * of the License, or any later version.7 *8 * For the full copyright and license information, please read the9 * LICENSE.txt file that was distributed with this source code.10 *11 * The TYPO3 project - inspiring people to share!12 */13/**14 * Module: TYPO3/CMS/T3editor/CodeCompletion/TsCodeCompletion15 * Contains the TsCodeCompletion class16 */17define([18 'jquery',19 'TYPO3/CMS/T3editor/Plugins/CodeCompletion/TsRef',20 'TYPO3/CMS/T3editor/Plugins/CodeCompletion/TsParser',21 'TYPO3/CMS/T3editor/Plugins/CodeCompletion/CompletionResult'22], function ($, TsRef, TsParser, CompletionResult) {23 /**24 *25 * @type {{tsRef: *, outerDiv: null, options: {ccWords: number}, index: number, currWord: number, cc_up: null, cc_down: null, mousePos: {x: number, y: number}, proposals: null, compResult: null, cc: number, linefeedsPrepared: boolean, currentCursorPosition: null, extTsObjTree: {}, latestCursorNode: null, codemirror: null, parser: null, plugins: string[], $codeCompleteBox: (*|jQuery)}}26 * @exports TYPO3/CMS/T3editor/CodeCompletion/TsCodeCompletion27 */28 var TsCodeCompletion = {29 tsRef: TsRef,30 outerDiv: null,31 options: {32 ccWords : 1033 },34 index: 0,35 currWord: 0,36 cc_up: null,37 cc_down: null,38 mousePos: {39 x:0,40 y:041 },42 proposals: null,43 compResult: null,44 cc: 0,45 linefeedsPrepared: false,46 currentCursorPosition: null,47 extTsObjTree: {},48 latestCursorNode: null,49 codemirror: null,50 parser: null,51 plugins: [52 'TYPO3/CMS/T3editor/Plugins/CodeCompletion/DescriptionPlugin'53 ],54 $codeCompleteBox: $('<div />', {class: 't3e_codeCompleteWrap'}).append(55 $('<div />', {class: 't3e_codeCompleteBox'})56 )57 };58 /**59 * All external templates along the rootline have to be loaded,60 * this function retrieves the JSON code by comitting a AJAX request61 */62 TsCodeCompletion.loadExtTemplatesAsync = function() {63 var id = TsCodeCompletion.getGetVar('id');64 if (id === '') {65 return;66 }67 $.ajax({68 url: TYPO3.settings.ajaxUrls['t3editor_codecompletion_loadtemplates'],69 data: {70 pageId: id71 },72 success: function(response) {73 TsCodeCompletion.extTsObjTree.c = response;74 TsCodeCompletion.resolveExtReferencesRec(TsCodeCompletion.extTsObjTree.c);75 }76 });77 };78 /**79 * Load registered plugins80 */81 TsCodeCompletion.loadPluginArray = function() {82 $.ajax({83 url: TYPO3.settings.ajaxUrls['t3editor_get_plugins'],84 success: function(response) {85 TsCodeCompletion.plugins = $.merge(TsCodeCompletion.plugins, response);86 // register an internal plugin87 TsCodeCompletion.loadPlugins();88 }89 });90 };91 /**92 * Load and initialize the plugins fetched by TsCodeCompletion.loadPluginArray()93 */94 TsCodeCompletion.loadPlugins = function() {95 for (var i = 0; i < TsCodeCompletion.plugins.length; i++) {96 require([TsCodeCompletion.plugins[i]], function(plugin) {97 if (typeof plugin.init === 'function') {98 plugin.init({99 tsRef: TsCodeCompletion.tsRef,100 codeCompleteBox: TsCodeCompletion.$codeCompleteBox,101 codemirror: TsCodeCompletion.codemirror102 });103 } else {104 console.warn('Cannot initialize plugin ' + TsCodeCompletion.plugins[i] + ', missing "init" method');105 }106 });107 }108 };109 /**110 * Get the value of a given GET parameter111 *112 * @param {String} name113 * @return {String}114 */115 TsCodeCompletion.getGetVar = function(name) {116 var get_string = document.location.search,117 return_value = '',118 value;119 do { //This loop is made to catch all instances of any get variable.120 var name_index = get_string.indexOf(name + '=');121 if (name_index !== -1) {122 get_string = get_string.substr(name_index + name.length + 1, get_string.length - name_index);123 var end_of_value = get_string.indexOf('&');124 if (end_of_value !== -1) {125 value = get_string.substr(0, end_of_value);126 } else {127 value = get_string;128 }129 if (return_value === '' || value === '') {130 return_value += value;131 } else {132 return_value += ', ' + value;133 }134 }135 } while (name_index !== -1);136 // Restores all the blank spaces.137 var space = return_value.indexOf('+');138 while (space !== -1) {139 return_value = return_value.substr(0, space) + ' ' + return_value.substr(space + 1, return_value.length);140 space = return_value.indexOf('+');141 }142 return return_value;143 };144 /**145 * Since the references are not resolved server side we have to do it client-side146 * Benefit: less loading time due to less data which has to be transmitted147 *148 * @param {Array} childNodes149 */150 TsCodeCompletion.resolveExtReferencesRec = function(childNodes) {151 for (var key in childNodes) {152 var childNode;153 // if the childnode has a value and there is a part of a reference operator ('<')154 // and it does not look like a html tag ('>')155 if (childNodes[key].v && childNodes[key].v[0] === '<' && childNodes[key].v.indexOf('>') === -1 ) {156 var path = $.trim(childNodes[key].v.replace(/</, ''));157 // if there are still whitespaces it's no path158 if (path.indexOf(' ') === -1) {159 childNode = TsCodeCompletion.getExtChildNode(path);160 // if the node was found - reference it161 if (childNode !== null) {162 childNodes[key] = childNode;163 }164 }165 }166 // if there was no reference-resolving then we go deeper into the tree167 if (!childNode && childNodes[key].c) {168 TsCodeCompletion.resolveExtReferencesRec(childNodes[key].c);169 }170 }171 };172 /**173 * Get the child node of given path174 *175 * @param {String} path176 * @returns {Object}177 */178 TsCodeCompletion.getExtChildNode = function(path) {179 var extTree = TsCodeCompletion.extTsObjTree,180 path = path.split('.'),181 pathSeg;182 for (var i = 0; i < path.length; i++) {183 pathSeg = path[i];184 if (typeof extTree.c === 'undefined' || typeof extTree.c[pathSeg] === 'undefined') {185 return null;186 }187 extTree = extTree.c[pathSeg];188 }189 return extTree;190 };191 /**192 * Replaces editor functions insertNewlineAtCursor and indentAtCursor193 * with modified ones that only execute when codecompletion box is not shown194 * @todo check if this works correctly after updating the codemirror base195 */196 TsCodeCompletion.prepareLinefeeds = function() {197 TsCodeCompletion.codemirror.win.select.insertNewlineAtCursor_original = TsCodeCompletion.codemirror.win.select.insertNewlineAtCursor;198 TsCodeCompletion.codemirror.win.select.insertNewlineAtCursor = function(window) {199 if (TsCodeCompletion.cc === 0) {200 TsCodeCompletion.codemirror.win.select.insertNewlineAtCursor_original(window);201 }202 };203 TsCodeCompletion.codemirror.editor.indentAtCursor_original = TsCodeCompletion.codemirror.editor.indentAtCursor;204 TsCodeCompletion.codemirror.editor.indentAtCursor = function() {205 if (TsCodeCompletion.cc === 0) {206 TsCodeCompletion.codemirror.editor.indentAtCursor_original();207 }208 };209 TsCodeCompletion.linefeedsPrepared = true;210 };211 /**212 *213 */214 TsCodeCompletion.click = function() {215 TsCodeCompletion.endAutoCompletion();216 };217 /**218 *219 * @param cursorNode220 * @returns {*}221 */222 TsCodeCompletion.getFilter = function(cursorNode) {223 if (cursorNode.currentText) {224 var filter = cursorNode.currentText.replace('.', '');225 return filter.replace(/\s/g, '');226 }227 return '';228 };229 /**230 * @returns {*}231 */232 TsCodeCompletion.getCursorNode = function() {233 var cursorNode = TsCodeCompletion.codemirror.win.select.selectionTopNode(TsCodeCompletion.codemirror.win.document.body, false);234 // cursorNode is null if the cursor is positioned at the beginning of the first line235 if (cursorNode === null) {236 cursorNode = TsCodeCompletion.codemirror.editor.container.firstChild;237 } else if (cursorNode.tagName === 'BR') {238 // if cursor is at the end of the line -> jump to beginning of the next line239 cursorNode = cursorNode.nextSibling;240 }241 return cursorNode;242 };243 /**244 *245 * @param {Object} cursor246 * @returns {String}247 */248 TsCodeCompletion.getCurrentLine = function(cursor) {249 var line = '',250 currentNode = cursor.start.node.parentNode;251 while (currentNode.tagName !== 'BR') {252 if (currentNode.hasChildNodes()253 && currentNode.firstChild.nodeType === 3254 && currentNode.currentText.length > 0)255 {256 line = currentNode.currentText + line;257 }258 if (typeof currentNode.previousSibling === 'undefined') {259 break;260 } else {261 currentNode = currentNode.previousSibling;262 }263 }264 return line;265 };266 /**267 * Eventhandler function executed after keystroke release268 * triggers CC on pressed dot and typing on269 *270 * @param {Event} e fired prototype event object271 * @type void272 */273 TsCodeCompletion.keyUp = function(e) {274 // 190 = .275 if (e.which === 190) {276 TsCodeCompletion.initCodeCompletion();277 TsCodeCompletion.refreshCodeCompletion();278 } else if (TsCodeCompletion.cc === 1) {279 // 38 = KEYUP, 40 = KEYDOWN280 if (e.which !== 40 && e.which !== 38) {281 if (e.which === 13) {282 // return283 e.preventDefault();284 if (TsCodeCompletion.currWord !== -1) {285 TsCodeCompletion.insertCurrWordAtCursor();286 }287 TsCodeCompletion.endAutoCompletion();288 } else {289 TsCodeCompletion.refreshCodeCompletion();290 }291 }292 }293 };294 /**295 * Highlights entry in codecomplete box by id296 *297 * @param {Number} id298 */299 TsCodeCompletion.mouseOver = function(id) {300 TsCodeCompletion.highlightCurrWord(id);301 for (var i = 0; i < TsCodeCompletion.plugins.length; i++) {302 require([TsCodeCompletion.plugins[i]], function(plugin) {303 if (typeof plugin.afterMouseOver === 'function') {304 plugin.afterMouseOver(TsCodeCompletion.proposals[TsCodeCompletion.currWord], TsCodeCompletion.compResult);305 }306 });307 }308 };309 /**310 * Event handler function executed after clicking in the editor.311 */312 TsCodeCompletion.click = function() {313 if (TsCodeCompletion.latestCursorNode !== TsCodeCompletion.getCursorNode()) {314 TsCodeCompletion.endAutoCompletion();315 }316 };317 /**318 * Eventhandler function executed after keystroke release319 * triggers CC on pressed dot and typing on320 *321 * @param {Event} e fired prototype event object322 */323 TsCodeCompletion.keyDown = function(e) {324 if (!TsCodeCompletion.linefeedsPrepared) {325 TsCodeCompletion.prepareLinefeeds();326 }327 if (TsCodeCompletion.cc === 1) {328 if (e.which === 38) {329 // Arrow up: move up cursor in codecomplete box330 e.preventDefault();331 TsCodeCompletion.codeCompleteBoxMoveUpCursor();332 for (var i = 0; i < TsCodeCompletion.plugins.length; i++) {333 require([TsCodeCompletion.plugins[i]], function(plugin) {334 if (typeof plugin.afterKeyUp === 'function') {335 plugin.afterKeyUp(TsCodeCompletion.proposals[TsCodeCompletion.currWord], TsCodeCompletion.compResult);336 }337 });338 }339 } else if (e.which === 40) {340 // Arrow down: move down cursor in codecomplete box341 e.preventDefault();342 TsCodeCompletion.codeCompleteBoxMoveDownCursor();343 for (var i = 0; i < TsCodeCompletion.plugins.length; i++) {344 require([TsCodeCompletion.plugins[i]], function(plugin) {345 if (typeof plugin.afterKeyDown === 'function') {346 plugin.afterKeyDown(TsCodeCompletion.proposals[TsCodeCompletion.currWord], TsCodeCompletion.compResult);347 }348 });349 }350 } else if (e.which === 27 || e.which === 37 || e.which === 39) {351 // Esc, Arrow Left, Arrow Right: if codecomplete box is showing, hide it352 TsCodeCompletion.endAutoCompletion();353 } else if (e.which === 32 && (!e.ctrlKey || !e.metaKey)) {354 // space355 TsCodeCompletion.endAutoCompletion();356 } else if (e.which === 32 && (e.ctrlKey || e.metaKey)) {357 // CTRL + space358 TsCodeCompletion.refreshCodeCompletion();359 } else if (e.which === 8) {360 // backspace361 var cursorNode = TsCodeCompletion.codemirror.win.select.selectionTopNode(TsCodeCompletion.codemirror.win.document.body, false);362 if (cursorNode.innerHTML === '.') {363 // force full refresh at keyUp364 TsCodeCompletion.compResult = null;365 }366 }367 } else { // if autocompletion is deactivated and ctrl+space is pressed368 if (e.which === 32 && (e.ctrlKey || e.metaKey)) {369 e.preventDefault();370 TsCodeCompletion.initCodeCompletion();371 TsCodeCompletion.refreshCodeCompletion();372 }373 }374 };375 /**376 * Initializes the code completion377 */378 TsCodeCompletion.initCodeCompletion = function() {379 if (TsCodeCompletion.outerDiv.has(TsCodeCompletion.$codeCompleteBox).length === 0) {380 TsCodeCompletion.outerDiv.append(TsCodeCompletion.$codeCompleteBox);381 }382 };383 /**384 * Refreshes the code completion list based on the cursor's position385 */386 TsCodeCompletion.refreshCodeCompletion = function() {387 // init vars for up/down moving in word list388 TsCodeCompletion.cc_up = 0;389 TsCodeCompletion.cc_down = TsCodeCompletion.options.ccWords-1;390 // clear the last completion wordposition391 TsCodeCompletion.currWord = -1;392 TsCodeCompletion.codemirror.editor.highlightAtCursor();393 // retrieves the node right to the cursor394 TsCodeCompletion.currentCursorPosition = TsCodeCompletion.codemirror.win.select.markSelection(TsCodeCompletion.codemirror);395 TsCodeCompletion.latestCursorNode = TsCodeCompletion.getCursorNode();396 // the cursornode has to be stored cause inserted breaks have to be deleted after pressing enter if the codecompletion is active397 var filter = TsCodeCompletion.getFilter(TsCodeCompletion.latestCursorNode);398 if (TsCodeCompletion.compResult === null || TsCodeCompletion.latestCursorNode.innerHTML === '.') {399 // TODO: implement cases: operatorCompletion reference/copy path completion (formerly found in getCompletionResults())400 var currentTsTreeNode = TsCodeCompletion.parser.buildTsObjTree(TsCodeCompletion.codemirror.editor.container.firstChild, TsCodeCompletion.latestCursorNode);401 TsCodeCompletion.compResult = CompletionResult.init({402 tsRef: TsRef,403 tsTreeNode: currentTsTreeNode404 });405 }406 TsCodeCompletion.proposals = TsCodeCompletion.compResult.getFilteredProposals(filter);407 // if proposals are found - show box408 if (TsCodeCompletion.proposals.length > 0) {409 // TODO: Drop instance dependency410 var index = 0;411 // make UL list of completation proposals412 var $ul = $('<ul />');413 for (var i = 0; i < TsCodeCompletion.proposals.length; i++) {414 var $li = $('<li />', {id: 'cc_word_' + i}).data('item', i).append(415 $('<span />', {class: 'word_' + TsCodeCompletion.proposals[i].cssClass}).text(TsCodeCompletion.proposals[i].word)416 ).on('click', function() {417 TsCodeCompletion.insertCurrWordAtCursor($(this).data('item'));418 TsCodeCompletion.endAutoCompletion();419 }).on('mouseover', function() {420 TsCodeCompletion.mouseOver($(this).data('item'));421 });422 $ul.append($li);423 }424 // put HTML and show box425 var $codeCompleteBox = TsCodeCompletion.$codeCompleteBox.find('.t3e_codeCompleteBox');426 $codeCompleteBox.html($ul);427 $codeCompleteBox.scrollTop(0);428 // init styles429 $codeCompleteBox.css({430 overflow: 'scroll',431 height: ((TsCodeCompletion.options.ccWords + 1) * $('#cc_word_0').height()) + 'px'432 });433 var wrapOffset = TsCodeCompletion.codemirror.options.originalTextarea.parent().find('.t3e_iframe_wrap').offset(),434 $cursorNode = $(TsCodeCompletion.latestCursorNode),435 nodeOffset = $cursorNode.offset();436 var leftpos = Math.round(wrapOffset.left + nodeOffset.left + TsCodeCompletion.latestCursorNode.offsetWidth) + 'px',437 toppos = Math.round($cursorNode.position().top + TsCodeCompletion.latestCursorNode.offsetHeight - $cursorNode.scrollTop()) + 'px';438 TsCodeCompletion.$codeCompleteBox.css({439 left: leftpos,440 top: toppos441 });442 // set flag to 1 - needed for continue typing word.443 TsCodeCompletion.cc = 1;444 // highlight first word in list445 TsCodeCompletion.highlightCurrWord(0);446 for (var i = 0; i < TsCodeCompletion.plugins.length; i++) {447 require([TsCodeCompletion.plugins[i]], function(plugin) {448 if (typeof plugin.afterCCRefresh === 'function') {449 plugin.afterCCRefresh(TsCodeCompletion.proposals[TsCodeCompletion.currWord], TsCodeCompletion.compResult);450 }451 });452 }453 } else {454 TsCodeCompletion.endAutoCompletion();455 }456 };457 /**458 * Stop code completion and call hooks459 */460 TsCodeCompletion.endAutoCompletion = function() {461 TsCodeCompletion.cc = 0;462 TsCodeCompletion.$codeCompleteBox.remove();463 // force full refresh464 TsCodeCompletion.compResult = null;465 for (var i = 0; i < TsCodeCompletion.plugins.length; i++) {466 require([TsCodeCompletion.plugins[i]], function(plugin) {467 if (typeof plugin.endCodeCompletion === 'function') {468 plugin.endCodeCompletion();469 }470 });471 }472 };473 /**474 * Move cursor in autocomplete box up475 */476 TsCodeCompletion.codeCompleteBoxMoveUpCursor = function() {477 var id;478 // if previous position was first or position not initialized - then move cursor to last word, else decrease position479 if (TsCodeCompletion.currWord === 0 || TsCodeCompletion.currWord === -1) {480 id = TsCodeCompletion.proposals.length - 1;481 } else {482 id = TsCodeCompletion.currWord - 1;483 }484 // hightlight new cursor position485 TsCodeCompletion.highlightCurrWord(id);486 // update id of first and last showing proposals and scroll box487 if (TsCodeCompletion.currWord < TsCodeCompletion.cc_up || TsCodeCompletion.currWord === (TsCodeCompletion.proposals.length - 1)) {488 TsCodeCompletion.cc_up = TsCodeCompletion.currWord;489 TsCodeCompletion.cc_down = TsCodeCompletion.currWord + (TsCodeCompletion.options.ccWords - 1);490 if (TsCodeCompletion.cc_up === (TsCodeCompletion.proposals.length - 1)) {491 TsCodeCompletion.cc_down = TsCodeCompletion.proposals.length - 1;492 TsCodeCompletion.cc_up = TsCodeCompletion.cc_down - (TsCodeCompletion.options.ccWords - 1);493 }494 TsCodeCompletion.$codeCompleteBox.find('.t3e_codeCompleteBox').scrollTop(TsCodeCompletion.cc_up * 18);495 }496 };497 /**498 * Move cursor in codecomplete box down499 */500 TsCodeCompletion.codeCompleteBoxMoveDownCursor = function() {501 var id;502 // if previous position was last word in list - then move cursor to first word if not than position ++503 if (TsCodeCompletion.currWord === TsCodeCompletion.proposals.length - 1) {504 id = 0;505 } else {506 id = TsCodeCompletion.currWord + 1;507 }508 // highlight new cursor position509 TsCodeCompletion.highlightCurrWord(id);510 // update id of first and last showing proposals and scroll box511 if (TsCodeCompletion.currWord > TsCodeCompletion.cc_down || TsCodeCompletion.currWord === 0) {512 TsCodeCompletion.cc_down = TsCodeCompletion.currWord;513 TsCodeCompletion.cc_up = TsCodeCompletion.currWord - (TsCodeCompletion.options.ccWords - 1);514 if (TsCodeCompletion.cc_down == 0) {515 TsCodeCompletion.cc_up = 0;516 TsCodeCompletion.cc_down = TsCodeCompletion.options.ccWords - 1;517 }518 TsCodeCompletion.$codeCompleteBox.find('.t3e_codeCompleteBox').scrollTop(TsCodeCompletion.cc_up * 18);519 }520 };521 /**522 * Highlight the active word in the code completion list523 *524 * @param {Number} id525 */526 TsCodeCompletion.highlightCurrWord = function(id) {527 if (TsCodeCompletion.currWord !== -1) {528 $('#cc_word_' + TsCodeCompletion.currWord).removeClass('active');529 }530 $('#cc_word_' + id).addClass('active');531 TsCodeCompletion.currWord = id;532 };533 /**534 * Insert selected word into text from codecompletebox535 */536 TsCodeCompletion.insertCurrWordAtCursor = function() {537 var word = TsCodeCompletion.proposals[TsCodeCompletion.currWord].word;538 // tokenize current line539 TsCodeCompletion.codemirror.editor.highlightAtCursor();540 var select = TsCodeCompletion.codemirror.win.select;541 var cursorNode = TsCodeCompletion.getCursorNode();542 if (cursorNode.currentText543 && cursorNode.currentText !== '.'544 && $.trim(cursorNode.currentText) !== '' ) {545 // if there is some typed text already, left to the "." -> simply replace node content with the word546 cursorNode.innerHTML = word;547 cursorNode.currentText = word;548 select.setCursorPos(TsCodeCompletion.codemirror.editor.container, {node: cursorNode, offset: 0});549 } else { // if there is no text there, insert the word at the cursor position550 TsCodeCompletion.codemirror.replaceSelection(word);551 }552 };553 /**554 * Save the mouse position555 *556 * @param {Event} e557 */558 TsCodeCompletion.saveMousePos = function(e) {559 TsCodeCompletion.mousePos.x = e.clientX;560 TsCodeCompletion.mousePos.y = e.clientY;561 };562 $(document).on('t3editor:init', function(e, codemirror, $outerDiv) {563 TsCodeCompletion.codemirror = codemirror;564 TsCodeCompletion.outerDiv = $outerDiv;565 TsCodeCompletion.parser = TsParser.init(TsCodeCompletion.tsRef, TsCodeCompletion.extTsObjTree);566 TsCodeCompletion.tsRef.loadTsrefAsync();567 $(codemirror.win)568 .on('click', TsCodeCompletion.click)569 .on('mousemove', TsCodeCompletion.saveMousePos)570 .on('keydown', function(e) {571 TsCodeCompletion.codemirror = codemirror;572 TsCodeCompletion.outerDiv = $outerDiv;573 TsCodeCompletion.keyDown(e);574 })575 .on('keyup', function(e) {576 TsCodeCompletion.codemirror = codemirror;577 TsCodeCompletion.outerDiv = $outerDiv;578 TsCodeCompletion.keyUp(e);579 });580 TsCodeCompletion.loadExtTemplatesAsync();581 TsCodeCompletion.loadPluginArray();582 });583 return TsCodeCompletion;...

Full Screen

Full Screen

suggest.js

Source:suggest.js Github

copy

Full Screen

1/*---------------------------------------------------------------------------------------------2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for license information.4 *--------------------------------------------------------------------------------------------*/5import { first } from '../../../base/common/async.js';6import { assign } from '../../../base/common/objects.js';7import { onUnexpectedExternalError, canceled, isPromiseCanceledError } from '../../../base/common/errors.js';8import { registerDefaultLanguageCommand } from '../../browser/editorExtensions.js';9import * as modes from '../../common/modes.js';10import { RawContextKey } from '../../../platform/contextkey/common/contextkey.js';11import { CancellationToken } from '../../../base/common/cancellation.js';12import { Range } from '../../common/core/range.js';13import { FuzzyScore } from '../../../base/common/filters.js';14export var Context = {15 Visible: new RawContextKey('suggestWidgetVisible', false),16 MultipleSuggestions: new RawContextKey('suggestWidgetMultipleSuggestions', false),17 MakesTextEdit: new RawContextKey('suggestionMakesTextEdit', true),18 AcceptSuggestionsOnEnter: new RawContextKey('acceptSuggestionOnEnter', true)19};20var CompletionItem = /** @class */ (function () {21 function CompletionItem(position, completion, container, provider, model) {22 this.position = position;23 this.completion = completion;24 this.container = container;25 this.provider = provider;26 // sorting, filtering27 this.score = FuzzyScore.Default;28 this.distance = 0;29 // ensure lower-variants (perf)30 this.labelLow = completion.label.toLowerCase();31 this.sortTextLow = completion.sortText && completion.sortText.toLowerCase();32 this.filterTextLow = completion.filterText && completion.filterText.toLowerCase();33 // create the suggestion resolver34 var resolveCompletionItem = provider.resolveCompletionItem;35 if (typeof resolveCompletionItem !== 'function') {36 this.resolve = function () { return Promise.resolve(); };37 }38 else {39 var cached_1;40 this.resolve = function (token) {41 if (!cached_1) {42 var isDone_1 = false;43 cached_1 = Promise.resolve(resolveCompletionItem.call(provider, model, position, completion, token)).then(function (value) {44 assign(completion, value);45 isDone_1 = true;46 }, function (err) {47 if (isPromiseCanceledError(err)) {48 // the IPC queue will reject the request with the49 // cancellation error -> reset cached50 cached_1 = undefined;51 }52 });53 token.onCancellationRequested(function () {54 if (!isDone_1) {55 // cancellation after the request has been56 // dispatched -> reset cache57 cached_1 = undefined;58 }59 });60 }61 return cached_1;62 };63 }64 }65 return CompletionItem;66}());67export { CompletionItem };68var CompletionOptions = /** @class */ (function () {69 function CompletionOptions(snippetSortOrder, kindFilter, providerFilter) {70 if (snippetSortOrder === void 0) { snippetSortOrder = 2 /* Bottom */; }71 if (kindFilter === void 0) { kindFilter = new Set(); }72 if (providerFilter === void 0) { providerFilter = new Set(); }73 this.snippetSortOrder = snippetSortOrder;74 this.kindFilter = kindFilter;75 this.providerFilter = providerFilter;76 }77 CompletionOptions.default = new CompletionOptions();78 return CompletionOptions;79}());80export { CompletionOptions };81var _snippetSuggestSupport;82export function getSnippetSuggestSupport() {83 return _snippetSuggestSupport;84}85export function provideSuggestionItems(model, position, options, context, token) {86 if (options === void 0) { options = CompletionOptions.default; }87 if (context === void 0) { context = { triggerKind: 0 /* Invoke */ }; }88 if (token === void 0) { token = CancellationToken.None; }89 var allSuggestions = [];90 var wordUntil = model.getWordUntilPosition(position);91 var defaultRange = new Range(position.lineNumber, wordUntil.startColumn, position.lineNumber, wordUntil.endColumn);92 position = position.clone();93 // get provider groups, always add snippet suggestion provider94 var supports = modes.CompletionProviderRegistry.orderedGroups(model);95 // add snippets provider unless turned off96 if (!options.kindFilter.has(25 /* Snippet */) && _snippetSuggestSupport) {97 supports.unshift([_snippetSuggestSupport]);98 }99 // add suggestions from contributed providers - providers are ordered in groups of100 // equal score and once a group produces a result the process stops101 var hasResult = false;102 var factory = supports.map(function (supports) { return function () {103 // for each support in the group ask for suggestions104 return Promise.all(supports.map(function (provider) {105 if (options.providerFilter.size > 0 && !options.providerFilter.has(provider)) {106 return undefined;107 }108 return Promise.resolve(provider.provideCompletionItems(model, position, context, token)).then(function (container) {109 var len = allSuggestions.length;110 if (container) {111 for (var _i = 0, _a = container.suggestions || []; _i < _a.length; _i++) {112 var suggestion = _a[_i];113 if (!options.kindFilter.has(suggestion.kind)) {114 // fill in default range when missing115 if (!suggestion.range) {116 suggestion.range = defaultRange;117 }118 allSuggestions.push(new CompletionItem(position, suggestion, container, provider, model));119 }120 }121 }122 if (len !== allSuggestions.length && provider !== _snippetSuggestSupport) {123 hasResult = true;124 }125 }, onUnexpectedExternalError);126 }));127 }; });128 var result = first(factory, function () {129 // stop on result or cancellation130 return hasResult || token.isCancellationRequested;131 }).then(function () {132 if (token.isCancellationRequested) {133 return Promise.reject(canceled());134 }135 return allSuggestions.sort(getSuggestionComparator(options.snippetSortOrder));136 });137 // result.then(items => {138 // console.log(model.getWordUntilPosition(position), items.map(item => `${item.suggestion.label}, type=${item.suggestion.type}, incomplete?${item.container.incomplete}, overwriteBefore=${item.suggestion.overwriteBefore}`));139 // return items;140 // }, err => {141 // console.warn(model.getWordUntilPosition(position), err);142 // });143 return result;144}145function defaultComparator(a, b) {146 // check with 'sortText'147 if (a.sortTextLow && b.sortTextLow) {148 if (a.sortTextLow < b.sortTextLow) {149 return -1;150 }151 else if (a.sortTextLow > b.sortTextLow) {152 return 1;153 }154 }155 // check with 'label'156 if (a.completion.label < b.completion.label) {157 return -1;158 }159 else if (a.completion.label > b.completion.label) {160 return 1;161 }162 // check with 'type'163 return a.completion.kind - b.completion.kind;164}165function snippetUpComparator(a, b) {166 if (a.completion.kind !== b.completion.kind) {167 if (a.completion.kind === 25 /* Snippet */) {168 return -1;169 }170 else if (b.completion.kind === 25 /* Snippet */) {171 return 1;172 }173 }174 return defaultComparator(a, b);175}176function snippetDownComparator(a, b) {177 if (a.completion.kind !== b.completion.kind) {178 if (a.completion.kind === 25 /* Snippet */) {179 return 1;180 }181 else if (b.completion.kind === 25 /* Snippet */) {182 return -1;183 }184 }185 return defaultComparator(a, b);186}187var _snippetComparators = new Map();188_snippetComparators.set(0 /* Top */, snippetUpComparator);189_snippetComparators.set(2 /* Bottom */, snippetDownComparator);190_snippetComparators.set(1 /* Inline */, defaultComparator);191export function getSuggestionComparator(snippetConfig) {192 return _snippetComparators.get(snippetConfig);193}194registerDefaultLanguageCommand('_executeCompletionItemProvider', function (model, position, args) {195 var result = {196 incomplete: false,197 suggestions: []198 };199 var resolving = [];200 var maxItemsToResolve = args['maxItemsToResolve'] || 0;201 return provideSuggestionItems(model, position).then(function (items) {202 for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {203 var item = items_1[_i];204 if (resolving.length < maxItemsToResolve) {205 resolving.push(item.resolve(CancellationToken.None));206 }207 result.incomplete = result.incomplete || item.container.incomplete;208 result.suggestions.push(item.completion);209 }210 }).then(function () {211 return Promise.all(resolving);212 }).then(function () {213 return result;214 });215});216var _provider = new /** @class */ (function () {217 function class_1() {218 this.onlyOnceSuggestions = [];219 }220 class_1.prototype.provideCompletionItems = function () {221 var suggestions = this.onlyOnceSuggestions.slice(0);222 var result = { suggestions: suggestions };223 this.onlyOnceSuggestions.length = 0;224 return result;225 };226 return class_1;227}());228modes.CompletionProviderRegistry.register('*', _provider);229export function showSimpleSuggestions(editor, suggestions) {230 setTimeout(function () {231 var _a;232 (_a = _provider.onlyOnceSuggestions).push.apply(_a, suggestions);233 editor.getContribution('editor.contrib.suggestController').triggerSuggest(new Set().add(_provider));234 }, 0);...

Full Screen

Full Screen

completionModel.js

Source:completionModel.js Github

copy

Full Screen

1/*---------------------------------------------------------------------------------------------2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for license information.4 *--------------------------------------------------------------------------------------------*/5import { fuzzyScore, fuzzyScoreGracefulAggressive, anyScore, FuzzyScore } from '../../../base/common/filters.js';6import { isDisposable } from '../../../base/common/lifecycle.js';7import { EDITOR_DEFAULTS } from '../../common/config/editorOptions.js';8var LineContext = /** @class */ (function () {9 function LineContext() {10 }11 return LineContext;12}());13export { LineContext };14var CompletionModel = /** @class */ (function () {15 function CompletionModel(items, column, lineContext, wordDistance, options) {16 if (options === void 0) { options = EDITOR_DEFAULTS.contribInfo.suggest; }17 this._snippetCompareFn = CompletionModel._compareCompletionItems;18 this._items = items;19 this._column = column;20 this._wordDistance = wordDistance;21 this._options = options;22 this._refilterKind = 1 /* All */;23 this._lineContext = lineContext;24 if (options.snippets === 'top') {25 this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsUp;26 }27 else if (options.snippets === 'bottom') {28 this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsDown;29 }30 }31 CompletionModel.prototype.dispose = function () {32 var seen = new Set();33 for (var _i = 0, _a = this._items; _i < _a.length; _i++) {34 var container = _a[_i].container;35 if (!seen.has(container)) {36 seen.add(container);37 if (isDisposable(container)) {38 container.dispose();39 }40 }41 }42 };43 Object.defineProperty(CompletionModel.prototype, "lineContext", {44 get: function () {45 return this._lineContext;46 },47 set: function (value) {48 if (this._lineContext.leadingLineContent !== value.leadingLineContent49 || this._lineContext.characterCountDelta !== value.characterCountDelta) {50 this._refilterKind = this._lineContext.characterCountDelta < value.characterCountDelta && this._filteredItems ? 2 /* Incr */ : 1 /* All */;51 this._lineContext = value;52 }53 },54 enumerable: true,55 configurable: true56 });57 Object.defineProperty(CompletionModel.prototype, "items", {58 get: function () {59 this._ensureCachedState();60 return this._filteredItems;61 },62 enumerable: true,63 configurable: true64 });65 Object.defineProperty(CompletionModel.prototype, "incomplete", {66 get: function () {67 this._ensureCachedState();68 return this._isIncomplete;69 },70 enumerable: true,71 configurable: true72 });73 CompletionModel.prototype.adopt = function (except) {74 var res = new Array();75 for (var i = 0; i < this._items.length;) {76 if (!except.has(this._items[i].provider)) {77 res.push(this._items[i]);78 // unordered removed79 this._items[i] = this._items[this._items.length - 1];80 this._items.pop();81 }82 else {83 // continue with next item84 i++;85 }86 }87 this._refilterKind = 1 /* All */;88 return res;89 };90 Object.defineProperty(CompletionModel.prototype, "stats", {91 get: function () {92 this._ensureCachedState();93 return this._stats;94 },95 enumerable: true,96 configurable: true97 });98 CompletionModel.prototype._ensureCachedState = function () {99 if (this._refilterKind !== 0 /* Nothing */) {100 this._createCachedState();101 }102 };103 CompletionModel.prototype._createCachedState = function () {104 this._isIncomplete = new Set();105 this._stats = { suggestionCount: 0, snippetCount: 0, textCount: 0 };106 var _a = this._lineContext, leadingLineContent = _a.leadingLineContent, characterCountDelta = _a.characterCountDelta;107 var word = '';108 var wordLow = '';109 // incrementally filter less110 var source = this._refilterKind === 1 /* All */ ? this._items : this._filteredItems;111 var target = [];112 // picks a score function based on the number of113 // items that we have to score/filter and based on the114 // user-configuration115 var scoreFn = (!this._options.filterGraceful || source.length > 2000) ? fuzzyScore : fuzzyScoreGracefulAggressive;116 for (var i = 0; i < source.length; i++) {117 var item = source[i];118 // collect those supports that signaled having119 // an incomplete result120 if (item.container.incomplete) {121 this._isIncomplete.add(item.provider);122 }123 // 'word' is that remainder of the current line that we124 // filter and score against. In theory each suggestion uses a125 // different word, but in practice not - that's why we cache126 var overwriteBefore = item.position.column - item.completion.range.startColumn;127 var wordLen = overwriteBefore + characterCountDelta - (item.position.column - this._column);128 if (word.length !== wordLen) {129 word = wordLen === 0 ? '' : leadingLineContent.slice(-wordLen);130 wordLow = word.toLowerCase();131 }132 // remember the word against which this item was133 // scored134 item.word = word;135 if (wordLen === 0) {136 // when there is nothing to score against, don't137 // event try to do. Use a const rank and rely on138 // the fallback-sort using the initial sort order.139 // use a score of `-100` because that is out of the140 // bound of values `fuzzyScore` will return141 item.score = FuzzyScore.Default;142 }143 else {144 // skip word characters that are whitespace until145 // we have hit the replace range (overwriteBefore)146 var wordPos = 0;147 while (wordPos < overwriteBefore) {148 var ch = word.charCodeAt(wordPos);149 if (ch === 32 /* Space */ || ch === 9 /* Tab */) {150 wordPos += 1;151 }152 else {153 break;154 }155 }156 if (wordPos >= wordLen) {157 // the wordPos at which scoring starts is the whole word158 // and therefore the same rules as not having a word apply159 item.score = FuzzyScore.Default;160 }161 else if (typeof item.completion.filterText === 'string') {162 // when there is a `filterText` it must match the `word`.163 // if it matches we check with the label to compute highlights164 // and if that doesn't yield a result we have no highlights,165 // despite having the match166 var match = scoreFn(word, wordLow, wordPos, item.completion.filterText, item.filterTextLow, 0, false);167 if (!match) {168 continue; // NO match169 }170 item.score = anyScore(word, wordLow, 0, item.completion.label, item.labelLow, 0);171 item.score[0] = match[0]; // use score from filterText172 }173 else {174 // by default match `word` against the `label`175 var match = scoreFn(word, wordLow, wordPos, item.completion.label, item.labelLow, 0, false);176 if (!match) {177 continue; // NO match178 }179 item.score = match;180 }181 }182 item.idx = i;183 item.distance = this._wordDistance.distance(item.position, item.completion);184 target.push(item);185 // update stats186 this._stats.suggestionCount++;187 switch (item.completion.kind) {188 case 25 /* Snippet */:189 this._stats.snippetCount++;190 break;191 case 18 /* Text */:192 this._stats.textCount++;193 break;194 }195 }196 this._filteredItems = target.sort(this._snippetCompareFn);197 this._refilterKind = 0 /* Nothing */;198 };199 CompletionModel._compareCompletionItems = function (a, b) {200 if (a.score[0] > b.score[0]) {201 return -1;202 }203 else if (a.score[0] < b.score[0]) {204 return 1;205 }206 else if (a.distance < b.distance) {207 return -1;208 }209 else if (a.distance > b.distance) {210 return 1;211 }212 else if (a.idx < b.idx) {213 return -1;214 }215 else if (a.idx > b.idx) {216 return 1;217 }218 else {219 return 0;220 }221 };222 CompletionModel._compareCompletionItemsSnippetsDown = function (a, b) {223 if (a.completion.kind !== b.completion.kind) {224 if (a.completion.kind === 25 /* Snippet */) {225 return 1;226 }227 else if (b.completion.kind === 25 /* Snippet */) {228 return -1;229 }230 }231 return CompletionModel._compareCompletionItems(a, b);232 };233 CompletionModel._compareCompletionItemsSnippetsUp = function (a, b) {234 if (a.completion.kind !== b.completion.kind) {235 if (a.completion.kind === 25 /* Snippet */) {236 return -1;237 }238 else if (b.completion.kind === 25 /* Snippet */) {239 return 1;240 }241 }242 return CompletionModel._compareCompletionItems(a, b);243 };244 return CompletionModel;245}());...

Full Screen

Full Screen

show-hint.js

Source:show-hint.js Github

copy

Full Screen

1(function() {2 "use strict";3 CodeMirror.showHint = function(cm, getHints, options) {4 // We want a single cursor position.5 if (cm.somethingSelected()) return;6 if (cm.state.completionActive) cm.state.completionActive.close();7 var completion = cm.state.completionActive = new Completion(cm, getHints, options || {});8 CodeMirror.signal(cm, "startCompletion", cm);9 if (completion.options.async)10 getHints(cm, function(hints) { completion.showHints(hints); }, completion.options);11 else12 return completion.showHints(getHints(cm, completion.options));13 };14 function Completion(cm, getHints, options) {15 this.cm = cm;16 this.getHints = getHints;17 this.options = options;18 this.widget = this.onClose = null;19 }20 Completion.prototype = {21 close: function() {22 if (!this.active()) return;23 if (this.widget) this.widget.close();24 if (this.onClose) this.onClose();25 this.cm.state.completionActive = null;26 CodeMirror.signal(this.cm, "endCompletion", this.cm);27 },28 active: function() {29 return this.cm.state.completionActive == this;30 },31 pick: function(data, i) {32 var completion = data.list[i];33 if (completion.hint) completion.hint(this.cm, data, completion);34 else this.cm.replaceRange(getText(completion), data.from, data.to);35 this.close();36 },37 showHints: function(data) {38 if (!data || !data.list.length || !this.active()) return this.close();39 if (this.options.completeSingle != false && data.list.length == 1)40 this.pick(data, 0);41 else42 this.showWidget(data);43 },44 showWidget: function(data) {45 this.widget = new Widget(this, data);46 CodeMirror.signal(data, "shown");47 var debounce = null, completion = this, finished;48 var closeOn = this.options.closeCharacters || /[\s()\[\]{};:>,]/;49 var startPos = this.cm.getCursor(), startLen = this.cm.getLine(startPos.line).length;50 function done() {51 if (finished) return;52 finished = true;53 completion.close();54 completion.cm.off("cursorActivity", activity);55 CodeMirror.signal(data, "close");56 }57 function isDone() {58 if (finished) return true;59 if (!completion.widget) { done(); return true; }60 }61 function update() {62 if (isDone()) return;63 if (completion.options.async)64 completion.getHints(completion.cm, finishUpdate, completion.options);65 else66 finishUpdate(completion.getHints(completion.cm, completion.options));67 }68 function finishUpdate(data) {69 if (isDone()) return;70 if (!data || !data.list.length) return done();71 completion.widget.close();72 completion.widget = new Widget(completion, data);73 }74 function activity() {75 clearTimeout(debounce);76 var pos = completion.cm.getCursor(), line = completion.cm.getLine(pos.line);77 if (pos.line != startPos.line || line.length - pos.ch != startLen - startPos.ch ||78 pos.ch < startPos.ch || completion.cm.somethingSelected() ||79 (pos.ch && closeOn.test(line.charAt(pos.ch - 1))))80 completion.close();81 else82 debounce = setTimeout(update, 170);83 }84 this.cm.on("cursorActivity", activity);85 this.onClose = done;86 }87 };88 function getText(completion) {89 if (typeof completion == "string") return completion;90 else return completion.text;91 }92 function buildKeyMap(options, handle) {93 var baseMap = {94 Up: function() {handle.moveFocus(-1);},95 Down: function() {handle.moveFocus(1);},96 PageUp: function() {handle.moveFocus(-handle.menuSize());},97 PageDown: function() {handle.moveFocus(handle.menuSize());},98 Home: function() {handle.setFocus(0);},99 End: function() {handle.setFocus(handle.length);},100 Enter: handle.pick,101 Tab: handle.pick,102 Esc: handle.close103 };104 var ourMap = options.customKeys ? {} : baseMap;105 function addBinding(key, val) {106 var bound;107 if (typeof val != "string")108 bound = function(cm) { return val(cm, handle); };109 // This mechanism is deprecated110 else if (baseMap.hasOwnProperty(val))111 bound = baseMap[val];112 else113 bound = val;114 ourMap[key] = bound;115 }116 if (options.customKeys)117 for (var key in options.customKeys) if (options.customKeys.hasOwnProperty(key))118 addBinding(key, options.customKeys[key]);119 if (options.extraKeys)120 for (var key in options.extraKeys) if (options.extraKeys.hasOwnProperty(key))121 addBinding(key, options.extraKeys[key]);122 return ourMap;123 }124 function Widget(completion, data) {125 this.completion = completion;126 this.data = data;127 var widget = this, cm = completion.cm, options = completion.options;128 var hints = this.hints = document.createElement("ul");129 hints.className = "CodeMirror-hints";130 this.selectedHint = 0;131 var completions = data.list;132 for (var i = 0; i < completions.length; ++i) {133 var elt = hints.appendChild(document.createElement("li")), cur = completions[i];134 var className = "CodeMirror-hint" + (i ? "" : " CodeMirror-hint-active");135 if (cur.className != null) className = cur.className + " " + className;136 elt.className = className;137 if (cur.render) cur.render(elt, data, cur);138 else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));139 elt.hintId = i;140 }141 var pos = cm.cursorCoords(options.alignWithWord !== false ? data.from : null);142 var left = pos.left, top = pos.bottom, below = true;143 hints.style.left = left + "px";144 hints.style.top = top + "px";145 // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.146 var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);147 var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);148 var box = hints.getBoundingClientRect();149 var overlapX = box.right - winW, overlapY = box.bottom - winH;150 if (overlapX > 0) {151 if (box.right - box.left > winW) {152 hints.style.width = (winW - 5) + "px";153 overlapX -= (box.right - box.left) - winW;154 }155 hints.style.left = (left = pos.left - overlapX) + "px";156 }157 if (overlapY > 0) {158 var height = box.bottom - box.top;159 if (box.top - (pos.bottom - pos.top) - height > 0) {160 overlapY = height + (pos.bottom - pos.top);161 below = false;162 } else if (height > winH) {163 hints.style.height = (winH - 5) + "px";164 overlapY -= height - winH;165 }166 hints.style.top = (top = pos.bottom - overlapY) + "px";167 }168 (options.container || document.body).appendChild(hints);169 cm.addKeyMap(this.keyMap = buildKeyMap(options, {170 moveFocus: function(n) { widget.changeActive(widget.selectedHint + n); },171 setFocus: function(n) { widget.changeActive(n); },172 menuSize: function() { return widget.screenAmount(); },173 length: completions.length,174 close: function() { completion.close(); },175 pick: function() { widget.pick(); }176 }));177 if (options.closeOnUnfocus !== false) {178 var closingOnBlur;179 cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });180 cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });181 }182 var startScroll = cm.getScrollInfo();183 cm.on("scroll", this.onScroll = function() {184 var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();185 var newTop = top + startScroll.top - curScroll.top;186 var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);187 if (!below) point += hints.offsetHeight;188 if (point <= editor.top || point >= editor.bottom) return completion.close();189 hints.style.top = newTop + "px";190 hints.style.left = (left + startScroll.left - curScroll.left) + "px";191 });192 CodeMirror.on(hints, "dblclick", function(e) {193 var t = e.target || e.srcElement;194 if (t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}195 });196 CodeMirror.on(hints, "click", function(e) {197 var t = e.target || e.srcElement;198 if (t.hintId != null) widget.changeActive(t.hintId);199 });200 CodeMirror.on(hints, "mousedown", function() {201 setTimeout(function(){cm.focus();}, 20);202 });203 CodeMirror.signal(data, "select", completions[0], hints.firstChild);204 return true;205 }206 Widget.prototype = {207 close: function() {208 if (this.completion.widget != this) return;209 this.completion.widget = null;210 this.hints.parentNode.removeChild(this.hints);211 this.completion.cm.removeKeyMap(this.keyMap);212 var cm = this.completion.cm;213 if (this.completion.options.closeOnUnfocus !== false) {214 cm.off("blur", this.onBlur);215 cm.off("focus", this.onFocus);216 }217 cm.off("scroll", this.onScroll);218 },219 pick: function() {220 this.completion.pick(this.data, this.selectedHint);221 },222 changeActive: function(i) {223 i = Math.max(0, Math.min(i, this.data.list.length - 1));224 if (this.selectedHint == i) return;225 var node = this.hints.childNodes[this.selectedHint];226 node.className = node.className.replace(" CodeMirror-hint-active", "");227 node = this.hints.childNodes[this.selectedHint = i];228 node.className += " CodeMirror-hint-active";229 if (node.offsetTop < this.hints.scrollTop)230 this.hints.scrollTop = node.offsetTop - 3;231 else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)232 this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;233 CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);234 },235 screenAmount: function() {236 return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;237 }238 };...

Full Screen

Full Screen

user-highlights.js

Source:user-highlights.js Github

copy

Full Screen

1/*global variable declarations*/2var urlList;3var extendType;4var rsb = new RunestoneBase();5function getCompletions() {6// Get the completion status7 if ((window.location.href).match(/(index.html|genindex.html|navhelp.html|toc.html|assignments.html|exercises.html)/)) {8 return;9 }10 var currentPathname = window.location.pathname;11 if (currentPathname.indexOf("?") !== -1) {12 currentPathname = currentPathname.substring(0, currentPathname.lastIndexOf("?"));13 }14 var data = {lastPageUrl: currentPathname};15 jQuery.ajax({url: eBookConfig.ajaxURL + 'getCompletionStatus', data: data, async: false}).done(function (data) {16 if (data != "None") {17 var completionData = $.parseJSON(data);18 var completionClass, completionMsg;19 if (completionData[0].completionStatus == 1) {20 completionClass = "buttonConfirmCompletion";21 completionMsg = "<i class='glyphicon glyphicon-ok'></i> Completed. Well Done!";22 }23 else {24 completionClass = "buttonAskCompletion";25 completionMsg = "Mark as completed";26 }27 $("#main-content").append('<div style="text-align:center"><button class="btn btn-lg ' + completionClass + '" id="completionButton">' + completionMsg + '</button></div>');28 }29 });30}31function showLastPositionBanner() {32 var lastPositionVal = $.getUrlVar('lastPosition');33 if (typeof lastPositionVal !== "undefined") {34 $("body").append('<img src="../_static/last-point.png" style="position:absolute; padding-top:55px; left: 10px; top: ' + parseInt(lastPositionVal) + 'px;"/>');35 $("html, body").animate({scrollTop: parseInt(lastPositionVal)}, 1000);36 }37}38function addNavigationAndCompletionButtons() {39 if ((window.location.href).match(/(index.html|genindex.html|navhelp.html|toc.html|assignments.html|exercises.html)/)) {40 return;41 }42 var navLinkBgRightHiddenPosition = -$("#navLinkBgRight").outerWidth() - 5;43 var navLinkBgRightHalfOpen;44 var navLinkBgRightFullOpen = 0;45 if ($("#completionButton").hasClass("buttonAskCompletion")) {46 navLinkBgRightHalfOpen = navLinkBgRightHiddenPosition + 70;47 }48 else if ($("#completionButton").hasClass("buttonConfirmCompletion")) {49 navLinkBgRightHalfOpen = 0;50 }51 var relationsNextIconInitialPosition = $("#relations-next").css("right");52 var relationsNextIconNewPosition = -(navLinkBgRightHiddenPosition + 35);53 $("#navLinkBgRight").css("right", navLinkBgRightHiddenPosition).show();54 var navBgShown = false;55 $(window).scroll(function () {56 if ($(window).scrollTop() + $(window).height() == $(document).height()) {57 $("#navLinkBgRight").animate(58 {"right": navLinkBgRightHalfOpen}, 20059 );60 $("#navLinkBgLeft").animate(61 {"left": "0px"}, 20062 );63 if ($("#completionButton").hasClass("buttonConfirmCompletion")) {64 $("#relations-next").animate({"right": relationsNextIconNewPosition}, 200);65 }66 navBgShown = true;67 }68 else if (navBgShown) {69 $("#navLinkBgRight").animate(70 {"right": navLinkBgRightHiddenPosition}, 20071 );72 $("#navLinkBgLeft").animate(73 {"left": "-65px"}, 20074 );75 $("#relations-next").animate({"right": relationsNextIconInitialPosition});76 navBgShown = false;77 }78 });79 var completionFlag = 0;80 if ($("#completionButton").hasClass("buttonAskCompletion")) {81 completionFlag = 0;82 } else {83 completionFlag = 1;84 }85 $("#completionButton").on("click", function () {86 if ($(this).hasClass("buttonAskCompletion")) {87 $(this).removeClass("buttonAskCompletion")88 .addClass("buttonConfirmCompletion")89 .html("<i class='glyphicon glyphicon-ok'></i> Completed. Well Done!");90 $("#navLinkBgRight").animate({"right": navLinkBgRightFullOpen});91 $("#relations-next").animate({"right": relationsNextIconNewPosition});92 navLinkBgRightHalfOpen = 0;93 completionFlag = 1;94 }95 else if ($(this).hasClass("buttonConfirmCompletion")) {96 $(this).removeClass("buttonConfirmCompletion")97 .addClass("buttonAskCompletion")98 .html("Mark as completed");99 navLinkBgRightHalfOpen = navLinkBgRightHiddenPosition + 70;100 $("#navLinkBgRight").animate({"right": navLinkBgRightHalfOpen});101 $("#relations-next").animate({"right": relationsNextIconInitialPosition});102 completionFlag = 0;103 }104 processPageState(completionFlag);105 });106 $(window).on('beforeunload', function (e) {107 if (completionFlag == 0) {108 processPageState(completionFlag);109 }110 });111}112function decorateTableOfContents() {113 if ((window.location.href).toLowerCase().indexOf("toc.html") != -1 ||114 (window.location.href).toLowerCase().indexOf("index.html") != -1) {115 jQuery.get(eBookConfig.ajaxURL + 'getAllCompletionStatus', function (data) {116 if (data != "None") {117 subChapterList = $.parseJSON(data);118 var allSubChapterURLs = $("#main-content div li a");119 $.each(subChapterList, function (index, item) {120 for (var s = 0; s < allSubChapterURLs.length; s++) {121 if (allSubChapterURLs[s].href.indexOf(item.chapterName + "/" + item.subChapterName) != -1) {122 if (item.completionStatus == 1) {123 $(allSubChapterURLs[s].parentElement).addClass("completed").append('<span class="infoTextCompleted">- Completed this topic on ' + item.endDate + "</span>").children().first().hover(124 function () {125 $(this).next(".infoTextCompleted").show();126 }, function () {127 $(this).next(".infoTextCompleted").hide()128 }129 );130 } else if (item.completionStatus == 0) {131 $(allSubChapterURLs[s].parentElement).addClass("active").append('<span class="infoTextActive">Last read this topic on ' + item.endDate + "</span>").children().first().hover(132 function () {133 $(this).next(".infoTextActive").show();134 }, function () {135 $(this).next(".infoTextActive").hide()136 }137 );138 }139 }140 }141 });142 }143 });144 data = {course: eBookConfig.course};145 jQuery.get(eBookConfig.ajaxURL + 'getlastpage', data, function (data) {146 if (data != "None") {147 lastPageData = $.parseJSON(data);148 if (lastPageData[0].lastPageChapter != null) {149 $("#continue-reading").show().html('<div id="jump-to-chapter" class="alert alert-info" ><strong>You were Last Reading:</strong> ' + lastPageData[0].lastPageChapter + ((lastPageData[0].lastPageSubchapter) ? ' &gt; ' + lastPageData[0].lastPageSubchapter : "") + ' <a href="' + lastPageData[0].lastPageUrl + '?lastPosition=' + lastPageData[0].lastPageScrollLocation + '">Continue Reading</a></div>');150 }151 }152 });153 }154}155function enableCompletions() {156 getCompletions();157 showLastPositionBanner();158 addNavigationAndCompletionButtons();159 decorateTableOfContents();160}161// call enable user highlights after login162$(document).bind("runestone:login",enableCompletions);163function processPageState(completionFlag) {164 /*Log last page visited*/165 var currentPathname = window.location.pathname;166 if (currentPathname.indexOf("?") !== -1) {167 currentPathname = currentPathname.substring(0, currentPathname.lastIndexOf("?"));168 }169 var data = {170 lastPageUrl: currentPathname,171 lastPageScrollLocation: $(window).scrollTop(),172 completionFlag: completionFlag,173 course: eBookConfig.course174 };175 $(document).ajaxError(function (e, jqhxr, settings, exception) {176 console.log("Request Failed for " + settings.url)177 });178 jQuery.ajax({url: eBookConfig.ajaxURL + 'updatelastpage', data: data, async: false});179}180$.extend({181 getUrlVars: function () {182 var vars = [], hash;183 var hashes = window.location.search.slice(window.location.search.indexOf('?') + 1).split('&');184 for (var i = 0; i < hashes.length; i++) {185 hash = hashes[i].split('=');186 vars.push(hash[0]);187 vars[hash[0]] = hash[1];188 }189 return vars;190 },191 getUrlVar: function (name) {192 return $.getUrlVars()[name];193 }...

Full Screen

Full Screen

moodle-availability_completion-form-debug.js

Source:moodle-availability_completion-form-debug.js Github

copy

Full Screen

1YUI.add('moodle-availability_completion-form', function (Y, NAME) {2/**3 * JavaScript for form editing completion conditions.4 *5 * @module moodle-availability_completion-form6 */7M.availability_completion = M.availability_completion || {};8/**9 * @class M.availability_completion.form10 * @extends M.core_availability.plugin11 */12M.availability_completion.form = Y.Object(M.core_availability.plugin);13/**14 * Initialises this plugin.15 *16 * @method initInner17 * @param {Array} cms Array of objects containing cmid => name18 */19M.availability_completion.form.initInner = function(cms) {20 this.cms = cms;21};22M.availability_completion.form.getNode = function(json) {23 // Create HTML structure.24 var html = '<span class="col-form-label p-r-1"> ' + M.util.get_string('title', 'availability_completion') + '</span>' +25 ' <span class="availability-group form-group"><label>' +26 '<span class="accesshide">' + M.util.get_string('label_cm', 'availability_completion') + ' </span>' +27 '<select class="custom-select" name="cm" title="' + M.util.get_string('label_cm', 'availability_completion') + '">' +28 '<option value="0">' + M.util.get_string('choosedots', 'moodle') + '</option>';29 for (var i = 0; i < this.cms.length; i++) {30 var cm = this.cms[i];31 // String has already been escaped using format_string.32 html += '<option value="' + cm.id + '">' + cm.name + '</option>';33 }34 html += '</select></label> <label><span class="accesshide">' +35 M.util.get_string('label_completion', 'availability_completion') +36 ' </span><select class="custom-select" ' +37 'name="e" title="' + M.util.get_string('label_completion', 'availability_completion') + '">' +38 '<option value="1">' + M.util.get_string('option_complete', 'availability_completion') + '</option>' +39 '<option value="0">' + M.util.get_string('option_incomplete', 'availability_completion') + '</option>' +40 '<option value="2">' + M.util.get_string('option_pass', 'availability_completion') + '</option>' +41 '<option value="3">' + M.util.get_string('option_fail', 'availability_completion') + '</option>' +42 '</select></label></span>';43 var node = Y.Node.create('<span class="form-inline">' + html + '</span>');44 // Set initial values.45 if (json.cm !== undefined &&46 node.one('select[name=cm] > option[value=' + json.cm + ']')) {47 node.one('select[name=cm]').set('value', '' + json.cm);48 }49 if (json.e !== undefined) {50 node.one('select[name=e]').set('value', '' + json.e);51 }52 // Add event handlers (first time only).53 if (!M.availability_completion.form.addedEvents) {54 M.availability_completion.form.addedEvents = true;55 var root = Y.one('.availability-field');56 root.delegate('change', function() {57 // Whichever dropdown changed, just update the form.58 M.core_availability.form.update();59 }, '.availability_completion select');60 }61 return node;62};63M.availability_completion.form.fillValue = function(value, node) {64 value.cm = parseInt(node.one('select[name=cm]').get('value'), 10);65 value.e = parseInt(node.one('select[name=e]').get('value'), 10);66};67M.availability_completion.form.fillErrors = function(errors, node) {68 var cmid = parseInt(node.one('select[name=cm]').get('value'), 10);69 if (cmid === 0) {70 errors.push('availability_completion:error_selectcmid');71 }72};...

Full Screen

Full Screen

moodle-availability_completion-form.js

Source:moodle-availability_completion-form.js Github

copy

Full Screen

1YUI.add('moodle-availability_completion-form', function (Y, NAME) {2/**3 * JavaScript for form editing completion conditions.4 *5 * @module moodle-availability_completion-form6 */7M.availability_completion = M.availability_completion || {};8/**9 * @class M.availability_completion.form10 * @extends M.core_availability.plugin11 */12M.availability_completion.form = Y.Object(M.core_availability.plugin);13/**14 * Initialises this plugin.15 *16 * @method initInner17 * @param {Array} cms Array of objects containing cmid => name18 */19M.availability_completion.form.initInner = function(cms) {20 this.cms = cms;21};22M.availability_completion.form.getNode = function(json) {23 // Create HTML structure.24 var html = '<span class="col-form-label p-r-1"> ' + M.util.get_string('title', 'availability_completion') + '</span>' +25 ' <span class="availability-group form-group"><label>' +26 '<span class="accesshide">' + M.util.get_string('label_cm', 'availability_completion') + ' </span>' +27 '<select class="custom-select" name="cm" title="' + M.util.get_string('label_cm', 'availability_completion') + '">' +28 '<option value="0">' + M.util.get_string('choosedots', 'moodle') + '</option>';29 for (var i = 0; i < this.cms.length; i++) {30 var cm = this.cms[i];31 // String has already been escaped using format_string.32 html += '<option value="' + cm.id + '">' + cm.name + '</option>';33 }34 html += '</select></label> <label><span class="accesshide">' +35 M.util.get_string('label_completion', 'availability_completion') +36 ' </span><select class="custom-select" ' +37 'name="e" title="' + M.util.get_string('label_completion', 'availability_completion') + '">' +38 '<option value="1">' + M.util.get_string('option_complete', 'availability_completion') + '</option>' +39 '<option value="0">' + M.util.get_string('option_incomplete', 'availability_completion') + '</option>' +40 '<option value="2">' + M.util.get_string('option_pass', 'availability_completion') + '</option>' +41 '<option value="3">' + M.util.get_string('option_fail', 'availability_completion') + '</option>' +42 '</select></label></span>';43 var node = Y.Node.create('<span class="form-inline">' + html + '</span>');44 // Set initial values.45 if (json.cm !== undefined &&46 node.one('select[name=cm] > option[value=' + json.cm + ']')) {47 node.one('select[name=cm]').set('value', '' + json.cm);48 }49 if (json.e !== undefined) {50 node.one('select[name=e]').set('value', '' + json.e);51 }52 // Add event handlers (first time only).53 if (!M.availability_completion.form.addedEvents) {54 M.availability_completion.form.addedEvents = true;55 var root = Y.one('.availability-field');56 root.delegate('change', function() {57 // Whichever dropdown changed, just update the form.58 M.core_availability.form.update();59 }, '.availability_completion select');60 }61 return node;62};63M.availability_completion.form.fillValue = function(value, node) {64 value.cm = parseInt(node.one('select[name=cm]').get('value'), 10);65 value.e = parseInt(node.one('select[name=e]').get('value'), 10);66};67M.availability_completion.form.fillErrors = function(errors, node) {68 var cmid = parseInt(node.one('select[name=cm]').get('value'), 10);69 if (cmid === 0) {70 errors.push('availability_completion:error_selectcmid');71 }72};...

Full Screen

Full Screen

form.js

Source:form.js Github

copy

Full Screen

1/**2 * JavaScript for form editing completion conditions.3 *4 * @module moodle-availability_completion-form5 */6M.availability_completion = M.availability_completion || {};7/**8 * @class M.availability_completion.form9 * @extends M.core_availability.plugin10 */11M.availability_completion.form = Y.Object(M.core_availability.plugin);12/**13 * Initialises this plugin.14 *15 * @method initInner16 * @param {Array} cms Array of objects containing cmid => name17 */18M.availability_completion.form.initInner = function(cms) {19 this.cms = cms;20};21M.availability_completion.form.getNode = function(json) {22 // Create HTML structure.23 var html = '<span class="col-form-label p-r-1"> ' + M.util.get_string('title', 'availability_completion') + '</span>' +24 ' <span class="availability-group form-group"><label>' +25 '<span class="accesshide">' + M.util.get_string('label_cm', 'availability_completion') + ' </span>' +26 '<select class="custom-select" name="cm" title="' + M.util.get_string('label_cm', 'availability_completion') + '">' +27 '<option value="0">' + M.util.get_string('choosedots', 'moodle') + '</option>';28 for (var i = 0; i < this.cms.length; i++) {29 var cm = this.cms[i];30 // String has already been escaped using format_string.31 html += '<option value="' + cm.id + '">' + cm.name + '</option>';32 }33 html += '</select></label> <label><span class="accesshide">' +34 M.util.get_string('label_completion', 'availability_completion') +35 ' </span><select class="custom-select" ' +36 'name="e" title="' + M.util.get_string('label_completion', 'availability_completion') + '">' +37 '<option value="1">' + M.util.get_string('option_complete', 'availability_completion') + '</option>' +38 '<option value="0">' + M.util.get_string('option_incomplete', 'availability_completion') + '</option>' +39 '<option value="2">' + M.util.get_string('option_pass', 'availability_completion') + '</option>' +40 '<option value="3">' + M.util.get_string('option_fail', 'availability_completion') + '</option>' +41 '</select></label></span>';42 var node = Y.Node.create('<span class="form-inline">' + html + '</span>');43 // Set initial values.44 if (json.cm !== undefined &&45 node.one('select[name=cm] > option[value=' + json.cm + ']')) {46 node.one('select[name=cm]').set('value', '' + json.cm);47 }48 if (json.e !== undefined) {49 node.one('select[name=e]').set('value', '' + json.e);50 }51 // Add event handlers (first time only).52 if (!M.availability_completion.form.addedEvents) {53 M.availability_completion.form.addedEvents = true;54 var root = Y.one('.availability-field');55 root.delegate('change', function() {56 // Whichever dropdown changed, just update the form.57 M.core_availability.form.update();58 }, '.availability_completion select');59 }60 return node;61};62M.availability_completion.form.fillValue = function(value, node) {63 value.cm = parseInt(node.one('select[name=cm]').get('value'), 10);64 value.e = parseInt(node.one('select[name=e]').get('value'), 10);65};66M.availability_completion.form.fillErrors = function(errors, node) {67 var cmid = parseInt(node.one('select[name=cm]').get('value'), 10);68 if (cmid === 0) {69 errors.push('availability_completion:error_selectcmid');70 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('A suite', function() {2 it('contains spec with an expectation', function() {3 expect(true).toBe(true);4 });5});6describe('A suite', function() {7 it('contains spec with an expectation', function(done) {8 setTimeout(function(){9 expect(true).toBe(true);10 done();11 }, 1000);12 });13});14describe('A suite', function() {15 it('contains spec with an expectation', function(done) {16 setTimeout(function(){17 expect(true).toBe(true);18 done();19 }, 1000);20 });21});22describe('A suite', function() {23 it('contains spec with an expectation', function(done) {24 setTimeout(function(){25 expect(true).toBe(true);26 done();27 }, 1000);28 });29});30describe('A suite', function() {31 it('contains spec with an expectation', function(done) {32 setTimeout(function(){33 expect(true).toBe(true);34 done();35 }, 1000);36 });37});38describe('A suite', function() {39 it('contains spec with an expectation', function(done) {40 setTimeout(function(){41 expect(true).toBe(true);42 done();43 }, 1000);44 });45});46describe('A suite', function() {47 it('contains spec with an expectation', function(done) {48 setTimeout(function(){49 expect(true).toBe(true);50 done();51 }, 1000);52 });53});54describe('A suite', function() {55 it('contains spec with an expectation', function(done) {56 setTimeout(function(){57 expect(true).toBe(true);58 done();59 }, 1000);60 });61});62describe('A suite', function() {63 it('contains spec with an expectation', function(done) {64 setTimeout(function(){65 expect(true).toBe(true);66 done();67 }, 1000);

Full Screen

Using AI Code Generation

copy

Full Screen

1describe("Test suite", function() {2 it("should test something", function() {3 var test = true;4 expect(test).toBe(true);5 });6});7describe("Test suite", function() {8 it("should test something", function(done) {9 var test = true;10 expect(test).toBe(true);11 done();12 });13});14describe("Test suite", function() {15 it("should test something", function(done) {16 var test = true;17 expect(test).toBe(true);18 setTimeout(function() {19 done();20 }, 1000);21 });22});23describe("Test suite", function() {24 it("should test something", function(done) {25 var test = true;26 expect(test).toBe(true);27 setTimeout(function() {28 done();29 }, 1000);30 });31});32describe("Test suite", function() {33 it("should test something", function(done) {34 var test = true;35 expect(test).toBe(true);36 setTimeout(function() {37 done();38 }, 1000);39 });40});41describe("Test suite", function() {42 it("should test something", function(done) {43 var test = true;44 expect(test).toBe(true);45 setTimeout(function() {46 done();47 }, 1000);48 });49});50describe("Test suite", function() {51 it("should test something", function(done) {52 var test = true;53 expect(test).toBe(true);54 setTimeout(function() {55 done();56 }, 1000);57 });58});59describe("Test suite", function() {60 it("should test something", function(done) {61 var test = true;62 expect(test).toBe(true);63 setTimeout(function() {64 done();65 }, 1000);66 });67});68describe("Test suite", function() {69 it("should test something", function

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Asynchronous specs', function() {2 var value;3 beforeEach(function(done) {4 setTimeout(function() {5 value = 0;6 done();7 }, 1);8 });9 it('should support async execution of test preparation and expectations', function(done) {10 value++;11 expect(value).toBeGreaterThan(0);12 done();13 });14});15describe('Asynchronous specs', function() {16 var value;17 beforeEach(function(done) {18 setTimeout(function() {19 value = 0;20 done();21 }, 1);22 });23 it('should support async execution of test preparation and expectations', function(done) {24 value++;25 expect(value).toBeGreaterThan(0);26 done();27 });28});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Karma automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful