How to use shortcut method in storybook-root

Best JavaScript code snippet using storybook-root

keyboard.js

Source:keyboard.js Github

copy

Full Screen

...119 /**120 * Convert a shortcut (shift-r) to a jQuery Event object121 **/122 type = type || 'keydown';123 shortcut = normalize_shortcut(shortcut);124 shortcut = shortcut.replace(/-$/, 'minus'); // catch shortcuts using '-' key125 var values = shortcut.split("-");126 var modifiers = values.slice(0,-1);127 var key = values[values.length-1];128 var opts = {which: keycodes[key]};129 if (modifiers.indexOf('alt') !== -1) {opts.altKey = true;}130 if (modifiers.indexOf('ctrl') !== -1) {opts.ctrlKey = true;}131 if (modifiers.indexOf('meta') !== -1) {opts.metaKey = true;}132 if (modifiers.indexOf('shift') !== -1) {opts.shiftKey = true;}133 return $.Event(type, opts);134 };135 var only_modifier_event = function(event){136 /**137 * Return `true` if the event only contains modifiers keys.138 * false otherwise139 **/140 var key = inv_keycodes[event.which];141 return ((event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) &&142 (key === 'alt'|| key === 'ctrl'|| key === 'meta'|| key === 'shift'));143 };144 var event_to_shortcut = function (event) {145 /**146 * Convert a jQuery Event object to a normalized shortcut string (shift-r)147 **/148 var shortcut = '';149 var key = inv_keycodes[event.which];150 if (event.altKey && key !== 'alt') {shortcut += 'alt-';}151 if (event.ctrlKey && key !== 'ctrl') {shortcut += 'ctrl-';}152 if (event.metaKey && key !== 'meta') {shortcut += 'meta-';}153 if (event.shiftKey && key !== 'shift') {shortcut += 'shift-';}154 shortcut += key;155 return shortcut;156 };157 // Shortcut manager class158 var ShortcutManager = function (delay, events, actions, env, config, mode) {159 /**160 * A class to deal with keyboard event and shortcut161 *162 * @class ShortcutManager163 * @constructor164 *165 * :config: configobjet on which to call `update(....)` to persist the config.166 * :mode: mode of this shortcut manager where to persist config.167 */168 mode = mode || 'command';169 this._shortcuts = {};170 this._defaults_bindings = [];171 this.delay = delay || 800; // delay in milliseconds172 this.events = events;173 this.actions = actions;174 this.actions.extend_env(env);175 this._queue = [];176 this._cleartimeout = null;177 this._config = config;178 this._mode = mode;179 Object.seal(this);180 };181 ShortcutManager.prototype.clearsoon = function(){182 /**183 * Clear the pending shortcut soon, and cancel previous clearing184 * that might be registered.185 **/186 var that = this;187 clearTimeout(this._cleartimeout);188 this._cleartimeout = setTimeout(function(){that.clearqueue();}, this.delay);189 };190 ShortcutManager.prototype.clearqueue = function(){191 /**192 * clear the pending shortcut sequence now. 193 **/194 this._queue = [];195 clearTimeout(this._cleartimeout);196 };197 var flatten_shorttree = function(tree){198 /**199 * Flatten a tree of shortcut sequences. 200 * use full to iterate over all the key/values of available shortcuts.201 **/202 var dct = {};203 _.forEach(tree, function(value, key) {204 if(typeof(value) === 'string'){205 dct[key] = value;206 } else {207 var ftree=flatten_shorttree(value);208 _.forEach(ftree, function(v2, subkey) {209 dct[key+','+subkey] = ftree[subkey];210 });211 } 212 });213 return dct;214 };215 ShortcutManager.prototype.get_action_shortcuts = function(name){216 var ftree = flatten_shorttree(this._shortcuts);217 var res = [];218 _.forEach(ftree, function(value, key) {219 if(value === name){220 res.push(key);221 }222 });223 return res;224 };225 226 ShortcutManager.prototype.get_action_shortcut = function(name){227 var matches = this.get_action_shortcuts(name);228 if (matches.length > 0) {229 return matches[0];230 }231 return undefined;232 };233 ShortcutManager.prototype.help = function () {234 var that = this;235 var help = [];236 var ftree = flatten_shorttree(this._shortcuts);237 _.forEach(ftree, function(value, key) {238 var action = that.actions.get(value);239 var help_string = action.help||'== no help ==';240 var help_index = action.help_index;241 if (help_string) {242 var shortstring = (action.shortstring||key);243 help.push({244 shortcut: shortstring,245 help: help_string,246 help_index: help_index}247 );248 }249 });250 help.sort(function (a, b) {251 if (a.help_index === b.help_index) {252 if (a.shortcut === b.shortcut) {253 return 0;254 }255 if (a.shortcut > b.shortcut) {256 return 1;257 }258 return -1;259 }260 if (a.help_index === undefined || a.help_index > b.help_index){261 return 1;262 }263 return -1;264 });265 return help;266 };267 ShortcutManager.prototype.clear_shortcuts = function () {268 this._shortcuts = {};269 };270 ShortcutManager.prototype.get_shortcut = function (shortcut){271 /**272 * return a node of the shortcut tree which an action name (string) if leaf,273 * and an object with `object.subtree===true`274 **/275 if(typeof(shortcut) === 'string'){276 shortcut = shortcut.split(',');277 }278 279 return this._get_leaf(shortcut, this._shortcuts);280 };281 ShortcutManager.prototype._get_leaf = function(shortcut_array, tree){282 /**283 * @private284 * find a leaf/node in a subtree of the keyboard shortcut285 *286 **/287 if(shortcut_array.length === 1){288 return tree[shortcut_array[0]];289 } else if( typeof(tree[shortcut_array[0]]) !== 'string'){290 return this._get_leaf(shortcut_array.slice(1), tree[shortcut_array[0]]);291 }292 return null;293 };294 ShortcutManager.prototype.set_shortcut = function( shortcut, action_name){295 if( typeof(action_name) !== 'string'){throw new Error('action is not a string', action_name);}296 if( typeof(shortcut) === 'string'){297 shortcut = shortcut.split(',');298 }299 return this._set_leaf(shortcut, action_name, this._shortcuts);300 };301 ShortcutManager.prototype._is_leaf = function(shortcut_array, tree){302 if(shortcut_array.length === 1){303 return(typeof(tree[shortcut_array[0]]) === 'string');304 } else {305 var subtree = tree[shortcut_array[0]];306 return this._is_leaf(shortcut_array.slice(1), subtree );307 }308 };309 ShortcutManager.prototype._remove_leaf = function(shortcut_array, tree, allow_node){310 if(shortcut_array.length === 1){311 var current_node = tree[shortcut_array[0]];312 if(typeof(current_node) === 'string'){313 delete tree[shortcut_array[0]];314 } else {315 throw new Error('try to delete non-leaf');316 }317 } else {318 this._remove_leaf(shortcut_array.slice(1), tree[shortcut_array[0]], allow_node);319 if(_.keys(tree[shortcut_array[0]]).length === 0){320 delete tree[shortcut_array[0]];321 }322 }323 };324 ShortcutManager.prototype.is_available_shortcut = function(shortcut){325 var shortcut_array = shortcut.split(',');326 return this._is_available_shortcut(shortcut_array, this._shortcuts);327 };328 ShortcutManager.prototype._is_available_shortcut = function(shortcut_array, tree){329 var current_node = tree[shortcut_array[0]];330 if(!shortcut_array[0]){331 return false;332 }333 if(current_node === undefined){334 return true;335 } else {336 if (typeof(current_node) === 'string'){337 return false;338 } else { // assume is a sub-shortcut tree339 return this._is_available_shortcut(shortcut_array.slice(1), current_node);340 }341 }342 };343 ShortcutManager.prototype._set_leaf = function(shortcut_array, action_name, tree){344 var current_node = tree[shortcut_array[0]];345 if(shortcut_array.length === 1){346 if(current_node !== undefined && typeof(current_node) !== 'string'){347 console.warn('[warning], you are overriting a long shortcut with a shorter one');348 }349 tree[shortcut_array[0]] = action_name;350 return true;351 } else {352 if(typeof(current_node) === 'string'){353 console.warn('you are trying to set a shortcut that will be shadowed'+354 'by a more specific one. Aborting for :', action_name, 'the following '+355 'will take precedence', current_node);356 return false;357 } else {358 tree[shortcut_array[0]] = tree[shortcut_array[0]]||{};359 }360 this._set_leaf(shortcut_array.slice(1), action_name, tree[shortcut_array[0]]);361 return true;362 }363 };364 ShortcutManager.prototype._persist_shortcut = function(shortcut, data) {365 /**366 * add a shortcut to this manager and persist it to the config file. 367 **/ 368 shortcut = shortcut.toLowerCase();369 this.add_shortcut(shortcut, data);370 var patch = {keys:{}};371 patch.keys[this._mode] = {bind:{}};372 patch.keys[this._mode].bind[shortcut] = data;373 this._config.update(patch);374 };375 ShortcutManager.prototype._persist_remove_shortcut = function(shortcut){376 /**377 * Remove a shortcut from this manager and persist its removal.378 */379 shortcut = shortcut.toLowerCase();380 this.remove_shortcut(shortcut);381 var patch = {keys: {}};382 patch.keys[this._mode] = {bind:{}};383 patch.keys[this._mode].bind[shortcut] = null;384 this._config.update(patch);385 // if the shortcut we unbind is a default one, we add it to the list of386 // things to unbind at startup387 if( this._defaults_bindings.indexOf(shortcut) !== -1 ){388 var cnf = (this._config.data.keys || {})[this._mode];389 var unbind_array = cnf.unbind || [];390 // unless it's already there (like if we have remapped a default391 // shortcut to another command): unbind it)392 if(unbind_array.indexOf(shortcut) === -1){393 var _parray = unbind_array.concat(shortcut);394 var unbind_patch = {keys:{}};395 unbind_patch.keys[this._mode] = {unbind:_parray};396 console.warn('up:', unbind_patch);397 this._config.update(unbind_patch);398 }399 }400 };401 ShortcutManager.prototype.add_shortcut = function (shortcut, data, suppress_help_update) {402 /**403 * Add an action to be handled by shortcut manager. 404 * 405 * - `shortcut` should be a `Shortcut Sequence` of the for `Ctrl-Alt-C,Meta-X`...406 * - `data` could be an `action name`, an `action` or a `function`.407 * if a `function` is passed it will be converted to an anonymous `action`. 408 *409 **/410 var action_name = this.actions.get_name(data);411 if (! action_name){412 if (typeof data === 'string') {413 // If we have an action name, allow it to be bound anyway.414 console.log("Unknown action '" + data + "' for shortcut " + shortcut415 + "; it may be defined by an extension which is not yet loaded.");416 action_name = data;417 } else {418 throw new Error('does not know how to deal with : ' + data);419 }420 }421 var _shortcut = normalize_shortcut(shortcut);422 this.set_shortcut(_shortcut, action_name);423 if (!suppress_help_update) {424 // update the keyboard shortcuts notebook help425 this.events.trigger('rebuild.QuickHelp');426 }427 };428 ShortcutManager.prototype.add_shortcuts = function (data) {429 /**430 * Convenient methods to call `add_shortcut(key, value)` on several items431 * 432 * data : Dict of the form {key:value, ...}433 **/434 var that = this;435 _.forEach(data, function(value, key) {436 that.add_shortcut(key, value, true);437 });438 // update the keyboard shortcuts notebook help439 this.events.trigger('rebuild.QuickHelp');440 };441 ShortcutManager.prototype._add_default_shortcuts = function (data) {442 /**443 * same as add_shortcuts, but register them as "default" that if persistently unbound, with444 * persist_remove_shortcut, need to be on the "unbind" list. 445 **/446 this._defaults_bindings = this._defaults_bindings.concat(Object.keys(data));447 this.add_shortcuts(data);448 };449 ShortcutManager.prototype.remove_shortcut = function (shortcut, suppress_help_update) {450 /**451 * Remove the binding of shortcut `shortcut` with its action.452 * throw an error if trying to remove a non-exiting shortcut453 **/454 if(!shortcut){455 console.warn('trying to remove empty shortcut');456 return;457 }458 shortcut = normalize_shortcut(shortcut);459 if( typeof(shortcut) === 'string'){460 shortcut = shortcut.split(',');461 }462 /*463 * The shortcut error should be explicit here, because it will be464 * seen by users.465 */466 try {467 this._remove_leaf(shortcut, this._shortcuts);468 if (!suppress_help_update) {469 // update the keyboard shortcuts notebook help470 this.events.trigger('rebuild.QuickHelp');471 }472 } catch (ex) {473 throw new Error('trying to remove a non-existent shortcut', shortcut, typeof shortcut);474 }475 };476 ShortcutManager.prototype.call_handler = function (event) {477 /**478 * Call the corresponding shortcut handler for a keyboard event479 * @method call_handler480 * @return {Boolean} `true|false`, `false` if no handler was found, otherwise the value return by the handler. 481 * @param event {event}482 *483 * given an event, call the corresponding shortcut. 484 * return false is event wan handled, true otherwise 485 * in any case returning false stop event propagation486 **/487 this.clearsoon();488 if(only_modifier_event(event)){489 return true;490 }491 var shortcut = event_to_shortcut(event);492 this._queue.push(shortcut);493 var action_name = this.get_shortcut(this._queue);494 if (typeof(action_name) === 'undefined'|| action_name === null){495 this.clearqueue();496 return true;497 }498 499 if (this.actions.exists(action_name)) {500 event.preventDefault();501 this.clearqueue();502 return this.actions.call(action_name, event);503 }504 return false;505 };506 ShortcutManager.prototype.handles = function (event) {507 var shortcut = event_to_shortcut(event);508 var action_name = this.get_shortcut(this._queue.concat(shortcut));509 return (typeof(action_name) !== 'undefined');510 };511 return {512 keycodes : keycodes,513 inv_keycodes : inv_keycodes,514 ShortcutManager : ShortcutManager,515 normalize_key : normalize_key,516 normalize_shortcut : normalize_shortcut,517 shortcut_to_event : shortcut_to_event,518 event_to_shortcut : event_to_shortcut,519 };...

Full Screen

Full Screen

Shortcuts.js

Source:Shortcuts.js Github

copy

Full Screen

1/**2 * Shortcuts.js3 *4 * Released under LGPL License.5 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved6 *7 * License: http://www.tinymce.com/license8 * Contributing: http://www.tinymce.com/contributing9 */10/**11 * Contains all logic for handling of keyboard shortcuts.12 *13 * @class tinymce.Shortcuts14 * @example15 * editor.shortcuts.add('ctrl+a', function() {});16 * editor.shortcuts.add('meta+a', function() {}); // "meta" maps to Command on Mac and Ctrl on PC17 * editor.shortcuts.add('ctrl+alt+a', function() {});18 * editor.shortcuts.add('access+a', function() {}); // "access" maps to ctrl+alt on Mac and shift+alt on PC19 */20define("tinymce/Shortcuts", [21 "tinymce/util/Tools",22 "tinymce/Env"23], function(Tools, Env) {24 var each = Tools.each, explode = Tools.explode;25 var keyCodeLookup = {26 "f9": 120,27 "f10": 121,28 "f11": 12229 };30 var modifierNames = Tools.makeMap('alt,ctrl,shift,meta,access');31 return function(editor) {32 var self = this, shortcuts = {}, pendingPatterns = [];33 function parseShortcut(pattern) {34 var id, key, shortcut = {};35 // Parse modifiers and keys ctrl+alt+b for example36 each(explode(pattern, '+'), function(value) {37 if (value in modifierNames) {38 shortcut[value] = true;39 } else {40 // Allow numeric keycodes like ctrl+219 for ctrl+[41 if (/^[0-9]{2,}$/.test(value)) {42 shortcut.keyCode = parseInt(value, 10);43 } else {44 shortcut.charCode = value.charCodeAt(0);45 shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0);46 }47 }48 });49 // Generate unique id for modifier combination and set default state for unused modifiers50 id = [shortcut.keyCode];51 for (key in modifierNames) {52 if (shortcut[key]) {53 id.push(key);54 } else {55 shortcut[key] = false;56 }57 }58 shortcut.id = id.join(',');59 // Handle special access modifier differently depending on Mac/Win60 if (shortcut.access) {61 shortcut.alt = true;62 if (Env.mac) {63 shortcut.ctrl = true;64 } else {65 shortcut.shift = true;66 }67 }68 // Handle special meta modifier differently depending on Mac/Win69 if (shortcut.meta) {70 if (Env.mac) {71 shortcut.meta = true;72 } else {73 shortcut.ctrl = true;74 shortcut.meta = false;75 }76 }77 return shortcut;78 }79 function createShortcut(pattern, desc, cmdFunc, scope) {80 var shortcuts;81 shortcuts = Tools.map(explode(pattern, '>'), parseShortcut);82 shortcuts[shortcuts.length - 1] = Tools.extend(shortcuts[shortcuts.length - 1], {83 func: cmdFunc,84 scope: scope || editor85 });86 return Tools.extend(shortcuts[0], {87 desc: editor.translate(desc),88 subpatterns: shortcuts.slice(1)89 });90 }91 function hasModifier(e) {92 return e.altKey || e.ctrlKey || e.metaKey;93 }94 function isFunctionKey(e) {95 return e.type === "keydown" && e.keyCode >= 112 && e.keyCode <= 123;96 }97 function matchShortcut(e, shortcut) {98 if (!shortcut) {99 return false;100 }101 if (shortcut.ctrl != e.ctrlKey || shortcut.meta != e.metaKey) {102 return false;103 }104 if (shortcut.alt != e.altKey || shortcut.shift != e.shiftKey) {105 return false;106 }107 if (e.keyCode == shortcut.keyCode || (e.charCode && e.charCode == shortcut.charCode)) {108 e.preventDefault();109 return true;110 }111 return false;112 }113 function executeShortcutAction(shortcut) {114 return shortcut.func ? shortcut.func.call(shortcut.scope) : null;115 }116 editor.on('keyup keypress keydown', function(e) {117 if ((hasModifier(e) || isFunctionKey(e)) && !e.isDefaultPrevented()) {118 each(shortcuts, function(shortcut) {119 if (matchShortcut(e, shortcut)) {120 pendingPatterns = shortcut.subpatterns.slice(0);121 if (e.type == "keydown") {122 executeShortcutAction(shortcut);123 }124 return true;125 }126 });127 if (matchShortcut(e, pendingPatterns[0])) {128 if (pendingPatterns.length === 1) {129 if (e.type == "keydown") {130 executeShortcutAction(pendingPatterns[0]);131 }132 }133 pendingPatterns.shift();134 }135 }136 });137 /**138 * Adds a keyboard shortcut for some command or function.139 *140 * @method add141 * @param {String} pattern Shortcut pattern. Like for example: ctrl+alt+o.142 * @param {String} desc Text description for the command.143 * @param {String/Function} cmdFunc Command name string or function to execute when the key is pressed.144 * @param {Object} scope Optional scope to execute the function in.145 * @return {Boolean} true/false state if the shortcut was added or not.146 */147 self.add = function(pattern, desc, cmdFunc, scope) {148 var cmd;149 cmd = cmdFunc;150 if (typeof cmdFunc === 'string') {151 cmdFunc = function() {152 editor.execCommand(cmd, false, null);153 };154 } else if (Tools.isArray(cmd)) {155 cmdFunc = function() {156 editor.execCommand(cmd[0], cmd[1], cmd[2]);157 };158 }159 each(explode(Tools.trim(pattern.toLowerCase())), function(pattern) {160 var shortcut = createShortcut(pattern, desc, cmdFunc, scope);161 shortcuts[shortcut.id] = shortcut;162 });163 return true;164 };165 /**166 * Remove a keyboard shortcut by pattern.167 *168 * @method remove169 * @param {String} pattern Shortcut pattern. Like for example: ctrl+alt+o.170 * @return {Boolean} true/false state if the shortcut was removed or not.171 */172 self.remove = function(pattern) {173 var shortcut = createShortcut(pattern);174 if (shortcuts[shortcut.id]) {175 delete shortcuts[shortcut.id];176 return true;177 }178 return false;179 };180 };...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3import { withRootDecorator } from 'storybook-root-decorator';4import MyComponent from './MyComponent';5storiesOf('MyComponent', module)6 .addDecorator(withRootDecorator({ style: { background: 'red' } }))7 .add('default', () => <MyComponent />);8import React from 'react';9import { storiesOf } from '@storybook/react';10import { withRootDecorator } from 'storybook-root-decorator';11import MyComponent from './MyComponent';12const decorator = withRootDecorator({ style: { background: 'red' } });13storiesOf('MyComponent', module)14 .addDecorator(decorator)15 .add('default', () => <MyComponent />);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { storiesOf } from '@storybook/react';2import { withInfo } from '@storybook/addon-info';3import { withKnobs, text, boolean, number } from '@storybook/addon-knobs/react';4import Button from './Button';5storiesOf('Button', module)6 .addDecorator(withInfo)7 .addDecorator(withKnobs)8 .add(9 () => (10 disabled={boolean('Disabled', false)}11 type={text('Type', 'primary')}12 size={number('Size', 1)}13 { info: 'A very simple component' }14 );15## `withInfo(options)`

Full Screen

Using AI Code Generation

copy

Full Screen

1import initStoryshots from "@storybook/addon-storyshots";2initStoryshots();3import { configure } from "@storybook/react";4const req = require.context("../src", true, /.stories.js$/);5function loadStories() {6 req.keys().forEach(filename => req(filename));7}8configure(loadStories, module);9import React from "react";10import { storiesOf } from "@storybook/react";11import { action } from "@storybook/addon-actions";12import { Button } from "../src";13storiesOf("Button", module)14 .add("with text", () => (15 <Button onClick={action("clicked")}>Hello Button</Button>16 .add("with some emoji", () => (17 <Button onClick={action("clicked")}>18 ));19{20 "scripts": {21 }22}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { withRoot } from 'storybook-root';2export default {3};4import { withRoot } from 'storybook-root';5export default {6};7export const MyComponent = () => <div>My Component</div>;8import { withRoot } from 'storybook-root';9export default {10};11export const MyComponent = () => <div>My Component</div>;12MyComponent.story = {13 parameters: {14 root: {15 style: {16 },17 },18 },19};20### withRoot(options)21import { withRoot } from 'storybook-root';22export default {23 withRoot({24 style: {25 },26 }),27};28### withRoot(options)29import { withRoot } from 'storybook-root';30export default {31};32export const MyComponent = () => <div>My Component</div>;33MyComponent.story = {34 parameters: {35 root: {36 style: {37 },38 },39 },40};41import React from 'react';42import { withRoot } from 'storybook-root';43export default {44 withRoot({45 style: {46 },47 }),48};49export const MyComponent = () => <div>My Component</div>;50[MIT](LICENSE)

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 storybook-root 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