language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class PendingCommitPage { constructor() { this.containerSelector = '[id="cmpsr-modal-pending-changes"]'; } loading() { browser.waitForExist(this.containerSelector, timeout); } commit() { const selector = `${this.containerSelector} .modal-footer button[class="btn btn-primary"]`; browser.waitUntil( () => browser.isVisible(selector), timeout, `Commit button in Changes Pending Commit dialog cannot be found by selector ${selector}` ); // browser.click() does not work with Edge due to "Element is Obscured" error. // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/5238133/ browser.execute(commitButton => { document.querySelector(commitButton).click(); return true; }, selector); } get closeButton() { const selector = "button=Close"; browser.waitUntil( () => browser.isExisting(selector), timeout, `Close button in Changes Pending Commit dialog cannot be found by selector ${selector}` ); return $(selector); } get xButton() { const selector = `${this.containerSelector} .pficon-close`; browser.waitUntil( () => browser.isExisting(selector), timeout, `X button in Changes Pending Commit dialog cannot be found by selector ${selector}` ); return $(selector); } get infoMessage() { const selector = "span=Only changes to selected components are shown."; browser.waitUntil( () => browser.isExisting(selector), timeout, `Info message in Changes Pending Commit dialog cannot be found by selector ${selector}` ); return $(selector); } get blueprintNameLabel() { const selector = `${this.containerSelector} .form-horizontal > p`; browser.waitUntil( () => browser.isExisting(selector), timeout, `blueprint name label in Changes Pending Commit dialog cannot be found by selector ${selector}` ); return $(selector); } get changeLogList() { return $$(`${this.containerSelector} .form-horizontal ul li`); } actionNameOnNth(nth) { return $$(`${this.containerSelector} .form-horizontal ul li .col-sm-3`)[nth].getText(); } changedPackageNameOnNth(nth) { return $$(`${this.containerSelector} .form-horizontal ul li .col-sm-9`)[nth].getText(); } }
JavaScript
class CarouselWithThumbnails extends Carousel { get defaults() { const base = super.defaults || {}; return Object.assign({}, base, { tags: Object.assign({}, base.tags, { proxy: 'elix-thumbnail' }) }); } get defaultState() { return Object.assign({}, super.defaultState, { proxyListOverlap: false }); } proxyUpdates(proxy, calcs) { const base = super.proxyUpdates(proxy, calcs); const item = calcs.item; return merge(base, { attributes: { src: item.src } }); } }
JavaScript
class RoomsSocket { constructor ( socketFactory, roomsEvents, routerGoService, routerStates ) { "ngInject"; Object.assign(this, { socketFactory, roomsEvents, routerGoService, routerStates }); } getRoomDetails (options) { let {success, failure, data} = Object(options); options.emit = { eventName: this.roomsEvents.reqJoinedRoomDetails, data: data }; options.events = [ { eventName: this.roomsEvents.resJoinedRoomDetailsSuccess, callback: data => { success(data); // success = null; // failure = null; }, offEvents: [] }, // TODO failure { eventName: this.roomsEvents.resJoinedRoomDetailsFailure, callback: data => { failure(data); // success = null; // failure = null; }, offEvents: [] } ]; this.socketFactory.emitHandler(options); } roomJoined () { // let {data, success} = options; let options = {}; options.emit = { eventName: this.roomsEvents.reqRoomJoined, // data: { // roomId: options.roomId // } }; this.socketFactory.emitHandler(options); // success(); // data = null; // success = null; options = null; } /** Join room and listen to room details */ joinRoom (options) { let {data, success, failure} = options; options.emit = { eventName: this.roomsEvents.reqJoinRoom, data: data }; options.events = [ { eventName: this.roomsEvents.resRoomJoinedSuccess, callback: data => { success(data); success = null; failure = null; }, offEvents: [] }, { // TODO failure eventName: this.roomsEvents.resRoomJoinedFailure, callback: data => { failure(data); success = null; failure = null; }, offEvents: [] } ]; this.socketFactory.emitHandler(options); } }
JavaScript
class MySQLSchema { constructor(schema) { schema = Object.assign( { id: { type: "VARCHAR", primary: true, length: 36, }, }, schema ); schema.createdAt = { type: "BIGINT", length: 13, default: Date.now(), name: "created_at", }; schema.updatedAt = { type: "BIGINT", length: 13, default: Date.now(), name: "updated_at", }; schema.createdBy = { type: "VARCHAR", length: 36, ref: "Users", name: "created_by", }; schema.updatedBy = { type: "VARCHAR", length: 36, ref: "Users", name: "updated_by", }; schema.isDelete = { type: "TINYINT", length: 1, default: 0, name: "is_deleted", }; this.schema = schema; } get column() { return Object.keys(this.schema) .map((key) => { if (this.schema[key].name) { return `${this.schema[key].name} AS ${key}`; } return key; }) .toString(); } }
JavaScript
class UnknownError extends Error { /** * @param {Number} statusCode * @param {String} message */ constructor(statusCode = 500, message = 'An unknown error occurred') { super(message); this.message = message; this.statusCode = statusCode; } }
JavaScript
class BadRequestError extends Error { /** * @param {String} message */ constructor(message) { super(message); this.message = message; this.statusCode = HttpStatus.BAD_REQUEST; } }
JavaScript
class InternalServerError extends Error { /** * Empty constructor */ constructor() { const message = 'We are sorry, an internal server error occurred. Please try your request again at a later time.'; super(message); this.message = message; this.statusCode = HttpStatus.INTERNAL_SERVER_ERROR; } }
JavaScript
class RouteNotFoundError extends Error { /** * @param {String} method */ constructor(method) { const message = `The requested ${method} route was not found.`; super(message); this.message = message; this.statusCode = HttpStatus.NOT_FOUND; } }
JavaScript
class BlockQuote extends Plugin { /** * @inheritDoc */ static get requires() { return [ BlockQuoteEngine ]; } /** * @inheritDoc */ static get pluginName() { return 'BlockQuote'; } /** * @inheritDoc */ init() { const editor = this.editor; const t = editor.t; const command = editor.commands.get( 'blockQuote' ); editor.ui.componentFactory.add( 'blockQuote', locale => { const buttonView = new ButtonView( locale ); buttonView.set( { label: t( 'Block quote' ), icon: quoteIcon, tooltip: true } ); // Bind button model to command. buttonView.bind( 'isOn', 'isEnabled' ).to( command, 'value', 'isEnabled' ); // Execute command. this.listenTo( buttonView, 'execute', () => editor.execute( 'blockQuote' ) ); return buttonView; } ); } /** * @inheritDoc */ afterInit() { const editor = this.editor; const command = editor.commands.get( 'blockQuote' ); // Overwrite default Enter key behavior. // If Enter key is pressed with selection collapsed in empty block inside a quote, break the quote. // This listener is added in afterInit in order to register it after list's feature listener. // We can't use a priority for this, because 'low' is already used by the enter feature, unless // we'd use numeric priority in this case. this.listenTo( this.editor.editing.view, 'enter', ( evt, data ) => { const doc = this.editor.document; const positionParent = doc.selection.getLastPosition().parent; if ( doc.selection.isCollapsed && positionParent.isEmpty && command.value ) { this.editor.execute( 'blockQuote' ); this.editor.editing.view.scrollToTheSelection(); data.preventDefault(); evt.stop(); } } ); } }
JavaScript
class Game { constructor() { //Get canvas's context and set its rendering with and height this.context = document.getElementById("game_canvas").getContext("2d"); this.context.canvas.width = 1920; this.context.canvas.height = 1080; //Create HTML input element, set its type to "file" and enable directory selection this.directorySelector = document.createElement("input"); this.directorySelector.type = "file"; //Note! Only seems to work on Chrome, Edge and Firefox! this.directorySelector.webkitdirectory = true; this.songList = []; this.currentChart = null; this.currentAudio = null; this.currentBG = null; this.currentTimingSection = 0; this.judgeOffset = 0; this.universalOffset = 90; this.showFPS = true; this.playDelay = 3000; this.state = 0; /* * States: * 0: Initial State * 1: Waiting for browser to generate file list (unused due to impossibility to detect when the browser is doing so) * 2: Generating song list * 3: Song selection menu * 4: In game * 5: Results (unused since no result screen is currently implemented) */ this.deltaTime = 0; this.lastTime = 0; this.lastFPS = 0; this.FPScounter = 0; this.nextFPSUpdate = 0; this.currentScore = [[]]; this.currentCombo = 0; this.playStartTime = performance.now(); this.objectLayers; this.autoPlay = false; this.currentProgress = 0; this.endProgress = 0; this.config = {}; this.defaultConfig = { keyConfigs: [ new KeyConfig( //Global config (index 0), other configs copy missing parameters from this one [], //Keys for lanes (button config) 128, //Lane width 160, //Hit position true, //Down scroll (true: notes go from top to bottom) 2.3, //Scroll speed multiplier (1: notes move 1000 pixels per second) false, //Special lane, not yet implemented true, //Special lane side (true: left) 30, //Note height for bar notes, should be rewritten to get from a noteskin object null, //Noteskin object to be used, noteskins not yet implemented [], //Note snap colours, not yet implemented 50, //Height of the beat line "#FFFFFF" //Colour of the beat line ), //Rest will copy other settings from the global config apart from keys new KeyConfig(["Space"]), new KeyConfig(["KeyX", "KeyM"]), new KeyConfig(["KeyX", "Space", "KeyM"]), new KeyConfig(["KeyZ", "KeyX", "KeyM", "Comma"]), new KeyConfig(["KeyZ", "KeyX", "Space", "KeyM", "Comma"]), new KeyConfig(["KeyZ", "KeyX", "KeyC", "KeyN", "KeyM", "Comma"]), new KeyConfig(["KeyZ", "KeyX", "KeyC", "Space", "KeyN", "KeyM", "Comma"]), new KeyConfig(["KeyZ", "KeyX", "KeyC", "ShiftLeft", "Space", "KeyN", "KeyM", "Comma"]), new KeyConfig(["KeyZ", "KeyX", "KeyC", "KeyV", "Space", "KeyB", "KeyN", "KeyM", "Comma"]), ], }; this.hitWindows = { marvelous: { hitWindow: 20, accValue: 100, judgeText: "Marvelous!!" }, perfect: { hitWindow: 40, accValue: 100, judgeText: "Perfect!" }, ok: { hitWindow: 60, accValue: 50, judgeText: "OK" }, bad: { hitWindow: 80, accValue: 0, judgeText: "Bad" }, miss: { hitWindow: 100, accValue: -20, judgeText: "Miss" } }; this.lastJudgement = this.hitWindows.marvelous; } get aspectRatio() { return this.context.canvas.width / this.context.canvas.height; } get inverseAspectRatio() { return this.context.canvas.height / this.context.canvas.width; } get beatT() { //Calculate milliseconds per beat from bpm let mspb = 60000 / this.currentChart.timingPoints[this.currentTimingSection].bpm; let t = (this.currentPlayTime - this.currentChart.timingPoints[this.currentTimingSection].time) % mspb / mspb; if (t < 0) { t = 0; } if (t > 1) { t = 1; } return t; } get currentKeyConfig() { let tempConfig = JSON.parse(JSON.stringify(this.config.keyConfigs[0])); if (this.currentChart !== null) { Object.assign(tempConfig, this.config.keyConfigs[this.currentChart.keyCount]); } return tempConfig; } UpdateFPS() { this.lastFPS = this.FPScounter; this.FPScounter = 0; this.fpsText.text = this.lastFPS; } IncrementCombo() { this.currentCombo++; this.comboText.Animate(); } HandleChange(e) { game.state = 2; GenerateSongList(); } HandleKeyDown(e) { switch (game.state) { case 0: switch (e.code) { case "Enter": game.directorySelector.click(); break; } break; case 1: break; case 2: break; case 3: switch (e.code) { case "ArrowRight": game.songWheel.relativeSongSelectionIndex = 1; break; case "ArrowLeft": game.songWheel.relativeSongSelectionIndex = -1; break; case "ArrowDown": game.songWheel.relativeDiffSelectionIndex = 1; break; case "ArrowUp": game.songWheel.relativeDiffSelectionIndex = -1; break; case "Enter": game.songWheel.Selecter(); break; } break; case 4: //We should only care about keys that are just pressed, not held down if (e.repeat) { return; } switch (e.code) { default: //Handle lane keys for (let i = 0; i < game.currentKeyConfig.keys.length; i++) { if (e.code == game.currentKeyConfig.keys[i]) { game.Judge(i); break; } } break; } break; case 5: break; } } HandleKeyUp(e) { switch (e.code) { default: if (game.state === 4) { for (let i = 0; i < game.currentKeyConfig.keys.length; i++) { if (e.code == game.currentKeyConfig.keys[i]) { game.JudgeLNEnd(i); break; } } } break; } } Judge(lane) { if (this.autoPlay) { return; } if (game.currentChart.noteList[lane].length > game.currentScore[lane].length) { if (game.currentChart.noteList[lane][game.currentScore[lane].length].type !== 2) { let hitError = Math.abs(game.currentChart.noteList[lane][game.currentScore[lane].length].time - game.currentPlayTime + game.judgeOffset); if (hitError < game.hitWindows.miss.hitWindow) { if (hitError < game.hitWindows.marvelous.hitWindow) { game.currentScore[lane].push(game.hitWindows.marvelous.accValue); game.lastJudgement = game.hitWindows.marvelous; game.IncrementCombo(); } else if (hitError < game.hitWindows.perfect.hitWindow) { game.currentScore[lane].push(game.hitWindows.perfect.accValue); game.lastJudgement = game.hitWindows.perfect; game.IncrementCombo(); } else if (hitError < game.hitWindows.ok.hitWindow) { game.currentScore[lane].push(game.hitWindows.ok.accValue); game.lastJudgement = game.hitWindows.ok; game.IncrementCombo(); } else if (hitError < game.hitWindows.bad.hitWindow) { game.currentScore[lane].push(game.hitWindows.bad.accValue); game.lastJudgement = game.hitWindows.bad; game.IncrementCombo(); } else { game.currentScore[lane].push(game.hitWindows.miss.accValue); game.lastJudgement = game.hitWindows.miss; game.currentCombo = 0; if (game.currentChart.noteList[lane][game.currentScore[lane].length].type === 2) { game.currentScore[lane].push(game.hitWindows.miss.accValue); } } game.judgementText.Animate(); } } } } JudgeLNEnd(lane) { if (this.autoPlay) { return; } if (game.currentChart.noteList[lane].length > game.currentScore[lane].length) { if (game.currentChart.noteList[lane][game.currentScore[lane].length].type === 2) { let hitError = Math.abs(game.currentChart.noteList[lane][game.currentScore[lane].length].time - game.currentPlayTime + game.judgeOffset); if (hitError < game.hitWindows.marvelous.hitWindow) { game.currentScore[lane].push(game.hitWindows.marvelous.accValue); game.lastJudgement = game.hitWindows.marvelous; game.IncrementCombo(); } else if (hitError < game.hitWindows.perfect.hitWindow) { game.currentScore[lane].push(game.hitWindows.perfect.accValue); game.lastJudgement = game.hitWindows.perfect; game.IncrementCombo(); } else if (hitError < game.hitWindows.ok.hitWindow) { game.currentScore[lane].push(game.hitWindows.ok.accValue); game.lastJudgement = game.hitWindows.ok; game.IncrementCombo(); } else if (hitError < game.hitWindows.bad.hitWindow) { game.currentScore[lane].push(game.hitWindows.bad.accValue); game.lastJudgement = game.hitWindows.bad; game.IncrementCombo(); } else { game.currentScore[lane].push(game.hitWindows.miss.accValue); game.lastJudgement = game.hitWindows.miss; game.currentCombo = 0; } } } } LoadConfiguration() { this.config = JSON.parse(JSON.stringify(this.defaultConfig)); Object.assign(this.config, JSON.parse(localStorage.getItem("gameConfig"))); } SaveConfiguration() { localStorage.setItem("gameConfig", JSON.stringify(game.config)); } Play(rate = 1.0) { //Copy original note lists to the working note lists game.currentChart.noteList = JSON.parse(JSON.stringify(game.currentChart.originalNoteList)); game.currentChart.scrollSpeedPoints = JSON.parse(JSON.stringify(game.currentChart.originalScrollSpeedPoints)); game.currentChart.timingPoints = JSON.parse(JSON.stringify(game.currentChart.originalTimingPoints)); //"this" won't work here either for some reason (or it might, i had an issue here earlier i fixed, haven't tested "this" yet) for (let i = 0; i < game.currentChart.noteList.length; i++) { for (let j = 0; j < game.currentChart.noteList[i].length; j++) { game.currentChart.noteList[i][j].time = game.currentChart.noteList[i][j].time / rate; } } for (let i = 0; i < game.currentChart.timingPoints.length; i++) { game.currentChart.timingPoints[i].time /= rate; game.currentChart.timingPoints[i].bpm *= rate; } for (let i = 0; i < game.currentChart.scrollSpeedPoints.length; i++) { game.currentChart.scrollSpeedPoints[i].time /= rate; } game.currentScore = []; game.playfield.nextNoteIndex = []; for (let i = 0; i < game.currentChart.keyCount; i++) { game.currentScore.push([]); game.playfield.nextNoteIndex.push(0); } game.currentCombo = 0; game.state = 4; game.playStartTime = performance.now() + this.playDelay + this.universalOffset; game.currentTimingSection = 0; if (game.currentAudio !== null) { game.currentAudio.pause(); game.currentAudio.playbackRate = rate; game.currentAudio.currentTime = 0; setTimeout(function () { game.currentAudio.play(); }, game.playDelay); } } Stop() { game.state = 3; } Update() { this.currentPlayTime = performance.now() - this.playStartTime; this.deltaTime = performance.now() - this.lastTime; this.lastTime = performance.now(); if (this.state !== 0) { this.objectLayers[0].skipDraw = true; if (this.state !== 2) { this.objectLayers[1].skipDraw = true; } } if (this.state === 4) { for (let i = 0; i < this.currentChart.keyCount; i++) { if (this.currentChart.noteList[i].length > this.currentScore[i].length) { // Auto-play if (this.autoPlay) { if (this.currentChart.noteList[i][this.currentScore[i].length].time <= this.currentPlayTime) { game.currentScore[i].push(game.hitWindows.marvelous.accValue); game.lastJudgement = game.hitWindows.marvelous; game.IncrementCombo(); game.judgementText.Animate(); } } else { // Check for missed notes if (this.currentChart.noteList[i][this.currentScore[i].length].time < this.currentPlayTime - this.hitWindows.miss.hitWindow) { this.currentScore[i].push(this.hitWindows.miss.accValue); this.lastJudgement = this.hitWindows.miss; this.currentCombo = 0; } } } //Check for end of chart if (this.currentChart.lastNote.time < this.currentPlayTime - 3000) { this.Stop(); } } //Update current timing section while (this.currentTimingSection < this.currentChart.timingPoints.length - 1) { if (this.currentChart.timingPoints[this.currentTimingSection + 1].time < this.currentPlayTime) { this.currentTimingSection++; } else { break; } } } //Updates!!//////////////////////////////////////////////////// for (let i = 0; i < this.objectLayers.length; i++) { this.objectLayers[i].Update(); } //Update FPS of last second if (this.nextFPSUpdate * 1000 < performance.now()) { this.UpdateFPS(); this.nextFPSUpdate++; } } Draw() { //Clear screen this.context.clearRect(0, 0, this.context.canvas.width, this.context.canvas.height); //Draws!!///////////////////////////////////////////////////// for (let i = 0; i < this.objectLayers.length; i++) { this.objectLayers[i].Draw(); } //Increment FPS counter this.FPScounter++; } Tick() { //I have no idea why I can't use "this" here game.Update(); game.Draw(); } Start() { //Load config objects this.LoadConfiguration(); //Setup objectlayers this.objectLayers = [ new Layer("startInstructionLayer", [ //Contains the text of the first screen. Probably better ways to do this but this works for now. new UIText("Welcome!", this.context.canvas.width / 2, 10, 0, -1, 90), new UIText("Instructions to start:", 10, 120, -1, -1, 40), new UIText("1. When prompted, choose a folder that contains your osu! beatmaps.", 10, 170, -1, -1, 40), new UIText("2. Wait for your files to get loaded into your browser. This will take up to couple of minutes.", 10, 250, -1, -1, 40), new UIText("Your browser might be unresponsive during the loading.", 10, 300, -1, -1, 40), new UIText("3. When the loading is done, the program will start parsing the files.", 10, 380, -1, -1, 40), new UIText("The progress of parsing is indicated by a progress bar.", 10, 430, -1, -1, 40), new UIText("Press Enter to start.", this.context.canvas.width / 2, this.context.canvas.height - 10, 0, 1, 90), ]), new Layer("songListGeneratorLayer", [new ProgressBar(new Rect(100, this.context.canvas.height - 100, this.context.canvas.width - 200, 60, true), "#FFFFFF")]), //Generator screen. Only contains the progress bar. new Layer("bgLayer", [new BGImage(null, false, false, true)]), //Background image layer new Layer("playfieldLayer", [new Playfield()]), //Playfield layer new Layer("playfieldUILayer", [new JudgementText(), new Combo()]), //Playfield UI layer (combo, judgement text) new Layer("songSelectUILayer", [new SongWheel()]), //Songwheel layer new Layer("debugUILayer", [new UIText("", 10, 10, -1, -1, 30, "Arial")]), //FPS text layer ]; //Set up easier to access references to objects this.bgImage = this.GetLayerByName("bgLayer").objectList[0]; this.playfield = this.GetLayerByName("playfieldLayer").objectList[0]; this.judgementText = this.GetLayerByName("playfieldUILayer").objectList[0]; this.comboText = this.GetLayerByName("playfieldUILayer").objectList[1]; this.songWheel = this.GetLayerByName("songSelectUILayer").objectList[0]; this.fpsText = this.GetLayerByName("debugUILayer").objectList[0]; this.fpsText.textStyle = "#FFFFFF"; //Add event listeners to key presses and releases addEventListener("keydown", this.HandleKeyDown); addEventListener("keyup", this.HandleKeyUp); this.directorySelector.addEventListener("change", this.HandleChange); //Intervals are unfortunately capped at 4 ms (250 intervals per second). There seems to be no workarounds for this this.tickInterval = setInterval(this.Tick); } GetLayerByName(name) { for (let i = 0; i < this.objectLayers.length; i++) { if (this.objectLayers[i].name == name) { return this.objectLayers[i]; } } return false; } async LoadSong(songIndex, chartI) { var chart = null; if (TypeOf(chartI) == "number") { chart = game.songList.getLooping(songIndex).chartList[chartI]; if (chart === undefined) { console.warn("No chart exists in chartList index " + chartI + " of song " + songIndex); } } else { for (let i = 0; i < game.songList.getLooping(songIndex).chartList.length; i++) { if (game.songList.getLooping(songIndex).chartList[i].chartName == chartI) { chart = game.songList.getLooping(songIndex).chartList[i]; break; } } if (chart === null) { console.warn("No chart named " + chart + " was found in song " + songIndex); return false; } } let object = this; let chartPromise = Chart.ParseOsuFile(chart.dataIndex); let bgPromise = new Promise(function (resolve, reject) { URL.revokeObjectURL(object.currentBG); if (chart.bgIndex !== null) { let tempBg = new Image(); tempBg.onload = function () { object.currentBG = tempBg; resolve(); } tempBg.src = URL.createObjectURL(game.directorySelector.files[chart.bgIndex]); } else { object.currentBG = null; resolve(); } }); let audioPromise = new Promise(function (resolve, reject) { URL.revokeObjectURL(object.currentAudio); if (chart.audioIndex !== null) { let tempAudio = new Audio(); //Because why would it be the same as above? tempAudio.onloadeddata = function () { object.currentAudio = tempAudio; resolve(); } tempAudio.src = URL.createObjectURL(game.directorySelector.files[chart.audioIndex]); } else { object.currentAudio = null; resolve(); } }); await bgPromise; await audioPromise; this.currentChart = await chartPromise; this.bgImage.UpdateBGImage(); game.currentScore = []; for (let i = 0; i < game.currentChart.keyCount; i++) { game.currentScore.push([]); } game.playfield.ReloadPlayfieldParameters(); } }
JavaScript
class BastionView extends OkitArtefactView { constructor(artefact=null, json_view) { if (!json_view.bastions) json_view.bastions = []; super(artefact, json_view); } // -- Reference get parent_id() { let primary_subnet = this.getJsonView().getSubnet(this.subnet_id); if (primary_subnet && primary_subnet.compartment_id === this.artefact.compartment_id) { return this.subnet_id; } else { return this.compartment_id; } } get parent() {return this.getJsonView().getSubnet(this.parent_id) ? this.getJsonView().getSubnet(this.parent_id) : this.getJsonView().getCompartment(this.parent_id);} // Direct Subnet Access get subnet_id() {return this.artefact.target_subnet_id;} set subnet_id(id) {this.artefact.target_subnet_id = id;} /* ** SVG Processing */ /* ** Property Sheet Load function */ loadProperties() { const self = this; $(jqId(PROPERTIES_PANEL)).load("propertysheets/bastion.html", () => {loadPropertiesSheet(self.artefact);}); } /* ** Load and display Value Proposition */ loadValueProposition() { $(jqId(VALUE_PROPOSITION_PANEL)).load("valueproposition/bastion.html"); } /* ** Static Functionality */ static getArtifactReference() { return Bastion.getArtifactReference(); } static getDropTargets() { return [Compartment.getArtifactReference(), Subnet.getArtifactReference()]; } }
JavaScript
class OffVideoTrackMenuItem extends VideoTrackMenuItem { constructor(player, options) { // Create pseudo track info // Requires options['kind'] options['track'] = { 'kind': options['kind'], 'player': player, 'label': options['kind'], 'default': false, 'selected': true }; // MenuItem is selectable options['selectable'] = true; super(player, options); } /** * Handle text track change * * @param {Object} event Event object * @method handleTracksChange */ handleTracksChange(event) { let tracks = this.player().videoTracks(); let selected = true; for (let i = 0, l = tracks.length; i < l; i++) { let track = tracks[i]; if (track['kind'] === 'main' && track['selected']) { selected = false; break; } } this.selected(selected); } }
JavaScript
class AllBins { constructor() { this.dataset = []; } add(value) { this.dataset.push(value); } data() { console.log('implement me!'); } len() { return this.dataset.length; } }
JavaScript
class UpdatedFrom extends ImmutableType { constructor(node) { const type = Map({ cms: { value: 'cms', label: 'CMS', key: 'select_option_fromcms', }, api: { value: 'api', label: 'API', key: 'select_option_fromapi', }, website: { value: 'website', label: 'Web', key: 'select_option_fromwebsite', }, mobileApp: { value: 'mobileApp', label: 'Mobile Application', key: 'select_option_frommobileapp', }, }); super(node); super.initialize({ type, isTransfer: true }); } }
JavaScript
class ViewConsumable { /** * Creates new ViewConsumable. */ constructor() { /** * Map of consumable elements. If {@link module:engine/view/element~Element element} is used as a key, * {@link module:engine/conversion/viewconsumable~ViewElementConsumables ViewElementConsumables} instance is stored as value. * For {@link module:engine/view/text~Text text nodes} and * {@link module:engine/view/documentfragment~DocumentFragment document fragments} boolean value is stored as value. * * @protected * @member {Map.<module:engine/conversion/viewconsumable~ViewElementConsumables|Boolean>} */ this._consumables = new Map(); } /** * Adds {@link module:engine/view/element~Element view element}, {@link module:engine/view/text~Text text node} or * {@link module:engine/view/documentfragment~DocumentFragment document fragment} as ready to be consumed. * * viewConsumable.add( p, { name: true } ); // Adds element's name to consume. * viewConsumable.add( p, { attributes: 'name' } ); // Adds element's attribute. * viewConsumable.add( p, { classes: 'foobar' } ); // Adds element's class. * viewConsumable.add( p, { styles: 'color' } ); // Adds element's style * viewConsumable.add( p, { attributes: 'name', styles: 'color' } ); // Adds attribute and style. * viewConsumable.add( p, { classes: [ 'baz', 'bar' ] } ); // Multiple consumables can be provided. * viewConsumable.add( textNode ); // Adds text node to consume. * viewConsumable.add( docFragment ); // Adds document fragment to consume. * * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `viewconsumable-invalid-attribute` when `class` or `style` * attribute is provided - it should be handled separately by providing actual style/class. * * viewConsumable.add( p, { attributes: 'style' } ); // This call will throw an exception. * viewConsumable.add( p, { styles: 'color' } ); // This is properly handled style. * * @param {module:engine/view/element~Element|module:engine/view/text~Text|module:engine/view/documentfragment~DocumentFragment} element * @param {Object} [consumables] Used only if first parameter is {@link module:engine/view/element~Element view element} instance. * @param {Boolean} consumables.name If set to true element's name will be included. * @param {String|Array.<String>} consumables.attributes Attribute name or array of attribute names. * @param {String|Array.<String>} consumables.classes Class name or array of class names. * @param {String|Array.<String>} consumables.styles Style name or array of style names. */ add(element, consumables) { let elementConsumables; // For text nodes and document fragments just mark them as consumable. if (element.is('text') || element.is('documentFragment')) { this._consumables.set(element, true); return; } // For elements create new ViewElementConsumables or update already existing one. if (!this._consumables.has(element)) { elementConsumables = new ViewElementConsumables(element); this._consumables.set(element, elementConsumables); } else { elementConsumables = this._consumables.get(element); } elementConsumables.add(consumables); } /** * Tests if {@link module:engine/view/element~Element view element}, {@link module:engine/view/text~Text text node} or * {@link module:engine/view/documentfragment~DocumentFragment document fragment} can be consumed. * It returns `true` when all items included in method's call can be consumed. Returns `false` when * first already consumed item is found and `null` when first non-consumable item is found. * * viewConsumable.test( p, { name: true } ); // Tests element's name. * viewConsumable.test( p, { attributes: 'name' } ); // Tests attribute. * viewConsumable.test( p, { classes: 'foobar' } ); // Tests class. * viewConsumable.test( p, { styles: 'color' } ); // Tests style. * viewConsumable.test( p, { attributes: 'name', styles: 'color' } ); // Tests attribute and style. * viewConsumable.test( p, { classes: [ 'baz', 'bar' ] } ); // Multiple consumables can be tested. * viewConsumable.test( textNode ); // Tests text node. * viewConsumable.test( docFragment ); // Tests document fragment. * * Testing classes and styles as attribute will test if all added classes/styles can be consumed. * * viewConsumable.test( p, { attributes: 'class' } ); // Tests if all added classes can be consumed. * viewConsumable.test( p, { attributes: 'style' } ); // Tests if all added styles can be consumed. * * @param {module:engine/view/element~Element|module:engine/view/text~Text|module:engine/view/documentfragment~DocumentFragment} element * @param {Object} [consumables] Used only if first parameter is {@link module:engine/view/element~Element view element} instance. * @param {Boolean} consumables.name If set to true element's name will be included. * @param {String|Array.<String>} consumables.attributes Attribute name or array of attribute names. * @param {String|Array.<String>} consumables.classes Class name or array of class names. * @param {String|Array.<String>} consumables.styles Style name or array of style names. * @returns {Boolean|null} Returns `true` when all items included in method's call can be consumed. Returns `false` * when first already consumed item is found and `null` when first non-consumable item is found. */ test(element, consumables) { const elementConsumables = this._consumables.get(element); if (elementConsumables === undefined) { return null; } // For text nodes and document fragments return stored boolean value. if (element.is('text') || element.is('documentFragment')) { return elementConsumables; } // For elements test consumables object. return elementConsumables.test(consumables); } /** * Consumes {@link module:engine/view/element~Element view element}, {@link module:engine/view/text~Text text node} or * {@link module:engine/view/documentfragment~DocumentFragment document fragment}. * It returns `true` when all items included in method's call can be consumed, otherwise returns `false`. * * viewConsumable.consume( p, { name: true } ); // Consumes element's name. * viewConsumable.consume( p, { attributes: 'name' } ); // Consumes element's attribute. * viewConsumable.consume( p, { classes: 'foobar' } ); // Consumes element's class. * viewConsumable.consume( p, { styles: 'color' } ); // Consumes element's style. * viewConsumable.consume( p, { attributes: 'name', styles: 'color' } ); // Consumes attribute and style. * viewConsumable.consume( p, { classes: [ 'baz', 'bar' ] } ); // Multiple consumables can be consumed. * viewConsumable.consume( textNode ); // Consumes text node. * viewConsumable.consume( docFragment ); // Consumes document fragment. * * Consuming classes and styles as attribute will test if all added classes/styles can be consumed. * * viewConsumable.consume( p, { attributes: 'class' } ); // Consume only if all added classes can be consumed. * viewConsumable.consume( p, { attributes: 'style' } ); // Consume only if all added styles can be consumed. * * @param {module:engine/view/element~Element|module:engine/view/text~Text|module:engine/view/documentfragment~DocumentFragment} element * @param {Object} [consumables] Used only if first parameter is {@link module:engine/view/element~Element view element} instance. * @param {Boolean} consumables.name If set to true element's name will be included. * @param {String|Array.<String>} consumables.attributes Attribute name or array of attribute names. * @param {String|Array.<String>} consumables.classes Class name or array of class names. * @param {String|Array.<String>} consumables.styles Style name or array of style names. * @returns {Boolean} Returns `true` when all items included in method's call can be consumed, * otherwise returns `false`. */ consume(element, consumables) { if (this.test(element, consumables)) { if (element.is('text') || element.is('documentFragment')) { // For text nodes and document fragments set value to false. this._consumables.set(element, false); } else { // For elements - consume consumables object. this._consumables.get(element).consume(consumables); } return true; } return false; } /** * Reverts {@link module:engine/view/element~Element view element}, {@link module:engine/view/text~Text text node} or * {@link module:engine/view/documentfragment~DocumentFragment document fragment} so they can be consumed once again. * Method does not revert items that were never previously added for consumption, even if they are included in * method's call. * * viewConsumable.revert( p, { name: true } ); // Reverts element's name. * viewConsumable.revert( p, { attributes: 'name' } ); // Reverts element's attribute. * viewConsumable.revert( p, { classes: 'foobar' } ); // Reverts element's class. * viewConsumable.revert( p, { styles: 'color' } ); // Reverts element's style. * viewConsumable.revert( p, { attributes: 'name', styles: 'color' } ); // Reverts attribute and style. * viewConsumable.revert( p, { classes: [ 'baz', 'bar' ] } ); // Multiple names can be reverted. * viewConsumable.revert( textNode ); // Reverts text node. * viewConsumable.revert( docFragment ); // Reverts document fragment. * * Reverting classes and styles as attribute will revert all classes/styles that were previously added for * consumption. * * viewConsumable.revert( p, { attributes: 'class' } ); // Reverts all classes added for consumption. * viewConsumable.revert( p, { attributes: 'style' } ); // Reverts all styles added for consumption. * * @param {module:engine/view/element~Element|module:engine/view/text~Text|module:engine/view/documentfragment~DocumentFragment} element * @param {Object} [consumables] Used only if first parameter is {@link module:engine/view/element~Element view element} instance. * @param {Boolean} consumables.name If set to true element's name will be included. * @param {String|Array.<String>} consumables.attributes Attribute name or array of attribute names. * @param {String|Array.<String>} consumables.classes Class name or array of class names. * @param {String|Array.<String>} consumables.styles Style name or array of style names. */ revert(element, consumables) { const elementConsumables = this._consumables.get(element); if (elementConsumables !== undefined) { if (element.is('text') || element.is('documentFragment')) { // For text nodes and document fragments - set consumable to true. this._consumables.set(element, true); } else { // For elements - revert items from consumables object. elementConsumables.revert(consumables); } } } /** * Creates consumable object from {@link module:engine/view/element~Element view element}. Consumable object will include * element's name and all its attributes, classes and styles. * * @static * @param {module:engine/view/element~Element} element * @returns {Object} consumables */ static consumablesFromElement(element) { const consumables = { element, name: true, attributes: [], classes: [], styles: [], }; const attributes = element.getAttributeKeys(); for (const attribute of attributes) { // Skip classes and styles - will be added separately. if (attribute == 'style' || attribute == 'class') { continue; } consumables.attributes.push(attribute); } const classes = element.getClassNames(); for (const className of classes) { consumables.classes.push(className); } const styles = element.getStyleNames(); for (const style of styles) { consumables.styles.push(style); } return consumables; } /** * Creates {@link module:engine/conversion/viewconsumable~ViewConsumable ViewConsumable} instance from * {@link module:engine/view/node~Node node} or {@link module:engine/view/documentfragment~DocumentFragment document fragment}. * Instance will contain all elements, child nodes, attributes, styles and classes added for consumption. * * @static * @param {module:engine/view/node~Node|module:engine/view/documentfragment~DocumentFragment} from View node or document fragment * from which `ViewConsumable` will be created. * @param {module:engine/conversion/viewconsumable~ViewConsumable} [instance] If provided, given `ViewConsumable` instance will be used * to add all consumables. It will be returned instead of a new instance. */ static createFrom(from, instance) { if (!instance) { instance = new ViewConsumable(from); } if (from.is('text')) { instance.add(from); return instance; } // Add `from` itself, if it is an element. if (from.is('element')) { instance.add(from, ViewConsumable.consumablesFromElement(from)); } if (from.is('documentFragment')) { instance.add(from); } for (const child of from.getChildren()) { instance = ViewConsumable.createFrom(child, instance); } return instance; } }
JavaScript
class ViewElementConsumables { /** * Creates ViewElementConsumables instance. * * @param {module:engine/view/node~Node|module:engine/view/documentfragment~DocumentFragment} from View node or document fragment * from which `ViewElementConsumables` is being created. */ constructor(from) { /** * @readonly * @member {module:engine/view/node~Node|module:engine/view/documentfragment~DocumentFragment} */ this.element = from; /** * Flag indicating if name of the element can be consumed. * * @private * @member {Boolean} */ this._canConsumeName = null; /** * Contains maps of element's consumables: attributes, classes and styles. * * @private * @member {Object} */ this._consumables = { attributes: new Map(), styles: new Map(), classes: new Map(), }; } /** * Adds consumable parts of the {@link module:engine/view/element~Element view element}. * Element's name itself can be marked to be consumed (when element's name is consumed its attributes, classes and * styles still could be consumed): * * consumables.add( { name: true } ); * * Attributes classes and styles: * * consumables.add( { attributes: 'title', classes: 'foo', styles: 'color' } ); * consumables.add( { attributes: [ 'title', 'name' ], classes: [ 'foo', 'bar' ] ); * * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `viewconsumable-invalid-attribute` when `class` or `style` * attribute is provided - it should be handled separately by providing `style` and `class` in consumables object. * * @param {Object} consumables Object describing which parts of the element can be consumed. * @param {Boolean} consumables.name If set to `true` element's name will be added as consumable. * @param {String|Array.<String>} consumables.attributes Attribute name or array of attribute names to add as consumable. * @param {String|Array.<String>} consumables.classes Class name or array of class names to add as consumable. * @param {String|Array.<String>} consumables.styles Style name or array of style names to add as consumable. */ add(consumables) { if (consumables.name) { this._canConsumeName = true; } for (const type in this._consumables) { if (type in consumables) { this._add(type, consumables[type]); } } } /** * Tests if parts of the {@link module:engine/view/node~Node view node} can be consumed. * * Element's name can be tested: * * consumables.test( { name: true } ); * * Attributes classes and styles: * * consumables.test( { attributes: 'title', classes: 'foo', styles: 'color' } ); * consumables.test( { attributes: [ 'title', 'name' ], classes: [ 'foo', 'bar' ] ); * * @param {Object} consumables Object describing which parts of the element should be tested. * @param {Boolean} consumables.name If set to `true` element's name will be tested. * @param {String|Array.<String>} consumables.attributes Attribute name or array of attribute names to test. * @param {String|Array.<String>} consumables.classes Class name or array of class names to test. * @param {String|Array.<String>} consumables.styles Style name or array of style names to test. * @returns {Boolean|null} `true` when all tested items can be consumed, `null` when even one of the items * was never marked for consumption and `false` when even one of the items was already consumed. */ test(consumables) { // Check if name can be consumed. if (consumables.name && !this._canConsumeName) { return this._canConsumeName; } for (const type in this._consumables) { if (type in consumables) { const value = this._test(type, consumables[type]); if (value !== true) { return value; } } } // Return true only if all can be consumed. return true; } /** * Consumes parts of {@link module:engine/view/element~Element view element}. This function does not check if consumable item * is already consumed - it consumes all consumable items provided. * Element's name can be consumed: * * consumables.consume( { name: true } ); * * Attributes classes and styles: * * consumables.consume( { attributes: 'title', classes: 'foo', styles: 'color' } ); * consumables.consume( { attributes: [ 'title', 'name' ], classes: [ 'foo', 'bar' ] ); * * @param {Object} consumables Object describing which parts of the element should be consumed. * @param {Boolean} consumables.name If set to `true` element's name will be consumed. * @param {String|Array.<String>} consumables.attributes Attribute name or array of attribute names to consume. * @param {String|Array.<String>} consumables.classes Class name or array of class names to consume. * @param {String|Array.<String>} consumables.styles Style name or array of style names to consume. */ consume(consumables) { if (consumables.name) { this._canConsumeName = false; } for (const type in this._consumables) { if (type in consumables) { this._consume(type, consumables[type]); } } } /** * Revert already consumed parts of {@link module:engine/view/element~Element view Element}, so they can be consumed once again. * Element's name can be reverted: * * consumables.revert( { name: true } ); * * Attributes classes and styles: * * consumables.revert( { attributes: 'title', classes: 'foo', styles: 'color' } ); * consumables.revert( { attributes: [ 'title', 'name' ], classes: [ 'foo', 'bar' ] ); * * @param {Object} consumables Object describing which parts of the element should be reverted. * @param {Boolean} consumables.name If set to `true` element's name will be reverted. * @param {String|Array.<String>} consumables.attributes Attribute name or array of attribute names to revert. * @param {String|Array.<String>} consumables.classes Class name or array of class names to revert. * @param {String|Array.<String>} consumables.styles Style name or array of style names to revert. */ revert(consumables) { if (consumables.name) { this._canConsumeName = true; } for (const type in this._consumables) { if (type in consumables) { this._revert(type, consumables[type]); } } } /** * Helper method that adds consumables of a given type: attribute, class or style. * * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `viewconsumable-invalid-attribute` when `class` or `style` * type is provided - it should be handled separately by providing actual style/class type. * * @private * @param {String} type Type of the consumable item: `attributes`, `classes` or `styles`. * @param {String|Array.<String>} item Consumable item or array of items. */ _add(type, item) { const items = isArray(item) ? item : [item]; const consumables = this._consumables[type]; for (const name of items) { if (type === 'attributes' && (name === 'class' || name === 'style')) { /** * Class and style attributes should be handled separately in * {@link module:engine/conversion/viewconsumable~ViewConsumable#add `ViewConsumable#add()`}. * * What you have done is trying to use: * * consumables.add( { attributes: [ 'class', 'style' ] } ); * * While each class and style should be registered separately: * * consumables.add( { classes: 'some-class', styles: 'font-weight' } ); * * @error viewconsumable-invalid-attribute */ throw new CKEditorError( 'viewconsumable-invalid-attribute: Classes and styles should be handled separately.', this ); } consumables.set(name, true); if (type === 'styles') { for (const alsoName of this.element.document.stylesProcessor.getRelatedStyles(name)) { consumables.set(alsoName, true); } } } } /** * Helper method that tests consumables of a given type: attribute, class or style. * * @private * @param {String} type Type of the consumable item: `attributes`, `classes` or `styles`. * @param {String|Array.<String>} item Consumable item or array of items. * @returns {Boolean|null} Returns `true` if all items can be consumed, `null` when one of the items cannot be * consumed and `false` when one of the items is already consumed. */ _test(type, item) { const items = isArray(item) ? item : [item]; const consumables = this._consumables[type]; for (const name of items) { if (type === 'attributes' && (name === 'class' || name === 'style')) { const consumableName = name == 'class' ? 'classes' : 'styles'; // Check all classes/styles if class/style attribute is tested. const value = this._test(consumableName, [...this._consumables[consumableName].keys()]); if (value !== true) { return value; } } else { const value = consumables.get(name); // Return null if attribute is not found. if (value === undefined) { return null; } if (!value) { return false; } } } return true; } /** * Helper method that consumes items of a given type: attribute, class or style. * * @private * @param {String} type Type of the consumable item: `attributes`, `classes` or `styles`. * @param {String|Array.<String>} item Consumable item or array of items. */ _consume(type, item) { const items = isArray(item) ? item : [item]; const consumables = this._consumables[type]; for (const name of items) { if (type === 'attributes' && (name === 'class' || name === 'style')) { const consumableName = name == 'class' ? 'classes' : 'styles'; // If class or style is provided for consumption - consume them all. this._consume(consumableName, [...this._consumables[consumableName].keys()]); } else { consumables.set(name, false); if (type == 'styles') { for (const toConsume of this.element.document.stylesProcessor.getRelatedStyles(name)) { consumables.set(toConsume, false); } } } } } /** * Helper method that reverts items of a given type: attribute, class or style. * * @private * @param {String} type Type of the consumable item: `attributes`, `classes` or , `styles`. * @param {String|Array.<String>} item Consumable item or array of items. */ _revert(type, item) { const items = isArray(item) ? item : [item]; const consumables = this._consumables[type]; for (const name of items) { if (type === 'attributes' && (name === 'class' || name === 'style')) { const consumableName = name == 'class' ? 'classes' : 'styles'; // If class or style is provided for reverting - revert them all. this._revert(consumableName, [...this._consumables[consumableName].keys()]); } else { const value = consumables.get(name); if (value === false) { consumables.set(name, true); } } } } }
JavaScript
class SelectedFile { constructor(file,senderid,linkheader){ this.file = file; this.senderid = senderid; this.linkheader = linkheader console.log("SelectedFile(), linkheader:",this.linkheader); } }
JavaScript
class CbcsDrmConfiguration { /** * Create a CbcsDrmConfiguration. * @property {object} [fairPlay] FairPlay configurations * @property {string} [fairPlay.customLicenseAcquisitionUrlTemplate] Template * for the URL of the custom service delivering licenses to end user players. * Not required when using Azure Media Services for issuing licenses. The * template supports replaceable tokens that the service will update at * runtime with the value specific to the request. The currently supported * token values are {AlternativeMediaId}, which is replaced with the value of * StreamingLocatorId.AlternativeMediaId, and {ContentKeyId}, which is * replaced with the value of identifier of the key being requested. * @property {boolean} [fairPlay.allowPersistentLicense] All license to be * persistent or not * @property {object} [playReady] PlayReady configurations * @property {string} [playReady.customLicenseAcquisitionUrlTemplate] * Template for the URL of the custom service delivering licenses to end user * players. Not required when using Azure Media Services for issuing * licenses. The template supports replaceable tokens that the service will * update at runtime with the value specific to the request. The currently * supported token values are {AlternativeMediaId}, which is replaced with * the value of StreamingLocatorId.AlternativeMediaId, and {ContentKeyId}, * which is replaced with the value of identifier of the key being requested. * @property {string} [playReady.playReadyCustomAttributes] Custom attributes * for PlayReady * @property {object} [widevine] Widevine configurations * @property {string} [widevine.customLicenseAcquisitionUrlTemplate] Template * for the URL of the custom service delivering licenses to end user players. * Not required when using Azure Media Services for issuing licenses. The * template supports replaceable tokens that the service will update at * runtime with the value specific to the request. The currently supported * token values are {AlternativeMediaId}, which is replaced with the value of * StreamingLocatorId.AlternativeMediaId, and {ContentKeyId}, which is * replaced with the value of identifier of the key being requested. */ constructor() { } /** * Defines the metadata of CbcsDrmConfiguration * * @returns {object} metadata of CbcsDrmConfiguration * */ mapper() { return { required: false, serializedName: 'CbcsDrmConfiguration', type: { name: 'Composite', className: 'CbcsDrmConfiguration', modelProperties: { fairPlay: { required: false, serializedName: 'fairPlay', type: { name: 'Composite', className: 'StreamingPolicyFairPlayConfiguration' } }, playReady: { required: false, serializedName: 'playReady', type: { name: 'Composite', className: 'StreamingPolicyPlayReadyConfiguration' } }, widevine: { required: false, serializedName: 'widevine', type: { name: 'Composite', className: 'StreamingPolicyWidevineConfiguration' } } } } }; } }
JavaScript
class QuizModelConverter { /** * Converte um Quiz para um QuizFullModel * @param {Quiz} quiz * @return {QuizFullModel} */ static toFullModel(quiz) { return new QuizFullModel( quiz.id, quiz.creatorId, quiz.title, quiz.isAnonymous, quiz.questions.map((q) => new QuestionModel( q.number, q.enunciation, q.type, q.items.map( (i) => new QuestionItemModel(i.number, i.enunciation))))); } }
JavaScript
class EventError extends Error { /** * Create an event error. * @param {Event} event - The event that caused the error. * @param {...any} params - Any other error params. */ constructor(event, ...params) { super(...params); if (Error.captureStackTrace) { Error.captureStackTrace(this, EventError); } this.event = event; } }
JavaScript
class FetchError extends Error { /** * Creat a fetch error. * @param {Response} response - The fetch response. * @param {...any} params - Any other Error params. */ constructor(response, ...params) { super(...params); if (Error.captureStackTrace) { Error.captureStackTrace(this, FetchError); } this.name = 'FetchError'; this.response = response; } }
JavaScript
class Navigation extends Component { state = { drawerOpen: false, }; handleDrawerOpen = () => { this.setState({ drawerOpen: true }); }; handleDrawerClose = () => { this.setState({ drawerOpen: false }); }; /** * Render method */ render() { return ( <div> <AppBar position="static"> <Toolbar> <IconButton color="contrast" aria-label="open drawer" onClick={() => this.handleDrawerOpen()} > <MenuIcon /> </IconButton> <Typography type="title" color="inherit" noWrap> worky </Typography> </Toolbar> </AppBar> <Drawer open={this.state.drawerOpen} onRequestClose={() => this.handleDrawerClose()}> <div> <ListItem button> <ListItemIcon> <InboxIcon /> </ListItemIcon> <ListItemText primary="Tasks" /> </ListItem> </div> </Drawer> </div> ); } }
JavaScript
class OccupancyColormaker extends Colormaker { constructor(params) { super(params); if (!params.scale) { this.parameters.scale = 'PuBu'; } if (!params.domain) { this.parameters.domain = [0.0, 1.0]; } this.occupancyScale = this.getScale(); } atomColor(a) { return this.occupancyScale(a.occupancy); } }
JavaScript
class BaseSocketController { /** * Binds a Socket instance to the controller methods. * * @param socket The socket instance */ static bindSocket(socket) { for (const action in this.methods) { if (this.methods.hasOwnProperty(action)) { socket.on(action, data => this.methods[action](socket, data)); } } } /** * Binds a Socket instance to this controller methods. This should not be * called directly, use the decorator instead. * * @see Listener * @param eventName The socket event name * @param eventName The socket action listener */ static bindEvent(eventName, action) { this.methods = this.methods || {}; this.methods[eventName] = action.bind(this); } }
JavaScript
class PublicKey { /** @param {ecurve.Point} public key */ constructor(Q) { this.Q = Q; } static fromBinary(bin) { return fromBuffer(new Buffer(bin, 'binary')); }; static fromBuffer(buffer) { return new PublicKey(ecurve.Point.decodeFrom(secp256k1, buffer)); }; toBuffer(compressed = this.Q.compressed) { return this.Q.getEncoded(compressed); } static fromPoint(point) { return new PublicKey(point); }; toUncompressed() { var buf = this.Q.getEncoded(false); var point = ecurve.Point.decodeFrom(secp256k1, buf); return PublicKey.fromPoint(point); } /** bts::blockchain::address (unique but not a full public key) */ toBlockchainAddress() { // address = Address.fromBuffer(@toBuffer()) // assert.deepEqual address.toBuffer(), h var pub_buf = this.toBuffer(); var pub_sha = hash.sha512(pub_buf); return hash.ripemd160(pub_sha); } /** Alias for {@link toPublicKeyString} */ toString(address_prefix = config.address_prefix) { return this.toPublicKeyString(address_prefix) } /** @arg {string} [address_prefix = config.address_prefix] @return {string} Full public key */ toPublicKeyString(address_prefix = config.address_prefix) { var pub_buf = this.toBuffer(); var checksum = hash.ripemd160(pub_buf); var addy = Buffer.concat([pub_buf, checksum.slice(0, 4)]); return address_prefix + base58.encode(addy); } /** {param1} public_key string {return} PublicKey */ static fromPublicKeyString(public_key, address_prefix = config.address_prefix) { try { var prefix = public_key.slice(0, address_prefix.length); assert.equal( address_prefix, prefix, `Expecting key to begin with ${address_prefix}, instead got ${prefix}`); public_key = public_key.slice(address_prefix.length); public_key = new Buffer(base58.decode(public_key), 'binary'); var checksum = public_key.slice(-4); public_key = public_key.slice(0, -4); var new_checksum = hash.ripemd160(public_key); new_checksum = new_checksum.slice(0, 4); assert.deepEqual(checksum, new_checksum, 'Checksum did not match'); return PublicKey.fromBuffer(public_key); } catch (e) { console.error('fromPublicKeyString', e); return null; } }; toAddressString(address_prefix = config.address_prefix) { var pub_buf = this.toBuffer(); var pub_sha = hash.sha512(pub_buf); var addy = hash.ripemd160(pub_sha); var checksum = hash.ripemd160(addy); addy = Buffer.concat([ addy, checksum.slice(0, 4) ]); return address_prefix + base58.encode(addy); } toPtsAddy() { var pub_buf = this.toBuffer(); var pub_sha = hash.sha256(pub_buf); var addy = hash.ripemd160(pub_sha); addy = Buffer.concat([ new Buffer([ 0x38 ]), addy ]); // version 56(decimal) var checksum = hash.sha256(addy); checksum = hash.sha256(checksum); addy = Buffer.concat([ addy, checksum.slice(0, 4) ]); return base58.encode(addy); } // <HEX> */ toByteBuffer() { var b = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN); this.appendByteBuffer(b); return b.copy(0, b.offset); } static fromHex(hex) { return fromBuffer(new Buffer(hex, 'hex')); }; toHex() { return this.toBuffer().toString('hex'); } static fromPublicKeyStringHex(hex) { return fromPublicKeyString(new Buffer(hex, 'hex')); }; }
JavaScript
class WasteWizardEntries extends React.Component { renderStar(favorite) { return ( <div className={`${styles.column} ${styles.star}`}> <FavoriteStar title={favorite.title} desc={favorite.desc} update={this.props.update} /> </div> ); } renderEntryTitle(title) { return <div className={`${styles.column} ${styles.left}`}>{title}</div>; } renderEntryDescription(desc) { return ( <DangerousHTML style={`${styles.column} ${styles.right}`} content={desc} /> ); } renderEntries() { if (this.props.entries !== undefined) { return this.props.entries.map((entry, key) => ( <div key={key} className={`${styles.row} ${styles.container}`}> {this.renderStar(entry)} {this.renderEntryTitle(entry.title)} {this.renderEntryDescription(entry.desc)} </div> )); } } render() { return <div>{this.renderEntries()}</div>; } }
JavaScript
class SessionScheme extends BaseScheme { constructor () { super() this._rememberTokenDuration = new Resetable(0) } /** * Reference to the value of `sessionKey` inside the config block. * Defaults to `adonis-auth` * * @attribute sessionKey * @readOnly * @return {String} */ get sessionKey () { return this._config.sessionKey || 'adonis-auth' } /** * Reference to the value of `rememberMeToken` inside the config block. * Defaults to `adonis-remember-token` * * @attribute rememberTokenKey * @readOnly * @return {String} */ get rememberTokenKey () { return this._config.rememberMeToken || 'adonis-remember-token' } /** * Set authentication session on user instance. Remember me cookie * will be saved if `rememberToken` and `duration` are provided. * * @method _setSession * * @param {Number|String} primaryKeyValue * @param {String} [rememberToken] * @param {Number} [duration] * * @returns {void} * * @private */ _setSession (primaryKeyValue, rememberToken, duration) { this._ctx.session.put(this.sessionKey, primaryKeyValue) /** * Set remember me cookie when token and duration is * defined */ if (rememberToken && duration) { this._ctx.response.cookie(this.rememberTokenKey, rememberToken, { expires: new Date(Date.now() + duration) }) } } /** * Removes the login session and remember me cookie. * * @method _removeSession * * @return {void} * * @private */ _removeSession () { this._ctx.session.forget(this.sessionKey) this._ctx.response.clearCookie(this.rememberTokenKey) } /** * Instruct login API to remember the user for a given * duration. Defaults to `5years`. * * This method must be called before `login`, `loginViaId` or * `attempt` method. * * @method remember * * @param {String|Number} [duration = 5y] * * @chainable * * @example * ```js * await auth.remember(true).login() * * // custom durating * await auth.remember('2y').login() * ``` */ remember (duration) { if (duration === true || duration === 1) { this._rememberTokenDuration.set(ms('5y')) } else if (typeof (duration) === 'string') { this._rememberTokenDuration.set(ms(duration)) } else if (duration !== 0 && duration !== false) { this._rememberTokenDuration.set(duration) } return this } /** * Attempt to login the user using `username` and `password`. An * exception will be raised when unable to find the user or * if password mis-matches. * * @method attempt * @async * * @param {String} uid * @param {String} password * * @return {Object} * * @throws {UserNotFoundException} If unable to find user with uid * @throws {PasswordMisMatchException} If password mismatches * * @example * ```js * try { * await auth.attempt(username, password) * } catch (error) { * // Invalid credentials * } * ``` */ async attempt (uid, password) { const user = await this.validate(uid, password, true) return this.login(user) } /** * Login the user using the user object. An exception will be * raised if the same user is already logged in. * * The exception is raised to improve your code flow, since your code * should never try to login a same user twice. * * @method login * * @param {Object} user * @async * * @return {Object} * * @example * ```js * try { * await auth.login(user) * } catch (error) { * // Unexpected error * } * ``` */ async login (user) { if (this.user) { throw GE .RuntimeException .invoke('Cannot login multiple users at once, since a user is already logged in', 500, 'E_CANNOT_LOGIN') } this.user = user /** * Make sure primary key value exists. */ if (!this.primaryKeyValue) { throw GE .RuntimeException .invoke('Cannot login user, since user id is not defined', 500, 'E_CANNOT_LOGIN') } /** * Set user remember token when remember token * duration is defined. */ const duration = this._rememberTokenDuration.pull() const rememberToken = duration ? uuid.v4() : null if (rememberToken) { await this._serializerInstance.saveToken(user, rememberToken, 'remember_token') } this._setSession(this.primaryKeyValue, rememberToken, duration) return user } /** * Login a user with their unique id. * * @method loginViaId * @async * * @param {Number|String} id * * @return {Object} * * @throws {UserNotFoundException} If unable to find user with id * * @example * ```js * try { * await auth.loginViaId(1) * } catch (error) { * // Unexpected error * } * ``` */ async loginViaId (id) { const user = await this._serializerInstance.findById(id) if (!user) { throw this.missingUserFor(id, this.primaryKey) } return this.login(user) } /** * Logout a user by removing the required cookies. Also remember * me token will be deleted from the tokens table. * * @method logout * @async * * @return {void} * * @example * ```js * await auth.logout() * ``` */ async logout () { if (this.user) { const rememberMeToken = this._ctx.request.cookie(this.rememberTokenKey) if (rememberMeToken) { await this._serializerInstance.deleteTokens(this.user, [rememberMeToken]) } this.user = null } this._removeSession() } /** * Check whether the user is logged in or not. If the user session * has been expired, but a valid `rememberMe` token exists, this * method will re-login the user. * * @method check * @async * * @return {Boolean} * * @throws {InvalidSessionException} If session is not valid anymore * * @example * ```js * try { * await auth.check() * } catch (error) { * // user is not logged * } * ``` */ async check () { if (this.user) { return true } const sessionValue = this._ctx.session.get(this.sessionKey) const rememberMeToken = this._ctx.request.cookie(this.rememberTokenKey) /** * Look for user only when there is a session * cookie */ if (sessionValue) { this.user = await this._serializerInstance.findById(sessionValue) } /** * If got user then return */ if (this.user) { return true } /** * Attempt to login the user when remeber me * token exists */ if (rememberMeToken) { const user = await this._serializerInstance.findByToken(rememberMeToken, 'remember_token') if (user) { await this.login(user) return true } } throw CE.InvalidSessionException.invoke() } /** * Same as {{#crossLink "SessionScheme/check:method"}}{{/crossLink}}, * but doesn't throw any exceptions. This method is useful for * routes, where login is optional. * * @method loginIfCan * @async * * @return {void} * * @example * ```js * await auth.loginIfCan() * ``` */ async loginIfCan () { if (this.user) { return } /** * Don't do anything when there is no session */ const sessionValue = this._ctx.session.get(this.sessionKey) const rememberMeToken = this._ctx.request.cookie(this.rememberTokenKey) /** * Don't attempt for anything when there is no session * value and no remember token */ if (!sessionValue && !rememberMeToken) { return } try { return await this.check() } catch (error) { // swallow exception } } /** * Login a user as a client. This is required when * you want to set the session on a request that * will reach the Adonis server. * * Adonis testing engine uses this method. * * @method clientLogin * @async * * @param {Function} headerFn - Method to set the header * @param {Function} sessionFn - Method to set the session * @param {Object} user - User to login * * @return {void} */ clientLogin (headerFn, sessionFn, user) { if (!user[this.primaryKey]) { throw new Error(`Cannot login user, since value for ${this.primaryKey} is missing`) } /** * Call the client method to set the session */ sessionFn(this.sessionKey, user[this.primaryKey]) } }
JavaScript
class ReceiveIterator extends PlanIterator { constructor(qpExec, step) { super(qpExec, step); if (step.pkFields) { this._dup = new Set(); this._dupMem = 0; this._dw = new DataWriter(); } if (step.sortSpecs) { const cmp = this._compareRes.bind(this); if (step.distKind === DistributionKind.ALL_SHARDS) { assert(qpExec._prepStmt && qpExec._prepStmt._topologyInfo); this._topoInfo = qpExec._prepStmt._topologyInfo; //seed empty shard results for sortingNext() loop this._spRes = new MinHeap(cmp, this._topoInfo.shardIds.map( _shardId => ({ _shardId }))); } else if (step.distKind === DistributionKind.ALL_PARTITIONS) { this._spRes = new MinHeap(cmp); this._allPartSort = true; this._allPartSortPhase1 = true; this._totalRows = 0; this._totalMem = 0; } } } _compareRes(res1, res2) { if (!hasLocalResults(res1)) { return hasLocalResults(res2) ? -1 : compPartShardIds(res1, res2); } if (!hasLocalResults(res2)) { return 1; } const compRes = compareRows(this, res1.rows[res1._idx], res2.rows[res2._idx], this._step.sortSpecs); return compRes ? compRes : compPartShardIds(res1, res2); } _getLimitFromMem() { const maxMem = this._qpExec.maxMem; const memPerRow = this._totalMem / this._totalRows; let limit = (maxMem - this._dupMem) / memPerRow; limit = Math.min(Math.floor(limit), 2048); if (limit <= 0) { throw this.memoryExceeded(`Cannot make another request because \ set memory limit of ${this._qpExec.maxMemMB} MB will be exceeded`); } return limit; } _setMemStats(res) { res._mem = sizeof(this, res.rows); this._totalRows += res.rows.length; this._totalMem += res._mem; this._qpExec.incMem(res._mem); } _validatePhase1Res(res) { //Check that we are really in sort phase 1 if (res._contAllPartSortPhase1 == null) { throw this.badProto('First response to ALL_PARTITIONS query is \ not a phase 1 response'); } if (res._contAllPartSortPhase1 && !res.continuationKey) { throw this.badProto('ALL_PARTITIONS query: missing continuation \ key needed to continue phase 1'); } if (!res._partIds) { res._partIds = []; } if (!res._partIds.length) { //Empty result case, do validation and return if (res.rows && res.rows.length) { throw this.badProto('ALL_PARTITIONS query phase 1: received \ rows but no partition ids'); } if (res._numResultsPerPartId && res._numResultsPerPartId.length) { throw this.badProto('ALL_PARTITIONS query phase 1: received \ numResultsPerPartitionId array but no partition ids'); } } else { const numResPerPartCnt = res._numResultsPerPartId ? res._numResultsPerPartId.length : 0; if (numResPerPartCnt !== res._partIds.length) { throw this.badProto(`ALL_PARTITIONS query phase 1: received \ mismatched arrays of partitionIds of length ${res._partIds.length} and \ numResultsPerPartitionId of length ${numResPerPartCnt}`); } } } //Group results by partition id and put them into the MinHeap _addPartResults(res) { let rowIdx = 0; for(let i = 0; i < res._partIds.length; i++) { const end = rowIdx + res._numResultsPerPartId[i]; if (end > res.rows.length) { throw this.badProto(`ALL PARTITIONS query phase 1: exceeded \ row count ${res.rows.length} while getting rows for partition id \ ${res._partId[i]}, expected index range [${rowIdx}, ${end})`); } const pRes = { rows: res.rows.slice(rowIdx, end), continuationKey: res._partContKeys[i], _partId: res._partIds[i], _idx: 0 }; this._spRes.add(pRes); this._setMemStats(pRes); rowIdx = end; } if (rowIdx !== res.rows.length) { throw this.badProto(`ALL PARTITIONS query phase 1: received per \ partition row counts (total ${rowIdx}) did not match total row count \ ${res.rows.length}`); } } //We have to convert PKs to string because JS Map and Set only do value //comparison for primitives, objects (etc. Buffer) are compared by //reference only _pk2MapKey(row) { this._dw.reset(); for(let fldName of this._step.pkFields) { BinaryProtocol.writeFieldValue(this._dw, row[fldName], this._qpExec.opt); } return resBuf2MapKey(this._dw.buffer); } _chkDup(row) { let key = this._pk2MapKey(row); if (this._dup.has(key)) { return true; } this._dup.add(key); const size = sizeof(this, key); this._dupMem += size; this._qpExec.incMem(size); return false; } _handleTopologyChange() { const topoInfo = this._qpExec._prepStmt._topologyInfo; if (this._topoInfo === topoInfo) { return; } //Shard ids removed in new topo let shardIds = this._topoInfo.shardIds.filter(shardId => !topoInfo.shardIds.includes(shardId)); if (shardIds.length) { this._spRes = this._spRes.filter(res => !shardIds.includes(res._shardId)); } //Shard ids added in new topo shardIds = topoInfo.shardIds.filter(shardId => !this._topoInfo.shardIds.includes(shardId)); for(let shardId of shardIds) { this._spRes.add({ shardId }); } this._topoInfo = topoInfo; } async _fetch(ck, shardId, limit) { assert(this._qpExec._req); const opt = this._qpExec._req.opt; const req = { api: this._qpExec._client.query, prepStmt: this._qpExec._prepStmt, opt: Object.assign({}, opt), _queryInternal: true, _shardId: shardId }; req.opt.continuationKey = ck; if (limit) { req.opt.limit = opt.limit ? Math.min(opt.limit, limit) : limit; } const res = await this._qpExec._client._execute(QueryOp, req); assert(Array.isArray(res.rows)); res._idx = 0; //initialize index to iterate res._shardId = shardId; //set shard id if any //We only make one internal request per user's query() call, //so the same consumed capacity will be returned to the user this._qpExec._cc = res.consumedCapacity; this._qpExec._fetchDone = true; assert(res._reachedLimit || !res.continuationKey || this._allPartSortPhase1); return res; } //Returns true if phase 1 is completed async _doAllPartSortPhase1() { //have to postpone phase 1 to the next query() call if (this._qpExec._fetchDone) { assert(this._qpExec._needUserCont); return false; } /* * Create and execute a request to get at least one result from * the partition whose id is specified in theContinuationKey and * from any other partition that is co-located with that partition. */ const res = await this._fetch(this._allPartSortPhase1CK); this._validatePhase1Res(res); this._allPartSortPhase1 = res._contAllPartSortPhase1; this._allPartSortPhase1CK = res.continuationKey; this._addPartResults(res); if (this._allPartSortPhase1) { //need more phase 1 results this._qpExec._needUserCont = true; return false; } return true; } async _simpleNext() { for(;;) { const res = this._res; if (res) { assert(res.rows && res._idx != null); if (res._idx < res.rows.length) { const row = res.rows[res._idx++]; if (this._dup && this._chkDup(row)) { continue; } this.result = row; return true; } if (!res.continuationKey) { return false; } } if (this._qpExec._fetchDone) { break; } this._res = await this._fetch(res ? res.continuationKey : null); } assert(this._res); if (this._res.continuationKey) { this._qpExec._needUserCont = true; } return false; } async _sortingFetch(fromRes) { let limit; if (this._allPartSort) { //We only limit number of rows for ALL_PARTITIONS query limit = this._getLimitFromMem(); //For ALL_PARTITIONS query, decrement memory from previous result this._qpExec.decMem(fromRes._mem); } let res; try { res = await this._fetch(fromRes.continuationKey, fromRes._shardId, limit); } catch(err) { if ((err instanceof NoSQLError) && err.retryable) { //add original result to retry later this._spRes.add(fromRes); } throw err; } this._spRes.add(res); if (this._allPartSort) { this._setMemStats(res); } else { this._handleTopologyChange(); } } _localNext(res) { const row = res.rows[res._idx]; res.rows[res._idx++] = null; //release memory for the row //more cached results or more remote results if (res._idx < res.rows.length || res.continuationKey) { this._spRes.add(res); } if (this._dup && this._chkDup(row)) { return false; } convertEmptyToNull(row); this.result = row; return true; } async _sortingNext() { if (this._allPartSortPhase1 && !(await this._doAllPartSortPhase1())) { return false; } let res; while ((res = this._spRes.pop())) { if (res.rows) { //we have real result assert(res._idx != null); if (res._idx < res.rows.length) { if (this._localNext(res)) { return true; } continue; } if (!res.continuationKey) { //no more results for this shard or partition continue; } } //remote fetch is needed if (this._qpExec._fetchDone) { //We limit to 1 fetch per query() call break; } else { await this._sortingFetch(res); } } if (res) { //another fetch needs to be performed on next query() call if (res.rows) { assert(res.continuationKey); //optimization to release array memory before next //query() call res.rows = null; } this._spRes.add(res); this._qpExec._needUserCont = true; } return false; } next() { return this._spRes ? this._sortingNext() : this._simpleNext(); } //should not be called reset() { throw this.illegalState( 'Reset should not be called for ReceiveIterator'); } }
JavaScript
class Board { /** * The Board constructor * @param {string} gameMap */ constructor(gameMap) { this.board = document.querySelector(".board"); this.walls = document.querySelector(".walls"); this.pos = Utils.getPosition(this.board); this.width = this.board.offsetWidth; this.height = this.board.offsetHeight; this.map = new Map(gameMap); this.matrix = []; this.starts = []; this.targets = []; this.listeners = {}; this.defaults = []; this.handler = this.clickListener.bind(this); this.hasStarted = false; this.board.addEventListener("click", this.handler); this.create(); } /** * Updates the inner started state when the game starts */ gameStarted() { this.hasStarted = true; } /** * Removes the event listener */ destroy() { this.board.removeEventListener("click", this.handler); } /** * Returns the Towers that will be built when starting this map * @return {Array.<{type: string, col: number, row: number, level: number}>} */ getInitialSetup() { return this.map.getInitialSetup(); } /** * Adds a new function for the board event listener * @param {string} name * @param {function(Event, DOMElement)} callback */ addListener(name, callback) { if (name === "default") { this.defaults.push(callback); } else { this.listeners[name] = callback; } } /** * The click listern in the Board DOM element * @param {Event} event */ clickListener(event) { let target = event.target.parentNode, type = target.dataset.type; if (this.listeners[type]) { this.listeners[type](event, target); } else { this.defaults.forEach(function (callback) { callback(event, target); }); } } /** * Creates the Board and Map */ create() { for (let i = 0; i < this.map.getPathsAmount(); i += 1) { this.starts[i] = []; this.targets[i] = []; } for (let i = 0; i < this.map.getRowsAmount(); i += 1) { this.matrix[i] = []; for (let j = 0; j < this.map.getColsAmount(); j += 1) { this.matrix[i][j] = this.map.getMatrixXY(i, j); this.addPaths(this.matrix[i][j], j, i); } } this.fixPaths(); this.createWalls(); } /** * Adds the paths starts and targets * @param {number} value * @param {number} row * @param {number} col */ addPaths(value, col, row) { if (this.map.isStart1(value)) { this.starts[0].push({ pos: [ col, row ], value: value }); } else if (this.map.isStart2(value)) { this.starts[1].push({ pos: [ col, row ], value: value }); } else if (this.map.isTarget1(value)) { this.targets[0].push({ pos: [ col, row ], value: value }); } else if (this.map.isTarget2(value)) { this.targets[1].push({ pos: [ col, row ], value: value }); } } /** * Fixes the paths starts and targets to have equal amount of starts and targets */ fixPaths() { for (let i = 0; i < this.starts.length; i += 1) { let j = 0; while (this.starts[i].length > this.targets[i].length) { if (j % 2 === 0) { this.targets[i].unshift(this.targets[i][j]); } else { this.targets[i].push(this.targets[i][this.targets[i].length - j]); } j += 1; } } } /** * Create the element for a Wall, Entrance or Exit */ createWalls() { let walls = this.map.getWalls(); this.walls.innerHTML = ""; for (let i = 1; i < walls.length; i += 1) { let el = document.createElement("div"); el.className = walls[i].cl; el.style.top = walls[i].top * this.map.getSquareSize() + "px"; el.style.left = walls[i].left * this.map.getSquareSize() + "px"; el.style.width = walls[i].width * this.map.getSquareSize() + "px"; el.style.height = walls[i].height * this.map.getSquareSize() + "px"; this.walls.appendChild(el); } } /** * Adds the given Tower to the board matrix and map setup, if required * @param {Tower} tower */ buildTower(tower) { let row = tower.getRow(), col = tower.getCol(), rows = row + tower.getSize(), cols = col + tower.getSize(); for (let i = row; i < rows; i += 1) { for (let j = col; j < cols; j += 1) { this.matrix[i][j] = tower.getID(); } } if (!this.hasStarted) { this.map.buildTower(tower); } } /** * Upgrades the level of the given Tower in the map setup, if required * @param {Tower} tower */ upgradeTower(tower) { if (!this.hasStarted) { this.map.upgradeTower(tower); } } /** * Removes the given Tower from the board matrix and from the map setup, if required * @param {Tower} tower */ sellTower(tower) { let row = tower.getRow(), col = tower.getCol(), rows = row + tower.getSize(), cols = col + tower.getSize(); for (let i = row; i < rows; i += 1) { for (let j = col; j < cols; j += 1) { this.matrix[i][j] = this.map.getNothingValue(); } } if (!this.hasStarted) { this.map.sellTower(tower); } } /** * Returns true if a Tower with the given size can be build in the given position * @param {number} row * @param {number} col * @param {number} size * @return {boolean} */ canBuild(row, col, size) { for (let i = row; i < row + size; i += 1) { for (let j = col; j < col + size; j += 1) { if (this.matrix[i] && this.matrix[i][j] !== this.map.getNothingValue()) { return false; } } } return true; } /** * Substracts 1 from the given position in the board matrix. We can then know how many mobs are in a given cell * @param {number} row * @param {number} col */ addMob(row, col) { if (this.matrix[row] && this.matrix[row][col] <= this.map.getNothingValue()) { this.matrix[row][col] -= 1; } } /** * Adds 1 to the given position in the board matrix * @param {number} row * @param {number} col */ removeMob(row, col) { if (this.matrix[row] && this.matrix[row][col] < this.map.getNothingValue()) { this.matrix[row][col] += 1; } } /** * Returns true if the given position corresponds to a border in the matrix * @param {number} row * @param {number} col * @return {boolean} */ isBorder(row, col) { return row < 1 || col < 1 || row > this.map.getRowsAmount() - 2 || col > this.map.getColsAmount() - 2; } /** * Returns true if the given position is not a border * @param {number} row * @param {number} col * @return {boolean} */ inMatrix(row, col, dim) { return !this.isBorder(row, col) && !this.isBorder(row + (dim || 0), col + (dim || 0)); } /** * Returns true if the given position is inside the board, including borders * @param {number} row * @param {number} col * @return {boolean} */ inBoard(row, col) { return row >= 0 && col >= 0 && row < this.map.getRowsAmount() && col < this.map.getColsAmount(); } /** * Returns true if the given position corresponds to a target * @param {number} row * @param {number} col * @return {boolean} */ isTarget(row, col) { return this.map.isTarget(this.matrix[row][col]); } /** * Returns true if the content at the given position is equal to the given value * @param {number} row * @param {number} col * @param {number} value * @return {boolean} */ isEqualTo(row, col, value) { return this.matrix[row][col] === value; } /** * Returns the content of a cell in the board at the given position * @param {number} row * @param {number} col * @return {number} */ getContent(row, col) { return this.matrix[row][col]; } /** * Returns the position of the board in the DOM * @return {{top: number, left: number}} */ getPos() { return this.pos; } /** * Returns the board matrix * @return {Array.<Array.<number>>} */ getMatrix() { return this.matrix; } /** * Returns the positions of the starting cells * @return {Array.<Array.<Array.<number>>>} */ getStarts() { return this.starts; } /** * Returns the positions of the target cells * @return {Array.<Array.<Array.<number>>>} */ getTargets() { return this.targets; } /** * Returns the size of a square in the map * @return {boolean} */ getSize() { return this.map.getSquareSize(); } /** * Returns the ID for the first Tower * @return {number} */ getTowerStart() { return this.map.getTowerStart(); } /** * Returns the value for Nothing in the board * @return {number} */ getNothingValue() { return this.map.getNothingValue(); } /** * Returns the ID for the Walls in the board * @return {number} */ getWallsValue() { return this.map.getWallsValue(); } }
JavaScript
class Scroller extends PureComponent { callIfAnimating = callback => (...args) => { // eslint-disable-line react/sort-comp if (!this.props.getUserScrollActive()) { callback(...args); } } breakScrollAnimation = condition => condition && this.props.breakScrollAnimation(); /* Break scroll animation on user scroll events: keydown (arrow up, arrow down) mouse wheel, handleMouseDown: click on scrollbar. Once the scroll animation has been cancelled - there is no point allowing these to be called again until the next animation starts. */ handleMouseDown = this.callIfAnimating( e => this.breakScrollAnimation(targetIsScrollBar(e.clientX, this.elem)) ); handleWheel = this.callIfAnimating(() => this.breakScrollAnimation(true)); handleKeyDown = this.callIfAnimating( e => this.breakScrollAnimation(e.keyCode === 38 || e.keyCode === 40) ); getClassName = (className) => { const initClassName = {}; initClassName[styles.scroller] = true; return classnames({ ...initClassName, }, className); } getScrollTop = () => (this.elem ? this.elem.scrollTop : null); setScrollTop = (val) => { if (this.elem && val >= 0) { this.elem.scrollTop = val; } return null; }; render() { const { className, children, style } = this.props; return ( <div className={this.getClassName(className)} onKeyDown={this.handleKeyDown} onMouseDown={this.handleMouseDown} onWheel={this.handleWheel} ref={(elemArg) => { this.elem = elemArg; }} role="presentation" style={style} > { children } </div> ); } }
JavaScript
class CYK { /** * @param {JSON} rules - rules which define the grammar */ constructor(rules) { // Store the original copy for the rules so that // this instance can be used multiple times on different words this._originalRules = rules; // More rules are created using the base rules // and stored in this property this._rules = {}; // Remember the previous word which was used // so that if the current word is the same // the previous values can be returned avoiding recalculations this._previousWord; this._substrings; } /** * @returns a boolean asserting whether the given word is accepted by the given grammar or not * @param {String} word - the word to check */ checkWord(word) { this._cyk(word); // Is there a rule for our word ? return this._rules[word] !== undefined; } /** * Applies the CYK algorithm for a given word * @param {String} word - the word to apply the CYK algorithm for */ _cyk(word) { // If it is the same word as last time if (this._previousWord == word) { // Just use the previous values return; } // Use the original rules this._rules = this._originalRules.clone(); // Get all word's substrings this._substrings = this._getAllSubstrings(word); // Skip the single character substrings for (let i = word.length; i < this._substrings.length; i++) { const substring = this._substrings[i]; // Split each substring into key - value pairs const substringPair = this._splitWord(substring); for (const key in substringPair) { const cartesianProduct = this._cartesianProduct(key, substringPair[key]); // Go through all of the elements of the cartesian product for (const element of cartesianProduct) { // If there is a rule for the element if (this._rules[element]) { // If there is no rule for the substring if (!this._rules[substring]) { // Create an empty one this._rules[substring] = []; } // For each element inside the rule for the cartesianProduct's element for (const elem of this._rules[element]) { // If the element was not already added to the rule if (this._rules[substring].indexOf(elem) == -1) { // Add it to the rule this._rules[substring].push(elem); } } } } } } // Remember the last used word this._previousWord = word; } /** * @param {String} word - the word to apply the CYK algorithm for * @returns {Array<Array<String>>} the CYK matrix for a given word and grammar */ getMatrix(word) { this._cyk(word); let matrix = [[]]; let rawLength = word.length; let rawIndex = 0; let columnIndex = 0; for (const substring of this._substrings) { matrix[rawIndex].push(this._rules[substring]); if (++columnIndex % rawLength == 0) { rawLength--; rawIndex++; columnIndex = 0; matrix.push([]); } } matrix.pop(); return matrix; } /** * @param {String} word - the word to get the substrings from * @returns {Array<String>} all of the word's substrings */ _getAllSubstrings(word) { let substrings = []; for (let i = 1; i < word.length; i++) { for (let start = 0; start + i <= word.length; start++) { substrings.push(word.substring(start, start + i)); } } substrings.push(word); return substrings; } /** * Splits a word into key - value piars where either the key * or the value is at least one character long * @param {String} word - the word to split * @returns {JSON} key - value pairs that when concatenated, * they reconstruct the given word */ _splitWord(word) { let splits = {}; for (let i = 1; i < word.length; i++) { splits[word.substring(0, i)] = word.substring(i, word.length); } return splits; } /** * @param {String} word1 - product's first word * @param {String} word2 - product's second word * @returns {Array<string>} the cartesian product for the given words */ _cartesianProduct(word1, word2) { if (!word1 || !word2) { return []; } if (!this._rules[word1] || !this._rules[word2]) { return []; } let cartesianProduct = new Set(); for (const transition1 of this._rules[word1]) { for (const transition2 of this._rules[word2]) { cartesianProduct.add(transition1 + transition2); } } return cartesianProduct; } }
JavaScript
class Watcher extends qx.event.Emitter { constructor() { super(); // Keeps track of the files and directories that are being watched this.watches = {}; } /** * Add a new file or directory to the watch list. If it already exists it is being ignored * */ add(name) { if (this.watches[name]) return; var w = fs.watch(name, (event, filename) => { console.info("Node changed " + name + " event " + event + " fileName " + filename); this.emit("change", name); }); this.watches[name] = w; } /** * Add a new directory to the watch list. If it already exists it is being ignored. * Only rename type of events are being propgated (so new files or deletes). * * Files within a directory changing size etc are not propagated. * */ addDir(name) { if (this.watches[name]) return; var w = fs.watch(name, (event, filename) => { console.info("Node changed " + name + " event " + event + " fileName " + filename); if (event === "rename") this.emit("change", name); }); this.watches[name] = w; } /** * Remove an entry from the watch list (file or directory) * * @param name The filepath that no longer should be watched * */ remove(name) { var w = this.watches[name]; if (w) { w.close(); delete this.watches[name]; } } }
JavaScript
class Ide extends qx.event.Emitter { constructor() { super(); this.projects = []; this.debug = false; this.lastEntry = {}; this.catsHomeDir = process.cwd(); this.loadMessages(); this.config = this.loadPreferences(); this.recentProjects = Array.isArray(this.config.projects) ? this.config.projects : []; this.icons = this.loadIconsMap(); this.themes = this.loadThemes(); window.onpopstate = (data) => { if (data && data.state) this.goto(data.state); }; this.loadShortCuts(); qx.theme.manager.Meta.getInstance().setTheme(cats.theme.Default); this.setTheme(this.config.theme); } loadShortCuts() { try { var fileName = Cats.OS.File.join(this.catsHomeDir, "resource/shortcuts.json"); var c = Cats.OS.File.readTextFile(fileName); var shortCutSets = JSON.parse(c); var os = "linux"; if (Cats.OS.File.isWindows()) { os = "win"; } else if (Cats.OS.File.isOSX()) { os = "osx"; } var shortCuts = shortCutSets[os]; for (var shortCut in shortCuts) { var commandName = shortCuts[shortCut]; var cmd = new qx.ui.command.Command(shortCut); cmd.addListener("execute", (function (commandName) { Cats.Commands.commandRegistry.runCommand(commandName); }).bind(null, commandName)); } } catch (err) { console.error("Error loading shortcuts" + err); } } /** * Load the icons map from the file. */ loadIconsMap() { return JSON.parse(Cats.OS.File.readTextFile("resource/icons.json")); } /** * Load the themes from the file. */ loadThemes() { return JSON.parse(Cats.OS.File.readTextFile("resource/themes.json")); } setFont(size = 14) { var theme = cats.theme.Font; theme.fonts.default.size = size; var manager = qx.theme.manager.Font.getInstance(); // @TODO hack to make Qooxdoo aware there is a change manager.setTheme(cats.theme.Font16); // manager.setTheme(null); manager.setTheme(theme); this.emit("config"); } setColors(colorTheme = cats.theme.ColorDark) { var manager = qx.theme.manager.Color.getInstance(); qx.theme.manager.Color.getInstance().setTheme(colorTheme); // document.body.style.color = "black"; document.body.style.color = colorTheme.colors.text; /* var colors = manager.getTheme()["colors"]; var jcolors = JSON.stringify(colors.__proto__,null,4); IDE.console.log(jcolors); var editor = new Gui.Editor.SourceEditor(); IDE.editorTabView.addEditor(editor,{row:0, column:0}); editor.setContent(jcolors); editor.setMode("ace/mode/json"); IDE.console.log(jcolors); for (var c in colors) { var dyn = manager.isDynamic(c); IDE.console.log(c + ":" + colors[c] + ":" + dyn); } */ } /** * Load all the locale dependend messages from the message file. * * @param locale The locale you want to retrieve the messages for */ loadMessages(locale = "en") { const fileName = "resource/locales/" + locale + "/messages.json"; const messages = JSON.parse(Cats.OS.File.readTextFile(fileName)); let map = {}; for (var key in messages) { map[key] = messages[key].message; } qx.locale.Manager.getInstance().setLocale(locale); qx.locale.Manager.getInstance().addTranslation(locale, map); } goto(entry) { const hash = entry.hash; this.lastEntry = entry; const page = qx.core.ObjectRegistry.fromHashCode(hash); if (page) Cats.IDE.editorTabView.navigateToPage(page, entry.pos); } /** * Initialize the different modules within the IDE. * */ init(rootDoc) { Cats.Commands.init(); const layouter = new Cats.Gui.Layout(rootDoc); rootDoc.setBackgroundColor("transparent"); layouter.layout(this); this.menuBar = new Cats.Gui.MenuBar(); // @TODO fix for 1.4 this.initFileDropArea(); this.handleCloseWindow(); } /** * Add an entry to the history list */ addHistory(editor, pos) { const page = this.editorTabView.getPageForEditor(editor); if ((this.lastEntry.hash === page.toHashCode()) && (this.lastEntry.pos === pos)) return; var entry = { hash: page.toHashCode(), pos: pos }; history.pushState(entry, page.getLabel()); } getCurrentTheme() { const themeName = this.config.theme || "default"; var theme = this.themes.find((theme) => { return theme.name == themeName; }); if (theme) return theme; return this.getDefaultTheme(); } getThemes() { return this.themes; } /** * Attach the drag n' drop event listeners to the document * * @author LordZardeck <[email protected]> */ initFileDropArea() { // Listen onto file drop events document.documentElement.addEventListener("drop", (ev) => this.acceptFileDrop(ev), false); // Prevent the browser from redirecting to the file document.documentElement.addEventListener("dragover", (event) => { event.stopPropagation(); event.preventDefault(); event.dataTransfer.dropEffect = "copy"; // Explicitly show this is a copy. }, false); } /** * Process the file and open it inside a new ACE session * * @param event {DragEvent} * @author LordZardeck <[email protected]> */ acceptFileDrop(event) { event.stopPropagation(); event.preventDefault(); // Loop over each file dropped. More than one file // can be added at a time const files = event.dataTransfer.files; for (var i = 0; i < files.length; i++) { var path = files[i].path; Cats.FileEditor.OpenEditor(path); } } /** * Load the projects and files that were open last time before the * IDE was closed. */ restorePreviousProjects() { console.info("restoring previous project and sessions."); if (this.config.projects && this.config.projects.length) { const projectDir = this.config.projects[0]; this.setDirectory(projectDir); if (this.config.sessions) { console.info("Found previous sessions: ", this.config.sessions.length); this.config.sessions.forEach((session) => { try { var editor = Cats.Editor.Restore(session.type, JSON.parse(session.state)); if (editor) Cats.IDE.editorTabView.addEditor(editor); } catch (err) { console.error("error " + err); } }); } // this.project.refresh(); } } getDefaultTheme() { return { "name": "default", "background": "linear-gradient(to right, #666 , #888)", "color": "Color", "ace": "ace/theme/eclipse" }; } findTheme(name) { return this.themes.find((theme) => { return theme.name == name; }); } /** * CLose the current project */ close() { this.projects.forEach((project) => project.close()); this.fileNavigator.clear(); this.todoList.clear(); this.problemResult.clear(); this.console.clear(); this.projects = []; } /** * Get a set of default preferences. */ getDefaultPreferences() { var defaultConfig = { version: "2.0", theme: "default", fontSize: 13, editor: { rightMargin: 100 }, locale: "en", rememberOpenFiles: false, sessions: [], projects: [] }; return defaultConfig; } /** * Load the configuration for the IDE. If there is no configuration * found or it is an old version, use the default one to use. */ loadPreferences() { var configStr = localStorage[Ide.STORE_KEY]; if (configStr) { try { var config = JSON.parse(configStr); if (config.version === "2.0") return config; } catch (err) { console.error("Error during parsing config " + err); } } return this.getDefaultPreferences(); } /** * Set the theme for this IDE */ setTheme(name = "default") { var theme = this.findTheme(name); if (!theme) { Cats.IDE.console.error(`Theme with name ${name} not found.`); theme = this.getDefaultTheme(); } this.theme = theme; const colorTheme = cats.theme[theme.color] || cats.theme.Color; document.body.style.background = theme.background; var manager = qx.theme.manager.Color.getInstance(); qx.theme.manager.Color.getInstance().setTheme(colorTheme); document.body.style.color = colorTheme.colors.text; this.setFont(this.config.fontSize); this.emit("config"); } /** * Update the configuration for IDE * */ updatePreferences(config) { this.config = config; this.setTheme(config.theme); this.emit("config", config); this.savePreferences(); } /** * Persist the current IDE configuration to a file */ savePreferences() { try { let config = this.config; config.version = "2.0"; config.sessions = []; config.projects = this.recentProjects; this.editorTabView.getEditors().forEach((editor) => { var state = editor.getState(); if ((state !== null) && (editor.getType())) { config.sessions.push({ state: JSON.stringify(state), type: editor.getType() }); } }); var configStr = JSON.stringify(config); localStorage[Ide.STORE_KEY] = configStr; } catch (err) { console.error(err); } } /** * For a given file get the first project it belongs to. */ getProject(fileName) { for (var x = 0; x < this.projects.length; x++) { let project = this.projects[x]; if (project.hasScriptFile(fileName)) return project; } } /** * Find all possible TSConfig files from a certain base directory. */ getTSConfigs(dir) { var configs = glob.sync(dir + "/" + "**/tsconfig*.json"); if (configs.length === 0) { this.console.log("No tsconfig file found, creating a default one"); let fileName = Cats.OS.File.PATH.join(dir, "tsconfig.json"); Cats.OS.File.writeTextFile(fileName, "{}"); configs = [fileName]; } return configs; } refresh() { this.setDirectory(this.rootDir, false); } /** * Set the working directory. CATS will start scanning the directory and subdirectories for * tsconfig files and for each one found create a TS Project. If none found it will create * the default config file and use that one instead. * * @param directory the directory of the new project * @param refreshFileNavigator should the fileNavigator also be refreshed. */ setDirectory(directory, refreshFileNavigator = true) { this.projects = []; this.rootDir = Cats.OS.File.PATH.resolve(this.catsHomeDir, directory); var index = this.recentProjects.indexOf(directory); if (index !== -1) { this.recentProjects.splice(index, 1); } this.recentProjects.push(directory); var name = Cats.OS.File.PATH.basename(directory); document.title = "CATS | " + name; if (refreshFileNavigator) this.fileNavigator.setRootDir(directory); var configs = this.getTSConfigs(directory); configs.forEach((config) => { let path = Cats.OS.File.PATH.resolve(config); path = Cats.OS.File.switchToForwardSlashes(path); let p = new Cats.Project(path); this.projects.push(p); }); } handleCloseWindow() { // Catch the close of the windows in order to save any unsaved changes var win = Cats.getNWWindow(); win.on("close", function () { var doClose = () => { Cats.IDE.savePreferences(); this.close(true); }; try { if (Cats.IDE.editorTabView.hasUnsavedChanges()) { var dialog = new Cats.Gui.ConfirmDialog("There are unsaved changes!\nDo you really want to continue?"); dialog.onConfirm = doClose; dialog.show(); } else { doClose(); } } catch (err) { } // lets ignore this }); } /** * Quit the application. If there are unsaved changes ask the user if they really * want to quit. */ quit() { var GUI = Cats.getNWGui(); var doClose = () => { this.savePreferences(); GUI.App.quit(); }; if (this.editorTabView.hasUnsavedChanges()) { var dialog = new Cats.Gui.ConfirmDialog("There are unsaved files!\nDo you really want to quit?"); dialog.onConfirm = doClose; dialog.show(); } else { doClose(); } } }
JavaScript
class TSWorkerProxy { constructor() { this.messageId = 0; this.registry = {}; // Create a new webworker this.worker = new Worker("lib/tsworker.js"); this.initWorker(); } /** * Stop the worker and release any resources maintained. */ stop() { this.worker.terminate(); } /** * Get the diagnostic messages for a file */ getErrors(fileName, cb) { this.perform("getErrors", fileName, cb); } getNavigateToItems(search, cb) { this.perform("getNavigateToItems", search, cb); } getAllDiagnostics(cb) { this.perform("getAllDiagnostics", cb); } getTodoItems(cb) { this.perform("getTodoItems", cb); } getFormattedTextForRange(sessionName, range, cb) { this.perform("getFormattedTextForRange", sessionName, range, cb); } getDefinitionAtPosition(sessionName, cursor, cb) { this.perform("getDefinitionAtPosition", sessionName, cursor, cb); } getTypeDefinitionAtPosition(sessionName, cursor, cb) { this.perform("getTypeDefinitionAtPosition", sessionName, cursor, cb); } findRenameLocations(fileName, position, findInStrings, findInComments, cb) { this.perform("findRenameLocations", fileName, position, findInStrings, findInComments, cb); } getCrossReference(type, sessionName, cursor, cb) { this.perform("getCrossReference", type, sessionName, cursor, cb); } compile(cb) { this.perform("compile", cb); } getScriptOutline(sessionName, cb) { this.perform("getScriptOutline", sessionName, cb); } getInfoAtPosition(name, docPos, cb) { this.perform("getInfoAtPosition", name, docPos, cb); } getRenameInfo(name, docPos, cb) { this.perform("getRenameInfo", name, docPos, cb); } insertDocComments(fileName, position, cb) { this.perform("insertDocComments", fileName, position, cb); } getObjectModel(cb) { this.perform("getObjectModel", cb); } setConfigFile(path, content) { this.perform("setConfigFile", path, content, null); } addScript(fileName, content) { this.perform("addScript", fileName, content, null); } updateScript(fileName, content) { this.perform("updateScript", fileName, content, null); } getCompletions(fileName, cursor, cb) { this.perform("getCompletions", fileName, cursor, cb); } initialize() { this.perform("initialize", null); } /** * Invoke a method on the worker using JSON-RPC message structure */ perform(method, ...data) { var handler = data.pop(); this.messageId++; var message = { id: this.messageId, method: method, params: data }; this.worker.postMessage(message); console.info("Send message: " + message.method); if (handler) { this.registry[this.messageId] = handler; } } /** * Clear any pending handlers */ clear() { this.registry = {}; } /** * Setup the message communication with the worker */ initWorker() { // Setup the message handler this.worker.onmessage = (e) => { var msg = e.data; if (msg.error) { console.error("Got error back !!! "); console.error(msg.error.stack); } // @TODO handle exceptions better and call callback var id = msg.id; if (id) { var handler = this.registry[id]; if (handler) { delete this.registry[id]; handler(msg.error, msg.result); } } else { var params = msg.params; var methodName = msg.method; if (methodName && (methodName === "setBusy")) { Cats.IDE.statusBar.setBusy(params[0], params[1]); } if (methodName && (methodName === "console")) { console[params[0]](params[1]); } } }; } }
JavaScript
class Project extends qx.event.Emitter { /** * Create a new project. */ constructor(tsConfigFile) { super(); this.tsConfigFile = tsConfigFile; this.tsfiles = []; this.projectDir = Cats.OS.File.PATH.dirname(tsConfigFile); this.refresh(); // @TODO optimize only refresh in case of changes this.refreshInterval = setInterval(() => { this.refreshTodoList(); }, 60000); } readConfigFile(fileName) { try { return tsconfig.readFileSync(fileName); } catch (err) { Cats.IDE.console.error(`Error reading config file ${fileName}`); } } /** * Save the project configuration */ updateConfig(config) { return; /* this.settings.value = config; this.emit("config", config); if (this.config.tslint.useLint) this.linter = new Linter(this); this.settings.store(); this.iSense.setSettings(this.config.compiler, this.config.codeFormat); */ } refreshTodoList() { this.iSense.getTodoItems((err, data) => { Cats.IDE.todoList.setData(data, this); }); } /** * Close the project */ close() { if (Cats.IDE.editorTabView.hasUnsavedChanges()) { var dialog = new Cats.Gui.ConfirmDialog("You have some unsaved changes that will get lost.\n Continue anyway ?"); dialog.onConfirm = () => { this._close(); }; } else { this._close(); } } /** * Close the project without confirmation. * (Internal, do not use directly) */ _close() { // Lets clear the various output panes. Cats.IDE.editorTabView.closeAll(); Cats.IDE.fileNavigator.clear(); Cats.IDE.outlineNavigator.clear(); Cats.IDE.problemResult.clear(); Cats.IDE.todoList.clear(); if (this.iSense) this.iSense.stop(); clearInterval(this.refreshInterval); Cats.IDE.projects = []; } /** * Show the errors on a project level */ validate(verbose = true) { this.iSense.getAllDiagnostics((err, data) => { if (data) { Cats.IDE.problemResult.setData(data, this); if ((data.length === 0) && verbose) { Cats.IDE.console.log(`Project ${this.name} has no errors`); } } }); } /** * Build this project either with the built-in capabilities or by calling * an external build tool. */ build() { Cats.IDE.console.log("Start building project " + this.name + " ..."); if (this.config.customBuild && this.config.customBuild.command) { // IDE.resultbar.selectOption(2); var cmd = this.config.customBuild.command; var options = this.config.customBuild.options || { cwd: null }; if (!options.cwd) { options.cwd = this.projectDir; } var child = Cats.OS.File.runCommand(cmd, options); } else { this.iSense.compile((err, data) => { this.showCompilationResults(data); if (data.errors && (data.errors.length > 0)) return; var files = data.outputFiles; files.forEach((file) => { if (!Cats.OS.File.PATH.isAbsolute(file.name)) { file.name = Cats.OS.File.PATH.join(this.projectDir, file.name); file.name = Cats.OS.File.PATH.normalize(file.name); } Cats.OS.File.writeTextFile(file.name, file.text); }); Cats.IDE.console.log("Done building project " + this.name + "."); }); } } /** * Refresh the project and loads required artifacts * again from the filesystem to be fully in sync */ refresh() { this.config = this.readConfigFile(this.tsConfigFile); Cats.IDE.console.log(`Found TypeScript project configuration at ${this.tsConfigFile} containing ${this.config.files.length} files`); this.tsfiles = this.config.files; this.name = this.config.name || Cats.OS.File.PATH.basename(this.projectDir); if (!this.config.compilerOptions) this.config.compilerOptions = {}; if (this.iSense) this.iSense.stop(); this.iSense = new Cats.TSWorkerProxy(); var content = JSON.stringify(this.config); this.iSense.setConfigFile(this.tsConfigFile, content); if (!this.config.compilerOptions.noLib) { let libFile; switch (this.config.compilerOptions.target) { case "es6": case "ES6": libFile = "resource/typings/lib.es6.d.ts"; break; case "es7": case "ES7": libFile = "resource/typings/lib.es7.d.ts"; break; default: libFile = "resource/typings/lib.d.ts"; break; } var fullName = Cats.OS.File.join(Cats.IDE.catsHomeDir, libFile); var libdts = Cats.OS.File.readTextFile(fullName); this.addScript(fullName, libdts); } this.loadProjectSourceFiles(); this.refreshTodoList(); } /** * Compile without actually saving the resulting files */ trialCompile() { this.iSense.compile((err, data) => { this.showCompilationResults(data); }); } showCompilationResults(data) { if (data.errors && (data.errors.length > 0)) { Cats.IDE.problemResult.setData(data.errors, this); return; } Cats.IDE.problemResult.clear(); Cats.IDE.console.log("Successfully generated " + data.outputFiles.length + " file(s)."); } /** * Run this project either with the built-in capabilities (only for web apps) or by calling * and external command (for example node). */ run() { if (this.config.customRun && this.config.customRun.command) { const cmd = this.config.customRun.command; var options = this.config.customRun.options || { cwd: null }; if (!options.cwd) { options.cwd = this.projectDir; } Cats.OS.File.runCommand(cmd, options); } else { const GUI = require('nw.gui'); const main = this.config.main; if (!main) { alert("Please specify the main html file or customRun in the project settings."); return; } const startPage = this.getStartURL(); console.info("Opening file: " + startPage); const win2 = GUI.Window.open(startPage, { toolbar: true, // nodejs: true, // "new-instance": true, webkit: { "page-cache": false } }); } } /** * Get the URL for running the project */ getStartURL() { const url = Cats.OS.File.join(this.projectDir, this.config.main); return "file://" + url; } hasScriptFile(fileName) { return this.tsfiles.indexOf(fileName) > -1; } updateScript(fullName, content) { this.iSense.updateScript(fullName, content); } addScript(fullName, content) { this.iSense.addScript(fullName, content); if (!this.hasScriptFile(fullName)) this.tsfiles.push(fullName); } getScripts() { return this.tsfiles; } /** * Load the source files that are part of this project. Typically * files ending with ts, tsx or js. */ loadProjectSourceFiles() { this.config.files.forEach((file) => { try { var fullName = Cats.OS.File.switchToForwardSlashes(file); // OS.File.join(this.projectDir, file); var content = Cats.OS.File.readTextFile(fullName); this.addScript(fullName, content); } catch (err) { console.error("Got error while handling file " + fullName); console.error(err); } }); } }
JavaScript
class FileEditor extends Editor { constructor(filePath) { super(); if (filePath) this.setFilePath(Cats.OS.File.switchToForwardSlashes(filePath)); } updateFileInfo() { if (this.filePath) { try { var prop = Cats.OS.File.getProperties(this.filePath); this.set("info", prop); } catch (err) { } } } setFilePath(filePath) { this.filePath = filePath; this.label = Cats.OS.File.PATH.basename(this.filePath); this.updateFileInfo(); } /** * Which type of files does this editor supports for editing. */ static SupportsFile(fileName) { return false; } /** * @override */ getDescription() { return this.filePath || this.label; } /** * Check for a given file which default editor should be opened and return an instance * of that. */ static CreateEditor(fileName) { if (Cats.Gui.Editor.ImageEditor.SupportsFile(fileName)) return new Cats.Gui.Editor.ImageEditor(fileName); if (Cats.Gui.Editor.SourceEditor.SupportsFile(fileName)) return new Cats.Gui.Editor.SourceEditor(fileName); return null; } /** * Open an existing file editor or if it doesn't exist yet create * a new FileEditor suitable for the file selected. */ static OpenEditor(fileName, pos = { row: 0, column: 0 }) { let editor; // var pages: Gui.EditorPage[] = []; const pages = Cats.IDE.editorTabView.getPagesForFile(fileName); if (!pages.length) { editor = this.CreateEditor(fileName); if (editor) { Cats.IDE.editorTabView.addEditor(editor, pos); } else { var dialog = new Cats.Gui.ConfirmDialog("No suitable editor found for this file type, open with default editor?"); dialog.onConfirm = () => { var editor = new Cats.Gui.Editor.SourceEditor(fileName); Cats.IDE.editorTabView.addEditor(editor, pos); }; dialog.show(); } } else { editor = pages[0].editor; Cats.IDE.editorTabView.setSelection([pages[0]]); if (editor.moveToPosition) editor.moveToPosition(pos); } return editor; } }
JavaScript
class IdeCommands { static init(registry) { registry(Commands.COMMANDNAME.ide_quit, quit); registry(Commands.COMMANDNAME.ide_toggle_toolbar, () => toggleView(Cats.IDE.toolBar)); registry(Commands.COMMANDNAME.ide_toggle_statusbar, () => toggleView(Cats.IDE.statusBar)); registry(Commands.COMMANDNAME.ide_toggle_result, () => toggleView(Cats.IDE.resultPane)); registry(Commands.COMMANDNAME.ide_toggle_context, () => toggleView(Cats.IDE.contextPane)); registry(Commands.COMMANDNAME.ide_configure, configureIde); registry(Commands.COMMANDNAME.ide_history_next, next); registry(Commands.COMMANDNAME.ide_history_prev, prev); registry(Commands.COMMANDNAME.ide_theme, setTheme); } }
JavaScript
class AutoCompletePopup extends qx.ui.popup.Popup { /** * Create the new Autocomplete popup window */ constructor() { super(new qx.ui.layout.Flow()); this.cursorPos = 0; // this.setDecorator(null); this.setPadding(0, 0, 0, 0); this.setMargin(0, 0, 0, 0); this.setWidth(300); this.setHeight(200); // this.setBackgroundColor("transparent"); this.createList(); this.initHandler(); this.changeListener = (ev) => this.onChange(ev); this.addListener("disappear", this.hidePopup, this); } /** * Create the list that hold the completions */ createList() { var self = this; // Creates the list and configures it var list = new qx.ui.list.List(null).set({ scrollbarX: "off", selectionMode: "single", // height: 280, width: 300, labelPath: "caption", iconPath: "meta", iconOptions: { converter: (data) => { var icon = Cats.IDE.icons.kind[data] || Cats.IDE.icons.kind["default"]; return icon; } } }); list.setDecorator(null); list.setBackgroundColor("transparent"); this.add(list); this.list = list; this.list.addListener("click", this.insertSelectedItem.bind(this)); } /** * Get the text between cursor and start */ getInputText() { var cursor = this.sourceEditor.getPosition(); var text = this.sourceEditor.getLine(cursor.row).slice(0, cursor.column); // console.log("input text:" + text); var matches = text.match(/[a-zA-Z_0-9\$]*$/); if (matches && matches[0]) return matches[0]; else return ""; } match_strict(text, completion) { if (!text) return true; if (completion.indexOf(text) === 0) return true; return false; } match_forgiven(text, completion) { if (!text) return true; if (completion.indexOf(text) > -1) return true; return false; } /** * Filter the available completions based on the users text input * so far. */ updateFilter() { var text = this.getInputText(); if (text) text = text.toLowerCase(); var matchFunction = this.match_forgiven; if (Cats.IDE.config.editor.completionMode) { var methodName = "match_" + Cats.IDE.config.editor.completionMode; if (this[methodName]) matchFunction = this[methodName]; } var lastItem = this.listModel.getItem(this.listModel.getLength() - 1); var counter = 0; this.filtered = []; var delegate = { filter: (data) => { var value = data.getCaption().toLowerCase(); var result = matchFunction(text, value); if (result) this.filtered.push(data); if (data === lastItem) { // IDE.console.log("filtered items: " + this.filtered.length); // @TODO check for selected var selection = this.list.getSelection().getItem(0); if (!(selection && (this.filtered.indexOf(selection) > -1))) { this.cursorPos = 0; this.moveCursor(0); } } return result; } }; this.list.setDelegate(delegate); } moveCursor(row) { this.cursorPos += row; var len = this.filtered.length - 1; if (this.cursorPos > len) this.cursorPos = len; if (this.cursorPos < 0) this.cursorPos = 0; var item = this.filtered[this.cursorPos]; this.list.resetSelection(); this.list.getSelection().push(item); // IDE.console.log("Cursor:" + this.cursorPos); } insertSelectedItem() { var current = this.list.getSelection().getItem(0); ; if (current) { var inputText = this.getInputText(); for (var i = 0; i < inputText.length; i++) { this.editor.remove("left"); } if (current.getMeta() === "snippet") { this.editor.insertSnippet(current.getSnippet()); } else { this.editor.insert(current.getValue()); } } this.hidePopup(); } /** * Setup the the keybindings so when typed the key events go to the * popup window and not the editor. */ initHandler() { this.handler = new HashHandler(); this.handler.bindKey("Home", () => { this.moveCursor(-10000); }); this.handler.bindKey("End", () => { this.moveCursor(10000); }); this.handler.bindKey("Down", () => { this.moveCursor(1); }); this.handler.bindKey("PageDown", () => { this.moveCursor(10); }); this.handler.bindKey("Up", () => { this.moveCursor(-1); }); this.handler.bindKey("PageUp", () => { this.moveCursor(-10); }); this.handler.bindKey("Esc", () => { this.hidePopup(); }); this.handler.bindKey("Return|Tab", () => { this.insertSelectedItem(); }); } isExecutable(kind) { if (kind === "method" || kind === "function" || kind === "constructor") return true; return false; } /** * Show the popup and make sure the keybindings are in place. * */ showPopup(completions) { if (this.list.isSeeable() || (completions.length === 0)) return; var cursor = this.editor.getCursorPosition(); var coords = this.editor.renderer.textToScreenCoordinates(cursor.row, cursor.column); this.editor.keyBinding.addKeyboardHandler(this.handler); this.moveTo(coords.pageX, coords.pageY + 20); var rawData = []; completions.forEach((completion) => { var extension = ""; if (this.isExecutable(completion.meta)) { completion.caption += "()"; if (completion.value) completion.value += "()"; } if ((!completion.caption) && (!completion.name)) { console.log(completion); return; } rawData.push({ caption: completion.caption || completion.name, meta: completion.meta, snippet: completion.snippet || "", value: completion.value || "" }); }); this.listModel = qx.data.marshal.Json.createModel(rawData, false); this.list.setModel(this.listModel); this.updateFilter(); this.cursorPos = 0; this.moveCursor(0); this.show(); // this.editor.commands.on('afterExec', (e) => { this.onChange2(e);}); this.editor.getSession().on("change", this.changeListener); } /** * Hide the popup and remove all the keybindings */ hidePopup() { this.editor.keyBinding.removeKeyboardHandler(this.handler); this.exclude(); this.editor.getSession().removeListener('change', this.changeListener); this.editor.focus(); } /** * Determines if the specified character may be part of a JS identifier */ static isJsIdentifierPart(ch) { ch |= 0; //tell JIT that ch is an int return ch >= 97 && ch <= 122 //a-z || ch >= 65 && ch <= 90 //A-Z || ch >= 48 && ch <= 57 //0-9 || ch === 95 //_ || ch === 36 //$ || ch > 127; //non-ASCII letter. Not accurate, but good enough for autocomplete } onChange2(e) { var key = e.args || ""; alert(key); if ((key == null) || (!AutoCompletePopup.isJsIdentifierPart(key.charCodeAt(0)))) { this.hidePopup(); return; } this.updateFilter(); } /** * Check wether the typed character is reason to stop * the code completion */ onChange(ev) { var key = ev.lines.join(""); if ((key == null) || (!AutoCompletePopup.isJsIdentifierPart(key.charCodeAt(0)))) { this.hidePopup(); return; } // hack to get the cursor updated before we render // TODO find out how to force update without a timer delay setTimeout(() => { this.updateFilter(); }, 0); } /** * This method is called from the editor to start the code completion process. */ complete(memberCompletionOnly, sourceEditor, editor) { this.editor = editor; this.sourceEditor = sourceEditor; var session = editor.getSession(); var pos = editor.getCursorPosition(); var line = session.getLine(pos.row); var prefix = Editor.retrievePrecedingIdentifier(line, pos.column); // this.base = session.doc.createAnchor(pos.row, pos.column - prefix.length); var matches = []; var completers = Editor.getCompleters(sourceEditor, memberCompletionOnly); var total = completers.length; completers.forEach((completer, i) => { completer.getCompletions(editor, session, pos, prefix, (err, results) => { total--; if (!err) matches = matches.concat(results); if (total === 0) { this.showPopup(matches); } }); }); } }
JavaScript
class SourceEditor extends Cats.FileEditor { constructor(fileName) { super(fileName); this.status = {}; this.unsavedChanges = false; this.pendingWorkerUpdate = false; this.createEditSession(); this.createWidget(); this.contextMenu = new Editor.SourceEditorContextMenu(this); this.widget.setContextMenu(this.contextMenu); Cats.IDE.on("config", () => { this.configureEditor(); }); } get project() { return Cats.IDE.getProject(this.filePath); } createWidget() { var widget = new qx.ui.core.Widget(); widget.setDecorator(null); widget.setFont(null); widget.setAppearance(null); widget.addListenerOnce("appear", () => { var container = widget.getContentElement().getDomElement(); container.style.lineHeight = "normal"; this.aceEditor = this.createAceEditor(container); this.configureEditor(); if (this.pendingPosition) this.moveToPosition(this.pendingPosition); }, this); widget.addListener("appear", () => { // this.session.activate(); this.informWorld(); if (this.aceEditor) this.aceEditor.focus(); }); // session.on("errors", this.showErrors, this); widget.addListener("resize", () => { this.resizeHandler(); }); this.widget = widget; } createEditSession() { this.editSession = new Editor.EditSession(this); this.editSession.on("changeAnnotation", () => { this.emit("errors", this.editSession.getMaxAnnotationLevel()); }); this.editSession.on("changeOverwrite", () => { this.informWorld(); }); this.editSession.on("change", () => { this.setHasUnsavedChanges(true); }); } getAceEditor() { return this.aceEditor; } setHasUnsavedChanges(value) { if (value === this.unsavedChanges) return; this.unsavedChanges = value; this.emit("changed", value); } getState() { return { fileName: this.filePath, pos: this.getPosition() }; } static RestoreState(state) { var editor = new SourceEditor(state.fileName); editor.moveToPosition(state.pos); return editor; } executeCommand(name, ...args) { switch (name) { case 'toggleInvisibles': this.aceEditor.setShowInvisibles(!this.aceEditor.getShowInvisibles()); break; case 'formatText': this.formatText(); break; default: this.aceEditor.execCommand(name); break; } } /** * Is the file being part of a tsconfig project. This is used to determine * wehter all type of features specific to TS will be enabled. * */ hasProject() { return this.project != null; } getType() { return registryEntryName; } static SupportsFile(fileName) { var name = Cats.OS.File.PATH.basename(fileName); var mode = modelist.getModeForPath(name); if (mode && mode.supportsFile(name)) return true; return false; } /** * Get the Qooxdoo Widget that can be added to the parent */ getLayoutItem() { return this.widget; } formatText() { var r = null; if (this.hasProject()) { var range = this.aceEditor.selection.getRange(); if (!range.isEmpty()) r = { start: range.start, end: range.end }; this.project.iSense.getFormattedTextForRange(this.filePath, r, (err, result) => { if (!err) this.setContent(result); }); } } setMode(mode) { this.editSession.setMode(mode); this.informWorld(); } /** * Replace the current content of this editor with new content and indicate * wether the cursor should stay on the same position * */ setContent(content, keepPosition = true) { var pos; if (keepPosition) pos = this.getPosition(); this.editSession.setValue(content); if (pos) this.moveToPosition(pos); } /** * Update the configuaration of the editor. * */ configureEditor() { var config = Cats.IDE.config; if (config.fontSize) this.aceEditor.setFontSize(config.fontSize + "px"); if (config.editor && config.editor.rightMargin) this.aceEditor.setPrintMarginColumn(config.editor.rightMargin); if (Cats.IDE.theme) this.aceEditor.setTheme(Cats.IDE.theme.ace); } /** * Inform the world about current status of the editor * */ informWorld() { var value = this.getPosition(); var label = (value.row + 1) + ":" + (value.column + 1); this.status = { overwrite: this.editSession.getOverwrite(), mode: Cats.OS.File.PATH.basename(this.editSession.mode).toUpperCase(), position: label }; this.emit("status", this.status); } replace(range, content) { this.editSession.replace(range, content); } getLine(row = this.getPosition().row) { return this.editSession.getLine(row); } /** * Get the content of the editor * */ getContent() { return this.editSession.getValue(); } /** * Make sure the ace editor is resized when the Qooxdoo container is resized. * */ resizeHandler() { if (!this.widget.isSeeable()) { this.addListenerOnce("appear", () => { this.resizeEditor(); }); } else { this.resizeEditor(); } } resizeEditor() { setTimeout(() => { this.aceEditor.resize(); }, 100); } clearSelectedTextMarker() { if (this.selectedTextMarker) { this.editSession.removeMarker(this.selectedTextMarker); this.selectedTextMarker = null; } } addTempMarker(r) { this.clearSelectedTextMarker(); var range = new Range(r.start.row, r.start.column, r.end.row, r.end.column); this.selectedTextMarker = this.editSession.addMarker(range, "ace_selected-word", "text"); } moveToPosition(pos) { if (!this.aceEditor) { this.pendingPosition = pos; } else { this.aceEditor.clearSelection(); super.moveToPosition(pos); if (pos) { if (pos.start) { this.aceEditor.moveCursorToPosition(pos.start); } else { this.aceEditor.moveCursorToPosition(pos); } } setTimeout(() => { this.aceEditor.centerSelection(); if (pos && pos.start) this.addTempMarker(pos); }, 100); } } /** * Get the position of the cursor within the content. * */ getPosition() { if (this.aceEditor) return this.aceEditor.getCursorPosition(); } /** * Get the Position based on mouse x,y coordinates */ getPositionFromScreenOffset(ev) { var x = ev.offsetX; var y = ev.offsetY; // var cursor = this.aceEditor.renderer.pixelToScreenCoordinates(x, y); // IDE.console.log(JSON.stringify(cursor)); // var docPos2 = this.aceEditor.getSession().screenToDocumentPosition(cursor.row, cursor.col); // IDE.console.log(JSON.stringify(docPos2)); var r = this.aceEditor.renderer; // var offset = (x + r.scrollLeft - r.$padding) / r.characterWidth; var offset = (x - r.$padding) / r.characterWidth; // @BUG: Quickfix for strange issue with top var correction = r.scrollTop ? 7 : 0; var row = Math.floor((y + r.scrollTop - correction) / r.lineHeight); var col = Math.round(offset); var docPos = this.aceEditor.getSession().screenToDocumentPosition(row, col); // IDE.console.log(JSON.stringify(docPos)); return docPos; } /** * Perform code autocompletion. */ showAutoComplete(memberCompletionOnly = false) { // Any pending changes that are not yet send to the worker? if (this.hasProject()) { this.project.iSense.updateScript(this.filePath, this.getContent()); } autoCompletePopup.complete(memberCompletionOnly, this, this.aceEditor); } liveAutoComplete(e) { if (!this.hasProject()) return; var text = e.args || ""; if ((e.command.name === "insertstring") && (text === ".")) { this.showAutoComplete(true); } } /** * Create a new isntance of the ACE editor and append is to a dom element * */ createAceEditor(rootElement) { var editor = ace.edit(rootElement); editor["$blockScrolling"] = Infinity; // surpresses ACE warning editor.setSession(this.editSession); editor.on("changeSelection", () => { this.clearSelectedTextMarker(); this.informWorld(); }); new Editor.TSTooltip(this); new Gui.TSHelper(this, this.editSession); editor.commands.on('afterExec', (e) => { this.liveAutoComplete(e); }); editor.setOptions({ enableSnippets: true }); editor.commands.addCommands([ { name: "autoComplete", bindKey: { win: "Ctrl-Space", mac: "Ctrl-Space" }, exec: () => { this.showAutoComplete(); } }, { name: "gotoDeclaration", bindKey: { win: "F12", mac: "F12" }, exec: () => { this.contextMenu.gotoDeclaration(); } }, { name: "save", bindKey: { win: "Ctrl-S", mac: "Command-S" }, exec: () => { this.save(); } } ]); return editor; } hasUnsavedChanges() { return this.unsavedChanges; } /** * Persist this session to the file system. This overrides the NOP in the base class */ save() { this.editSession.save(); } }
JavaScript
class ImageEditor extends Cats.FileEditor { constructor(fileName) { super(fileName); this.canvas = new qx.ui.embed.Canvas(); this.set("status", { mode: "IMAGE" }); this.loadImage(fileName); this.createContextMenu(); } getLayoutItem() { return this.canvas; } executeCommand(name, ...args) { return false; } save() { } loadImage(url) { var image = new Image(); image.onload = () => { this.drawImage(image); }; url = Cats.OS.File.switchToForwardSlashes(url); image.src = "file://" + url; } getState() { return { fileName: this.filePath }; } getType() { return registryEntryName; } resizeIfRequired(image) { if (image.width > this.canvas.getCanvasWidth()) { this.canvas.setCanvasWidth(image.width); } if (image.height > this.canvas.getCanvasHeight()) { this.canvas.setCanvasHeight(image.height); } } drawImage(image) { this.resizeIfRequired(image); this.canvas.getContext2d().drawImage(image, this.canvas.getCanvasWidth() / 2 - image.width / 2, this.canvas.getCanvasHeight() / 2 - image.height / 2); } createContextMenu() { var menu = new qx.ui.menu.Menu(); ImageEditor.BackgroundColors.forEach((color) => { var button = new qx.ui.menu.Button("Background " + color); button.addListener("execute", () => { this.canvas.setBackgroundColor(color); }); menu.add(button); }); this.canvas.setContextMenu(menu); } static SupportsFile(fileName) { var supportedExt = [".png", ".gif", ".jpg", ".jpeg"]; var ext = Cats.OS.File.PATH.extname(fileName); return supportedExt.indexOf(ext) > -1; } moveToPosition(pos) { } }
JavaScript
class SourceEditorContextMenu extends qx.ui.menu.Menu { constructor(editor) { super(); this.editor = editor; this.init(); } createContextMenuItem(name, fn, self) { var button = new qx.ui.menu.Button(name); button.addListener("execute", fn, self); return button; } getIsense() { return this.editor.project.iSense; } gotoDeclaration() { this.getIsense().getDefinitionAtPosition(this.editor.filePath, this.getPos(), (err, data) => { if (data && data.fileName) Cats.FileEditor.OpenEditor(data.fileName, data.range.start); }); } gotoTypeDeclaration() { this.getIsense().getTypeDefinitionAtPosition(this.editor.filePath, this.getPos(), (err, data) => { if (data && data.fileName) Cats.FileEditor.OpenEditor(data.fileName, data.range.start); }); } getPos() { return this.editor.getPosition(); } getInfoAt(type) { this.getIsense().getCrossReference(type, this.editor.filePath, this.getPos(), (err, data) => { if (!data) return; var resultTable = new Gui.ResultTable(); var page = Cats.IDE.resultPane.addPage("info_tab", resultTable); page.setShowCloseButton(true); resultTable.setData(data, this.editor.project); }); } findReferences() { return this.getInfoAt("getReferencesAtPosition"); } findOccurences() { return this.getInfoAt("getOccurrencesAtPosition"); } findImplementors() { return this.getInfoAt("getImplementorsAtPosition"); } insertDoc() { this.getIsense().insertDocComments(this.editor.filePath, this.getPos(), (err, data) => { if (data) this.editor.getAceEditor().insert(data.newText); }); } bookmark() { var dialog = new Gui.PromptDialog("Please provide bookmark name"); dialog.onSuccess = (name) => { var pos = this.getPos(); Cats.IDE.bookmarks.addData({ message: name, fileName: this.editor.filePath, range: { start: pos, end: pos } }); }; dialog.show(); } refactor() { var pos = this.getPos(); Cats.Refactor.rename(this.editor.filePath, this.editor.project, pos); } createModeMenu() { var menu = new qx.ui.menu.Menu(); var modes = ace.require('ace/ext/modelist').modes; modes.forEach((entry) => { var button = new qx.ui.menu.Button(entry.caption); button.addListener("execute", () => { this.editor.setMode(entry.mode); }); menu.add(button); }); return menu; } init() { if (this.editor.project) { this.add(this.createContextMenuItem("Goto Declaration", this.gotoDeclaration, this)); this.add(this.createContextMenuItem("Goto Type Declaration", this.gotoTypeDeclaration, this)); this.add(this.createContextMenuItem("Find References", this.findReferences, this)); this.add(this.createContextMenuItem("Find Occurences", this.findOccurences, this)); // this.add(this.createContextMenuItem("Find Implementations", this.findImplementors, this)); this.addSeparator(); this.add(this.createContextMenuItem("Rename", this.refactor, this)); this.addSeparator(); this.add(this.createContextMenuItem("Insert doc comments", this.insertDoc, this)); this.addSeparator(); } this.add(this.createContextMenuItem("Bookmark", this.bookmark, this)); var modeMenu = this.createModeMenu(); var b = new qx.ui.menu.Button("Modes", null, null, modeMenu); this.add(b); } }
JavaScript
class EditSession extends ace.EditSession { constructor(editor) { super("", "ace/mode/text"); this.editor = editor; this.filePath = editor.filePath; var content = ""; this.version = 0; this.mode = this.calculateMode(); if (this.filePath) { content = Cats.OS.File.readTextFile(this.filePath); } super.setMode(this.mode); super.setValue(content); this.setNewLineMode("unix"); // this.configureAceSession(IDE.config.editor); @TODO this.setUndoManager(new UndoManager()); // @TODO // project.on("config", (c:ProjectConfiguration) => { this.configureAceSession(c); }); this.on("change", () => { this.version++; }); } get project() { return Cats.IDE.getProject(this.filePath); } calculateMode() { if (!this.editor.filePath) return "ace/mode/text"; var mode = modelist.getModeForPath(this.editor.filePath).mode; return mode; } /** * Check if there are any errors for this session and show them. */ showAnnotations(result) { if (!result) return; var annotations = []; result.forEach((error) => { annotations.push({ row: error.range.start.row, column: error.range.start.column, type: error.severity, text: error.message + "" }); }); super.setAnnotations(annotations); } /** * Is the file being edited a possible candiate for the tsconfig project. Right now * TypeScript supports 4 type of scripts: TS, TSX, JS, JSX. * */ isProjectCandidate() { if (!this.filePath) return false; var exts = [".ts", ".tsx", ".js", ".jsx"]; var ext = Cats.OS.File.PATH.extname(this.filePath); return (exts.indexOf(ext) > -1); } setMode(mode) { this.mode = mode; super.setMode(mode); } /** * Determine the maximum level of severity within a set of annotations. * * @return Possible return values are info, warning or error */ getMaxAnnotationLevel() { var annotations = this.getAnnotations(); if ((!annotations) || (annotations.length === 0)) return ""; var result = "info"; annotations.forEach((annotation) => { if (annotation.type === "error") result = "error"; if (annotation.type === "warning" && result === "info") result = "warning"; }); return result; } configureAceSession(projectConfig) { var config = projectConfig.codeFormat; if (config.TabSize) this.setTabSize(config.TabSize); if (config.ConvertTabsToSpaces != null) this.setUseSoftTabs(config.ConvertTabsToSpaces); } /** * Persist this session to the file system. This overrides the NOP in the base class */ save() { var filePath = this.editor.filePath; var content = this.getValue(); if (filePath == null) { var dir = Cats.OS.File.join(Cats.IDE.rootDir, "/"); var dialog = new Gui.PromptDialog("Please enter the file name", dir); dialog.onSuccess = (filePath) => { filePath = Cats.OS.File.switchToForwardSlashes(filePath); this.editor.setFilePath(filePath); this.mode = this.calculateMode(); this.setMode(this.mode); this.save(); if (this.isProjectCandidate()) { var addDialog = new Gui.ConfirmDialog("Not yet part of any project, refresh IDE now?"); addDialog.onConfirm = () => { Cats.IDE.refresh(); }; addDialog.show(); } }; dialog.show(); } else { Cats.OS.File.writeTextFile(filePath, content); this.editor.setHasUnsavedChanges(false); this.editor.updateFileInfo(); Cats.IDE.console.log("Saved file " + filePath); if (this.project) { this.project.updateScript(filePath, content); this.project.validate(false); if (this.project.config.compileOnSave) { this.project.build(); } else { if (this.project.config.validateOnSave) { this.project.validate(true); } } } } } }
JavaScript
class ConsoleLog extends qx.ui.embed.Html { constructor() { super(null); this.printTime = true; this.tsRef = /ts\([0-9]+,[0-9]+\):/i; this.setPadding(2, 2, 2, 2); this.setDecorator(null); this.setOverflow("auto", "auto"); this.addListenerOnce("appear", () => { this.container = this.getContentElement().getDomElement(); }); this.setContextMenu(this.createContextMenu()); this.setFocusable(false); } addBody(parent, prefix, line) { if (line.search(this.tsRef) === -1) { parent.innerText = prefix + line; } else { parent.innerText = prefix; var a = document.createElement("a"); a.href = "#"; a.onclick = handleClick; a.innerText = line; parent.appendChild(a); } } insertLine(prefix, line, severity) { if (line.trim()) { var elem = document.createElement("span"); // HTMLAnchorElement|HTMLSpanElement; this.addBody(elem, prefix, line); if (severity === 2) elem.style.color = "red"; if (severity === 1) elem.style.color = "green"; this.container.appendChild(elem); } this.container.appendChild(document.createElement('BR')); } print(msg, severity) { this.container.scrollTop = this.container.scrollHeight; this.fireDataEvent("contentChange", null); if (this.container) { var prefix = ""; if (this.printTime) { var dt = new Date(); prefix = dt.toLocaleTimeString() + " "; } var lines = msg.split("\n"); lines.forEach((line) => { this.insertLine(prefix, line, severity); }); this.container.scrollTop = this.container.scrollHeight; } } /** * Log a message to the console widget. This should only be used for * logging mesages that are useful to the enduser (= developer) and not for * debug information. * */ log(msg) { this.print(msg, 0); } info(msg) { this.print(msg, 1); } error(msg) { this.print(msg, 2); } createContextMenu() { var menu = new qx.ui.menu.Menu(); var item1 = new qx.ui.menu.Button("Clear Output"); item1.addListener("execute", () => { this.clear(); }); menu.add(item1); var item2 = new qx.ui.menu.Button("Toggle Print Time"); item2.addListener("execute", () => { this.printTime = !this.printTime; }); menu.add(item2); return menu; } clear() { if (this.container) this.container.innerHTML = ""; } }
JavaScript
class FileNavigator extends qx.ui.tree.VirtualTree { constructor() { super(null, "label", "children"); this.rootTop = { label: "qx-cats", fullPath: "", directory: true, children: [{ label: "Loading", icon: "loading", directory: false }], loaded: false }; this.directoryModels = {}; this.parents = {}; this.setDecorator(null); this.setPadding(0, 0, 0, 0); this.setBackgroundColor("transparent"); var contextMenu = new Gui.FileContextMenu(this); this.setContextMenu(contextMenu); this.setupDragAndDrop(); } /** * Enable drag and drop on the FileNavigator * @TODO finalized implementation */ setupDragAndDrop2() { this.setDraggable(true); this.setDroppable(true); // @TODO Issue because <cntrl> is also right click. // this.setSelectionMode("multi"); this.addListener("dragstart", (e) => { Cats.IDE.console.log("drag started. Not yet implemented!!!"); e.addAction("move"); e.addType("tree-items"); e.addData("tree-items", this.getSelection()); }, this); this.addListener("drop", (e) => { Cats.IDE.console.log("Target path:" + e.getRelatedTarget()); for (var i = 0; i < this.getSelection().getLength(); i++) { Cats.IDE.console.log("To be moved:" + this.getSelection().getItem(i)); } }, this); } setupDragAndDrop() { this.setDraggable(true); this.setDroppable(true); this.addListener("dragstart", (e) => { e.addAction("move"); e.addType("tree-items"); e.addData("tree-items", this.getSelection()); }); this.addListener("drop", (e) => { // Using the selection sorted by the original index in the list var sel = e.getData("tree-items"); console.log("Drag and Drop"); console.log(e); // This is the original target hovered var orig = e.getOriginalTarget(); console.log(orig); for (var i = 0, l = sel.length; i < l; i++) { // Insert before the marker console.log(sel[i]); // Recover selection as it gets lost during child move // this.addToSelection(sel[i]); } }); } setRootDir(dir) { this.projectDir = dir; this.watcher = Cats.OS.File.getWatcher(); this.watcher.on("change", (dir) => { var parent = this.parents[dir]; if (parent) this.readDir(parent); }); var directory = dir; this.rootTop.fullPath = directory; this.rootTop.label = Cats.OS.File.PATH.basename(directory); var root = qx.data.marshal.Json.createModel(this.rootTop, true); this.setModel(root); this.setupDelegate(); this.setup(); console.info("Icon path:" + this.getIconPath()); this.addListener("dblclick", () => { var file = this.getSelectedFile(); if (file) { Cats.FileEditor.OpenEditor(file.getFullPath()); } }); // Force a relaod after a close /* this.addListener("close", (event) => { var data = event.getData(); data.setLoaded(false); }); */ } clear() { this.setModel(null); } getSelectedFile() { var item = this.getSelection().getItem(0); if (!item) return null; if (!item.getDirectory) return null; if (!item.getDirectory()) { return item; } return null; } /** * Get an icon for a file based on its mimetype */ getIconForMimeType(mimetype) { var icon = Cats.IDE.icons.mimetype[mimetype] || Cats.IDE.icons.mimetype["text/plain"]; return icon; } setup() { this.setIconPath(""); this.setIconOptions({ converter: (value, model) => { if (value.getDirectory()) { return this.getIconForMimeType("inode/directory"); } var mimetype = Cats.Util.MimeTypeFinder.lookup(value.getLabel()); return this.getIconForMimeType(mimetype); } }); } setupDelegate() { var self = this; var delegate = { bindItem: function (controller, item, index) { controller.bindDefaultProperties(item, index); controller.bindProperty("", "open", { converter: function (value, model, source, target) { var isOpen = target.isOpen(); if (isOpen && !value.getLoaded()) { value.setLoaded(true); setTimeout(function () { value.getChildren().removeAll(); self.readDir(value); }, 0); } return isOpen; } }, item, index); } }; this.setDelegate(delegate); } /** * Read the files from a directory * @param directory The directory name that should be read */ readDir(parent) { var directory = parent.getFullPath(); this.watcher.addDir(directory); this.parents[directory] = parent; parent.getChildren().removeAll(); var entries = []; try { entries = Cats.OS.File.readDir(directory, true); } catch (err) { } entries.forEach((entry) => { var node = { label: entry.name, fullPath: entry.fullName, loaded: !entry.isDirectory, directory: entry.isDirectory, children: entry.isDirectory ? [{ label: "Loading", icon: "loading", directory: false }] : null }; parent.getChildren().push(qx.data.marshal.Json.createModel(node, true)); }); } }
JavaScript
class OutlineNavigator extends qx.ui.tree.VirtualTree { constructor() { super(null, "label", "kids"); this.setDecorator(null); this.setPadding(0, 0, 0, 0); this.setHideRoot(true); this.setBackgroundColor("transparent"); this.setDecorator(null); this.addListener("click", () => { var item = this.getSelectedItem(); if (item && item.getPos) { var position = JSON.parse(qx.util.Serializer.toJson(item.getPos())); Cats.IDE.editorTabView.navigateToPage(this.page, position); } }); this.setIconPath("kind"); this.setIconOptions({ converter: (value) => { var icon = Cats.IDE.icons.kind[value] || Cats.IDE.icons.kind["default"]; return icon; } }); Cats.IDE.editorTabView.onChangeEditor(this.register.bind(this)); } register(editor, page) { if (this.editor) { this.editor.off("outline", this.updateOutline, this); } this.page = page; if (editor) { this.editor = editor; editor.on("outline", this.updateOutline, this); this.updateOutline(editor.get("outline")); } else { this.clear(); this.editor = null; } } getSelectedItem() { var item = this.getSelection().getItem(0); return item; } /** * Clear the content of the outline navigator * */ clear() { this.setModel(null); } expandAll(root, count = 0) { if (root && root.getKids) { this.openNode(root); var children = root.getKids(); count += children.length; if (count > OutlineNavigator.MAX_DEFAULT_OPEN) return count; for (var i = 0; i < children.length; i++) { var child = children.getItem(i); count = this.expandAll(child, count); if (count > OutlineNavigator.MAX_DEFAULT_OPEN) return count; } } return count; } /** * Lets check the worker if something changed in the outline of the source. * But lets not call this too often. */ updateOutline(data = []) { // IDE.console.log("Received outline info:" + data.length); var root = { label: "root", kids: data, kind: "" }; this.setModel(qx.data.marshal.Json.createModel(root, false)); this.expandAll(this.getModel()); } }
JavaScript
class ResultTable extends qx.ui.table.Table { constructor(headers = ["tableheader_message", "tableheader_project", "tableheader_file", "tableheader_position"]) { var tableModel = new qx.ui.table.model.Simple(); var columns = []; // headers.forEach((header) => { columns.push(this.tr(header))}); headers.forEach((header) => { columns.push(Cats.translate(header)); }); tableModel.setColumns(columns); tableModel.setData([]); var custom = { tableColumnModel: function () { return new qx.ui.table.columnmodel.Resize(); } }; super(tableModel, custom); this.setStatusBarVisible(false); this.setDecorator(null); this.projectData = {}; this.setPadding(0, 0, 0, 0); this.addListener("click", () => { var selectedRow = this.getSelectionModel().getLeadSelectionIndex(); var data = this.getTableModel().getRowData(selectedRow); if (data && data[4]) Cats.FileEditor.OpenEditor(data[4], data[5]); }); this.setContextMenu(this.createContextMenu()); } rangeToPosition(range) { if (range) { return (range.start.row + 1) + ":" + (range.start.column + 1); } else { return ""; } } /** * Clear all the data from the table */ clear() { var model = this.getTableModel(); this.projectData = {}; model.setData([]); } convert(row) { var baseDir = Cats.IDE.rootDir; var fileName = row.fileName || ""; if (fileName) fileName = Cats.OS.File.PATH.relative(baseDir, fileName); return [ row.message, "", fileName || "", this.rangeToPosition(row.range), row.fileName || "", row.range ]; } areEmpty(...args) { for (var i = 0; i < args.length; i++) { var arr = args[i]; if (arr && (arr.length > 0)) return false; } return true; } /** * Flatten the currently set data for possible multiple projects into a single array. */ flatten() { var result = []; var baseDir = Cats.IDE.rootDir; Object.keys(this.projectData).forEach((key) => { var projectData = this.projectData[key]; var projectName = projectData.project ? projectData.project.name : "default"; var data = projectData.data || []; data.forEach((row) => { var fileName = row.fileName || ""; if (fileName) fileName = Cats.OS.File.PATH.relative(baseDir, fileName); result.push([ row.message, projectName, fileName, this.rangeToPosition(row.range), row.fileName || "", row.range ]); }); }); return result; } /** * Set the data for this table */ setData(data, project) { var key = project ? project.tsConfigFile : "default"; // if (this.areEmpty(this.projectData[key], data)) return; this.fireDataEvent("contentChange", null); this.projectData[key] = { data: data, project: project }; var rows = this.flatten(); var model = this.getTableModel(); model.setData(rows); // this.getSelectionModel().resetSelection(); } /** * Add a row to the table */ addData(row) { var model = this.getTableModel(); model.addRows([this.convert(row)]); } createContextMenu() { var menu = new qx.ui.menu.Menu(); var item1 = new qx.ui.menu.Button("Clear Output"); item1.addListener("execute", () => { this.clear(); }); menu.add(item1); return menu; } }
JavaScript
class TabViewPage extends qx.ui.tabview.Page { constructor(id, widget, tooltipText) { super(Cats.translate(id), Cats.IDE.icons.tab[id]); this.id = id; // Hints if this tab want to get selected if its content changes this.autoSelect = false; this.setLayout(new qx.ui.layout.Canvas()); if (tooltipText) { var button = this.getButton(); var tooltip = new qx.ui.tooltip.ToolTip(tooltipText); button.setToolTip(tooltip); button.setBlockToolTip(false); } if (widget) { this.add(widget, { edge: 0 }); widget.addListener("contentChange", () => { if (this.autoSelect) { var elem = document.activeElement; this.select(); setTimeout(() => { if (elem) elem.focus(); }, 10); } }); } } /** * Convenience method to select this page in the tab view. */ select() { var tabView = this.getLayoutParent().getLayoutParent(); tabView.setSelection([this]); } }
JavaScript
class TabView extends qx.ui.tabview.TabView { constructor() { super(); this.setPadding(0, 0, 0, 0); this.setContentPadding(0, 0, 0, 0); this.createContextMenu(); } createContextMenu() { var menu = new qx.ui.menu.Menu(); var directions = ["top", "left", "right", "bottom"]; directions.forEach((dir) => { var item = new qx.ui.menu.Button(Cats.translate(dir)); item.addListener("execute", () => { this.setBarPosition(dir); }); menu.add(item); }); var mainmenu = new qx.ui.menu.Menu(); var b = new qx.ui.menu.Button("Tab layout", null, null, menu); mainmenu.add(b); this.setContextMenu(mainmenu); } /** * Add a new Page to the tab Viewx */ addPage(id, widget, tooltipText) { var tab = new TabViewPage(id, widget, tooltipText); this.add(tab); this.setSelection([tab]); return tab; } }
JavaScript
class ToolBar extends qx.ui.toolbar.ToolBar { constructor() { super(); this.commands = [ Cats.Commands.COMMANDNAME.file_new, Cats.Commands.COMMANDNAME.file_close, Cats.Commands.COMMANDNAME.file_closeAll, null, Cats.Commands.COMMANDNAME.file_save, Cats.Commands.COMMANDNAME.file_saveAll, Cats.Commands.COMMANDNAME.file_saveAs, null, Cats.Commands.COMMANDNAME.project_open, Cats.Commands.COMMANDNAME.project_close, Cats.Commands.COMMANDNAME.project_build, Cats.Commands.COMMANDNAME.project_run, Cats.Commands.COMMANDNAME.project_refresh, null, Cats.Commands.COMMANDNAME.edit_undo, Cats.Commands.COMMANDNAME.edit_redo, Cats.Commands.COMMANDNAME.edit_find, Cats.Commands.COMMANDNAME.edit_replace, Cats.Commands.COMMANDNAME.edit_indent, Cats.Commands.COMMANDNAME.edit_outdent, // Cats.Commands.CMDS.edit_toggleComment null, Cats.Commands.COMMANDNAME.ide_history_prev, Cats.Commands.COMMANDNAME.ide_history_next, null, Cats.Commands.COMMANDNAME.ide_theme ]; this.init(); } createButton(command) { var cmd = Cats.Commands.commandRegistry.getCommand(command); var icon = Cats.IDE.icons.toolbar[cmd.name]; var button = new qx.ui.toolbar.Button(cmd.label, icon); button.setShow("icon"); button.getChildControl("icon").set({ width: 22, height: 22, scale: true }); var tooltip = new qx.ui.tooltip.ToolTip(cmd.label, null); button.setToolTip(tooltip); button.setBlockToolTip(false); button.addListener("click", () => { cmd.command(); }); return button; } init() { var part = new qx.ui.toolbar.Part(); this.commands.forEach((cmd) => { if (cmd === null) { this.add(part); part = new qx.ui.toolbar.Part(); } else { var button = this.createButton(cmd); part.add(button); } }); this.add(part); } }
JavaScript
class EditorPage extends qx.ui.tabview.Page { constructor(editor) { super(editor.label); this.editor = editor; this.add(editor.getLayoutItem(), { edge: 0 }); this.setShowCloseButton(true); this.setLayout(new qx.ui.layout.Canvas()); this.setPadding(0, 0, 0, 0); this.setMargin(0, 0, 0, 0); this.createContextMenu(); this.createToolTip(); this.getButton().setShow("both"); editor.on("changed", this.setChanged, this); editor.on("errors", this.setHasErrors, this); } continueWhenNeedSaving(callback) { if (this.editor.hasUnsavedChanges()) { var dialog = new Gui.ConfirmDialog("There are unsaved changes!\nDo you really want to continue?"); dialog.onConfirm = callback; dialog.show(); } else { callback(); } } _onButtonClose() { this.continueWhenNeedSaving(() => { super._onButtonClose(); }); } createToolTip() { const button = this.getButton(); const tooltipText = this.editor.getDescription() || this.editor.label; const tooltip = new qx.ui.tooltip.ToolTip(tooltipText); button.setToolTip(tooltip); } createContextMenu() { const button = this.getButton(); const menu = new qx.ui.menu.Menu(); const item1 = new qx.ui.menu.Button("Close"); item1.addListener("execute", () => { Cats.IDE.editorTabView.close(this); }); const item2 = new qx.ui.menu.Button("Close other"); item2.addListener("execute", () => { Cats.IDE.editorTabView.closeOther(this); }); const item3 = new qx.ui.menu.Button("Close all"); item3.addListener("execute", () => { Cats.IDE.editorTabView.closeAll(); }); menu.add(item1); menu.add(item2); menu.add(item3); button.setContextMenu(menu); } /** * Tell the Page that the editor on it has detected some errors in the code */ setHasErrors(level) { if (level) { var icon = Cats.IDE.icons.annotation[level]; this.setIcon(icon); } else { this.resetIcon(); } } setChanged(changed) { const button = this.getButton(); if (changed) { button.setLabel("*" + this.editor.label); } else { button.setLabel(this.editor.label); } } }
JavaScript
class StatusBar extends qx.ui.toolbar.ToolBar { constructor() { super(); this.status = {}; this.init(); this.setPadding(0, 0, 0, 0); Cats.IDE.editorTabView.onChangeEditor(this.register.bind(this)); } clear() { this.modeInfo.setLabel(""); this.overwriteInfo.setLabel("INSERT"); this.positionInfo.setLabel(""); } updateStatus(status) { if (!status) return; if (status.mode !== this.status.mode) { this.modeInfo.setLabel(status.mode || "Unknown"); } if (status.overwrite !== this.status.overwrite) { this.overwriteInfo.setLabel(status.overwrite ? "OVERWRITE" : "INSERT"); } if (status.position !== this.status.position) { this.positionInfo.setLabel(status.position || ":"); } this.status = status; } register(editor) { if (this.editor) { this.editor.off("status", this.updateStatus, this); } if (editor) { this.editor = editor; editor.on("status", this.updateStatus, this); this.updateStatus(editor.get("status")); } else { this.clear(); this.editor = null; } } /** * Create a new button * */ createButton(label, icon) { var button = new qx.ui.toolbar.Button(label, icon); // button.setPadding(1,1,1,1); button.setMargin(0, 10, 0, 10); button.setMinWidth(100); button.setDecorator(null); return button; } /** * Initialize the status bar * */ init() { this.positionInfo = this.createButton("-:-"); this.add(this.positionInfo); this.modeInfo = this.createButton("Unknown"); this.add(this.modeInfo); this.addSpacer(); this.busyInfo = this.createButton("", "./resource/cats/loader.gif"); this.busyInfo.setShow("icon"); this.add(this.busyInfo); this.overwriteInfo = this.createButton("INSERT"); this.add(this.overwriteInfo); } /** * Indicate if the worker is busy or not * @TODO fix for when multiple projects */ setBusy(busy, activity) { if (busy) { this.busyInfo.setIcon("./resource/cats/loader_anim.gif"); } else { this.busyInfo.setIcon("./resource/cats/loader.gif"); } if (Cats.IDE.debug && busy && activity) Cats.IDE.console.log(activity); } }
JavaScript
class ConfirmDialog extends qx.ui.window.Window { constructor(text) { super(name); var layout = new qx.ui.layout.VBox(); this.setLayout(layout); this.setModal(true); this.setShowMinimize(false); this.setShowMaximize(false); this.addControls(text); this.addListener("resize", this.center); } addControls(text) { var form = new qx.ui.form.Form(); // Prompt message form.addGroupHeader(text); // Confirm command var confirmCommand = new qx.ui.command.Command("Enter"); confirmCommand.addListener("execute", () => { if (this.onConfirm) { this.onConfirm(); } this.close(); }); // Cancel command var cancelCommand = new qx.ui.command.Command("Escape"); cancelCommand.addListener("execute", () => { if (this.onCancel) { this.onCancel(); } this.close(); }); // Command cleanup this.addListener("close", () => { confirmCommand.setEnabled(false); cancelCommand.setEnabled(false); }); // Confirm button var okbutton = new qx.ui.form.Button("Confirm"); form.addButton(okbutton); okbutton.setCommand(confirmCommand); // Cancel button var cancelbutton = new qx.ui.form.Button("Cancel"); cancelbutton.setCommand(cancelCommand); form.addButton(cancelbutton); var renderer = new qx.ui.form.renderer.Single(form); this.add(renderer); } }
JavaScript
class PromptDialog extends qx.ui.window.Window { constructor(text, value = "") { super(name); var layout = new qx.ui.layout.VBox(); this.setLayout(layout); this.setModal(true); this.setShowMinimize(false); this.setShowMaximize(false); this.addControls(text, value); this.addListener("resize", this.center); } addControls(text, value) { var form = new qx.ui.form.Form(); // Prompt message form.addGroupHeader(text); // Value text field var valuefield = new qx.ui.form.TextField(); valuefield.setValue(value); valuefield.setWidth(400); form.add(valuefield, ""); this.addListener("appear", () => { valuefield.focus(); }); // Success command var successCommand = new qx.ui.command.Command("Enter"); successCommand.addListener("execute", () => { if (form.validate()) { if (this.onSuccess) { this.onSuccess(valuefield.getValue()); } this.close(); } ; }); // Cancel command var cancelCommand = new qx.ui.command.Command("Escape"); cancelCommand.addListener("execute", () => { this.close(); }); // Command cleanup this.addListener("close", () => { successCommand.setEnabled(false); cancelCommand.setEnabled(false); }); // Ok button var okbutton = new qx.ui.form.Button("Ok"); form.addButton(okbutton); okbutton.setCommand(successCommand); // Cancel button var cancelbutton = new qx.ui.form.Button("Cancel"); cancelbutton.setCommand(cancelCommand); form.addButton(cancelbutton); var renderer = new qx.ui.form.renderer.Single(form); this.add(renderer); } }
JavaScript
class QuickOpenDialog extends qx.ui.window.Window { constructor(project) { super("Quick Open"); this.project = project; this.files = []; if (!fuzzy) fuzzy = require("fuzzy"); this.collectFiles(); var layout = new qx.ui.layout.VBox(); layout.setSpacing(6); this.setLayout(layout); this.setModal(true); this.setShowMinimize(false); this.setShowMaximize(false); this.addControls(); this.addListener("resize", this.center); } collectFiles() { var projectDir = this.project.projectDir; this.project.getScripts().forEach((absolutePath) => { if (absolutePath.lastIndexOf(projectDir, 0) === 0) { var relativePath = absolutePath.slice(projectDir.length + 1); this.files.push(relativePath); } }); } addControls() { // Prompt message // form.addGroupHeader("Type a few letters to find a project file to open..."); // Value text field var valuefield = new qx.ui.form.TextField(); valuefield.setWidth(450); this.add(valuefield); this.addListener("appear", () => { valuefield.focus(); }); // File list var filelist = new qx.ui.form.List(); filelist.setMinHeight(500); this.add(filelist); var doFilter = () => { var query = valuefield.getValue(); var opts = { pre: '{{{', post: '}}}' }; var results = fuzzy.filter(query, this.files, opts); filelist.removeAll(); for (var i = 0; i < results.length; i++) { var result = results[i]; function format(str) { return str.replace(/{{{/g, "<strong>").replace(/}}}/g, "</strong>"); } var cutIndex = result.string.lastIndexOf('/'); var long = result.string; var short = result.string.slice(cutIndex + 1); var pretty = "<span style='font-size: 120%; display: block;'>" + format(short) + "</span><span style='opacity: 0.7;'>" + format(long) + "</span>"; var item = new qx.ui.form.ListItem(pretty); item.setRich(true); item.setModel(result.original); filelist.add(item); if (i === 0) { filelist.addToSelection(item); } } }; valuefield.addListener("input", throttle(doFilter, 100)); valuefield.addListener("keypress", (ev) => { var id = ev.getKeyIdentifier(); switch (id) { case "Down": case "Up": filelist.handleKeyPress(ev); break; } }); // Success command var successCommand = new qx.ui.command.Command("Enter"); successCommand.addListener("execute", () => { var results = filelist.getSelection(); if (results.length > 0) { var result = results[0]; var relativePath = result.getModel(); var filePath = Cats.OS.File.join(this.project.projectDir, relativePath); Cats.FileEditor.OpenEditor(filePath); this.close(); } ; }); filelist.addListener("dblclick", () => { successCommand.execute(null); }); // Cancel command var cancelCommand = new qx.ui.command.Command("Escape"); cancelCommand.addListener("execute", () => { this.close(); }); // Command cleanup this.addListener("close", () => { successCommand.setEnabled(false); cancelCommand.setEnabled(false); }); } }
JavaScript
class FileContextMenu extends qx.ui.menu.Menu { constructor(fileNavigator) { super(); this.fileNavigator = fileNavigator; this.searchDialog = new Gui.SearchDialog(); this.init(); } openInApp() { var gui = Cats.getNWGui(); var osPath = Cats.OS.File.join(this.getFullPath(), "", true); if (osPath) gui.Shell.openItem(osPath); } showInFolder() { var gui = Cats.getNWGui(); var osPath = Cats.OS.File.join(this.getFullPath(), "", true); if (osPath) gui.Shell.showItemInFolder(osPath); } search() { this.searchDialog.search(this.getFullPath()); } getSelectedItem() { return this.fileNavigator.getSelection().getItem(0); } getFullPath() { var item = this.getSelectedItem(); if (item) return item.getFullPath(); } init() { // var refreshButton = new qx.ui.menu.Button("Refresh"); var renameButton = new qx.ui.menu.Button("Rename"); renameButton.addListener("execute", this.rename, this); var deleteButton = new qx.ui.menu.Button("Delete"); deleteButton.addListener("execute", this.deleteFile, this); var newFileButton = new qx.ui.menu.Button("New File"); newFileButton.addListener("execute", this.newFile, this); var newDirButton = new qx.ui.menu.Button("New Directory"); newDirButton.addListener("execute", this.newFolder, this); var searchButton = new qx.ui.menu.Button("Search"); searchButton.addListener("execute", this.search, this); var openInAppButton = new qx.ui.menu.Button("Open in default App"); openInAppButton.addListener("execute", this.openInApp, this); var showInFolderButton = new qx.ui.menu.Button("Show item in folder"); showInFolderButton.addListener("execute", this.showInFolder, this); // this.add(refreshButton); this.add(renameButton); this.add(deleteButton); this.add(newFileButton); this.add(newDirButton); this.addSeparator(); this.add(searchButton); this.addSeparator(); this.add(openInAppButton); this.add(showInFolderButton); } deleteFile() { var fullName = this.getFullPath(); var basename = Cats.OS.File.PATH.basename(fullName); var dialog = new Gui.ConfirmDialog("Delete " + basename + "?"); dialog.onConfirm = () => { Cats.OS.File.remove(fullName); }; dialog.show(); } getBaseDir() { var item = this.getSelectedItem(); var fullPath = this.getFullPath(); if (item.getDirectory()) { return fullPath; } else { return Cats.OS.File.PATH.dirname(fullPath); } } newFile() { var basedir = this.getBaseDir(); var dialog = new Gui.PromptDialog("Enter new file name in directory " + basedir); dialog.onSuccess = (name) => { var fullName = Cats.OS.File.join(basedir, name); Cats.OS.File.writeTextFile(fullName, ""); }; dialog.show(); } newFolder() { var basedir = this.getBaseDir(); var dialog = new Gui.PromptDialog("Enter new folder name in directory " + basedir); dialog.onSuccess = (name) => { var fullName = Cats.OS.File.join(basedir, name); Cats.OS.File.mkdirRecursiveSync(fullName); }; dialog.show(); } rename() { var fullName = this.getFullPath(); var dirname = Cats.OS.File.PATH.dirname(fullName); var basename = Cats.OS.File.PATH.basename(fullName); var dialog = new Gui.PromptDialog("Enter new name", basename); dialog.onSuccess = (name) => { var message = "Going to rename " + basename + " to " + name; var confirmDialog = new Gui.ConfirmDialog(message); confirmDialog.onConfirm = () => { try { Cats.OS.File.rename(fullName, Cats.OS.File.join(dirname, name)); } catch (err) { alert(err); } }; confirmDialog.show(); }; dialog.show(); } }
JavaScript
class ConfigDialog extends qx.ui.window.Window { constructor(name) { super(name); var layout = new qx.ui.layout.VBox(); this.setLayout(layout); this.setModal(true); this.addTabs(); this.addButtons(); this.addListener("resize", this.center); } addTabs() { // to do in subclasses; } saveValues() { // to do in subclass } addButtons() { // Save button var form = new qx.ui.form.Form(); var okbutton = new qx.ui.form.Button("Ok"); form.addButton(okbutton); okbutton.addListener("execute", () => { if (form.validate()) { this.saveValues(); this.close(); } ; }, this); // Cancel button var cancelbutton = new qx.ui.form.Button("Cancel"); form.addButton(cancelbutton); cancelbutton.addListener("execute", function () { this.close(); }, this); var renderer = new qx.ui.form.renderer.Single(form); this.add(renderer); // this.add(form); } }
JavaScript
class ConfigDialogPage extends qx.ui.tabview.Page { constructor(name) { super(name); this.form = new qx.ui.form.Form(); this.setLayout(new qx.ui.layout.Canvas()); } addCheckBox(model) { var cb = new qx.ui.form.CheckBox(); var label = this.getLabelString(model); this.form.add(cb, label, null, model); } getLabelString(model) { if (!model) return "<model undefined>"; var labelId = "config_" + model; var label = Cats.translate(labelId); if (label != labelId) return label; return model.split(/(?=[A-Z])/).join(" "); } addSpinner(model, min, max) { var s = new qx.ui.form.Spinner(); s.set({ minimum: min, maximum: max }); var label = this.getLabelString(model); this.form.add(s, label, null, model); } addTextField(model) { var t = new qx.ui.form.TextField(); t.setWidth(200); var label = this.getLabelString(model); this.form.add(t, label, null, model); } addSelectBox(model, items) { var s = new qx.ui.form.SelectBox(); items.forEach((item) => { var listItem = new qx.ui.form.ListItem(item.label, null, item.model); s.add(listItem); }); var label = this.getLabelString(model); this.form.add(s, label, null, model); } setData(data) { for (var key in data) { try { this.model.set(key, data[key]); } catch (err) { } } } /** * Get the data back as a JSON object */ getData() { var result = JSON.parse(qx.util.Serializer.toJson(this.model)); return result; } finalStep() { var controller = new qx.data.controller.Form(null, this.form); this.model = controller.createModel(false); var renderer = new qx.ui.form.renderer.Single(this.form); this.add(renderer); } }
JavaScript
class ProjectSettingsDialog extends Gui.ConfigDialog { constructor(project) { super(Cats.translate("project_settings")); this.project = project; this.loadValues(); } loadValues() { var config = this.project.config; this.projectSettings.setData(config); this.compilerSettings.setData(config.compilerOptions); this.codeFormatSettings.setData(config.codeFormat); this.tslintSettings.setData(config.tslint); this.customBuild.setData(config.customBuild); this.customRun.setData(config.customRun); this.documentationSettings.setData(config.documentation); } saveValues() { var config = this.projectSettings.getData(); config.compiler = this.compilerSettings.getData(); config.codeFormat = this.codeFormatSettings.getData(); config.customBuild = this.customBuild.getData(); config.customRun = this.customRun.getData(); config.documentation = this.documentationSettings.getData(); config.tslint = this.tslintSettings.getData(); this.project.updateConfig(config); } addTabs() { var tab = new qx.ui.tabview.TabView(); this.compilerSettings = new ProjectCompilerSettings(); tab.add(this.compilerSettings); this.projectSettings = new ProjectGeneric(); tab.add(this.projectSettings); this.codeFormatSettings = new CodeFormatSettings(); tab.add(this.codeFormatSettings); this.tslintSettings = new TSLintSettings(); tab.add(this.tslintSettings); this.documentationSettings = new DocumentationSettings(); tab.add(this.documentationSettings); this.customBuild = new CustomBuildSettings(); tab.add(this.customBuild); this.customRun = new CustomRunSettings(); tab.add(this.customRun); this.add(tab); } }
JavaScript
class ProjectCompilerSettings extends Gui.ConfigDialogPage { constructor() { super("Compiler"); this.moduleGenTarget = [ { label: "none", model: ts.ModuleKind.None }, { label: "commonjs", model: ts.ModuleKind.CommonJS }, { label: "amd", model: ts.ModuleKind.AMD }, { label: "umd", model: ts.ModuleKind.UMD }, { label: "system", model: ts.ModuleKind.System }, { label: "es2015", model: ts.ModuleKind.ES2015 } ]; this.jsTarget = [ { label: "es3", model: ts.ScriptTarget.ES3 }, { label: "es5", model: ts.ScriptTarget.ES5 }, { label: "es2015", model: ts.ScriptTarget.ES2015 }, { label: "latest", model: ts.ScriptTarget.Latest } ]; this.newLineKind = [ { label: "OSX/Linux", model: ts.NewLineKind.LineFeed }, { label: "Windows", model: ts.NewLineKind.CarriageReturnLineFeed }, ]; this.jsxEmit = [ { label: "None", model: ts.JsxEmit.None }, { label: "Preserve (jsx)", model: ts.JsxEmit.Preserve }, { label: "Generate React code (js)", model: ts.JsxEmit.React } ]; this.createForm(); this.finalStep(); } createForm() { this.addCheckBox("noLib"); this.addCheckBox("removeComments"); this.addCheckBox("noImplicitAny"); this.addCheckBox("noEmitHelpers"); this.addCheckBox("declaration"); this.addCheckBox("sourceMap"); this.addCheckBox("propagateEnumConstants"); this.addCheckBox("allowAutomaticSemicolonInsertion"); this.addCheckBox("allowSyntheticDefaultImports"); this.addCheckBox("experimentalDecorators"); this.addCheckBox("emitDecoratorMetadata"); this.addCheckBox("allowUnusedLabels"); this.addCheckBox("allowUnreachableCode"); this.addSelectBox("target", this.jsTarget); this.addSelectBox("module", this.moduleGenTarget); this.addSelectBox("newLine", this.newLineKind); this.addSelectBox("jsx", this.jsxEmit); this.addTextField("outDir"); this.addTextField("rootDir"); this.addTextField("out"); } }
JavaScript
class ProjectGeneric extends Gui.ConfigDialogPage { constructor() { super("Generic"); this.projectType = [ { label: "standard", model: "standard" }, { label: "webworker", model: "webworker" }, { label: "ECMAScript", model: "core" }, { label: "scriptHost", model: "scriptHost" }, // { label: "IE10", model: "dom" }, { label: "none", model: "none" } ]; this.createForm(); this.finalStep(); } createForm() { this.addTextField("src"); this.addTextField("main"); this.addCheckBox("buildOnSave"); this.addSelectBox("projectType", this.projectType); } }
JavaScript
class CodeFormatSettings extends Gui.ConfigDialogPage { constructor() { super("Code Formatting"); this.newLineMode = [ { label: "Linux/OSX", model: "\n" }, { label: "Dos/Windows", model: "\r\n" }, ]; this.createForm(); this.finalStep(); } createForm() { this.addSelectBox("NewLineCharacter", this.newLineMode); this.addCheckBox("ConvertTabsToSpaces"); this.addSpinner("IndentSize", 1, 16); this.addSpinner("TabSize", 1, 16); // this.addCheckBox2("InsertSpaceAfterCommaDelimiter"); // this.addCheckBox2("InsertSpaceAfterFunctionKeywordForAnonymousFunctions"); // this.addCheckBox2("") } }
JavaScript
class TSLintSettings extends Gui.ConfigDialogPage { constructor() { super("TSLint Settings"); this.createForm(); this.finalStep(); } createForm() { this.addCheckBox("useLint"); this.addTextField("lintFile"); } }
JavaScript
class DocumentationSettings extends Gui.ConfigDialogPage { constructor() { super("Documentation Settings"); this.themes = [ { label: "Default", model: "default" }, ]; this.createForm(); this.finalStep(); } createForm() { this.addCheckBox("includeDeclarations"); this.addTextField("outputDirectory"); this.addTextField("readme"); this.addSelectBox("theme", this.themes); } }
JavaScript
class IdePreferencesDialog extends Gui.ConfigDialog { constructor(config) { super("CATS Settings"); this.config = config; this.loadValues(); } loadValues() { var config = this.config; this.editorSettings.setData(config.editor); this.ideGenericSettings.setData(config); } saveValues() { var config = this.ideGenericSettings.getData(); config.editor = this.editorSettings.getData(); Cats.IDE.updatePreferences(config); } addTabs() { var tab = new qx.ui.tabview.TabView(); this.ideGenericSettings = new GenericPreferences; this.editorSettings = new EditorPreferences; tab.add(this.ideGenericSettings); tab.add(this.editorSettings); this.add(tab); } }
JavaScript
class GenericPreferences extends Gui.ConfigDialogPage { constructor() { super("Generic"); this.locales = [ { label: "English", model: "en" } ]; this.createForm(); this.finalStep(); } getThemes() { var themes = Cats.IDE.getThemes().map((theme) => { return { label: theme.name, model: theme.name }; }); return themes; } createForm() { this.addSelectBox("theme", this.getThemes()); this.addSpinner("fontSize", 6, 24); this.addSelectBox("locale", this.locales); this.addCheckBox("rememberOpenFiles"); this.addCheckBox("rememberLayout"); } }
JavaScript
class EditorPreferences extends Gui.ConfigDialogPage { constructor() { super("Source Editor"); this.completionMode = [ { label: "strict", model: "strict" }, { label: "forgiven", model: "forgiven" } ]; this.newLineMode = [ { label: "Linux/OSX", model: "\n" }, { label: "Dos/Windows", model: "\r\n" }, ]; this.createForm(); this.finalStep(); } getThemes() { var themelist = ace.require("ace/ext/themelist"); var result = []; themelist.themes.forEach((x) => { var label = x.caption; if (x.isDark) label += " (dark)"; result.push({ model: x.theme, label: label }); }); return result; } createForm() { this.addSpinner("fontSize", 6, 24); this.addSpinner("rightMargin", 40, 240); this.addSelectBox("completionMode", this.completionMode); // this.addSelectBox("NewLineCharacter", this.newLineMode); // this.addCheckBox("ConvertTabsToSpaces"); // this.addSpinner("IndentSize", 1, 16); // this.addSpinner("TabSize", 1, 16); } }
JavaScript
class ProcessTable extends qx.ui.container.Composite { constructor() { super(new qx.ui.layout.VBox()); this.setPadding(0, 0, 0, 0); this.add(this.createControls()); this.add(this.createTable(), { flex: 1 }); } /** * Add a new process to the table */ addProcess(child, cmd) { var row = new Array("" + child.pid, cmd, child); var model = this.table.getTableModel(); model.addRows([row]); this.table.getSelectionModel().resetSelection(); } sendSignal(signal) { var table = this.table; var selectedRow = table.getSelectionModel().getLeadSelectionIndex(); if (selectedRow < 0) { alert("You have to select a process from the table below first"); return; } var data = table.getTableModel().getRowData(selectedRow); var child = data[2]; child.kill(signal); } addButton(bar, label, signal) { var button = new qx.ui.toolbar.Button(label); button.addListener("execute", () => { this.sendSignal(signal); }); bar.add(button); } createTable() { var tableModel = new qx.ui.table.model.Simple(); var headers = [Cats.translate("tableheader_pid"), Cats.translate("tableheader_command")]; tableModel.setColumns(headers); tableModel.setData([]); var custom = { tableColumnModel: function () { return new qx.ui.table.columnmodel.Resize(); } }; var table = new qx.ui.table.Table(tableModel, custom); table.setDecorator(null); table.setStatusBarVisible(false); this.table = table; return table; } createControls() { var bar = new qx.ui.toolbar.ToolBar(); this.addButton(bar, "Stop", "SIGTERM"); this.addButton(bar, "Kill", "SIGKILL"); this.addButton(bar, "Pause", "SIGSTOP"); this.addButton(bar, "Resume", "SIGCONT"); return bar; } }
JavaScript
class BusyWindow extends qx.ui.window.Window { constructor(name) { super(name); this.setLayout(new qx.ui.layout.Basic()); this.setMinWidth(300); this.setMinHeight(150); this.add(new qx.ui.basic.Label("Please wait one moment ....")); this.setModal(true); this.addListener("resize", this.center); this.addListenerOnce("appear", () => { setTimeout(() => { this.fireDataEvent("ready", {}); }, 100); }); } }
JavaScript
class PropertyTable extends qx.ui.table.Table { constructor() { var tableModel = new qx.ui.table.model.Simple(); var headers = [Cats.translate("tableheader_name"), Cats.translate("tableheader_value")]; tableModel.setColumns(headers); tableModel.setData([]); var custom = { tableColumnModel: function (obj) { return new qx.ui.table.columnmodel.Resize(); } }; super(tableModel, custom); this.setStatusBarVisible(false); this.setDecorator(null); this.setPadding(0, 0, 0, 0); Cats.IDE.editorTabView.onChangeEditor(this.register.bind(this)); } clear() { this.setData([]); } register(editor) { if (this.editor) { this.editor.off("info", this.setData, this); } this.editor = editor; if (editor) { editor.on("info", this.setData, this); this.setData(editor.get("info")); } else { this.clear(); } } getData() { return this.data; } setData(data) { this.data = data; var rows = []; if (data) { data.forEach((row) => { rows.push([row.key, row.value]); }); } var model = this.getTableModel(); model.setData(rows); this.getSelectionModel().resetSelection(); } }
JavaScript
class Layout { constructor(rootDoc) { this.rootDoc = rootDoc; } /** * Layout the various parts of de IDE */ layout(ide) { // container layout var layout = new qx.ui.layout.VBox(); // main container var mainContainer = new qx.ui.container.Composite(layout); mainContainer.setBackgroundColor("transparent"); this.rootDoc.add(mainContainer, { edge: 0 }); ide.toolBar = new Gui.ToolBar(); mainContainer.add(ide.toolBar, { flex: 0 }); // mainsplit, contains the editor splitpane and the info splitpane var mainsplit = new qx.ui.splitpane.Pane("horizontal"); // mainsplit.set({ decorator: null }); // ********************* Navigator Pane ******************** var navigatorPane = new Gui.TabView(); ide.bookmarks = new Gui.ResultTable(["tableheader_bookmark"]); ide.fileNavigator = new Gui.FileNavigator(); var fileTab = navigatorPane.addPage("files_tab", ide.fileNavigator); navigatorPane.addPage("bookmarks_tab", ide.bookmarks); navigatorPane.setSelection([fileTab]); mainsplit.add(navigatorPane, 1); // navigator var editorSplit = new qx.ui.splitpane.Pane("vertical"); // editorSplit.setDecorator(null); var infoSplit = new qx.ui.splitpane.Pane("horizontal"); ide.editorTabView = new Gui.EditorTabView(); // infoSplit.set({ decorator: null }); infoSplit.add(ide.editorTabView, 4); // editor ide.contextPane = new Gui.TabView(); ide.outlineNavigator = new Gui.OutlineNavigator(); ide.propertyTable = new Gui.PropertyTable(); var outlineTab = ide.contextPane.addPage("outline_tab", ide.outlineNavigator); ide.contextPane.addPage("properties_tab", ide.propertyTable); ide.contextPane.setSelection([outlineTab]); infoSplit.add(ide.contextPane, 1); editorSplit.add(infoSplit, 4); // ********************** Problem Pane *************************** ide.resultPane = new Gui.TabView(); editorSplit.add(ide.resultPane, 2); // Info ide.console = new Gui.ConsoleLog(); ide.problemResult = new Gui.ResultTable(); ide.todoList = new Gui.ResultTable(); ide.processTable = new Gui.ProcessTable(); var problemPage = ide.resultPane.addPage("problems_tab", ide.problemResult); problemPage.autoSelect = true; var consolePage = ide.resultPane.addPage("console_tab", ide.console); consolePage.autoSelect = true; ide.resultPane.addPage("process_tab", ide.processTable); ide.resultPane.addPage("todo_tab", ide.todoList); ide.resultPane.setSelection([consolePage]); mainsplit.add(editorSplit, 4); // main area mainContainer.add(mainsplit, { flex: 1 }); // ************************ Status Bar ***************************** ide.statusBar = new Gui.StatusBar(); mainContainer.add(ide.statusBar, { flex: 0 }); } }
JavaScript
class SearchDialog extends qx.ui.window.Window { constructor() { super("Search in Files"); this.form = new qx.ui.form.Form(); var layout = new qx.ui.layout.VBox(); this.setLayout(layout); this.add(this.createForm()); this.setModal(true); this.addListener("resize", this.center); } /** * Open the search dialog with a root directory */ search(rootDir) { this.rootDir = rootDir; this.show(); } getResults(fileName, pattern, result) { try { var content = Cats.OS.File.readTextFile(fileName); if (!content.match(pattern)) return; var lines = content.split("\n"); for (var x = 0; x < lines.length; x++) { var line = lines[x]; var match = null; while (match = pattern.exec(line)) { var columnX = pattern.lastIndex - match[0].length; var columnY = pattern.lastIndex; var item = { range: { start: { row: x, column: columnX }, end: { row: x, column: columnY } }, fileName: fileName, message: line }; result.push(item); } } } catch (err) { console.error("Got error while handling file " + fileName); console.error(err); } } run(param) { var result = []; var mod = param.caseInsensitive ? "i" : ""; var searchPattern = new RegExp(param.search, "g" + mod); if (!param.glob) param.glob = "**/*"; Cats.OS.File.find(param.glob, this.rootDir, (err, files) => { files.forEach((file) => { if (result.length > param.maxHits) return; var fullName = Cats.OS.File.join(this.rootDir, file); this.getResults(fullName, searchPattern, result); }); var resultTable = new Gui.ResultTable(); var toolTipText = "Search results for " + searchPattern + " in " + this.rootDir + "/" + param.glob; var page = Cats.IDE.resultPane.addPage("search", resultTable, toolTipText); page.setShowCloseButton(true); resultTable.setData(result); this.close(); }); } addTextField(label, model) { var t = new qx.ui.form.TextField(); t.setWidth(200); this.form.add(t, label, null, model); return t; } addSpinner(label, model) { var s = new qx.ui.form.Spinner(); s.set({ minimum: 0, maximum: 1000 }); this.form.add(s, label, null, model); return s; } addCheckBox(label, model) { var cb = new qx.ui.form.CheckBox(); this.form.add(cb, label, null, model); return cb; } createForm() { var s = this.addTextField("Search for", "search"); s.setRequired(true); var p = this.addTextField("File Pattern", "glob"); p.setValue("**/*"); var c = this.addCheckBox("Case insensitive", "caseInsensitive"); c.setValue(false); var m = this.addSpinner("Maximum hits", "maxHits"); m.setValue(100); var searchButton = new qx.ui.form.Button("Search"); var cancelButton = new qx.ui.form.Button("Cancel"); this.form.addButton(searchButton); searchButton.addListener("execute", () => { if (this.form.validate()) { var param = { search: s.getValue(), glob: p.getValue(), caseInsensitive: c.getValue(), maxHits: m.getValue() }; this.run(param); } ; }, this); this.form.addButton(cancelButton); cancelButton.addListener("execute", () => { this.close(); }, this); var renderer = new qx.ui.form.renderer.Single(this.form); return renderer; } createResultTable() { var r = new Gui.ResultTable(); return r; } }
JavaScript
class RenameDialog extends qx.ui.window.Window { constructor() { super("Rename"); this.form = new qx.ui.form.Form(); var layout = new qx.ui.layout.VBox(); this.setLayout(layout); this.add(this.createForm()); this.setModal(true); this.addListener("resize", this.center); } run(fileName, project, pos) { project.iSense.getRenameInfo(fileName, pos, (err, data) => { if (!data) return; if (!data.canRename) { alert("Cannot rename the selected element"); return; } var dialog = new Gui.PromptDialog("Rename " + data.displayName + " into:"); dialog.onSuccess = (newName) => { project.iSense.findRenameLocations(fileName, pos, false, false, (err, data) => { // renameOccurences(data, newName); }); }; dialog.show(); }); } addTextField(label, model) { var t = new qx.ui.form.TextField(); t.setWidth(200); this.form.add(t, label, undefined, model); return t; } addSpinner(label, model) { var s = new qx.ui.form.Spinner(); s.set({ minimum: 0, maximum: 1000 }); this.form.add(s, label, undefined, model); return s; } addCheckBox(label, model) { var cb = new qx.ui.form.CheckBox(); this.form.add(cb, label, undefined, model); return cb; } createForm() { var s = this.addTextField("New name", "name"); s.setRequired(true); var c = this.addCheckBox("Replace in strings", "caseInsensitive"); c.setValue(false); var d = this.addCheckBox("Replace in comments", "caseInsensitive"); d.setValue(false); var searchButton = new qx.ui.form.Button("Refactor"); var cancelButton = new qx.ui.form.Button("Cancel"); this.form.addButton(searchButton); searchButton.addListener("execute", () => { if (this.form.validate()) { var param = { name: s.getValue(), caseInsensitive: c.getValue() }; // this.run(param); } ; }, this); this.form.addButton(cancelButton); cancelButton.addListener("execute", () => { this.close(); }, this); var renderer = new qx.ui.form.renderer.Single(this.form); return renderer; } }
JavaScript
class MenuBar { constructor() { this.menus = {}; this.createMenuBar(); this.createFileMenu(); this.createEditMenu(); this.createViewMenu(); this.createProjectMenu(); this.createSourceMenu(); this.createHelpMenu(); var win = GUI.Window.get(); win.menu = this.menu; } createMenuBar() { this.menu = new GUI.Menu({ type: "menubar" }); if (Cats.OS.File.isOSX() && this.menu.createMacBuiltin) { this.menu.createMacBuiltin("CATS"); this.menus.cats = this.menu.items[0].submenu; this.menus.edit = this.menu.items[1].submenu; this.menus.window = this.menu.items[2].submenu; // 0 is builtin CATS menu this.createMenuBarItem("file", 1); // 2 is builtin Edit this.createMenuBarItem("view", 3); this.createMenuBarItem("project", 4); this.createMenuBarItem("source", 5); // 6 is builtin Windows this.createMenuBarItem("help"); } else { this.createMenuBarItem("file"); this.createMenuBarItem("edit"); this.createMenuBarItem("view"); this.createMenuBarItem("project"); this.createMenuBarItem("source"); this.createMenuBarItem("help"); } } /** * Create an item in the main menu bar. Optional the position can be passed * for this item. */ createMenuBarItem(name, position) { var label = Cats.translate(name + "_menu_name"); var menu = new GUI.Menu(); this.menus[name] = menu; if (position) { this.menu.insert(new GUI.MenuItem({ label: label, submenu: menu }), position); } else { this.menu.append(new GUI.MenuItem({ label: label, submenu: menu })); } } createSourceMenu() { var source = this.menus.source; source.append(getItem(Cats.Commands.COMMANDNAME.edit_toggleComment)); source.append(getItem(Cats.Commands.COMMANDNAME.edit_toggleInvisibles)); source.append(new GUI.MenuItem({ type: "separator" })); source.append(getItem(Cats.Commands.COMMANDNAME.edit_indent)); source.append(getItem(Cats.Commands.COMMANDNAME.edit_outdent)); source.append(new GUI.MenuItem({ type: "separator" })); source.append(getItem(Cats.Commands.COMMANDNAME.source_format)); source.append(getItem(Cats.Commands.COMMANDNAME.edit_gotoLine)); } createHelpMenu() { var help = this.menus["help"]; help.append(getItem(Cats.Commands.COMMANDNAME.help_shortcuts)); help.append(getItem(Cats.Commands.COMMANDNAME.help_processInfo)); help.append(getItem(Cats.Commands.COMMANDNAME.help_devTools)); help.append(getItem(Cats.Commands.COMMANDNAME.help_about)); } createEditMenu() { var edit = this.menus.edit; // Already done by native OSX menu if (!Cats.OS.File.isOSX()) { edit.append(getItem(Cats.Commands.COMMANDNAME.edit_undo)); edit.append(getItem(Cats.Commands.COMMANDNAME.edit_redo)); edit.append(new GUI.MenuItem({ type: "separator" })); edit.append(getItem(Cats.Commands.COMMANDNAME.edit_cut)); edit.append(getItem(Cats.Commands.COMMANDNAME.edit_copy)); edit.append(getItem(Cats.Commands.COMMANDNAME.edit_paste)); } edit.append(new GUI.MenuItem({ type: "separator" })); edit.append(getItem(Cats.Commands.COMMANDNAME.edit_find)); edit.append(getItem(Cats.Commands.COMMANDNAME.edit_findNext)); edit.append(getItem(Cats.Commands.COMMANDNAME.edit_findPrev)); edit.append(getItem(Cats.Commands.COMMANDNAME.edit_replace)); edit.append(getItem(Cats.Commands.COMMANDNAME.edit_replaceAll)); edit.append(new GUI.MenuItem({ type: "separator" })); edit.append(getItem(Cats.Commands.COMMANDNAME.edit_toggleRecording)); edit.append(getItem(Cats.Commands.COMMANDNAME.edit_replayMacro)); } createFileMenu() { var file = this.menus.file; file.append(getItem(Cats.Commands.COMMANDNAME.file_new)); file.append(new GUI.MenuItem({ type: "separator" })); file.append(getItem(Cats.Commands.COMMANDNAME.file_save)); file.append(getItem(Cats.Commands.COMMANDNAME.file_saveAs)); file.append(getItem(Cats.Commands.COMMANDNAME.file_saveAll)); file.append(new GUI.MenuItem({ type: "separator" })); file.append(getItem(Cats.Commands.COMMANDNAME.file_close)); file.append(getItem(Cats.Commands.COMMANDNAME.file_closeAll)); file.append(getItem(Cats.Commands.COMMANDNAME.file_closeOther)); file.append(new GUI.MenuItem({ type: "separator" })); file.append(getItem(Cats.Commands.COMMANDNAME.ide_configure)); if (!Cats.OS.File.isOSX()) { file.append(getItem(Cats.Commands.COMMANDNAME.ide_quit)); } } recentProjects() { var menu = new GUI.Menu(); Cats.IDE.config.projects.slice().reverse().forEach((project) => { if (!project) return; var item = { label: project, click: () => { Cats.IDE.setDirectory(project); } }; menu.append(new GUI.MenuItem(item)); }); var entry = new GUI.MenuItem({ label: "Recent Projects", submenu: menu }); return entry; } createProjectMenu() { var proj = this.menus.project; proj.append(getItem(Cats.Commands.COMMANDNAME.project_open)); proj.append(getItem(Cats.Commands.COMMANDNAME.project_close)); proj.append(getItem(Cats.Commands.COMMANDNAME.project_new)); proj.append(this.recentProjects()); proj.append(new GUI.MenuItem({ type: "separator" })); proj.append(getItem(Cats.Commands.COMMANDNAME.project_build)); proj.append(getItem(Cats.Commands.COMMANDNAME.project_run)); proj.append(getItem(Cats.Commands.COMMANDNAME.project_validate)); proj.append(getItem(Cats.Commands.COMMANDNAME.project_refresh)); // proj.append( new GUI.MenuItem( { type: "separator" }) ); // proj.append( getItem( Commands.COMMANDNAME.project_configure ) ); } createViewMenu() { var view = this.menus.view; view.append(getItem(Cats.Commands.COMMANDNAME.ide_toggle_toolbar)); view.append(getItem(Cats.Commands.COMMANDNAME.ide_toggle_statusbar)); view.append(getItem(Cats.Commands.COMMANDNAME.ide_toggle_context)); view.append(getItem(Cats.Commands.COMMANDNAME.ide_toggle_result)); } }
JavaScript
class TSHelper { constructor(editor, editSession) { this.editor = editor; this.editSession = editSession; this.pendingUpdates = false; this.init(); } init() { this.updateDiagnostics(0); this.updateOutline(0); this.editor.getLayoutItem().addListener("appear", () => { this.updateDiagnostics(0); }); this.editSession.on("change", () => { this.updateContent(); }); } updateContent(timeout = 500) { if (!this.editor.hasProject()) return; clearTimeout(this.updateSourceTimer); this.pendingUpdates = true; this.updateSourceTimer = setTimeout(() => { if (this.pendingUpdates) { this.editor.project.iSense.updateScript(this.editor.filePath, this.editSession.getValue()); this.pendingUpdates = false; this.updateDiagnostics(); this.updateOutline(); } }, timeout); } /** * Lets check the worker if something changed in the outline of the source. * But lets not call this too often. * */ updateOutline(timeout = 5000) { if (!this.editor.hasProject()) return; var project = this.editor.project; clearTimeout(this.outlineTimer); this.outlineTimer = setTimeout(() => { project.iSense.getScriptOutline(this.editor.filePath, (err, data) => { this.editor.set("outline", data); }); }, timeout); } /** * Lets check the worker if something changed in the diagnostic. * */ updateDiagnostics(timeout = 1000) { if (!this.editor.hasProject()) return; var project = this.editor.project; this.diagnosticTimer = setTimeout(() => { project.iSense.getErrors(this.editor.filePath, (err, result) => { this.editSession.showAnnotations(result); }); }, timeout); } }
JavaScript
class MimeTypeFinder { /** * Find the mimetype for a file name */ static lookup(filename, fallback) { return this.types[Cats.OS.File.PATH.extname(filename)] || fallback || this.default_type; } }
JavaScript
class ResourceLoader { require(file, callback) { callback = callback || function () { }; var jsfile_extension = /(.js)$/i; var cssfile_extension = /(.css)$/i; if (jsfile_extension.test(file)) { var scriptnode = document.createElement('script'); scriptnode.src = file; scriptnode.onload = function () { callback(); }; document.head.appendChild(scriptnode); } else if (cssfile_extension.test(file)) { var linknode = document.createElement('link'); linknode.rel = 'stylesheet'; linknode.type = 'text/css'; linknode.href = file; document.head.appendChild(linknode); callback(); } else { console.log("Unknown file type to load."); } } loadResources(files, callback) { var counter = 0; files.forEach((file) => { this.require(file, () => { counter++; if (counter === files.length) { callback(); } }); }); } }
JavaScript
class VOIPWorkletProcessor extends AudioWorkletProcessor { constructor() { super(); this.buffer = new RingBuffer(); this.inputbuffer = new RingBuffer(); this.sampleRate = 24000; this.port.onmessage = (event) => this.handleMessage(event.data); console.log('Initialized VOIP worklet'); } process(inputs, outputs, parameters) { // Output buffered audio data as received from MixedAudio packets let output = outputs[0]; let outputChannel = output[0]; let buf = new Float32Array(outputChannel.length); // Unroll ring buffer into output channel // FIXME - I'd expect to have to handle stereo channels directly here, but it's acting like a mono device this.buffer.read(buf, outputChannel.length); // Output audio stream from data we've received from the server for (let i = 0; i < outputChannel.length; i++) { let idx = i; output[0][idx] = buf[i]; if (output[1]) { output[1][idx] = buf[i]; } } // Capture microphone input, and send it to the main thread when we've queued more than a specified chunk size if (inputs[0][0].length > 0) { let buffer = inputs[0][0]; // DEBUG - generate a pure sine wave tone before resampling /* buffer = new Float32Array(buffer.length); if (!this.sincounter) this.sincounter = 0; for (let i = 0; i < buffer.length; i++) { buffer[i] = Math.sin(this.sincounter++ / 100.0 * Math.PI); } */ if (this.inputSampleRate != this.sampleRate) { /* if (!this.resampler.inputBufferLength) { this.resampler.inputBufferLength = buffer.length; this.resampler.initialize(); } buffer = this.resampler.resampler(buffer); */ // FIXME - resampler library introduces scratchiness, use a simple 48000->24000Hz conversion for now // TODO - reuse buffer to eliminate gc let buffer2 = new Float32Array(buffer.length / 2); for (let i = 0; i < buffer2.length; i++) { buffer2[i] = buffer[i * 2]; } buffer = buffer2; } this.port.postMessage({ type: 'voipdata', //buffer: this.encode(resampler.outputBuffer) buffer: this.encode(buffer) }); } return true; } encode(input) { console.warn('VOIPWorkletProcessor called encode() on base class'); } decode(output) { console.warn('VOIPWorkletProcessor called decode() on base class'); } handleMessage(message) { if (message.inputSampleRate) { this.inputSampleRate = message.inputSampleRate; this.resampler = new Resampler(this.inputSampleRate, this.sampleRate, 1); } else { this.buffer.add(this.decode(message)); } } }
JavaScript
class ViewModel { /** Create a ViewModel. **/ constructor() { // Initialize some KnockoutJS variables/observables. // see: http://knockoutjs.com/documentation/observables.html this.filterInput = ko.observable(""); this.locationList = ko.observableArray(); //init an empty array // Init the some required Google Maps objects. // We are using the Google Maps Javascript API. // see: https://developers.google.com/maps/documentation/javascript this.map = this.createMap(); this.infowindow = new google.maps.InfoWindow(); this.bounds = new google.maps.LatLngBounds(); // Import the available locations and create 'Location' objects. availableLocations.forEach(function(loc){ this.locationList.push( new Location(loc.title, loc.position, this.map, this.infowindow)); }, this); this.fitBoundsToLocations(this.locationList()); // Filter the LocationList with KnockoutJS: this.filteredList = ko.computed(function() { var filterStr = this.filterInput().toLowerCase(); if (!filterStr) { // no filter will be applied this.showAllMarkers(); this.fitBoundsToLocations(this.locationList()); return this.locationList(); } else { // filter the locationsList var remainingLocations = ko.utils.arrayFilter(this.locationList(), function(location) { var filterResult = location.title.toLowerCase().includes(filterStr); location.showMarker(filterResult); return filterResult; }); this.fitBoundsToLocations(remainingLocations); return remainingLocations; // Note: the knockout utility methods are very usefull but I wasn't // able to find them in the official documentation for some reason! :o // I found the arrayFilter method on other websites, thanks to Google. // see: https://stackoverflow.com/questions/20857594/knockout-filtering-on-observable-array // also usefull: http://jsfiddle.net/rniemeyer/vdcUA/ } }, this); } /** * Creates a new google.maps.Map instance, which is centered to my city. * see: https://developers.google.com/maps/documentation/javascript/tutorial * @return {Map} the map object. */ createMap() { var map = new google.maps.Map(document.getElementById('map'), { // only center and zoom are required. center: {lat: 47.075004, lng: 15.436732}, zoom: 10 }); return map; } /** * Displays/Activates the markers for all locations on the map */ showAllMarkers() { this.locationList().forEach(function(locationItem) { locationItem.showMarker(true); }); } /** * Extend the boundaries of the map so that we can see the active locations. */ fitBoundsToLocations(activeLocations) { activeLocations.forEach(function(locationItem) { this.bounds.extend(locationItem.position); }, this); // Extend the boundaries of the map for each marker this.map.fitBounds(this.bounds); } }
JavaScript
class AgentWsServer { /** *Creates an instance of AgentWsServer. * @memberof AgentWsServer */ constructor() { this.wsServer = null; } /** * Create WS server and listen to events * @param {Object} server - NodeJs HTTPS server */ init() { const _this = this; _this.wsServer = new Server({ serverType: 'ws', queueType: 'redis', serverOptions: { port: process.env.PORT }, messageBrokerOptions: { username: '', password: '', host: '' } }); _this.wsServer.subscribeToGlobalMessage("name", constants.TUNNEL_OPEN_SUCCESS); socketIdController.init(_this.wsServer); console.log("Agent WS Server started"); _this.wsServer.on('connection', () => { }); _this.wsServer.on('message', (payload, socket) => { if (socket) { console.log(`------------ON MESSAGE----------------payload: ${JSON.stringify(payload)} socket-identity: ${JSON.stringify(socket.identity)}`); } else { console.log(`------------ON MESSAGE----------------payload: ${JSON.stringify(payload)}`); } agentWebSocketModel.processMessage(_this.wsServer, socket, payload); }); _this.wsServer.on('close', (socket) => { console.log(`------------ON CLOSE----------------socket-identity: ${JSON.stringify(socket.identity)}`); agentWebSocketModel.handleSocketDisconnection(_this.wsServer, socket, 'closed'); }); _this.wsServer.on('terminate', (socket) => { console.log(`------------ON TERMINATE----------------socket-identity: ${JSON.stringify(socket.identity)}`); agentWebSocketModel.handleSocketDisconnection(_this.wsServer, socket, 'terminated'); }); _this.wsServer.on('socket-error', (socket, err) => { console.log(`------------ON SOCKET ERROR----------------socket-identity: ${JSON.stringify(socket.identity)} Error: ${err}`); agentWebSocketModel.handleSocketDisconnection(socket, 'closed on error'); }); } /** * Global method to send WS message to both onboard and pre-onboard devices * @param {string} merchantId <- * @param {string} registerNo <- * @param {string|null} macAddress <- * @param {*} data - the data sent here will be stringified before being sent * @param {function} callback <- * @return {*} - callback */ sendMessageGlobal(merchantId, registerNo, macAddress, data, callback) { let socket = socketIdController.getSocket(merchantId, registerNo, macAddress); if (!socket) { let err = new Error("Device is offline"); console.log(err); return callback(err); } this.logger.info(`Sending Message to ${merchantId} | ${registerNo} | ${macAddress}`); socket.send(JSON.stringify(data), (err) => { if (err) { return callback(err); } return callback(null); }); } /** * Send message interface explicitly for onboard devices * Here we will simply call the sendMessageGlobal with macAddress set as null * * @param {string} merchantId <- * @param {string} registerNo <- * @param {*} data - the data sent here will be stringified before being sent * @param {function} callback <- * @return {*} - callback */ sendMessage(merchantId, registerNo, data, callback) { return this.sendMessageGlobal(merchantId, registerNo, null, data, callback); } /** * Proxy socket close call to socketId controller * @param {string} args <- */ closeSocket(...args) { socketIdController.closeSocket(...args); } }
JavaScript
class SwitchReducer extends MonoidalReducer { constructor() { super(MapMonad); } reduceSwitchCase(node, state) { // It's unsafe to simply check whether a given switch has subswitches with this reducer itself, since there are // switch cases with complex snippets, which might contain switches themselves. This is the safest, albeit verbose, way function has_subswitch(node) { return ( ( node.consequent.length == 2 && node.consequent[1].type === 'BreakStatement' || node.consequent.length == 1 // Last case has no closing "break" ) && node.consequent[0].type === 'ExpressionStatement' && node.consequent[0].expression.type === 'UnaryExpression' && node.consequent[0].expression.operator === '!' && node.consequent[0].expression.operand.type === 'CallExpression' && node.consequent[0].expression.operand.callee.type === 'FunctionExpression' && node.consequent[0].expression.operand.callee.isAsync === false && node.consequent[0].expression.operand.callee.isGenerator === false && node.consequent[0].expression.operand.callee.name === null && node.consequent[0].expression.operand.callee.body.statements.length === 1 && node.consequent[0].expression.operand.callee.body.statements[0].type === 'SwitchStatement' ); } if (node.test.type !== 'LiteralNumericExpression') { throw new Error(`Reducing switch-case with non-numeric cases: found a ${node.test.type} test condition.`) } if (node.consequent.lenght == 0) { return new MapMonad({map: new Map( [ [node.test.value, undefined ] ] )}); // TODO IS THIS REQUIRED? } else if (has_subswitch(node)) { // Current case has additional switch cases nested below return new MapMonad({map: new Map( [ [node.test.value, super.reduceSwitchCase(node, state) ] ] )}); // TODO shouldn't this be a call to "reduce(new SwitchReducer, node)" with final cast to map via MapMonad.toMap? } else { // No cases, return the statements themselve return new MapMonad({map: new Map( [ [node.test.value, node.consequent ] ] )}); } } }
JavaScript
class EntriesfulComponent extends React.Component { /** * By default entriesful component loads entries at mount. */ componentDidMount() { const entriesType = this.getEntriesType(); if(!this.getEntries(entriesType) && !this.isLoadPerformed() && !this.isLoadStarted()) { const actionParams = this.getActionParams(); this.props.entriesActions.load(entriesType, actionParams); } } getActionParams() { return {}; } /** * By default, entriesful component clear stored entries, if required. */ componentWillUnmount() { const { isClearRequired = false } = this.props; if(isClearRequired) { const entriesType = this.getEntriesType(); this.props.entriesActions.clearEntries(entriesType); } } /** * Return nothing, because this is just abstract component. */ render() { return null; } /** * Abstract component can not have entries type, but * every child component SHOULD return strict type. */ getEntriesType() { return null; } /** * If entries by current type already loaded earlier. * Just check state property. */ isLoadPerformed() { const entriesType = this.getEntriesType(); const { isLoadPerformed = false } = this.props.state.entries[entriesType]; return isLoadPerformed; } /** * If entries by current state type already started to download. * Just check state property. */ isLoadStarted() { const entriesType = this.getEntriesType(); const { state } = this.props; return state.entries[entriesType].isLoadStarted || false; } /** * If entries unsorted at this moment. Just check state property. */ isSortingRequired() { const entriesType = this.getEntriesType(); const { isSortingRequired = false } = this.props.state.entries[entriesType]; return isSortingRequired; } /** * If user started a search by this entries type. Just check state property. */ isSearching() { const entriesType = this.getEntriesType(); return this.props.state.entries[entriesType].isSearching || false; } /** * Sort entries and returns array of sorted entries. * State stay unchanged. * * @param type String * @return Array */ getSortedEntries(type) { const SorterInstance = new Sorter(type); const entries = this.props.state.entries[type].items ? this.props.state.entries[type].items.slice() : null; if(entries) { const order = SorterInstance.getDefaultOrder(); const orderBy = SorterInstance.getDefaultOrderBy(); SorterInstance.sort(entries, orderBy, order); } return entries || []; } /** * Returns all entries from state. * * @param type String * @return Array | null */ getEntries(type) { if(!type) { type = this.getEntriesType(); } const entries = this.props.state.entries[type].items ? this.props.state.entries[type].items : null; return entries; } }
JavaScript
class RequestList { constructor(args, cb) { $.checkArgument(args.hosts); const request = args.request || require('request'); if (!lodash.isArray(args.hosts)) { args.hosts = [args.hosts]; } args.timeout = args.timeout || DEFAULT_TIMEOUT; const urls = lodash.map(args.hosts, function (x) { return (x + args.path); }); let nextUrl; let result; let success; async.whilst( function () { nextUrl = urls.shift(); return nextUrl && !success; }, function (a_cb) { args.uri = nextUrl; request(args, function (err, res, body) { if (err) { log.warn(`REQUEST FAIL: ${ nextUrl } ERROR: ${ err}`); } if (res) { success = !!res.statusCode.toString().match(/^[1234]../); if (!success) { log.warn(`REQUEST FAIL: ${ nextUrl } STATUS CODE: ${ res.statusCode}`); } } result = [err, res, body]; return a_cb(); }); }, function (err) { if (err) { return cb(err); } return cb(result[0], result[1], result[2]); } ); } }
JavaScript
class Textarea extends React.PureComponent { state = { value: this.props.value == null ? '' : this.props.value } componentWillReceiveProps (props) { if (props.value != null && props.value !== this.props.value) { this.setState({ value: props.value }) } } /** * Handle textarea change. * * @param {SyntheticEvent} event */ change = event => { const { value, onChange } = this.props const nextValue = event.target.value if (value == null) { this.setState({ value: nextValue }) } // Trigger change to parent components if (onChange) { onChange(nextValue, event) } } render () { const { className, disabled, placeholder, resize, error, TextareaComponent, value, onChange, ...passedProps } = this.props const clsName = buildClassName('textarea', className, { 'no-resize': !resize, disabled }) return ( <TextareaComponent className={clsName} disabled={disabled} placeholder={placeholder} value={this.state.value} onChange={this.change} {...passedProps} /> ) } }
JavaScript
class BitcoinTransactionIn { /** * Instantiate a new `BitcoinTransactionIn`. * * See the class properties for expanded information on these parameters. * * @param {BitcoinOutPoint} prevout * @param {Uint8Array|Buffer} scriptSig * @param {number} sequence * @constructs BitcoinTransactionIn */ constructor (prevout, scriptSig, sequence) { this.prevout = prevout this.scriptSig = scriptSig this.sequence = sequence } toJSON (_, coinbase) { let obj if (coinbase) { obj = { coinbase: this.scriptSig.toString('hex') } } else { obj = { txid: toHashHex(this.prevout.hash), vout: this.prevout.n, scriptSig: { asm: scriptToAsmStr(this.scriptSig, true), hex: this.scriptSig.toString('hex') } } } if (this.scriptWitness && this.scriptWitness.length) { obj.txinwitness = this.scriptWitness.map((w) => w.toString('hex')) } obj.sequence = this.sequence return obj } /** * Convert to a serializable form that has nice stringified hashes and other simplified forms. May * be useful for simplified inspection. * * The object returned by this method matches the shape of the JSON structure provided by the * `getblock` (or `gettransaction`) RPC call of Bitcoin Core. Performing a `JSON.stringify()` on * this object will yield the same data as the RPC. * * See [block-porcelain.ipldsch](block-porcelain.ipldsch) for a description of the layout of the * object returned from this method. * * @returns {object} */ toPorcelain () { return this.toJSON() } }
JavaScript
class User { /** * Get the current user * @param {Object} client * @param {Object} msg * @return {user} */ static async constructor(client, msg) { await this.user(client, msg); } /** * Get the current user * @param {Object} client * @param {Object} msg * @returns {Promise<void>} */ static async user(client, msg) { await client.users.cache.get(msg.author.id); } /** * Get a list of all users * @param {Object} client * @param {Object} msg * @returns {Promise<void>} */ static async all(client, msg) { await client.guilds.cache.get(msg.guild.id).members.cache.forEach(member => console.log(member.user.username)); } }
JavaScript
class BoundingSphere { /** * Constructs a new bounding sphere with the given values. * * @param {Vector3} center - The center position of the bounding sphere. * @param {Number} radius - The radius of the bounding sphere. */ constructor( center = new Vector3(), radius = 0 ) { /** * The center position of the bounding sphere. * @type {Vector3} */ this.center = center; /** * The radius of the bounding sphere. * @type {Number} */ this.radius = radius; } /** * Sets the given values to this bounding sphere. * * @param {Vector3} center - The center position of the bounding sphere. * @param {Number} radius - The radius of the bounding sphere. * @return {BoundingSphere} A reference to this bounding sphere. */ set( center, radius ) { this.center = center; this.radius = radius; return this; } /** * Copies all values from the given bounding sphere to this bounding sphere. * * @param {BoundingSphere} sphere - The bounding sphere to copy. * @return {BoundingSphere} A reference to this bounding sphere. */ copy( sphere ) { this.center.copy( sphere.center ); this.radius = sphere.radius; return this; } /** * Creates a new bounding sphere and copies all values from this bounding sphere. * * @return {BoundingSphere} A new bounding sphere. */ clone() { return new this.constructor().copy( this ); } /** * Ensures the given point is inside this bounding sphere and stores * the result in the given vector. * * @param {Vector3} point - A point in 3D space. * @param {Vector3} result - The result vector. * @return {Vector3} The result vector. */ clampPoint( point, result ) { result.copy( point ); const squaredDistance = this.center.squaredDistanceTo( point ); if ( squaredDistance > ( this.radius * this.radius ) ) { result.sub( this.center ).normalize(); result.multiplyScalar( this.radius ).add( this.center ); } return result; } /** * Returns true if the given point is inside this bounding sphere. * * @param {Vector3} point - A point in 3D space. * @return {Boolean} The result of the containments test. */ containsPoint( point ) { return ( point.squaredDistanceTo( this.center ) <= ( this.radius * this.radius ) ); } /** * Returns true if the given bounding sphere intersects this bounding sphere. * * @param {BoundingSphere} sphere - The bounding sphere to test. * @return {Boolean} The result of the intersection test. */ intersectsBoundingSphere( sphere ) { const radius = this.radius + sphere.radius; return ( sphere.center.squaredDistanceTo( this.center ) <= ( radius * radius ) ); } /** * Returns true if the given plane intersects this bounding sphere. * * Reference: Testing Sphere Against Plane in Real-Time Collision Detection * by Christer Ericson (chapter 5.2.2) * * @param {Plane} plane - The plane to test. * @return {Boolean} The result of the intersection test. */ intersectsPlane( plane ) { return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; } /** * Returns the normal for a given point on this bounding sphere's surface. * * @param {Vector3} point - The point on the surface * @param {Vector3} result - The result vector. * @return {Vector3} The result vector. */ getNormalFromSurfacePoint( point, result ) { return result.subVectors( point, this.center ).normalize(); } /** * Computes a bounding sphere that encloses the given set of points. * * @param {Array<Vector3>} points - An array of 3D vectors representing points in 3D space. * @return {BoundingSphere} A reference to this bounding sphere. */ fromPoints( points ) { // Using an AABB is a simple way to compute a bounding sphere for a given set // of points. However, there are other more complex algorithms that produce a // more tight bounding sphere. For now, this approach is a good start. aabb.fromPoints( points ); aabb.getCenter( this.center ); this.radius = this.center.distanceTo( aabb.max ); return this; } /** * Transforms this bounding sphere with the given 4x4 transformation matrix. * * @param {Matrix4} matrix - The 4x4 transformation matrix. * @return {BoundingSphere} A reference to this bounding sphere. */ applyMatrix4( matrix ) { this.center.applyMatrix4( matrix ); this.radius = this.radius * matrix.getMaxScale(); return this; } /** * Returns true if the given bounding sphere is deep equal with this bounding sphere. * * @param {BoundingSphere} sphere - The bounding sphere to test. * @return {Boolean} The result of the equality test. */ equals( sphere ) { return ( sphere.center.equals( this.center ) ) && ( sphere.radius === this.radius ); } /** * Transforms this instance into a JSON object. * * @return {Object} The JSON object. */ toJSON() { return { type: this.constructor.name, center: this.center.toArray( new Array() ), radius: this.radius }; } /** * Restores this instance from the given JSON object. * * @param {Object} json - The JSON object. * @return {BoundingSphere} A reference to this bounding sphere. */ fromJSON( json ) { this.center.fromArray( json.center ); this.radius = json.radius; return this; } }
JavaScript
class Stream { static nil = () => new Stream(function* nil() { // Empty stream }); /** * Stream with the only element * @param {A} x - The only element * @return {Stream(A)} */ static of = x => new Stream(function* singleton() { yield x; }); /** * @param {() => Generator} g - Generator-function without args */ constructor(g) { this.g = g; this[Symbol.iterator] = g; } /** * @return {A} First element */ get head() { return this.g().next().value; } /** * @return {Stream(A)} First element wrapped into stream */ first() { const stream = this; return new this.constructor(function* head() { yield stream.head; }); } /** * @return {Stream(A)} Elements of stream exluding the first one */ get tail() { const stream = this; return new this.constructor(function* tail() { const gen = stream.g(); gen.next(); // Behead yield* gen; }); } /** * Converts stream to provider function to access consequent elements one by one * Provider is an unpure function (encapsulates side effect) * @param {A} emptyVal - Default value * @return {() -> A} */ provider(emptyVal) { const gen = this.g(); return () => { const {value, done} = gen.next(); return !done ? value : emptyVal; }; } take = n => take(this, n); /** * Functor's part * @param {A -> B} f * @return {Stream(B)} */ map(f) { const stream = this; return new this.constructor(function* mapped() { for (const x of stream) yield f(x); }); } /** * Monad's part. Also know as flatMap or bind * @param {A -> Stream(B)} f * @return {Stream(B)} */ chain(f) { const stream = this; return new this.constructor(function* chained() { for (const x of stream) yield* f(x); }); } /** * Applicative's part * @param {Stream(A -> B)} stream * @return {Stream(B)} */ ap = stream => this.chain(x => stream.map(f => f(x))); /** * http://reactivex.io/documentation/operators/scan.html * @param {(B, A) -> B} f - Reducer * @param {B} acc - Optional accumulator * @return {Stream(B)} */ scan(f, acc) { const stream = this; return new this.constructor(function* scanned() { let y = acc; for (const x of stream) yield y = f(y, x); }); } /** * Concatenate all streams regarding arguments order * @param {[Stream(A)]} xss - Iterables * @return {Stream(A)} Concatenated stream */ concat(...xss) { const stream = this; return new this.constructor(function* concatenated() { yield* stream; for (const xs of xss) { if (Symbol.iterator in xs) { yield* xs; } else { yield xs; } } }); } }
JavaScript
class PublicKey { /** Create a new instance from a WIF-encoded key. */ static fromString (wif) { const { key, prefix } = decodePublic(wif) return new PublicKey(key, prefix) } /** Create a new instance. */ static from (value) { if (value instanceof PublicKey) { return value } else { return PublicKey.fromString(value) } } constructor (key, prefix = DEFAULT_ADDRESS_PREFIX) { this.key = key this.prefix = prefix // assert(secp256k1.publicKeyVerify(key), 'invalid public key') } /** * Verify a 32-byte signature. * @param message 32-byte message to verify. * @param signature Signature to verify. */ // verify(message, signature) { // return secp256k1.verify(message, signature.data, this.key) // } /** Return a WIF-encoded representation of the key. */ toString () { return encodePublic(this.key, this.prefix) } /** Return JSON representation of this key, same as toString(). */ toJSON () { return this.toString() } /** Used by `utils.inspect` and `console.log` in node.js. */ inspect () { return `PublicKey: ${this.toString()}` } }
JavaScript
class AI { /** * Default constructor for AI, takes minesweeper instance as an object. * Initializes the probability map and defaults all times to 0.5. * * @param {minesweeper.js} game the minesweeper.js instance */ constructor(game) { this.game = game; // init probability map this.probabilityMap = new Array(this.game.board.length); for (let i = 0; i < this.probabilityMap.length; i++) { this.probabilityMap[i] = new Array(this.game.board[i].length); for (let j = 0; j < this.probabilityMap[i].length; j++) { this.probabilityMap[i][j] = 0.5; // default to 0.5 (schrodingers mine) } } } /** * Calculates the next best move based on the probability map. */ nextMove = () => { this.calculateProbabilities(); // calculate probability map let board = this.game.board; // to avoid this.game.board a bunch // check all the board tiles for (let i = 0; i < board.length; i++) { for (let j = 0; j < board[i].length; j++) { // check if not revealed and not flagged (if it is, its a normal tile) if (!board[i][j].revealed && !board[i][j].flagged) { // if we know its a mine, flag it if (this.probabilityMap[i][j] === 1) { board[i][j].flag(); return; } // if we know its not a mine, reveal it else if (this.probabilityMap[i][j] === 0) { board[i][j].reveal(); return; } } } } // if we have no decent move, check if we won this.game.checkWin(); // if we did win, don't try to make a random move (prevents infinite loop) if (this.game.won) return; // WORST CASE SCENARIO: we guess the best probability tile // or just a random tile if all have the same probability let min = 0.5; let posY = Math.floor(Math.random() * board.length); let posX = Math.floor(Math.random() * board[posY].length); for (let i = 0; i < board.length; i++) { for (let j = 0; j < board[i].length; j++) { if (this.probabilityMap[i][j] >= 0 && this.probabilityMap[i][j] < min) { min = this.probabilityMap[i][j]; posY = i; posX = j; } } } board[posY][posX].reveal(); }; /** * Calculates the probability map. */ calculateProbabilities = () => { let board = this.game.board; // to avoid this.game.board a bunch // for every tile on the board for (let i = 0; i < board.length; i++) { for (let j = 0; j < board.length; j++) { let t = board[i][j]; // if this tile is revealed, see if we have any guaranteed tiles around it if (t.revealed) { this.probabilityMap[i][j] = -1; // -1 to ignore // if this tile is satisfied already if (t.isSatisfied()) { // see if any adjacent unrevealed tiles can be determined as not a mine t.getAdjacentUnrevealedTiles().forEach(adj => { // if we're a satisfied tile, this tile can't be a mine (0) if (!adj.flagged) this.probabilityMap[adj.x][adj.y] = 0; }); } else { // if not satisfied try and find some guaranteed mines let adj = t.getAdjacentUnrevealedTiles(); // grab adjacent tiles adj.forEach(a => { // if the number of adjacent tiles is the number of mines, all remaining // adjacent tiles must be mines, otherwise, each mine has a (NUMBER - ADJACENT_FLAGS) / ADJACENT chance to be // a mine, this is a reduction, but works very well (if there are 4 unrevealed mines and the // number is 3, each mine has ~75% chance of being a mine, so another set of tiles might be a better guess) if (!a.flagged && this.probabilityMap[a.x][a.y] > 0 && this.probabilityMap[a.x][a.y] < 1) { if (t.number >= adj.length) this.probabilityMap[a.x][a.y] = 1; else this.probabilityMap[a.x][a.y] = Math.round((t.number - t.getAdjacentFlags().length) / Math.max(adj.length, 1) * 100) / 100; } }); } } } } }; }
JavaScript
class Constants { static COLORS = { COLD_FIRE: '#389888', FIRE: '#f98026', WHITE: '#ffffff', }; static SECONDS = { IN_ONE_ROUND: 6, IN_ONE_MINUTE: 60, IN_TEN_MINUTES: 600, IN_ONE_HOUR: 3600, IN_SIX_HOURS: 21600, IN_EIGHT_HOURS: 28800, IN_ONE_DAY: 86400, IN_ONE_WEEK: 604800, }; }
JavaScript
class OneReferenceTemplate { constructor(container) { this.label = new highlightedLabel_1.HighlightedLabel(container, false); } set(element, score) { var _a; const preview = (_a = element.parent.getPreview(element)) === null || _a === void 0 ? void 0 : _a.preview(element.range); if (!preview || !preview.value) { // this means we FAILED to resolve the document or the value is the empty string this.label.set(`${resources_1.basename(element.uri)}:${element.range.startLineNumber + 1}:${element.range.startColumn + 1}`); } else { // render search match as highlight unless // we have score, then render the score const { value, highlight } = preview; if (score && !filters_1.FuzzyScore.isDefault(score)) { this.label.element.classList.toggle('referenceMatch', false); this.label.set(value, filters_1.createMatches(score)); } else { this.label.element.classList.toggle('referenceMatch', true); this.label.set(value, [highlight]); } } } }
JavaScript
class WatchExpressionListStore { constructor(watchExpressionStore, dispatcher) { this._watchExpressionStore = watchExpressionStore; const dispatcherToken = dispatcher.register(this._handlePayload.bind(this)); this._disposables = new _atom.CompositeDisposable(new _atom.Disposable(() => { dispatcher.unregister(dispatcherToken); })); this._watchExpressions = new _rxjsBundlesRxMinJs.BehaviorSubject([]); } /** * Treat the underlying EvaluatedExpressionList as immutable. */ _handlePayload(payload) { switch (payload.actionType) { case (_DebuggerDispatcher || _load_DebuggerDispatcher()).ActionTypes.ADD_WATCH_EXPRESSION: this._addWatchExpression(payload.data.expression); break; case (_DebuggerDispatcher || _load_DebuggerDispatcher()).ActionTypes.REMOVE_WATCH_EXPRESSION: this._removeWatchExpression(payload.data.index); break; case (_DebuggerDispatcher || _load_DebuggerDispatcher()).ActionTypes.UPDATE_WATCH_EXPRESSION: this._updateWatchExpression(payload.data.index, payload.data.newExpression); break; case (_DebuggerDispatcher || _load_DebuggerDispatcher()).ActionTypes.DEBUGGER_MODE_CHANGE: if (payload.data === (_DebuggerStore || _load_DebuggerStore()).DebuggerMode.STARTING) { this._refetchWatchSubscriptions(); } break; default: return; } } _getExpressionEvaluationFor(expression) { return { expression, value: this._watchExpressionStore.evaluateWatchExpression(expression) }; } getWatchExpressions() { return this._watchExpressions.asObservable(); } _addWatchExpression(expression) { this._watchExpressions.next([...this._watchExpressions.getValue(), this._getExpressionEvaluationFor(expression)]); } _removeWatchExpression(index) { const watchExpressions = this._watchExpressions.getValue().slice(); watchExpressions.splice(index, 1); this._watchExpressions.next(watchExpressions); } _updateWatchExpression(index, newExpression) { const watchExpressions = this._watchExpressions.getValue().slice(); watchExpressions[index] = this._getExpressionEvaluationFor(newExpression); this._watchExpressions.next(watchExpressions); } _refetchWatchSubscriptions() { const watchExpressions = this._watchExpressions.getValue().slice(); const refetchedWatchExpressions = watchExpressions.map(({ expression }) => { return this._getExpressionEvaluationFor(expression); }); this._watchExpressions.next(refetchedWatchExpressions); } dispose() { this._disposables.dispose(); } }
JavaScript
class AuthController { /** * Logins a user. * @param {Request} req - Response object. * @param {Response} res - The payload. * @memberof AuthController * @returns {JSON} - A JSON success response. */ static async login(req, res) { try { const { username } = req.body; const token = UserUtility.generateToken(username); const response = { token, username }; return res.status(200).json({ status: 'success', data: response }); } catch (err) { return res.status(500).json({ status: '500 Internal server error', error: 'Error Logging in user' }); } } }
JavaScript
class GameCard extends window.HTMLElement { constructor () { super() this.attachShadow({ mode: 'open' }) } connectedCallback () { this.shadowRoot.innerHTML = /* html */ ` <style> :host { display: flex; justify-content: center; align-items: center; } div { width: 100%; height: 100%; background-size: contain; background-repeat: no-repeat; background-position: center; } </style> ` this.div = document.createElement('div') this.shadowRoot.appendChild(this.div) this.setAttribute('tabindex', '0') this.revealed = false this._updateImage() } _updateImage () { if (this.revealed) { this.div.style.backgroundImage = `url(${this.frontUrl})` } else { this.div.style.backgroundImage = `url(${this.backUrl})` } } /** * Swaps the image being displayed from front to back or vice-versa. * * @memberof GameCard */ flip () { this.revealed = !this.revealed this._updateImage() } /** * Hides this card by adding visibility="hidden" to it's style. * * @memberof GameCard */ hide () { this.div.style.visibility = 'hidden' } /** * Return true if this card is hidden. * * @returns {boolean} * @memberof GameCard */ isHidden () { return this.div.style.visibility === 'hidden' } /** * Sets the images to be used for the front and back of this card. * * @param {string} frontUrl * @param {string} backUrl * @memberof GameCard */ setImages (frontUrl, backUrl) { this.frontUrl = frontUrl this.backUrl = backUrl } /** * Returns the URL of the image used for the front of this card. * * @returns {string} * @memberof GameCard */ getFront () { return this.frontUrl } /** * Returns the URL of the image used for the back of this card. * * @returns {string} * @memberof GameCard */ getBack () { return this.backUrl } }
JavaScript
class Access extends Component { constructor(props) { super(props); } render() { return ( <Layout> <div className={styles.screen}> <AccessCompo auth={this.props.auth}/> </div> </Layout> ); } }
JavaScript
class BCancel extends Behavior { /** * @constructs */ constructor() { super(); /** * @param {string} behavior * @param {Control} ctrlCancel */ this.defineMethod( "config", (that, ctrlCancel) => { let elmButton = document.createElement("div"); elmButton.setAttribute("element-type", "CancelButton"); elmButton.setAttribute("element-name", "cancel-button"); elmButton.setAttribute("visible", "true"); ctrlCancel.setAttribute("closable", "true"); ctrlCancel.addControl(elmButton); /** * @member {boolean} */ that.defineProperty("closable", { get() { return ctrlCancel.getAttribute("closable") === "true"; }, set(v) { if (instanceOf(v, "boolean")) { ctrlCancel.setAttribute("closable", v ? "true" : "false"); elmButton.setAttribute("visible", v ? "true" : "false"); } }, type: Boolean }); elmButton.addEventListener( "click", (e) => { that.visible = false; }, true ); }, [Object, Control, Control] ); } }
JavaScript
class FeeComponent { /** * Constructs a new <code>FeeComponent</code>. * A fee associated with the event. * @alias module:client/models/FeeComponent * @class */ constructor() { } /** * Constructs a <code>FeeComponent</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:client/models/FeeComponent} obj Optional instance to populate. * @return {module:client/models/FeeComponent} The populated <code>FeeComponent</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new FeeComponent(); if (data.hasOwnProperty('FeeType')) { obj['FeeType'] = ApiClient.convertToType(data['FeeType'], 'String'); } if (data.hasOwnProperty('FeeAmount')) { obj['FeeAmount'] = Currency.constructFromObject(data['FeeAmount']); } } return obj; } /** * The type of fee. For more information about Selling on Amazon fees, see [Selling on Amazon Fee Schedule](https://sellercentral.amazon.com/gp/help/200336920) on Seller Central. For more information about Fulfillment by Amazon fees, see [FBA features, services and fees](https://sellercentral.amazon.com/gp/help/201074400) on Seller Central. * @member {String} FeeType */ 'FeeType' = undefined; /** * @member {module:client/models/Currency} FeeAmount */ 'FeeAmount' = undefined; }
JavaScript
class NetworkQualitySendStats extends NetworkQualitySendOrRecvStats { /** * Construct a {@link NetworkQualitySendStats}. * @param {SendOrRecvStats} sendOrRecvStats */ constructor(sendOrRecvStats) { super(sendOrRecvStats); } }
JavaScript
class SyntaxHighlight { // Two parameters are optional constructor(source = null, dest = null) { // Handle source/destination // // By default only source is declared // Destination is optional if (dest === null) { this.source = source; this.dest = source; } else if (source === true && dest === true) { this.source = source; this.dest = dest; } else { console.log("Please provide a source location."); } // retrieve type of syntax highlighting // // can be 'html' or 'css' add this to your // source element as a name attribute this.type = source.attributes.name.nodeValue; // process type and formate accordingly if (this.type === "html") { this.format_html(); } else if (this.type === "css") { this.format_css(); }else if (this.type == 'js'){ this.format_js(); } else if (this.type == 'php'){ this.format__php(); } else { console.log("Please Formate HTML or CSS"); } } format_html() { // retrive code to be parsed let code = this.source.innerHTML; // Replace crucial symboles with html entities code = code.replace(/\"\>/g, '\" >') .replace(/</g, ' &lt;') .replace(/>/g, '&gt; ') .replace(/\=\"/g, '\= \"'); // compile into an array for processing let codeParts = code.split(" "), finished = ""; // cycles through code and applies syntax for (let part of codeParts) { // finds opening comment if (part.startsWith('&lt;!--')) { finished += "<em><span class='c'>" + part; // finds closing comment } else if (part.endsWith('--&gt;')) { finished += part + "</span></em>"; // finds opening and closing brackets for tags }else if (part.startsWith('&lt;') || part.endsWith('&gt;')) { finished += "<span class='t'>" + part + "</span> "; // finds attributes in tags } else if(part.endsWith("=")) { finished += "<span class='a'>" + part + "</span>"; // finds values to attributes or strings } else if (part.startsWith('"')) { finished += "<span class='s'>" + part + " "; } else if(part.endsWith('"')) { finished += part + "</span>" // Adds all other parts of the code seperated by spaces }else { finished += part + " "; } } // injects formatted code into dom for syntax highlighting this.dest.innerHTML = finished; } format_css () { let code = this.source.innerHTML, finished = ""; // remedies line breaks & space bug code = code.replace(/\n/g, " \n "); let codeParts = code.split(" "); for (let part of codeParts) { // class if (part.startsWith(".")) { finished += "<span class='l'>"+ part + "</span> "; // id }else if (part.startsWith("#") && !part.endsWith(";")) { finished += "<span class='t'>" + part + "</span> "; // property }else if (part.endsWith(":")) { finished += "<span class='a'>" + part + "</span> "; // value }else if (part.endsWith(";")) { finished += "<span class='s'>" + part + "</span>"; // @ decorator }else if (part.startsWith("@")) { finished += "<span class='t'>" + part + "</span> "; // comments } else if (part.startsWith("/*")) { finished += "<span class='c'>" + part + " "; } else if (part.endsWith("/*")) { finished += " " + part + "</span>"; } else { finished += part + " "; } this.dest.innerHTML = finished; } } format_js () { let code = this.source.innerHTML, finished = ""; // remedies line breaks & space bug code = code.replace(/\n/g, " \n "); let codeParts = code.split(" "); for(let part of codeParts) { // keywords let keywords = ['function', 'class', 'let', 'var', 'const', 'if', 'for', 'while', 'new']; for(let word of keywords){ if(this.part == word) { finished += "<span class='l'>" + part + "</span> "; } } } } format_php () { let code = this.source.innerHTML, finished = ""; // remedies line breaks & space bug code = code.replace(/\n/g, " \n "); let codeParts = code.split(" "); for(let part of codeParts) { // keywords let keywords = ['function', 'class', 'const', 'if', 'for', 'while', 'new']; for(let word of keywords){ if(this.part == word) { finished += "<span class='l'>" + part + "</span> "; } } } } }
JavaScript
class UniformBuffer { /** * @param {WebGLRenderer} renderer * @constructor */ constructor(renderer) { this.uid = uid(); this.renderer = renderer; this.gl = this.renderer.gl; this.size = 0; this.buffer = null; } }