How to use console method in chromy

Best JavaScript code snippet using chromy

console.js

Source:console.js Github

copy

Full Screen

1/* vim: set expandtab sw=4 ts=4 sts=4: */2/**3 * Used in or for console4 *5 * @package phpMyAdmin-Console6 */7/**8 * Console object9 */10var PMA_console = {11 /**12 * @var object, jQuery object, selector is '#pma_console>.content'13 * @access private14 */15 $consoleContent: null,16 /**17 * @var object, jQuery object, selector is '#pma_console .content',18 * used for resizer19 * @access private20 */21 $consoleAllContents: null,22 /**23 * @var object, jQuery object, selector is '#pma_console .toolbar'24 * @access private25 */26 $consoleToolbar: null,27 /**28 * @var object, jQuery object, selector is '#pma_console .template'29 * @access private30 */31 $consoleTemplates: null,32 /**33 * @var object, jQuery object, form for submit34 * @access private35 */36 $requestForm: null,37 /**38 * @var object, contain console config39 * @access private40 */41 config: null,42 /**43 * @var bool, if console element exist, it'll be true44 * @access public45 */46 isEnabled: false,47 /**48 * @var bool, make sure console events bind only once49 * @access private50 */51 isInitialized: false,52 /**53 * Used for console initialize, reinit is ok, just some variable assignment54 *55 * @return void56 */57 initialize: function() {58 if($('#pma_console').length === 0) {59 return;60 }61 PMA_console.isEnabled = true;62 // Cookie var checks and init63 if(! $.cookie('pma_console_height')) {64 $.cookie('pma_console_height', 92);65 }66 if(! $.cookie('pma_console_mode')) {67 $.cookie('pma_console_mode', 'info');68 }69 // Vars init70 PMA_console.$consoleToolbar = $('#pma_console>.toolbar');71 PMA_console.$consoleContent = $('#pma_console>.content');72 PMA_console.$consoleAllContents = $('#pma_console .content');73 PMA_console.$consoleTemplates = $('#pma_console>.templates');74 // Generate a from for post75 PMA_console.$requestForm = $('<form method="post" action="import.php">' +76 '<input name="is_js_confirmed" value="0">' +77 '<textarea name="sql_query"></textarea>' +78 '<input name="console_message_id" value="0">' +79 '<input name="server" value="">' +80 '<input name="db" value="">' +81 '<input name="table" value="">' +82 '<input name="token" value="' +83 PMA_commonParams.get('token') +84 '">' +85 '</form>'86 );87 PMA_console.$requestForm.bind('submit', AJAX.requestHandler);88 // Event binds shouldn't run again89 if(PMA_console.isInitialized === false) {90 // Load config first91 var tempConfig = JSON.parse($.cookie('pma_console_config'));92 if(tempConfig) {93 if(tempConfig.alwaysExpand === true) {94 $('#pma_console_options input[name=always_expand]').prop('checked', true);95 }96 if(tempConfig.startHistory === true) {97 $('#pma_console_options input[name=start_history]').prop('checked', true);98 }99 if(tempConfig.currentQuery === true) {100 $('#pma_console_options input[name=current_query]').prop('checked', true);101 }102 } else {103 $('#pma_console_options input[name=current_query]').prop('checked', true);104 }105 PMA_console.updateConfig();106 PMA_consoleResizer.initialize();107 PMA_consoleInput.initialize();108 PMA_consoleMessages.initialize();109 PMA_consoleBookmarks.initialize();110 PMA_console.$consoleToolbar.children('.console_switch').click(PMA_console.toggle);111 $(document).keydown(function(event) {112 // Ctrl + Alt + C113 if(event.ctrlKey && event.altKey && event.keyCode === 67) {114 PMA_console.toggle();115 }116 });117 $('#pma_console .toolbar').children().mousedown(function(event) {118 event.preventDefault();119 event.stopImmediatePropagation();120 });121 $('#pma_console .button.clear').click(function() {122 PMA_consoleMessages.clear();123 });124 $('#pma_console .button.history').click(function() {125 PMA_consoleMessages.showHistory();126 });127 $('#pma_console .button.options').click(function() {128 PMA_console.showCard('#pma_console_options');129 });130 PMA_console.$consoleContent.click(function(event) {131 if (event.target == this) {132 PMA_consoleInput.focus();133 }134 });135 $('#pma_console .mid_layer').click(function() {136 PMA_console.hideCard($(this).parent().children('.card'));137 });138 $('#pma_bookmarks .switch_button').click(function() {139 PMA_console.hideCard($(this).closest('.card'));140 });141 $('#pma_console_options input[type=checkbox]').change(function() {142 PMA_console.updateConfig();143 });144 $('#pma_console_options .button.default').click(function() {145 $('#pma_console_options input[name=always_expand]').prop('checked', false);146 $('#pma_console_options input[name=start_history]').prop('checked', false);147 $('#pma_console_options input[name=current_query]').prop('checked', true);148 PMA_console.updateConfig();149 });150 $(document).ajaxComplete(function (event, xhr) {151 try {152 var data = $.parseJSON(xhr.responseText);153 PMA_console.ajaxCallback(data);154 } catch (e) {155 console.log("Invalid JSON!" + e.message);156 if(AJAX.xhr && AJAX.xhr.status === 0 && AJAX.xhr.statusText !== 'abort') {157 PMA_ajaxShowMessage($('<div />',{class:'error',html:PMA_messages.strRequestFailed+' ( '+AJAX.xhr.statusText+' )'}));158 AJAX.active = false;159 AJAX.xhr = null;160 }161 }162 });163 PMA_console.isInitialized = true;164 }165 // Change console mode from cookie166 switch($.cookie('pma_console_mode')) {167 case 'collapse':168 PMA_console.collapse();169 break;170 /* jshint -W086 */// no break needed in default section171 default:172 $.cookie('pma_console_mode', 'info');173 case 'info':174 /* jshint +W086 */175 PMA_console.info();176 break;177 case 'show':178 PMA_console.show(true);179 PMA_console.scrollBottom();180 break;181 }182 },183 /**184 * Execute query and show results in console185 *186 * @return void187 */188 execute: function(queryString, options) {189 if(typeof(queryString) != 'string' || ! /[a-z]|[A-Z]/.test(queryString)){190 return;191 }192 PMA_console.$requestForm.children('textarea').val(queryString);193 PMA_console.$requestForm.children('[name=server]').attr('value', PMA_commonParams.get('server'));194 if(options && options.db) {195 PMA_console.$requestForm.children('[name=db]').val(options.db);196 if(options.table) {197 PMA_console.$requestForm.children('[name=table]').val(options.table);198 } else {199 PMA_console.$requestForm.children('[name=table]').val('');200 }201 } else {202 PMA_console.$requestForm.children('[name=db]').val(203 (PMA_commonParams.get('db').length > 0 ? PMA_commonParams.get('db') : ''));204 }205 PMA_console.$requestForm.find('[name=profiling]').remove();206 if(options && options.profiling === true) {207 PMA_console.$requestForm.append('<input name="profiling" value="on">');208 }209 if (! confirmQuery(PMA_console.$requestForm[0], PMA_console.$requestForm.children('textarea')[0])) {210 return;211 }212 PMA_console.$requestForm.children('[name=console_message_id]')213 .val(PMA_consoleMessages.appendQuery({sql_query: queryString}).message_id);214 PMA_console.$requestForm.trigger('submit');215 PMA_consoleInput.clear();216 PMA_reloadNavigation();217 },218 ajaxCallback: function(data) {219 if(data && data.console_message_id) {220 PMA_consoleMessages.updateQuery(data.console_message_id, data.success,221 (data._reloadQuerywindow ? data._reloadQuerywindow : false));222 } else if( data && data._reloadQuerywindow) {223 if(data._reloadQuerywindow.sql_query.length > 0) {224 PMA_consoleMessages.appendQuery(data._reloadQuerywindow, 'successed')225 .$message.addClass(PMA_console.config.currentQuery ? '' : 'hide');226 }227 }228 },229 /**230 * Change console to collapse mode231 *232 * @return void233 */234 collapse: function() {235 $.cookie('pma_console_mode', 'collapse');236 var pmaConsoleHeight = $.cookie('pma_console_height');237 if(pmaConsoleHeight < 32) {238 $.cookie('pma_console_height', 92);239 }240 PMA_console.$consoleToolbar.addClass('collapsed');241 PMA_console.$consoleAllContents.height(pmaConsoleHeight);242 PMA_console.$consoleContent.stop();243 PMA_console.$consoleContent.animate({'margin-bottom': -1 * PMA_console.$consoleContent.outerHeight() + 'px'},244 'fast', 'easeOutQuart', function() {245 PMA_console.$consoleContent.css({display:'none'});246 $(window).trigger('resize');247 });248 PMA_console.hideCard();249 },250 /**251 * Show console252 *253 * @param bool inputFocus If true, focus the input line after show()254 * @return void255 */256 show: function(inputFocus) {257 $.cookie('pma_console_mode', 'show');258 var pmaConsoleHeight = $.cookie('pma_console_height');259 if(pmaConsoleHeight < 32) {260 $.cookie('pma_console_height', 32);261 PMA_console.collapse();262 return;263 }264 PMA_console.$consoleContent.css({display:'block'});265 if(PMA_console.$consoleToolbar.hasClass('collapsed')) {266 PMA_console.$consoleToolbar.removeClass('collapsed');267 }268 PMA_console.$consoleAllContents.height(pmaConsoleHeight);269 PMA_console.$consoleContent.stop();270 PMA_console.$consoleContent.animate({'margin-bottom': 0},271 'fast', 'easeOutQuart', function() {272 $(window).trigger('resize');273 if(inputFocus) {274 PMA_consoleInput.focus();275 }276 });277 },278 /**279 * Change console to SQL information mode280 * this mode shows current SQL query281 * This mode is the default mode282 *283 * @return void284 */285 info: function() {286 // Under construction287 PMA_console.collapse();288 },289 /**290 * Toggle console mode between collapse/show291 * Used for toggle buttons and shortcuts292 *293 * @return void294 */295 toggle: function() {296 switch($.cookie('pma_console_mode')) {297 case 'collapse':298 case 'info':299 PMA_console.show(true);300 break;301 case 'show':302 PMA_console.collapse();303 break;304 default:305 PMA_consoleInitialize();306 }307 },308 /**309 * Scroll console to bottom310 *311 * @return void312 */313 scrollBottom: function() {314 PMA_console.$consoleContent.scrollTop(PMA_console.$consoleContent.prop("scrollHeight"));315 },316 /**317 * Show card318 *319 * @param string cardSelector Selector, select string will be "#pma_console " + cardSelector320 * this param also can be JQuery object, if you need.321 *322 * @return void323 */324 showCard: function(cardSelector) {325 var $card = null;326 if(typeof(cardSelector) !== 'string') {327 if (cardSelector.length > 0) {328 $card = cardSelector;329 } else {330 return;331 }332 } else {333 $card = $("#pma_console " + cardSelector);334 }335 if($card.length === 0) {336 return;337 }338 $card.parent().children('.mid_layer').show().fadeTo(0, 0.15);339 $card.addClass('show');340 PMA_consoleInput.blur();341 if($card.parents('.card').length > 0) {342 PMA_console.showCard($card.parents('.card'));343 }344 },345 /**346 * Scroll console to bottom347 *348 * @param object $targetCard Target card JQuery object, if it's empty, function will hide all cards349 * @return void350 */351 hideCard: function($targetCard) {352 if(! $targetCard) {353 $('#pma_console .mid_layer').fadeOut(140);354 $('#pma_console .card').removeClass('show');355 } else if($targetCard.length > 0) {356 $targetCard.parent().find('.mid_layer').fadeOut(140);357 $targetCard.find('.card').removeClass('show');358 $targetCard.removeClass('show');359 }360 },361 /**362 * Used for update console config363 *364 * @return void365 */366 updateConfig: function() {367 PMA_console.config = {368 alwaysExpand: $('#pma_console_options input[name=always_expand]').prop('checked'),369 startHistory: $('#pma_console_options input[name=start_history]').prop('checked'),370 currentQuery: $('#pma_console_options input[name=current_query]').prop('checked')371 };372 $.cookie('pma_console_config', JSON.stringify(PMA_console.config));373 },374 isSelect: function (queryString) {375 var reg_exp = /^SELECT\s+/i;376 return reg_exp.test(queryString);377 }378};379/**380 * Resizer object381 * Careful: this object UI logics highly related with functions under PMA_console382 * Resizing min-height is 32, if small than it, console will collapse383 */384var PMA_consoleResizer = {385 _posY: 0,386 _height: 0,387 _resultHeight: 0,388 /**389 * Mousedown event handler for bind to resizer390 *391 * @return void392 */393 _mousedown: function(event) {394 if($.cookie('pma_console_mode') !== 'show') {395 return;396 }397 PMA_consoleResizer._posY = event.pageY;398 PMA_consoleResizer._height = PMA_console.$consoleContent.height();399 $(document).mousemove(PMA_consoleResizer._mousemove);400 $(document).mouseup(PMA_consoleResizer._mouseup);401 // Disable text selection while resizing402 $(document).bind('selectstart', function(){ return false; });403 },404 /**405 * Mousemove event handler for bind to resizer406 *407 * @return void408 */409 _mousemove: function(event) {410 if (event.pageY < 35) {411 event.pageY = 35412 }413 PMA_consoleResizer._resultHeight = PMA_consoleResizer._height + (PMA_consoleResizer._posY -event.pageY);414 // Content min-height is 32, if adjusting height small than it we'll move it out of the page415 if(PMA_consoleResizer._resultHeight <= 32) {416 PMA_console.$consoleAllContents.height(32);417 PMA_console.$consoleContent.css('margin-bottom', PMA_consoleResizer._resultHeight - 32);418 }419 else {420 // Logic below makes viewable area always at bottom when adjusting height and content already at bottom421 if(PMA_console.$consoleContent.scrollTop() + PMA_console.$consoleContent.innerHeight() + 16422 >= PMA_console.$consoleContent.prop('scrollHeight')) {423 PMA_console.$consoleAllContents.height(PMA_consoleResizer._resultHeight);424 PMA_console.scrollBottom();425 } else {426 PMA_console.$consoleAllContents.height(PMA_consoleResizer._resultHeight);427 }428 }429 },430 /**431 * Mouseup event handler for bind to resizer432 *433 * @return void434 */435 _mouseup: function() {436 $.cookie('pma_console_height', PMA_consoleResizer._resultHeight);437 PMA_console.show();438 $(document).unbind('mousemove');439 $(document).unbind('mouseup');440 $(document).unbind('selectstart');441 },442 /**443 * Used for console resizer initialize444 *445 * @return void446 */447 initialize: function() {448 $('#pma_console .toolbar').unbind('mousedown');449 $('#pma_console .toolbar').mousedown(PMA_consoleResizer._mousedown);450 }451};452/**453 * Console input object454 */455var PMA_consoleInput = {456 /**457 * @var array, contains Codemirror objects or input jQuery objects458 * @access private459 */460 _inputs: null,461 /**462 * @var bool, if codemirror enabled463 * @access private464 */465 _codemirror: false,466 /**467 * @var int, count for history navigation, 0 for current input468 * @access private469 */470 _historyCount: 0,471 /**472 * @var string, current input when navigating through history473 * @access private474 */475 _historyPreserveCurrent: null,476 /**477 * Used for console input initialize478 *479 * @return void480 */481 initialize: function() {482 // _cm object can't be reinitialize483 if(PMA_consoleInput._inputs !== null) {484 return;485 }486 if(typeof CodeMirror !== 'undefined') {487 PMA_consoleInput._codemirror = true;488 }489 PMA_consoleInput._inputs = [];490 if (PMA_consoleInput._codemirror) {491 PMA_consoleInput._inputs.console = CodeMirror($('#pma_console .console_query_input')[0], {492 theme: 'pma',493 mode: 'text/x-sql',494 lineWrapping: true,495 extraKeys: {"Ctrl-Space": "autocomplete"},496 hintOptions: {"completeSingle": false, "completeOnSingleClick": true}497 });498 PMA_consoleInput._inputs.console.on("inputRead", codemirrorAutocompleteOnInputRead);499 PMA_consoleInput._inputs.console.on("keydown", function(instance, event) {500 PMA_consoleInput._historyNavigate(event);501 });502 if ($('#pma_bookmarks').length !== 0) {503 PMA_consoleInput._inputs.bookmark = CodeMirror($('#pma_console .bookmark_add_input')[0], {504 theme: 'pma',505 mode: 'text/x-sql',506 lineWrapping: true,507 extraKeys: {"Ctrl-Space": "autocomplete"},508 hintOptions: {"completeSingle": false, "completeOnSingleClick": true}509 });510 PMA_consoleInput._inputs.bookmark.on("inputRead", codemirrorAutocompleteOnInputRead);511 }512 } else {513 PMA_consoleInput._inputs.console =514 $('<textarea>').appendTo('#pma_console .console_query_input')515 .on('keydown', PMA_consoleInput._historyNavigate);516 if ($('#pma_bookmarks').length !== 0) {517 PMA_consoleInput._inputs.bookmark =518 $('<textarea>').appendTo('#pma_console .bookmark_add_input');519 }520 }521 $('#pma_console .console_query_input').keydown(PMA_consoleInput._keydown);522 },523 _historyNavigate: function(event) {524 if (event.keyCode == 38 || event.keyCode == 40) {525 var upPermitted = false;526 var downPermitted = false;527 var editor = PMA_consoleInput._inputs.console;528 var cursorLine;529 var totalLine;530 if (PMA_consoleInput._codemirror) {531 cursorLine = editor.getCursor().line;532 totalLine = editor.lineCount();533 } else {534 // Get cursor position from textarea535 var text = PMA_consoleInput.getText();536 cursorLine = text.substr(0, editor.prop("selectionStart")).split("\n").length - 1;537 totalLine = text.split(/\r*\n/).length;538 }539 if (cursorLine === 0) {540 upPermitted = true;541 }542 if (cursorLine == totalLine - 1) {543 downPermitted = true;544 }545 var nextCount;546 var queryString = false;547 if (upPermitted && event.keyCode == 38) {548 // Navigate up in history549 if (PMA_consoleInput._historyCount === 0) {550 PMA_consoleInput._historyPreserveCurrent = PMA_consoleInput.getText();551 }552 nextCount = PMA_consoleInput._historyCount + 1;553 queryString = PMA_consoleMessages.getHistory(nextCount);554 } else if (downPermitted && event.keyCode == 40) {555 // Navigate down in history556 if (PMA_consoleInput._historyCount === 0) {557 return;558 }559 nextCount = PMA_consoleInput._historyCount - 1;560 if (nextCount === 0) {561 queryString = PMA_consoleInput._historyPreserveCurrent;562 } else {563 queryString = PMA_consoleMessages.getHistory(nextCount);564 }565 }566 if (queryString !== false) {567 PMA_consoleInput._historyCount = nextCount;568 PMA_consoleInput.setText(queryString, 'console');569 if (PMA_consoleInput._codemirror) {570 editor.setCursor(editor.lineCount(), 0);571 }572 event.preventDefault();573 }574 }575 },576 /**577 * Mousedown event handler for bind to input578 * Shortcut is Ctrl+Enter key579 *580 * @return void581 */582 _keydown: function(event) {583 if(event.ctrlKey && event.keyCode === 13) {584 PMA_consoleInput.execute();585 }586 },587 /**588 * Used for send text to PMA_console.execute()589 *590 * @return void591 */592 execute: function() {593 if (PMA_consoleInput._codemirror) {594 PMA_console.execute(PMA_consoleInput._inputs.console.getValue());595 } else {596 PMA_console.execute(PMA_consoleInput._inputs.console.val());597 }598 },599 /**600 * Used for clear the input601 *602 * @param string target, default target is console input603 * @return void604 */605 clear: function(target) {606 PMA_consoleInput.setText('', target);607 },608 /**609 * Used for set focus to input610 *611 * @return void612 */613 focus: function() {614 PMA_consoleInput._inputs.console.focus();615 },616 /**617 * Used for blur input618 *619 * @return void620 */621 blur: function() {622 if (PMA_consoleInput._codemirror) {623 PMA_consoleInput._inputs.console.getInputField().blur();624 } else {625 PMA_consoleInput._inputs.console.blur();626 }627 },628 /**629 * Used for set text in input630 *631 * @param string text632 * @param string target633 * @return void634 */635 setText: function(text, target) {636 if (PMA_consoleInput._codemirror) {637 switch(target) {638 case 'bookmark':639 PMA_console.execute(PMA_consoleInput._inputs.bookmark.setValue(text));640 break;641 default:642 case 'console':643 PMA_console.execute(PMA_consoleInput._inputs.console.setValue(text));644 }645 } else {646 switch(target) {647 case 'bookmark':648 PMA_console.execute(PMA_consoleInput._inputs.bookmark.val(text));649 break;650 default:651 case 'console':652 PMA_console.execute(PMA_consoleInput._inputs.console.val(text));653 }654 }655 },656 getText: function(target) {657 if (PMA_consoleInput._codemirror) {658 switch(target) {659 case 'bookmark':660 return PMA_consoleInput._inputs.bookmark.getValue();661 default:662 case 'console':663 return PMA_consoleInput._inputs.console.getValue();664 }665 } else {666 switch(target) {667 case 'bookmark':668 return PMA_consoleInput._inputs.bookmark.val();669 default:670 case 'console':671 return PMA_consoleInput._inputs.console.val();672 }673 }674 }675};676/**677 * Console messages, and message items management object678 */679var PMA_consoleMessages = {680 /**681 * Used for clear the messages682 *683 * @return void684 */685 clear: function() {686 $('#pma_console .content .console_message_container .message:not(.welcome)').addClass('hide');687 $('#pma_console .content .console_message_container .message.failed').remove();688 $('#pma_console .content .console_message_container .message.expanded').find('.action.collapse').click();689 },690 /**691 * Used for show history messages692 *693 * @return void694 */695 showHistory: function() {696 $('#pma_console .content .console_message_container .message.hide').removeClass('hide');697 },698 /**699 * Used for getting a perticular history query700 *701 * @param int nthLast get nth query message from latest, i.e 1st is last702 * @return string message703 */704 getHistory: function(nthLast) {705 var $queries = $('#pma_console .content .console_message_container .query');706 var length = $queries.length;707 var $query = $queries.eq(length - nthLast);708 if (!$query || (length - nthLast) < 0) {709 return false;710 } else {711 return $query.text();712 }713 },714 /**715 * Used for log new message716 *717 * @param string msgString Message to show718 * @param string msgType Message type719 * @return object, {message_id, $message}720 */721 append: function(msgString, msgType) {722 if(typeof(msgString) !== 'string') {723 return false;724 }725 // Generate an ID for each message, we can find them later726 var msgId = Math.round(Math.random()*(899999999999)+100000000000);727 var now = new Date();728 var $newMessage =729 $('<div class="message '730 + (PMA_console.config.alwaysExpand ? 'expanded' : 'collapsed')731 +'" msgid="' + msgId + '"><div class="action_content"></div></div>');732 switch(msgType) {733 case 'query':734 $newMessage.append('<div class="query highlighted"></div>');735 if(PMA_consoleInput._codemirror) {736 CodeMirror.runMode(msgString,737 'text/x-sql', $newMessage.children('.query')[0]);738 } else {739 $newMessage.children('.query').text(msgString);740 }741 $newMessage.children('.action_content')742 .append(PMA_console.$consoleTemplates.children('.query_actions').html());743 break;744 default:745 case 'normal':746 $newMessage.append('<div>' + msgString + '</div>');747 }748 PMA_consoleMessages._msgEventBinds($newMessage);749 $newMessage.find('span.text.query_time span')750 .text(now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds())751 .parent().attr('title', now);752 return {message_id: msgId,753 $message: $newMessage.appendTo('#pma_console .content .console_message_container')};754 },755 /**756 * Used for log new query757 *758 * @param string queryData Struct should be759 * {sql_query: "Query string", db: "Target DB", table: "Target Table"}760 * @param string state Message state761 * @return object, {message_id: string message id, $message: JQuery object}762 */763 appendQuery: function(queryData, state) {764 var targetMessage = PMA_consoleMessages.append(queryData.sql_query, 'query');765 if(! targetMessage) {766 return false;767 }768 if(queryData.db && queryData.table) {769 targetMessage.$message.attr('targetdb', queryData.db);770 targetMessage.$message.attr('targettable', queryData.table);771 targetMessage.$message.find('.text.targetdb span').text(queryData.db);772 }773 if(PMA_console.isSelect(queryData.sql_query)) {774 targetMessage.$message.addClass('select');775 }776 switch(state) {777 case 'failed':778 targetMessage.$message.addClass('failed');779 break;780 case 'successed':781 targetMessage.$message.addClass('successed');782 break;783 default:784 case 'pending':785 targetMessage.$message.addClass('pending');786 }787 return targetMessage;788 },789 _msgEventBinds: function($targetMessage) {790 // Leave unbinded elements, remove binded.791 $targetMessage = $targetMessage.filter(':not(.binded)');792 if($targetMessage.length === 0) {793 return;794 }795 $targetMessage.addClass('binded');796 $targetMessage.find('.action.expand').click(function () {797 $(this).closest('.message').removeClass('collapsed');798 $(this).closest('.message').addClass('expanded');799 });800 $targetMessage.find('.action.collapse').click(function () {801 $(this).closest('.message').addClass('collapsed');802 $(this).closest('.message').removeClass('expanded');803 });804 $targetMessage.find('.action.edit').click(function () {805 PMA_consoleInput.setText($(this).parent().siblings('.query').text());806 PMA_consoleInput.focus();807 });808 $targetMessage.find('.action.requery').click(function () {809 var query = $(this).parent().siblings('.query').text();810 var $message = $(this).closest('.message');811 if(confirm(PMA_messages.strConsoleRequeryConfirm + '\n'812 + (query.length<100 ? query : query.slice(0, 100) + '...'))) {813 PMA_console.execute(query, {db: $message.attr('targetdb'), table: $message.attr('targettable')});814 }815 });816 $targetMessage.find('.action.bookmark').click(function () {817 var query = $(this).parent().siblings('.query').text();818 var $message = $(this).closest('.message');819 PMA_consoleBookmarks.addBookmark(query, $message.attr('targetdb'));820 PMA_console.showCard('#pma_bookmarks .card.add');821 });822 $targetMessage.find('.action.edit_bookmark').click(function () {823 var query = $(this).parent().siblings('.query').text();824 var $message = $(this).closest('.message');825 var isShared = $message.find('span.bookmark_label').hasClass('shared');826 var label = $message.find('span.bookmark_label').text();827 PMA_consoleBookmarks.addBookmark(query, $message.attr('targetdb'), label, isShared);828 PMA_console.showCard('#pma_bookmarks .card.add');829 });830 $targetMessage.find('.action.delete_bookmark').click(function () {831 var $message = $(this).closest('.message');832 if(confirm(PMA_messages.strConsoleDeleteBookmarkConfirm + '\n' + $message.find('.bookmark_label').text())) {833 $.post('import.php',834 {token: PMA_commonParams.get('token'),835 server: PMA_commonParams.get('server'),836 action_bookmark: 2,837 ajax_request: true,838 id_bookmark: $message.attr('bookmarkid')},839 function () {840 PMA_consoleBookmarks.refresh();841 });842 }843 });844 $targetMessage.find('.action.profiling').click(function () {845 var $message = $(this).closest('.message');846 PMA_console.execute($(this).parent().siblings('.query').text(),847 {db: $message.attr('targetdb'),848 table: $message.attr('targettable'),849 profiling: true});850 });851 $targetMessage.find('.action.explain').click(function () {852 var $message = $(this).closest('.message');853 PMA_console.execute('EXPLAIN ' + $(this).parent().siblings('.query').text(),854 {db: $message.attr('targetdb'),855 table: $message.attr('targettable')});856 });857 if(PMA_consoleInput._codemirror) {858 $targetMessage.find('.query:not(.highlighted)').each(function(index, elem) {859 CodeMirror.runMode($(elem).text(),860 'text/x-sql', elem);861 $(this).addClass('highlighted');862 });863 }864 },865 msgAppend: function(msgId, msgString, msgType) {866 var $targetMessage = $('#pma_console .content .console_message_container .message[msgid=' + msgId +']');867 if($targetMessage.length === 0 || isNaN(parseInt(msgId)) || typeof(msgString) !== 'string') {868 return false;869 }870 $targetMessage.append('<div>' + msgString + '</div>');871 },872 updateQuery: function(msgId, isSuccessed, queryData) {873 var $targetMessage = $('#pma_console .console_message_container .message[msgid=' + parseInt(msgId) +']');874 if($targetMessage.length === 0 || isNaN(parseInt(msgId))) {875 return false;876 }877 $targetMessage.removeClass('pending failed successed');878 if(isSuccessed) {879 $targetMessage.addClass('successed');880 if(queryData) {881 $targetMessage.children('.query').text('');882 $targetMessage.removeClass('select');883 if(PMA_console.isSelect(queryData.sql_query)) {884 $targetMessage.addClass('select');885 }886 if(PMA_consoleInput._codemirror) {887 CodeMirror.runMode(queryData.sql_query, 'text/x-sql', $targetMessage.children('.query')[0]);888 } else {889 $targetMessage.children('.query').text(queryData.sql_query);890 }891 $targetMessage.attr('targetdb', queryData.db);892 $targetMessage.attr('targettable', queryData.table);893 $targetMessage.find('.text.targetdb span').text(queryData.db);894 }895 } else {896 $targetMessage.addClass('failed');897 }898 },899 /**900 * Used for console messages initialize901 *902 * @return void903 */904 initialize: function() {905 PMA_consoleMessages._msgEventBinds($('#pma_console .message:not(.binded)'));906 if(PMA_console.config.startHistory) {907 PMA_consoleMessages.showHistory();908 }909 }910};911/**912 * Console bookmarks card, and bookmarks items management object913 */914var PMA_consoleBookmarks = {915 _bookmarks: [],916 addBookmark: function (queryString, targetDb, label, isShared, id) {917 $('#pma_bookmarks .add [name=shared]').prop('checked', false);918 $('#pma_bookmarks .add [name=label]').val('');919 $('#pma_bookmarks .add [name=targetdb]').val('');920 $('#pma_bookmarks .add [name=id_bookmark]').val('');921 PMA_consoleInput.setText('', 'bookmark');922 switch(arguments.length) {923 case 4:924 $('#pma_bookmarks .add [name=shared]').prop('checked', isShared);925 case 3:926 $('#pma_bookmarks .add [name=label]').val(label);927 case 2:928 $('#pma_bookmarks .add [name=targetdb]').val(targetDb);929 case 1:930 PMA_consoleInput.setText(queryString, 'bookmark');931 default:932 break;933 }934 },935 refresh: function () {936 $.get('import.php',937 {ajax_request: true,938 token: PMA_commonParams.get('token'),939 server: PMA_commonParams.get('server'),940 console_bookmark_refresh: 'refresh'},941 function(data) {942 if(data.console_message_bookmark) {943 $('#pma_bookmarks .content.bookmark').html(data.console_message_bookmark);944 PMA_consoleMessages._msgEventBinds($('#pma_bookmarks .message:not(.binded)'));945 }946 });947 },948 /**949 * Used for console bookmarks initialize950 * message events are already binded by PMA_consoleMsg._msgEventBinds951 *952 * @return void953 */954 initialize: function() {955 if($('#pma_bookmarks').length === 0) {956 return;957 }958 $('#pma_console .button.bookmarks').click(function() {959 PMA_console.showCard('#pma_bookmarks');960 });961 $('#pma_bookmarks .button.add').click(function() {962 PMA_console.showCard('#pma_bookmarks .card.add');963 });964 $('#pma_bookmarks .card.add [name=submit]').click(function () {965 if ($('#pma_bookmarks .card.add [name=label]').val().length === 0966 || PMA_consoleInput.getText('bookmark').length === 0)967 {968 alert(PMA_messages.strFormEmpty);969 return;970 }971 $(this).prop('disabled', true);972 $.post('import.php',973 {token: PMA_commonParams.get('token'),974 ajax_request: true,975 console_bookmark_add: 'true',976 label: $('#pma_bookmarks .card.add [name=label]').val(),977 server: PMA_commonParams.get('server'),978 db: $('#pma_bookmarks .card.add [name=targetdb]').val(),979 bookmark_query: PMA_consoleInput.getText('bookmark'),980 shared: $('#pma_bookmarks .card.add [name=shared]').prop('checked')},981 function () {982 PMA_consoleBookmarks.refresh();983 $('#pma_bookmarks .card.add [name=submit]').prop('disabled', false);984 PMA_console.hideCard($('#pma_bookmarks .card.add'));985 });986 });987 $('#pma_console .button.refresh').click(function() {988 PMA_consoleBookmarks.refresh();989 });990 }991};992/**993 * Executed on page load994 */995$(function () {996 PMA_console.initialize();...

Full Screen

Full Screen

fizzbuzz.js

Source:fizzbuzz.js Github

copy

Full Screen

1(function () {2 "use strict";3 console.log("fizzbuz1");4 let fizzbuzz1 = function (num) {5 for (let i = 1; i <= num; i++) {6 if (i % 3 === 0 && i % 5 === 0) {7 console.log("fizzbuzz");8 } else if (i % 3 === 0) {9 console.log("fizz");10 } else if (i % 5 === 0) {11 console.log("buzz");12 } else {13 console.log(i);14 }15 }16 }17 fizzbuzz1( 31);18 console.log("fizzbuzz2");19 let fizzbuzz2 = function (num) {20 for (let i = 1; i <= num; i++) {21 if (i % 3 === 0 && i % 5 === 0) {22 console.log("fizzbuzz");23 } else if (i % 3 === 0) {24 console.log("fizz");25 } else if (i % 5 === 0) {26 console.log("buzz");27 } else {28 console.log(i);29 }30 }31 }32 fizzbuzz2(31);33 console.log("fizzbuzz3");34 let fizzbuzz3 = function(num) {35 for (let i = 1; i <= num; i++) {36 if (i % 3 === 0 && i % 5 === 0) {37 console.log("fizzbuzz");38 } else if (i % 3 === 0) {39 console.log("fizz");40 } else if (i % 5 === 0) {41 console.log("buzz");42 } else {43 console.log(i);44 }45 }46 }47 fizzbuzz3(31);48 console.log("fizzbuzz4");49 let fizzbuzz4 = function(num) {50 for (let i = 1; i <= num; i ++) {51 if (i % 3 === 0 && i % 5 === 0) {52 console.log("fizzbuzz");53 } else if (i % 3 === 0) {54 console.log("fizz");55 } else if (i % 5 === 0) {56 console.log("buzz");57 } else {58 console.log(i);59 }60 }61 }62 fizzbuzz4(31)63 console.log("fizzbuzz5");64 let fizzbuzz5 = function(num) {65 for (let i = 1; i <= num; i++) {66 if (i % 5 === 0 && i % 3 === 0) {67 console.log("fizzbuzz");68 } else if (i % 3 === 0) {69 console.log("fizz");70 `` } else if (i % 5 === 0) {71 console.log("buzz");72 } else {73 console.log(i);74 }75 }76 }77 fizzbuzz5(31);78 console.log("fizzbuzz6");79 let fizzbuzz6 = function(num) {80 for (let i = 1; i <= num; i++) {81 if (i % 5 === 0 && i % 3 === 0) {82 console.log("fizzbuzz");83 } else if (i % 3 === 0) {84 console.log("fizz");85 } else if (i % 5 === 0) {86 console.log("buzz");87 } else {88 console.log(i);89 }90 }91 }92 fizzbuzz6(31)93 console.log("fizzbuzz7");94 let fizzbuzz7 = function(num) {95 for (let i = 1; i <= num; i++) {96 if (i % 5 === 0 && i % 3 === 0){97 console.log("fizzbuzz");98 } else if (i % 3 ===0) {99 console.log("fizz");100 } else if (i % 5 === 0) {101 console.log("buzz");102 } else {103 console.log(i);104 }105 }106 }107 fizzbuzz7(31);108 console.log("fizzbuzz8");109 function fizzbuzz8(num) {110 for (var i = 1; i <= num; i++) {111 switch (true) {112 case i % 3 === 0 && i % 5 === 0:113 console.log("fizzbuzz");114 break;115 case i % 3 === 0:116 console.log("fizz");117 break;118 case i % 5 === 0:119 console.log("buzz");120 break;121 default:122 console.log(i);123 break;124 }125 }126 }127 fizzbuzz8(31);128 console.log("fizzbuzz9");129 function fizzbuzz9(num) {130 for (var i = 1; i <= num; i++) {131 var f = i % 3 === 0, b = i % 5 === 0;132 console.log(f ? b ? "fizzbuzz" : "fizz" : b ? "buzz" : i);133 }134 }135 fizzbuzz9(31);136 console.log("fizzbuzz10");137 let fizzbuzz10 = function(num) {138 for (let i = 1; i <= num; i++) {139 if (i % 5 === 0 && i % 3 === 0){140 console.log("fizzbuzz");141 } else if (i % 3 ===0) {142 console.log("fizz");143 } else if (i % 5 === 0) {144 console.log("buzz");145 } else {146 console.log(i);147 }148 }149 }150 fizzbuzz10(31);151 console.log("fizzbuzz11");152 let fizzbuzz11 = function(num) {153 for (let i = 1; i <= num; i++) {154 if (i % 5 === 0 && i % 3 === 0) {155 console.log("fizzbuzz");156 } else if (i % 3 === 0) {157 console.log("fizz")158 } else if (i % 5 === 0) {159 console.log("buzz")160 } else {161 console.log(i);162 }163 }164 }165 fizzbuzz11(31);166 console.log("fizzbuzz12");167 const fizzbuzz12 = function(num) {168 for (var i = 1; i <= num; i++) {169 if (i % 5 === 0 && i % 3 === 0) {170 console.log("fizzbuzz");171 } else if (i % 3 === 0) {172 console.log("fizz");173 } else if (i % 5 === 0) {174 console.log("buzz");175 } else {176 console.log(i);177 }178 }179 }180 fizzbuzz12(31);181 console.log("fizzbuzz13");182 function fizzbuzz13(num) {183 for (var i = 1; i <= num; i++) {184 switch (true) {185 case i % 3 === 0 && i % 5 === 0:186 console.log("fizzbuzz");187 break;188 case i % 3 === 0:189 console.log("fizz");190 break;191 case i % 5 === 0:192 console.log("buzz");193 break;194 default:195 console.log(i);196 break;197 }198 }199 }200 fizzbuzz13(31);201 console.log("fibonacci");202 let fibonacci = function(num) {203 let output = [0,1];204 let i = output.length;205 while (i<num) {206 output.push(output[output.length - 2] + output[output.length - 1]);207 i++;208 }209 return output;210 }211 console.log(fibonacci(31));212 console.log("fibonacci2");213 let fibonacci2 = function(num) {214 let output = [0,1];215 let i = output.length;216 while (i<num) {217 output.push(output[output.length - 2] + output[output.length - 1]);218 i++;219 }220 return output;221 }222 console.log(fibonacci2(31));...

Full Screen

Full Screen

webConsole.js

Source:webConsole.js Github

copy

Full Screen

1define(["customConsole"], function (customConsole) {2 /**3 * 页面输出公共方法4 * @method 5 * @for webConsole6 * @param {String} type console类型7 * {String} consoleStr 输出内容8 * {String} consoleLocationStr 输出源9 * @return10 */11 var consoleFn = function (type, consoleStr, consoleLocationStr) {12 var loadConsoleObj = function (typ, str, locationStr) {13 var consoleObj = {14 consoleType: "",15 consoleStr: "",16 consoleLocationStr: ""17 };18 consoleObj.consoleType = "[webConsole--" + type + "]" || "[unKnown Type]";19 consoleObj.consoleStr = str || "";20 consoleObj.consoleLocationStr = locationStr || "";21 return consoleObj;22 }23 var consoleShow = "";24 if (typeof (type) != "string" && typeof (consoleStr) != "string") {25 type = "error";26 consoleShow = loadConsoleObj(type, "consoleFn's params need correct defining!", "consoleFn");27 }28 else {29 if (consoleStr != undefined && !consoleStr.isNull()) {30 consoleShow = loadConsoleObj(type, consoleStr, consoleLocationStr);31 }32 else {33 type = "warn";34 consoleShow = loadConsoleObj(type, "unKnown Error:" + "{type:" + type + "}" + "{consoleStr:" + consoleStr + "}" + "{consoleLocationStr:" + consoleLocationStr + "}", "consoleFn");35 }36 }37 console.log(consoleShow);38 };39 /**40 * 页面错误输出41 * @method error42 * @for webConsole43 * @param {String} exStr 错误内容44 * {String} locationExStr 错误源(建议)45 * @return46 */47 var errorFn = function (exStr, locationExStr) {48 if (consoleFn && typeof (consoleFn) == "function") {49 consoleFn("error", exStr, locationExStr);50 }51 };52 /**53 * 页面警告输出54 * @method warn55 * @for webConsole56 * @param {String} warnStr 警告内容57 * {String} locationWarnStr 警告源(建议)58 * @return59 */60 var warnFn = function (warnStr, locationWarnStr) {61 if (consoleFn && typeof (consoleFn) == "function") {62 consoleFn("warn", warnStr, locationWarnStr);63 }64 }65 /**66 * 页面日志输出67 * @method log68 * @for webConsole69 * @param {String} logStr 日志内容70 * {String} locationLogStr 日志源(可选)71 * @return72 */73 var logFn = function (logStr, locationLogStr) {74 if (consoleFn && typeof (consoleFn) == "function") {75 consoleFn("log", logStr, locationLogStr);76 }77 };78 return {79 error: errorFn,80 warn: warnFn,81 log: logFn82 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const Chromy = require('chromy');2const chromy = new Chromy();3chromy.chain()4 .evaluate(() => {5 console.log('Hello World');6 })7 .end()8 .then(() => chromy.close());

Full Screen

Using AI Code Generation

copy

Full Screen

1chromy.chain()2 .evaluate(function(){3 console.log('Hello World');4 })5 .end()6 .then(function(result){7 console.log('result', result);8 })9 .catch(function(err){10 console.log('err', err);11 });12### 2. `chromy.chain().goto().evaluate().end().then().catch()`13chromy.chain()14 .evaluate(function(){15 console.log('Hello World');16 })17 .end()18 .then(function(result){19 console.log('result', result);20 })21 .catch(function(err){22 console.log('err', err);23 });24### 3. `chromy.chain().goto().evaluate().screenshot().end().then().catch()`25chromy.chain()26 .evaluate(function(){27 console.log('Hello World');28 })29 .screenshot()30 .end()31 .then(function(result){32 console.log('result', result);33 })34 .catch(function(err){35 console.log('err', err);36 });37### 4. `chromy.chain().goto().evaluate().wait().end().then().catch()`38chromy.chain()39 .evaluate(function(){40 console.log('Hello World');41 })42 .wait(5000)43 .end()44 .then(function(result){45 console.log('result', result);46 })47 .catch(function(err){48 console.log('err', err);49 });50### 5. `chromy.chain().goto().evaluate().wait().screenshot().end().then().catch()`51chromy.chain()52 .evaluate(function(){53 console.log('Hello World');54 })55 .wait(5000)56 .screenshot()57 .end()58 .then(function(result){59 console.log('result',

Full Screen

Using AI Code Generation

copy

Full Screen

1chromy.on('Console.messageAdded', msg => {2 console.log('Console Message:', msg.message.text);3});4chromy.on('Page.loadEventFired', () => {5 chromy.evaluate(() => {6 console.log('Page loadEventFired');7 });8});9chromy.on('Page.frameStartedLoading', frameId => {10 chromy.evaluate(() => {11 console.log('Page frameStartedLoading');12 });13});14chromy.on('Page.frameNavigated', frame => {15 chromy.evaluate(() => {16 console.log('Page frameNavigated');17 });18});19chromy.on('Page.frameStoppedLoading', frameId => {20 chromy.evaluate(() => {21 console.log('Page frameStoppedLoading');22 });23});24chromy.on('Page.frameScheduledNavigation', (frameId, delay) => {25 chromy.evaluate(() => {26 console.log('Page frameScheduledNavigation');27 });28});29chromy.on('Page.frameClearedScheduledNavigation', frameId => {30 chromy.evaluate(() => {31 console.log('Page frameClearedScheduledNavigation');32 });33});34chromy.on('Page.frameResized', () => {35 chromy.evaluate(() => {36 console.log('Page frameResized');37 });38});39chromy.on('Page.domContentEventFired', timestamp => {40 chromy.evaluate(() => {41 console.log('Page domContentEventFired');42 });43});44chromy.on('Page.loadEventFired', timestamp => {45 chromy.evaluate(() => {46 console.log('Page loadEventFired');47 });48});49chromy.on('Page.javascriptDialogOpening', () => {50 chromy.evaluate(() => {51 console.log('Page javascriptDialogOpening');52 });53});54chromy.on('Page.javascriptDialogClosed', () => {55 chromy.evaluate(() => {56 console.log('Page javascriptDialogClosed');57 });58});59chromy.on('Page.screencastFrame', frame => {60 chromy.evaluate(() => {61 console.log('Page screencastFrame');62 });63});64chromy.on('Page.screencastVisibilityChanged', visible => {65 chromy.evaluate(() => {66 console.log('Page screencastVisibilityChanged');67 });68});69chromy.on('Page.interstitialShown', () => {70 chromy.evaluate(() => {71 console.log('Page interstitialShown');72 });73});74chromy.on('Page.interstitialHidden', () =>

Full Screen

Using AI Code Generation

copy

Full Screen

1 .evaluate(function() {2 console.log('Hello, world!');3 })4 .end()5 .then(function(result) {6 })7 .catch(function(err) {8 });9 .evaluate(function() {10 console.log('Hello, world!');11 })12 .end()13 .then(function(result) {14 })15 .catch(function(err) {16 });

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 chromy 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