How to use jsCode method in Cypress

Best JavaScript code snippet using cypress

keyDefinitions.js

Source:keyDefinitions.js Github

copy

Full Screen

1/* eslint-disable import/no-cycle */2import {3  forwardLayers,4  otherLayers,5  dualFunctionLabel,6  shortcutsLabel7} from "./macroParams";89export const aliases = {10  KC_LCTL: "KC_LCTRL",11  KC_SLCK: "KC_SCROLLLOCK",12  ALGR_T: "RALT_T"13};1415export const keyCategories = {16  autoshift: "Auto shift",17  digit: "Digits",18  letters: "Letters",19  dualFunction: "Dual-function keys",20  fn: "Fn keys",21  layer: "Layer switch",22  layerShortcuts: "Layer Shortcuts",23  media: "Media",24  modifier: "Modifiers",25  momentary: "Momentary layer switch",26  mouse: "Mouse control",27  nav: "Navigational",28  nordic: "Nordic",29  numpad: "Numpad",30  other: "Other",31  punct: "Punctuation",32  shiftedPunct: "Shifted punctuation",33  shine: "EZ Shine control",34  shortcuts: "Shortcuts",35  spacing: "Spacing",36  special: "Special Chars",37  system: "System control",38  toggle: "Toggle layer"39};4041/* eslint-disable no-use-before-define */42export const keyCodes = {43  /** Alphanumeric **/44  KC_0: { label: "0", jsCode: "Digit0", category: "digit" },45  KC_1: { label: "1", jsCode: "Digit1", category: "digit" },46  KC_2: { label: "2", jsCode: "Digit2", category: "digit" },47  KC_3: { label: "3", jsCode: "Digit3", category: "digit" },48  KC_4: { label: "4", jsCode: "Digit4", category: "digit" },49  KC_5: { label: "5", jsCode: "Digit5", category: "digit" },50  KC_6: { label: "6", jsCode: "Digit6", category: "digit" },51  KC_7: { label: "7", jsCode: "Digit7", category: "digit" },52  KC_8: { label: "8", jsCode: "Digit8", category: "digit" },53  KC_9: { label: "9", jsCode: "Digit9", category: "digit" },54  KC_A: { label: "A", jsCode: "KeyA", category: "letters" },55  KC_B: { label: "B", jsCode: "KeyB", category: "letters" },56  KC_C: { label: "C", jsCode: "KeyC", category: "letters" },57  KC_D: { label: "D", jsCode: "KeyD", category: "letters" },58  KC_E: { label: "E", jsCode: "KeyE", category: "letters" },59  KC_F: { label: "F", jsCode: "KeyF", category: "letters" },60  KC_G: { label: "G", jsCode: "KeyG", category: "letters" },61  KC_H: { label: "H", jsCode: "KeyH", category: "letters" },62  KC_I: { label: "I", jsCode: "KeyI", category: "letters" },63  KC_J: { label: "J", jsCode: "KeyJ", category: "letters" },64  KC_K: { label: "K", jsCode: "KeyK", category: "letters" },65  KC_L: { label: "L", jsCode: "KeyL", category: "letters" },66  KC_M: { label: "M", jsCode: "KeyM", category: "letters" },67  KC_N: { label: "N", jsCode: "KeyN", category: "letters" },68  KC_O: { label: "O", jsCode: "KeyO", category: "letters" },69  KC_P: { label: "P", jsCode: "KeyP", category: "letters" },70  KC_Q: { label: "Q", jsCode: "KeyQ", category: "letters" },71  KC_R: { label: "R", jsCode: "KeyR", category: "letters" },72  KC_S: { label: "S", jsCode: "KeyS", category: "letters" },73  KC_T: { label: "T", jsCode: "KeyT", category: "letters" },74  KC_U: { label: "U", jsCode: "KeyU", category: "letters" },75  KC_V: { label: "V", jsCode: "KeyV", category: "letters" },76  KC_W: { label: "W", jsCode: "KeyW", category: "letters" },77  KC_X: { label: "X", jsCode: "KeyX", category: "letters" },78  KC_Y: { label: "Y", jsCode: "KeyY", category: "letters" },79  KC_Z: { label: "Z", jsCode: "KeyZ", category: "letters" },80  /** AuthoShift **/81  KC_ASDN: {82    label: "Autoshift timeout down",83    description: "Lower the Auto Shift timeout variable (down)",84    category: "autoshift"85  },86  KC_ASUP: {87    label: "Autoshift timeout up",88    description: "Raise the Auto Shift timeout variable (up)",89    category: "autoshift"90  },91  KC_ASRP: {92    label: "Autoshift report",93    description: "Report your current Auto Shift timeout value",94    category: "autoshift"95  },96  KC_ASON: {97    label: "Autoshift on",98    description: "Turns on the Auto Shift Function",99    category: "autoshift"100  },101  KC_ASOFF: {102    label: "Autoshift off",103    description: "Turns off the Auto Shift Function",104    category: "autoshift"105  },106  KC_ASTG: {107    label: "Autoshift toggle",108    description: "Toggles the state of the Auto Shift feature",109    category: "autoshift"110  },111  ALL_T: {112    command: "KC_NO",113    label: dualFunctionLabel,114    menuLabel: "Hyper",115    params: { command: true },116    category: "dualFunction",117    description: "Holding acts as Hyper (Alt+Shift+Ctrl+Cmd)"118  },119  MEH_T: {120    command: "KC_NO",121    label: dualFunctionLabel,122    params: { command: true },123    menuLabel: "Meh",124    category: "dualFunction",125    description: "Holding acts as Meh (Alt+Shift+Ctrl)"126  },127  SCMD_T: {128    command: "KC_NO",129    menuLabel: "SCMD",130    label: dualFunctionLabel,131    params: { command: true },132    category: "dualFunction",133    description:134      "Tapping results in the keystroke specified in <command> - holding acts as Shift + Win/Cmd"135  },136  SFT_T: {137    command: "KC_NO",138    menuLabel: "Left Shift",139    category: "dualFunction",140    label: dualFunctionLabel,141    params: { command: true },142    description:143      "Tapping results in the keystroke specified in <command> - holding acts as Left Shift"144  },145  ALT_T: {146    command: "KC_NO",147    menuLabel: "Left Alt",148    label: dualFunctionLabel,149    params: { command: true },150    category: "dualFunction",151    description:152      "Tapping results in the keystroke specified in <command> - holding acts as Left Alt"153  },154  CTL_T: {155    command: "KC_NO",156    menuLabel: "Left Ctrl",157    label: dualFunctionLabel,158    params: { command: true },159    category: "dualFunction",160    description:161      "Tapping results in the keystroke specified in <command> - holding acts as Left Control"162  },163  GUI_T: {164    command: "KC_NO",165    menuLabel: "Left Cmd/Win",166    label: dualFunctionLabel,167    params: { command: true },168    category: "dualFunction",169    description:170      "Tapping results in the keystroke specified in <command> - holding acts as Left Win/Cmd"171  },172  RSFT_T: {173    command: "KC_NO",174    menuLabel: "Right Shift",175    label: dualFunctionLabel,176    params: { command: true },177    category: "dualFunction",178    description:179      "Tapping results in the keystroke specified in <command> - holding acts as Right Shift"180  },181  RALT_T: {182    command: "KC_NO",183    menuLabel: "Right Alt",184    label: dualFunctionLabel,185    params: { command: true },186    category: "dualFunction",187    description:188      "Tapping results in the keystroke specified in <command> - holding acts as Right Alt (AltGr)"189  },190  RCTL_T: {191    command: "KC_NO",192    menuLabel: "Right Ctrl",193    label: dualFunctionLabel,194    params: { command: true },195    category: "dualFunction",196    description:197      "Tapping results in the keystroke specified in <command> - holding acts as Right Control"198  },199  RGUI_T: {200    command: "KC_NO",201    menuLabel: "Right Cmd/Win",202    label: dualFunctionLabel,203    params: { command: true },204    category: "dualFunction",205    description:206      "Tapping results in the keystroke specified in <command> - holding acts as Right Win/Cmd"207  },208  C_S_T: {209    command: "KC_NO",210    menuLabel: "Ctrl+Shift",211    label: dualFunctionLabel,212    params: { command: true },213    category: "dualFunction",214    description:215      "Tapping results in the keystroke specified in <command> - holding acts as Left Ctrl + Shift"216  },217  KC_F1: { label: "F1", jsCode: "F1", category: "fn" },218  KC_F2: { label: "F2", jsCode: "F2", category: "fn" },219  KC_F3: { label: "F3", jsCode: "F3", category: "fn" },220  KC_F4: { label: "F4", jsCode: "F4", category: "fn" },221  KC_F5: { label: "F5", jsCode: "F5", category: "fn" },222  KC_F6: { label: "F6", jsCode: "F6", category: "fn" },223  KC_F7: { label: "F7", jsCode: "F7", category: "fn" },224  KC_F8: { label: "F8", jsCode: "F8", category: "fn" },225  KC_F9: { label: "F9", jsCode: "F9", category: "fn" },226  KC_F10: { label: "F10", jsCode: "F10", category: "fn" },227  KC_F11: { label: "F11", jsCode: "F11", category: "fn" },228  KC_F12: { label: "F12", jsCode: "F12", category: "fn" },229  KC_F13: { label: "F13", jsCode: "F13", category: "fn" },230  KC_F14: {231    jsCode: "F14",232    category: "fn",233    os: {234      others: {235        label: "F14",236        menuLabel: "F14"237      },238      osx: {239        glyph: "brightness-down icon-big",240        menuLabel: "F14 (Mac)",241        description:242          "Decrease Mac screen brightness. Only works when you disconnect other keyboards."243      }244    }245  },246  KC_F15: {247    jsCode: "F15",248    category: "fn",249    os: {250      others: {251        label: "F15",252        menuLabel: "F15"253      },254      osx: {255        glyph: "brightness-up icon-big",256        menuLabel: "F15 (Mac)",257        description:258          "Increase Mac screen brightness. Only works when you disconnect other keyboards."259      }260    }261  },262  KC_F16: { label: "F16", jsCode: "F16", category: "fn" },263  KC_F17: { label: "F17", jsCode: "F17", category: "fn" },264  KC_F18: { label: "F18", jsCode: "F18", category: "fn" },265  KC_F19: { label: "F19", jsCode: "F19", category: "fn" },266  KC_F20: { label: "F20", jsCode: "F20", category: "fn" },267  KC_F21: { label: "F21", jsCode: "F21", category: "fn" },268  KC_F22: { label: "F22", jsCode: "F22", category: "fn" },269  KC_F23: { label: "F23", jsCode: "F23", category: "fn" },270  KC_F24: { label: "F24", jsCode: "F24", category: "fn" },271  TG: {272    label: ({ layer }) => `❐ ${layer}`,273    menuLabel: "TG",274    params: { layer: forwardLayers },275    precedingKey: true,276    category: "layer",277    description:278      "Toggle layer: Switch to a given layer. Tap this key again to return to the current layer."279  },280  MO: {281    label: ({ layer }) => `⟲ ${layer}`,282    menuLabel: "MO",283    params: { layer: forwardLayers },284    precedingKey: true,285    category: "layer",286    description:287      "Momentary layer toggle: Activates the selected layer, but only as long as you keep this key pressed."288  },289  OSL: {290    label: ({ layer }) => `OSL ${layer}`,291    menuLabel: "OSL",292    params: { layer: forwardLayers },293    precedingKey: true,294    category: "layer",295    description:296      "One-shot layer: Flips a layer on, but only for one keypress. Once you press a key in the new layer, the layer is then deactivated. You can keep the layer active by holding the key down."297  },298  TO: {299    label: ({ layer }) => `TO ${layer}`,300    menuLabel: "TO",301    params: { layer: otherLayers },302    category: "layer",303    description:304      "Direct switch to a layer. Works for switching to lower layers as well."305  },306  TT: {307    label: ({ layer }) => `TT ${layer}`,308    menuLabel: "TT",309    params: { layer: forwardLayers },310    category: "layer",311    description:312      "Layer Tap-Toggle. If you hold the key down, the layer becomes active, and then deactivates when you let go. And if you tap it, the layer simply becomes active (toggles on)."313  },314  LT: {315    command: "KC_NO",316    label: ({ code, layer, command, os }) => {317      const firstLabel = dualFunctionLabel({ code, command, os })[0];318      return [firstLabel, `LT → ${layer}`];319    },320    params: { layer: forwardLayers, command: true },321    menuLabel: "LT",322    precedingKey: true,323    category: "layerShortcuts",324    description:325      "Momentary Layer Toggle: Switch to the selected layer when held, send the selected key when tapped"326  },327  KC_AUDIO_MUTE: {328    label: "Mute",329    glyph: "volume-off",330    jsCode: "AudioVolumeMute",331    category: "media"332  },333  KC_AUDIO_VOL_UP: {334    label: "Volume up",335    glyph: "volume-up",336    jsCode: "AudioVolumeUp",337    category: "media"338  },339  KC_AUDIO_VOL_DOWN: {340    label: "Volume down",341    glyph: "volume-down",342    jsCode: "AudioVolumeDown",343    category: "media"344  },345  KC_MEDIA_NEXT_TRACK: {346    label: "Next",347    glyph: "step-forward",348    jsCode: "MediaTrackNext",349    category: "media"350  },351  KC_MEDIA_PREV_TRACK: {352    label: "Prev",353    glyph: "step-backward",354    jsCode: "MediaTrackPrevious",355    category: "media"356  },357  KC_MEDIA_STOP: {358    label: "Stop",359    glyph: "stop",360    jsCode: "MediaStop",361    category: "media"362  },363  KC_MEDIA_PLAY_PAUSE: {364    label: "Play",365    glyph: "play",366    jsCode: "MediaPlayPause",367    category: "media"368  },369  KC_MEDIA_EJECT: { label: "Eject", jsCode: "Eject", category: "media" },370  KC_MAIL: { label: "Mail", jsCode: "LaunchMail", category: "media" },371  KC_CALCULATOR: { label: "Calc", jsCode: "LaunchApp2", category: "media" },372  KC_MY_COMPUTER: {373    label: "File manager",374    jsCode: "LaunchApp1",375    category: "media"376  },377  KC_WWW_SEARCH: {378    label: "Search",379    jsCode: "BrowserSearch",380    category: "media"381  },382  KC_WWW_HOME: { label: "WWW Home", jsCode: "BrowserHome", category: "media" },383  KC_WWW_BACK: {384    label: "WWW Back",385    jsCode: "BrowserBack",386    category: "media"387  },388  KC_WWW_FORWARD: {389    label: "WWW Fwd",390    jsCode: "BrowserForward",391    category: "media"392  },393  KC_WWW_REFRESH: {394    label: "Refresh",395    jsCode: "BrowserRefresh",396    category: "media"397  },398  KC_WWW_FAVORITES: {399    label: "Favorites",400    jsCode: "BrowserFavorites",401    category: "media"402  },403  KC_MEDIA_FAST_FORWARD: {404    label: "Fast forward",405    category: "media"406  },407  KC_MEDIA_REWIND: { label: "Rewind", category: "media" },408  KC_LSHIFT: {409    label: "Left Shift",410    jsCode: "ShiftLeft",411    category: "modifier"412  },413  KC_RSHIFT: {414    label: "Right Shift",415    jsCode: "ShiftRight",416    category: "modifier"417  },418  KC_LCTRL: { label: "Left Ctrl", jsCode: "ControlLeft", category: "modifier" },419  KC_RCTRL: {420    label: "Right Ctrl",421    jsCode: "ControlRight",422    category: "modifier"423  },424  KC_LALT: {425    jsCode: "AltLeft",426    category: "modifier",427    os: {428      others: {429        label: "Left Alt",430        menuLabel: "Left Alt"431      },432      osx: {433        glyph: "alt icon-small",434        menuLabel: "Left Option (Mac)"435      }436    }437  },438  KC_RALT: {439    jsCode: "AltRight",440    category: "modifier",441    description: "Also known as AltGr.",442    os: {443      others: {444        label: "Right Alt",445        menuLabel: "Right Alt"446      },447      osx: {448        glyph: "alt icon-small",449        menuLabel: "Right Option (Mac)"450      }451    }452  },453  KC_LGUI: {454    category: "modifier",455    jsCode: "MetaLeft",456    os: {457      osx: {458        label: "⌘",459        glyph: "command",460        menuLabel: "Left Command (Mac)"461      },462      win: {463        label: "win",464        glyph: "windows",465        menuLabel: "Left Win"466      },467      linux: {468        label: "tux",469        glyph: "linux zoomed",470        menuLabel: "Left Meta (Linux)"471      }472    }473  },474  KC_RGUI: {475    category: "modifier",476    jsCode: "MetaRight",477    os: {478      osx: {479        label: "⌘",480        glyph: "command",481        menuLabel: "Right Command (Mac)"482      },483      win: {484        label: "win",485        glyph: "windows",486        menuLabel: "Right Win"487      },488      linux: {489        label: "tux",490        glyph: "linux zoomed",491        menuLabel: "Right Meta (Linux)"492      }493    }494  },495  OSM: {496    command: "MOD_LCTL",497    category: "modifier",498    params: { modifier: true },499    label: dualFunctionLabel,500    menuLabel: "OSM",501    modifiable: false,502    description:503      "One-shot modifier: Turns a modifier on, but only for one keypress. Once you press a key in the modifier is then deactivated. You can keep the modifier active by holding the key down."504  },505  MOD_LSFT: {506    label: "Left Shift",507    menuLabel: "Shift",508    jsCode: "ShiftLeft",509    category: "modifier",510    description: "Shift",511    modifierCommand: true512  },513  MOD_RSFT: {514    label: "Right Shift",515    jsCode: "ShiftRight",516    modifierCommand: true,517    category: "modifier"518  },519  MOD_LCTL: {520    label: "Left Ctrl",521    jsCode: "ControlLeft",522    modifierCommand: true,523    category: "modifier"524  },525  MOD_RCTL: {526    label: "Right Ctrl",527    jsCode: "ControlRight",528    modifierCommand: true,529    category: "modifier"530  },531  MOD_LALT: {532    jsCode: "AltLeft",533    category: "modifier",534    modifierCommand: true,535    description: "Alt",536    os: {537      others: {538        label: "Alt",539        menuLabel: "Alt"540      },541      osx: {542        glyph: "alt icon-small",543        menuLabel: "Left Option (Mac)"544      }545    }546  },547  MOD_RALT: {548    jsCode: "AltRight",549    category: "modifier",550    modifierCommand: true,551    description: "Right Alt, also known as AltGr.",552    os: {553      others: {554        label: "AltGr",555        menuLabel: "AltGr"556      },557      osx: {558        glyph: "alt icon-small",559        menuLabel: "Right Option (Mac)"560      }561    }562  },563  MOD_LGUI: {564    category: "modifier",565    jsCode: "MetaLeft",566    modifierCommand: true,567    os: {568      osx: {569        label: "⌘",570        glyph: "command",571        menuLabel: "Left Command (Mac)"572      },573      win: {574        label: "win",575        glyph: "windows",576        menuLabel: "Left Win"577      },578      linux: {579        label: "tux",580        glyph: "linux zoomed",581        menuLabel: "Left Meta (Linux)"582      }583    }584  },585  MOD_RGUI: {586    category: "modifier",587    jsCode: "MetaRight",588    modifierCommand: true,589    os: {590      osx: {591        label: "⌘",592        glyph: "command",593        menuLabel: "Right Command (Mac)"594      },595      win: {596        label: "win",597        glyph: "windows",598        menuLabel: "Right Win"599      },600      linux: {601        label: "tux",602        glyph: "linux zoomed",603        menuLabel: "Right Meta (Linux)"604      }605    }606  },607  KC_MS_UP: {608    label: "Move up",609    glyph: "mouse-up bolded zoomed",610    category: "mouse"611  },612  KC_MS_DOWN: {613    label: "Move down",614    glyph: "mouse-down bolded zoomed",615    category: "mouse"616  },617  KC_MS_LEFT: {618    label: "Move left",619    glyph: "mouse-left bolded zoomed",620    category: "mouse"621  },622  KC_MS_RIGHT: {623    label: "Move right",624    glyph: "mouse-right bolded zoomed",625    category: "mouse"626  },627  KC_MS_BTN1: {628    label: "Left click",629    glyph: "left-click bolded zoomed",630    category: "mouse"631  },632  KC_MS_BTN2: {633    label: "Right click",634    glyph: "right-click bolded zoomed",635    category: "mouse"636  },637  KC_MS_BTN3: {638    label: "Middle click",639    glyph: "middle-click bolded zoomed",640    category: "mouse"641  },642  KC_MS_BTN4: { label: "Button 4", category: "mouse" },643  KC_MS_BTN5: { label: "Button 5", category: "mouse" },644  KC_MS_WH_UP: { label: "Wheel Up", category: "mouse" },645  KC_MS_WH_DOWN: { label: "Wheel Down", category: "mouse" },646  KC_MS_WH_LEFT: { label: "Wheel Left", category: "mouse" },647  KC_MS_WH_RIGHT: { label: "Wheel Right", category: "mouse" },648  KC_MS_ACCEL0: { label: "Acceleration 0", category: "mouse" },649  KC_MS_ACCEL1: { label: "Acceleration 1", category: "mouse" },650  KC_MS_ACCEL2: { label: "Acceleration 2", category: "mouse" },651  KC_TRANSPARENT: {652    label: "",653    menuLabel: false,654    jsCode: -1,655    category: "other"656  },657  KC_BSPACE: {658    label: "⌫",659    menuLabel: "Backspace",660    jsCode: "Backspace",661    category: "spacing"662  },663  KC_TAB: { label: "Tab", jsCode: "Tab", category: "spacing" },664  KC_ENTER: {665    label: "⏎",666    menuLabel: "Enter",667    jsCode: "Enter",668    category: "spacing"669  },670  LALT: {671    label: shortcutsLabel,672    command: "KC_NO",673    menuLabel: "Alt",674    params: { command: true },675    category: "shortcuts",676    description: "Alt"677  },678  KC_PAUSE: { label: "Pause", jsCode: "Pause", category: "other" },679  KC_ESCAPE: { label: "Esc", jsCode: "Escape", category: "spacing" },680  KC_SPACE: {681    label: "⎵",682    menuLabel: "Space",683    jsCode: "Space",684    category: "spacing",685    description: "Spacebar"686  },687  KC_PGUP: {688    label: "PgUp",689    menuLabel: "Page Up",690    jsCode: "PageUp",691    category: "nav"692  },693  KC_APPLICATION: {694    label: "Application",695    glyph: "list-alt zoomed",696    jsCode: "ContextMenu",697    category: "nav"698  },699  KC_PGDOWN: {700    label: "PgDn",701    menuLabel: "Page Down",702    jsCode: "PageDown",703    category: "nav"704  },705  KC_END: { label: "End", jsCode: "End", category: "nav" },706  KC_HOME: { label: "Home", jsCode: "Home", category: "nav" },707  KC_LEFT: {708    label: "◀",709    menuLabel: "Left arrow",710    jsCode: "ArrowLeft",711    category: "nav"712  },713  KC_UP: {714    label: "▲",715    menuLabel: "Up arrow",716    jsCode: "ArrowUp",717    category: "nav"718  },719  KC_RIGHT: {720    label: "▶",721    menuLabel: "Right arrow",722    jsCode: "ArrowRight",723    category: "nav"724  },725  KC_DOWN: {726    label: "▼",727    menuLabel: "Down arrow",728    jsCode: "ArrowDown",729    category: "nav"730  },731  KC_PSCREEN: {732    label: "SysRq",733    jsCode: "PrintScreen",734    category: "nav",735    description:736      "Also known as Print Screen. Alt+SysRq would give you the Linux Magic SysRq combo on one key."737  },738  KC_INSERT: {739    label: "Ins",740    jsCode: "Insert",741    category: "nav",742    menuLabel: "Insert"743  },744  KC_DELETE: {745    label: "Del",746    jsCode: "Delete",747    category: "nav",748    menuLabel: "Delete"749  },750  KC_SCROLLLOCK: { label: "Scroll lock", jsCode: "ScollLock", category: "nav" },751  KC_KP_0: { label: "0", jsCode: "Numpad0", category: "numpad" },752  KC_KP_1: { label: "1", jsCode: "Numpad1", category: "numpad" },753  KC_KP_2: { label: "2", jsCode: "Numpad2", category: "numpad" },754  KC_KP_3: { label: "3", jsCode: "Numpad3", category: "numpad" },755  KC_KP_4: { label: "4", jsCode: "Numpad4", category: "numpad" },756  KC_KP_5: { label: "5", jsCode: "Numpad5", category: "numpad" },757  KC_KP_6: { label: "6", jsCode: "Numpad6", category: "numpad" },758  KC_KP_7: { label: "7", jsCode: "Numpad7", category: "numpad" },759  KC_KP_8: { label: "8", jsCode: "Numpad8", category: "numpad" },760  KC_KP_9: { label: "9", jsCode: "Numpad9", category: "numpad" },761  KC_KP_ENTER: { label: "Enter", jsCode: "NumpadEnter", category: "numpad" },762  KC_KP_ASTERISK: {763    label: "*",764    jsCode: "NumpadMultiply",765    category: "numpad",766    description: "Asterisk/Star"767  },768  KC_KP_PLUS: {769    label: "+",770    jsCode: "NumpadAdd",771    category: "numpad",772    description: "Plus"773  },774  KC_KP_MINUS: {775    label: "-",776    jsCode: "NumpadSubtract",777    category: "numpad",778    description: "Minus"779  },780  KC_KP_DOT: {781    label: ".",782    jsCode: "NumpadDecimal",783    category: "numpad",784    description: "Numpad dot"785  },786  KC_KP_COMMA: { label: ",", jsCode: "NumpadComma", category: "numpad" },787  KC_KP_SLASH: { label: "/", jsCode: "NumpadDivide", category: "numpad" },788  KC_NUMLOCK: { label: "Numlock", jsCode: "NumLock", category: "numpad" },789  KC_SCOLON: {790    label: ";",791    jsCode: "Semicolon",792    category: "punct",793    description: "Semicolon"794  },795  KC_EQUAL: {796    label: "=",797    jsCode: "Equal",798    category: "punct",799    description: "Equal sign"800  },801  KC_COMMA: {802    label: ",",803    jsCode: "Comma",804    category: "punct",805    description: "Comma"806  },807  KC_MINUS: {808    label: "-",809    jsCode: "Minus",810    category: "punct",811    description: "Minus"812  },813  KC_DOT: {814    label: ".",815    jsCode: "Period",816    category: "punct",817    description: "Dot (also known as a period or a full stop)"818  },819  KC_SLASH: { label: "/", jsCode: "Slash", category: "punct" },820  KC_GRAVE: {821    label: "`",822    jsCode: "Backquote",823    category: "punct",824    description: "Backtick (grave accent)"825  },826  KC_NONUS_HASH: { label: "Non-US # and ~", category: "punct" },827  KC_LBRACKET: {828    label: "[",829    jsCode: "BracketLeft",830    category: "punct",831    description: "Left bracket (hold Shift for curly brace)"832  },833  KC_BSLASH: { label: "\\", jsCode: "Backslash", category: "punct" },834  KC_RBRACKET: {835    label: "]",836    jsCode: "BracketRight",837    category: "punct",838    description: "Right bracket (hold Shift for curly brace)"839  },840  KC_QUOTE: {841    label: "'",842    jsCode: "Quote",843    category: "punct",844    description: "Single quote (hold Shift for double quote)"845  },846  KC_CAPSLOCK: {847    label: "Caps",848    jsCode: "Capslock",849    category: "punct",850    description: "Caps lock"851  },852  KC_NONUS_BSLASH: {853    label: "Non-US \\",854    jsCode: "IntlBackslash",855    category: "punct",856    description: "Non-US backslash and pipe"857  },858  KC_NO: { label: "None", category: "other" },859  RESET: {860    label: "Reset",861    category: "other",862    description:863      "Resets the keyboard back to the Teensy bootloader, to flash new firmware."864  },865  KC_POWER: { label: "Power", category: "other" },866  KC_UNDO: {867    label: "Undo (Mac)",868    jsCode: "Undo",869    category: "other",870    description: "For one-key Undo on Windows, use Z modified by Ctrl"871  },872  KC_CUT: {873    label: "Cut (Mac)",874    jsCode: "Cut",875    category: "other",876    description: "For one-key Cut on Windows, use X modified by Ctrl"877  },878  KC_COPY: {879    label: "Copy (Mac)",880    jsCode: "Copy",881    category: "other",882    description: "For one-key Copy on Windows, use C modified by Ctrl"883  },884  KC_PASTE: {885    label: "Paste (Mac)",886    jsCode: "Paste",887    category: "other",888    description: "For one-key Paste on Windows, use V modified by Ctrl"889  },890  KC_FIND: { label: "Find", jsCode: "Find", category: "other" },891  KC_LANG1: {892    label: "LANG 1",893    jsCode: "Lang1",894    category: "other",895    description: "Language 1 key for Asian languages"896  },897  KC_LANG2: {898    label: "LANG 2",899    jsCode: "Lang2",900    category: "other",901    description: "Language 2 key for Asian languages"902  },903  KC_LANG3: { label: "LANG 3", jsCode: "Lang3", category: "other" },904  KC_LANG4: { label: "LANG 4", jsCode: "Lang4", category: "other" },905  KC_LANG5: { label: "LANG 5", jsCode: "Lang5", category: "other" },906  KC_LANG6: { label: "LANG 6", jsCode: "Lang6", category: "other" },907  KC_LANG7: { label: "LANG 7", jsCode: "Lang7", category: "other" },908  KC_LANG8: { label: "LANG 8", jsCode: "Lang8", category: "other" },909  KC_LANG9: { label: "LANG 9", jsCode: "Lang9", category: "other" },910  KC_SYSTEM_POWER: { label: "Power", jsCode: "Power", category: "system" },911  KC_SYSTEM_SLEEP: { label: "Sleep", jsCode: "Sleep", category: "system" },912  KC_SYSTEM_WAKE: { label: "Wake", jsCode: "WakeUp", category: "system" },913  KC_LSPO: {914    label: "Shift (",915    category: "other",916    description:917      'Space Cadet Shift: When held, acts as Shift; when tapped, sends "(" (opening parentheses). Great for your left shift key.'918  },919  KC_RSPC: {920    label: "Shift )",921    category: "other",922    description:923      'Space Cadet Shift: When held, acts as Shift; when tapped, sends ")" (closing parentheses). Great for your right shift key.'924  },925  KC_EXLM: { label: "!", category: "shiftedPunct" },926  KC_AT: { label: "@", category: "shiftedPunct" },927  KC_LCBR: { label: "{", category: "shiftedPunct" },928  KC_RCBR: { label: "}", category: "shiftedPunct" },929  KC_PIPE: { label: "|", category: "shiftedPunct" },930  KC_HASH: { label: "#", category: "shiftedPunct" },931  KC_DLR: { label: "$", category: "shiftedPunct" },932  KC_LPRN: { label: "(", category: "shiftedPunct" },933  KC_RPRN: { label: ")", category: "shiftedPunct" },934  KC_PERC: { label: "%", category: "shiftedPunct" },935  KC_CIRC: { label: "^", category: "shiftedPunct" },936  KC_AMPR: { label: "&", category: "shiftedPunct" },937  KC_ASTR: { label: "*", category: "shiftedPunct" },938  KC_PLUS: {939    label: "+",940    category: "shiftedPunct",941    description: "Plus"942  },943  KC_TILD: { label: "~", category: "shiftedPunct" },944  KC_COLN: { label: ":", category: "shiftedPunct" },945  KC_UNDS: { label: "_", category: "shiftedPunct" },946  EPRM: {947    label: "EEPROM",948    category: "other",949    description:950      "Wipe the EEPROM. Should be used sparingly, for troubleshooting only."951  },952  KC_DQUO: { label: '"', category: "shiftedPunct" },953  KC_LABK: { label: "<", category: "shiftedPunct" },954  KC_RABK: { label: ">", category: "shiftedPunct" },955  KC_QUES: { label: "?", category: "shiftedPunct" },956  NO_HALF: { label: "½", category: "nordic" },957  NO_PLUS: { label: "+", category: "nordic" },958  NO_ACUT: { label: "'", category: "nordic" },959  NO_AM: { label: "å", category: "nordic" },960  NO_QUOT: { label: '"', category: "nordic" },961  NO_AE: { label: "ø", category: "nordic" },962  NO_OSLH: { label: "æ", category: "nordic" },963  NO_APOS: { label: "'", category: "nordic" },964  NO_LESS: { label: "<", category: "nordic" },965  NO_MINS: { label: "-", category: "nordic" },966  NO_QUO2: { label: "NO_QUO2", category: "nordic" },967  NO_BULT: { label: "NO_BULT", category: "nordic" },968  NO_AMPR: { label: "&", category: "nordic" },969  NO_SLSH: { label: "/", category: "nordic" },970  NO_LPRN: { label: "(", category: "nordic" },971  NO_RPRN: { label: ")", category: "nordic" },972  NO_EQL: { label: "=", category: "nordic" },973  NO_QUES: { label: "?", category: "nordic" },974  NO_GRV: { label: "`", category: "nordic" },975  NO_CIRC: { label: "^", category: "nordic" },976  NO_GRTR: { label: ">", category: "nordic" },977  NO_SCLN: { label: ";", category: "nordic" },978  NO_COLN: { label: ":", category: "nordic" },979  NO_UNDS: { label: "_", category: "nordic" },980  NO_AT: { label: "@", category: "nordic" },981  NO_PND: { label: "#", category: "nordic" },982  NO_LCBR: { label: "¶", category: "nordic" },983  NO_LBRC: { label: "[", category: "nordic" },984  NO_RBRC: { label: "]", category: "nordic" },985  NO_RCBR: { label: "≠", category: "nordic" },986  NO_PIPE: { label: "<", category: "nordic" },987  NO_EURO: { label: "€", category: "nordic" },988  NO_TILD: { label: "~", category: "nordic" },989  NO_MU: { label: "NO_MU", category: "nordic" },990  DE_Z: { label: "German Z", category: "nordic" },991  DE_Y: { label: "German Y", category: "nordic" },992  DE_SS: { label: "German ß", category: "nordic" },993  DE_AE: { label: "German Æ", category: "nordic" },994  DE_UE: { label: "German Ü", category: "nordic" },995  DE_OE: { label: "German Ö", category: "nordic" },996  DE_CIRC: {997    label: "German ^°",998    category: "nordic"999  },1000  DE_ACUT: {1001    label: "German ´`",1002    category: "nordic"1003  },1004  DE_PLUS: {1005    label: "German +*~",1006    category: "nordic"1007  },1008  DE_HASH: { label: "German #'", category: "nordic" },1009  DE_LESS: {1010    label: "German <>|",1011    category: "nordic"1012  },1013  DE_MINS: { label: "German -_", category: "nordic" },1014  DE_RING: { label: "German °", category: "nordic" },1015  DE_EXLM: { label: "German !", category: "nordic" },1016  DE_DQOT: { label: 'German "', category: "nordic" },1017  DE_PARA: { label: "German §", category: "nordic" },1018  DE_DLR: { label: "German $", category: "nordic" },1019  DE_PERC: { label: "German %", category: "nordic" },1020  DE_AMPR: { label: "German &", category: "nordic" },1021  DE_SLSH: { label: "German /", category: "nordic" },1022  DE_LPRN: { label: "German (", category: "nordic" },1023  DE_RPRN: { label: "German )", category: "nordic" },1024  DE_EQL: { label: "German =", category: "nordic" },1025  DE_QST: { label: "German ?", category: "nordic" },1026  DE_GRV: { label: "German `", category: "nordic" },1027  DE_ASTR: { label: "German *", category: "nordic" },1028  DE_QUOT: { label: "German '", category: "nordic" },1029  DE_MORE: { label: "German >", category: "nordic" },1030  DE_COLN: { label: "German :", category: "nordic" },1031  DE_SCLN: { label: "German ;", category: "nordic" },1032  DE_UNDS: { label: "German _", category: "nordic" },1033  DE_SQ2: { label: "German ²", category: "nordic" },1034  DE_SQ3: { label: "German ³", category: "nordic" },1035  DE_LCBR: { label: "German {", category: "nordic" },1036  DE_LBRC: { label: "German [", category: "nordic" },1037  DE_RBRC: { label: "German ]", category: "nordic" },1038  DE_RCBR: { label: "German }", category: "nordic" },1039  DE_BSLS: { label: "German \\", category: "nordic" },1040  DE_AT: { label: "German @", category: "nordic" },1041  DE_EURO: { label: "German €", category: "nordic" },1042  DE_TILD: { label: "German ~", category: "nordic" },1043  DE_PIPE: { label: "German |", category: "nordic" },1044  KC_INT1: { label: "Int 1", category: "other" },1045  KC_INT2: { label: "Int 2", category: "other" },1046  KC_INT3: { label: "Int 3 (yen)", category: "other" },1047  KC_INT4: { label: "Int 4", category: "other" },1048  KC_INT5: { label: "Int 5", category: "other" },1049  KC_INT6: { label: "Int 6", category: "other" },1050  KC_INT7: { label: "Int 7", category: "other" },1051  KC_INT8: { label: "Int 8", category: "other" },1052  KC_INT9: { label: "Int 9", category: "other" },1053  RGB_MOD: {1054    label: "Animate",1055    glyph: "air zoomed",1056    menuLabel: false,1057    category: "shine"1058  },1059  RGB_SLD: {1060    label: "Stop animation",1061    glyph: "pause-circle-o zoomed",1062    menuLabel: false,1063    category: "shine"1064  },1065  RGB_VAI: {1066    label: "Brightness +",1067    glyph: "brightness-up zoomed",1068    menuLabel: false,1069    category: "shine"1070  },1071  RGB_VAD: {1072    label: "Brightness -",1073    glyph: "brightness-down zoomed",1074    menuLabel: false,1075    category: "shine"1076  },1077  RGB_HUI: {1078    label: "Hue +",1079    glyph: "hui",1080    menuLabel: false,1081    category: "shine"1082  },1083  RGB_HUD: {1084    label: "Hue -",1085    glyph: "hud",1086    menuLabel: false,1087    category: "shine"1088  },1089  RGB_TOG: {1090    label: "Toggle lighting",1091    glyph: "toggle-on zoomed",1092    menuLabel: false,1093    category: "shine"1094  },1095  RGB: {1096    label: "",1097    glyph: "color-palette zoomed",1098    menuLabel: false,1099    jsCode: -1,1100    category: "shine"1101  }1102};11031104// render the list of keycode in a shape expected by react-select11051106const keyOptions = [];1107const modifierOptions = [];1108const colorKeyCodes = [];11091110function getOption(keyCode, os) {1111  const keyOption = this.filter(key => {1112    if (os && key.os) return key.value === keyCode && key.os === os;1113    return key.value === keyCode;1114  })[0];1115  return (1116    keyOption || {1117      category: null,1118      categoryName: null,1119      description: null,1120      label: null,1121      value: "KC_TRANSPARENT"1122    }1123  );1124}11251126Object.keys(keyCategories).forEach(categoryKey => {1127  const categoryName = keyCategories[categoryKey];1128  // Iterate all keyCodes and keep only those KEYCODES (string) whose category matches1129  const categoryKeys = Object.keys(keyCodes).filter(1130    keyCode => keyCodes[keyCode].category === categoryKey1131  );1132  categoryKeys.forEach(keyCode => {1133    const key = keyCodes[keyCode];1134    const {1135      label,1136      menuLabel,1137      modifierCommand,1138      description,1139      precedingKey,1140      os1141    } = key;1142    const arr = modifierCommand === true ? modifierOptions : keyOptions;1143    // Exclude option if menuLabel is explicitly false1144    // and modifier command keys1145    const optionLabel = menuLabel || label;1146    if (menuLabel !== false) {1147      if (os) {1148        Object.keys(os).forEach(val => {1149          arr.push({1150            category: categoryKey,1151            categoryName,1152            description: os[val].description || description,1153            label: os[val].menuLabel,1154            precedingKey,1155            value: keyCode,1156            os: val1157          });1158        });1159      } else {1160        arr.push({1161          category: categoryKey,1162          categoryName,1163          description,1164          label: optionLabel,1165          precedingKey,1166          value: keyCode1167        });1168      }1169    }1170    if (categoryKey === "shine" && keyCode !== "RGB") {1171      colorKeyCodes.push({ code: keyCode, ...key });1172    }1173  });1174});1175keyOptions.getOption = getOption;11761177const commandOptions = keyOptions.filter(1178  ({ category }) =>1179    ![1180      "autoshift",1181      "other",1182      "mouse",1183      "layer",1184      "dualFunction",1185      "layerShortcuts",1186      "shortcuts",1187      "shiftedPunct"1188    ].includes(category)1189);11901191commandOptions.getOption = getOption;11921193modifierOptions.getOption = getOption;11941195export const selectKeyOptions = keyOptions;1196export const selectCommandOptions = commandOptions;1197export const selectModifierOptions = modifierOptions;
...

Full Screen

Full Screen

BFInterpreter.js

Source:BFInterpreter.js Github

copy

Full Screen

1function download(text) {2    var element = document.createElement('a');3    4    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));5    element.setAttribute('download', 'bf.cpp');6  7    element.style.display = 'none';8    document.body.appendChild(element);9  10    element.click();11    document.body.removeChild(element);12}13function tabs(count) {14    retext = "";15    for (var i = 0; i < count; i++) {16        retext += "  ";17    }18    return retext;19}20function genCode(text) {21    var JSCode = "var st = Date.now(); var dt = 0; var a = new Uint8Array(0xffff).fill(0); var p = 0; var o=\"\";";22    var CCCode = "#include <iostream>\n\nint main() {\n  unsigned char a[0xffff]={0};\n  unsigned char* p=a;\n\n\n"23    var left_count  = 0;24    var right_count = 0;25    var plus_count  = 0;26    var minus_count = 0;27    var brace_count = 0;28    for (var i = 0; i < text.length; i++) {29        switch (text[i]) {30            case '>': {31                if(left_count != 0) {32                    JSCode += "p-="+left_count+";"33                    CCCode += tabs(1+brace_count)+" p -= "+left_count+";\n";34                } else if(plus_count != 0) {35                    JSCode += "a[p]+="+plus_count+";"36                    CCCode += tabs(1+brace_count)+"*p += "+plus_count+";\n";37                } else if(minus_count != 0) {38                    JSCode += "a[p]-="+minus_count+";"39                    CCCode += tabs(1+brace_count)+"*p -= "+minus_count+";\n";40                }41                right_count++; left_count = 0;42                plus_count = 0; minus_count = 0;43                break;44            }45            case '<': {46                if(right_count != 0) {47                    JSCode += "p+="+right_count+";"48                    CCCode += tabs(1+brace_count)+" p += "+right_count+";\n";49                } else if(plus_count != 0) {50                    JSCode += "a[p]+="+plus_count+";"51                    CCCode += tabs(1+brace_count)+"*p += "+plus_count+";\n";52                } else if(minus_count != 0) {53                    JSCode += "a[p]-="+minus_count+";"54                    CCCode += tabs(1+brace_count)+"*p -= "+minus_count+";\n";55                }56                right_count = 0; left_count++;57                plus_count = 0; minus_count = 0;58                break;59            }60            case '+': {61                if(right_count != 0) {62                    JSCode += "p+="+right_count+";"63                    CCCode += tabs(1+brace_count)+" p += "+right_count+";\n";64                } else if(left_count != 0) {65                    JSCode += "p-="+left_count+";"66                    CCCode += tabs(1+brace_count)+" p -= "+left_count+";\n";67                } else if(minus_count != 0) {68                    JSCode += "a[p]-="+minus_count+";"69                    CCCode += tabs(1+brace_count)+"*p -= "+minus_count+";\n";70                }71                right_count = 0; left_count = 0;72                plus_count++; minus_count = 0;73                break;74            }75            case '-': {76                if(right_count != 0) {77                    JSCode += "p+="+right_count+";"78                    CCCode += tabs(1+brace_count)+" p += "+right_count+";\n";79                } else if(left_count != 0) {80                    JSCode += "p-="+left_count+";"81                    CCCode += tabs(1+brace_count)+" p -= "+left_count+";\n";82                } else if(plus_count != 0) {83                    JSCode += "a[p]+="+plus_count+";"84                    CCCode += tabs(1+brace_count)+"*p += "+plus_count+";\n";85                }86                right_count = 0; left_count = 0;87                plus_count = 0; minus_count++;88                break;89            }90            case '[': {91                if(right_count != 0) {92                    JSCode += "p+="+right_count+";"93                    CCCode += tabs(1+brace_count)+" p += "+right_count+";\n";94                } else if(left_count != 0) {95                    JSCode += "p-="+left_count+";"96                    CCCode += tabs(1+brace_count)+" p -= "+left_count+";\n";97                } else if (plus_count != 0) {98                    JSCode += "a[p]+="+plus_count+";"99                    CCCode += tabs(1+brace_count)+"*p += "+plus_count+";\n";100                } else if(minus_count != 0) {101                    JSCode += "a[p]-="+minus_count+";"102                    CCCode += tabs(1+brace_count)+"*p -= "+minus_count+";\n";103                }104                JSCode += "while (a[p] != 0) {dt = Date.now() - st; if (dt > "+document.getElementById("timeout").value+") {o = \"Timed out!\"; break;}";105                CCCode += tabs(1+brace_count)+" while (*p) {\n";106                right_count = 0; left_count = 0;107                plus_count = 0; minus_count = 0;108                brace_count++;109                break;110            }111            case ']': {112                if(right_count != 0) {113                    JSCode += "p+="+right_count+";"114                    CCCode += tabs(1+brace_count)+" p += "+right_count+";\n";115                } else if(left_count != 0) {116                    JSCode += "p-="+left_count+";"117                    CCCode += tabs(1+brace_count)+" p -= "+left_count+";\n";118                } else if (plus_count != 0) {119                    JSCode += "a[p]+="+plus_count+";"120                    CCCode += tabs(1+brace_count)+"*p += "+plus_count+";\n";121                } else if(minus_count != 0) {122                    JSCode += "a[p]-="+minus_count+";"123                    CCCode += tabs(1+brace_count)+"*p -= "+minus_count+";\n";124                }125                JSCode += "}";126                CCCode += tabs(brace_count)+" }\n";127                right_count = 0; left_count = 0;128                plus_count = 0; minus_count = 0;129                brace_count--;130                if (brace_count < 0) {131                    return [false , CCCode];132                }133                break;134            }135            case ',': {136                if(right_count != 0) {137                    JSCode += "p+="+right_count+";"138                    CCCode += tabs(1+brace_count)+" p += "+right_count+";\n";139                } else if(left_count != 0) {140                    JSCode += "p-="+left_count+";"141                    CCCode += tabs(1+brace_count)+" p -= "+left_count+";\n";142                } else if (plus_count != 0) {143                    JSCode += "a[p]+="+plus_count+";"144                    CCCode += tabs(1+brace_count)+"*p += "+plus_count+";\n";145                } else if(minus_count != 0) {146                    JSCode += "a[p]-="+minus_count+";"147                    CCCode += tabs(1+brace_count)+"*p -= "+minus_count+";\n";148                }149                CCCode += tabs(1+brace_count)+" std::cin >> p;\n"150                right_count = 0; left_count = 0;151                plus_count = 0; minus_count = 0;152                break;153            }154            case '.': {155                if(right_count != 0) {156                    JSCode += "p+="+right_count+";"157                    CCCode += tabs(1+brace_count)+" p += "+right_count+";\n";158                } else if(left_count != 0) {159                    JSCode += "p-="+left_count+";"160                    CCCode += tabs(1+brace_count)+" p -= "+left_count+";\n";161                } else if (plus_count != 0) {162                    JSCode += "a[p]+="+plus_count+";"163                    CCCode += tabs(1+brace_count)+"*p += "+plus_count+";\n";164                } else if(minus_count != 0) {165                    JSCode += "a[p]-="+minus_count+";"166                    CCCode += tabs(1+brace_count)+"*p -= "+minus_count+";\n";167                }168                JSCode += "o += String.fromCharCode(a[p]);";169                CCCode += tabs(1+brace_count)+" std::cout << *p;\n"170                right_count = 0; left_count = 0;171                plus_count = 0; minus_count = 0;172                break;173            }174            default: {175                if(right_count != 0) {176                    JSCode += "p+="+right_count+";"177                    CCCode += tabs(1+brace_count)+" p += "+right_count+";\n";178                } else if(left_count != 0) {179                    JSCode += "p-="+left_count+";"180                    CCCode += tabs(1+brace_count)+" p -= "+left_count+";\n";181                } else if (plus_count != 0) {182                    JSCode += "a[p]+="+plus_count+";"183                    CCCode += tabs(1+brace_count)+"*p += "+plus_count+";\n";184                } else if(minus_count != 0) {185                    JSCode += "a[p]-="+minus_count+";"186                    CCCode += tabs(1+brace_count)+"*p -= "+minus_count+";\n";187                }188                right_count = 0; left_count = 0;189                plus_count = 0; minus_count = 0;190                break;191            }192        }193    }194    if(right_count != 0) {195        JSCode += "p+="+right_count+";"196        CCCode += tabs(1+brace_count)+" p += "+right_count+";\n";197    } else if(left_count != 0) {198        JSCode += "p-="+left_count+";"199        CCCode += tabs(1+brace_count)+" p -= "+left_count+";\n";200    } else if (plus_count != 0) {201        JSCode += "a[p]+="+plus_count+";"202        CCCode += tabs(1+brace_count)+"*p += "+plus_count+";\n";203    } else if(minus_count != 0) {204        JSCode += "a[p]-="+minus_count+";"205        CCCode += tabs(1+brace_count)+"*p -= "+minus_count+";\n";206    }207    right_count = 0; left_count = 0;208    plus_count = 0; minus_count = 0;209    JSCode += "var mem_log = \"\";for (var i = 0; i < 0xffff; i++) {if (i % 12 == 0) {mem_log += '\\n';}mem_log += a[i].toString(16).padStart(2, '0') + ' ';} return [o, mem_log];";210    CCCode += "\n\n  return 0;\n}";211    return (brace_count == 0) ? [JSCode, CCCode] : [false, CCCode];212}213document.getElementById("bf").value = "++++++++[>++++++++>++++++++<<-]>++.++++.+++.<++++++[>++++++<-]>+.++++++.>>++++++[>++++++<-]>[-<<+>>]<<+[>+>+<<-]>.+++++++++++++.--.++.>.<++.>.<--.>[-]++++[>++[>+++++<-]<-]>>[-<<<->>>]<<<.+++++++++.<+++++[<<++>>-]<<.>>>>++++[>++++[>++<-]<-]>>...>++++[>++++<-]>[-<<<<<->>>>>]<<<<<.<<--.-------------.>>[-]<<[->+>+<<]>----.>+++++++++++++++.<++++.-.<<.>>>>>>......<<++++++++[>++++++++>++++++++<<-]>++.<<+++++.<<<.>++++++++[>>>++[>>>++<<<-]<<<-]>>>>>>.<<<<<----------.>>>>+.[->>+>+<<<]>>++.<<<<++++[<---->-]<-.-------.>++++[<++++>-]<+.+++++++.>>>>.<++++[-<++++>]<.>++++[->>++++<<]>>++.--.."214var code = genCode(document.getElementById("bf").value);215var jsfunc = Function(code[0]);216document.getElementById("cpp").value = code[1];217document.getElementById("mem").value = jsfunc()[1];218document.getElementById("output").value = jsfunc()[0];219document.getElementById("download-button").addEventListener("click", function(){220    download(code[1]);221}, false);222document.getElementById("bf").oninput = function() {223    code = genCode(document.getElementById("bf").value);224    225    jsfunc = Function(code[0]);226    var ans = jsfunc();227    document.getElementById("cpp").value = code[1];228    if (ans) {229        document.getElementById("mem").value = ans[1];230        document.getElementById("output").value = ans[0];231    } else {232        document.getElementById("output").value = "Brace Mismatch";233    }...

Full Screen

Full Screen

template.js

Source:template.js Github

copy

Full Screen

1<<<<<<< HEAD2/**3 * seekTemplate - 前端轻量级模板插件4 * Created by likaituan on 14/8/18.5 */6define(function (req, exp) {7	"use strict";8    var $ = req("sys.filter");9	$.local = localStorage;10	$.session = sessionStorage;11	//生成JS代码12	exp.getJsCode= function (tmpCode) {13		tmpCode = tmpCode.replace(/\r\n|\r|\n/g, ""); //去除换行符14		var jscode = [];15		jscode.push('var buf = [];');16		var R = RegExp;17        var literalRe = /\{literal\}([\s\S]+?)\{\/literal\}/;18        var jsRe = /<%([\s\S]+?)%>/;19        var smartyRe = /\{(.+?)\}/;20		//添加HTML代码21		var addHTML = function (s) {22			s = s.replace(/【/g, "{").replace(/】/g, "}");23			s = s.replace(/'/g, "\\'");24			jscode.push("buf.push('" + s + "');");25		};26		//添加JS代码27		var addJs = function (ss) {28			ss = ss.replace(/\$\((.+?)\);?/g, "buf.push($1);");29			jscode.push(ss);30		};31		//解析Smarty代码32		var o;33		var parseSmarty = function (ss) {34			//ss = ss.replace(/\$/g, "this.");35			var aa = ss.split(" ");36			var s0 = aa.shift();37			if (s0 == "foreach") {38				o = {};39				aa.map(function (exp) {40					exp = exp.split("=");41					o[exp[0]] = exp[1];42				});43				var key = o.key || "i";44				var item = o.item || "item";45				if (o.start) {46					jscode.push("for(var " + key + "=" + o.start + ";" + key + "<=" + o.end + "; " + key + "++){");47				} else {48                    var a = o.from||o.src;49					jscode.push("var sn,src;for(var " + key + " in " + a + "){");50                    jscode.push("var " + item + "=" + a + "[" + key + "];");51                    jscode.push("sn="+key+"*1+1;");52                    jscode.push("src={length:"+a+".length, first:"+key+"==0, last:"+key+"=="+a+".length-1};");53				}54			} else if (s0 == "elseforeach" || s0=="elseach") {55				jscode.push("}; if(" + (o.from||o.src) + ".length==0){");56			} else if (s0 == "/foreach") {57				jscode.push("}");58			} else if (s0 == "if") {59				jscode.push("if(" + aa[0] + "){");60			} else if (s0 == "elseif" || s0=="elsif") {61				jscode.push("}else if(" + aa[0] + "){");62			} else if (s0 == "else") {63				jscode.push("}else{");64			} else if (s0 == "/if") {65				jscode.push("}");66			} else if (s0 == "loop") {67				jscode.push(filter.stringFormat("for(var {0}={1}; {0}<={2}; {0}++){", aa[0], aa[2], aa[4]));68			} else if (s0 == "/loop") {69				jscode.push("}");70			} else if (ss[0] == "=") {71				jscode.push("console.log("+ss.slice(1)+");");72			} else {73				var smf = $.split2(ss, "|");74				//避免碰到||的时候75				if (smf[1] && smf[1][0] == "|") {76					smf = [ss];77				}78				var s = smf[0];79				if (smf[1]) {80					var mf = $.split2(smf[1], ":");81					var m = mf[0];82					var f = mf[1];83					s = f ? "$." + m + "(" + s + ",'" + f + "')" : "$." + m + "(" + s + ")";84				}85				s && jscode.push("buf.push(" + s + ");");86			}87		};88		//先编译literal字面量89		var compileLiteral = function (code) {90			if (literalRe.test(code)) {91				var a = [R.leftContext, R.$1.trim(), R.rightContext];92				a[0] && compileJs(a[0]);93				a[1] && addHTML(a[1]);94				a[2] && compileLiteral(a[2]);95			} else {96				compileJs(code);97			}98		};99        //然后编译JS100		var compileJs = function (code) {101			if (jsRe.test(code)) {102				var a = [R.leftContext, R.$1, R.rightContext];103				a[0] && compileSmarty(a[0]);104				a[1] && addJs(a[1]);105				a[2] && compileJs(a[2]);106			} else {107				compileSmarty(code);108			}109		};110		//最后编译Smarty语法111		var compileSmarty = function (code) {112			code = code.replace(/\{\{/g, "【").replace(/\}\}/g, "】");113			if (smartyRe.test(code)) {114				var a = [R.leftContext, R.$1, R.rightContext];115				a[0] && addHTML(a[0]);116				a[1] && parseSmarty(a[1]);117				a[2] && compileSmarty(a[2]);118			} else {119				addHTML(code);120			}121		};122		compileLiteral(tmpCode);123		jscode.push('return buf.join("");');124		jscode = jscode.join("\n");125        //console.log(jscode);126        return jscode;127    };128    //获得编译函数129    exp.getFun = function (tplCode) {130        var jscode = exp.getJsCode(tplCode);131		return new Function("$", jscode);132	};133    //编译函数134    exp.compileFun = function (tplFun) {135        return function (data) {136            return tplFun.call(data, $);137        };138    };139    //直接编译模板代码140    exp.compile = function (tplCode) {141        var jscode = exp.getJsCode(tplCode);142        //console.log(jscode);143        var templateFun = new Function("$", jscode);144        return exp.compileFun(templateFun);145    };146});147=======148/**149 * seekTemplate - 前端轻量级模板插件150 * Created by likaituan on 14/8/18.151 */152153define(function (req, exp) {154	"use strict";155    var $ = req("sys.filter");156	$.local = localStorage;157	$.session = sessionStorage;158159	//生成JS代码160	exp.getJsCode= function (tmpCode) {161		tmpCode = tmpCode.replace(/\r\n|\r|\n/g, ""); //去除换行符162		var jscode = [];163		jscode.push('var buf = [];');164		var R = RegExp;165        var literalRe = /\{literal\}([\s\S]+?)\{\/literal\}/;166        var jsRe = /<%([\s\S]+?)%>/;167        var smartyRe = /\{(.+?)\}/;168169		//添加HTML代码170		var addHTML = function (s) {171			s = s.replace(/【/g, "{").replace(/】/g, "}");172			s = s.replace(/'/g, "\\'");173			jscode.push("buf.push('" + s + "');");174		};175176		//添加JS代码177		var addJs = function (ss) {178			ss = ss.replace(/\$\((.+?)\);?/g, "buf.push($1);");179			jscode.push(ss);180		};181182		//解析Smarty代码183		var o;184		var parseSmarty = function (ss) {185			//ss = ss.replace(/\$/g, "this.");186			var aa = ss.split(" ");187			var s0 = aa.shift();188			if (s0 == "foreach") {189				o = {};190				aa.map(function (exp) {191					exp = exp.split("=");192					o[exp[0]] = exp[1];193				});194				var key = o.key || "i";195				var item = o.item || "item";196				if (o.start) {197					jscode.push("for(var " + key + "=" + o.start + ";" + key + "<=" + o.end + "; " + key + "++){");198				} else {199                    var a = o.from||o.src;200					jscode.push("var sn,src;for(var " + key + " in " + a + "){");201                    jscode.push("var " + item + "=" + a + "[" + key + "];");202                    jscode.push("sn="+key+"*1+1;");203                    jscode.push("src={length:"+a+".length, first:"+key+"==0, last:"+key+"=="+a+".length-1};");204				}205			} else if (s0 == "elseforeach" || s0=="elseach") {206				jscode.push("}; if(" + (o.from||o.src) + ".length==0){");207			} else if (s0 == "/foreach") {208				jscode.push("}");209210			} else if (s0 == "if") {211				jscode.push("if(" + aa[0] + "){");212			} else if (s0 == "elseif" || s0=="elsif") {213				jscode.push("}else if(" + aa[0] + "){");214			} else if (s0 == "else") {215				jscode.push("}else{");216			} else if (s0 == "/if") {217				jscode.push("}");218219220			} else if (s0 == "loop") {221				jscode.push(filter.stringFormat("for(var {0}={1}; {0}<={2}; {0}++){", aa[0], aa[2], aa[4]));222			} else if (s0 == "/loop") {223				jscode.push("}");224225226			} else if (ss[0] == "=") {227				jscode.push("console.log("+ss.slice(1)+");");228			} else {229				var smf = $.split2(ss, "|");230				//避免碰到||的时候231				if (smf[1] && smf[1][0] == "|") {232					smf = [ss];233				}234				var s = smf[0];235				if (smf[1]) {236					var mf = $.split2(smf[1], ":");237					var m = mf[0];238					var f = mf[1];239					s = f ? "$." + m + "(" + s + ",'" + f + "')" : "$." + m + "(" + s + ")";240				}241				s && jscode.push("buf.push(" + s + ");");242			}243		};244245		//先编译literal字面量246		var compileLiteral = function (code) {247			if (literalRe.test(code)) {248				var a = [R.leftContext, R.$1.trim(), R.rightContext];249				a[0] && compileJs(a[0]);250				a[1] && addHTML(a[1]);251				a[2] && compileLiteral(a[2]);252			} else {253				compileJs(code);254			}255		};256257        //然后编译JS258		var compileJs = function (code) {259			if (jsRe.test(code)) {260				var a = [R.leftContext, R.$1, R.rightContext];261				a[0] && compileSmarty(a[0]);262				a[1] && addJs(a[1]);263				a[2] && compileJs(a[2]);264			} else {265				compileSmarty(code);266			}267		};268269270		//最后编译Smarty语法271		var compileSmarty = function (code) {272			code = code.replace(/\{\{/g, "【").replace(/\}\}/g, "】");273			if (smartyRe.test(code)) {274				var a = [R.leftContext, R.$1, R.rightContext];275				a[0] && addHTML(a[0]);276				a[1] && parseSmarty(a[1]);277				a[2] && compileSmarty(a[2]);278			} else {279				addHTML(code);280			}281		};282283		compileLiteral(tmpCode);284285		jscode.push('return buf.join("");');286		jscode = jscode.join("\n");287        //console.log(jscode);288        return jscode;289    };290291    //获得编译函数292    exp.getFun = function (tplCode) {293        var jscode = exp.getJsCode(tplCode);294		return new Function("$", jscode);295	};296297    //编译函数298    exp.compileFun = function (tplFun) {299        return function (data) {300            return tplFun.call(data, $);301        };302    };303304    //直接编译模板代码305    exp.compile = function (tplCode) {306        var jscode = exp.getJsCode(tplCode);307        //console.log(jscode);308        var templateFun = new Function("$", jscode);309        return exp.compileFun(templateFun);310    };311312});
...

Full Screen

Full Screen

era-code-gen-js.js

Source:era-code-gen-js.js Github

copy

Full Screen

1// era-code-gen-js.js2// Copyright 2016 Ross Angle. Released under the MIT License.3"use strict";4// This file defines `jsCode()`, `jsCodeVar()`, and `jsCodeReified()`,5// which can be used as a way to generate and invoke JavaScript6// expressions with reified first-class values and tracking of free7// variables. These utilities return a `JsCode` object, which has8// several useful methods.9//10// Notably, the `JsCode#asStatic()` method transforms code that has no11// free variables so that it runs at the beginning of the compiled12// code, so that the same computation is not performed over and over.13// Multiple expressions transformed this way run in the order they14// would have appeared in the generated code if they hadn't been made15// static.16// TODO: This file is unused for now, but let's refactor Cene to use17// it so we can factor out non-macro ways for Cene code to obtain and18// manipulate compiled expressions.19function jsCode_toFreeVars_( freeVars ) {20    return isArray( freeVars ) && arrAll( freeVars, function ( va ) {21        return isPrimString( va );22    } ) ? strMap().plusArrTruth( freeVars ) : freeVars;23}24function JsCode() {}25JsCode.prototype.init_ = function (26    freeVars, staticExprs, getCode ) {27    28    this.freeVars_ = freeVars;29    this.staticExprs_ = staticExprs;30    this.getCode_ = getCode;31    return this;32};33JsCode.prototype.withFreeVars_ = function ( freeVars ) {34    return new JsCode().init_(35        freeVars, this.staticExprs_, this.getCode_ );36};37JsCode.prototype.plusFreeVars = function ( freeVars ) {38    return this.withFreeVars_(39        this.freeVars_.plus( jsCode_toFreeVars_( freeVars ) ) );40};41JsCode.prototype.minusFreeVars = function ( freeVars ) {42    return this.withFreeVars_(43        this.freeVars_.minus( jsCode_toFreeVars_( freeVars ) ) );44};45JsCode.prototype.assertNotFreeVars = function ( freeVars ) {46    var self = this;47    jsCode_toFreeVars_( freeVars ).each( function ( va, truth ) {48        if ( self.freeVars_.has( va ) )49            throw new Error();50    } );51    return self;52};53JsCode.prototype.assertNoFreeVars = function () {54    if ( this.freeVars_.hasAny() ) {55        var freeVars = [];56        this.freeVars_.each( function ( va, truth ) {57            freeVars.push( va );58        } );59        throw new Error(60            "Encountered " +61            (freeVars.length === 1 ?62                "an unbound variable" :63                "unbound variables") + " " +64            "when generating JavaScript code: " +65            freeVars.join( ", " ) );66    }67    return this;68};69function jsCodeSingleStatic_( staticExpr ) {70    return new JsCode().init_( strMap(), [ staticExpr ],71        function ( staticVars ) {72        73        if ( staticVars.length !== 1 )74            throw new Error();75        return staticVars[ 0 ];76    } );77}78JsCode.prototype.asStatic = function () {79    this.assertNoFreeVars();80    return jsCodeSingleStatic_( { type: "expr", expr: this } );81};82JsCode.prototype.toExpr_ = function (83    disallowedGensyms, reifiedVars, reifiedVals ) {84    85    var gensymNumber = 0;86    function nextGensym() {87        while ( true ) {88            var candidate = "gs" + gensymNumber++;89            if ( !disallowedGensyms.has( candidate ) )90                return candidate;91        }92    }93    94    function toExpr( code ) {95        var result = "(function () {";96        var staticVars = [];97        arrEach( code.staticExprs_, function ( staticExpr ) {98            if ( staticExpr.type === "expr" ) {99                var exprCode = toExpr( staticExpr.expr );100            } else if ( staticExpr.type === "reified" ) {101                var reifiedVar = nextGensym();102                reifiedVars.push( reifiedVar );103                reifiedVals.push( staticExpr.val );104                var exprCode = reifiedVar;105            } else {106                throw new Error();107            }108            var staticVar = nextGensym();109            result +=110                "    var " + staticVar + " = " + exprCode + ";\n";111            staticVars.push( staticVar );112        } );113        var getCode = code.getCode_;114        result +=115            "    return " + getCode( staticVars ) + ";\n" +116            "})()";117        return result;118    }119    120    return toExpr( this );121};122JsCode.prototype.toExpr = function () {123    this.assertNoFreeVars();124    125    var reifiedVars = [];126    var expr = this.toExpr_( strMap(), reifiedVars, [] );127    if ( reifiedVars.length !== 0 )128        throw new Error();129    return expr;130};131JsCode.prototype.toFunction = function ( paramVarsArr ) {132    if ( !isArray( paramVarsArr ) )133        throw new Error();134    this.minusFreeVars( paramVarsArr ).assertNoFreeVars();135    136    var disallowedGensyms = strMap().plusArrTruth( paramVarsArr );137    var reifiedVars = [];138    var reifiedVals = [];139    var expr =140        this.toExpr_( disallowedGensyms, reifiedVars, reifiedVals );141    142    var compiled =143        Function.apply( null, reifiedVars.concat( paramVarsArr, [144            "return " + expr + ";"145        ] ) );146    147    return function ( var_args ) {148        var paramValsArr = [].slice.call( arguments );149        return compiled.apply( this,150            reifiedVals.concat( paramValsArr ) );151    }152};153JsCode.prototype.instantiate = function ( envObj ) {154    var vars = [];155    var vals = [];156    objOwnEach( envObj, function ( va, val ) {157        vars.push( va );158        vals.push( val );159    } );160    return this.toFunction( vars ).apply( null, vals );161};162JsCode.prototype.toFunctionExpr_ = function ( paramVarsArr, minify ) {163    if ( !isArray( paramVarsArr ) )164        throw new Error();165    this.minusFreeVars( paramVarsArr ).assertNoFreeVars();166    167    var disallowedGensyms = strMap().plusArrTruth( paramVarsArr );168    var reifiedVars = [];169    var expr = this.toExpr_( disallowedGensyms, reifiedVars, [] );170    if ( reifiedVars.length !== 0 )171        throw new Error();172    173    return "Function( " + jsStr( minify(174        "return function ( " + paramVarsArr.join( ", " ) + " ) {\n" +175        "return " + expr + ";\n" +176        "};\n"177    ) ) + " )()";178};179// TODO: See if we'll ever use this.180JsCode.prototype.toInstantiateExpr = function ( envObj, minify ) {181    var vars = [];182    var vals = [];183    objOwnEach( envObj, function ( va, val ) {184        vars.push( va );185        vals.push( val );186    } );187    return this.toFunctionExpr_( vars, minify ) + "( " +188        vals.join( ", " ) + " )";189};190JsCode.prototype.toString = function () {191    throw new Error( "Tried to convert a JsCode object to a string" );192};193function jsCode( var_args ) {194    var freeVars = strMap();195    var staticExprs = [];196    var segments = [];197    198    addArg( [].slice.call( arguments ) );199    function addArg( arg ) {200        if ( isArray( arg ) ) {201            arrEach( arg, function ( arg, i ) {202                addArg( arg );203            } );204        } else if ( isPrimString( arg ) ) {205            segments.push( { size: 0, func: function ( staticVars ) {206                return arg;207            } } );208            209        } else if ( typeof arg === "object"210            && arg instanceof JsCode ) {211            212            staticExprs = staticExprs.concat( arg.staticExprs_ );213            freeVars = freeVars.plus( arg.freeVars_ );214            segments.push( { size: arg.staticExprs_.length,215                func: arg.getCode_ } );216        } else {217            throw new Error();218        }219    }220    221    return new JsCode().init_( freeVars, staticExprs,222        function ( staticVars ) {223        224        var result = "";225        var i = 0;226        var n = staticVars.length;227        arrEach( segments, function ( segment ) {228            var nextI = i + segment.size;229            if ( n < nextI )230                throw new Error();231            var func = segment.func;232            result += func( staticVars.slice( i, nextI ) );233            i = nextI;234        } );235        if ( i !== n )236            throw new Error();237        return result;238    } );239}240function jsCodeVar( va ) {241    if ( !isPrimString( va ) )242        throw new Error();243    return jsCode( va ).plusFreeVars( [ va ] );244}245function jsCodeReified( val ) {246    return jsCodeSingleStatic_( { type: "reified", val: val } );...

Full Screen

Full Screen

h5template.js

Source:h5template.js Github

copy

Full Screen

1/**2 * seekTemplate - 前端轻量级模板插件3 * Created by likaituan on 14/8/18.4 */5(function (req, exp) {6    "use strict";7    var $ = {};8    //根据指定的分隔符截成两半9    var split2 = function (str, flag) {10        var a = str.split(flag);11        var ret = [a.shift()];12        a.length > 0 && ret.push(a.join(flag));13        return ret;14    };15    //生成JS代码16    exp.getJsCode= function (tmpCode) {17        tmpCode = tmpCode.replace(/\r\n|\r|\n/g, "");18        var jscode = [];19        jscode.push('var buf = [];');20        var R = RegExp;21        var literalRe = /\{literal\}([\s\S]+?)\{\/literal\}/;22        var jsRe = /<%([\s\S]+?)%>/;23        var smartyRe = /\{(.+?)\}/;24        //添加HTML代码25        var addHTML = function (s) {26            s = s.replace(/【/g, "{").replace(/】/g, "}");27            s = s.replace(/'/g, "\\'");28            jscode.push("buf.push('" + s + "');");29        };30        //添加JS代码31        var addJs = function (ss) {32            ss = ss.replace(/\$\((.+?)\);?/g, "buf.push($1);");33            jscode.push(ss);34        };35        //解析Smarty代码36        var o;37        var parseSmarty = function (ss) {38            //ss = ss.replace(/\$/g, "this.");39            var aa = ss.split(" ");40            var s0 = aa.shift();41            if (s0 == "foreach") {42                o = {};43                aa.map(function (exp) {44                    exp = exp.split("=");45                    o[exp[0]] = exp[1];46                });47                var key = o.key || "i";48                var item = o.item || "item";49                if (o.start) {50                    jscode.push("for(var " + key + "=" + o.start + ";" + key + "<=" + o.end + "; " + key + "++){");51                } else {52                    var a = o.from||o.src;53                    jscode.push("var sn,src;for(var " + key + " in " + a + "){");54                    jscode.push("var " + item + "=" + a + "[" + key + "];");55                    jscode.push("sn="+key+"*1+1;");56                    jscode.push("src={length:"+a+".length, first:"+key+"==0, last:"+key+"=="+a+".length-1};");57                }58            } else if (s0 == "elseforeach" || s0=="elseach") {59                jscode.push("}; if(" + (o.from||o.src) + ".length==0){");60            } else if (s0 == "/foreach") {61                jscode.push("}");62            } else if (s0 == "if") {63                jscode.push("if(" + aa[0] + "){");64            } else if (s0 == "elseif" || s0=="elsif") {65                jscode.push("}else if(" + aa[0] + "){");66            } else if (s0 == "else") {67                jscode.push("}else{");68            } else if (s0 == "/if") {69                jscode.push("}");70            } else if (s0 == "loop") {71                var ii = aa[0];72                jscode.push(`for(var ${ii}=${aa[2]}; ${ii}<=${aa[4]}; ${ii}++){`);73            } else if (s0 == "/loop") {74                jscode.push("}");75            } else if (ss[0] == "=") {76                jscode.push("console.log("+ss.slice(1)+");");77            } else {78                var smf = split2(ss, "|");79                //避免碰到||的时候80                if (smf[1] && smf[1][0] == "|") {81                    smf = [ss];82                }83                var s = smf[0];84                if (smf[1]) {85                    var mf = split2(smf[1], ":");86                    var m = mf[0];87                    var f = mf[1];88                    s = f ? "$." + m + "(" + s + ",'" + f + "')" : "$." + m + "(" + s + ")";89                }90                s && jscode.push("buf.push(" + s + ");");91            }92        };93        //先编译literal字面量94        var compileLiteral = function (code) {95            if (literalRe.test(code)) {96                var a = [R.leftContext, R.$1.trim(), R.rightContext];97                a[0] && compileJs(a[0]);98                a[1] && addHTML(a[1]);99                a[2] && compileLiteral(a[2]);100            } else {101                compileJs(code);102            }103        };104        //然后编译JS105        var compileJs = function (code) {106            if (jsRe.test(code)) {107                var a = [R.leftContext, R.$1, R.rightContext];108                a[0] && compileSmarty(a[0]);109                a[1] && addJs(a[1]);110                a[2] && compileJs(a[2]);111            } else {112                compileSmarty(code);113            }114        };115        //最后编译Smarty语法116        var compileSmarty = function (code) {117            code = code.replace(/\{\{/g, "【").replace(/\}\}/g, "】");118            if (smartyRe.test(code)) {119                var a = [R.leftContext, R.$1, R.rightContext];120                a[0] && addHTML(a[0]);121                a[1] && parseSmarty(a[1]);122                a[2] && compileSmarty(a[2]);123            } else {124                addHTML(code);125            }126        };127        compileLiteral(tmpCode);128        jscode.push('return buf.join("");');129        jscode = jscode.join("\n");130        return jscode;131    };132    //获得编译函数133    exp.getFun = function (tplCode) {134        var jscode = exp.getJsCode(tplCode);135        return new Function("$", jscode);136    };137    //编译函数138    exp.compileFun = function (tplFun) {139        return function (data) {140            return tplFun.call(data, $);141        };142    };143    //直接编译模板代码144    exp.compile = function (tplCode) {145        var jscode = exp.getJsCode(tplCode);146        //console.log(jscode);147        var templateFun = new Function("$", jscode);148        return exp.compileFun(templateFun);149    };...

Full Screen

Full Screen

require_analyzer.js

Source:require_analyzer.js Github

copy

Full Screen

1var astProcessor  = require('uglify-js').uglify,2    Common        = require('./../common'),3    Hammerhead    = require('testcafe-hammerhead'),4    Ast           = require('./../ast'),5    CallAnalyzer  = require('./call_analyzer'),6    StepsAnalyzer = require('./steps_analyzer');7function extractMixins (ast, descriptor, errs, sourceIndex) {8    var walker             = astProcessor.ast_walker(),9        mixinAnalyzer      = new StepsAnalyzer(true, descriptor.rawMixinsStepData, errs, sourceIndex),10        requireCodeRebuild = false;11    walker.with_walkers({12        'string': function () {13            var astPath      = walker.stack(),14                topStatement = astPath[1][0];15            if (this[1] === Common.MIXIN_DECLARATION_MARKER) {16                topStatement.remove = true;17                requireCodeRebuild  = true;18                mixinAnalyzer.run(walker.stack(), descriptor.filename, descriptor.jsCode);19            }20        }21    }, function () {22        walker.walk(ast);23    });24    return requireCodeRebuild;25}26function analyzeRequireCode (requireAst, descriptor, errs, sourceIndex) {27    //OPTIMIZATION: use footprints to determine if we need deeper analysis28    var originalSrc = descriptor.jsCode;29    if (Common.MIXIN_FOOTPRINT_REGEXP.test(descriptor.jsCode)) {30        var rebuildCode = extractMixins(requireAst, descriptor, errs, sourceIndex);31        //NOTE: we need to rebuild js code if mixins were removed from AST32        if (rebuildCode) {33            requireAst        = Ast.getRemainderAst(requireAst);34            descriptor.jsCode = requireAst ? astProcessor.gen_code(requireAst, { beautify: true }) : '';35        }36    }37    if (Common.ACTION_OR_ASSERTION_FOOTPRINT_REGEXP.test(descriptor.jsCode)) {38        //NOTE: validate what require file doesn't contain action functions calls and update source index39        if (CallAnalyzer.run(requireAst, descriptor.filename, errs, true, sourceIndex, originalSrc)) {40            //NOTE: if call analyzer found assertions and added them to index, we need to rebuild again41            descriptor.jsCode = requireAst ? astProcessor.gen_code(requireAst, { beautify: true }) : '';42        }43    }44}45exports.run = function (requireFilename, ownerFilename, sourceIndex, callback) {46    var errs       = [],47        descriptor = {48            hasErrs:           false,49            jsCode:            null,50            rawMixinsStepData: {},51            filename:          requireFilename52        };53    Ast.construct(requireFilename, ownerFilename, function (parsingErr, requireAst, srcCode) {54        if (parsingErr)55            errs.push(parsingErr);56        else if (requireAst) {57            descriptor.jsCode = srcCode;58            analyzeRequireCode(requireAst, descriptor, errs, sourceIndex);59        }60        if (!errs.length)61            descriptor.jsCode = Hammerhead.wrapDomAccessors(descriptor.jsCode, true);62        //NOTE: User can forget ';' at the end of the require js file. In this case, an js exception may occure after63        //requires merging. So we add ';' at the end of the require code manually64        if (descriptor.jsCode && descriptor.jsCode[descriptor.jsCode.length - 1] !== ';')65            descriptor.jsCode += ';';66        descriptor.hasErrs = !!errs.length;67        callback(errs, descriptor);68    });...

Full Screen

Full Screen

generate.js

Source:generate.js Github

copy

Full Screen

1'use strict';2var childProcess = require('child_process'),3    fs = require('fs'),4    mote = require('mote'),5    wordwrap = require('wordwrap'),6    path = require('path'),7    moment = require('moment'),8    php = 'php'; // on windows something like 'C:\\xampp\\php\\php.exe'9function generateLicenseAndVersionInfo() {10    var pkg = require(path.join(__dirname, '..', 'package.json'));11    var today = moment().format('YYYY-MM-DD');12    return {13        licenceComment: '/*!' + pkg.name + ' v' + pkg.version + ' ' + today + '*/\n',14        versionInfo: pkg.version + ' ' + today15    };16}17function generateCode() {18    var phpScript = path.join(__dirname, 'export-config.php');19    childProcess.exec(php + ' ' + phpScript, function (error, stdout, stderr) {20        if (error) {21            console.log(error.stack);22            console.log('Error code: '+error.code);23            console.log('Signal received: '+error.signal);24            return;25        }26        var template = fs.readFileSync(path.join(__dirname, 'mobile-detect.template.js'), 'utf8'),27            replaceToken = '{/*rules*/}',28            tokenPos = template.indexOf(replaceToken),29            jsCode,30            licenceAndVersion = generateLicenseAndVersionInfo();31        jsCode = template.substring(0, tokenPos) + stdout + template.substring(tokenPos + replaceToken.length);32        jsCode = addComments(jsCode, stdout);33        jsCode = '// THIS FILE IS GENERATED - DO NOT EDIT!\n' + licenceAndVersion.licenceComment + jsCode;34        jsCode = jsCode.replace(/MOBILE_DETECT_VERSION/, licenceAndVersion.versionInfo);35        fs.writeFileSync(path.join(__dirname, '..', 'mobile-detect.js'), jsCode, 'utf-8');36    });37}38function addComments(jsCode, rulesJson) {39    var rules = JSON.parse(rulesJson),40        comments = {},41        wrap = wordwrap(80);42    ['phones', 'tablets', 'oss', 'uas', 'props', 'utils'].forEach(function (key) {43        var list = Object.keys(rules[key]).join(', ');44        list = wrap(list).split(/\n/g);45        comments[key] = list.join('\n         * ');46    });47    return mote.compile(jsCode)({'keys': comments});48}49function generateTestData() {50    var uaListJson, uaList,51        mobilePerVendor,52        number,53        out;54    uaListJson = fs.readFileSync(path.join(__dirname, '..', '..', 'Mobile-Detect', 'tests', 'ualist.json'), 'utf8');55    uaList = JSON.parse(uaListJson);56    mobilePerVendor = {};57    number = 0;58    uaList.user_agents.forEach(function (item) {59        var vendor = item.vendor;60        if ('mobile' in item) {61            delete item.vendor;62            item.nr = ++number;63            mobilePerVendor[vendor] = mobilePerVendor[vendor] || [];64            mobilePerVendor[vendor].push(item);65        }66    });67    out = [68        '/* This file was generated - do not edit! */',69        '/* hash = ' + uaList.hash + ' */',70        '',71        'var mobilePerVendor =',72        JSON.stringify(mobilePerVendor, null, 4) + ';',73        '',74        'if (typeof module !== "undefined") {',75        '    module.exports = mobilePerVendor;',76        '}'77    ].join('\n');78    fs.writeFileSync(path.join(__dirname, '..', 'tests', 'data', 'user-agents.js'), out, 'utf-8');79}80generateCode();...

Full Screen

Full Screen

parsingXML.js

Source:parsingXML.js Github

copy

Full Screen

1////// Append some tex with tabulation2////function append(text, tab) {3////    var t = "  ";4////    for (var i = 0; i < tab; i++) {5////        text = t + text;6////    }7////    return text;8////}9////function appendln(text, tab) {10////    return append(text, tab) + "\n";11////}12////// Try to parse XML into a custom block13////function tryParse(workspace_) {14////    var firstBlock = workspace_.getAllBlocks()[0];15////    var domBlock = Blockly.Xml.blockToDom(firstBlock);16////    var names = domBlock.getElementsByTagName("*");17////    var name = names[3].tagName;18////    for (var i = 0; i < names.length; i++) {19////        var item = names[i];20////        switch (item.tagName) {21////            case "FIELD":22////                name = item.content;23////                break;24////            default:25////                break;26////        }27////    }28////    ////var text = Blockly.Xml.domToPrettyText(domBlock);29////    ////alert(text);30////    var JSCode = "Blockly.Blocks['" +31////        name +32////        appendln("'] = {") +33////        appendln("init: function() {", 1);34////    JSCode += appendln("this.appendDummyInput", 2) +35////        appendln(".setAlign(Blockly.ALIGN_CENTRE)", 4) +36////        appendln(".appendField('" + "');", 4);37////    JSCode += appendln("}", 1) + appendln("};");38////    alert(JSCode);39////}40////function parse() {41////    var firstBlock = workspace.getAllBlocks()[0];42////    var domBlock = Blockly.Xml.blockToDom(firstBlock);43////    var tags = domBlock.getElementsByTagName("*");44////    var JSCode = "Blockly.Blocks['" + domBlock.getAttribute("type") + "'] = {\n" + appendln("init: function() {", 1);45////    for (var i = 0; i < tags.length; i++) {46////        switch (tags[i].tagName) {47////            case "FIELD":48////                JSCode += appendln('this.appendDummyInput()', 2);49////                JSCode += appendln('.appendField(' + '"' + tags[i].getAttribute("name") + '"' + ")", 3);50////                JSCode += appendln("appendField(new Blockly.FieldTextInput(" + '"' + tags[i].innerHTML + '"' + "), " + '"' + tags[i].innerHTML + '"' + ");", 3);51////                break;52////            case "STATEMENT":53////                JSCode += appendln('this.appendStatementInput("NAME")', 2);54////                JSCode += appendln('.setCheck(null);', 3);55////                break;56////            case "BLOCK":57////                break;58////        }59////    }60////    alert(JSCode);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.jsCode('console.log("Hello World")');2cy.jsCode('console.log("Hello World")');3cy.jsCode('console.log("Hello World")');4cy.jsCode('console.log("Hello World")');5cy.jsCode('console.log("Hello World")');6cy.jsCode('console.log("Hello World")');7cy.jsCode('console.log("Hello World")');8cy.jsCode('console.log("Hello World")');9cy.jsCode('console.log("Hello World")');10cy.jsCode('console.log("Hello World")');11cy.jsCode('console.log("Hello World")');12cy.jsCode('console.log("Hello World")');13cy.jsCode('console.log("Hello World")');14cy.jsCode('console.log("Hello World")');15cy.jsCode('console.log("Hello World")');16cy.jsCode('console.log("Hello World")');17cy.jsCode('console.log("Hello World")');18cy.jsCode('console.log("Hello World")');19cy.jsCode('console.log("Hello World")');20cy.jsCode('console.log("Hello World")');21cy.jsCode('console.log("Hello World")');22cy.jsCode('console.log("Hello World")');23cy.jsCode('console.log("Hello World")');24cy.jsCode('console.log("Hello World")');

Full Screen

Using AI Code Generation

copy

Full Screen

1describe("test", () => {2  it("test", () => {3    cy.get("input[name=q]").type("cypress");4    cy.get("input[name=q]").then(($input) => {5      var value = $input[0].value;6      expect(value).to.eq("cypress");7    });8  });9});10{11}12describe("test", () => {13  it("test", () => {14      (response) => {15        cy.wrap(response).its("body").should("deep.eq", {16        });17      }18    );19  });20});21describe("test", () => {22  it("test", () => {23      (response) => {24        cy.wrap(response).its("body").should("deep.eq", {

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress 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